{"version":3,"file":"A2UIRenderer.mjs","names":[],"sources":["../../../../src/plugins/A2UI/A2UIRenderer.tsx"],"sourcesContent":["import React, { type ComponentPropsWithoutRef, type ComponentType } from 'react';\n\nimport type { AIUIDocument } from '../AIComponents/GenerativeUI/AIUIDocument';\nimport type { AIUIHost } from '../AIComponents/GenerativeUI/AIUIHost';\nimport {\n  type AIUIMediaURL,\n  aiUIPublicMediaURL,\n} from '../AIComponents/GenerativeUI/AIUIMedia';\nimport type { AIUIEngine, AIUIRenderer } from '../AIComponents/GenerativeUI/AIUIRenderer';\nimport {\n  AIUIRuntimeLoader,\n  AIUIRuntimeView,\n} from '../AIComponents/GenerativeUI/AIUIRuntimeLoader';\nimport { A2UIPlaceholder } from './A2UIPlaceholder';\nimport { A2UI_DEFAULT_CATALOG_ID, A2UI_LEGACY_CATALOG_ID } from './catalogDocument';\nimport { A2UI_VERSION, a2uiSourceOf, supportsA2UIVersion } from './A2UIStream';\nimport { a2uiInstructions } from './A2UIInstructions';\n// Types only: the runtime, with the A2UI packages, loads in the browser when a reply first\n// shows A2UI.\nimport type { ReactA2uiComponentProps } from '@a2ui/react';\nimport type { A2UIReplyState, A2UIRuntime } from './runtime';\n\nexport { A2UI_DEFAULT_CATALOG_ID, A2UI_LEGACY_CATALOG_ID };\n\n/** What went wrong in a reply's A2UI, as the A2UI specification reports it to an agent. */\nexport type A2UIError = {\n  /** A code such as `VALIDATION_FAILED` or `EXPRESSION_ERROR`. */\n  code: string;\n  message: string;\n  /** Where in the message it went wrong, as a JSON pointer. */\n  path?: string;\n  surfaceId?: string;\n};\n\n/** The components of A2UI's basic catalog, each of which an app can draw its own way or leave out. */\nexport type A2UIBasicComponentName =\n  | 'AudioPlayer'\n  | 'Button'\n  | 'Card'\n  | 'CheckBox'\n  | 'ChoicePicker'\n  | 'Column'\n  | 'DateTimeInput'\n  | 'Divider'\n  | 'Icon'\n  | 'Image'\n  | 'List'\n  | 'Modal'\n  | 'Row'\n  | 'Slider'\n  | 'Tabs'\n  | 'Text'\n  | 'TextField'\n  | 'Video';\n\n/**\n * An app's view of one of the basic catalog's components, as `@a2ui/react` places it: with\n * `props` worked out from what the agent wrote, `buildChild` to place its children by id, and\n * the component's `context`.\n */\nexport type A2UIBasicComponent = ComponentType<\n  ReactA2uiComponentProps<Record<string, unknown>>\n>;\n\nexport type A2UIRendererOptions = {\n  /**\n   * The basic catalog's components to draw the app's way, by name, or `null` to leave one out\n   * of the catalog and the agent's instructions, such as `{ Video: null }`.\n   */\n  basicComponents?: Partial<Record<A2UIBasicComponentName, A2UIBasicComponent | null>>;\n  /**\n   * The id the agent names the catalog with the app's components by. A surface naming the\n   * basic catalog shows them too, and a surface naming none is made with this one.\n   */\n  catalogId?: string;\n  /**\n   * The icon font the page loads, such as `'Material Symbols Outlined'`, for the icons of A2UI's\n   * Icon that neither `icons` nor Stream draws. Without one, such an icon shows nothing.\n   */\n  iconFont?: string;\n  /**\n   * The app's icons for the names A2UI's Icon takes, such as `shoppingCart`, over Stream's.\n   * Stream draws about 30 of the 60 names.\n   */\n  icons?: Partial<Record<string, ComponentType<ComponentPropsWithoutRef<'svg'>>>>;\n  /**\n   * What the app tells the agent's model about writing its UI, such as when to answer with UI,\n   * ahead of A2UI's own instructions in `capabilities`.\n   */\n  instructions?: string;\n  /**\n   * What an image, video or sound the agent links to loads: the URL, another, or `null` not to\n   * load it. Public web links and the page's own site load by default (`aiUIPublicMediaURL`).\n   */\n  mediaUrl?: AIUIMediaURL;\n  /**\n   * Tells the app what went wrong in a reply's A2UI, such as a message that isn't JSON or a\n   * component the catalog doesn't have, with the reply's id. The rest of the reply's UI still\n   * shows. What is wrong with the renderer rather than a reply, such as an app's component that\n   * can't join the catalog or a runtime that couldn't load, comes without an id. Logged by\n   * default.\n   */\n  onError?: (error: A2UIError, messageId?: string) => void;\n};\n\nconst reportA2UIError = (\n  options: A2UIRendererOptions,\n  error: A2UIError,\n  messageId?: string,\n) => {\n  if (options.onError) options.onError(error, messageId);\n  else console.error(`A reply's A2UI can't show: ${error.code} ${error.message}`, error);\n};\n\n/**\n * Shows the A2UI of one conversation. Each reply's surfaces are its own, kept for as long as\n * the host keeps the engine, so what the person entered survives scrolling.\n */\nexport class A2UIEngine implements AIUIEngine {\n  readonly catalogId: string;\n  readonly basicComponents: NonNullable<A2UIRendererOptions['basicComponents']>;\n  readonly host: AIUIHost;\n  readonly iconFont?: string;\n  readonly icons?: A2UIRendererOptions['icons'];\n  /** What an image, video or sound the agent links to loads. */\n  readonly mediaURL: AIUIMediaURL;\n  /** Loads the runtime, the A2UI packages, when a reply first shows A2UI. */\n  readonly loader: AIUIRuntimeLoader<A2UIRuntime>;\n  /** Each reply's surfaces, by the reply's id. */\n  readonly replies = new Map<string, A2UIReplyState>();\n\n  private readonly options: A2UIRendererOptions;\n\n  constructor(host: AIUIHost, options: A2UIRendererOptions) {\n    this.host = host;\n    this.options = options;\n    this.catalogId = options.catalogId ?? A2UI_DEFAULT_CATALOG_ID;\n    this.basicComponents = options.basicComponents ?? {};\n    this.iconFont = options.iconFont;\n    this.icons = options.icons;\n    this.mediaURL = options.mediaUrl ?? aiUIPublicMediaURL;\n    this.loader = new AIUIRuntimeLoader(\n      host,\n      () => import('./runtime'),\n      (error) =>\n        this.report({\n          code: 'EXECUTION_ERROR',\n          message: `The A2UI renderer couldn't load: ${String(error)}`,\n        }),\n    );\n  }\n\n  /**\n   * Tells the app what went wrong, after the current render: a reply's messages are applied\n   * as it first shows, and an app may set state when told.\n   */\n  report(error: A2UIError, messageId?: string) {\n    queueMicrotask(() => reportA2UIError(this.options, error, messageId));\n  }\n\n  remove(messageId: string) {\n    this.replies.get(messageId)?.dispose();\n    this.replies.delete(messageId);\n  }\n\n  view(document: AIUIDocument, messageId: string) {\n    if (a2uiSourceOf(document) === undefined || this.loader.showsText(document))\n      return null;\n    // A finished reply whose A2UI made no surface shows its text instead, once that is known.\n    if (this.loader.runtime?.showsNothing(this, document, messageId)) return null;\n    return (\n      <AIUIRuntimeView\n        loader={this.loader}\n        placeholder={<A2UIPlaceholder />}\n        render={({ A2UIReplyContent }) => (\n          <A2UIReplyContent document={document} engine={this} messageId={messageId} />\n        )}\n      />\n    );\n  }\n}\n\n/**\n * The renderer of [A2UI](https://a2ui.org) 1.0 for `AIUIHost`, on the official A2UI packages\n * (`@a2ui/web_core` and `@a2ui/react`, which the app installs). The app's components join its\n * catalog, so the agent places them like the basic catalog's own. The counterpart of\n * `A2UIRenderer` in StreamChatA2UI.\n */\nexport const createA2UIRenderer = (options: A2UIRendererOptions = {}): AIUIRenderer => {\n  const catalogId = options.catalogId ?? A2UI_DEFAULT_CATALOG_ID;\n  return {\n    // As StreamChatA2UI's: the fence, the catalog and the instructions for both, with the\n    // app's own instructions first and its tools, written with the A2UI core, which loads to\n    // write them. Without them, when it can't load, the rest still goes to the agent's backend.\n    capabilities: async (components, tools = []) => {\n      const fence = `ui:a2ui@${A2UI_VERSION}`;\n      const remove = Object.entries(options.basicComponents ?? {})\n        .filter(([, view]) => view === null)\n        .map(([name]) => name);\n      let instructions: string | undefined;\n      try {\n        instructions = await a2uiInstructions({\n          catalogId,\n          components,\n          fence,\n          ...(options.instructions?.trim()\n            ? { preamble: options.instructions.trim() }\n            : {}),\n          ...(remove.length ? { remove } : {}),\n          ...(tools.length ? { tools } : {}),\n        });\n      } catch (error) {\n        reportA2UIError(options, {\n          code: 'EXECUTION_ERROR',\n          message: `The A2UI instructions couldn't be written: ${String(error)}`,\n        });\n      }\n      return {\n        catalog_id: catalogId,\n        fence,\n        ...(instructions === undefined ? {} : { instructions }),\n      };\n    },\n    createEngine: (host) => new A2UIEngine(host, options),\n    format: 'a2ui',\n    supports: supportsA2UIVersion,\n  };\n};\n"],"mappings":";;;;;;;;;AAyGA,IAAM,mBACJ,SACA,OACA,cACG;CACH,IAAI,QAAQ,SAAS,QAAQ,QAAQ,OAAO,SAAS;MAChD,QAAQ,MAAM,8BAA8B,MAAM,KAAK,GAAG,MAAM,WAAW,KAAK;AACvF;;;;;AAMA,IAAa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