{"version":3,"file":"OpenUIRenderer.mjs","names":[],"sources":["../../../../src/plugins/OpenUI/OpenUIRenderer.tsx"],"sourcesContent":["import React from 'react';\n\nimport type { AIUIComponent } from '../AIComponents/GenerativeUI/AIUIComponent';\nimport {\n  type AIUIDocument,\n  aiUIDocumentText,\n} 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 type { AIUIClientToolDefinition } from '../AIComponents/GenerativeUI/AIUITools';\nimport {\n  AIUIRuntimeLoader,\n  AIUIRuntimeView,\n} from '../AIComponents/GenerativeUI/AIUIRuntimeLoader';\nimport { OpenUIPlaceholder } from './OpenUIPlaceholder';\n// Types only: the runtime, with the OpenUI packages, loads when a reply first shows OpenUI.\nimport type { OpenUILibrary, OpenUIRuntime } from './runtime';\n\n// `@openuidev/react-lang` mounts OpenUI's inspector in development unless this is set first.\nconst DEVTOOLS_MOUNTED = Symbol.for('openui.devtools.autoMount');\n\n// Loads the runtime, keeping OpenUI's inspector off the page unless the app asked for it.\nconst loadRuntime = (devtools = false) => {\n  if (!devtools) (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED] = true;\n  return import('./runtime');\n};\n\n/** The fence an agent writes an OpenUI program in, which the agents router reads. */\nexport const OPENUI_FENCE = 'openui-lang';\n\n/** What went wrong in a reply's OpenUI program, as OpenUI reports it to an agent. */\nexport type OpenUIError = {\n  /** A code such as `unknown-component` or `missing-required`. */\n  code: string;\n  message: string;\n  /** The component it is about, when it is about one. */\n  component?: string;\n  /** The statement it is about, such as `root`. */\n  statementId?: string;\n};\n\nexport type OpenUIRendererOptions = {\n  /**\n   * Whether OpenUI's own inspector shows in development, as `@openuidev/react-lang` mounts it\n   * on every page that loads it, with its offers. Off by default: the app's page is the app's.\n   */\n  devtools?: boolean;\n  /**\n   * What the app tells the agent's model about writing its UI, such as when to answer with UI,\n   * ahead of OpenUI's own instructions in `capabilities`.\n   */\n  instructions?: string;\n  /**\n   * The library the agent writes with, before the app's components join it: OpenUI's chat\n   * library (`openuiChatLibrary` of `@openuidev/react-ui/genui-lib`) by default. Give one made\n   * with `createLibrary` of `@openuidev/react-lang` to use components of your own.\n   */\n  library?: OpenUILibrary;\n  /**\n   * What an image the agent links to loads: the URL, another, or `null` not to load it.\n   * 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 program, such as a component the library\n   * doesn't have, with the reply's id. The rest of the reply's UI still shows. What is wrong\n   * with the renderer rather than a reply, such as an app's component that can't join the\n   * library or a runtime that couldn't load, comes without an id. Logged by default.\n   */\n  onError?: (error: OpenUIError, messageId?: string) => void;\n  /**\n   * Runs the tools a program's `Query()` and `Mutation()` call. By default they are the host's\n   * client tools, run in the page: one that isn't read-only only just after the person pressed a\n   * control in the reply's UI, such as a button, and a Query asking the same again within 5 s\n   * gets the answer it got.\n   */\n  toolProvider?: Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n};\n\nconst reportOpenUIError = (\n  options: OpenUIRendererOptions,\n  error: OpenUIError,\n  messageId?: string,\n) => {\n  if (options.onError) options.onError(error, messageId);\n  else\n    console.error(`A reply's OpenUI can't show: ${error.code} ${error.message}`, error);\n};\n\n/**\n * Shows the OpenUI of one conversation. Each reply's form values are kept in the host, so\n * they survive scrolling.\n */\nexport class OpenUIEngine implements AIUIEngine {\n  readonly host: AIUIHost;\n  /** Loads the runtime, the OpenUI packages, when a reply first shows OpenUI. */\n  readonly loader: AIUIRuntimeLoader<OpenUIRuntime>;\n  /** What an image the agent links to loads. */\n  readonly mediaURL: AIUIMediaURL;\n  readonly options: OpenUIRendererOptions;\n  /** What has been said about each reply's program, so each error is said once. */\n  readonly reported = new Map<string, Set<string>>();\n\n  // The program of each finished reply that draws nothing, so the reply shows its text.\n  private readonly drawsNothing = new Map<string, string>();\n\n  constructor(host: AIUIHost, options: OpenUIRendererOptions) {\n    this.host = host;\n    this.options = options;\n    this.mediaURL = options.mediaUrl ?? aiUIPublicMediaURL;\n    this.loader = new AIUIRuntimeLoader(\n      host,\n      () => loadRuntime(options.devtools),\n      (error) =>\n        this.report({\n          code: 'runtime-error',\n          message: `The OpenUI renderer couldn't load: ${String(error)}`,\n        }),\n    );\n  }\n\n  /** Notes that a finished reply's program draws nothing, such as words that aren't OpenUI. */\n  drewNothing(messageId: string, program: string) {\n    if (this.drawsNothing.get(messageId) === program) return;\n    this.drawsNothing.set(messageId, program);\n    this.host.refresh();\n  }\n\n  remove(messageId: string) {\n    this.drawsNothing.delete(messageId);\n    this.reported.delete(messageId);\n  }\n\n  /**\n   * Tells the app what went wrong, after the current render: the library is made as a reply\n   * first shows, and an app may set state when told.\n   */\n  report(error: OpenUIError, messageId?: string) {\n    queueMicrotask(() => reportOpenUIError(this.options, error, messageId));\n  }\n\n  view(document: AIUIDocument, messageId: string) {\n    const program = aiUIDocumentText(document);\n    // A finished reply whose program draws nothing shows its text instead.\n    if (\n      program === undefined ||\n      this.loader.showsText(document) ||\n      (!document.isStreaming &&\n        (program.trim() === '' || this.drawsNothing.get(messageId) === program))\n    ) {\n      return null;\n    }\n    return (\n      <AIUIRuntimeView\n        loader={this.loader}\n        placeholder={<OpenUIPlaceholder />}\n        render={({ OpenUIReplyContent }) => (\n          <OpenUIReplyContent document={document} engine={this} messageId={messageId} />\n        )}\n      />\n    );\n  }\n}\n\n/**\n * The instructions that teach an agent's model to write OpenUI with the library and the app's\n * `components`, call the app's `tools`, and heed the app's own `instructions`, which come\n * first, from OpenUI's own prompt generator. Give them to the agent's backend, as the part of\n * its instructions about UI. It loads the OpenUI packages.\n */\nexport const openUIInstructions = async (\n  components: AIUIComponent[],\n  options: Pick<OpenUIRendererOptions, 'devtools' | 'instructions' | 'library'> & {\n    tools?: AIUIClientToolDefinition[];\n  } = {},\n) =>\n  (await loadRuntime(options.devtools)).instructionsFor(components, {\n    ...(options.instructions ? { instructions: options.instructions } : {}),\n    ...(options.library ? { library: options.library } : {}),\n    ...(options.tools ? { tools: options.tools } : {}),\n  });\n\n/**\n * The renderer of [OpenUI](https://openui.com) for `AIUIHost`, on the official OpenUI packages\n * (`@openuidev/react-lang` and `@openuidev/react-ui`, which the app installs). The app's\n * components join its library, so the agent places them like the library's own. The\n * counterpart of `OpenUIRenderer` in StreamChatOpenUI.\n */\nexport const createOpenUIRenderer = (\n  options: OpenUIRendererOptions = {},\n): AIUIRenderer => ({\n  // As StreamChatOpenUI's: the fence and the instructions, with the app's tools, written with\n  // OpenUI's own prompt generator, which loads the OpenUI packages to write them. Without them,\n  // when they can't load, the fence still goes to the agent's backend.\n  capabilities: async (components, tools = []) => {\n    let instructions: string | undefined;\n    try {\n      instructions = await openUIInstructions(components, { ...options, tools });\n    } catch (error) {\n      reportOpenUIError(options, {\n        code: 'runtime-error',\n        message: `The OpenUI instructions couldn't be written: ${String(error)}`,\n      });\n    }\n    return {\n      fence: OPENUI_FENCE,\n      ...(instructions === undefined ? {} : { instructions }),\n    };\n  },\n  createEngine: (host) => new OpenUIEngine(host, options),\n  format: 'openui',\n});\n"],"mappings":";;;;;;;AAuBA,IAAM,mBAAmB,OAAO,IAAI,2BAA2B;AAG/D,IAAM,eAAe,WAAW,UAAU;CACxC,IAAI,CAAC,UAAU,WAAwC,oBAAoB;CAC3E,OAAO,OAAO;AAChB;;AAGA,IAAa,eAAe;AAmD5B,IAAM,qBACJ,SACA,OACA,cACG;CACH,IAAI,QAAQ,SAAS,QAAQ,QAAQ,OAAO,SAAS;MAEnD,QAAQ,MAAM,gCAAgC,MAAM,KAAK,GAAG,MAAM,WAAW,KAAK;AACtF;;;;;AAMA,IAAa,eAAb,MAAgD;CAC9C;;CAEA;;CAEA;CACA;;CAEA,2BAAoB,IAAI,IAAyB;CAGjD,+BAAgC,I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