@copilotkit/react-core 2.0.0-rc.42 → 2.0.0-rc.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{MarkdownRendererContext-BL8ct_3U.d.mts → MarkdownRendererContext-CytkPOAJ.d.mts} +1 -1
- package/dist/{MarkdownRendererContext-BL8ct_3U.d.mts.map → MarkdownRendererContext-CytkPOAJ.d.mts.map} +1 -1
- package/dist/MarkdownSurfaces-DlYqJkAE.mjs +135 -0
- package/dist/MarkdownSurfaces-DlYqJkAE.mjs.map +1 -0
- package/dist/MarkdownSurfaces-DytbRzj2.cjs +141 -0
- package/dist/MarkdownSurfaces-DytbRzj2.cjs.map +1 -0
- package/dist/{MarkdownSurfaces-Byz821bg.mjs → ProviderMarkdown-BZaPDROY.mjs} +6 -132
- package/dist/ProviderMarkdown-BZaPDROY.mjs.map +1 -0
- package/dist/{MarkdownSurfaces-D2Ck-cbb.cjs → ProviderMarkdown-i_i2osOH.cjs} +4 -136
- package/dist/ProviderMarkdown-i_i2osOH.cjs.map +1 -0
- package/dist/accessibility-BLK-gE0R.mjs +129 -0
- package/dist/accessibility-BLK-gE0R.mjs.map +1 -0
- package/dist/accessibility-GnodqxkH.cjs +228 -0
- package/dist/accessibility-GnodqxkH.cjs.map +1 -0
- package/dist/{chat-Bf0vVdo7.mjs → chat-B1zczXUD.mjs} +21 -145
- package/dist/chat-B1zczXUD.mjs.map +1 -0
- package/dist/{chat-DgP2N7bD.d.mts → chat-C5XWeO1M.d.mts} +1 -1
- package/dist/{chat-DgP2N7bD.d.mts.map → chat-C5XWeO1M.d.mts.map} +1 -1
- package/dist/{chat-D3fxo6Ah.cjs → chat-CkFZMo5E.cjs} +29 -234
- package/dist/chat-CkFZMo5E.cjs.map +1 -0
- package/dist/context.cjs +2 -2
- package/dist/context.cjs.map +1 -1
- package/dist/context.d.cts +2 -2
- package/dist/context.d.mts +2 -2
- package/dist/context.mjs +2 -2
- package/dist/context.mjs.map +1 -1
- package/dist/generative-ui/native.cjs +9 -8
- package/dist/generative-ui/native.cjs.map +1 -1
- package/dist/generative-ui/native.d.cts.map +1 -1
- package/dist/generative-ui/native.d.mts +2 -2
- package/dist/generative-ui/native.d.mts.map +1 -1
- package/dist/generative-ui/native.mjs +4 -3
- package/dist/generative-ui/native.mjs.map +1 -1
- package/dist/generative-ui.cjs +11 -5767
- package/dist/generative-ui.cjs.map +1 -1
- package/dist/generative-ui.d.mts +4 -4
- package/dist/generative-ui.mjs +8 -5764
- package/dist/generative-ui.mjs.map +1 -1
- package/dist/{hooks-BRYonCVu.d.mts → hooks-DqsOIh8A.d.mts} +3 -3
- package/dist/{hooks-BRYonCVu.d.mts.map → hooks-DqsOIh8A.d.mts.map} +1 -1
- package/dist/index.cjs +180 -683
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -102
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +11 -104
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +64 -409
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +6132 -797
- package/dist/index.umd.js.map +1 -1
- package/dist/{refs-BIUfn1wb.cjs → refs-B5Dn59Pn.cjs} +2 -2
- package/dist/{refs-BIUfn1wb.cjs.map → refs-B5Dn59Pn.cjs.map} +1 -1
- package/dist/{refs-CMrRm3ta.mjs → refs-BW15wX_V.mjs} +1 -1
- package/dist/{refs-CMrRm3ta.mjs.map → refs-BW15wX_V.mjs.map} +1 -1
- package/dist/standard-CqGTZUZy.cjs +5780 -0
- package/dist/standard-CqGTZUZy.cjs.map +1 -0
- package/dist/standard-s8jByRiE.mjs +5784 -0
- package/dist/standard-s8jByRiE.mjs.map +1 -0
- package/dist/{use-generative-ui-root-C12htqbK.cjs → use-generative-ui-root-CIp0ytE6.cjs} +3 -3
- package/dist/{use-generative-ui-root-C12htqbK.cjs.map → use-generative-ui-root-CIp0ytE6.cjs.map} +1 -1
- package/dist/{use-generative-ui-root-CVgsDy1f.mjs → use-generative-ui-root-oBqPa6uy.mjs} +3 -2
- package/dist/{use-generative-ui-root-CVgsDy1f.mjs.map → use-generative-ui-root-oBqPa6uy.mjs.map} +1 -1
- package/package.json +7 -10
- package/dist/MarkdownSurfaces-Byz821bg.mjs.map +0 -1
- package/dist/MarkdownSurfaces-D2Ck-cbb.cjs.map +0 -1
- package/dist/chat-Bf0vVdo7.mjs.map +0 -1
- package/dist/chat-D3fxo6Ah.cjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_accessibility = require('./accessibility-GnodqxkH.cjs');
|
|
2
2
|
let react = require("react");
|
|
3
3
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
4
4
|
let _copilotkit_core_generative_ui = require("@copilotkit/core/generative-ui");
|
|
@@ -123,7 +123,7 @@ function useGenerativeUIRoot(copilotkit, config) {
|
|
|
123
123
|
configRef.current = config;
|
|
124
124
|
const ui = config?.ui;
|
|
125
125
|
const transport = config?.transport ?? "tool";
|
|
126
|
-
const theme =
|
|
126
|
+
const theme = require_accessibility.useShallowStableRef(config?.theme);
|
|
127
127
|
const core = (0, react.useMemo)(() => {
|
|
128
128
|
if (!ui) return null;
|
|
129
129
|
const reportError = (info) => {
|
|
@@ -387,4 +387,4 @@ Object.defineProperty(exports, 'useGenerativeUIRoot', {
|
|
|
387
387
|
return useGenerativeUIRoot;
|
|
388
388
|
}
|
|
389
389
|
});
|
|
390
|
-
//# sourceMappingURL=use-generative-ui-root-
|
|
390
|
+
//# sourceMappingURL=use-generative-ui-root-CIp0ytE6.cjs.map
|
package/dist/{use-generative-ui-root-C12htqbK.cjs.map → use-generative-ui-root-CIp0ytE6.cjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generative-ui-root-C12htqbK.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/generative-ui/markdown/context.ts","../src/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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,+BACd,YACA,SACA,SACA;CACA,MAAM,EAAE,SAAS,aAAa;CAE9B,MAAM,cAAc,aAAa,SAAY,KAAK,KAAK,UAAU,SAAS;AAE1E,4BAAgB;AACd,MAAI,CAAC,WAAW,CAAC,QAAS;EAC1B,MAAM,iBAAuC,cACzC,KAAK,MAAM,YAAY,GACvB;EACJ,MAAM,QAAQ,iBAAiB,EAAE,UAAU,gBAAgB,GAAG,EAAE;EAGhE,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,MAAM,iBAAiB,aAAiC;GACtD,MAAM,yEAAqC,SAAS,SAAS;GAC7D,MAAM,0HACsB,SAAS,CACpC;AACD,OAAI,cAAc,gBAAgB;AAChC,QAAI,gBAAgB,OAAW,YAAW,cAAc,YAAY;AACpE,qBAAiB;AACjB,kBAAc,WAAW,WAAW;KAClC,aAAaA;KACb,OAAO;KACP,GAAG;KACJ,CAAC;;GAEJ,MAAM,yD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AAM,CAAC;;AAEhD,QAAK,cAAc,IAAI,OAAO,UAAU,UAAU,QAAQ;;EAE5D,MAAM,eAAe,WAAW,UAAU,EAKxC,oBAAoB,EAAE,YAAY;AAChC,QAAK,QAAQ,gBAAgB,MAAM,SAAS;GAC5C,MAAM,SAAS,UAAU;AACzB,OAAI,OAAQ,aAAY,OAAO,OAAO;AACtC,OAAI,CAAC,QAAQ,IAAI,MAAM,EAAE;AACvB,YAAQ,IAAI,MAAM;AAClB,uBAAmB,KACjB,MAAM,UAAU;KACd,oBAAoB,EAAE,eACpB,aAAa,OAAO,UAAU,MAAM,UAAU;KAIhD,sBAAsB,aAAa,OAAO,MAAM,UAAU,MAAM;KAChE,mBAAmB,aAAa,OAAO,MAAM,UAAU,MAAM;KAC9D,CAAC,CACH;;AAGH,gBAAa,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"}
|
|
1
|
+
{"version":3,"file":"use-generative-ui-root-CIp0ytE6.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/generative-ui/markdown/context.ts","../src/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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,+BACd,YACA,SACA,SACA;CACA,MAAM,EAAE,SAAS,aAAa;CAE9B,MAAM,cAAc,aAAa,SAAY,KAAK,KAAK,UAAU,SAAS;AAE1E,4BAAgB;AACd,MAAI,CAAC,WAAW,CAAC,QAAS;EAC1B,MAAM,iBAAuC,cACzC,KAAK,MAAM,YAAY,GACvB;EACJ,MAAM,QAAQ,iBAAiB,EAAE,UAAU,gBAAgB,GAAG,EAAE;EAGhE,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,MAAM,iBAAiB,aAAiC;GACtD,MAAM,yEAAqC,SAAS,SAAS;GAC7D,MAAM,0HACsB,SAAS,CACpC;AACD,OAAI,cAAc,gBAAgB;AAChC,QAAI,gBAAgB,OAAW,YAAW,cAAc,YAAY;AACpE,qBAAiB;AACjB,kBAAc,WAAW,WAAW;KAClC,aAAaA;KACb,OAAO;KACP,GAAG;KACJ,CAAC;;GAEJ,MAAM,yDACJ,iEAC+B,CAAC,OAAO,SACxC;AACD,OAAI,UAAU,YAAa;AAC3B,OAAI,aAAa,OAAW,YAAW,cAAc,SAAS;AAC9D,iBAAc;AACd,cAAW,WAAW,WAAW;IAC/B,aAAaC;IACb;IACA,GAAG;IACJ,CAAC;;AAEJ,gBAAc,QAAQ,QAAQ,iBAAiB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AAO,OAAO;AACtC,OAAI,CAAC,QAAQ,IAAI,MAAM,EAAE;AACvB,YAAQ,IAAI,MAAM;AAClB,uBAAmB,KACjB,MAAM,UAAU;KACd,oBAAoB,EAAE,eACpB,aAAa,OAAO,UAAU,MAAM,UAAU;KAIhD,sBAAsB,aAAa,OAAO,MAAM,UAAU,MAAM;KAChE,mBAAmB,aAAa,OAAO,MAAM,UAAU,MAAM;KAC9D,CAAC,CACH;;AAGH,gBAAa,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"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { g as
|
|
1
|
+
import { g as useShallowStableRef, s as catalogIdsOf } from "./accessibility-BLK-gE0R.mjs";
|
|
2
|
+
import { d as parseGenerativeUISurfaceContent } from "./chat-B1zczXUD.mjs";
|
|
2
3
|
import { useEffect, useMemo, useRef } from "react";
|
|
3
4
|
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
5
|
import { GenerativeUISurfaceManager, activityFunctionCalls, buildActionMessageText, buildGenerativeUIEnvelope, buildGenerativeUIManifest, createFunctionCallRunner, createGenerativeUIDebugSource, createGenerativeUIDispatcher, describeGenerativeUIRun, envelopeOptionsFor, getMarkdownSurfaceSource, markdownFunctionCalls, surfaceLabelResolver } from "@copilotkit/core/generative-ui";
|
|
@@ -382,4 +383,4 @@ function useGenerativeUIRoot(copilotkit, config) {
|
|
|
382
383
|
|
|
383
384
|
//#endregion
|
|
384
385
|
export { useGenerativeUIRoot as t };
|
|
385
|
-
//# sourceMappingURL=use-generative-ui-root-
|
|
386
|
+
//# sourceMappingURL=use-generative-ui-root-oBqPa6uy.mjs.map
|
package/dist/{use-generative-ui-root-CVgsDy1f.mjs.map → use-generative-ui-root-oBqPa6uy.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generative-ui-root-CVgsDy1f.mjs","names":[],"sources":["../src/generative-ui/markdown/context.ts","../src/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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,+BACd,YACA,SACA,SACA;CACA,MAAM,EAAE,SAAS,aAAa;CAE9B,MAAM,cAAc,aAAa,SAAY,KAAK,KAAK,UAAU,SAAS;AAE1E,iBAAgB;AACd,MAAI,CAAC,WAAW,CAAC,QAAS;EAC1B,MAAM,iBAAuC,cAC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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"}
|
|
1
|
+
{"version":3,"file":"use-generative-ui-root-oBqPa6uy.mjs","names":[],"sources":["../src/generative-ui/markdown/context.ts","../src/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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,+BACd,YACA,SACA,SACA;CACA,MAAM,EAAE,SAAS,aAAa;CAE9B,MAAM,cAAc,aAAa,SAAY,KAAK,KAAK,UAAU,SAAS;AAE1E,iBAAgB;AACd,MAAI,CAAC,WAAW,CAAC,QAAS;EAC1B,MAAM,iBAAuC,cACzC,KAAK,MAAM,YAAY,GACvB;EACJ,MAAM,QAAQ,iBAAiB,EAAE,UAAU,gBAAgB,GAAG,EAAE;EAGhE,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,MAAM,iBAAiB,aAAiC;GACtD,MAAM,WAAW,0BAA0B,SAAS,SAAS;GAC7D,MAAM,YAAY,oCAChB,0BAA0B,SAAS,CACpC;AACD,OAAI,cAAc,gBAAgB;AAChC,QA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rc.
|
|
3
|
+
"version": "2.0.0-rc.43",
|
|
4
4
|
"private": false,
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -77,16 +77,14 @@
|
|
|
77
77
|
"access": "public"
|
|
78
78
|
},
|
|
79
79
|
"dependencies": {
|
|
80
|
-
"@a2ui/web_core": "0.15.0",
|
|
81
80
|
"@ag-ui/client": "1.0.4",
|
|
82
81
|
"@ag-ui/core": "1.0.4",
|
|
83
|
-
"@copilotkit/
|
|
84
|
-
"@copilotkit/
|
|
85
|
-
"@copilotkit/
|
|
86
|
-
"@copilotkit/
|
|
87
|
-
"@copilotkit/
|
|
88
|
-
"@copilotkit/web-
|
|
89
|
-
"@copilotkit/web-inspector": "2.0.0-rc.42",
|
|
82
|
+
"@copilotkit/core": "2.0.0-rc.43",
|
|
83
|
+
"@copilotkit/markdown": "2.0.0-rc.43",
|
|
84
|
+
"@copilotkit/mcp-apps-renderer": "2.0.0-rc.43",
|
|
85
|
+
"@copilotkit/shared": "2.0.0-rc.43",
|
|
86
|
+
"@copilotkit/web-components": "2.0.0-rc.43",
|
|
87
|
+
"@copilotkit/web-inspector": "2.0.0-rc.43",
|
|
90
88
|
"@radix-ui/react-dropdown-menu": "^2.1.15",
|
|
91
89
|
"@radix-ui/react-popover": "^1.1.15",
|
|
92
90
|
"@radix-ui/react-tooltip": "^1.2.7",
|
|
@@ -123,7 +121,6 @@
|
|
|
123
121
|
"vitest": "^3.2.4",
|
|
124
122
|
"@playwright/test": "^1.59.1",
|
|
125
123
|
"rxjs": "7.8.1",
|
|
126
|
-
"zod-v3": "npm:zod@^3.25.76",
|
|
127
124
|
"@copilotkit/typescript-config": "1.55.0-next.8"
|
|
128
125
|
},
|
|
129
126
|
"peerDependencies": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MarkdownSurfaces-Byz821bg.mjs","names":[],"sources":["../src/components/chat/StreamingMarkdownDefaultRenderer.tsx","../src/components/icons/CopilotIcon.tsx","../src/lib/slots.tsx","../src/providers/MarkdownRendererContext.tsx","../src/generative-ui/markdown/ProviderMarkdown.tsx","../src/generative-ui/markdown/MarkdownSurfaces.tsx"],"sourcesContent":["\"use client\";\n\nimport React from \"react\";\nimport { StreamingMarkdownRenderer } from \"@copilotkit/markdown/react\";\nimport {\n CHAT_MARKDOWN_NODE_CLASS_NAMES,\n warnUnsupportedRichSyntaxOnce,\n} from \"@copilotkit/markdown\";\nimport type {\n DefaultMarkdownRendererProps,\n MarkdownRendererProps,\n} from \"../../providers/MarkdownRendererContext\";\n\n/**\n * react-core's built-in default markdown renderer — a thin adapter over\n * `@copilotkit/markdown`'s streaming renderer. Maps the pluggable\n * renderer contract (`{ content, isStreaming, className }`) onto the streaming\n * renderer for streaming-safe incremental rendering + per-token animation.\n * Still overridable via the slot/provider pluggable interface.\n */\nexport function StreamingMarkdownDefaultRenderer({\n content,\n isStreaming,\n className,\n nodeRenderers,\n caret,\n options,\n onLinkClick,\n onCitationClick,\n}: MarkdownRendererProps & DefaultMarkdownRendererProps) {\n if (!content) return null;\n // Dev-only: nudge upgraders from the bundled Streamdown default when their\n // content needs math/syntax highlighting the built-in renderer doesn't do.\n warnUnsupportedRichSyntaxOnce(content);\n return (\n <StreamingMarkdownRenderer\n className={className}\n isComplete={!isStreaming}\n caret={caret ?? !!isStreaming}\n nodeRenderers={nodeRenderers}\n nodeClassNames={CHAT_MARKDOWN_NODE_CLASS_NAMES}\n options={options}\n onLinkClick={onLinkClick}\n onCitationClick={onCitationClick}\n >\n {content}\n </StreamingMarkdownRenderer>\n );\n}\n\nStreamingMarkdownDefaultRenderer.displayName =\n \"StreamingMarkdownDefaultRenderer\";\n","import React, { createElement, forwardRef } from \"react\";\nimport { ɵcopilotIcons, ɵcopilotIconSvgAttributes } from \"@copilotkit/core\";\nimport type { CopilotIconName } from \"@copilotkit/core\";\nimport { cn } from \"../../lib/utils\";\n\n/** One SVG child element of an icon, such as a `<path>` or a `<circle>`. */\nexport interface IconSvgNode {\n readonly tag: string;\n readonly attributes: Readonly<Record<string, string | number>>;\n}\n\n/** Turns SVG attribute names such as `stroke-width` into React's `strokeWidth`. */\nfunction toReactAttributes(attributes: Readonly<Record<string, string>>) {\n return Object.fromEntries(\n Object.entries(attributes).map(([key, value]) => [\n key.replace(/-([a-z])/g, (_match, letter: string) =>\n letter.toUpperCase(),\n ),\n value,\n ]),\n );\n}\n\nconst svgDefaults = toReactAttributes(ɵcopilotIconSvgAttributes);\n\n/** True when the props give the icon an accessible name or role. */\nfunction hasAccessibleProp(props: object) {\n return Object.keys(props).some(\n (key) => key.startsWith(\"aria-\") || key === \"role\" || key === \"title\",\n );\n}\n\ntype SvgProps = React.ComponentPropsWithoutRef<\"svg\">;\n\n/** Props of `IconSvg` and `CopilotIcon` that change how the icon is drawn. */\ninterface IconDrawProps extends SvgProps {\n /** Width and height of the icon. Defaults to `24`. */\n size?: number | string;\n}\n\ninterface IconSvgProps extends IconDrawProps {\n /** The Lucide icon name in kebab case, for the `lucide-<name>` class. */\n lucideName: string;\n nodes: readonly IconSvgNode[];\n}\n\n/**\n * Internal. Draws a Lucide icon from its node data, the way Lucide's React package\n * does: Lucide's default SVG attributes, the `lucide lucide-<name>` classes,\n * and `aria-hidden=\"true\"` when no `aria-*`, `role` or `title` prop names it.\n */\nexport const IconSvg = forwardRef<SVGSVGElement, IconSvgProps>(function IconSvg(\n {\n lucideName,\n nodes,\n size = 24,\n color = \"currentColor\",\n strokeWidth = 2,\n className,\n children,\n ...props\n },\n ref,\n) {\n const isDecorative = !children && !hasAccessibleProp(props);\n return (\n <svg\n ref={ref}\n {...svgDefaults}\n width={size}\n height={size}\n stroke={color}\n strokeWidth={strokeWidth}\n className={cn(\"lucide\", `lucide-${lucideName}`, className)}\n aria-hidden={isDecorative || undefined}\n {...props}\n >\n {nodes.map((node, index) =>\n createElement(node.tag, { key: index, ...node.attributes }),\n )}\n {children}\n </svg>\n );\n});\n\n/** Props of `CopilotIcon`. Any other SVG prop goes on the `<svg>`. */\nexport interface CopilotIconProps extends IconDrawProps {\n /** The chat icon to draw, for example `\"ArrowUp\"`. */\n name: CopilotIconName;\n}\n\n/**\n * Draws one of the chat icons as an inline `<svg>`.\n *\n * The `<svg>` has the classes `lucide lucide-<icon name>`, so CSS that selects\n * them (for example `svg.lucide-arrow-up`) keeps working. The icon is hidden\n * from screen readers unless you give it an `aria-label`, `role` or `title`.\n *\n * @param props.name - The chat icon, for example `\"ArrowUp\"` or `\"X\"`.\n * @param props.size - Width and height. Defaults to `24`.\n * @param props.strokeWidth - Line width. Defaults to `2`.\n * @param props.color - Line color. Defaults to `currentColor`.\n *\n * @example\n * ```tsx\n * <CopilotIcon name=\"ArrowUp\" className=\"cpk-chat-input-send-icon\" />\n * <CopilotIcon name=\"X\" aria-label=\"Close\" />\n * ```\n */\nexport const CopilotIcon = forwardRef<SVGSVGElement, CopilotIconProps>(\n function CopilotIcon({ name, ...props }, ref) {\n const icon = ɵcopilotIcons[name];\n return (\n <IconSvg ref={ref} lucideName={icon.name} nodes={icon.nodes} {...props} />\n );\n },\n);\n","import React from \"react\";\nimport { cn } from \"./utils\";\nimport { shallowEqual, useShallowStableRef } from \"./shallow-stable-ref\";\n\n// Reference-stability helpers moved to ./shallow-stable-ref (a leaf module) so\n// the lean @copilotkit/react-core/headless entry can reach them without\n// pulling in this module (issue #4893). Re-exported here to preserve this\n// module's public surface for existing importers (e.g. CopilotChat).\nexport { shallowEqual, useShallowStableRef };\n\n/** Existing union (unchanged) */\nexport type SlotValue<C extends React.ComponentType<any>> =\n | C\n | string\n | Partial<React.ComponentProps<C>>;\n\n/** Utility: concrete React elements for every slot */\ntype SlotElements<S> = { [K in keyof S]: React.ReactElement };\n\nexport type WithSlots<\n S extends Record<string, React.ComponentType<any>>,\n Rest = {},\n> = {\n /** Per‑slot overrides */\n [K in keyof S]?: SlotValue<S[K]>;\n} & {\n children?: (props: SlotElements<S> & Rest) => React.ReactNode;\n} & Omit<Rest, \"children\">;\n\n/**\n * Check if a value is a React component type (function, class, forwardRef, memo, etc.)\n */\nexport function isReactComponentType(\n value: unknown,\n): value is React.ComponentType<any> {\n if (typeof value === \"function\") {\n return true;\n }\n // forwardRef, memo, lazy have $$typeof but are not valid elements\n if (\n value &&\n typeof value === \"object\" &&\n \"$$typeof\" in value &&\n !React.isValidElement(value)\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * Internal function to render a slot value as a React element (non-memoized).\n */\nfunction renderSlotElement(\n slot: SlotValue<React.ComponentType<any>> | undefined,\n DefaultComponent: React.ComponentType<any>,\n props: Record<string, unknown>,\n): React.ReactElement {\n if (typeof slot === \"string\") {\n // When slot is a string, treat it as a className and merge with existing className\n const existingClassName = props.className as string | undefined;\n return React.createElement(DefaultComponent, {\n ...props,\n className: cn(existingClassName, slot),\n });\n }\n\n // Check if slot is a React component type (function, forwardRef, memo, etc.)\n if (isReactComponentType(slot)) {\n return React.createElement(slot, props);\n }\n\n // If slot is a plain object (not a React element), treat it as props override\n if (slot && typeof slot === \"object\" && !React.isValidElement(slot)) {\n return React.createElement(DefaultComponent, {\n ...props,\n ...slot,\n });\n }\n\n return React.createElement(DefaultComponent, props);\n}\n\n/**\n * Internal memoized wrapper component for renderSlot.\n * Uses forwardRef to support ref forwarding.\n */\nconst MemoizedSlotWrapper = React.memo(\n React.forwardRef<unknown, any>(function MemoizedSlotWrapper(props, ref) {\n const { $slot, $component, ...rest } = props;\n const propsWithRef: Record<string, unknown> =\n ref !== null ? { ...rest, ref } : rest;\n return renderSlotElement($slot, $component, propsWithRef);\n }),\n (prev: any, next: any) => {\n // Compare slot and component references\n if (prev.$slot !== next.$slot) return false;\n if (prev.$component !== next.$component) return false;\n\n // Shallow compare remaining props (ref is handled separately by React)\n const { $slot: _ps, $component: _pc, ...prevRest } = prev;\n const { $slot: _ns, $component: _nc, ...nextRest } = next;\n return shallowEqual(\n prevRest as Record<string, unknown>,\n nextRest as Record<string, unknown>,\n );\n },\n);\n\n/**\n * Renders a slot value as a memoized React element.\n * Automatically prevents unnecessary re-renders using shallow prop comparison.\n * Supports ref forwarding.\n *\n * @example\n * renderSlot(customInput, CopilotChatInput, { onSubmit: handleSubmit })\n */\nexport function renderSlot<\n C extends React.ComponentType<any>,\n P = React.ComponentProps<C>,\n>(\n slot: SlotValue<C> | undefined,\n DefaultComponent: C,\n props: P,\n): React.ReactElement {\n return React.createElement(MemoizedSlotWrapper, {\n ...props,\n $slot: slot,\n $component: DefaultComponent,\n } as any);\n}\n","\"use client\";\n\nimport React, { createContext, useContext } from \"react\";\nimport type { StreamingMarkdownRendererProps } from \"@copilotkit/markdown/react\";\n\n/** Props every markdown renderer (built-in or plugged-in) receives. */\nexport interface MarkdownRendererProps {\n /** Raw, possibly-partial (streaming) markdown string. */\n content: string;\n /** Hint that the message is still streaming, for cursor/affordance use. */\n isStreaming?: boolean;\n className?: string;\n}\n\n/**\n * Config for the built-in default renderer. Pass this (instead of a component)\n * as `markdownRenderer` to configure the built-in renderer without writing a\n * wrapper — e.g. `markdownRenderer={{ nodeRenderers: { codeBlock: Shiki } }}`.\n */\nexport type DefaultMarkdownRendererProps = Pick<\n StreamingMarkdownRendererProps,\n | \"nodeRenderers\"\n | \"caret\"\n | \"options\"\n | \"className\"\n | \"onLinkClick\"\n | \"onCitationClick\"\n>;\n\n/** A markdown renderer: a component, OR config for the built-in default. */\nexport type MarkdownRenderer =\n | React.ComponentType<MarkdownRendererProps>\n | DefaultMarkdownRendererProps;\n\nconst MarkdownRendererContext = createContext<MarkdownRenderer | undefined>(\n undefined,\n);\n\nexport const MarkdownRendererProvider: React.FC<{\n renderer?: MarkdownRenderer;\n children: React.ReactNode;\n}> = ({ renderer, children }) => (\n <MarkdownRendererContext.Provider value={renderer}>\n {children}\n </MarkdownRendererContext.Provider>\n);\n\n/**\n * The markdown renderer set at the provider level, or `undefined` when none was\n * supplied. Message components fall back to the built-in\n * `StreamingMarkdownDefaultRenderer` (via `CopilotChatAssistantMessage.MarkdownRenderer`)\n * when this is `undefined`.\n */\nexport function useMarkdownRenderer(): MarkdownRenderer | undefined {\n return useContext(MarkdownRendererContext);\n}\n","\"use client\";\n\nimport React from \"react\";\nimport { StreamingMarkdownDefaultRenderer } from \"../../components/chat/StreamingMarkdownDefaultRenderer\";\nimport { isReactComponentType } from \"../../lib/slots\";\nimport { useMarkdownRenderer } from \"../../providers/MarkdownRendererContext\";\nimport type {\n DefaultMarkdownRendererProps,\n MarkdownRendererProps,\n} from \"../../providers/MarkdownRendererContext\";\n\n/**\n * Markdown prose inside generative UI, rendered like the chat text around\n * it: the renderer set on the provider when there is one, else the built-in\n * streaming renderer. Config passed here wins over provider config.\n */\nexport function ProviderMarkdown({\n content,\n isStreaming,\n className,\n ...config\n}: MarkdownRendererProps & DefaultMarkdownRendererProps) {\n const renderer = useMarkdownRenderer();\n if (renderer && isReactComponentType(renderer)) {\n const Renderer = renderer;\n return (\n <Renderer\n content={content}\n isStreaming={isStreaming}\n className={className}\n />\n );\n }\n return (\n <StreamingMarkdownDefaultRenderer\n {...(renderer as DefaultMarkdownRendererProps | undefined)}\n {...config}\n content={content}\n isStreaming={isStreaming}\n className={className}\n />\n );\n}\n","import React, { useContext, useInsertionEffect, useMemo } from \"react\";\nimport type { ComponentType } from \"react\";\nimport { splitA2UIMarkdown } from \"@copilotkit/core\";\nimport { GENERATIVE_UI_ROOT_ID } from \"@copilotkit/shared\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { GenerativeUIChatSlotContext } from \"../chat\";\nimport type { GenerativeUIChatSurfaceProps } from \"../chat\";\nimport { useManagerVersion } from \"../hooks\";\nimport { useRequiredGenerativeUIRuntime } from \"../runtime-context\";\nimport type { GenerativeUIRuntime } from \"../runtime-context\";\nimport { SurfaceView } from \"../SurfaceView\";\nimport type { DefaultMarkdownRendererProps } from \"../../providers/MarkdownRendererContext\";\nimport { ProviderMarkdown } from \"./ProviderMarkdown\";\nimport { getMarkdownSurfaceSource } from \"@copilotkit/core/generative-ui\";\nimport type { MarkdownFenceBlock } from \"@copilotkit/core/generative-ui\";\n\n/** Config for the built-in markdown renderer, plus `className`. */\ntype MarkdownProps = DefaultMarkdownRendererProps;\n\nconst FADE_STYLE_ID = \"a2ui-markdown-fade\";\n/**\n * Components fade in as they stream: each element that appears under a\n * markdown surface runs the keyframes once on mount. React keeps the keys\n * stable per component id, so an element that is already there never\n * animates again. SVG internals are left out: a chart library re-creates\n * its nodes on each render, and a fade on each of them would read as the\n * chart flashing whenever a sibling arrives. The fade runs under reduced\n * motion too, because it moves nothing.\n */\nconst FADE_CSS = [\n // Opacity only, so it also runs when the user asks for reduced motion:\n // that setting is about movement, and a short fade is not movement.\n // The keyframes give only the start, so each element fades to its own\n // opacity (a disabled control to its dimmed one), and no fill holds the\n // end: a finished fade must not pin opacity, or an element that hides\n // itself with opacity (the map's zoom hint) stays visible forever.\n \"@keyframes a2ui-fade-in{from{opacity:0}}\",\n \"[data-a2ui-markdown-surface] .a2ui-surface *:not(svg):not(svg *){animation:a2ui-fade-in .35s ease-out backwards}\",\n].join(\"\\n\");\n\n// There is no document on the server, so nothing is added there.\nconst noEffect: typeof useInsertionEffect = () => {};\nconst useInjectEffect =\n typeof document === \"undefined\" ? noEffect : useInsertionEffect;\n\nfunction useFadeStyles() {\n useInjectEffect(() => {\n if (document.getElementById(FADE_STYLE_ID)) return;\n const style = document.createElement(\"style\");\n style.id = FADE_STYLE_ID;\n style.textContent = FADE_CSS;\n document.head.appendChild(style);\n }, []);\n}\n\n/**\n * The default wrapper of a chat surface in the markdown transport. It draws\n * no box: a surface sits in the flow of the reply like a paragraph, and a\n * Card draws its own box when it is interactive. Nothing shows while the\n * surface streams. A rejected operation gets one line.\n */\nexport function DefaultMarkdownChatSurface({\n surfaceId,\n error,\n children,\n}: GenerativeUIChatSurfaceProps) {\n useFadeStyles();\n return (\n <div\n data-generative-ui-chat-surface={surfaceId}\n data-a2ui-markdown-surface={surfaceId}\n className=\"cpk-markdown-chat-surface\"\n >\n {children}\n {error && (\n <div role=\"alert\" className=\"cpk-markdown-chat-surface-error\">\n Part of this UI couldn't be shown.\n </div>\n )}\n </div>\n );\n}\n\nexport type MarkdownSurfacesProps = MarkdownProps & {\n /** The text of the assistant message, complete or still streaming. */\n content: string;\n /** The id of the message. The fences of the message are found by it. */\n messageId: string;\n /** Whether the message is still streaming. Only its last prose shows the caret. */\n isStreaming?: boolean;\n};\n\n/**\n * One chat surface in the chat wrapper. Nothing renders until the surface\n * has its root component, so a half-streamed fence shows no empty card.\n */\nfunction ChatSurface({\n runtime,\n threadId,\n surfaceId,\n Wrapper,\n}: {\n runtime: GenerativeUIRuntime;\n threadId: string;\n surfaceId: string;\n Wrapper: ComponentType<GenerativeUIChatSurfaceProps>;\n}) {\n // A surface whose createSurface was rejected shows only the error.\n const surface =\n runtime.manager.getSurface(threadId, surfaceId) ??\n runtime.manager.getFailedSurface(threadId, surfaceId);\n const root = surface?.model.componentsModel.get(GENERATIVE_UI_ROOT_ID);\n if (!surface || (!root && !surface.failed)) return null;\n const rejected = [...surface.serverRejected, ...surface.clientRejected];\n const error = rejected.length\n ? new Error(`${rejected.length} UI update(s) could not be shown`, {\n cause: rejected,\n })\n : undefined;\n return (\n <Wrapper\n surfaceId={surfaceId}\n isStreaming={surface.status === \"streaming\"}\n error={error}\n rejected={rejected}\n >\n {surface.failed ? null : <SurfaceView surface={surface} />}\n </Wrapper>\n );\n}\n\n/** The blocks of one fence: lifted prose and chat surfaces, in order. */\nfunction FenceBlocks({\n blocks,\n runtime,\n threadId,\n isStreaming,\n markdownProps,\n}: {\n blocks: MarkdownFenceBlock[];\n runtime: GenerativeUIRuntime;\n threadId: string;\n isStreaming: boolean;\n markdownProps: MarkdownProps;\n}) {\n const Wrapper =\n useContext(GenerativeUIChatSlotContext) ?? DefaultMarkdownChatSurface;\n let surfaceCount = 0;\n return (\n <>\n {blocks.map((block, index) => {\n // Keys follow the surfaces, so a surface keeps its element when\n // prose splits off around it during streaming.\n if (block.kind === \"markdown\") {\n return (\n <ProviderMarkdown\n key={`md-${surfaceCount}`}\n {...markdownProps}\n content={block.markdown}\n isStreaming={isStreaming && index === blocks.length - 1}\n />\n );\n }\n surfaceCount++;\n return (\n <ChatSurface\n key={block.surfaceId}\n runtime={runtime}\n threadId={threadId}\n surfaceId={block.surfaceId}\n Wrapper={Wrapper}\n />\n );\n })}\n </>\n );\n}\n\n/**\n * Experimental. Renders an assistant message of the markdown transport.\n * Prose renders as markdown. In place of each ```a2ui fence:\n *\n * - the fence that created a chat surface renders that surface (and the\n * prose lifted out of it) in the chat wrapper;\n * - every other fence renders nothing: a fence that updates the surface of\n * an earlier fence, or a fence for a named target, which\n * `<GenerativeUISurface id>` renders.\n *\n * Use it inside `<CopilotKitProvider generativeUI={{ ui, transport: \"markdown\" }}>`.\n * `CopilotChatAssistantMessage` uses it there on its own.\n *\n * @example\n * ```tsx\n * <MarkdownSurfaces content={message.content} messageId={message.id} />\n * ```\n */\nexport function MarkdownSurfaces({\n content,\n messageId,\n isStreaming = false,\n ...markdownProps\n}: MarkdownSurfacesProps) {\n const runtime = useRequiredGenerativeUIRuntime();\n const chatThreadId = useCopilotChatConfiguration()?.threadId;\n useManagerVersion(runtime);\n const segments = useMemo(() => splitA2UIMarkdown(content), [content]);\n const threadId = chatThreadId ?? runtime.manager.getActiveThread();\n const source = getMarkdownSurfaceSource(runtime);\n\n return (\n <>\n {segments.map((segment, index) => {\n const isLast = index === segments.length - 1;\n if (segment.type === \"markdown\") {\n return (\n <ProviderMarkdown\n key={`md-${index}`}\n {...markdownProps}\n content={segment.text}\n isStreaming={isStreaming && isLast}\n />\n );\n }\n const blocks = threadId\n ? source.getFenceBlocks(threadId, messageId, segment.index)\n : undefined;\n if (!threadId || !blocks) return null;\n return (\n <FenceBlocks\n key={`a2ui-${segment.index}`}\n blocks={blocks}\n runtime={runtime}\n threadId={threadId}\n isStreaming={isStreaming && isLast}\n markdownProps={markdownProps}\n />\n );\n })}\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,SA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QAAQ,QAMrB;GAEJ,GACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MarkdownSurfaces-D2Ck-cbb.cjs","names":["StreamingMarkdownRenderer","CHAT_MARKDOWN_NODE_CLASS_NAMES","ɵcopilotIconSvgAttributes","ɵcopilotIcons","React","shallowEqual","useInsertionEffect","GENERATIVE_UI_ROOT_ID","SurfaceView","GenerativeUIChatSlotContext","useRequiredGenerativeUIRuntime","useCopilotChatConfiguration"],"sources":["../src/components/chat/StreamingMarkdownDefaultRenderer.tsx","../src/components/icons/CopilotIcon.tsx","../src/lib/slots.tsx","../src/providers/MarkdownRendererContext.tsx","../src/generative-ui/markdown/ProviderMarkdown.tsx","../src/generative-ui/markdown/MarkdownSurfaces.tsx"],"sourcesContent":["\"use client\";\n\nimport React from \"react\";\nimport { StreamingMarkdownRenderer } from \"@copilotkit/markdown/react\";\nimport {\n CHAT_MARKDOWN_NODE_CLASS_NAMES,\n warnUnsupportedRichSyntaxOnce,\n} from \"@copilotkit/markdown\";\nimport type {\n DefaultMarkdownRendererProps,\n MarkdownRendererProps,\n} from \"../../providers/MarkdownRendererContext\";\n\n/**\n * react-core's built-in default markdown renderer — a thin adapter over\n * `@copilotkit/markdown`'s streaming renderer. Maps the pluggable\n * renderer contract (`{ content, isStreaming, className }`) onto the streaming\n * renderer for streaming-safe incremental rendering + per-token animation.\n * Still overridable via the slot/provider pluggable interface.\n */\nexport function StreamingMarkdownDefaultRenderer({\n content,\n isStreaming,\n className,\n nodeRenderers,\n caret,\n options,\n onLinkClick,\n onCitationClick,\n}: MarkdownRendererProps & DefaultMarkdownRendererProps) {\n if (!content) return null;\n // Dev-only: nudge upgraders from the bundled Streamdown default when their\n // content needs math/syntax highlighting the built-in renderer doesn't do.\n warnUnsupportedRichSyntaxOnce(content);\n return (\n <StreamingMarkdownRenderer\n className={className}\n isComplete={!isStreaming}\n caret={caret ?? !!isStreaming}\n nodeRenderers={nodeRenderers}\n nodeClassNames={CHAT_MARKDOWN_NODE_CLASS_NAMES}\n options={options}\n onLinkClick={onLinkClick}\n onCitationClick={onCitationClick}\n >\n {content}\n </StreamingMarkdownRenderer>\n );\n}\n\nStreamingMarkdownDefaultRenderer.displayName =\n \"StreamingMarkdownDefaultRenderer\";\n","import React, { createElement, forwardRef } from \"react\";\nimport { ɵcopilotIcons, ɵcopilotIconSvgAttributes } from \"@copilotkit/core\";\nimport type { CopilotIconName } from \"@copilotkit/core\";\nimport { cn } from \"../../lib/utils\";\n\n/** One SVG child element of an icon, such as a `<path>` or a `<circle>`. */\nexport interface IconSvgNode {\n readonly tag: string;\n readonly attributes: Readonly<Record<string, string | number>>;\n}\n\n/** Turns SVG attribute names such as `stroke-width` into React's `strokeWidth`. */\nfunction toReactAttributes(attributes: Readonly<Record<string, string>>) {\n return Object.fromEntries(\n Object.entries(attributes).map(([key, value]) => [\n key.replace(/-([a-z])/g, (_match, letter: string) =>\n letter.toUpperCase(),\n ),\n value,\n ]),\n );\n}\n\nconst svgDefaults = toReactAttributes(ɵcopilotIconSvgAttributes);\n\n/** True when the props give the icon an accessible name or role. */\nfunction hasAccessibleProp(props: object) {\n return Object.keys(props).some(\n (key) => key.startsWith(\"aria-\") || key === \"role\" || key === \"title\",\n );\n}\n\ntype SvgProps = React.ComponentPropsWithoutRef<\"svg\">;\n\n/** Props of `IconSvg` and `CopilotIcon` that change how the icon is drawn. */\ninterface IconDrawProps extends SvgProps {\n /** Width and height of the icon. Defaults to `24`. */\n size?: number | string;\n}\n\ninterface IconSvgProps extends IconDrawProps {\n /** The Lucide icon name in kebab case, for the `lucide-<name>` class. */\n lucideName: string;\n nodes: readonly IconSvgNode[];\n}\n\n/**\n * Internal. Draws a Lucide icon from its node data, the way Lucide's React package\n * does: Lucide's default SVG attributes, the `lucide lucide-<name>` classes,\n * and `aria-hidden=\"true\"` when no `aria-*`, `role` or `title` prop names it.\n */\nexport const IconSvg = forwardRef<SVGSVGElement, IconSvgProps>(function IconSvg(\n {\n lucideName,\n nodes,\n size = 24,\n color = \"currentColor\",\n strokeWidth = 2,\n className,\n children,\n ...props\n },\n ref,\n) {\n const isDecorative = !children && !hasAccessibleProp(props);\n return (\n <svg\n ref={ref}\n {...svgDefaults}\n width={size}\n height={size}\n stroke={color}\n strokeWidth={strokeWidth}\n className={cn(\"lucide\", `lucide-${lucideName}`, className)}\n aria-hidden={isDecorative || undefined}\n {...props}\n >\n {nodes.map((node, index) =>\n createElement(node.tag, { key: index, ...node.attributes }),\n )}\n {children}\n </svg>\n );\n});\n\n/** Props of `CopilotIcon`. Any other SVG prop goes on the `<svg>`. */\nexport interface CopilotIconProps extends IconDrawProps {\n /** The chat icon to draw, for example `\"ArrowUp\"`. */\n name: CopilotIconName;\n}\n\n/**\n * Draws one of the chat icons as an inline `<svg>`.\n *\n * The `<svg>` has the classes `lucide lucide-<icon name>`, so CSS that selects\n * them (for example `svg.lucide-arrow-up`) keeps working. The icon is hidden\n * from screen readers unless you give it an `aria-label`, `role` or `title`.\n *\n * @param props.name - The chat icon, for example `\"ArrowUp\"` or `\"X\"`.\n * @param props.size - Width and height. Defaults to `24`.\n * @param props.strokeWidth - Line width. Defaults to `2`.\n * @param props.color - Line color. Defaults to `currentColor`.\n *\n * @example\n * ```tsx\n * <CopilotIcon name=\"ArrowUp\" className=\"cpk-chat-input-send-icon\" />\n * <CopilotIcon name=\"X\" aria-label=\"Close\" />\n * ```\n */\nexport const CopilotIcon = forwardRef<SVGSVGElement, CopilotIconProps>(\n function CopilotIcon({ name, ...props }, ref) {\n const icon = ɵcopilotIcons[name];\n return (\n <IconSvg ref={ref} lucideName={icon.name} nodes={icon.nodes} {...props} />\n );\n },\n);\n","import React from \"react\";\nimport { cn } from \"./utils\";\nimport { shallowEqual, useShallowStableRef } from \"./shallow-stable-ref\";\n\n// Reference-stability helpers moved to ./shallow-stable-ref (a leaf module) so\n// the lean @copilotkit/react-core/headless entry can reach them without\n// pulling in this module (issue #4893). Re-exported here to preserve this\n// module's public surface for existing importers (e.g. CopilotChat).\nexport { shallowEqual, useShallowStableRef };\n\n/** Existing union (unchanged) */\nexport type SlotValue<C extends React.ComponentType<any>> =\n | C\n | string\n | Partial<React.ComponentProps<C>>;\n\n/** Utility: concrete React elements for every slot */\ntype SlotElements<S> = { [K in keyof S]: React.ReactElement };\n\nexport type WithSlots<\n S extends Record<string, React.ComponentType<any>>,\n Rest = {},\n> = {\n /** Per‑slot overrides */\n [K in keyof S]?: SlotValue<S[K]>;\n} & {\n children?: (props: SlotElements<S> & Rest) => React.ReactNode;\n} & Omit<Rest, \"children\">;\n\n/**\n * Check if a value is a React component type (function, class, forwardRef, memo, etc.)\n */\nexport function isReactComponentType(\n value: unknown,\n): value is React.ComponentType<any> {\n if (typeof value === \"function\") {\n return true;\n }\n // forwardRef, memo, lazy have $$typeof but are not valid elements\n if (\n value &&\n typeof value === \"object\" &&\n \"$$typeof\" in value &&\n !React.isValidElement(value)\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * Internal function to render a slot value as a React element (non-memoized).\n */\nfunction renderSlotElement(\n slot: SlotValue<React.ComponentType<any>> | undefined,\n DefaultComponent: React.ComponentType<any>,\n props: Record<string, unknown>,\n): React.ReactElement {\n if (typeof slot === \"string\") {\n // When slot is a string, treat it as a className and merge with existing className\n const existingClassName = props.className as string | undefined;\n return React.createElement(DefaultComponent, {\n ...props,\n className: cn(existingClassName, slot),\n });\n }\n\n // Check if slot is a React component type (function, forwardRef, memo, etc.)\n if (isReactComponentType(slot)) {\n return React.createElement(slot, props);\n }\n\n // If slot is a plain object (not a React element), treat it as props override\n if (slot && typeof slot === \"object\" && !React.isValidElement(slot)) {\n return React.createElement(DefaultComponent, {\n ...props,\n ...slot,\n });\n }\n\n return React.createElement(DefaultComponent, props);\n}\n\n/**\n * Internal memoized wrapper component for renderSlot.\n * Uses forwardRef to support ref forwarding.\n */\nconst MemoizedSlotWrapper = React.memo(\n React.forwardRef<unknown, any>(function MemoizedSlotWrapper(props, ref) {\n const { $slot, $component, ...rest } = props;\n const propsWithRef: Record<string, unknown> =\n ref !== null ? { ...rest, ref } : rest;\n return renderSlotElement($slot, $component, propsWithRef);\n }),\n (prev: any, next: any) => {\n // Compare slot and component references\n if (prev.$slot !== next.$slot) return false;\n if (prev.$component !== next.$component) return false;\n\n // Shallow compare remaining props (ref is handled separately by React)\n const { $slot: _ps, $component: _pc, ...prevRest } = prev;\n const { $slot: _ns, $component: _nc, ...nextRest } = next;\n return shallowEqual(\n prevRest as Record<string, unknown>,\n nextRest as Record<string, unknown>,\n );\n },\n);\n\n/**\n * Renders a slot value as a memoized React element.\n * Automatically prevents unnecessary re-renders using shallow prop comparison.\n * Supports ref forwarding.\n *\n * @example\n * renderSlot(customInput, CopilotChatInput, { onSubmit: handleSubmit })\n */\nexport function renderSlot<\n C extends React.ComponentType<any>,\n P = React.ComponentProps<C>,\n>(\n slot: SlotValue<C> | undefined,\n DefaultComponent: C,\n props: P,\n): React.ReactElement {\n return React.createElement(MemoizedSlotWrapper, {\n ...props,\n $slot: slot,\n $component: DefaultComponent,\n } as any);\n}\n","\"use client\";\n\nimport React, { createContext, useContext } from \"react\";\nimport type { StreamingMarkdownRendererProps } from \"@copilotkit/markdown/react\";\n\n/** Props every markdown renderer (built-in or plugged-in) receives. */\nexport interface MarkdownRendererProps {\n /** Raw, possibly-partial (streaming) markdown string. */\n content: string;\n /** Hint that the message is still streaming, for cursor/affordance use. */\n isStreaming?: boolean;\n className?: string;\n}\n\n/**\n * Config for the built-in default renderer. Pass this (instead of a component)\n * as `markdownRenderer` to configure the built-in renderer without writing a\n * wrapper — e.g. `markdownRenderer={{ nodeRenderers: { codeBlock: Shiki } }}`.\n */\nexport type DefaultMarkdownRendererProps = Pick<\n StreamingMarkdownRendererProps,\n | \"nodeRenderers\"\n | \"caret\"\n | \"options\"\n | \"className\"\n | \"onLinkClick\"\n | \"onCitationClick\"\n>;\n\n/** A markdown renderer: a component, OR config for the built-in default. */\nexport type MarkdownRenderer =\n | React.ComponentType<MarkdownRendererProps>\n | DefaultMarkdownRendererProps;\n\nconst MarkdownRendererContext = createContext<MarkdownRenderer | undefined>(\n undefined,\n);\n\nexport const MarkdownRendererProvider: React.FC<{\n renderer?: MarkdownRenderer;\n children: React.ReactNode;\n}> = ({ renderer, children }) => (\n <MarkdownRendererContext.Provider value={renderer}>\n {children}\n </MarkdownRendererContext.Provider>\n);\n\n/**\n * The markdown renderer set at the provider level, or `undefined` when none was\n * supplied. Message components fall back to the built-in\n * `StreamingMarkdownDefaultRenderer` (via `CopilotChatAssistantMessage.MarkdownRenderer`)\n * when this is `undefined`.\n */\nexport function useMarkdownRenderer(): MarkdownRenderer | undefined {\n return useContext(MarkdownRendererContext);\n}\n","\"use client\";\n\nimport React from \"react\";\nimport { StreamingMarkdownDefaultRenderer } from \"../../components/chat/StreamingMarkdownDefaultRenderer\";\nimport { isReactComponentType } from \"../../lib/slots\";\nimport { useMarkdownRenderer } from \"../../providers/MarkdownRendererContext\";\nimport type {\n DefaultMarkdownRendererProps,\n MarkdownRendererProps,\n} from \"../../providers/MarkdownRendererContext\";\n\n/**\n * Markdown prose inside generative UI, rendered like the chat text around\n * it: the renderer set on the provider when there is one, else the built-in\n * streaming renderer. Config passed here wins over provider config.\n */\nexport function ProviderMarkdown({\n content,\n isStreaming,\n className,\n ...config\n}: MarkdownRendererProps & DefaultMarkdownRendererProps) {\n const renderer = useMarkdownRenderer();\n if (renderer && isReactComponentType(renderer)) {\n const Renderer = renderer;\n return (\n <Renderer\n content={content}\n isStreaming={isStreaming}\n className={className}\n />\n );\n }\n return (\n <StreamingMarkdownDefaultRenderer\n {...(renderer as DefaultMarkdownRendererProps | undefined)}\n {...config}\n content={content}\n isStreaming={isStreaming}\n className={className}\n />\n );\n}\n","import React, { useContext, useInsertionEffect, useMemo } from \"react\";\nimport type { ComponentType } from \"react\";\nimport { splitA2UIMarkdown } from \"@copilotkit/core\";\nimport { GENERATIVE_UI_ROOT_ID } from \"@copilotkit/shared\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { GenerativeUIChatSlotContext } from \"../chat\";\nimport type { GenerativeUIChatSurfaceProps } from \"../chat\";\nimport { useManagerVersion } from \"../hooks\";\nimport { useRequiredGenerativeUIRuntime } from \"../runtime-context\";\nimport type { GenerativeUIRuntime } from \"../runtime-context\";\nimport { SurfaceView } from \"../SurfaceView\";\nimport type { DefaultMarkdownRendererProps } from \"../../providers/MarkdownRendererContext\";\nimport { ProviderMarkdown } from \"./ProviderMarkdown\";\nimport { getMarkdownSurfaceSource } from \"@copilotkit/core/generative-ui\";\nimport type { MarkdownFenceBlock } from \"@copilotkit/core/generative-ui\";\n\n/** Config for the built-in markdown renderer, plus `className`. */\ntype MarkdownProps = DefaultMarkdownRendererProps;\n\nconst FADE_STYLE_ID = \"a2ui-markdown-fade\";\n/**\n * Components fade in as they stream: each element that appears under a\n * markdown surface runs the keyframes once on mount. React keeps the keys\n * stable per component id, so an element that is already there never\n * animates again. SVG internals are left out: a chart library re-creates\n * its nodes on each render, and a fade on each of them would read as the\n * chart flashing whenever a sibling arrives. The fade runs under reduced\n * motion too, because it moves nothing.\n */\nconst FADE_CSS = [\n // Opacity only, so it also runs when the user asks for reduced motion:\n // that setting is about movement, and a short fade is not movement.\n // The keyframes give only the start, so each element fades to its own\n // opacity (a disabled control to its dimmed one), and no fill holds the\n // end: a finished fade must not pin opacity, or an element that hides\n // itself with opacity (the map's zoom hint) stays visible forever.\n \"@keyframes a2ui-fade-in{from{opacity:0}}\",\n \"[data-a2ui-markdown-surface] .a2ui-surface *:not(svg):not(svg *){animation:a2ui-fade-in .35s ease-out backwards}\",\n].join(\"\\n\");\n\n// There is no document on the server, so nothing is added there.\nconst noEffect: typeof useInsertionEffect = () => {};\nconst useInjectEffect =\n typeof document === \"undefined\" ? noEffect : useInsertionEffect;\n\nfunction useFadeStyles() {\n useInjectEffect(() => {\n if (document.getElementById(FADE_STYLE_ID)) return;\n const style = document.createElement(\"style\");\n style.id = FADE_STYLE_ID;\n style.textContent = FADE_CSS;\n document.head.appendChild(style);\n }, []);\n}\n\n/**\n * The default wrapper of a chat surface in the markdown transport. It draws\n * no box: a surface sits in the flow of the reply like a paragraph, and a\n * Card draws its own box when it is interactive. Nothing shows while the\n * surface streams. A rejected operation gets one line.\n */\nexport function DefaultMarkdownChatSurface({\n surfaceId,\n error,\n children,\n}: GenerativeUIChatSurfaceProps) {\n useFadeStyles();\n return (\n <div\n data-generative-ui-chat-surface={surfaceId}\n data-a2ui-markdown-surface={surfaceId}\n className=\"cpk-markdown-chat-surface\"\n >\n {children}\n {error && (\n <div role=\"alert\" className=\"cpk-markdown-chat-surface-error\">\n Part of this UI couldn't be shown.\n </div>\n )}\n </div>\n );\n}\n\nexport type MarkdownSurfacesProps = MarkdownProps & {\n /** The text of the assistant message, complete or still streaming. */\n content: string;\n /** The id of the message. The fences of the message are found by it. */\n messageId: string;\n /** Whether the message is still streaming. Only its last prose shows the caret. */\n isStreaming?: boolean;\n};\n\n/**\n * One chat surface in the chat wrapper. Nothing renders until the surface\n * has its root component, so a half-streamed fence shows no empty card.\n */\nfunction ChatSurface({\n runtime,\n threadId,\n surfaceId,\n Wrapper,\n}: {\n runtime: GenerativeUIRuntime;\n threadId: string;\n surfaceId: string;\n Wrapper: ComponentType<GenerativeUIChatSurfaceProps>;\n}) {\n // A surface whose createSurface was rejected shows only the error.\n const surface =\n runtime.manager.getSurface(threadId, surfaceId) ??\n runtime.manager.getFailedSurface(threadId, surfaceId);\n const root = surface?.model.componentsModel.get(GENERATIVE_UI_ROOT_ID);\n if (!surface || (!root && !surface.failed)) return null;\n const rejected = [...surface.serverRejected, ...surface.clientRejected];\n const error = rejected.length\n ? new Error(`${rejected.length} UI update(s) could not be shown`, {\n cause: rejected,\n })\n : undefined;\n return (\n <Wrapper\n surfaceId={surfaceId}\n isStreaming={surface.status === \"streaming\"}\n error={error}\n rejected={rejected}\n >\n {surface.failed ? null : <SurfaceView surface={surface} />}\n </Wrapper>\n );\n}\n\n/** The blocks of one fence: lifted prose and chat surfaces, in order. */\nfunction FenceBlocks({\n blocks,\n runtime,\n threadId,\n isStreaming,\n markdownProps,\n}: {\n blocks: MarkdownFenceBlock[];\n runtime: GenerativeUIRuntime;\n threadId: string;\n isStreaming: boolean;\n markdownProps: MarkdownProps;\n}) {\n const Wrapper =\n useContext(GenerativeUIChatSlotContext) ?? DefaultMarkdownChatSurface;\n let surfaceCount = 0;\n return (\n <>\n {blocks.map((block, index) => {\n // Keys follow the surfaces, so a surface keeps its element when\n // prose splits off around it during streaming.\n if (block.kind === \"markdown\") {\n return (\n <ProviderMarkdown\n key={`md-${surfaceCount}`}\n {...markdownProps}\n content={block.markdown}\n isStreaming={isStreaming && index === blocks.length - 1}\n />\n );\n }\n surfaceCount++;\n return (\n <ChatSurface\n key={block.surfaceId}\n runtime={runtime}\n threadId={threadId}\n surfaceId={block.surfaceId}\n Wrapper={Wrapper}\n />\n );\n })}\n </>\n );\n}\n\n/**\n * Experimental. Renders an assistant message of the markdown transport.\n * Prose renders as markdown. In place of each ```a2ui fence:\n *\n * - the fence that created a chat surface renders that surface (and the\n * prose lifted out of it) in the chat wrapper;\n * - every other fence renders nothing: a fence that updates the surface of\n * an earlier fence, or a fence for a named target, which\n * `<GenerativeUISurface id>` renders.\n *\n * Use it inside `<CopilotKitProvider generativeUI={{ ui, transport: \"markdown\" }}>`.\n * `CopilotChatAssistantMessage` uses it there on its own.\n *\n * @example\n * ```tsx\n * <MarkdownSurfaces content={message.content} messageId={message.id} />\n * ```\n */\nexport function MarkdownSurfaces({\n content,\n messageId,\n isStreaming = false,\n ...markdownProps\n}: MarkdownSurfacesProps) {\n const runtime = useRequiredGenerativeUIRuntime();\n const chatThreadId = useCopilotChatConfiguration()?.threadId;\n useManagerVersion(runtime);\n const segments = useMemo(() => splitA2UIMarkdown(content), [content]);\n const threadId = chatThreadId ?? runtime.manager.getActiveThread();\n const source = getMarkdownSurfaceSource(runtime);\n\n return (\n <>\n {segments.map((segment, index) => {\n const isLast = index === segments.length - 1;\n if (segment.type === \"markdown\") {\n return (\n <ProviderMarkdown\n key={`md-${index}`}\n {...markdownProps}\n content={segment.text}\n isStreaming={isStreaming && isLast}\n />\n );\n }\n const blocks = threadId\n ? source.getFenceBlocks(threadId, messageId, segment.index)\n : undefined;\n if (!threadId || !blocks) return null;\n return (\n <FenceBlocks\n key={`a2ui-${segment.index}`}\n blocks={blocks}\n runtime={runtime}\n threadId={threadId}\n isStreaming={isStreaming && isLast}\n markdownProps={markdownProps}\n />\n );\n })}\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,SAAgB,iCAAiC,EAC/C,SACA,aACA,WACA,eACA,OACA,SACA,aACA,mBACuD;AACvD,KAAI,CAAC,QAAS,QAAO;AAGrB,yDAA8B,QAAQ;AACtC,QACE,2CAACA;EACY;EACX,YAAY,CAAC;EACb,OAAO,SAAS,CAAC,CAAC;EACH;EACf,gBAAgBC;EACP;EACI;EACI;YAEhB;GACyB;;AAIhC,iCAAiC,cAC/B;;;;;ACvCF,SAAS,kBAAkB,YAA8C;AACvE,QAAO,OAAO,YACZ,OAAO,QAAQ,WAAW,CAAC,KAAK,CAAC,KAAK,WAAW,CAC/C,IAAI,QAAQ,cAAc,QAAQ,WAChC,OAAO,aAAa,CACrB,EACD,MACD,CAAC,CACH;;AAGH,MAAM,cAAc,kBAAkBC,2CAA0B;;AAGhE,SAAS,kBAAkB,OAAe;AACxC,QAAO,OAAO,KAAK,MAAM,CAAC,MACvB,QAAQ,IAAI,WAAW,QAAQ,IAAI,QAAQ,UAAU,QAAQ,QAC/D;;;;;;;AAsBH,MAAa,gCAAkD,SAAS,QACtE,EACE,YACA,OACA,OAAO,IACP,QAAQ,gBACR,cAAc,GACd,WACA,UACA,GAAG,SAEL,KACA;CACA,MAAM,eAAe,CAAC,YAAY,CAAC,kBAAkB,MAAM;AAC3D,QACE,4CAAC;EACM;EACL,GAAI;EACJ,OAAO;EACP,QAAQ;EACR,QAAQ;EACK;EACb,qCAAc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