@copilotkit/react-core 1.85.0 → 1.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/MarkdownSurfaces-BCVdnDAk.cjs +161 -0
  2. package/dist/MarkdownSurfaces-BCVdnDAk.cjs.map +1 -0
  3. package/dist/MarkdownSurfaces-CjJduaJR.mjs +149 -0
  4. package/dist/MarkdownSurfaces-CjJduaJR.mjs.map +1 -0
  5. package/dist/{MarkdownSurfaces-3cGU5_0H.cjs → chat-BnsrQ0VS.cjs} +667 -320
  6. package/dist/chat-BnsrQ0VS.cjs.map +1 -0
  7. package/dist/{MarkdownSurfaces-D-W4f9Dy.mjs → chat-IWySXWXP.mjs} +647 -312
  8. package/dist/chat-IWySXWXP.mjs.map +1 -0
  9. package/dist/{copilotkit-D6mTCuNU.mjs → copilotkit-B1OLgEU8.mjs} +6 -354
  10. package/dist/copilotkit-B1OLgEU8.mjs.map +1 -0
  11. package/dist/{copilotkit-Dn4PbHJV.d.mts → copilotkit-C7G95NO-.d.mts} +4 -4
  12. package/dist/{copilotkit-Dn4PbHJV.d.mts.map → copilotkit-C7G95NO-.d.mts.map} +1 -1
  13. package/dist/{copilotkit-BpKHgURs.cjs → copilotkit-Ca0IcTZU.cjs} +79 -427
  14. package/dist/copilotkit-Ca0IcTZU.cjs.map +1 -0
  15. package/dist/{copilotkit-CuTAoQF2.d.cts → copilotkit-DwD7D6jJ.d.cts} +2 -2
  16. package/dist/{copilotkit-CuTAoQF2.d.cts.map → copilotkit-DwD7D6jJ.d.cts.map} +1 -1
  17. package/dist/hooks-DMSkcNOl.d.cts +89 -0
  18. package/dist/hooks-DMSkcNOl.d.cts.map +1 -0
  19. package/dist/hooks-EwGvqYsW.d.mts +89 -0
  20. package/dist/hooks-EwGvqYsW.d.mts.map +1 -0
  21. package/dist/index.cjs +8 -8
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +2 -2
  24. package/dist/index.d.mts +2 -2
  25. package/dist/index.mjs +2 -2
  26. package/dist/index.umd.js +645 -140
  27. package/dist/index.umd.js.map +1 -1
  28. package/dist/refs-DL7ITFFD.cjs +43 -0
  29. package/dist/refs-DL7ITFFD.cjs.map +1 -0
  30. package/dist/refs-DiZXJ63p.mjs +31 -0
  31. package/dist/refs-DiZXJ63p.mjs.map +1 -0
  32. package/dist/{runtime-context-Er5UIbZA.d.mts → runtime-context-B4fKyzo6.d.mts} +31 -9
  33. package/dist/runtime-context-B4fKyzo6.d.mts.map +1 -0
  34. package/dist/{runtime-context-DrVNUYLi.d.cts → runtime-context-Da7T5vy4.d.cts} +31 -9
  35. package/dist/runtime-context-Da7T5vy4.d.cts.map +1 -0
  36. package/dist/use-generative-ui-root-CaTyBFNR.cjs +390 -0
  37. package/dist/use-generative-ui-root-CaTyBFNR.cjs.map +1 -0
  38. package/dist/use-generative-ui-root-WI9ERMpo.mjs +385 -0
  39. package/dist/use-generative-ui-root-WI9ERMpo.mjs.map +1 -0
  40. package/dist/v2/generative-ui/native.cjs +66 -0
  41. package/dist/v2/generative-ui/native.cjs.map +1 -0
  42. package/dist/v2/generative-ui/native.d.cts +155 -0
  43. package/dist/v2/generative-ui/native.d.cts.map +1 -0
  44. package/dist/v2/generative-ui/native.d.mts +155 -0
  45. package/dist/v2/generative-ui/native.d.mts.map +1 -0
  46. package/dist/v2/generative-ui/native.mjs +24 -0
  47. package/dist/v2/generative-ui/native.mjs.map +1 -0
  48. package/dist/v2/generative-ui.cjs +45 -70
  49. package/dist/v2/generative-ui.cjs.map +1 -1
  50. package/dist/v2/generative-ui.d.cts +229 -308
  51. package/dist/v2/generative-ui.d.cts.map +1 -1
  52. package/dist/v2/generative-ui.d.mts +229 -308
  53. package/dist/v2/generative-ui.d.mts.map +1 -1
  54. package/dist/v2/generative-ui.mjs +4 -29
  55. package/dist/v2/generative-ui.mjs.map +1 -1
  56. package/dist/v2/headless.d.cts +185 -294
  57. package/dist/v2/headless.d.cts.map +1 -1
  58. package/dist/v2/index.cjs +5 -5
  59. package/dist/v2/index.d.cts +2 -2
  60. package/dist/v2/index.d.mts +2 -2
  61. package/dist/v2/index.mjs +2 -2
  62. package/dist/v2/index.umd.js +645 -140
  63. package/dist/v2/index.umd.js.map +1 -1
  64. package/package.json +14 -10
  65. package/dist/MarkdownSurfaces-3cGU5_0H.cjs.map +0 -1
  66. package/dist/MarkdownSurfaces-D-W4f9Dy.mjs.map +0 -1
  67. package/dist/copilotkit-BpKHgURs.cjs.map +0 -1
  68. package/dist/copilotkit-D6mTCuNU.mjs.map +0 -1
  69. package/dist/runtime-context-DrVNUYLi.d.cts.map +0 -1
  70. package/dist/runtime-context-Er5UIbZA.d.mts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"MarkdownSurfaces-D-W4f9Dy.mjs","names":["createGenerativeUI","createSharedGenerativeUI","noopSubscribe","accessibilityAttributes"],"sources":["../src/v2/lib/shallow-stable-ref.ts","../src/v2/providers/CopilotChatConfigurationProvider.tsx","../src/v2/hooks/useKatexStyles.ts","../src/v2/types/defineToolCallRenderer.ts","../src/v2/generative-ui/catalog.ts","../src/v2/generative-ui/runtime-context.ts","../src/v2/generative-ui/hooks.ts","../src/v2/generative-ui/boundaries.tsx","../src/v2/generative-ui/accessibility.ts","../src/v2/generative-ui/SurfaceView.tsx","../src/v2/generative-ui/chat.tsx","../src/v2/generative-ui/markdown/MarkdownSurfaces.tsx"],"sourcesContent":["import { useRef } from \"react\";\n\n// Tailwind-free reference-stability helpers. Kept in their own leaf module (not\n// in ./slots, which imports `tailwind-merge`) so that DOM/CSS-free consumers —\n// e.g. CopilotChatConfigurationProvider, which is re-exported from the lean\n// `@copilotkit/react-core/v2/headless` entry — can reach them without pulling\n// `tailwind-merge` into the bundle (issue #4893).\n\n/**\n * Shallow equality comparison for objects.\n */\nexport function shallowEqual<T extends Record<string, unknown>>(\n obj1: T,\n obj2: T,\n): boolean {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n\n if (keys1.length !== keys2.length) return false;\n\n for (const key of keys1) {\n if (obj1[key] !== obj2[key]) return false;\n }\n\n return true;\n}\n\n/**\n * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,\n * class instances, and other exotic objects that happen to have typeof \"object\".\n */\nfunction isPlainObject(obj: unknown): obj is Record<string, unknown> {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n Object.prototype.toString.call(obj) === \"[object Object]\"\n );\n}\n\n/**\n * Returns the same reference as long as the value is shallowly equal to the\n * previous render's value.\n *\n * - Identical references bail out immediately (O(1)).\n * - Plain objects ({}) are shallow-compared key-by-key.\n * - Arrays, Dates, class instances, functions, and primitives are compared by\n * reference only — shallowEqual is never called on non-plain objects, which\n * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).\n *\n * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow\n * equality check isn't defeated by a new object reference on every render.\n */\nexport function useShallowStableRef<T>(value: T): T {\n const ref = useRef(value);\n\n // 1. Identical reference — bail early, no comparison needed.\n if (ref.current === value) return ref.current;\n\n // 2. Both are plain objects — shallow-compare to detect structural equality.\n if (isPlainObject(ref.current) && isPlainObject(value)) {\n if (shallowEqual(ref.current, value)) return ref.current;\n }\n\n // 3. Different values (or non-comparable types) — update the ref.\n ref.current = value;\n return ref.current;\n}\n","import type { ReactNode } from \"react\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { DEFAULT_AGENT_ID, randomUUID } from \"@copilotkit/shared\";\nimport type { OpenThreadRegistration } from \"@copilotkit/core\";\nimport { CopilotKitContext, useDefaultAgentId } from \"../context\";\n// Import from the tailwind-free leaf module (not ../lib/slots, which pulls\n// tailwind-merge) so this provider stays lean in the headless entry (issue #4893).\nimport { useShallowStableRef } from \"../lib/shallow-stable-ref\";\n\n// Default labels\nexport const CopilotChatDefaultLabels = {\n chatInputPlaceholder: \"Type a message...\",\n chatInputToolbarStartTranscribeButtonLabel: \"Transcribe\",\n chatInputToolbarCancelTranscribeButtonLabel: \"Cancel\",\n chatInputToolbarFinishTranscribeButtonLabel: \"Finish\",\n chatInputToolbarAddButtonLabel: \"Add attachments\",\n chatInputToolbarToolsButtonLabel: \"Tools\",\n chatInputToolbarSendButtonLabel: \"Send message\",\n chatInputToolbarStopButtonLabel: \"Stop\",\n assistantMessageToolbarCopyCodeLabel: \"Copy\",\n assistantMessageToolbarCopyCodeCopiedLabel: \"Copied\",\n assistantMessageToolbarCopyMessageLabel: \"Copy\",\n assistantMessageToolbarInspectorLabel: \"View in Inspector\",\n assistantMessageToolbarInspectorDescription:\n \"Open this message in the Inspector\",\n assistantMessageToolbarInspectorLocalOnlyLabel: \"Local only\",\n assistantMessageToolbarInspectorLocalOnlyDescription:\n \"Only visible on localhost or loopback hosts in development. Never shown in production.\",\n assistantMessageToolbarInspectorTitle: \"CopilotKit Inspector\",\n assistantMessageToolbarInspectorHideLabel: \"Hide this icon\",\n assistantMessageToolbarInspectorHideDescription: \"Until you reload this page\",\n assistantMessageToolbarThumbsUpLabel: \"Good response\",\n assistantMessageToolbarThumbsDownLabel: \"Bad response\",\n assistantMessageFeedbackCommentPlaceholder: \"Add a comment (optional)\",\n assistantMessageFeedbackCommentSubmitLabel: \"Send comment\",\n assistantMessageToolbarReadAloudLabel: \"Read aloud\",\n assistantMessageToolbarRegenerateLabel: \"Regenerate\",\n userMessageToolbarCopyMessageLabel: \"Copy\",\n userMessageToolbarEditMessageLabel: \"Edit\",\n userMessageToolbarPreviousBranchLabel: \"Previous branch\",\n userMessageToolbarNextBranchLabel: \"Next branch\",\n chatDisclaimerText:\n \"AI can make mistakes. Please verify important information.\",\n chatToggleOpenLabel: \"Open chat\",\n chatToggleCloseLabel: \"Close chat\",\n chatScrollToBottomLabel: \"Scroll to bottom\",\n chatConnectingLabel: \"Loading conversation\",\n modalHeaderTitle: \"CopilotKit Chat\",\n welcomeMessageText: \"How can I help you today?\",\n reasoningMessageThinkingLabel: \"Thinking…\",\n chatInputSlashMenuLabel: \"Slash commands\",\n chatInputSlashMenuEmptyText: \"No commands found\",\n attachmentRemoveButtonLabel: \"Remove attachment\",\n attachmentPlayVideoButtonLabel: \"Play video\",\n attachmentPreviewCloseButtonLabel: \"Close preview\",\n modalHeaderCloseButtonLabel: \"Close\",\n modalHeaderThreadsButtonLabel: \"Open threads\",\n sidebarLabel: \"Copilot chat sidebar\",\n};\n\nexport type CopilotChatLabels = typeof CopilotChatDefaultLabels;\n\n/**\n * Mobile breakpoint below which the chat modal and the thread-list drawer are\n * mutually exclusive. At or above this width both surfaces may coexist. This\n * mirrors the `(max-width: 767px)` / `(min-width: 768px)` split already used by\n * CopilotChatInput and CopilotSidebarView.\n */\nconst MOBILE_MAX_WIDTH_PX = 767;\n\n/**\n * Reports whether the current viewport is in the mobile range (`<768px`), where\n * the chat modal and drawer must not be open simultaneously. SSR-safe and\n * defensive against environments without `matchMedia` (treated as desktop, so\n * no mutual-exclusion constraint is applied).\n *\n * @returns `true` when the viewport is mobile-width, `false` otherwise.\n */\nfunction isMobileViewport(): boolean {\n if (\n typeof window === \"undefined\" ||\n typeof window.matchMedia !== \"function\"\n ) {\n return false;\n }\n return window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH_PX}px)`).matches;\n}\n\n// Define the full configuration interface\nexport interface CopilotChatConfigurationValue {\n labels: CopilotChatLabels;\n agentId: string;\n threadId: string;\n isModalOpen: boolean;\n setModalOpen: (open: boolean) => void;\n /**\n * Whether the thread-list drawer is open. A sibling boolean to `isModalOpen`\n * (deliberately NOT folded into a tri-state enum): on desktop the chat modal\n * and the drawer coexist, so two independent booleans are required.\n */\n drawerOpen: boolean;\n /**\n * Toggles the drawer open state. On mobile viewports (`<768px`) opening the\n * drawer closes the chat modal (mutual exclusion); on desktop there is no\n * constraint.\n */\n setDrawerOpen: (open: boolean) => void;\n /**\n * True once a `<CopilotThreadsDrawer>` wrapper has registered itself with this chat\n * configuration. The header thread-list launcher renders ONLY when this is\n * set, so chats with no drawer stay byte-for-byte unchanged.\n */\n drawerRegistered: boolean;\n /**\n * Called by the drawer wrapper on mount to announce its presence (and flip\n * `drawerRegistered`). Returns a cleanup function that de-registers the\n * drawer on unmount.\n *\n * @returns A cleanup callback that reverses the registration.\n */\n registerDrawer: () => () => void;\n /**\n * Internal: registers the modal-close setter of the provider that actually\n * owns the rendered modal (a descendant that supplied `isModalDefaultOpen`),\n * so the drawer's mobile mutual-exclusion — owned by the top-most provider —\n * closes the modal that is genuinely on screen rather than the top-most\n * provider's own (possibly unrendered) modal state.\n *\n * @param closeModal - A setter the drawer may call to close the rendered modal.\n * @returns A cleanup callback that de-registers the closer.\n */\n ɵregisterModalCloser: (closeModal: (open: boolean) => void) => () => void;\n // True when the current threadId was chosen by the caller rather than\n // silently minted inside the provider chain. Consumers that only make\n // sense against a real backend thread (e.g. /connect, suppressing the\n // welcome screen on switch) gate on this instead of `!!threadId`.\n hasExplicitThreadId: boolean;\n /**\n * Imperatively sets the active thread for this chat configuration.\n *\n * Use this to drive the rendered thread without a host callback — e.g. a\n * `<CopilotThreadsDrawer>` selecting a thread row sets it explicitly so the chat\n * connects to that backend thread.\n *\n * Guarded like the top-level `<CopilotKit>` provider's `setThreadId`: when\n * the consumer controls the threadId via the `threadId` prop on this\n * provider, this is a no-op (a warning is logged) so a prop-controlled\n * threadId is never silently overridden.\n *\n * @param threadId - The thread id to make active.\n * @param options.explicit - Whether the thread is a caller choice. Defaults\n * to `true` (a picked thread). Pass `false` to set a non-explicit thread\n * so the welcome screen shows (see {@link startNewThread}).\n */\n setActiveThreadId: (\n threadId: string,\n options?: { explicit?: boolean },\n ) => void;\n /**\n * Resets the active thread to a fresh, non-explicit client-side thread: a\n * newly minted UUID with `hasExplicitThreadId=false`, so the welcome screen\n * shows. Pairs with the core `startNewThread()` to clear the conversation\n * with no host wiring.\n *\n * Guarded identically to {@link setActiveThreadId}: a no-op when the\n * threadId is prop-controlled.\n */\n startNewThread: () => void;\n}\n\n// Create the configuration context\nconst CopilotChatConfiguration =\n createContext<CopilotChatConfigurationValue | null>(null);\n\n// Provider props interface\nexport interface CopilotChatConfigurationProviderProps {\n children: ReactNode;\n labels?: Partial<CopilotChatLabels>;\n agentId?: string;\n threadId?: string;\n // Lets internal wrappers (e.g. the v1 CopilotKit bridge, which pipes a\n // ThreadsProvider-minted UUID through as `threadId`) declare that the\n // threadId they are supplying is NOT a caller choice. When omitted, the\n // provider infers explicitness from whether the `threadId` prop itself\n // was supplied.\n hasExplicitThreadId?: boolean;\n isModalDefaultOpen?: boolean;\n}\n\n// Provider component\nexport const CopilotChatConfigurationProvider: React.FC<\n CopilotChatConfigurationProviderProps\n> = ({\n children,\n labels,\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n}) => {\n const parentConfig = useContext(CopilotChatConfiguration);\n\n // Stabilize labels references so that inline objects (new reference on every\n // parent render) don't invalidate mergedLabels and churn the context value.\n // parentConfig?.labels is already stabilized by the parent provider's own\n // useShallowStableRef, so we only need to stabilize the local labels prop.\n const stableLabels = useShallowStableRef(labels);\n const mergedLabels: CopilotChatLabels = useMemo(\n () => ({\n ...CopilotChatDefaultLabels,\n ...parentConfig?.labels,\n ...stableLabels,\n }),\n [stableLabels, parentConfig?.labels],\n );\n\n // `<CopilotKitProvider agentId>` is the last fallback before the global\n // default, so a provider-level agent reaches every chat that does not name\n // one of its own.\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId =\n agentId ?? parentConfig?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID;\n\n // A threadId prop is \"authoritative\" (caller-chosen) only when it is present\n // AND not explicitly flagged non-explicit. The v1 `<CopilotKit>` bridge pipes\n // an auto-minted UUID through as `threadId` with `hasExplicitThreadId={false}`\n // to SEED the thread without claiming the caller picked it; that seed must\n // stay overridable so imperative callers (e.g. `<CopilotThreadsDrawer>` selecting a\n // row, or `startNewThread`) can switch threads. A bare `threadId` prop (no\n // `hasExplicitThreadId`) is still treated as a caller choice.\n const threadIdPropIsAuthoritative =\n threadId !== undefined && hasExplicitThreadId !== false;\n\n // Whether this provider's threadId is controlled by the consumer. When\n // controlled, the imperative active-thread setters below must not override\n // the prop-driven value. A non-authoritative seed (v1 bridge auto-mint) is\n // NOT controlled, so imperative selection still works underneath it.\n const isThreadIdControlled = threadIdPropIsAuthoritative;\n\n // Imperative active-thread override owned by the TOP-MOST provider (the one\n // with no parent). A non-null override takes precedence over the auto-minted\n // UUID fallback below. Nested providers do not own this state — they proxy\n // the parent's setter (see resolved*ActiveThread below) and observe the\n // override through the inherited `parentConfig.threadId`.\n const [activeThreadOverride, setActiveThreadOverride] = useState<{\n threadId: string;\n explicit: boolean;\n } | null>(null);\n\n const resolvedThreadId = useMemo(() => {\n // An authoritative (caller-chosen) threadId prop always wins.\n if (threadIdPropIsAuthoritative) {\n return threadId as string;\n }\n // Otherwise an imperative override (a picked row or freshly-started thread)\n // beats both a non-authoritative seed (the v1 bridge's auto-minted UUID) and\n // the thread inherited from a parent provider.\n if (activeThreadOverride) {\n return activeThreadOverride.threadId;\n }\n if (parentConfig?.threadId) {\n return parentConfig.threadId;\n }\n if (threadId) {\n return threadId;\n }\n return randomUUID();\n }, [\n threadIdPropIsAuthoritative,\n threadId,\n parentConfig?.threadId,\n activeThreadOverride,\n ]);\n\n // Tell Core which Thread this view shows, so captured interactions can link\n // to it. Read the context directly: this provider also works without a\n // CopilotKitProvider, and then there is nothing to register with.\n const copilotkit = useContext(CopilotKitContext)?.copilotkit;\n const openThreadRef = useRef<OpenThreadRegistration | null>(null);\n const latestThreadIdRef = useRef(resolvedThreadId);\n latestThreadIdRef.current = resolvedThreadId;\n useEffect(() => {\n if (copilotkit === undefined) return;\n const registration = copilotkit.registerOpenThread({\n agentId: resolvedAgentId,\n threadId: latestThreadIdRef.current,\n });\n openThreadRef.current = registration;\n return () => {\n registration.unregister();\n openThreadRef.current = null;\n };\n }, [copilotkit, resolvedAgentId]);\n useEffect(() => {\n openThreadRef.current?.update(resolvedThreadId);\n }, [resolvedThreadId]);\n\n // Explicitness of this provider's own thread, mirroring the resolution order\n // above: an authoritative prop is a caller choice; otherwise an imperative\n // override carries its own explicitness (a picked row is explicit, a fresh\n // `startNewThread` is not); failing both, fall back to the (non-authoritative)\n // prop flag, which is `false` for the v1 bridge seed.\n const ownHasExplicitThreadId = threadIdPropIsAuthoritative\n ? true\n : (activeThreadOverride?.explicit ?? hasExplicitThreadId ?? false);\n const resolvedHasExplicitThreadId =\n ownHasExplicitThreadId || !!parentConfig?.hasExplicitThreadId;\n\n const resolvedDefaultOpen = isModalDefaultOpen ?? true;\n\n const [internalModalOpen, setInternalModalOpen] =\n useState<boolean>(resolvedDefaultOpen);\n\n const hasExplicitDefault = isModalDefaultOpen !== undefined;\n\n // When this provider owns its modal state, wrap the setter so that changes\n // propagate upward to any ancestor provider. This allows an outer\n // CopilotChatConfigurationProvider (e.g. a user's layout-level provider) to\n // observe open/close events that originate deep in the tree — fixing the\n // \"outer hook always returns true\" regression (CPK-7152 Behavior B).\n const setAndSync = useCallback(\n (open: boolean) => {\n setInternalModalOpen(open);\n parentConfig?.setModalOpen(open);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [parentConfig?.setModalOpen],\n );\n\n // Sync parent → child: when an ancestor's modal state is changed externally\n // (e.g. the user calls setModalOpen from an outer hook), reflect that change\n // in our own state so the sidebar/popup responds accordingly.\n // Skip the initial mount so that our own isModalDefaultOpen is respected and\n // not immediately overwritten by the parent's current value.\n const isMounted = useRef(false);\n useEffect(() => {\n if (!hasExplicitDefault) return;\n if (!isMounted.current) {\n isMounted.current = true;\n return;\n }\n if (parentConfig?.isModalOpen === undefined) return;\n setInternalModalOpen(parentConfig.isModalOpen);\n }, [parentConfig?.isModalOpen, hasExplicitDefault]);\n\n const resolvedIsModalOpen = hasExplicitDefault\n ? internalModalOpen\n : (parentConfig?.isModalOpen ?? internalModalOpen);\n const resolvedSetModalOpen = hasExplicitDefault\n ? setAndSync\n : (parentConfig?.setModalOpen ?? setInternalModalOpen);\n\n // Drawer presence + open state. When a parent provider exists, this provider\n // proxies the parent's drawer state and registration so that the whole chain\n // shares a single drawer (the drawer wrapper registers once, anywhere in the\n // subtree, and the header launcher anywhere can read/toggle it). Only the\n // top-most provider owns the underlying state.\n const [ownDrawerOpen, setOwnDrawerOpen] = useState<boolean>(false);\n const [ownDrawerCount, setOwnDrawerCount] = useState<number>(0);\n\n // The modal-close path used by the drawer's mobile mutual-exclusion. Held in\n // a ref so the drawer setter (owned by the top-most provider) can reach the\n // resolved modal setter without recreating its identity on every render.\n const modalCloseRef = useRef<(open: boolean) => void>(() => {});\n // Default to this provider's own resolved modal setter. When a DESCENDANT\n // provider owns the rendered modal (it supplied `isModalDefaultOpen`), it\n // registers its closer via `ɵregisterModalCloser` below, which overrides this\n // so the drawer closes the modal that is actually on screen.\n modalCloseRef.current = resolvedSetModalOpen;\n\n // Stack of descendant-registered modal closers. The most recently registered\n // closer (the deepest/last-rendered modal owner) is preferred, mirroring how\n // `resolvedThreadId`/modal ownership flows to the nearest explicit owner.\n const registeredModalClosersRef = useRef<Array<(open: boolean) => void>>([]);\n\n const ownRegisterModalCloser = useCallback(\n (closeModal: (open: boolean) => void) => {\n registeredModalClosersRef.current.push(closeModal);\n return () => {\n registeredModalClosersRef.current =\n registeredModalClosersRef.current.filter(\n (entry) => entry !== closeModal,\n );\n };\n },\n [],\n );\n\n const ownSetDrawerOpen = useCallback((open: boolean) => {\n setOwnDrawerOpen(open);\n // Mobile mutual-exclusion: opening the drawer closes the chat modal. Prefer\n // a descendant-registered closer (the actually-rendered modal) over this\n // provider's own resolved modal setter.\n if (open && isMobileViewport()) {\n const registered = registeredModalClosersRef.current;\n const closeModal =\n registered.length > 0\n ? registered[registered.length - 1]\n : modalCloseRef.current;\n closeModal(false);\n }\n }, []);\n\n const ownRegisterDrawer = useCallback(() => {\n setOwnDrawerCount((count) => count + 1);\n return () => {\n setOwnDrawerCount((count) => Math.max(0, count - 1));\n };\n }, []);\n\n const resolvedDrawerOpen = parentConfig\n ? parentConfig.drawerOpen\n : ownDrawerOpen;\n const resolvedSetDrawerOpen = parentConfig\n ? parentConfig.setDrawerOpen\n : ownSetDrawerOpen;\n const resolvedDrawerRegistered = parentConfig\n ? parentConfig.drawerRegistered\n : ownDrawerCount > 0;\n const resolvedRegisterDrawer = parentConfig\n ? parentConfig.registerDrawer\n : ownRegisterDrawer;\n const resolvedRegisterModalCloser = parentConfig\n ? parentConfig.ɵregisterModalCloser\n : ownRegisterModalCloser;\n\n // When THIS provider owns the rendered modal (it supplied\n // `isModalDefaultOpen`), register its closer up the chain so the top-most\n // provider's drawer mobile mutual-exclusion closes the modal that is actually\n // on screen. Re-registers if the resolved setter identity changes.\n useEffect(() => {\n if (!hasExplicitDefault) return;\n return resolvedRegisterModalCloser(resolvedSetModalOpen);\n }, [hasExplicitDefault, resolvedRegisterModalCloser, resolvedSetModalOpen]);\n\n // Active-thread override setters. The TOP-MOST provider owns the override\n // state; nested providers proxy the parent's setter so the whole chain drives\n // a single active thread (the override placed on the owner flows down via the\n // inherited threadId).\n //\n // The controlled-guard is applied at EACH level, not only on the owner: a\n // provider whose own `threadId` prop pins the rendered thread (per the\n // `resolvedThreadId` precedence above) intercepts the set with a no-op +\n // warning BEFORE proxying upward. This is required because in a nested chain\n // the controlled provider is often NOT the override owner — e.g. an\n // uncontrolled top-most provider with a controlled nested provider. Guarding\n // only the owner would let the set silently no-op (the nested `threadId` prop\n // wins at render) while the documented warning never fired.\n const isThreadIdControlledRef = useRef(isThreadIdControlled);\n isThreadIdControlledRef.current = isThreadIdControlled;\n\n const ownSetActiveThreadId = useCallback(\n (id: string, options?: { explicit?: boolean }) => {\n setActiveThreadOverride({\n threadId: id,\n explicit: options?.explicit ?? true,\n });\n },\n [],\n );\n\n const ownStartNewThread = useCallback(() => {\n setActiveThreadOverride({ threadId: randomUUID(), explicit: false });\n }, []);\n\n // Proxy to the parent's setter when nested, else to the owner's. Wrapped with\n // this provider's own controlled-guard so the nearest pinning (controlled)\n // provider — wherever it sits in the chain — is the one that no-ops + warns.\n const parentSetActiveThreadId = parentConfig?.setActiveThreadId;\n const parentStartNewThread = parentConfig?.startNewThread;\n\n const resolvedSetActiveThreadId = useCallback(\n (id: string, options?: { explicit?: boolean }) => {\n if (isThreadIdControlledRef.current) {\n console.warn(\n \"[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled \" +\n \"via the `threadId` prop on CopilotChatConfigurationProvider.\",\n );\n return;\n }\n if (parentSetActiveThreadId) {\n parentSetActiveThreadId(id, options);\n return;\n }\n ownSetActiveThreadId(id, options);\n },\n [parentSetActiveThreadId, ownSetActiveThreadId],\n );\n\n const resolvedStartNewThread = useCallback(() => {\n if (isThreadIdControlledRef.current) {\n console.warn(\n \"[CopilotKit] Ignoring startNewThread(): threadId is controlled via \" +\n \"the `threadId` prop on CopilotChatConfigurationProvider.\",\n );\n return;\n }\n if (parentStartNewThread) {\n parentStartNewThread();\n return;\n }\n ownStartNewThread();\n }, [parentStartNewThread, ownStartNewThread]);\n\n // Mobile mutual-exclusion (other direction): opening the chat modal closes\n // the drawer. Layered over whichever modal setter we resolved above so the\n // existing parent/child modal-sync contract is preserved untouched.\n const setModalOpenWithDrawerExclusion = useCallback(\n (open: boolean) => {\n if (open && isMobileViewport()) {\n resolvedSetDrawerOpen(false);\n }\n resolvedSetModalOpen(open);\n },\n [resolvedSetModalOpen, resolvedSetDrawerOpen],\n );\n\n const configurationValue: CopilotChatConfigurationValue = useMemo(\n () => ({\n labels: mergedLabels,\n agentId: resolvedAgentId,\n threadId: resolvedThreadId,\n hasExplicitThreadId: resolvedHasExplicitThreadId,\n isModalOpen: resolvedIsModalOpen,\n setModalOpen: setModalOpenWithDrawerExclusion,\n drawerOpen: resolvedDrawerOpen,\n setDrawerOpen: resolvedSetDrawerOpen,\n drawerRegistered: resolvedDrawerRegistered,\n registerDrawer: resolvedRegisterDrawer,\n ɵregisterModalCloser: resolvedRegisterModalCloser,\n setActiveThreadId: resolvedSetActiveThreadId,\n startNewThread: resolvedStartNewThread,\n }),\n [\n mergedLabels,\n resolvedAgentId,\n resolvedThreadId,\n resolvedHasExplicitThreadId,\n resolvedIsModalOpen,\n setModalOpenWithDrawerExclusion,\n resolvedDrawerOpen,\n resolvedSetDrawerOpen,\n resolvedDrawerRegistered,\n resolvedRegisterDrawer,\n resolvedRegisterModalCloser,\n resolvedSetActiveThreadId,\n resolvedStartNewThread,\n ],\n );\n\n return (\n <CopilotChatConfiguration.Provider value={configurationValue}>\n {children}\n </CopilotChatConfiguration.Provider>\n );\n};\n\n// Hook to use the full configuration\nexport const useCopilotChatConfiguration =\n (): CopilotChatConfigurationValue | null => {\n const configuration = useContext(CopilotChatConfiguration);\n return configuration;\n };\n\n/**\n * Props for {@link ControlledModalOpenScope}.\n */\nexport interface ControlledModalOpenScopeProps {\n children: ReactNode;\n /**\n * The host-owned open state. When this is a boolean, everything inside the\n * scope reads it as `isModalOpen`, so the host prop is the single source of\n * truth for what is on screen. Leave it `undefined` to keep the underlying\n * state in charge and only report requests through `onOpenChange`.\n */\n open?: boolean;\n /**\n * Called with the requested state whenever something inside the scope asks\n * to open or close the modal (the toggle button, click-outside, a consumer\n * calling `setModalOpen`). Fires whether or not `open` is supplied.\n */\n onOpenChange?: (open: boolean) => void;\n}\n\n/**\n * Reports modal open/close requests to the host, and — when `open` is\n * supplied — makes the modal state of an already-established chat\n * configuration **controlled** for the subtree it wraps.\n *\n * This is deliberately a scope component rather than another mode inside\n * {@link CopilotChatConfigurationProvider}. The provider resolves modal state\n * across a nested chain (own state, parent sync, drawer mutual-exclusion, the\n * modal-closer registry); a controlled branch inside that resolution would add\n * a fourth interacting mode. Overriding the context for the subtree instead\n * leaves every one of those paths untouched:\n *\n * - `isModalOpen` is replaced with the host's `open`, so the rendered surface\n * follows the prop from the very first frame (no open-then-close flash).\n * - `setModalOpen` still calls the underlying setter, so the existing\n * parent-sync and drawer mutual-exclusion side effects continue to run, and\n * *then* reports the request through `onOpenChange`.\n * - The wrapped setter is registered as the modal closer, so the drawer's\n * mobile mutual-exclusion reaches the host instead of silently flipping\n * state that nothing displays.\n *\n * A host that supplies `open` and ignores `onOpenChange` gets a modal pinned\n * to `open`, which is the standard controlled-component contract. A host that\n * supplies only `onOpenChange` is notified while the modal keeps managing\n * itself.\n *\n * Renders `children` unchanged when no chat configuration is in scope.\n */\nexport const ControlledModalOpenScope: React.FC<\n ControlledModalOpenScopeProps\n> = ({ children, open, onOpenChange }) => {\n const parentConfig = useContext(CopilotChatConfiguration);\n const parentSetModalOpen = parentConfig?.setModalOpen;\n const registerModalCloser = parentConfig?.ɵregisterModalCloser;\n\n const setModalOpen = useCallback(\n (next: boolean) => {\n parentSetModalOpen?.(next);\n onOpenChange?.(next);\n },\n [parentSetModalOpen, onOpenChange],\n );\n\n useEffect(() => {\n if (!registerModalCloser) return;\n return registerModalCloser(setModalOpen);\n }, [registerModalCloser, setModalOpen]);\n\n const configurationValue = useMemo(\n () =>\n parentConfig\n ? {\n ...parentConfig,\n isModalOpen: open ?? parentConfig.isModalOpen,\n setModalOpen,\n }\n : null,\n [parentConfig, open, setModalOpen],\n );\n\n if (!configurationValue) {\n return <>{children}</>;\n }\n\n return (\n <CopilotChatConfiguration.Provider value={configurationValue}>\n {children}\n </CopilotChatConfiguration.Provider>\n );\n};\n\nControlledModalOpenScope.displayName = \"ControlledModalOpenScope\";\n","\"use client\";\n\nimport { useEffect } from \"react\";\n\nlet injected = false;\n\n/**\n * Dynamically injects KaTeX CSS at runtime to avoid the Next.js\n * \"Global CSS cannot be imported from within node_modules\" build error.\n *\n * Uses a singleton flag so the stylesheet is only injected once.\n */\nexport function useKatexStyles(): void {\n useEffect(() => {\n if (injected || typeof document === \"undefined\") return;\n injected = true;\n\n // Dynamic import defers CSS loading to runtime, bypassing\n // Next.js static analysis that rejects global CSS from node_modules.\n\n void import(\"katex/dist/katex.min.css\").catch(() => {\n console.warn(\n \"[CopilotKit] Failed to load katex styles — math content may render without formatting\",\n );\n });\n }, []);\n}\n","import React from \"react\";\nimport { z } from \"zod\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport type { ReactToolCallRenderer } from \"./react-tool-call-renderer\";\nimport type { ToolCallStatus } from \"@copilotkit/core\";\n\n/**\n * Helper to define a type-safe tool call renderer entry.\n * - Accepts a single object whose keys match ReactToolCallRenderer's fields: { name, args, render, agentId? }.\n * - Derives `args` type from the provided schema (any Standard Schema V1 compatible library).\n * - Ensures the render function param type exactly matches ReactToolCallRenderer<T>[\"render\"]'s param.\n * - For wildcard tools (name: \"*\"), args is optional and defaults to z.any()\n */\ntype RenderProps<T> =\n | {\n name: string;\n toolCallId: string;\n args: Partial<T>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n }\n | {\n name: string;\n toolCallId: string;\n args: T;\n status: ToolCallStatus.Executing;\n result: undefined;\n }\n | {\n name: string;\n toolCallId: string;\n args: T;\n status: ToolCallStatus.Complete;\n result: string;\n };\n\n// Overload for wildcard tools without args\nexport function defineToolCallRenderer(def: {\n name: \"*\";\n render: (props: RenderProps<any>) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n}): ReactToolCallRenderer<any>;\n\n// Overload for regular tools with args\nexport function defineToolCallRenderer<S extends StandardSchemaV1>(def: {\n name: string;\n args: S;\n render: (\n props: RenderProps<InferSchemaOutput<S>>,\n ) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n}): ReactToolCallRenderer<InferSchemaOutput<S>>;\n\n// Implementation\nexport function defineToolCallRenderer<S extends StandardSchemaV1>(def: {\n name: string;\n args?: S;\n render: (props: any) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n}): ReactToolCallRenderer<any> {\n // For wildcard tools, default to z.any() if no args provided\n const argsSchema = def.name === \"*\" && !def.args ? z.any() : def.args;\n\n return {\n name: def.name,\n args: argsSchema,\n render: def.render as React.ComponentType<any>,\n ...(def.agentId ? { agentId: def.agentId } : {}),\n ...(def.group ? { group: true } : {}),\n };\n}\n","import type { ComponentType, ReactNode } from \"react\";\nimport { createGenerativeUI as createSharedGenerativeUI } from \"@copilotkit/shared/generative-ui\";\nimport type {\n AnyGenerativeUI,\n CreateGenerativeUIConfig as SharedCreateGenerativeUIConfig,\n GenerativeUI as SharedGenerativeUI,\n GenerativeUIBasesDefinitions,\n GenerativeUIComponentDefinition as SharedGenerativeUIComponentDefinition,\n GenerativeUIComponentProps as SharedGenerativeUIComponentProps,\n GenerativeUIDefinitions,\n GenerativeUIFunctionDefinition,\n GenerativeUIResultDefinitions,\n GenerativeUISchema,\n ResolvedGenerativeUIComponent as SharedResolvedGenerativeUIComponent,\n} from \"@copilotkit/shared/generative-ui\";\n\n// The catalog is framework-free and lives in `@copilotkit/shared/generative-ui`.\n// These types pin its component type to React components and its rendered\n// child type to `ReactNode`.\n\nexport {\n catalogIdsOf,\n componentCatalogIds,\n setterNameOf,\n} from \"@copilotkit/shared/generative-ui\";\nexport type {\n GenerativeUIComponentName,\n GenerativeUIDefinitionsOf,\n GenerativeUIEventDefinition,\n GenerativeUIEventInput,\n GenerativeUIFunctionArgs,\n GenerativeUIFunctionDefinition,\n GenerativeUIFunctionInput,\n GenerativeUIFunctionName,\n GenerativeUIFunctionsOf,\n GenerativeUISelector,\n GenerativeUISlotKind,\n GenerativeUIStateOf,\n PropsSchema,\n UnionToIntersection,\n} from \"@copilotkit/shared/generative-ui\";\n\n/** One component of a generative UI, as the renderer reads it. */\nexport type GenerativeUIComponentDefinition =\n SharedGenerativeUIComponentDefinition<ComponentType<any>>;\n\n/** A component after `createGenerativeUI` resolved its bindings. */\nexport type ResolvedGenerativeUIComponent = SharedResolvedGenerativeUIComponent<\n ComponentType<any>\n>;\n\n/**\n * Experimental. The result of `createGenerativeUI`: the components the model\n * can render, the app state they read, and the functions they call. Give it\n * to the provider (`generativeUI={{ ui }}`) and to the typed hooks.\n */\nexport type GenerativeUI<\n Definitions extends GenerativeUIDefinitions = GenerativeUIDefinitions,\n> = SharedGenerativeUI<Definitions, ComponentType<any>>;\n\n/**\n * Props that the renderer passes to a component:\n * `function CheckoutForm(props: GenerativeUIComponentProps<typeof ui, \"CheckoutForm\">)`.\n * Data props are the parsed `props` schema, bound props included. Event and\n * slot props are present only when they are bound or filled. Each writable\n * prop gets a setter (`value` gets `setValue`), which is always present.\n */\nexport type GenerativeUIComponentProps<\n UI extends AnyGenerativeUI,\n Name extends keyof NonNullable<UI[\"definitions\"]>[\"components\"] & string,\n> = SharedGenerativeUIComponentProps<UI, Name, ReactNode>;\n\n/** One new React component for each component of the bases that it names. */\ntype OverridesConfig<Bases extends readonly AnyGenerativeUI[]> = {\n [Name in keyof GenerativeUIBasesDefinitions<Bases>[\"components\"] & string]?: {\n component: ComponentType<\n GenerativeUIBasesDefinitions<Bases> extends infer Definitions extends\n GenerativeUIDefinitions\n ? GenerativeUIComponentProps<GenerativeUI<Definitions>, Name>\n : never\n >;\n };\n};\n\n/** The config of `createGenerativeUI`. */\nexport type CreateGenerativeUIConfig<\n Bases extends readonly AnyGenerativeUI[],\n State extends Record<string, GenerativeUISchema>,\n Functions extends Record<string, GenerativeUIFunctionDefinition>,\n Props extends Record<string, unknown>,\n Events extends Record<string, unknown>,\n Slots extends Record<string, unknown>,\n Writable extends Record<string, unknown>,\n> = SharedCreateGenerativeUIConfig<\n Bases,\n State,\n Functions,\n Props,\n Events,\n Slots,\n Writable,\n OverridesConfig<Bases>\n>;\n\n/**\n * Experimental. Declares the components the model can render, the app state\n * they read, and the functions they call.\n *\n * - A prop with the name of a top-level state key is bound to that state.\n * - `bind: { prop: (state, props) => value }` binds a prop to a selector.\n * - An event binds to the function with its name, else to the name without\n * `on` (`onAddToCart` calls `addToCart`).\n * - `writable: [\"value\"]` gives the component a `setValue` prop. See\n * `GenerativeUIComponentDefinition.writable`.\n *\n * The model does not see bound props or matched events.\n *\n * @param config - `id`, then optional `extends`, `state`, `functions` and\n * `overrides`, then `components`. Put `state` before `components`, so the selectors\n * get typed state.\n * @throws Error when a name comes from two places, an override names no\n * component of the bases, `props` is not an object\n * schema with a JSON Schema, a key is reserved or used\n * twice on a component, an event matches two functions, an unmatched event\n * has no `parameters`, a `bind` key is not a prop, a `writable` key is not\n * a prop or is a bound prop, or a setter name is already a key of the\n * component. Also throws when `parameterOrder` contains duplicate or unknown\n * keys, or an ordered component declares integer-index keys whose JSON object\n * enumeration order cannot be controlled.\n *\n * @example\n * ```ts\n * const ui = createGenerativeUI({\n * id: \"acme/store@1\",\n * state: { cart: cartSchema },\n * functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },\n * components: {\n * CartSummary: {\n * component: CartSummary,\n * props: z.object({ count: z.number() }),\n * bind: { count: (state) => state.cart.count },\n * },\n * },\n * });\n * ```\n */\nexport function createGenerativeUI<\n Bases extends readonly AnyGenerativeUI[] = [],\n State extends Record<string, GenerativeUISchema> = {},\n Functions extends Record<string, GenerativeUIFunctionDefinition> = {},\n Props extends Record<string, unknown> = {},\n Events extends Record<string, unknown> = {},\n Slots extends Record<string, unknown> = {},\n Writable extends Record<string, unknown> = {},\n>(\n config: CreateGenerativeUIConfig<\n Bases,\n State,\n Functions,\n Props,\n Events,\n Slots,\n Writable\n >,\n) {\n // The React config only narrows the shared one (React component types),\n // so the shared runtime builds the same UI.\n const build = createSharedGenerativeUI as (config: unknown) => unknown;\n return build(config) as GenerativeUI<\n GenerativeUIResultDefinitions<\n Bases,\n State,\n Functions,\n Props,\n Events,\n Slots,\n Writable\n >\n >;\n}\n","import { createContext, useContext } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { GenerativeUIUserEvent } from \"@copilotkit/shared\";\nimport type { GenerativeUIAccessibility } from \"./accessibility\";\nimport type { GenerativeUI } from \"./catalog\";\nimport type { GenerativeUIDispatcher } from \"@copilotkit/core/generative-ui\";\nimport type {\n GenerativeUIErrorInfo,\n GenerativeUIInvokeResult,\n} from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUISurfaceManager } from \"@copilotkit/core/generative-ui\";\nimport type { GenerativeUITheme } from \"@copilotkit/shared/generative-ui\";\n\nexport type { GenerativeUITheme };\n\nexport interface GenerativeUIErrorBoundaryConfig {\n /** Replaces the default per-component fallback. */\n fallback?: (props: {\n error: Error;\n retry: () => void;\n surfaceId: string;\n componentId: string;\n }) => ReactNode;\n /** Called for render, props, operation, function and event failures. */\n onError?: (info: GenerativeUIErrorInfo) => void;\n}\n\ninterface GenerativeUIBaseConfig {\n /**\n * The result of `createGenerativeUI`: the components the model can render,\n * the app state they read and the functions they call.\n */\n ui: GenerativeUI;\n /**\n * The agents that get the generative UI. When omitted, every agent gets\n * it. Other agents get no envelope.\n */\n agentIds?: string[];\n /**\n * Values for the `--a2ui-*` CSS variables and the map style. Top-level\n * values apply in both modes. `dark` changes them in dark mode, which is\n * on under a `.dark` class, like the CopilotKit chat.\n */\n theme?: GenerativeUITheme;\n /** Fallback UI and error reporting for generated UI. */\n errorBoundary?: GenerativeUIErrorBoundaryConfig;\n}\n\n/**\n * The tool transport: the model calls the `render_ui` tool, and the runtime\n * validates each operation before it streams it to the client.\n */\nexport interface GenerativeUIToolConfig extends GenerativeUIBaseConfig {\n /** Leave it out, or set \"tool\". */\n transport?: \"tool\";\n // Markdown-only options. `never` makes them a type error here, also when\n // `transport` is left out.\n sendContext?: never;\n includeCatalog?: never;\n}\n\n/**\n * The markdown transport: the model writes the operations in ```a2ui fences\n * in its reply. The client reads and validates them.\n */\nexport interface GenerativeUIMarkdownConfig extends GenerativeUIBaseConfig {\n transport: \"markdown\";\n /**\n * Send the component schema and the fence guideline as context entries.\n * Set `false` when the backend builds its own prompt from the envelope.\n * Default `true`.\n */\n sendContext?: boolean;\n /**\n * Send the component schemas in the envelope (`catalog.components`).\n * Default `true`.\n */\n includeCatalog?: boolean;\n}\n\n/**\n * Experimental. The `generativeUI` prop of `CopilotKitProvider`. Set\n * `transport: \"markdown\"` to get the markdown options.\n *\n * @example\n * ```tsx\n * <CopilotKitProvider generativeUI={{ ui }} />\n * <CopilotKitProvider generativeUI={{ ui, transport: \"markdown\", sendContext: false }} />\n * ```\n */\nexport type GenerativeUIConfig =\n | GenerativeUIToolConfig\n | GenerativeUIMarkdownConfig;\n\nexport interface GenerativeUIRuntime {\n manager: GenerativeUISurfaceManager;\n dispatcher: GenerativeUIDispatcher;\n /** The generative UI given to the provider as `generativeUI={{ ui }}`. */\n ui: GenerativeUI;\n /** How the model sends operations. \"tool\" when the config leaves it out. */\n transport: \"tool\" | \"markdown\";\n /** The latest `generativeUI` config of the provider. */\n readonly config: GenerativeUIConfig;\n /** The latest `theme`. Each surface root sets its CSS variables. */\n theme?: GenerativeUITheme;\n forwardEvent: (\n event: GenerativeUIUserEvent,\n agentId: string | undefined,\n ) => Promise<GenerativeUIInvokeResult>;\n reportError: (info: GenerativeUIErrorInfo) => void;\n readonly errorFallback?: GenerativeUIErrorBoundaryConfig[\"fallback\"];\n}\n\nexport const GenerativeUIRuntimeContext =\n createContext<GenerativeUIRuntime | null>(null);\n\nexport function useGenerativeUIRuntime(): GenerativeUIRuntime | null {\n return useContext(GenerativeUIRuntimeContext);\n}\n\nexport function useRequiredGenerativeUIRuntime(): GenerativeUIRuntime {\n const runtime = useContext(GenerativeUIRuntimeContext);\n if (!runtime) {\n throw new Error(\n \"Generative UI components must be rendered inside <CopilotKitProvider generativeUI={{ ui }}>.\",\n );\n }\n return runtime;\n}\n\nexport { reportErrorSafely } from \"@copilotkit/core/generative-ui\";\n\nexport interface GenerativeUINodeContextValue {\n surfaceKey: string;\n surfaceId: string;\n componentId: string;\n /** The resolved `accessibility` of the component envelope, if any. */\n accessibility?: GenerativeUIAccessibility;\n}\n\nexport const GenerativeUINodeContext =\n createContext<GenerativeUINodeContextValue | null>(null);\n","import { useEffect, useRef, useSyncExternalStore } from \"react\";\nimport type {\n GenerativeUI,\n GenerativeUIDefinitionsOf,\n GenerativeUIFunctionArgs,\n GenerativeUIFunctionName,\n GenerativeUIStateOf,\n} from \"./catalog\";\nimport { useRequiredGenerativeUIRuntime } from \"./runtime-context\";\nimport type { GenerativeUIRuntime } from \"./runtime-context\";\nimport { formatIssues, validateSchema } from \"@copilotkit/shared/generative-ui\";\nimport type {\n SchemaInput,\n ValidationResult,\n} from \"@copilotkit/shared/generative-ui\";\n\nconst noopSubscribe = () => () => {};\nconst zero = () => 0;\n\n/** Re-renders on any surface-manager change. */\nexport function useManagerVersion(runtime: GenerativeUIRuntime | null): number {\n return useSyncExternalStore(\n runtime?.manager.subscribe ?? noopSubscribe,\n runtime?.manager.getVersion ?? zero,\n zero,\n );\n}\n\n/** What `useGenerativeUIState` takes for one key: the input of its schema. */\ntype StateInput<\n UI extends GenerativeUI<any>,\n Key extends keyof GenerativeUIStateOf<UI>,\n> = SchemaInput<GenerativeUIDefinitionsOf<UI>[\"state\"][Key]>;\n\n/**\n * Experimental. Gives one key of the app state declared in\n * `createGenerativeUI({ state })` its value. Bound props of generated\n * components read it. The model does not see it.\n *\n * The key is set on mount and when the value changes (compared as JSON). It\n * is removed on unmount.\n *\n * @param ui - The object from `createGenerativeUI`. It gives the key and the\n * value their types.\n * @param key - A top-level key of `state`.\n * @param value - The value of that key. It must fit the key's schema.\n *\n * @example\n * ```tsx\n * useGenerativeUIState(storeUI, \"cart\", { count, total, coupon, items });\n * ```\n */\nexport function useGenerativeUIState<\n UI extends GenerativeUI<any>,\n Key extends keyof GenerativeUIStateOf<UI> & string,\n>(ui: UI, key: Key, value: StateInput<UI, Key>) {\n // ponytail: `ui` is for types only. The hook writes to the provider's generative UI and does not check that `ui` is that object.\n const runtime = useRequiredGenerativeUIRuntime();\n const serialized = JSON.stringify(value);\n useEffect(() => {\n const raw: unknown = JSON.parse(serialized ?? \"null\");\n let current = true;\n const apply = (parsed: ValidationResult) => {\n if (!current) return;\n if (parsed.success) {\n runtime.manager.setState(key, parsed.data);\n return;\n }\n // An invalid value is not stored. Bound props that read this key show the props fallback.\n runtime.manager.removeState(key);\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\n `[generativeUI] useGenerativeUIState: invalid value for \"${key}\": ${formatIssues(parsed.issues, \"value\")}`,\n );\n }\n };\n // Selectors get the parsed output, so schema defaults and transforms run\n // here. A schema that validates synchronously applies at once.\n const schema = runtime.ui.state.get(key);\n const parsed = schema\n ? validateSchema(schema, raw)\n : { success: true as const, data: raw };\n if (parsed instanceof Promise) void parsed.then(apply);\n else apply(parsed);\n return () => {\n current = false;\n };\n }, [runtime, key, serialized]);\n useEffect(() => () => runtime.manager.removeState(key), [runtime, key]);\n}\n\n/**\n * Experimental. Mounts the handler of a function declared in\n * `createGenerativeUI({ functions })`. Generated UI can call the function\n * only while exactly one handler for it is mounted.\n *\n * The handler gets the parsed arguments: schema defaults are set. It can\n * change on each render. The latest handler always runs, and the hook does\n * not register again.\n *\n * @param ui - The object from `createGenerativeUI`. It gives the name and the\n * handler arguments their types.\n * @param name - A key of `functions`.\n * @param handler - Runs when generated UI calls the function. Its return\n * value goes back to the caller as `{ ok: true, result }`.\n *\n * @example\n * ```tsx\n * useGenerativeUIFunction(storeUI, \"addToCart\", ({ productId, quantity }) =>\n * cart.addItem(productId, quantity),\n * );\n * ```\n */\nexport function useGenerativeUIFunction<\n UI extends GenerativeUI<any>,\n Name extends GenerativeUIFunctionName<UI>,\n>(\n ui: UI,\n name: Name,\n handler: (args: GenerativeUIFunctionArgs<UI, Name>) => unknown,\n) {\n // ponytail: `ui` is for types only. The hook registers with the provider's generative UI and does not check that `ui` is that object.\n const runtime = useRequiredGenerativeUIRuntime();\n const latest = useRef(handler);\n latest.current = handler;\n useEffect(() => runtime.dispatcher.register(name, latest), [runtime, name]);\n}\n","import React, { Component } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { reportErrorSafely } from \"./runtime-context\";\nimport type { GenerativeUIRuntime } from \"./runtime-context\";\n\nexport function DefaultNodeFallback({\n message,\n componentId,\n retry,\n}: {\n message: string;\n componentId: string;\n retry?: () => void;\n}) {\n return (\n <div\n role=\"alert\"\n data-generative-ui-error={componentId}\n style={{\n border: \"1px solid #fca5a5\",\n background: \"#fef2f2\",\n color: \"#991b1b\",\n borderRadius: 8,\n padding: \"8px 12px\",\n fontSize: 13,\n }}\n >\n Couldn’t display this part: {message}\n {retry && (\n <button\n type=\"button\"\n onClick={retry}\n style={{ marginLeft: 8, textDecoration: \"underline\" }}\n >\n Retry\n </button>\n )}\n </div>\n );\n}\n\n/**\n * A child that has not streamed yet renders nothing. The prose keeps\n * streaming above the surface, and each component appears as soon as it is\n * complete. A grey block in its place would read as a broken layout.\n */\nexport function NodePlaceholder(_props: { componentId: string }) {\n return null;\n}\n\ninterface NodeBoundaryProps {\n surfaceId: string;\n componentId: string;\n /** Wire props object of the node; a new object means a new agent revision. */\n revision: unknown;\n runtime: GenerativeUIRuntime;\n children: ReactNode;\n}\n\ninterface NodeBoundaryState {\n error: Error | null;\n revision: unknown;\n}\n\n/** Per-node boundary. Resets on retry or a new agent revision, not on data ticks. */\nexport class NodeBoundary extends Component<\n NodeBoundaryProps,\n NodeBoundaryState\n> {\n state: NodeBoundaryState = { error: null, revision: this.props.revision };\n\n static getDerivedStateFromError(error: Error): Partial<NodeBoundaryState> {\n return { error };\n }\n\n static getDerivedStateFromProps(\n props: NodeBoundaryProps,\n state: NodeBoundaryState,\n ): Partial<NodeBoundaryState> | null {\n return props.revision !== state.revision\n ? { error: null, revision: props.revision }\n : null;\n }\n\n componentDidCatch(error: Error) {\n const { runtime, surfaceId, componentId } = this.props;\n reportErrorSafely(runtime, {\n kind: \"render\",\n surfaceId,\n componentId,\n error,\n });\n }\n\n private retry = () => this.setState({ error: null });\n\n render() {\n const { error } = this.state;\n if (!error) return this.props.children;\n const { runtime, surfaceId, componentId } = this.props;\n const fallback = runtime.errorFallback;\n return fallback ? (\n fallback({ error, retry: this.retry, surfaceId, componentId })\n ) : (\n <DefaultNodeFallback\n message={error.message}\n componentId={componentId}\n retry={this.retry}\n />\n );\n }\n}\n\n/** Outer boundary: a failure here must not reach the chat or the host page. */\nexport class SurfaceBoundary extends Component<\n { surfaceId: string; runtime: GenerativeUIRuntime; children: ReactNode },\n { error: Error | null }\n> {\n state = { error: null as Error | null };\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n componentDidCatch(error: Error) {\n reportErrorSafely(this.props.runtime, {\n kind: \"render\",\n surfaceId: this.props.surfaceId,\n error,\n });\n }\n\n render() {\n if (!this.state.error) return this.props.children;\n return (\n <DefaultNodeFallback\n message=\"this generated UI failed to render\"\n componentId=\"surface\"\n />\n );\n }\n}\n","import { useContext, useMemo } from \"react\";\nimport { accessibilityAttributes } from \"@copilotkit/core/generative-ui\";\nimport type { GenerativeUIAriaAttributes } from \"@copilotkit/core/generative-ui\";\nimport { GenerativeUINodeContext } from \"./runtime-context\";\n\n// The accessibility helpers are framework-free and live in\n// `@copilotkit/core/generative-ui`. The standard components import them\n// from here.\nexport {\n accessibilityAttributes,\n controlAria,\n namedRole,\n readAccessibility,\n wrapperAria,\n} from \"@copilotkit/core/generative-ui\";\nexport type {\n GenerativeUIAccessibility,\n GenerativeUIAriaAttributes,\n} from \"@copilotkit/core/generative-ui\";\n\n/**\n * Experimental. The ARIA attributes of the `accessibility` that the model\n * gave the component being rendered, to spread on its root element. The\n * standard components do this; a custom component does it itself:\n *\n * @example\n * ```tsx\n * function Panel({ children }: { children?: ReactNode }) {\n * const aria = useGenerativeUIAccessibility();\n * return <section {...aria}>{children}</section>;\n * }\n * ```\n *\n * Outside of generated UI it gives `{}`.\n */\nexport function useGenerativeUIAccessibility(): GenerativeUIAriaAttributes {\n const node = useContext(GenerativeUINodeContext);\n const accessibility = node?.accessibility;\n return useMemo(() => accessibilityAttributes(accessibility), [accessibility]);\n}\n","import React, {\n memo,\n useCallback,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { ComponentModel, SurfaceModel } from \"@a2ui/web_core/v0_9\";\nimport {\n A2UI_COMPONENT_ENVELOPE_KEYS,\n GENERATIVE_UI_ROOT_ID,\n isActionBinding,\n isPathBinding,\n mapAtChildRef,\n} from \"@copilotkit/shared\";\nimport type {\n ChildRef,\n GenerativeUIActionBinding,\n GenerativeUITemplateChildren,\n} from \"@copilotkit/shared\";\nimport { shallowEqual } from \"../lib/shallow-stable-ref\";\nimport { setterNameOf } from \"./catalog\";\nimport type { ResolvedGenerativeUIComponent } from \"./catalog\";\nimport {\n joinPath,\n resolvePath,\n tryResolveDynamicValue,\n} from \"@copilotkit/core/generative-ui\";\nimport {\n formatIssues,\n isAsyncIssue,\n issueKey,\n validateSchemaSync,\n withoutRejectedNulls,\n} from \"@copilotkit/shared/generative-ui\";\nimport {\n DefaultNodeFallback,\n NodeBoundary,\n NodePlaceholder,\n SurfaceBoundary,\n} from \"./boundaries\";\nimport {\n accessibilityAttributes,\n readAccessibility,\n wrapperAria,\n} from \"./accessibility\";\nimport type { GenerativeUIAccessibility } from \"./accessibility\";\nimport type { GenerativeUIInvokeResult } from \"@copilotkit/shared/generative-ui\";\nimport {\n invokeBoundEvent,\n invokeMatchedEvent,\n} from \"@copilotkit/core/generative-ui\";\nimport {\n GenerativeUINodeContext,\n reportErrorSafely,\n useRequiredGenerativeUIRuntime,\n} from \"./runtime-context\";\nimport type { GenerativeUIRuntime } from \"./runtime-context\";\nimport { themeStyleSheet } from \"@copilotkit/shared/generative-ui\";\nimport type {\n GenerativeUISurfaceManager,\n ManagedSurface,\n} from \"@copilotkit/core/generative-ui\";\n\nconst NO_ANCESTORS: readonly string[] = [];\nconst ROOT_STYLE = { display: \"contents\" } as const;\n// No surface state exists on the server or during hydration.\nconst undefinedSnapshot = () => undefined;\nconst noopSubscribe = () => () => {};\nconst zeroSnapshot = () => 0;\n\n/** A \"multiple\" slot value that repeats a component for each list item. */\nfunction isTemplateChildren(\n value: unknown,\n): value is GenerativeUITemplateChildren {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"componentId\" in value &&\n typeof value.componentId === \"string\" &&\n \"path\" in value &&\n typeof value.path === \"string\"\n );\n}\n\nexport function SurfaceView({ surface }: { surface: ManagedSurface }) {\n const runtime = useRequiredGenerativeUIRuntime();\n const { theme } = runtime;\n const sheet = useMemo(() => themeStyleSheet(theme), [theme]);\n // The root element is always there, so a theme change does not remount\n // the surface. `display: contents` keeps it out of the layout, and the\n // CSS variables still reach every component of the surface. The\n // `a2ui-surface` class scopes the standard catalog's surface CSS rules.\n // The theme is a stylesheet, not an inline style, so that its `dark`\n // values can apply in dark mode only. The values are checked in\n // `themeStyleSheet`, and the HTML is set as is, so the server render\n // keeps the quotes of the rule.\n return (\n <div\n className=\"a2ui-surface\"\n data-generative-ui-root={surface.surfaceId}\n data-a2ui-theme={sheet?.id}\n style={ROOT_STYLE}\n >\n {sheet ? <style dangerouslySetInnerHTML={{ __html: sheet.css }} /> : null}\n <SurfaceBoundary surfaceId={surface.surfaceId} runtime={runtime}>\n <NodeView\n surface={surface}\n componentId={GENERATIVE_UI_ROOT_ID}\n basePath={undefined}\n ancestors={NO_ANCESTORS}\n />\n </SurfaceBoundary>\n </div>\n );\n}\n\n/**\n * Resolves a component by id. Subscribes to the manager rather than web_core's\n * `onCreated`/`onDeleted`: web_core's EventEmitter awaits each listener in turn,\n * so with several subscribers (one per slotted child, or one per mount of the\n * same surface) all but the first are notified a microtask late. That is only\n * visible inside synchronous flushes such as `act()` / `flushSync`, where the\n * old tree would still be on screen, but it makes updates order-dependent.\n * The manager notifies synchronously once an ingest has been fully applied.\n */\nfunction useComponentModel(\n manager: GenerativeUISurfaceManager,\n model: SurfaceModel<any>,\n id: string,\n): ComponentModel | undefined {\n return useSyncExternalStore(\n manager.subscribe,\n () => model.componentsModel.get(id),\n undefinedSnapshot,\n );\n}\n\n/** Same reasoning as `useComponentModel`: never rely on web_core's emitters. */\nfunction useComponentProperties(\n manager: GenerativeUISurfaceManager,\n component: ComponentModel | undefined,\n) {\n return useSyncExternalStore(\n manager.subscribe,\n () => component?.properties,\n undefinedSnapshot,\n );\n}\n\n/**\n * The id of a node in the ancestor list. A template renders the same\n * component once per item, so the item path is part of the id. A real cycle\n * repeats both.\n */\nfunction scopedId(componentId: string, basePath: string | undefined) {\n return `${basePath ?? \"\"}#${componentId}`;\n}\n\nconst NodeView = memo(function NodeView({\n surface,\n componentId,\n basePath,\n ancestors,\n}: {\n surface: ManagedSurface;\n componentId: string;\n /**\n * The data model path of the template item this node renders, or\n * `undefined` outside of a template. Relative paths resolve against it.\n */\n basePath: string | undefined;\n /** Scoped ids of the nodes above this one; used to cut cyclic references. */\n ancestors: readonly string[];\n}) {\n const runtime = useRequiredGenerativeUIRuntime();\n const component = useComponentModel(\n runtime.manager,\n surface.model,\n componentId,\n );\n const properties = useComponentProperties(runtime.manager, component);\n if (ancestors.includes(scopedId(componentId, basePath))) {\n return (\n <DefaultNodeFallback\n message={`cyclic reference to ${componentId}`}\n componentId={componentId}\n />\n );\n }\n if (!component || !properties)\n return <NodePlaceholder componentId={componentId} />;\n const definition = runtime.ui.components.get(component.type);\n if (!definition) {\n return (\n <DefaultNodeFallback\n message={`unknown component \"${component.type}\"`}\n componentId={componentId}\n />\n );\n }\n return (\n <NodeBoundary\n key={component.type}\n surfaceId={surface.surfaceId}\n componentId={componentId}\n revision={properties}\n runtime={runtime}\n >\n <ResolvedNode\n surface={surface}\n componentId={componentId}\n definition={definition}\n properties={properties}\n runtime={runtime}\n basePath={basePath}\n ancestors={ancestors}\n />\n </NodeBoundary>\n );\n});\n\n/**\n * Renders the component of a template once for each item of the list at the\n * template path, keyed by index. Renders nothing when there is no list.\n */\nfunction TemplateChildren({\n surface,\n template,\n basePath,\n ancestors,\n}: {\n surface: ManagedSurface;\n template: GenerativeUITemplateChildren;\n basePath: string | undefined;\n ancestors: readonly string[];\n}) {\n const dataModel = surface.model.dataModel;\n const listPath = resolvePath(template.path, basePath);\n const subscribe = useCallback(\n (onChange: () => void) => {\n const subscription = dataModel.subscribe(listPath, onChange);\n return () => subscription.unsubscribe();\n },\n [dataModel, listPath],\n );\n const getCount = () => {\n const list = dataModel.get(listPath);\n return Array.isArray(list) ? list.length : 0;\n };\n const count = useSyncExternalStore(subscribe, getCount, zeroSnapshot);\n const indexes = Array.from({ length: count }, (_, index) => index);\n return (\n <>\n {indexes.map((index) => (\n <NodeView\n key={index}\n surface={surface}\n componentId={template.componentId}\n basePath={joinPath(listPath, String(index))}\n ancestors={ancestors}\n />\n ))}\n </>\n );\n}\n\n/** What one data prop resolved to, and what it read to get there. */\ninterface ResolvedProp {\n /** The raw prop value it was resolved from. */\n raw: unknown;\n /** The template item path it was resolved in. */\n basePath: string | undefined;\n /** The value, or the reason it could not be computed. */\n outcome: { ok: true; value: unknown } | { ok: false; message: string };\n /** The data model value at each path it read, when it was resolved. */\n reads: Map<string, unknown>;\n}\n\ntype ModelData =\n | {\n ok: true;\n values: Record<string, unknown>;\n /** The resolved `accessibility` of the component envelope. */\n accessibility: GenerativeUIAccessibility | undefined;\n }\n | { ok: false; problem: string };\n\n/**\n * The props the model sets, with their dynamic values resolved from the\n * surface data model: `{\"@path\"}` bindings, `{\"@call\"}` function values and\n * `{\"@call\":\"@index\"}` in a template, at any depth. A literal writable prop\n * that the component set shows the local value from `overrides`. Bound\n * props, events and slots are left out, and so are the keys of the A2UI\n * component envelope; `accessibility` is resolved the same way and given\n * on its own.\n *\n * A prop is resolved again only when its raw value or a data model value it\n * read has changed, so the result keeps its identity otherwise. A function\n * value that cannot be computed gives a problem instead of values.\n */\nfunction useModelDataProps(\n surface: ManagedSurface,\n definition: ResolvedGenerativeUIComponent,\n properties: Record<string, unknown>,\n basePath: string | undefined,\n overrides: Record<string, unknown>,\n): ModelData {\n const dataModel = surface.model.dataModel;\n // The units to resolve: each model prop, and each field of the envelope's\n // `accessibility` on its own, so a label that cannot be computed does not\n // take the other fields with it.\n const units = useMemo(() => {\n const list: Array<{ key: string; raw: unknown; field?: string }> = [];\n for (const key of Object.keys(properties)) {\n if (\n definition.events?.[key] ||\n definition.slots?.[key] ||\n Object.hasOwn(definition.selectors, key) ||\n A2UI_COMPONENT_ENVELOPE_KEYS.has(key)\n ) {\n continue;\n }\n list.push({ key, raw: properties[key] });\n }\n const a11y = properties.accessibility;\n if (typeof a11y === \"object\" && a11y !== null && !Array.isArray(a11y)) {\n for (const [field, raw] of Object.entries(a11y)) {\n list.push({ key: `accessibility/${field}`, raw, field });\n }\n }\n return list;\n }, [properties, definition]);\n const [, rerender] = useReducer((n: number) => n + 1, 0);\n const cache = useRef(new Map<string, ResolvedProp>());\n const values: Record<string, unknown> = {};\n const a11yValues: Record<string, unknown> = {};\n const paths = new Set<string>();\n let problem: string | undefined;\n const next = new Map<string, ResolvedProp>();\n for (const { key, raw, field } of units) {\n const cached = cache.current.get(key);\n // A cached resolution holds while the raw prop, the template item and\n // every value it read are the same. A data model notification clears\n // the cache (below), because web_core changes lists and objects in\n // place, so a changed item inside one keeps the identity of the list.\n const isFresh =\n cached !== undefined &&\n cached.raw === raw &&\n cached.basePath === basePath &&\n [...cached.reads].every(([path, value]) =>\n Object.is(dataModel.get(path), value),\n );\n const resolve = (): ResolvedProp => {\n const resolved = tryResolveDynamicValue(\n raw,\n { data: dataModel, basePath },\n { isChecks: key === \"checks\" },\n );\n // The reads are kept also when the resolution failed, so the node\n // stays subscribed to the data that can fix it.\n const reads = new Map<string, unknown>();\n for (const path of resolved.paths) reads.set(path, dataModel.get(path));\n return {\n raw,\n basePath,\n reads,\n outcome: resolved.ok\n ? { ok: true, value: resolved.value }\n : { ok: false, message: resolved.error.message },\n };\n };\n const entry = isFresh && cached ? cached : resolve();\n next.set(key, entry);\n if (field !== undefined) {\n // The envelope is not a prop: a label that cannot be computed names\n // nothing, and the component is not at fault for it. Its reads stay\n // subscribed, so the data that fixes it brings the label.\n if (entry.outcome.ok) a11yValues[field] = entry.outcome.value;\n } else if (entry.outcome.ok) values[key] = entry.outcome.value;\n else problem ??= `${key}: ${entry.outcome.message}`;\n for (const path of entry.reads.keys()) paths.add(path);\n }\n cache.current = next;\n const accessibility = readAccessibility(a11yValues);\n for (const [key, value] of Object.entries(overrides)) {\n if (!isPathBinding(properties[key])) values[key] = value;\n }\n // The values this render was based on, so the effect can detect a write that\n // landed between render and subscription (web_core never replays the current\n // value on subscribe).\n const rendered = useRef(next);\n rendered.current = next;\n const pathKey = [...paths].sort().join(\"\\n\");\n useEffect(() => {\n const list = pathKey === \"\" ? [] : pathKey.split(\"\\n\");\n const onChange = () => {\n cache.current = new Map();\n rerender();\n };\n const subscriptions = list.map((path) =>\n dataModel.subscribe(path, onChange),\n );\n const isStale = [...rendered.current.values()].some((entry) =>\n [...entry.reads].some(\n ([path, value]) => !Object.is(dataModel.get(path), value),\n ),\n );\n if (isStale) rerender();\n return () => subscriptions.forEach((s) => s.unsubscribe());\n }, [dataModel, pathKey]);\n const stable = useRef<ModelData>({\n ok: true,\n values: {},\n accessibility: undefined,\n });\n const result: ModelData =\n problem === undefined\n ? { ok: true, values, accessibility }\n : { ok: false, problem };\n const last = stable.current;\n const isSame =\n result.ok && last.ok\n ? shallowEqual(last.values, result.values) &&\n shallowEqual(\n (last.accessibility ?? {}) as Record<string, unknown>,\n (result.accessibility ?? {}) as Record<string, unknown>,\n )\n : !result.ok && !last.ok && last.problem === result.problem;\n if (!isSame) stable.current = result;\n return stable.current;\n}\n\n/** The selector results of one node, or the reason they could not be read. */\ntype Selection =\n | { ok: true; values: Record<string, unknown> }\n | { ok: false; problem: string };\n\nconst NO_SELECTION: Selection = { ok: true, values: {} };\n\nfunction isSameSelection(a: Selection, b: Selection) {\n if (a.ok && b.ok) return shallowEqual(a.values, b.values);\n if (!a.ok && !b.ok) return a.problem === b.problem;\n return false;\n}\n\n/** Runs every selector of a node. A selector that throws gives a problem. */\nfunction select(\n definition: ResolvedGenerativeUIComponent,\n state: Readonly<Record<string, unknown>>,\n modelProps: Record<string, unknown>,\n): Selection {\n const values: Record<string, unknown> = {};\n const selectors = Object.entries(definition.selectors);\n for (const [key, selector] of selectors) {\n try {\n values[key] = selector(state, modelProps);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, problem: `${key}: selector threw: ${message}` };\n }\n }\n return { ok: true, values };\n}\n\ninterface SelectionCache {\n state: Readonly<Record<string, unknown>>;\n modelProps: Record<string, unknown>;\n selection: Selection;\n}\n\n/**\n * The values of the bound props of a node, read from the app state.\n *\n * The selectors run again only when the state object or the parsed model\n * props change. When the new values are shallow-equal to the last ones, the\n * last snapshot is kept. So the node re-renders only when a selected value\n * changes. A selector that returns a new array on each call cannot cause a\n * render loop: with the same inputs, the cached snapshot comes back.\n *\n * A node without bound props does not subscribe to the state.\n */\nfunction useSelection(\n manager: GenerativeUISurfaceManager,\n definition: ResolvedGenerativeUIComponent,\n modelProps: Record<string, unknown> | undefined,\n) {\n const hasSelectors = Object.keys(definition.selectors).length > 0;\n const cache = useRef<SelectionCache | undefined>(undefined);\n const getSnapshot = () => {\n if (!hasSelectors || modelProps === undefined) return NO_SELECTION;\n const state = manager.getState();\n const cached = cache.current;\n const isCacheHit =\n cached !== undefined &&\n cached.state === state &&\n cached.modelProps === modelProps;\n if (isCacheHit) return cached.selection;\n const next = select(definition, state, modelProps);\n const selection =\n cached !== undefined && isSameSelection(cached.selection, next)\n ? cached.selection\n : next;\n cache.current = { state, modelProps, selection };\n return selection;\n };\n // The server uses the same snapshot. It reads the state that is set now.\n return useSyncExternalStore(\n hasSelectors ? manager.subscribe : noopSubscribe,\n getSnapshot,\n getSnapshot,\n );\n}\n\ntype DataProps =\n | {\n ok: true;\n props: Record<string, unknown>;\n accessibility: GenerativeUIAccessibility | undefined;\n }\n | { ok: false; problem: string };\n\ntype ModelCheck =\n | { ok: true; values: Record<string, unknown> }\n | { ok: false; problem: string };\n\n/**\n * Checks the model-set props with the props schema before the selectors run.\n * The bound props are not set yet, so their issues do not count. Neither do\n * issues with no path (a check over several props), which the full check\n * after the selectors reports.\n */\nfunction checkModelProps(\n definition: ResolvedGenerativeUIComponent,\n modelData: Record<string, unknown>,\n): ModelCheck {\n if (!definition.props) return { ok: true, values: {} };\n let values = modelData;\n let result = validateSchemaSync(definition.props, values);\n if (!result.success) {\n // A null the schema rejects is an unset prop: check again without it.\n const unset = withoutRejectedNulls(values, result.issues);\n if (unset) {\n values = unset;\n result = validateSchemaSync(definition.props, values);\n }\n }\n if (!result.success) {\n const issues = result.issues.filter((issue) => {\n const key = issueKey(issue);\n return key === undefined\n ? isAsyncIssue(issue)\n : !Object.hasOwn(definition.selectors, key);\n });\n if (issues.length > 0) return { ok: false, problem: formatIssues(issues) };\n }\n return { ok: true, values };\n}\n\n/**\n * The data props of a node, in three steps: check the model-set props with\n * the props schema, run the selectors with them, then parse all props with\n * the props schema. Gives the reason when a step fails.\n */\nfunction useDataProps(\n runtime: GenerativeUIRuntime,\n surface: ManagedSurface,\n definition: ResolvedGenerativeUIComponent,\n properties: Record<string, unknown>,\n basePath: string | undefined,\n overrides: Record<string, unknown>,\n) {\n const modelData = useModelDataProps(\n surface,\n definition,\n properties,\n basePath,\n overrides,\n );\n const modelCheck = useMemo(\n () =>\n modelData.ok ? checkModelProps(definition, modelData.values) : modelData,\n [definition, modelData],\n );\n const selection = useSelection(\n runtime.manager,\n definition,\n modelCheck.ok ? modelCheck.values : undefined,\n );\n const accessibility = modelData.ok ? modelData.accessibility : undefined;\n return useMemo((): DataProps => {\n if (!modelCheck.ok) return modelCheck;\n if (!selection.ok) return selection;\n if (!definition.props) return { ok: true, props: {}, accessibility };\n const input = { ...modelCheck.values, ...selection.values };\n let parsed = validateSchemaSync(definition.props, input);\n if (!parsed.success) {\n // A null the schema rejects is an unset prop: validate without it.\n const unset = withoutRejectedNulls(input, parsed.issues);\n if (unset) parsed = validateSchemaSync(definition.props, unset);\n }\n if (!parsed.success) {\n return { ok: false, problem: formatIssues(parsed.issues) };\n }\n return {\n ok: true,\n props: parsed.data as Record<string, unknown>,\n accessibility,\n };\n }, [definition, modelCheck, selection, accessibility]);\n}\n\n/**\n * The event props of a node. A matched event (one that matches a declared\n * function) is always bound. An unmatched event is bound only when the model\n * bound it.\n */\nfunction useEventProps(\n runtime: GenerativeUIRuntime,\n surface: ManagedSurface,\n componentId: string,\n definition: ResolvedGenerativeUIComponent,\n properties: Record<string, unknown>,\n basePath: string | undefined,\n) {\n const latest = useRef(properties);\n latest.current = properties;\n const boundNames = Object.keys(definition.events ?? {})\n .filter(\n (name) =>\n Object.hasOwn(definition.eventFunctions, name) ||\n isActionBinding(properties[name]),\n )\n .join(\"|\");\n return useMemo(() => {\n const handlers: Record<\n string,\n (args?: unknown) => Promise<GenerativeUIInvokeResult>\n > = {};\n const names = boundNames ? boundNames.split(\"|\") : [];\n for (const name of names) {\n const call = {\n runtime,\n surface,\n componentId,\n name,\n parameters: definition.events?.[name]?.parameters,\n };\n const functionName = Object.hasOwn(definition.eventFunctions, name)\n ? definition.eventFunctions[name]\n : undefined;\n handlers[name] =\n functionName === undefined\n ? (args) =>\n invokeBoundEvent({\n ...call,\n binding: latest.current[name] as GenerativeUIActionBinding,\n basePath,\n args,\n })\n : (args) => invokeMatchedEvent({ ...call, functionName, args });\n }\n return handlers;\n }, [boundNames, runtime, surface, componentId, definition, basePath]);\n}\n\n/**\n * The setter props of a node: `setValue` for the writable prop `value`. For\n * a prop the model bound to `{\"@path\"}`, the setter writes the data model\n * and makes the path user-owned. For a literal prop, it sets `overrides`, a\n * local value of this mounted node. The setters keep their identity.\n */\nfunction useSetterProps(\n runtime: GenerativeUIRuntime,\n surface: ManagedSurface,\n componentId: string,\n definition: ResolvedGenerativeUIComponent,\n properties: Record<string, unknown>,\n basePath: string | undefined,\n) {\n const [overrides, setOverrides] = useState<Record<string, unknown>>({});\n const latest = useRef(properties);\n latest.current = properties;\n const setters = useMemo(() => {\n const result: Record<string, (value: unknown) => void> = {};\n const writable = definition.writable ?? [];\n for (const key of writable) {\n result[setterNameOf(key)] = (value) => {\n const binding = latest.current[key];\n if (!isPathBinding(binding)) {\n setOverrides((current) => ({ ...current, [key]: value }));\n return;\n }\n try {\n runtime.manager.setOwnedValue(\n surface.key,\n resolvePath(binding[\"@path\"], basePath),\n value,\n );\n } catch (cause) {\n const message =\n cause instanceof Error ? cause.message : String(cause);\n reportErrorSafely(runtime, {\n kind: \"props\",\n surfaceId: surface.surfaceId,\n componentId,\n error: new Error(`${setterNameOf(key)}: ${message}`),\n });\n }\n };\n }\n return result;\n }, [runtime, surface, componentId, definition, basePath]);\n return { overrides, setters };\n}\n\nfunction useSlotProps(\n surface: ManagedSurface,\n definition: ResolvedGenerativeUIComponent,\n properties: Record<string, unknown>,\n componentId: string,\n basePath: string | undefined,\n ancestors: readonly string[],\n) {\n return useMemo(() => {\n const childAncestors = [...ancestors, scopedId(componentId, basePath)];\n const slots: Record<string, ReactNode> = {};\n for (const [name, kind] of Object.entries(definition.slots ?? {})) {\n const value = properties[name];\n if (kind === \"single\" && typeof value === \"string\") {\n slots[name] = (\n <NodeView\n surface={surface}\n componentId={value}\n basePath={basePath}\n ancestors={childAncestors}\n />\n );\n } else if (kind === \"multiple\" && isTemplateChildren(value)) {\n slots[name] = (\n <TemplateChildren\n surface={surface}\n template={value}\n basePath={basePath}\n ancestors={childAncestors}\n />\n );\n } else if (kind === \"multiple\" && Array.isArray(value)) {\n // Dedupe so React keys stay unique if the agent repeats an id.\n const ids = [\n ...new Set(\n value.filter((id): id is string => typeof id === \"string\"),\n ),\n ];\n slots[name] = ids.map((id) => (\n <NodeView\n key={id}\n surface={surface}\n componentId={id}\n basePath={basePath}\n ancestors={childAncestors}\n />\n ));\n }\n }\n return slots;\n }, [surface, definition, properties, componentId, basePath, ancestors]);\n}\n\n/**\n * The parsed data props with every typed child reference (`child()`,\n * `childList()`, at any depth) replaced by the rendered component. Without\n * references, the parsed props come back as they are.\n */\nfunction useChildRefProps(\n surface: ManagedSurface,\n refs: readonly ChildRef[],\n props: Record<string, unknown> | undefined,\n componentId: string,\n basePath: string | undefined,\n ancestors: readonly string[],\n) {\n return useMemo(() => {\n if (props === undefined || refs.length === 0) return props;\n const childAncestors = [...ancestors, scopedId(componentId, basePath)];\n const render = (kind: ChildRef[\"kind\"], value: unknown): unknown => {\n if (kind === \"single\") {\n return typeof value === \"string\" ? (\n <NodeView\n surface={surface}\n componentId={value}\n basePath={basePath}\n ancestors={childAncestors}\n />\n ) : undefined;\n }\n if (isTemplateChildren(value)) {\n return (\n <TemplateChildren\n surface={surface}\n template={value}\n basePath={basePath}\n ancestors={childAncestors}\n />\n );\n }\n if (!Array.isArray(value)) return undefined;\n const ids = [\n ...new Set(value.filter((id): id is string => typeof id === \"string\")),\n ];\n return ids.map((id) => (\n <NodeView\n key={id}\n surface={surface}\n componentId={id}\n basePath={basePath}\n ancestors={childAncestors}\n />\n ));\n };\n let result: unknown = props;\n for (const ref of refs) {\n result = mapAtChildRef(result, ref.path, (found) =>\n render(ref.kind, found),\n );\n }\n return result as Record<string, unknown>;\n }, [surface, refs, props, componentId, basePath, ancestors]);\n}\n\nfunction ResolvedNode({\n surface,\n componentId,\n definition,\n properties,\n runtime,\n basePath,\n ancestors,\n}: {\n surface: ManagedSurface;\n componentId: string;\n definition: ResolvedGenerativeUIComponent;\n properties: Record<string, unknown>;\n runtime: GenerativeUIRuntime;\n basePath: string | undefined;\n ancestors: readonly string[];\n}) {\n const { overrides, setters } = useSetterProps(\n runtime,\n surface,\n componentId,\n definition,\n properties,\n basePath,\n );\n const dataProps = useDataProps(\n runtime,\n surface,\n definition,\n properties,\n basePath,\n overrides,\n );\n const eventProps = useEventProps(\n runtime,\n surface,\n componentId,\n definition,\n properties,\n basePath,\n );\n const slotProps = useSlotProps(\n surface,\n definition,\n properties,\n componentId,\n basePath,\n ancestors,\n );\n const childRefProps = useChildRefProps(\n surface,\n definition.childRefs,\n dataProps.ok ? dataProps.props : undefined,\n componentId,\n basePath,\n ancestors,\n );\n const accessibility = dataProps.ok ? dataProps.accessibility : undefined;\n const nodeContext = useMemo(\n () => ({\n surfaceKey: surface.key,\n surfaceId: surface.surfaceId,\n componentId,\n accessibility,\n }),\n [surface.key, surface.surfaceId, componentId, accessibility],\n );\n const problem = dataProps.ok ? undefined : dataProps.problem;\n\n useEffect(() => {\n if (problem) {\n reportErrorSafely(runtime, {\n kind: \"props\",\n surfaceId: surface.surfaceId,\n componentId,\n error: new Error(`Invalid props: ${problem}`),\n });\n }\n }, [problem, runtime, surface.surfaceId, componentId]);\n\n if (!dataProps.ok) {\n return (\n <DefaultNodeFallback\n message={`invalid props (${problem})`}\n componentId={componentId}\n />\n );\n }\n const Component = definition.component;\n const rendered = (\n <Component {...childRefProps} {...eventProps} {...slotProps} {...setters} />\n );\n // The hidden state and the live region of the envelope apply to every\n // component here, in a wrapper with no box of its own. A label or a\n // description needs an element with a role, so the component sets those\n // itself (the standard ones do; see useGenerativeUIAccessibility). The\n // wrapper is there whenever the component has an envelope (unless the\n // component applies the envelope itself: a table row or cell cannot sit\n // in a span), whatever its values: a bound `hidden` that flips must not remount the component and\n // lose what the user typed into it. A component that is sent again with\n // an envelope added or removed does remount: a wrapper on every node\n // would break the stylesheet's child selectors (table rows and cells,\n // the last text of a spaceBetween row), and bound inputs keep their\n // values in the data model anyway.\n const hasEnvelope =\n properties.accessibility !== undefined &&\n definition.accessibility !== \"self\";\n return (\n <GenerativeUINodeContext.Provider value={nodeContext}>\n {hasEnvelope ? (\n <span\n data-a2ui-accessibility=\"\"\n style={ROOT_STYLE}\n {...wrapperAria(accessibilityAttributes(accessibility))}\n >\n {rendered}\n </span>\n ) : (\n rendered\n )}\n </GenerativeUINodeContext.Provider>\n );\n}\n","import React, {\n createContext,\n useContext,\n useEffect,\n useLayoutEffect,\n} from \"react\";\nimport type { ComponentType, ReactNode } from \"react\";\nimport { z } from \"zod\";\nimport {\n GENERATIVE_UI_ACTIVITY_TYPE,\n GENERATIVE_UI_CHAT_TARGET,\n GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,\n GENERATIVE_UI_RENDER_TOOL,\n} from \"@copilotkit/shared\";\nimport type {\n GenerativeUIRejectedOperation,\n GenerativeUISurfaceContent,\n} from \"@copilotkit/shared\";\n// From ../context, not the provider module: the provider imports this file.\nimport { useCopilotKit } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { defineToolCallRenderer } from \"../types/defineToolCallRenderer\";\nimport type { ReactActivityMessageRenderer } from \"../types/react-activity-message-renderer\";\nimport { useManagerVersion } from \"./hooks\";\nimport { useGenerativeUIRuntime } from \"./runtime-context\";\nimport { SurfaceView } from \"./SurfaceView\";\n\nexport interface GenerativeUIChatSurfaceProps {\n surfaceId: string;\n isStreaming: boolean;\n /**\n * Set when operations from the latest render_ui call were rejected. The\n * message is user-facing; `error.cause` holds the same list as `rejected`.\n */\n error?: Error;\n /** Rejected operations from the latest render_ui call, with validator reasons. */\n rejected: GenerativeUIRejectedOperation[];\n children: ReactNode;\n}\n\nexport const GenerativeUIChatSlotContext = createContext<\n ComponentType<GenerativeUIChatSurfaceProps> | undefined\n>(undefined);\n\nexport function DefaultGenerativeUIChatCard({\n surfaceId,\n isStreaming,\n error,\n children,\n}: GenerativeUIChatSurfaceProps) {\n return (\n <div\n data-generative-ui-chat-surface={surfaceId}\n className=\"cpk:my-2 cpk:w-full cpk:rounded-xl cpk:border cpk:border-gray-200 cpk:p-3\"\n >\n {children}\n {error && (\n <div role=\"alert\" className=\"cpk:mt-2 cpk:text-xs cpk:text-red-600\">\n Part of this UI couldn't be shown.\n </div>\n )}\n </div>\n );\n}\n\nconst ContentSchema = z\n .object({\n surfaceId: z.string(),\n target: z.string(),\n catalogId: z.string(),\n operations: z.array(z.any()),\n status: z.enum([\"streaming\", \"ready\", \"error\"]),\n rejected: z\n .array(z.object({ index: z.number(), reason: z.string() }))\n .default([]),\n })\n .passthrough();\n\nfunction GenerativeUIChatActivity({\n content,\n agent,\n}: {\n content: GenerativeUISurfaceContent;\n agent: { threadId?: string; agentId?: string } | undefined;\n}) {\n const runtime = useGenerativeUIRuntime();\n const threadId = useCopilotChatConfiguration()?.threadId ?? agent?.threadId;\n const Wrapper =\n useContext(GenerativeUIChatSlotContext) ?? DefaultGenerativeUIChatCard;\n useManagerVersion(runtime);\n useLayoutEffect(() => {\n if (runtime && threadId)\n runtime.manager.ingest(threadId, agent?.agentId, content);\n }, [runtime, threadId, agent?.agentId, content]);\n\n if (!runtime || !threadId || content.target !== GENERATIVE_UI_CHAT_TARGET)\n return null;\n // A surface whose createSurface was rejected shows only the error.\n const surface =\n runtime.manager.getSurface(threadId, content.surfaceId) ??\n runtime.manager.getFailedSurface(threadId, content.surfaceId);\n if (!surface) return null;\n // Both lists cover only the latest render_ui call (see the manager's ingest).\n // Custom wrappers get the detailed reasons (`rejected`, `error.cause`), and\n // client-side ones also reach `errorBoundary.onError`; the default card\n // shows a generic message.\n const rejected = [...(content.rejected ?? []), ...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={content.surfaceId}\n isStreaming={content.status === \"streaming\"}\n error={error}\n rejected={rejected}\n >\n {surface.failed ? null : <SurfaceView surface={surface} />}\n </Wrapper>\n );\n}\n\nexport function createGenerativeUIActivityRenderer(): ReactActivityMessageRenderer<GenerativeUISurfaceContent> {\n return {\n activityType: GENERATIVE_UI_ACTIVITY_TYPE,\n content:\n ContentSchema as unknown as ReactActivityMessageRenderer<GenerativeUISurfaceContent>[\"content\"],\n render:\n GenerativeUIChatActivity as ReactActivityMessageRenderer<GenerativeUISurfaceContent>[\"render\"],\n };\n}\n\n/**\n * Shows nothing in the chat for an agent-called function. The root reads the\n * function-call activities from the messages and runs them. This renderer\n * only keeps a wildcard (\"*\") activity renderer from showing them.\n */\nexport function createGenerativeUIFunctionCallActivityRenderer(): ReactActivityMessageRenderer<unknown> {\n return {\n activityType: GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,\n content: z.unknown(),\n render: () => null,\n };\n}\n\n/** Hides the raw `render_ui` tool call; the surface activity owns the UX. */\nexport function GenerativeUIToolCallRenderer(): null {\n const { copilotkit } = useCopilotKit();\n useEffect(() => {\n const renderer = defineToolCallRenderer({\n name: GENERATIVE_UI_RENDER_TOOL,\n args: z.any(),\n render: () => <></>,\n });\n const existing = (copilotkit as any)._renderToolCalls ?? [];\n copilotkit.setRenderToolCalls([\n ...existing.filter((rc: any) => rc.name !== GENERATIVE_UI_RENDER_TOOL),\n renderer,\n ]);\n }, [copilotkit]);\n return null;\n}\n","import React, { useContext, useInsertionEffect, useMemo } from \"react\";\nimport type { ComponentProps, ComponentType } from \"react\";\nimport { Streamdown } from \"streamdown\";\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 { getMarkdownSurfaceSource } from \"@copilotkit/core/generative-ui\";\nimport type { MarkdownFenceBlock } from \"@copilotkit/core/generative-ui\";\n\ntype MarkdownProps = Omit<ComponentProps<typeof Streamdown>, \"children\">;\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:relative cpk:my-4 cpk:flex cpk:w-full cpk:min-w-0 cpk:max-w-full cpk:flex-col\"\n >\n {children}\n {error && (\n <div role=\"alert\" className=\"cpk:mt-2 cpk:text-xs cpk:text-red-600\">\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};\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 markdownProps,\n}: {\n blocks: MarkdownFenceBlock[];\n runtime: GenerativeUIRuntime;\n threadId: string;\n markdownProps: MarkdownProps;\n}) {\n const Wrapper =\n useContext(GenerativeUIChatSlotContext) ?? DefaultMarkdownChatSurface;\n let surfaceCount = 0;\n return (\n <>\n {blocks.map((block) => {\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 <Streamdown key={`md-${surfaceCount}`} {...markdownProps}>\n {block.markdown}\n </Streamdown>\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 ...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 if (segment.type === \"markdown\") {\n return (\n <Streamdown key={`md-${index}`} {...markdownProps}>\n {segment.text}\n </Streamdown>\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 markdownProps={markdownProps}\n />\n );\n })}\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA,SAAgB,aACd,MACA,MACS;CACT,MAAM,QAAQ,OAAO,KAAK,KAAK;CAC/B,MAAM,QAAQ,OAAO,KAAK,KAAK;AAE/B,KAAI,MAAM,WAAW,MAAM,OAAQ,QAAO;AAE1C,MAAK,MAAM,OAAO,MAChB,KAAI,KAAK,SAAS,KAAK,KAAM,QAAO;AAGtC,QAAO;;;;;;AAOT,SAAS,cAAc,KAA8C;AACnE,QACE,QAAQ,QACR,OAAO,QAAQ,YACf,OAAO,UAAU,SAAS,KAAK,IAAI,KAAK;;;;;;;;;;;;;;;AAiB5C,SAAgB,oBAAuB,OAAa;CAClD,MAAM,MAAM,OAAO,MAAM;AAGzB,KAAI,IAAI,YAAY,MAAO,QAAO,IAAI;AAGtC,KAAI,cAAc,IAAI,QAAQ,IAAI,cAAc,MAAM,EACpD;MAAI,aAAa,IAAI,SAAS,MAAM,CAAE,QAAO,IAAI;;AAInD,KAAI,UAAU;AACd,QAAO,IAAI;;;;;AC/Cb,MAAa,2BAA2B;CACtC,sBAAsB;CACtB,4CAA4C;CAC5C,6CAA6C;CAC7C,6CAA6C;CAC7C,gCAAgC;CAChC,kCAAkC;C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