@copilotkit/react-core 1.84.2-canary.openbot-intel-fixes → 1.86.0

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.
Files changed (70) hide show
  1. package/dist/MarkdownSurfaces-BCVdnDAk.cjs +161 -0
  2. package/dist/MarkdownSurfaces-BCVdnDAk.cjs.map +1 -0
  3. package/dist/MarkdownSurfaces-CjJduaJR.mjs +149 -0
  4. package/dist/MarkdownSurfaces-CjJduaJR.mjs.map +1 -0
  5. package/dist/{MarkdownSurfaces-3cGU5_0H.cjs → chat-BnsrQ0VS.cjs} +667 -320
  6. package/dist/chat-BnsrQ0VS.cjs.map +1 -0
  7. package/dist/{MarkdownSurfaces-D-W4f9Dy.mjs → chat-IWySXWXP.mjs} +647 -312
  8. package/dist/chat-IWySXWXP.mjs.map +1 -0
  9. package/dist/{copilotkit-UHD9sXsS.mjs → copilotkit-B1OLgEU8.mjs} +6 -354
  10. package/dist/copilotkit-B1OLgEU8.mjs.map +1 -0
  11. package/dist/{copilotkit-Dn4PbHJV.d.mts → copilotkit-C7G95NO-.d.mts} +4 -4
  12. package/dist/{copilotkit-Dn4PbHJV.d.mts.map → copilotkit-C7G95NO-.d.mts.map} +1 -1
  13. package/dist/{copilotkit-DYtl9zj0.cjs → copilotkit-Ca0IcTZU.cjs} +79 -427
  14. package/dist/copilotkit-Ca0IcTZU.cjs.map +1 -0
  15. package/dist/{copilotkit-CuTAoQF2.d.cts → copilotkit-DwD7D6jJ.d.cts} +2 -2
  16. package/dist/{copilotkit-CuTAoQF2.d.cts.map → copilotkit-DwD7D6jJ.d.cts.map} +1 -1
  17. package/dist/hooks-DMSkcNOl.d.cts +89 -0
  18. package/dist/hooks-DMSkcNOl.d.cts.map +1 -0
  19. package/dist/hooks-EwGvqYsW.d.mts +89 -0
  20. package/dist/hooks-EwGvqYsW.d.mts.map +1 -0
  21. package/dist/index.cjs +8 -8
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +2 -2
  24. package/dist/index.d.mts +2 -2
  25. package/dist/index.mjs +2 -2
  26. package/dist/index.umd.js +645 -140
  27. package/dist/index.umd.js.map +1 -1
  28. package/dist/refs-DL7ITFFD.cjs +43 -0
  29. package/dist/refs-DL7ITFFD.cjs.map +1 -0
  30. package/dist/refs-DiZXJ63p.mjs +31 -0
  31. package/dist/refs-DiZXJ63p.mjs.map +1 -0
  32. package/dist/{runtime-context-Er5UIbZA.d.mts → runtime-context-B4fKyzo6.d.mts} +31 -9
  33. package/dist/runtime-context-B4fKyzo6.d.mts.map +1 -0
  34. package/dist/{runtime-context-DrVNUYLi.d.cts → runtime-context-Da7T5vy4.d.cts} +31 -9
  35. package/dist/runtime-context-Da7T5vy4.d.cts.map +1 -0
  36. package/dist/use-generative-ui-root-CaTyBFNR.cjs +390 -0
  37. package/dist/use-generative-ui-root-CaTyBFNR.cjs.map +1 -0
  38. package/dist/use-generative-ui-root-WI9ERMpo.mjs +385 -0
  39. package/dist/use-generative-ui-root-WI9ERMpo.mjs.map +1 -0
  40. package/dist/v2/generative-ui/native.cjs +66 -0
  41. package/dist/v2/generative-ui/native.cjs.map +1 -0
  42. package/dist/v2/generative-ui/native.d.cts +155 -0
  43. package/dist/v2/generative-ui/native.d.cts.map +1 -0
  44. package/dist/v2/generative-ui/native.d.mts +155 -0
  45. package/dist/v2/generative-ui/native.d.mts.map +1 -0
  46. package/dist/v2/generative-ui/native.mjs +24 -0
  47. package/dist/v2/generative-ui/native.mjs.map +1 -0
  48. package/dist/v2/generative-ui.cjs +45 -70
  49. package/dist/v2/generative-ui.cjs.map +1 -1
  50. package/dist/v2/generative-ui.d.cts +229 -308
  51. package/dist/v2/generative-ui.d.cts.map +1 -1
  52. package/dist/v2/generative-ui.d.mts +229 -308
  53. package/dist/v2/generative-ui.d.mts.map +1 -1
  54. package/dist/v2/generative-ui.mjs +4 -29
  55. package/dist/v2/generative-ui.mjs.map +1 -1
  56. package/dist/v2/headless.d.cts +185 -294
  57. package/dist/v2/headless.d.cts.map +1 -1
  58. package/dist/v2/index.cjs +5 -5
  59. package/dist/v2/index.d.cts +2 -2
  60. package/dist/v2/index.d.mts +2 -2
  61. package/dist/v2/index.mjs +2 -2
  62. package/dist/v2/index.umd.js +645 -140
  63. package/dist/v2/index.umd.js.map +1 -1
  64. package/package.json +15 -11
  65. package/dist/MarkdownSurfaces-3cGU5_0H.cjs.map +0 -1
  66. package/dist/MarkdownSurfaces-D-W4f9Dy.mjs.map +0 -1
  67. package/dist/copilotkit-DYtl9zj0.cjs.map +0 -1
  68. package/dist/copilotkit-UHD9sXsS.mjs.map +0 -1
  69. package/dist/runtime-context-DrVNUYLi.d.cts.map +0 -1
  70. package/dist/runtime-context-Er5UIbZA.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-generative-ui-root-CaTyBFNR.cjs","names":["GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION","GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION","GENERATIVE_UI_ACTIVITY_TYPE","useShallowStableRef","GenerativeUISurfaceManager","COPILOTKIT_FORWARDED_PROPS_KEY","GenerativeUIError","DEFAULT_AGENT_ID"],"sources":["../src/v2/generative-ui/markdown/context.ts","../src/v2/generative-ui/use-generative-ui-root.ts"],"sourcesContent":["import { useEffect } from \"react\";\nimport {\n buildCompactGenerativeUISchema,\n buildGenerativeUIMarkdownGuidelines,\n generativeUIGuideFeatures,\n GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,\n GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,\n defaultGenerativeUIPromptSpec,\n renderGenerativeUISchema,\n} from \"@copilotkit/shared\";\nimport { buildGenerativeUIManifest } from \"@copilotkit/core/generative-ui\";\nimport type { CopilotKitCoreReact } from \"../../lib/react-core\";\nimport type { GenerativeUIRuntime } from \"../runtime-context\";\n\n/** The compact schema lives in shared, so tools outside React build the same text. */\nexport { buildCompactGenerativeUISchema };\n\n/** What the markdown context of the generative UI needs. */\nexport interface GenerativeUIMarkdownContextOptions {\n /** Register the entries. False for the tool transport or `sendContext: false`. */\n enabled: boolean;\n /** The agents that get the entries. All agents when left out. */\n agentIds: string[] | undefined;\n}\n\n/**\n * Registers the two context entries of the markdown transport: the compact\n * component schema and the fence guideline. Both go only to `agentIds`.\n *\n * The schema is built again at each run start and when a\n * `<GenerativeUISurface>` mounts, unmounts, or changes its description or\n * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.\n *\n * @param copilotkit - The CopilotKit core of the provider.\n * @param runtime - The generative UI runtime parts, or null without one.\n * @param options - `enabled` and `agentIds`.\n *\n * @example\n * ```ts\n * useGenerativeUIMarkdownContext(copilotkit, core, {\n * enabled: config?.transport === \"markdown\" && config.sendContext !== false,\n * agentIds: config?.agentIds,\n * });\n * ```\n */\nexport function useGenerativeUIMarkdownContext(\n copilotkit: CopilotKitCoreReact,\n runtime: Pick<GenerativeUIRuntime, \"ui\" | \"manager\" | \"dispatcher\"> | null,\n options: GenerativeUIMarkdownContextOptions,\n) {\n const { enabled, agentIds } = options;\n // A new array with the same ids must not register the entries again.\n const agentIdsKey = agentIds === undefined ? \"\" : JSON.stringify(agentIds);\n\n useEffect(() => {\n if (!runtime || !enabled) return;\n const scopedAgentIds: string[] | undefined = agentIdsKey\n ? JSON.parse(agentIdsKey)\n : undefined;\n const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};\n // The guideline has only the rule groups that the manifest uses, and the\n // mounted functions can change, so it is built again with the schema.\n let guidelineId: string | undefined;\n let guidelineValue: string | undefined;\n let schemaId: string | undefined;\n let schemaValue: string | undefined;\n const refreshSchema = (threadId: string | undefined) => {\n const manifest = buildGenerativeUIManifest(runtime, threadId);\n const guideline = buildGenerativeUIMarkdownGuidelines(\n generativeUIGuideFeatures(manifest),\n );\n if (guideline !== guidelineValue) {\n if (guidelineId !== undefined) copilotkit.removeContext(guidelineId);\n guidelineValue = guideline;\n guidelineId = copilotkit.addContext({\n description: GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,\n value: guideline,\n ...scope,\n });\n }\n const value = renderGenerativeUISchema(\n manifest,\n defaultGenerativeUIPromptSpec().schema.markdown,\n );\n if (value === schemaValue) return;\n if (schemaId !== undefined) copilotkit.removeContext(schemaId);\n schemaValue = value;\n schemaId = copilotkit.addContext({\n description: GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,\n value,\n ...scope,\n });\n };\n refreshSchema(runtime.manager.getActiveThread());\n\n // The manager notifies on every operation. Build the schema again only\n // when the mounted targets, their descriptions, or their component lists\n // change.\n let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());\n const unsubscribeManager = runtime.manager.subscribe(() => {\n const nextKey = JSON.stringify(runtime.manager.getMountedTargets());\n if (nextKey === targetsKey) return;\n targetsKey = nextKey;\n refreshSchema(runtime.manager.getActiveThread());\n });\n // Function handlers can mount at any time. Core reads the context after\n // this callback, so the run gets the current functions and the surfaces\n // of its thread.\n const subscription = copilotkit.subscribe({\n onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId),\n });\n\n return () => {\n subscription.unsubscribe();\n unsubscribeManager();\n if (guidelineId !== undefined) copilotkit.removeContext(guidelineId);\n if (schemaId !== undefined) copilotkit.removeContext(schemaId);\n };\n }, [copilotkit, runtime, enabled, agentIdsKey]);\n}\n","import { useEffect, useMemo, useRef } from \"react\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport {\n COPILOTKIT_FORWARDED_PROPS_KEY,\n DEFAULT_AGENT_ID,\n GENERATIVE_UI_ACTIVITY_TYPE,\n randomUUID,\n toA2UIActionMessage,\n} from \"@copilotkit/shared\";\nimport type { A2UIActionMessage } from \"@copilotkit/shared\";\nimport type { CopilotKitCoreReact } from \"../lib/react-core\";\nimport { useShallowStableRef } from \"../lib/shallow-stable-ref\";\nimport {\n buildActionMessageText,\n envelopeOptionsFor,\n surfaceLabelResolver,\n} from \"@copilotkit/core/generative-ui\";\nimport {\n createGenerativeUIDebugSource,\n describeGenerativeUIRun,\n} from \"@copilotkit/core/generative-ui\";\nimport { createGenerativeUIDispatcher } from \"@copilotkit/core/generative-ui\";\nimport { GenerativeUIError } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUIErrorInfo } from \"@copilotkit/shared/generative-ui\";\nimport { parseGenerativeUISurfaceContent } from \"./activity\";\nimport { catalogIdsOf } from \"./catalog\";\nimport { buildGenerativeUIEnvelope } from \"@copilotkit/core/generative-ui\";\nimport type {\n GenerativeUIConfig,\n GenerativeUIRuntime,\n} from \"./runtime-context\";\nimport { useGenerativeUIMarkdownContext } from \"./markdown/context\";\nimport { getMarkdownSurfaceSource } from \"@copilotkit/core/generative-ui\";\nimport {\n activityFunctionCalls,\n createFunctionCallRunner,\n markdownFunctionCalls,\n} from \"@copilotkit/core/generative-ui\";\nimport type { ReadonlyMessages } from \"@copilotkit/core/generative-ui\";\nimport { GenerativeUISurfaceManager } from \"@copilotkit/core/generative-ui\";\n\nconst isDevelopment = () => process.env.NODE_ENV !== \"production\";\n\n/**\n * The malformed-content warnings already printed, by manager, so each\n * distinct issue warns once while the manager lives.\n */\nconst warnedMalformed = new WeakMap<GenerativeUISurfaceManager, Set<string>>();\n\n/**\n * Ingests the surface activity messages of `messages`. A message whose\n * content is malformed (for example `null`) is skipped, in development with a\n * warning once for each distinct issue, so it cannot throw inside the\n * agent's run; the messages after it are still ingested.\n */\nfunction ingestMessages(\n manager: GenerativeUISurfaceManager,\n agent: AbstractAgent,\n messages: ReadonlyMessages,\n) {\n const { threadId } = agent;\n if (!threadId) return;\n for (const message of messages) {\n if (\n message.role !== \"activity\" ||\n message.activityType !== GENERATIVE_UI_ACTIVITY_TYPE\n ) {\n continue;\n }\n const parsed = parseGenerativeUISurfaceContent(message.content);\n if (parsed.content) {\n manager.ingest(threadId, agent.agentId, parsed.content);\n continue;\n }\n if (!isDevelopment()) continue;\n const warning = `[generativeUI] skipped an activity message of thread ${JSON.stringify(threadId)}: its content is malformed: ${parsed.issues.join(\"; \")}.`;\n let warned = warnedMalformed.get(manager);\n if (!warned) {\n warned = new Set();\n warnedMalformed.set(manager, warned);\n }\n if (warned.has(warning)) continue;\n warned.add(warning);\n console.warn(warning);\n }\n}\n\n/** Provider-side wiring: manager, dispatcher, agent subscriptions, envelope. */\nexport function useGenerativeUIRoot(\n copilotkit: CopilotKitCoreReact,\n config: GenerativeUIConfig | undefined,\n): GenerativeUIRuntime | null {\n const configRef = useRef(config);\n configRef.current = config;\n const ui = config?.ui;\n const transport = config?.transport ?? \"tool\";\n const theme = useShallowStableRef(config?.theme);\n\n // The parts that live as long as `ui`. The surfaces are in the manager, so\n // a new theme or transport does not remount them.\n const core = useMemo(() => {\n if (!ui) return null;\n // Never throws: it is called from rendering, ingestion and event handlers,\n // and a throwing host `onError` must not break any of them.\n const reportError = (info: GenerativeUIErrorInfo) => {\n try {\n configRef.current?.errorBoundary?.onError?.(info);\n } catch (hostError) {\n if (isDevelopment()) {\n console.error(\n \"[generativeUI] errorBoundary.onError threw:\",\n hostError,\n );\n }\n }\n if (isDevelopment()) {\n console.warn(\n `[generativeUI] ${info.kind} error in ${info.surfaceId}${info.componentId ? `/${info.componentId}` : \"\"}: ${info.error?.message}`,\n );\n }\n };\n const manager = new GenerativeUISurfaceManager(ui, {\n onOperationRejected: ({ surfaceId, index, reason }) =>\n reportError({\n kind: \"operation\",\n surfaceId,\n error: new Error(`operation ${index} rejected: ${reason}`),\n }),\n });\n const dispatcher = createGenerativeUIDispatcher({\n getDeclared: () => ui.functions,\n onError: ({ name, origin, error }) => {\n if (\"functionCallId\" in origin) {\n // The model gets this error in the answer of the call. The error\n // info of `onError` needs a surface, and this call has none.\n if (isDevelopment()) {\n console.warn(\n `[generativeUI] function call ${origin.functionCallId} to \"${name}\" failed: ${error.message}`,\n );\n }\n return;\n }\n reportError({ kind: \"function\", ...origin, error });\n },\n });\n const functionCalls = createFunctionCallRunner({\n core: copilotkit,\n dispatcher,\n manifest: {\n catalogId: ui.id,\n catalogIds: catalogIdsOf(ui),\n components: ui.manifestComponents,\n },\n // As for a frontend-tool follow-up: let React commit the state that\n // the handlers set, so that the follow-up run reads it.\n settle: () => copilotkit.waitForPendingFrameworkUpdates(),\n warn: (message, error) => {\n if (isDevelopment()) console.warn(message, error);\n },\n });\n // The agents with an event on its way to a run. Set before the run\n // starts, so a repeat click in the same tick is caught too.\n const forwardingAgents = new Set<AbstractAgent>();\n /**\n * The action of a user event, as an envelope entry scoped to the agent\n * the user acted on, for the run that the event starts: the structured\n * form of the user message. It is set before the run starts and dropped\n * when the run is over, so a suggestion request or a follow-up run\n * (both read the properties with no run start) does not carry the same\n * action again, and another agent never gets a click meant for this one.\n * The entry comes after the shared envelope, so it wins for its agent;\n * `refreshActions` keeps it last when the shared envelope is set again.\n */\n const actions = new Map<\n AbstractAgent,\n {\n id: string;\n action: A2UIActionMessage;\n /** Drops the action when the run ends, before any follow-up run. */\n subscription: { unsubscribe(): void };\n }\n >();\n const dropAction = (agent: AbstractAgent) => {\n const entry = actions.get(agent);\n if (!entry) return;\n entry.subscription.unsubscribe();\n copilotkit.removeScopedProperties(entry.id);\n actions.delete(agent);\n };\n const setAction = (agent: AbstractAgent, action: A2UIActionMessage) => {\n const previous = actions.get(agent);\n previous?.subscription.unsubscribe();\n if (previous) copilotkit.removeScopedProperties(previous.id);\n actions.delete(agent);\n const latest = configRef.current;\n if (!latest) return;\n const envelope = buildGenerativeUIEnvelope(\n { ui, manager, dispatcher },\n agent.threadId,\n { ...envelopeOptionsFor(latest), action },\n );\n const id = copilotkit.addScopedProperties({\n properties: { [COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: envelope } },\n agentIds:\n agent.agentId === undefined ? latest.agentIds : [agent.agentId],\n });\n // The run ends before `runAgent` resolves: a frontend tool makes a\n // follow-up run first, and that run must not carry the action again.\n // The agent itself says when its run is over.\n const subscription = agent.subscribe({\n onRunFinalized: () => dropAction(agent),\n onRunFailed: () => dropAction(agent),\n });\n actions.set(agent, { id, action, subscription });\n };\n const refreshActions = () => {\n for (const [agent, { action }] of [...actions]) setAction(agent, action);\n };\n const dropAllActions = () => {\n for (const agent of [...actions.keys()]) dropAction(agent);\n };\n const forwardEvent: GenerativeUIRuntime[\"forwardEvent\"] = async (\n event,\n agentId,\n ) => {\n const fail = (message: string) => {\n const error = new GenerativeUIError(\"event_forward_failed\", message);\n reportError({\n kind: \"event\",\n surfaceId: event.surfaceId,\n componentId: event.componentId,\n error,\n });\n return { ok: false as const, error };\n };\n const agent = copilotkit.getAgent(agentId ?? DEFAULT_AGENT_ID);\n if (!agent) {\n return fail(`No agent \"${agentId}\" to receive \"${event.name}\"`);\n }\n // An event is a one-click send. While the agent runs, or another event\n // is on its way, a second one is almost always a repeat: a double\n // click, or a click while the reply streams. Sending it would start a\n // second run and derail the chat, so it is dropped. The component gets\n // `agent_busy`; it is not an error of the UI, so nothing is reported.\n if (agent.isRunning || forwardingAgents.has(agent)) {\n return {\n ok: false as const,\n error: new GenerativeUIError(\n \"agent_busy\",\n `\"${event.name}\" was not sent: the agent is running`,\n ),\n };\n }\n forwardingAgents.add(agent);\n try {\n // A visible user message: the user and the model both see the event.\n const surface = agent.threadId\n ? manager.getSurface(agent.threadId, event.surfaceId)\n : undefined;\n const resolveLabel = surface\n ? surfaceLabelResolver(surface)\n : undefined;\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: buildActionMessageText(event, resolveLabel),\n });\n // Set now, not at the run start: while another agent runs, this\n // run starts with no run-start notification.\n setAction(agent, toA2UIActionMessage(event));\n await copilotkit.runAgent({ agent });\n return { ok: true, result: undefined };\n } catch (cause) {\n return fail(\n `Forwarding \"${event.name}\" failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n } finally {\n forwardingAgents.delete(agent);\n dropAction(agent);\n }\n };\n return {\n manager,\n dispatcher,\n ui,\n forwardEvent,\n reportError,\n functionCalls,\n refreshActions,\n dropAllActions,\n };\n }, [ui, copilotkit]);\n\n // A new object when the theme or the transport changes, so that the\n // components that read them render again.\n const runtime = useMemo<GenerativeUIRuntime | null>(() => {\n if (!core) return null;\n const { manager, dispatcher, forwardEvent, reportError } = core;\n return {\n manager,\n dispatcher,\n ui: core.ui,\n forwardEvent,\n reportError,\n transport,\n theme,\n get config() {\n // `core` exists only while the provider has a config. After the\n // config is removed, nothing reads this runtime again.\n return configRef.current ?? { ui: core.ui };\n },\n get errorFallback() {\n return configRef.current?.errorBoundary?.fallback;\n },\n };\n }, [core, transport, theme]);\n\n useEffect(() => {\n if (!core) return;\n const watched = new WeakSet<AbstractAgent>();\n const agentSubscriptions: Array<{ unsubscribe(): void }> = [];\n let envelopeId: string | undefined;\n // The inspector reads the catalog, the surfaces, and the runs from it.\n const debug = createGenerativeUIDebugSource(core, () => {\n const latest = configRef.current ?? { ui: core.ui };\n return {\n options: envelopeOptionsFor(latest),\n agentIds: latest.agentIds,\n };\n });\n copilotkit.ɵsetGenerativeUIDebugSource(debug.source);\n const removeEnvelope = () => {\n if (envelopeId === undefined) return;\n copilotkit.removeScopedProperties(envelopeId);\n envelopeId = undefined;\n };\n /**\n * Sets the shared envelope of the run. The action entries of the agents\n * with a user event under way (see `forwardEvent`) are set again after\n * it, so they stay the last entries and win for their agents.\n */\n const setEnvelope = (agent: AbstractAgent, latest: GenerativeUIConfig) => {\n removeEnvelope();\n const run = describeGenerativeUIRun(\n core,\n agent.threadId,\n envelopeOptionsFor(latest),\n );\n envelopeId = copilotkit.addScopedProperties({\n properties: {\n [COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: run.envelope },\n },\n agentIds: latest.agentIds,\n });\n core.refreshActions();\n const isForAgent =\n !latest.agentIds || latest.agentIds.includes(agent.agentId ?? \"\");\n if (isForAgent) {\n debug.recordRun({\n ...run,\n agentId: agent.agentId,\n threadId: agent.threadId,\n startedAt: Date.now(),\n });\n }\n };\n /**\n * The tool transport reads the surface activity messages. The markdown\n * transport reads the ```a2ui fences of the assistant messages, and\n * builds the surfaces of the thread from them again on each change.\n * Both give their function calls to the one runner.\n */\n const readMessages = (\n agent: AbstractAgent,\n messages: ReadonlyMessages,\n running: boolean,\n ) => {\n const requests = activityFunctionCalls(messages);\n const { threadId } = agent;\n if (configRef.current?.transport !== \"markdown\") {\n ingestMessages(core.manager, agent, messages);\n } else if (threadId) {\n // A thread switch can happen with no run start. The named targets\n // must show the surfaces of the thread that the messages belong to.\n core.manager.setActiveThread(threadId);\n const calls = getMarkdownSurfaceSource(core).sync(\n threadId,\n agent.agentId,\n messages,\n { running },\n );\n requests.push(...markdownFunctionCalls(calls));\n }\n core.functionCalls.run(agent, requests, messages, running);\n };\n const subscription = copilotkit.subscribe({\n // Core awaits this before it reads the properties for the run, so the\n // envelope set here goes with this run. Tool-call follow-up runs do not\n // fire it. The scoped entry stays until the next run start replaces it,\n // so the follow-up runs send the same envelope.\n onAgentRunStarted: ({ agent }) => {\n core.manager.setActiveThread(agent.threadId);\n const latest = configRef.current;\n if (latest) setEnvelope(agent, latest);\n if (!watched.has(agent)) {\n watched.add(agent);\n agentSubscriptions.push(\n agent.subscribe({\n onMessagesChanged: ({ messages }) =>\n readMessages(agent, messages, agent.isRunning),\n // The last message is final now. An open fence in it is final\n // too, so its surface is no longer \"streaming\". The function\n // calls of the run get their answers now.\n onRunFinalized: () => readMessages(agent, agent.messages, false),\n onRunFailed: () => readMessages(agent, agent.messages, false),\n }),\n );\n }\n // The run starts now, but the agent is not marked as running yet.\n readMessages(agent, agent.messages, true);\n },\n });\n return () => {\n subscription.unsubscribe();\n for (const s of agentSubscriptions) s.unsubscribe();\n // Stop advertising a generative UI that is no longer mounted.\n core.dropAllActions();\n removeEnvelope();\n if (copilotkit.ɵgenerativeUIDebugSource === debug.source) {\n copilotkit.ɵsetGenerativeUIDebugSource(undefined);\n }\n };\n }, [core, copilotkit]);\n\n useGenerativeUIMarkdownContext(copilotkit, core, {\n enabled: config?.transport === \"markdown\" && config.sendContext !== false,\n agentIds: config?.agentIds,\n });\n\n return runtime;\n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AAK,mBAAoB,GAAE,aAAa;AAEnD,QAAK,gBAAgB;AACrB,mBAAgB;AAChB,OAAI,WAAW,6BAA6B,MAAM,OAChD,YAAW,4BAA4B,OAAU;;IAGpD,CAAC,MAAM,WAAW,CAAC;AAEtB,gCAA+B,YAAY,MAAM;EAC/C,SAAS,QAAQ,cAAc,cAAc,OAAO,gBAAgB;EACpE,UAAU,QAAQ;EACnB,CAAC;AAEF,QAAO"}
@@ -0,0 +1,385 @@
1
+ import { M as useShallowStableRef, g as parseGenerativeUISurfaceContent, p as catalogIdsOf } from "./chat-IWySXWXP.mjs";
2
+ import { useEffect, useMemo, useRef } from "react";
3
+ import { COPILOTKIT_FORWARDED_PROPS_KEY, DEFAULT_AGENT_ID, GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION, GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION, buildGenerativeUIMarkdownGuidelines, defaultGenerativeUIPromptSpec, generativeUIGuideFeatures, randomUUID, renderGenerativeUISchema, toA2UIActionMessage } from "@copilotkit/shared";
4
+ import { GenerativeUISurfaceManager, activityFunctionCalls, buildActionMessageText, buildGenerativeUIEnvelope, buildGenerativeUIManifest, createFunctionCallRunner, createGenerativeUIDebugSource, createGenerativeUIDispatcher, describeGenerativeUIRun, envelopeOptionsFor, getMarkdownSurfaceSource, markdownFunctionCalls, surfaceLabelResolver } from "@copilotkit/core/generative-ui";
5
+ import { GenerativeUIError } from "@copilotkit/shared/generative-ui";
6
+
7
+ //#region src/v2/generative-ui/markdown/context.ts
8
+ /**
9
+ * Registers the two context entries of the markdown transport: the compact
10
+ * component schema and the fence guideline. Both go only to `agentIds`.
11
+ *
12
+ * The schema is built again at each run start and when a
13
+ * `<GenerativeUISurface>` mounts, unmounts, or changes its description or
14
+ * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.
15
+ *
16
+ * @param copilotkit - The CopilotKit core of the provider.
17
+ * @param runtime - The generative UI runtime parts, or null without one.
18
+ * @param options - `enabled` and `agentIds`.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * useGenerativeUIMarkdownContext(copilotkit, core, {
23
+ * enabled: config?.transport === "markdown" && config.sendContext !== false,
24
+ * agentIds: config?.agentIds,
25
+ * });
26
+ * ```
27
+ */
28
+ function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
29
+ const { enabled, agentIds } = options;
30
+ const agentIdsKey = agentIds === void 0 ? "" : JSON.stringify(agentIds);
31
+ useEffect(() => {
32
+ if (!runtime || !enabled) return;
33
+ const scopedAgentIds = agentIdsKey ? JSON.parse(agentIdsKey) : void 0;
34
+ const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};
35
+ let guidelineId;
36
+ let guidelineValue;
37
+ let schemaId;
38
+ let schemaValue;
39
+ const refreshSchema = (threadId) => {
40
+ const manifest = buildGenerativeUIManifest(runtime, threadId);
41
+ const guideline = buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest));
42
+ if (guideline !== guidelineValue) {
43
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
44
+ guidelineValue = guideline;
45
+ guidelineId = copilotkit.addContext({
46
+ description: GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
47
+ value: guideline,
48
+ ...scope
49
+ });
50
+ }
51
+ const value = renderGenerativeUISchema(manifest, defaultGenerativeUIPromptSpec().schema.markdown);
52
+ if (value === schemaValue) return;
53
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
54
+ schemaValue = value;
55
+ schemaId = copilotkit.addContext({
56
+ description: GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
57
+ value,
58
+ ...scope
59
+ });
60
+ };
61
+ refreshSchema(runtime.manager.getActiveThread());
62
+ let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());
63
+ const unsubscribeManager = runtime.manager.subscribe(() => {
64
+ const nextKey = JSON.stringify(runtime.manager.getMountedTargets());
65
+ if (nextKey === targetsKey) return;
66
+ targetsKey = nextKey;
67
+ refreshSchema(runtime.manager.getActiveThread());
68
+ });
69
+ const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId) });
70
+ return () => {
71
+ subscription.unsubscribe();
72
+ unsubscribeManager();
73
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
74
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
75
+ };
76
+ }, [
77
+ copilotkit,
78
+ runtime,
79
+ enabled,
80
+ agentIdsKey
81
+ ]);
82
+ }
83
+
84
+ //#endregion
85
+ //#region src/v2/generative-ui/use-generative-ui-root.ts
86
+ const isDevelopment = () => process.env.NODE_ENV !== "production";
87
+ /**
88
+ * The malformed-content warnings already printed, by manager, so each
89
+ * distinct issue warns once while the manager lives.
90
+ */
91
+ const warnedMalformed = /* @__PURE__ */ new WeakMap();
92
+ /**
93
+ * Ingests the surface activity messages of `messages`. A message whose
94
+ * content is malformed (for example `null`) is skipped, in development with a
95
+ * warning once for each distinct issue, so it cannot throw inside the
96
+ * agent's run; the messages after it are still ingested.
97
+ */
98
+ function ingestMessages(manager, agent, messages) {
99
+ const { threadId } = agent;
100
+ if (!threadId) return;
101
+ for (const message of messages) {
102
+ if (message.role !== "activity" || message.activityType !== GENERATIVE_UI_ACTIVITY_TYPE) continue;
103
+ const parsed = parseGenerativeUISurfaceContent(message.content);
104
+ if (parsed.content) {
105
+ manager.ingest(threadId, agent.agentId, parsed.content);
106
+ continue;
107
+ }
108
+ if (!isDevelopment()) continue;
109
+ const warning = `[generativeUI] skipped an activity message of thread ${JSON.stringify(threadId)}: its content is malformed: ${parsed.issues.join("; ")}.`;
110
+ let warned = warnedMalformed.get(manager);
111
+ if (!warned) {
112
+ warned = /* @__PURE__ */ new Set();
113
+ warnedMalformed.set(manager, warned);
114
+ }
115
+ if (warned.has(warning)) continue;
116
+ warned.add(warning);
117
+ console.warn(warning);
118
+ }
119
+ }
120
+ /** Provider-side wiring: manager, dispatcher, agent subscriptions, envelope. */
121
+ function useGenerativeUIRoot(copilotkit, config) {
122
+ const configRef = useRef(config);
123
+ configRef.current = config;
124
+ const ui = config?.ui;
125
+ const transport = config?.transport ?? "tool";
126
+ const theme = useShallowStableRef(config?.theme);
127
+ const core = useMemo(() => {
128
+ if (!ui) return null;
129
+ const reportError = (info) => {
130
+ try {
131
+ configRef.current?.errorBoundary?.onError?.(info);
132
+ } catch (hostError) {
133
+ if (isDevelopment()) console.error("[generativeUI] errorBoundary.onError threw:", hostError);
134
+ }
135
+ if (isDevelopment()) console.warn(`[generativeUI] ${info.kind} error in ${info.surfaceId}${info.componentId ? `/${info.componentId}` : ""}: ${info.error?.message}`);
136
+ };
137
+ const manager = new GenerativeUISurfaceManager(ui, { onOperationRejected: ({ surfaceId, index, reason }) => reportError({
138
+ kind: "operation",
139
+ surfaceId,
140
+ error: /* @__PURE__ */ new Error(`operation ${index} rejected: ${reason}`)
141
+ }) });
142
+ const dispatcher = createGenerativeUIDispatcher({
143
+ getDeclared: () => ui.functions,
144
+ onError: ({ name, origin, error }) => {
145
+ if ("functionCallId" in origin) {
146
+ if (isDevelopment()) console.warn(`[generativeUI] function call ${origin.functionCallId} to "${name}" failed: ${error.message}`);
147
+ return;
148
+ }
149
+ reportError({
150
+ kind: "function",
151
+ ...origin,
152
+ error
153
+ });
154
+ }
155
+ });
156
+ const functionCalls = createFunctionCallRunner({
157
+ core: copilotkit,
158
+ dispatcher,
159
+ manifest: {
160
+ catalogId: ui.id,
161
+ catalogIds: catalogIdsOf(ui),
162
+ components: ui.manifestComponents
163
+ },
164
+ settle: () => copilotkit.waitForPendingFrameworkUpdates(),
165
+ warn: (message, error) => {
166
+ if (isDevelopment()) console.warn(message, error);
167
+ }
168
+ });
169
+ const forwardingAgents = /* @__PURE__ */ new Set();
170
+ /**
171
+ * The action of a user event, as an envelope entry scoped to the agent
172
+ * the user acted on, for the run that the event starts: the structured
173
+ * form of the user message. It is set before the run starts and dropped
174
+ * when the run is over, so a suggestion request or a follow-up run
175
+ * (both read the properties with no run start) does not carry the same
176
+ * action again, and another agent never gets a click meant for this one.
177
+ * The entry comes after the shared envelope, so it wins for its agent;
178
+ * `refreshActions` keeps it last when the shared envelope is set again.
179
+ */
180
+ const actions = /* @__PURE__ */ new Map();
181
+ const dropAction = (agent) => {
182
+ const entry = actions.get(agent);
183
+ if (!entry) return;
184
+ entry.subscription.unsubscribe();
185
+ copilotkit.removeScopedProperties(entry.id);
186
+ actions.delete(agent);
187
+ };
188
+ const setAction = (agent, action) => {
189
+ const previous = actions.get(agent);
190
+ previous?.subscription.unsubscribe();
191
+ if (previous) copilotkit.removeScopedProperties(previous.id);
192
+ actions.delete(agent);
193
+ const latest = configRef.current;
194
+ if (!latest) return;
195
+ const envelope = buildGenerativeUIEnvelope({
196
+ ui,
197
+ manager,
198
+ dispatcher
199
+ }, agent.threadId, {
200
+ ...envelopeOptionsFor(latest),
201
+ action
202
+ });
203
+ const id = copilotkit.addScopedProperties({
204
+ properties: { [COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: envelope } },
205
+ agentIds: agent.agentId === void 0 ? latest.agentIds : [agent.agentId]
206
+ });
207
+ const subscription = agent.subscribe({
208
+ onRunFinalized: () => dropAction(agent),
209
+ onRunFailed: () => dropAction(agent)
210
+ });
211
+ actions.set(agent, {
212
+ id,
213
+ action,
214
+ subscription
215
+ });
216
+ };
217
+ const refreshActions = () => {
218
+ for (const [agent, { action }] of [...actions]) setAction(agent, action);
219
+ };
220
+ const dropAllActions = () => {
221
+ for (const agent of [...actions.keys()]) dropAction(agent);
222
+ };
223
+ const forwardEvent = async (event, agentId) => {
224
+ const fail = (message) => {
225
+ const error = new GenerativeUIError("event_forward_failed", message);
226
+ reportError({
227
+ kind: "event",
228
+ surfaceId: event.surfaceId,
229
+ componentId: event.componentId,
230
+ error
231
+ });
232
+ return {
233
+ ok: false,
234
+ error
235
+ };
236
+ };
237
+ const agent = copilotkit.getAgent(agentId ?? DEFAULT_AGENT_ID);
238
+ if (!agent) return fail(`No agent "${agentId}" to receive "${event.name}"`);
239
+ if (agent.isRunning || forwardingAgents.has(agent)) return {
240
+ ok: false,
241
+ error: new GenerativeUIError("agent_busy", `"${event.name}" was not sent: the agent is running`)
242
+ };
243
+ forwardingAgents.add(agent);
244
+ try {
245
+ const surface = agent.threadId ? manager.getSurface(agent.threadId, event.surfaceId) : void 0;
246
+ const resolveLabel = surface ? surfaceLabelResolver(surface) : void 0;
247
+ agent.addMessage({
248
+ id: randomUUID(),
249
+ role: "user",
250
+ content: buildActionMessageText(event, resolveLabel)
251
+ });
252
+ setAction(agent, toA2UIActionMessage(event));
253
+ await copilotkit.runAgent({ agent });
254
+ return {
255
+ ok: true,
256
+ result: void 0
257
+ };
258
+ } catch (cause) {
259
+ return fail(`Forwarding "${event.name}" failed: ${cause instanceof Error ? cause.message : String(cause)}`);
260
+ } finally {
261
+ forwardingAgents.delete(agent);
262
+ dropAction(agent);
263
+ }
264
+ };
265
+ return {
266
+ manager,
267
+ dispatcher,
268
+ ui,
269
+ forwardEvent,
270
+ reportError,
271
+ functionCalls,
272
+ refreshActions,
273
+ dropAllActions
274
+ };
275
+ }, [ui, copilotkit]);
276
+ const runtime = useMemo(() => {
277
+ if (!core) return null;
278
+ const { manager, dispatcher, forwardEvent, reportError } = core;
279
+ return {
280
+ manager,
281
+ dispatcher,
282
+ ui: core.ui,
283
+ forwardEvent,
284
+ reportError,
285
+ transport,
286
+ theme,
287
+ get config() {
288
+ return configRef.current ?? { ui: core.ui };
289
+ },
290
+ get errorFallback() {
291
+ return configRef.current?.errorBoundary?.fallback;
292
+ }
293
+ };
294
+ }, [
295
+ core,
296
+ transport,
297
+ theme
298
+ ]);
299
+ useEffect(() => {
300
+ if (!core) return;
301
+ const watched = /* @__PURE__ */ new WeakSet();
302
+ const agentSubscriptions = [];
303
+ let envelopeId;
304
+ const debug = createGenerativeUIDebugSource(core, () => {
305
+ const latest = configRef.current ?? { ui: core.ui };
306
+ return {
307
+ options: envelopeOptionsFor(latest),
308
+ agentIds: latest.agentIds
309
+ };
310
+ });
311
+ copilotkit.ɵsetGenerativeUIDebugSource(debug.source);
312
+ const removeEnvelope = () => {
313
+ if (envelopeId === void 0) return;
314
+ copilotkit.removeScopedProperties(envelopeId);
315
+ envelopeId = void 0;
316
+ };
317
+ /**
318
+ * Sets the shared envelope of the run. The action entries of the agents
319
+ * with a user event under way (see `forwardEvent`) are set again after
320
+ * it, so they stay the last entries and win for their agents.
321
+ */
322
+ const setEnvelope = (agent, latest) => {
323
+ removeEnvelope();
324
+ const run = describeGenerativeUIRun(core, agent.threadId, envelopeOptionsFor(latest));
325
+ envelopeId = copilotkit.addScopedProperties({
326
+ properties: { [COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: run.envelope } },
327
+ agentIds: latest.agentIds
328
+ });
329
+ core.refreshActions();
330
+ if (!latest.agentIds || latest.agentIds.includes(agent.agentId ?? "")) debug.recordRun({
331
+ ...run,
332
+ agentId: agent.agentId,
333
+ threadId: agent.threadId,
334
+ startedAt: Date.now()
335
+ });
336
+ };
337
+ /**
338
+ * The tool transport reads the surface activity messages. The markdown
339
+ * transport reads the ```a2ui fences of the assistant messages, and
340
+ * builds the surfaces of the thread from them again on each change.
341
+ * Both give their function calls to the one runner.
342
+ */
343
+ const readMessages = (agent, messages, running) => {
344
+ const requests = activityFunctionCalls(messages);
345
+ const { threadId } = agent;
346
+ if (configRef.current?.transport !== "markdown") ingestMessages(core.manager, agent, messages);
347
+ else if (threadId) {
348
+ core.manager.setActiveThread(threadId);
349
+ const calls = getMarkdownSurfaceSource(core).sync(threadId, agent.agentId, messages, { running });
350
+ requests.push(...markdownFunctionCalls(calls));
351
+ }
352
+ core.functionCalls.run(agent, requests, messages, running);
353
+ };
354
+ const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => {
355
+ core.manager.setActiveThread(agent.threadId);
356
+ const latest = configRef.current;
357
+ if (latest) setEnvelope(agent, latest);
358
+ if (!watched.has(agent)) {
359
+ watched.add(agent);
360
+ agentSubscriptions.push(agent.subscribe({
361
+ onMessagesChanged: ({ messages }) => readMessages(agent, messages, agent.isRunning),
362
+ onRunFinalized: () => readMessages(agent, agent.messages, false),
363
+ onRunFailed: () => readMessages(agent, agent.messages, false)
364
+ }));
365
+ }
366
+ readMessages(agent, agent.messages, true);
367
+ } });
368
+ return () => {
369
+ subscription.unsubscribe();
370
+ for (const s of agentSubscriptions) s.unsubscribe();
371
+ core.dropAllActions();
372
+ removeEnvelope();
373
+ if (copilotkit.ɵgenerativeUIDebugSource === debug.source) copilotkit.ɵsetGenerativeUIDebugSource(void 0);
374
+ };
375
+ }, [core, copilotkit]);
376
+ useGenerativeUIMarkdownContext(copilotkit, core, {
377
+ enabled: config?.transport === "markdown" && config.sendContext !== false,
378
+ agentIds: config?.agentIds
379
+ });
380
+ return runtime;
381
+ }
382
+
383
+ //#endregion
384
+ export { useGenerativeUIRoot as t };
385
+ //# sourceMappingURL=use-generative-ui-root-WI9ERMpo.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-generative-ui-root-WI9ERMpo.mjs","names":[],"sources":["../src/v2/generative-ui/markdown/context.ts","../src/v2/generative-ui/use-generative-ui-root.ts"],"sourcesContent":["import { useEffect } from \"react\";\nimport {\n buildCompactGenerativeUISchema,\n buildGenerativeUIMarkdownGuidelines,\n generativeUIGuideFeatures,\n GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,\n GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,\n defaultGenerativeUIPromptSpec,\n renderGenerativeUISchema,\n} from \"@copilotkit/shared\";\nimport { buildGenerativeUIManifest } from \"@copilotkit/core/generative-ui\";\nimport type { CopilotKitCoreReact } from \"../../lib/react-core\";\nimport type { GenerativeUIRuntime } from \"../runtime-context\";\n\n/** The compact schema lives in shared, so tools outside React build the same text. */\nexport { buildCompactGenerativeUISchema };\n\n/** What the markdown context of the generative UI needs. */\nexport interface GenerativeUIMarkdownContextOptions {\n /** Register the entries. False for the tool transport or `sendContext: false`. */\n enabled: boolean;\n /** The agents that get the entries. All agents when left out. */\n agentIds: string[] | undefined;\n}\n\n/**\n * Registers the two context entries of the markdown transport: the compact\n * component schema and the fence guideline. Both go only to `agentIds`.\n *\n * The schema is built again at each run start and when a\n * `<GenerativeUISurface>` mounts, unmounts, or changes its description or\n * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.\n *\n * @param copilotkit - The CopilotKit core of the provider.\n * @param runtime - The generative UI runtime parts, or null without one.\n * @param options - `enabled` and `agentIds`.\n *\n * @example\n * ```ts\n * useGenerativeUIMarkdownContext(copilotkit, core, {\n * enabled: config?.transport === \"markdown\" && config.sendContext !== false,\n * agentIds: config?.agentIds,\n * });\n * ```\n */\nexport function useGenerativeUIMarkdownContext(\n copilotkit: CopilotKitCoreReact,\n runtime: Pick<GenerativeUIRuntime, \"ui\" | \"manager\" | \"dispatcher\"> | null,\n options: GenerativeUIMarkdownContextOptions,\n) {\n const { enabled, agentIds } = options;\n // A new array with the same ids must not register the entries again.\n const agentIdsKey = agentIds === undefined ? \"\" : JSON.stringify(agentIds);\n\n useEffect(() => {\n if (!runtime || !enabled) return;\n const scopedAgentIds: string[] | undefined = agentIdsKey\n ? JSON.parse(agentIdsKey)\n : undefined;\n const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};\n // The guideline has only the rule groups that the manifest uses, and the\n // mounted functions can change, so it is built again with the schema.\n let guidelineId: string | undefined;\n let guidelineValue: string | undefined;\n let schemaId: string | undefined;\n let schemaValue: string | undefined;\n const refreshSchema = (threadId: string | undefined) => {\n const manifest = buildGenerativeUIManifest(runtime, threadId);\n const guideline = buildGenerativeUIMarkdownGuidelines(\n generativeUIGuideFeatures(manifest),\n );\n if (guideline !== guidelineValue) {\n if (guidelineId !== undefined) copilotkit.removeContext(guidelineId);\n guidelineValue = guideline;\n guidelineId = copilotkit.addContext({\n description: GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,\n value: guideline,\n ...scope,\n });\n }\n const value = renderGenerativeUISchema(\n manifest,\n defaultGenerativeUIPromptSpec().schema.markdown,\n );\n if (value === schemaValue) return;\n if (schemaId !== undefined) copilotkit.removeContext(schemaId);\n schemaValue = value;\n schemaId = copilotkit.addContext({\n description: GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,\n value,\n ...scope,\n });\n };\n refreshSchema(runtime.manager.getActiveThread());\n\n // The manager notifies on every operation. Build the schema again only\n // when the mounted targets, their descriptions, or their component lists\n // change.\n let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());\n const unsubscribeManager = runtime.manager.subscribe(() => {\n const nextKey = JSON.stringify(runtime.manager.getMountedTargets());\n if (nextKey === targetsKey) return;\n targetsKey = nextKey;\n refreshSchema(runtime.manager.getActiveThread());\n });\n // Function handlers can mount at any time. Core reads the context after\n // this callback, so the run gets the current functions and the surfaces\n // of its thread.\n const subscription = copilotkit.subscribe({\n onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId),\n });\n\n return () => {\n subscription.unsubscribe();\n unsubscribeManager();\n if (guidelineId !== undefined) copilotkit.removeContext(guidelineId);\n if (schemaId !== undefined) copilotkit.removeContext(schemaId);\n };\n }, [copilotkit, runtime, enabled, agentIdsKey]);\n}\n","import { useEffect, useMemo, useRef } from \"react\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport {\n COPILOTKIT_FORWARDED_PROPS_KEY,\n DEFAULT_AGENT_ID,\n GENERATIVE_UI_ACTIVITY_TYPE,\n randomUUID,\n toA2UIActionMessage,\n} from \"@copilotkit/shared\";\nimport type { A2UIActionMessage } from \"@copilotkit/shared\";\nimport type { CopilotKitCoreReact } from \"../lib/react-core\";\nimport { useShallowStableRef } from \"../lib/shallow-stable-ref\";\nimport {\n buildActionMessageText,\n envelopeOptionsFor,\n surfaceLabelResolver,\n} from \"@copilotkit/core/generative-ui\";\nimport {\n createGenerativeUIDebugSource,\n describeGenerativeUIRun,\n} from \"@copilotkit/core/generative-ui\";\nimport { createGenerativeUIDispatcher } from \"@copilotkit/core/generative-ui\";\nimport { GenerativeUIError } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUIErrorInfo } from \"@copilotkit/shared/generative-ui\";\nimport { parseGenerativeUISurfaceContent } from \"./activity\";\nimport { catalogIdsOf } from \"./catalog\";\nimport { buildGenerativeUIEnvelope } from \"@copilotkit/core/generative-ui\";\nimport type {\n GenerativeUIConfig,\n GenerativeUIRuntime,\n} from \"./runtime-context\";\nimport { useGenerativeUIMarkdownContext } from \"./markdown/context\";\nimport { getMarkdownSurfaceSource } from \"@copilotkit/core/generative-ui\";\nimport {\n activityFunctionCalls,\n createFunctionCallRunner,\n markdownFunctionCalls,\n} from \"@copilotkit/core/generative-ui\";\nimport type { ReadonlyMessages } from \"@copilotkit/core/generative-ui\";\nimport { GenerativeUISurfaceManager } from \"@copilotkit/core/generative-ui\";\n\nconst isDevelopment = () => process.env.NODE_ENV !== \"production\";\n\n/**\n * The malformed-content warnings already printed, by manager, so each\n * distinct issue warns once while the manager lives.\n */\nconst warnedMalformed = new WeakMap<GenerativeUISurfaceManager, Set<string>>();\n\n/**\n * Ingests the surface activity messages of `messages`. A message whose\n * content is malformed (for example `null`) is skipped, in development with a\n * warning once for each distinct issue, so it cannot throw inside the\n * agent's run; the messages after it are still ingested.\n */\nfunction ingestMessages(\n manager: GenerativeUISurfaceManager,\n agent: AbstractAgent,\n messages: ReadonlyMessages,\n) {\n const { threadId } = agent;\n if (!threadId) return;\n for (const message of messages) {\n if (\n message.role !== \"activity\" ||\n message.activityType !== GENERATIVE_UI_ACTIVITY_TYPE\n ) {\n continue;\n }\n const parsed = parseGenerativeUISurfaceContent(message.content);\n if (parsed.content) {\n manager.ingest(threadId, agent.agentId, parsed.content);\n continue;\n }\n if (!isDevelopment()) continue;\n const warning = `[generativeUI] skipped an activity message of thread ${JSON.stringify(threadId)}: its content is malformed: ${parsed.issues.join(\"; \")}.`;\n let warned = warnedMalformed.get(manager);\n if (!warned) {\n warned = new Set();\n warnedMalformed.set(manager, warned);\n }\n if (warned.has(warning)) continue;\n warned.add(warning);\n console.warn(warning);\n }\n}\n\n/** Provider-side wiring: manager, dispatcher, agent subscriptions, envelope. */\nexport function useGenerativeUIRoot(\n copilotkit: CopilotKitCoreReact,\n config: GenerativeUIConfig | undefined,\n): GenerativeUIRuntime | null {\n const configRef = useRef(config);\n configRef.current = config;\n const ui = config?.ui;\n const transport = config?.transport ?? \"tool\";\n const theme = useShallowStableRef(config?.theme);\n\n // The parts that live as long as `ui`. The surfaces are in the manager, so\n // a new theme or transport does not remount them.\n const core = useMemo(() => {\n if (!ui) return null;\n // Never throws: it is called from rendering, ingestion and event handlers,\n // and a throwing host `onError` must not break any of them.\n const reportError = (info: GenerativeUIErrorInfo) => {\n try {\n configRef.current?.errorBoundary?.onError?.(info);\n } catch (hostError) {\n if (isDevelopment()) {\n console.error(\n \"[generativeUI] errorBoundary.onError threw:\",\n hostError,\n );\n }\n }\n if (isDevelopment()) {\n console.warn(\n `[generativeUI] ${info.kind} error in ${info.surfaceId}${info.componentId ? `/${info.componentId}` : \"\"}: ${info.error?.message}`,\n );\n }\n };\n const manager = new GenerativeUISurfaceManager(ui, {\n onOperationRejected: ({ surfaceId, index, reason }) =>\n reportError({\n kind: \"operation\",\n surfaceId,\n error: new Error(`operation ${index} rejected: ${reason}`),\n }),\n });\n const dispatcher = createGenerativeUIDispatcher({\n getDeclared: () => ui.functions,\n onError: ({ name, origin, error }) => {\n if (\"functionCallId\" in origin) {\n // The model gets this error in the answer of the call. The error\n // info of `onError` needs a surface, and this call has none.\n if (isDevelopment()) {\n console.warn(\n `[generativeUI] function call ${origin.functionCallId} to \"${name}\" failed: ${error.message}`,\n );\n }\n return;\n }\n reportError({ kind: \"function\", ...origin, error });\n },\n });\n const functionCalls = createFunctionCallRunner({\n core: copilotkit,\n dispatcher,\n manifest: {\n catalogId: ui.id,\n catalogIds: catalogIdsOf(ui),\n components: ui.manifestComponents,\n },\n // As for a frontend-tool follow-up: let React commit the state that\n // the handlers set, so that the follow-up run reads it.\n settle: () => copilotkit.waitForPendingFrameworkUpdates(),\n warn: (message, error) => {\n if (isDevelopment()) console.warn(message, error);\n },\n });\n // The agents with an event on its way to a run. Set before the run\n // starts, so a repeat click in the same tick is caught too.\n const forwardingAgents = new Set<AbstractAgent>();\n /**\n * The action of a user event, as an envelope entry scoped to the agent\n * the user acted on, for the run that the event starts: the structured\n * form of the user message. It is set before the run starts and dropped\n * when the run is over, so a suggestion request or a follow-up run\n * (both read the properties with no run start) does not carry the same\n * action again, and another agent never gets a click meant for this one.\n * The entry comes after the shared envelope, so it wins for its agent;\n * `refreshActions` keeps it last when the shared envelope is set again.\n */\n const actions = new Map<\n AbstractAgent,\n {\n id: string;\n action: A2UIActionMessage;\n /** Drops the action when the run ends, before any follow-up run. */\n subscription: { unsubscribe(): void };\n }\n >();\n const dropAction = (agent: AbstractAgent) => {\n const entry = actions.get(agent);\n if (!entry) return;\n entry.subscription.unsubscribe();\n copilotkit.removeScopedProperties(entry.id);\n actions.delete(agent);\n };\n const setAction = (agent: AbstractAgent, action: A2UIActionMessage) => {\n const previous = actions.get(agent);\n previous?.subscription.unsubscribe();\n if (previous) copilotkit.removeScopedProperties(previous.id);\n actions.delete(agent);\n const latest = configRef.current;\n if (!latest) return;\n const envelope = buildGenerativeUIEnvelope(\n { ui, manager, dispatcher },\n agent.threadId,\n { ...envelopeOptionsFor(latest), action },\n );\n const id = copilotkit.addScopedProperties({\n properties: { [COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: envelope } },\n agentIds:\n agent.agentId === undefined ? latest.agentIds : [agent.agentId],\n });\n // The run ends before `runAgent` resolves: a frontend tool makes a\n // follow-up run first, and that run must not carry the action again.\n // The agent itself says when its run is over.\n const subscription = agent.subscribe({\n onRunFinalized: () => dropAction(agent),\n onRunFailed: () => dropAction(agent),\n });\n actions.set(agent, { id, action, subscription });\n };\n const refreshActions = () => {\n for (const [agent, { action }] of [...actions]) setAction(agent, action);\n };\n const dropAllActions = () => {\n for (const agent of [...actions.keys()]) dropAction(agent);\n };\n const forwardEvent: GenerativeUIRuntime[\"forwardEvent\"] = async (\n event,\n agentId,\n ) => {\n const fail = (message: string) => {\n const error = new GenerativeUIError(\"event_forward_failed\", message);\n reportError({\n kind: \"event\",\n surfaceId: event.surfaceId,\n componentId: event.componentId,\n error,\n });\n return { ok: false as const, error };\n };\n const agent = copilotkit.getAgent(agentId ?? DEFAULT_AGENT_ID);\n if (!agent) {\n return fail(`No agent \"${agentId}\" to receive \"${event.name}\"`);\n }\n // An event is a one-click send. While the agent runs, or another event\n // is on its way, a second one is almost always a repeat: a double\n // click, or a click while the reply streams. Sending it would start a\n // second run and derail the chat, so it is dropped. The component gets\n // `agent_busy`; it is not an error of the UI, so nothing is reported.\n if (agent.isRunning || forwardingAgents.has(agent)) {\n return {\n ok: false as const,\n error: new GenerativeUIError(\n \"agent_busy\",\n `\"${event.name}\" was not sent: the agent is running`,\n ),\n };\n }\n forwardingAgents.add(agent);\n try {\n // A visible user message: the user and the model both see the event.\n const surface = agent.threadId\n ? manager.getSurface(agent.threadId, event.surfaceId)\n : undefined;\n const resolveLabel = surface\n ? surfaceLabelResolver(surface)\n : undefined;\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: buildActionMessageText(event, resolveLabel),\n });\n // Set now, not at the run start: while another agent runs, this\n // run starts with no run-start notification.\n setAction(agent, toA2UIActionMessage(event));\n await copilotkit.runAgent({ agent });\n return { ok: true, result: undefined };\n } catch (cause) {\n return fail(\n `Forwarding \"${event.name}\" failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n } finally {\n forwardingAgents.delete(agent);\n dropAction(agent);\n }\n };\n return {\n manager,\n dispatcher,\n ui,\n forwardEvent,\n reportError,\n functionCalls,\n refreshActions,\n dropAllActions,\n };\n }, [ui, copilotkit]);\n\n // A new object when the theme or the transport changes, so that the\n // components that read them render again.\n const runtime = useMemo<GenerativeUIRuntime | null>(() => {\n if (!core) return null;\n const { manager, dispatcher, forwardEvent, reportError } = core;\n return {\n manager,\n dispatcher,\n ui: core.ui,\n forwardEvent,\n reportError,\n transport,\n theme,\n get config() {\n // `core` exists only while the provider has a config. After the\n // config is removed, nothing reads this runtime again.\n return configRef.current ?? { ui: core.ui };\n },\n get errorFallback() {\n return configRef.current?.errorBoundary?.fallback;\n },\n };\n }, [core, transport, theme]);\n\n useEffect(() => {\n if (!core) return;\n const watched = new WeakSet<AbstractAgent>();\n const agentSubscriptions: Array<{ unsubscribe(): void }> = [];\n let envelopeId: string | undefined;\n // The inspector reads the catalog, the surfaces, and the runs from it.\n const debug = createGenerativeUIDebugSource(core, () => {\n const latest = configRef.current ?? { ui: core.ui };\n return {\n options: envelopeOptionsFor(latest),\n agentIds: latest.agentIds,\n };\n });\n copilotkit.ɵsetGenerativeUIDebugSource(debug.source);\n const removeEnvelope = () => {\n if (envelopeId === undefined) return;\n copilotkit.removeScopedProperties(envelopeId);\n envelopeId = undefined;\n };\n /**\n * Sets the shared envelope of the run. The action entries of the agents\n * with a user event under way (see `forwardEvent`) are set again after\n * it, so they stay the last entries and win for their agents.\n */\n const setEnvelope = (agent: AbstractAgent, latest: GenerativeUIConfig) => {\n removeEnvelope();\n const run = describeGenerativeUIRun(\n core,\n agent.threadId,\n envelopeOptionsFor(latest),\n );\n envelopeId = copilotkit.addScopedProperties({\n properties: {\n [COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: run.envelope },\n },\n agentIds: latest.agentIds,\n });\n core.refreshActions();\n const isForAgent =\n !latest.agentIds || latest.agentIds.includes(agent.agentId ?? \"\");\n if (isForAgent) {\n debug.recordRun({\n ...run,\n agentId: agent.agentId,\n threadId: agent.threadId,\n startedAt: Date.now(),\n });\n }\n };\n /**\n * The tool transport reads the surface activity messages. The markdown\n * transport reads the ```a2ui fences of the assistant messages, and\n * builds the surfaces of the thread from them again on each change.\n * Both give their function calls to the one runner.\n */\n const readMessages = (\n agent: AbstractAgent,\n messages: ReadonlyMessages,\n running: boolean,\n ) => {\n const requests = activityFunctionCalls(messages);\n const { threadId } = agent;\n if (configRef.current?.transport !== \"markdown\") {\n ingestMessages(core.manager, agent, messages);\n } else if (threadId) {\n // A thread switch can happen with no run start. The named targets\n // must show the surfaces of the thread that the messages belong to.\n core.manager.setActiveThread(threadId);\n const calls = getMarkdownSurfaceSource(core).sync(\n threadId,\n agent.agentId,\n messages,\n { running },\n );\n requests.push(...markdownFunctionCalls(calls));\n }\n core.functionCalls.run(agent, requests, messages, running);\n };\n const subscription = copilotkit.subscribe({\n // Core awaits this before it reads the properties for the run, so the\n // envelope set here goes with this run. Tool-call follow-up runs do not\n // fire it. The scoped entry stays until the next run start replaces it,\n // so the follow-up runs send the same envelope.\n onAgentRunStarted: ({ agent }) => {\n core.manager.setActiveThread(agent.threadId);\n const latest = configRef.current;\n if (latest) setEnvelope(agent, latest);\n if (!watched.has(agent)) {\n watched.add(agent);\n agentSubscriptions.push(\n agent.subscribe({\n onMessagesChanged: ({ messages }) =>\n readMessages(agent, messages, agent.isRunning),\n // The last message is final now. An open fence in it is final\n // too, so its surface is no longer \"streaming\". The function\n // calls of the run get their answers now.\n onRunFinalized: () => readMessages(agent, agent.messages, false),\n onRunFailed: () => readMessages(agent, agent.messages, false),\n }),\n );\n }\n // The run starts now, but the agent is not marked as running yet.\n readMessages(agent, agent.messages, true);\n },\n });\n return () => {\n subscription.unsubscribe();\n for (const s of agentSubscriptions) s.unsubscribe();\n // Stop advertising a generative UI that is no longer mounted.\n core.dropAllActions();\n removeEnvelope();\n if (copilotkit.ɵgenerativeUIDebugSource === debug.source) {\n copilotkit.ɵsetGenerativeUIDebugSource(undefined);\n }\n };\n }, [core, copilotkit]);\n\n useGenerativeUIMarkdownContext(copilotkit, core, {\n enabled: config?.transport === \"markdown\" && config.sendContext !== false,\n agentIds: config?.agentIds,\n });\n\n return runtime;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6C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a,OAAO,MAAM,UAAU,KAAK;KAE5C,CAAC;AACF,eAAa;AACX,gBAAa,aAAa;AAC1B,QAAK,MAAM,KAAK,mBAAoB,GAAE,aAAa;AAEnD,QAAK,gBAAgB;AACrB,mBAAgB;AAChB,OAAI,WAAW,6BAA6B,MAAM,OAChD,YAAW,4BAA4B,OAAU;;IAGpD,CAAC,MAAM,WAAW,CAAC;AAEtB,gCAA+B,YAAY,MAAM;EAC/C,SAAS,QAAQ,cAAc,cAAc,OAAO,gBAAgB;EACpE,UAAU,QAAQ;EACnB,CAAC;AAEF,QAAO"}
@@ -0,0 +1,66 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_chat = require('../../chat-BnsrQ0VS.cjs');
3
+ const require_use_generative_ui_root = require('../../use-generative-ui-root-CaTyBFNR.cjs');
4
+ const require_refs = require('../../refs-DL7ITFFD.cjs');
5
+ let _copilotkit_shared_generative_ui = require("@copilotkit/shared/generative-ui");
6
+ let _copilotkit_core_generative_ui = require("@copilotkit/core/generative-ui");
7
+
8
+ //#region src/v2/generative-ui/native.ts
9
+ /**
10
+ * Provider-side wiring: the surface manager, the agent subscriptions and the
11
+ * envelope of each run. Typed with the `CopilotKitCoreReact` of
12
+ * `/v2/context`, which is the instance a React Native provider holds.
13
+ *
14
+ * In source it is the same class that `use-generative-ui-root.ts` imports
15
+ * from `../lib/react-core`, so no cast is needed. The annotation is for the
16
+ * emitted declarations: `../context` is external to the build, so they import
17
+ * the class from `@copilotkit/react-core/v2/context`. Re-exported as is, the
18
+ * hook would be declared with a copy of the class from a bundled chunk, which
19
+ * the `/v2/context` instance is not assignable to (the class has private
20
+ * members). `scripts/assert-dist-context-types.mjs` checks this.
21
+ */
22
+ const useGenerativeUIRoot = require_use_generative_ui_root.useGenerativeUIRoot;
23
+
24
+ //#endregion
25
+ Object.defineProperty(exports, 'GenerativeUIError', {
26
+ enumerable: true,
27
+ get: function () {
28
+ return _copilotkit_shared_generative_ui.GenerativeUIError;
29
+ }
30
+ });
31
+ exports.GenerativeUIHostContext = require_chat.GenerativeUIHostContext;
32
+ exports.GenerativeUIRuntimeContext = require_chat.GenerativeUIRuntimeContext;
33
+ Object.defineProperty(exports, 'GenerativeUISurfaceContentSchema', {
34
+ enumerable: true,
35
+ get: function () {
36
+ return _copilotkit_core_generative_ui.GenerativeUISurfaceContentSchema;
37
+ }
38
+ });
39
+ exports.GenerativeUIToolCallRenderer = require_chat.GenerativeUIToolCallRenderer;
40
+ exports.SurfaceView = require_chat.SurfaceView;
41
+ exports.child = require_refs.child;
42
+ exports.childList = require_refs.childList;
43
+ exports.createGenerativeUI = require_chat.createGenerativeUI;
44
+ Object.defineProperty(exports, 'exportA2UICatalog', {
45
+ enumerable: true,
46
+ get: function () {
47
+ return _copilotkit_shared_generative_ui.exportA2UICatalog;
48
+ }
49
+ });
50
+ Object.defineProperty(exports, 'parseGenerativeUISurfaceContent', {
51
+ enumerable: true,
52
+ get: function () {
53
+ return _copilotkit_core_generative_ui.parseGenerativeUISurfaceContent;
54
+ }
55
+ });
56
+ exports.useGenerativeUIAccessibility = require_chat.useGenerativeUIAccessibility;
57
+ exports.useGenerativeUIActivitySurface = require_chat.useGenerativeUIActivitySurface;
58
+ exports.useGenerativeUIFunction = require_chat.useGenerativeUIFunction;
59
+ exports.useGenerativeUIHost = require_chat.useGenerativeUIHost;
60
+ exports.useGenerativeUIRejected = require_chat.useGenerativeUIRejected;
61
+ exports.useGenerativeUIRoot = useGenerativeUIRoot;
62
+ exports.useGenerativeUIRuntime = require_chat.useGenerativeUIRuntime;
63
+ exports.useGenerativeUIState = require_chat.useGenerativeUIState;
64
+ exports.useManagerVersion = require_chat.useManagerVersion;
65
+ exports.useRequiredGenerativeUIRuntime = require_chat.useRequiredGenerativeUIRuntime;
66
+ //# sourceMappingURL=native.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native.cjs","names":["useGenerativeUIRootImpl"],"sources":["../../../src/v2/generative-ui/native.ts"],"sourcesContent":["// The `@copilotkit/react-core/v2/generative-ui/native` entry: generative UI\n// without the DOM. It has the catalog API, the hooks and the surface\n// renderer, and leaves out what only a browser can run: the standard\n// catalog (DOM components, portals, KaTeX), the markdown surfaces\n// (streamdown) and the DOM `<GenerativeUISurface>` mount. A platform gives\n// its host elements through `GenerativeUIHostContext`. That context defaults\n// to the DOM host, which renders HTML elements, so a platform\n// without a DOM MUST provide its own host above every surface it renders.\n// Nothing checks that it did: without one, on React Native, the `<div>` of\n// the surface root fails to render, the surface fallback (a `<div>` too)\n// fails as well, and the surface renders nothing; only the reported errors\n// show it. `@copilotkit/react-native/generative-ui` is built on this entry,\n// and its `GenerativeUIProvider` provides the native host.\n//\n// It is built together with `/v2` and `/v2/generative-ui`, so the three\n// entries share one copy of each React context.\n\n// The catalog API, as in `/v2/generative-ui`.\nexport { createGenerativeUI } from \"./catalog\";\nexport type {\n CreateGenerativeUIConfig,\n GenerativeUI,\n GenerativeUIComponentDefinition,\n GenerativeUIComponentName,\n GenerativeUIComponentProps,\n GenerativeUIEventDefinition,\n GenerativeUIFunctionArgs,\n GenerativeUIFunctionDefinition,\n GenerativeUIFunctionInput,\n GenerativeUIFunctionName,\n GenerativeUISlotKind,\n GenerativeUIStateOf,\n} from \"./catalog\";\nexport { child, childList } from \"./refs\";\nexport { exportA2UICatalog } from \"@copilotkit/shared/generative-ui\";\nexport type { ExportA2UICatalogOptions } from \"@copilotkit/shared/generative-ui\";\nexport { useGenerativeUIAccessibility } from \"./accessibility\";\nexport type {\n GenerativeUIAccessibility,\n GenerativeUIAriaAttributes,\n} from \"./accessibility\";\nexport { GenerativeUIError } from \"@copilotkit/shared/generative-ui\";\nexport type {\n GenerativeUIErrorCode,\n GenerativeUIErrorInfo,\n GenerativeUIEventHandler,\n GenerativeUIInvokeResult,\n} from \"@copilotkit/shared/generative-ui\";\nexport type {\n GenerativeUIConfig,\n GenerativeUIErrorBoundaryConfig,\n GenerativeUIMarkdownConfig,\n GenerativeUITheme,\n GenerativeUIToolConfig,\n} from \"./runtime-context\";\nexport { useGenerativeUIRuntime } from \"./runtime-context\";\nexport { useGenerativeUIFunction, useGenerativeUIState } from \"./hooks\";\n\n// The plumbing that a platform package uses to build its provider and\n// surfaces.\nimport { useGenerativeUIRoot as useGenerativeUIRootImpl } from \"./use-generative-ui-root\";\nimport type { CopilotKitCoreReact } from \"../context\";\nimport type {\n GenerativeUIConfig,\n GenerativeUIRuntime,\n} from \"./runtime-context\";\n/**\n * Provider-side wiring: the surface manager, the agent subscriptions and the\n * envelope of each run. Typed with the `CopilotKitCoreReact` of\n * `/v2/context`, which is the instance a React Native provider holds.\n *\n * In source it is the same class that `use-generative-ui-root.ts` imports\n * from `../lib/react-core`, so no cast is needed. The annotation is for the\n * emitted declarations: `../context` is external to the build, so they import\n * the class from `@copilotkit/react-core/v2/context`. Re-exported as is, the\n * hook would be declared with a copy of the class from a bundled chunk, which\n * the `/v2/context` instance is not assignable to (the class has private\n * members). `scripts/assert-dist-context-types.mjs` checks this.\n */\nexport const useGenerativeUIRoot: (\n copilotkit: CopilotKitCoreReact,\n config: GenerativeUIConfig | undefined,\n) => GenerativeUIRuntime | null = useGenerativeUIRootImpl;\nexport {\n GenerativeUIRuntimeContext,\n useRequiredGenerativeUIRuntime,\n} from \"./runtime-context\";\nexport type { GenerativeUIRuntime } from \"./runtime-context\";\nexport { useManagerVersion } from \"./hooks\";\nexport { SurfaceView } from \"./SurfaceView\";\nexport { GenerativeUIToolCallRenderer } from \"./chat\";\nexport {\n GenerativeUISurfaceContentSchema,\n parseGenerativeUISurfaceContent,\n useGenerativeUIActivitySurface,\n useGenerativeUIRejected,\n} from \"./activity\";\nexport type { ParsedGenerativeUISurfaceContent } from \"./activity\";\nexport type { GenerativeUIChatSurfaceProps } from \"./chat\";\nexport { GenerativeUIHostContext, useGenerativeUIHost } from \"./host\";\nexport type {\n GenerativeUIAccessibilityWrapperProps,\n GenerativeUIHost,\n GenerativeUINodeFallbackProps,\n GenerativeUISurfaceRootProps,\n} from \"./host\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+EA,MAAa,sBAGqBA"}