@copilotkit/react-core 1.80.0 → 1.81.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 (46) hide show
  1. package/dist/MarkdownSurfaces-D-OkjUpU.cjs +3807 -0
  2. package/dist/MarkdownSurfaces-D-OkjUpU.cjs.map +1 -0
  3. package/dist/MarkdownSurfaces-L67964_B.mjs +3522 -0
  4. package/dist/MarkdownSurfaces-L67964_B.mjs.map +1 -0
  5. package/dist/{copilotkit-CWOSXhRO.d.mts → copilotkit-BEcaM4L4.d.mts} +25 -34
  6. package/dist/copilotkit-BEcaM4L4.d.mts.map +1 -0
  7. package/dist/{copilotkit-DKICi3nC.cjs → copilotkit-BjllYYjw.cjs} +2022 -600
  8. package/dist/copilotkit-BjllYYjw.cjs.map +1 -0
  9. package/dist/{copilotkit-Dfw9HzO9.d.cts → copilotkit-D9jIImy9.d.cts} +25 -34
  10. package/dist/copilotkit-D9jIImy9.d.cts.map +1 -0
  11. package/dist/{copilotkit-BNLtgOyD.mjs → copilotkit-fKrKqoiP.mjs} +1966 -493
  12. package/dist/copilotkit-fKrKqoiP.mjs.map +1 -0
  13. package/dist/index.cjs +8 -7
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +2 -1
  16. package/dist/index.d.cts.map +1 -1
  17. package/dist/index.d.mts +2 -1
  18. package/dist/index.d.mts.map +1 -1
  19. package/dist/index.mjs +2 -1
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/index.umd.js +4463 -9
  22. package/dist/index.umd.js.map +1 -1
  23. package/dist/runtime-context-CrHq-iTf.d.mts +924 -0
  24. package/dist/runtime-context-CrHq-iTf.d.mts.map +1 -0
  25. package/dist/runtime-context-D3NcP9oE.d.cts +924 -0
  26. package/dist/runtime-context-D3NcP9oE.d.cts.map +1 -0
  27. package/dist/v2/generative-ui.cjs +8154 -0
  28. package/dist/v2/generative-ui.cjs.map +1 -0
  29. package/dist/v2/generative-ui.d.cts +4950 -0
  30. package/dist/v2/generative-ui.d.cts.map +1 -0
  31. package/dist/v2/generative-ui.d.mts +4950 -0
  32. package/dist/v2/generative-ui.d.mts.map +1 -0
  33. package/dist/v2/generative-ui.mjs +8140 -0
  34. package/dist/v2/generative-ui.mjs.map +1 -0
  35. package/dist/v2/index.cjs +65 -4
  36. package/dist/v2/index.css +1 -1
  37. package/dist/v2/index.d.cts +3 -2
  38. package/dist/v2/index.d.mts +3 -2
  39. package/dist/v2/index.mjs +3 -2
  40. package/dist/v2/index.umd.js +4832 -180
  41. package/dist/v2/index.umd.js.map +1 -1
  42. package/package.json +21 -8
  43. package/dist/copilotkit-BNLtgOyD.mjs.map +0 -1
  44. package/dist/copilotkit-CWOSXhRO.d.mts.map +0 -1
  45. package/dist/copilotkit-DKICi3nC.cjs.map +0 -1
  46. package/dist/copilotkit-Dfw9HzO9.d.cts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MarkdownSurfaces-D-OkjUpU.cjs","names":["DEFAULT_AGENT_ID","CopilotKitContext","z","A2UI_COMPONENT_ENVELOPE_KEYS","numberOf","GENERATIVE_UI_FUNCTIONS","GENERATIVE_UI_ROOT_ID","getMarkdownOperationSurfaceId","GENERATIVE_UI_CHAT_TARGET","A2UI_VERSION","A2UI_INDEX_FUNCTION","noopSubscribe","Component","GENERATIVE_UI_ROOT_ID","A2UI_COMPONENT_ENVELOPE_KEYS","z","GENERATIVE_UI_CHAT_TARGET","GENERATIVE_UI_ACTIVITY_TYPE","GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE","GENERATIVE_UI_RENDER_TOOL","useInsertionEffect","GENERATIVE_UI_ROOT_ID","Streamdown"],"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/json-schema.ts","../src/v2/generative-ui/catalog.ts","../src/v2/generative-ui/is-record.ts","../src/v2/generative-ui/errors.ts","../src/v2/generative-ui/functions.ts","../src/v2/generative-ui/markdown/source.ts","../src/v2/generative-ui/calc.ts","../src/v2/generative-ui/resolve.ts","../src/v2/generative-ui/schema.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/events.ts","../src/v2/generative-ui/theme.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 modalHeaderTitle: \"CopilotKit Chat\",\n welcomeMessageText: \"How can I help you today?\",\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 { applyChildRefMarks, schemaToJsonSchema } from \"@copilotkit/shared\";\nimport type {\n GenerativeUIJSONSchema,\n StandardSchemaV1,\n} from \"@copilotkit/shared\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\nimport type { z } from \"zod\";\n\n/**\n * JSON Schema for a Standard Schema (zod v3 via zod-to-json-schema),\n * inlined, no `$schema`. A prop marked by `child()` or `childList()`\n * becomes an A2UI `$ref` to `ComponentId` or `ChildList`.\n */\nexport function toJsonSchema(schema: StandardSchemaV1): GenerativeUIJSONSchema {\n const json = schemaToJsonSchema(schema, {\n zodToJsonSchema: (s: unknown) =>\n zodToJsonSchema(s as z.ZodType, { $refStrategy: \"none\" }) as Record<\n string,\n unknown\n >,\n });\n const { $schema: _omit, ...rest } = json as Record<string, unknown>;\n return applyChildRefMarks(rest);\n}\n","import type { ComponentType, ReactNode } from \"react\";\nimport {\n A2UI_COMPONENT_ENVELOPE_KEYS,\n collectChildRefs,\n functionCallers,\n} from \"@copilotkit/shared\";\nimport type {\n A2UIFunctionPermissions,\n A2UIFunctionReturnType,\n ChildRef,\n GenerativeUIComponentManifest,\n GenerativeUIJSONSchema,\n StandardSchemaV1,\n} from \"@copilotkit/shared\";\nimport type { GenerativeUIInvokeResult } from \"./errors\";\nimport { toJsonSchema } from \"./json-schema\";\nimport type { GenerativeUISchema, SchemaInput, SchemaOutput } from \"./schema\";\n\nexport type GenerativeUISlotKind = \"single\" | \"multiple\";\n\n/**\n * The schema of the props of a component: any Standard Schema of an object,\n * for example `z.object({ ... })` or `v.object({ ... })`. The model gets\n * the props as JSON Schema, so the schema must give one: Standard JSON\n * Schema (zod 4.2+, ArkType, Valibot with `toStandardJsonSchema`) or zod 3.\n * It must validate synchronously, because props are checked while a\n * surface renders.\n */\nexport type PropsSchema = StandardSchemaV1<\n Record<string, unknown>,\n Record<string, unknown>\n>;\n\n/** An event prop of a component. */\nexport interface GenerativeUIEventDefinition {\n description?: string;\n /**\n * Arguments the component passes when it calls the event prop. An event\n * that matches a declared function can leave this out. Then the function\n * parameters are used.\n */\n parameters?: GenerativeUISchema;\n}\n\n/**\n * A function that generated UI can call. The handler comes from\n * `useGenerativeUIFunction`.\n */\nexport interface GenerativeUIFunctionDefinition extends A2UIFunctionPermissions {\n description?: string;\n parameters: GenerativeUISchema;\n /**\n * Who may call it. `\"rendererOnly\"` (the default, as in A2UI 1.0): event\n * bindings and prop values. `\"agentOnly\"`: `callRendererFunction`.\n * `\"rendererOrAgent\"`: both. The agent calls only what you allow.\n */\n allowedCallers?: A2UIFunctionPermissions[\"allowedCallers\"];\n /**\n * True for a function that runs only from a user gesture, like `openUrl`.\n * It is then for the renderer only.\n */\n requiresUserActivation?: boolean;\n /** What the handler gives back, as A2UI 1.0 names it. */\n returnType?: A2UIFunctionReturnType;\n}\n\n/**\n * Gives a bound prop its value. It gets the full state and the model-set\n * props of the node, before the props schema parses them (no defaults or\n * transforms). It runs in the browser and must be pure.\n */\nexport type GenerativeUISelector = (\n state: Record<string, unknown>,\n props: Record<string, unknown>,\n) => unknown;\n\n/**\n * Method syntax makes the parameters bivariant. So a selector with typed\n * parameters fits this runtime type.\n */\ntype RuntimeSelector = {\n select(\n state: Record<string, unknown>,\n props: Record<string, unknown>,\n ): unknown;\n}[\"select\"];\n\n/** One component of a generative UI, as the renderer reads it. */\nexport interface GenerativeUIComponentDefinition {\n component: ComponentType<any>;\n description?: string;\n /**\n * Positional prefix across props, slots and events for catalog consumers.\n * Remaining visible keys follow in declaration order (props, slots, events).\n * A2UI exports encode this as property order, not a protocol field.\n */\n parameterOrder?: readonly string[];\n /** All data props: the props the model sets and the bound props. */\n props?: PropsSchema;\n /** Explicit selectors for bound props. */\n bind?: Record<string, RuntimeSelector>;\n /** Callback props. */\n events?: Record<string, GenerativeUIEventDefinition>;\n /**\n * Child props, filled with rendered child components. A \"multiple\" slot\n * takes a list of component ids, or a template `{ componentId, path }`\n * that renders one component for each item of the list at `path`.\n */\n slots?: Record<string, GenerativeUISlotKind>;\n /**\n * Props that the component can write. Each one gets a setter prop named\n * `set` + the prop name: `value` gets `setValue`. When the model binds the\n * prop to `{ \"@path\" }`, the setter writes the surface data model at that\n * path, and the agent can no longer change that path. Else the setter\n * changes local state only.\n */\n writable?: readonly string[];\n /**\n * Who applies the `accessibility` envelope of the component: by default\n * the engine, in a wrapper element around the component. `\"self\"` for a\n * component that must not be wrapped (a table row or cell) and applies\n * the attributes itself with `useGenerativeUIAccessibility()`.\n */\n accessibility?: \"wrapper\" | \"self\";\n}\n\n/** A component after `createGenerativeUI` resolved its bindings. */\nexport interface ResolvedGenerativeUIComponent extends GenerativeUIComponentDefinition {\n /**\n * One selector for each bound prop. A prop with the name of a top-level\n * state key reads `state[key]`. A `bind` entry wins over the name rule.\n */\n selectors: Record<string, GenerativeUISelector>;\n /** Event name to the name of the declared function it calls. */\n eventFunctions: Record<string, string>;\n /** The keys of `props`, read from its JSON Schema. */\n propKeys: readonly string[];\n /**\n * The component references in `props` (`child()`, `childList()`), at any\n * depth. The renderer replaces each one with the rendered component. The\n * `slots` of the definition are not in here.\n */\n childRefs: readonly ChildRef[];\n /** Who applies the `accessibility` envelope; see the definition. */\n accessibility: \"wrapper\" | \"self\";\n}\n\n/** Type-level data of one component, kept in `GenerativeUI[\"definitions\"]`. */\nexport interface GenerativeUIComponentTypes {\n /** The `props` schema, or `unknown` when the component has none. */\n props: unknown;\n /** The `events` object, or `unknown` when the component has none. */\n events: unknown;\n /** The `slots` object, or `unknown` when the component has none. */\n slots: unknown;\n /** The `writable` list, or `unknown` when the component has none. */\n writable: unknown;\n}\n\n/** Type-level data of a generative UI, with the keys of its bases merged in. */\nexport interface GenerativeUIDefinitions {\n state: Record<string, GenerativeUISchema>;\n functions: Record<string, GenerativeUIFunctionDefinition>;\n components: Record<string, GenerativeUIComponentTypes>;\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 interface GenerativeUI<\n Definitions extends GenerativeUIDefinitions = GenerativeUIDefinitions,\n> {\n /** Surfaces pin to this id. */\n readonly id: string;\n /** State schemas, bases first. */\n readonly state: ReadonlyMap<string, GenerativeUISchema>;\n /** Declared functions, bases first. */\n readonly functions: ReadonlyMap<string, GenerativeUIFunctionDefinition>;\n /** Components, bases first. */\n readonly components: ReadonlyMap<string, ResolvedGenerativeUIComponent>;\n /** What the model sees: model-set props and unmatched events only. */\n readonly manifestComponents: Record<string, GenerativeUIComponentManifest>;\n /** Type only, never set at runtime. */\n readonly definitions?: Definitions;\n /**\n * A copy without the named components. The model no longer sees them, so\n * the prompt gets smaller. State and functions stay. Call it once, at\n * module level, like `createGenerativeUI`.\n *\n * @throws Error when a name is not a component of this UI.\n *\n * @example\n * ```ts\n * const ui = createGenerativeUI({\n * id: \"acme/app@1\",\n * extends: [standardUI.omit([\"Map\", \"Chart\"])],\n * components: {},\n * });\n * ```\n */\n omit<Names extends keyof Definitions[\"components\"] & string>(\n names: readonly Names[],\n ): GenerativeUI<OmitComponents<Definitions, Names>>;\n}\n\n/** Definitions without some components. */\ntype OmitComponents<\n Definitions extends GenerativeUIDefinitions,\n Names extends PropertyKey,\n> = {\n state: Definitions[\"state\"];\n functions: Definitions[\"functions\"];\n components: Omit<Definitions[\"components\"], Names>;\n};\n\ntype AnyGenerativeUI = GenerativeUI<any>;\n\n/**\n * Any function or class component. Unlike `ComponentType`, checking a value\n * against it does not read the component's props type. So a component can\n * type its props from `typeof ui` without a circular type reference.\n */\ntype AnyComponent =\n | ((...args: never) => unknown)\n | (abstract new (...args: never) => unknown);\n\ntype Simplify<T> = { [Key in keyof T]: T[Key] } & {};\n\n/** `A | B` to `A & B`. */\nexport type UnionToIntersection<U> = (\n U extends unknown ? (value: U) => void : never\n) extends (value: infer I) => void\n ? I\n : never;\n\ntype OutputOf<Schema> = SchemaOutput<Schema>;\ntype InputOf<Schema> = SchemaInput<Schema>;\n/** The prop names. None for a component without `props`. */\ntype PropKeys<Props> = Props extends PropsSchema\n ? keyof OutputOf<Props> & string\n : never;\n/** The input type of one prop of a props schema. */\ntype PropInput<Props, Key> = Key extends keyof InputOf<Props>\n ? InputOf<Props>[Key]\n : never;\n\n/** The type-level data of a generative UI. */\nexport type GenerativeUIDefinitionsOf<UI extends AnyGenerativeUI> = NonNullable<\n UI[\"definitions\"]\n>;\n\ntype StateValues<State> = Simplify<{\n [Key in keyof State]: OutputOf<State[Key]>;\n}>;\n\n/**\n * The state object of a generative UI, bases included. Selectors get it, and\n * `useGenerativeUIState(ui, key, value)` sets one key of it.\n */\nexport type GenerativeUIStateOf<UI extends AnyGenerativeUI> = StateValues<\n GenerativeUIDefinitionsOf<UI>[\"state\"]\n>;\n\n/** The declared functions of a generative UI, bases included. */\nexport type GenerativeUIFunctionsOf<UI extends AnyGenerativeUI> =\n GenerativeUIDefinitionsOf<UI>[\"functions\"];\n\n/** The name of a declared function of a generative UI. */\nexport type GenerativeUIFunctionName<UI extends AnyGenerativeUI> =\n keyof GenerativeUIFunctionsOf<UI> & string;\n\n/**\n * The name of a component of a generative UI, bases included. For\n * `GenerativeUI<any>`, it is `string`.\n */\nexport type GenerativeUIComponentName<UI extends AnyGenerativeUI> =\n keyof GenerativeUIDefinitionsOf<UI>[\"components\"] & string;\n\ntype FunctionInput<Functions, Name> = Name extends keyof Functions\n ? Functions[Name] extends GenerativeUIFunctionDefinition\n ? InputOf<Functions[Name][\"parameters\"]>\n : never\n : never;\n\n/** What a caller passes to a declared function (the schema input). */\nexport type GenerativeUIFunctionInput<\n UI extends AnyGenerativeUI,\n Name extends GenerativeUIFunctionName<UI>,\n> = FunctionInput<GenerativeUIFunctionsOf<UI>, Name>;\n\n/**\n * What the handler of a declared function gets: the parsed arguments (the\n * schema output, with defaults set).\n */\nexport type GenerativeUIFunctionArgs<\n UI extends AnyGenerativeUI,\n Name extends GenerativeUIFunctionName<UI>,\n> = OutputOf<GenerativeUIFunctionsOf<UI>[Name][\"parameters\"]>;\n\n/**\n * The function an event calls: the function with the same name, else the\n * name without `on` and with a lowercase first letter. `never` when none.\n */\ntype MatchedFunction<\n Name extends string,\n Functions,\n> = Name extends keyof Functions\n ? Name\n : Name extends `on${infer Rest}`\n ? Uncapitalize<Rest> extends keyof Functions\n ? Uncapitalize<Rest>\n : never\n : never;\n\n/**\n * The argument type of an event prop. The event `parameters` input when it\n * declares them, else the input of the matched function.\n */\nexport type GenerativeUIEventInput<\n Name extends string,\n Event,\n Functions,\n> = \"parameters\" extends keyof Event\n ? InputOf<Event[\"parameters\" & keyof Event]>\n : FunctionInput<Functions, MatchedFunction<Name, Functions>>;\n\ntype DataProps<Props> = Props extends PropsSchema ? OutputOf<Props> : {};\n\ntype EventProps<Events, Functions> =\n Events extends Record<string, unknown>\n ? {\n [Name in keyof Events]?: (\n args: GenerativeUIEventInput<Name & string, Events[Name], Functions>,\n ) => Promise<GenerativeUIInvokeResult>;\n }\n : {};\n\ntype SlotProps<Slots> =\n Slots extends Record<string, unknown>\n ? { [Name in keyof Slots]?: ReactNode }\n : {};\n\ntype WritableKeys<Writable> = Writable extends readonly (infer Key)[]\n ? Key & string\n : never;\n\n/** One setter for each writable prop: `value` gets `setValue`. */\ntype SetterProps<Props, Writable> = {\n [Key in WritableKeys<Writable> &\n PropKeys<Props> as `set${Capitalize<Key>}`]: (\n value: PropInput<Props, Key>,\n ) => void;\n};\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 GenerativeUIDefinitionsOf<UI>[\"components\"] & string,\n> = Simplify<\n DataProps<GenerativeUIDefinitionsOf<UI>[\"components\"][Name][\"props\"]> &\n EventProps<\n GenerativeUIDefinitionsOf<UI>[\"components\"][Name][\"events\"],\n GenerativeUIDefinitionsOf<UI>[\"functions\"]\n > &\n SlotProps<GenerativeUIDefinitionsOf<UI>[\"components\"][Name][\"slots\"]> &\n SetterProps<\n GenerativeUIDefinitionsOf<UI>[\"components\"][Name][\"props\"],\n GenerativeUIDefinitionsOf<UI>[\"components\"][Name][\"writable\"]\n >\n>;\n\n// ---- Config types ----\n\ntype BaseDefinitions<Bases extends readonly AnyGenerativeUI[]> =\n GenerativeUIDefinitionsOf<Bases[number]>;\n\ntype MergedState<Bases extends readonly AnyGenerativeUI[], State> = Simplify<\n UnionToIntersection<BaseDefinitions<Bases>[\"state\"]> & State\n>;\n\ntype MergedFunctions<\n Bases extends readonly AnyGenerativeUI[],\n Functions,\n> = Simplify<\n UnionToIntersection<BaseDefinitions<Bases>[\"functions\"]> & Functions\n>;\n\n/** Props keys with the name of a top-level state key. */\ntype NameKeys<Props, State> = PropKeys<Props> & keyof State;\n\ntype SelectorFor<Props, State, Key extends PropKeys<Props>> = (\n state: StateValues<State>,\n // ponytail: the type hides the name-bound keys and the key itself. Other `bind` keys stay in it, because TypeScript cannot read the `bind` keys before it types the selectors.\n props: Simplify<Omit<InputOf<Props>, NameKeys<Props, State> | Key>>,\n) => PropInput<Props, Key>;\n\ntype BindSelectors<Props, State> = {\n [Key in PropKeys<Props>]?: SelectorFor<Props, State, Key>;\n};\n\n/** Name-bound keys whose state type does not fit the prop schema input. */\ntype MismatchedNameKeys<Props, State> = {\n [Key in NameKeys<Props, State>]: [OutputOf<State[Key]>] extends [\n PropInput<Props, Key>,\n ]\n ? never\n : Key;\n}[NameKeys<Props, State>];\n\n/**\n * `bind` is optional. When a prop has the name of a state key but the state\n * type does not fit, `bind` must give that prop a selector.\n */\ntype BindField<Props, State> = [MismatchedNameKeys<Props, State>] extends [\n never,\n]\n ? { bind?: BindSelectors<Props, State> }\n : {\n bind: BindSelectors<Props, State> & {\n [Key in MismatchedNameKeys<Props, State>]-?: SelectorFor<\n Props,\n State,\n Key\n >;\n };\n };\n\n/** `unknown` (no props) or an object schema. Else `props` gets an error. */\ntype PropsCheck<Props> = unknown extends Props\n ? unknown\n : Props extends PropsSchema\n ? unknown\n : { props?: PropsSchema };\n\ntype MatchCheck<Name extends string, Event, Functions> = [\n MatchedFunction<Name, Functions>,\n] extends [never]\n ? \"parameters\" extends keyof Event\n ? unknown\n : { parameters: GenerativeUISchema }\n : \"parameters\" extends keyof Event\n ? [OutputOf<Event[\"parameters\" & keyof Event]>] extends [\n FunctionInput<Functions, MatchedFunction<Name, Functions>>,\n ]\n ? unknown\n : {\n parameters: `The output of these parameters does not fit the input of function \"${MatchedFunction<\n Name,\n Functions\n > &\n string}\".`;\n }\n : unknown;\n\n/**\n * `unknown` when the event is valid. Else a type the event does not fit, so\n * `tsc` reports the error on the event.\n */\ntype EventCheck<\n Name extends string,\n Event,\n Functions,\n> = Event extends GenerativeUIEventDefinition\n ? MatchCheck<Name, Event, Functions>\n : GenerativeUIEventDefinition;\n\ntype EventsCheck<Events, Functions> = {\n [Name in keyof Events]: EventCheck<Name & string, Events[Name], Functions>;\n};\n\n/** Props that a component can list in `writable`: not bound by name. */\ntype WritableKey<Props, State> = Exclude<\n PropKeys<Props>,\n NameKeys<Props, State>\n>;\n\n/**\n * Each component config is split over four mapped types. Each one infers\n * one part (props, events, slots, writable) of every component. The checks\n * are in `NoInfer`, so they do not change what is inferred. They are not\n * intersected with schema types directly, because two schema class types do\n * not intersect cleanly.\n */\ntype ComponentsConfig<Props, Events, Slots, Writable, State, Functions> = {\n [Name in keyof Props]: {\n component: AnyComponent;\n description?: string;\n parameterOrder?: readonly string[];\n props?: Props[Name];\n accessibility?: \"wrapper\" | \"self\";\n } & NoInfer<PropsCheck<Props[Name]> & BindField<Props[Name], State>>;\n} & {\n [Name in keyof Events]: {\n events?: Events[Name] & NoInfer<EventsCheck<Events[Name], Functions>>;\n };\n} & {\n [Name in keyof Slots]: {\n slots?: Slots[Name] & Record<string, GenerativeUISlotKind>;\n };\n} & {\n [Name in keyof Writable]: {\n writable?: Writable[Name] &\n NoInfer<readonly WritableKey<Props[Name & keyof Props], State>[]>;\n };\n};\n\n/** The config of `createGenerativeUI`. */\nexport interface 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> {\n /** Surfaces pin to it. Use a versioned id, for example \"acme/store@1\". */\n id: string;\n /** Bases. Their state, functions and components merge in, in order. */\n extends?: Bases;\n /** App state schemas, by top-level key. Put it before `components`. */\n state?: State;\n /** Functions that components can call. */\n functions?: Functions;\n /**\n * New React components for components of the bases, by name. The model\n * sees the same component: its description, props, events and slots stay.\n * The new component gets the same props as the one it replaces.\n */\n overrides?: NoInfer<OverridesConfig<Bases>>;\n /** The components the model can render. */\n components: ComponentsConfig<\n Props,\n Events,\n Slots,\n Writable,\n MergedState<Bases, State>,\n MergedFunctions<Bases, Functions>\n >;\n}\n\n/** The definitions of the bases, merged. */\ntype BasesDefinitions<Bases extends readonly AnyGenerativeUI[]> =\n ResultDefinitions<Bases, {}, {}, {}, {}, {}, {}>;\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 BasesDefinitions<Bases>[\"components\"] & string]?: {\n component: ComponentType<\n BasesDefinitions<Bases> extends infer Definitions extends\n GenerativeUIDefinitions\n ? GenerativeUIComponentProps<GenerativeUI<Definitions>, Name>\n : never\n >;\n };\n};\n\ntype OwnComponents<Props, Events, Slots, Writable> = {\n [Name in keyof Props]: {\n props: Props[Name];\n events: Name extends keyof Events ? Events[Name] : unknown;\n slots: Name extends keyof Slots ? Slots[Name] : unknown;\n writable: Name extends keyof Writable ? Writable[Name] : unknown;\n };\n};\n\ntype ResultDefinitions<\n Bases extends readonly AnyGenerativeUI[],\n State,\n Functions,\n Props,\n Events,\n Slots,\n Writable,\n> = {\n state: MergedState<Bases, State>;\n functions: MergedFunctions<Bases, Functions>;\n components: Simplify<\n UnionToIntersection<BaseDefinitions<Bases>[\"components\"]> &\n OwnComponents<Props, Events, Slots, Writable>\n >;\n};\n\n// ---- Runtime ----\n\ninterface RuntimeComponentDefinition extends Omit<\n GenerativeUIComponentDefinition,\n \"component\"\n> {\n component: AnyComponent;\n}\n\ninterface RuntimeConfig {\n id: string;\n extends?: readonly AnyGenerativeUI[];\n state?: Record<string, GenerativeUISchema>;\n functions?: Record<string, GenerativeUIFunctionDefinition>;\n overrides?: Record<string, { component: AnyComponent }>;\n components: Record<string, RuntimeComponentDefinition>;\n}\n\n/** The A2UI component envelope: `id`, `component`, `catalogId`, `accessibility`, `metadata`. */\nconst RESERVED_KEYS = new Set([\n \"id\",\n \"component\",\n ...A2UI_COMPONENT_ENVELOPE_KEYS,\n]);\n\n/** The id of the catalog that declared each component, for the inspector. */\nconst componentCatalogs = new WeakMap<object, ReadonlyMap<string, string>>();\n\n/**\n * The id of the catalog that declared each component of `ui`. A component\n * from `extends` keeps the id of its base. Not exported from the package.\n */\nexport function componentCatalogIds(\n ui: AnyGenerativeUI,\n): ReadonlyMap<string, string> {\n return componentCatalogs.get(ui) ?? new Map();\n}\n\n/**\n * The catalogs that an operation can name: the id of `ui`, then the ids of\n * the catalogs in its `extends` that declared a component. Not exported\n * from the package.\n */\nexport function catalogIdsOf(ui: Pick<AnyGenerativeUI, \"id\">): string[] {\n const declared = componentCatalogs.get(ui)?.values() ?? [];\n return [...new Set([ui.id, ...declared])];\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 // TypeScript cannot relate the generic mapped config type to the runtime\n // shape. The config type is stricter than `RuntimeConfig`, so this is safe.\n const ui: GenerativeUI<\n ResultDefinitions<Bases, State, Functions, Props, Events, Slots, Writable>\n > = buildGenerativeUI(config as RuntimeConfig) as GenerativeUI<any>;\n return ui;\n}\n\nfunction buildGenerativeUI(config: RuntimeConfig) {\n const where = `generative UI \"${config.id}\"`;\n const state = new Map<string, GenerativeUISchema>();\n const functions = new Map<string, GenerativeUIFunctionDefinition>();\n const definitions = new Map<string, RuntimeComponentDefinition>();\n const catalogs = new Map<string, string>();\n\n function add<Value>(\n map: Map<string, Value>,\n kind: string,\n name: string,\n value: Value,\n ) {\n if (map.has(name)) {\n throw new Error(\n `[generativeUI] ${kind} \"${name}\" is defined more than once in ${where}.`,\n );\n }\n map.set(name, value);\n }\n\n const bases = config.extends ?? [];\n for (const base of bases) {\n for (const [name, schema] of base.state)\n add(state, \"State key\", name, schema);\n for (const [name, fn] of base.functions)\n add(functions, \"Function\", name, fn);\n const baseCatalogs = componentCatalogIds(base);\n for (const [name, component] of base.components) {\n add(definitions, \"Component\", name, component);\n catalogs.set(name, baseCatalogs.get(name) ?? base.id);\n }\n }\n for (const [name, override] of Object.entries(config.overrides ?? {})) {\n const base = definitions.get(name);\n if (!base) {\n throw new Error(\n `[generativeUI] Override \"${name}\" is not a component of the bases of ${where}.`,\n );\n }\n definitions.set(name, { ...base, component: override.component });\n }\n for (const [name, schema] of Object.entries(config.state ?? {}))\n add(state, \"State key\", name, schema);\n for (const [name, fn] of Object.entries(config.functions ?? {}))\n add(functions, \"Function\", name, fn);\n for (const [name, fn] of functions) {\n const isGestureOnly = fn.requiresUserActivation === true;\n if (\n isGestureOnly &&\n fn.allowedCallers !== undefined &&\n fn.allowedCallers !== \"rendererOnly\"\n ) {\n throw new Error(\n `[generativeUI] Function \"${name}\" in ${where} requires user activation, so its allowedCallers must be \"rendererOnly\", not \"${fn.allowedCallers}\".`,\n );\n }\n }\n for (const [name, component] of Object.entries(config.components)) {\n add(definitions, \"Component\", name, component);\n catalogs.set(name, config.id);\n }\n\n const components = new Map<string, ResolvedGenerativeUIComponent>();\n const manifestComponents: Record<string, GenerativeUIComponentManifest> = {};\n for (const [name, definition] of definitions) {\n const { component, manifest } = resolveComponent(name, definition, {\n state,\n functions,\n where,\n });\n components.set(name, component);\n manifestComponents[name] = manifest;\n }\n return withOmit(\n { id: config.id, state, functions, components, manifestComponents },\n catalogs,\n );\n}\n\n/** Adds the `omit` method to the data of a generative UI. */\nfunction withOmit(\n data: Omit<GenerativeUI, \"omit\">,\n catalogs: ReadonlyMap<string, string>,\n): GenerativeUI {\n // The method is typed on `GenerativeUI`. The runtime works with names only.\n const omit = (names: readonly string[]): GenerativeUI => {\n for (const name of names) {\n if (!data.components.has(name)) {\n throw new Error(\n `[generativeUI] Cannot omit \"${name}\": it is not a component of generative UI \"${data.id}\".`,\n );\n }\n }\n const isKept = (name: string) => !names.includes(name);\n return withOmit(\n {\n id: data.id,\n state: data.state,\n functions: data.functions,\n components: new Map(\n [...data.components].filter(([name]) => isKept(name)),\n ),\n manifestComponents: Object.fromEntries(\n Object.entries(data.manifestComponents).filter(([name]) =>\n isKept(name),\n ),\n ),\n },\n catalogs,\n );\n };\n const ui = { ...data, omit: omit as GenerativeUI[\"omit\"] };\n componentCatalogs.set(ui, catalogs);\n return ui;\n}\n\ninterface ResolveContext {\n state: ReadonlyMap<string, GenerativeUISchema>;\n functions: ReadonlyMap<string, GenerativeUIFunctionDefinition>;\n where: string;\n}\n\n/** Builds the selectors, the event map and the manifest of one component. */\nfunction resolveComponent(\n name: string,\n definition: RuntimeComponentDefinition,\n context: ResolveContext,\n) {\n const propsJson = propsJsonSchema(name, definition, context.where);\n const propKeys = Object.keys(propsJson.properties);\n assertDisjointKeys(name, definition, propKeys);\n assertParameterOrder(name, definition, propKeys);\n\n const selectors: Record<string, GenerativeUISelector> = {};\n for (const key of propKeys) {\n if (context.state.has(key)) selectors[key] = (state) => state[key];\n }\n const bind = definition.bind ?? {};\n for (const [key, selector] of Object.entries(bind)) {\n if (!propKeys.includes(key)) {\n throw new Error(\n `[generativeUI] bind key \"${key}\" is not a prop of component \"${name}\" in ${context.where}.`,\n );\n }\n selectors[key] = selector;\n }\n const eventFunctions: Record<string, string> = {};\n const modelEvents: NonNullable<GenerativeUIComponentManifest[\"events\"]> = {};\n const events = definition.events ?? {};\n for (const [eventName, event] of Object.entries(events)) {\n const functionName = matchFunction(eventName, name, context);\n if (functionName !== undefined) {\n const matched = context.functions.get(functionName);\n if (matched && !functionCallers(matched).renderer) {\n throw new Error(\n `[generativeUI] Event \"${eventName}\" of component \"${name}\" matches function \"${functionName}\", which the UI cannot call (allowedCallers \"agentOnly\") in ${context.where}.`,\n );\n }\n eventFunctions[eventName] = functionName;\n continue;\n }\n if (!event.parameters) {\n throw new Error(\n `[generativeUI] Event \"${eventName}\" of component \"${name}\" matches no function in ${context.where}, so it needs \"parameters\".`,\n );\n }\n modelEvents[eventName] = {\n ...(event.description ? { description: event.description } : {}),\n parameters: toJsonSchema(event.parameters),\n };\n }\n\n assertWritable(name, definition, propKeys, selectors, context.where);\n\n const component: ResolvedGenerativeUIComponent = {\n // The config checks components against `AnyComponent` (see above). Here\n // the renderer needs the React type.\n component: definition.component as ComponentType<any>,\n description: definition.description,\n parameterOrder: definition.parameterOrder?.slice(),\n props: definition.props,\n bind: definition.bind,\n events: definition.events,\n slots: definition.slots,\n writable: definition.writable,\n accessibility: definition.accessibility ?? \"wrapper\",\n selectors,\n eventFunctions,\n propKeys,\n childRefs: collectChildRefs(propsJson),\n };\n return {\n component,\n manifest: toManifest(\n definition,\n modelPropsJsonSchema(propsJson, selectors),\n modelEvents,\n ),\n };\n}\n\ntype ObjectJsonSchema = GenerativeUIJSONSchema & {\n properties: Record<string, GenerativeUIJSONSchema>;\n};\n\n/** The JSON Schema of `props`. A component without `props` has none. */\nfunction propsJsonSchema(\n name: string,\n definition: RuntimeComponentDefinition,\n where: string,\n): ObjectJsonSchema {\n if (!definition.props) return { type: \"object\", properties: {} };\n const json = toJsonSchema(definition.props);\n const { properties } = json;\n const isObject =\n typeof properties === \"object\" &&\n properties !== null &&\n !Array.isArray(properties);\n if (!isObject) {\n throw new Error(\n `[generativeUI] the props of component \"${name}\" in ${where} must be an object schema.`,\n );\n }\n return json as ObjectJsonSchema;\n}\n\n/**\n * What the model sees of the props: the JSON Schema without the bound props,\n * and with no other keys allowed.\n */\nfunction modelPropsJsonSchema(\n json: ObjectJsonSchema,\n bound: Record<string, unknown>,\n): GenerativeUIJSONSchema {\n const isModelKey = (key: string) => !Object.hasOwn(bound, key);\n const {\n properties,\n required,\n additionalProperties: _additionalProperties,\n ...rest\n } = json;\n const modelRequired = Array.isArray(required)\n ? required.filter((key: unknown) => isModelKey(String(key)))\n : [];\n return {\n ...rest,\n type: \"object\",\n properties: Object.fromEntries(\n Object.entries(properties).filter(([key]) => isModelKey(key)),\n ),\n ...(modelRequired.length > 0 ? { required: modelRequired } : {}),\n additionalProperties: false,\n };\n}\n\n/** `onAddToCart` to `addToCart`. `undefined` when the name has no `on` prefix. */\nfunction withoutOnPrefix(eventName: string) {\n const hasOnPrefix = eventName.length > 2 && eventName.startsWith(\"on\");\n if (!hasOnPrefix) return undefined;\n return eventName.charAt(2).toLowerCase() + eventName.slice(3);\n}\n\n/** The declared function an event calls, or `undefined` when none matches. */\nfunction matchFunction(\n eventName: string,\n componentName: string,\n context: ResolveContext,\n) {\n const exact = context.functions.has(eventName) ? eventName : undefined;\n const stripped = withoutOnPrefix(eventName);\n const fromPrefix =\n stripped !== undefined && context.functions.has(stripped)\n ? stripped\n : undefined;\n if (exact !== undefined && fromPrefix !== undefined) {\n throw new Error(\n `[generativeUI] Event \"${eventName}\" of component \"${componentName}\" matches two functions, \"${exact}\" and \"${fromPrefix}\", in ${context.where}.`,\n );\n }\n return exact ?? fromPrefix;\n}\n\n/** The setter prop of a writable prop: `value` gives `setValue`. */\nexport function setterNameOf(key: string) {\n return `set${key.charAt(0).toUpperCase()}${key.slice(1)}`;\n}\n\n/** Why a `writable` key is not valid, or `undefined` when it is valid. */\nfunction writableProblem(\n key: string,\n definition: RuntimeComponentDefinition,\n propKeys: readonly string[],\n selectors: Record<string, GenerativeUISelector>,\n) {\n if (Object.hasOwn(definition.events ?? {}, key)) return \"an event\";\n if (Object.hasOwn(definition.slots ?? {}, key)) return \"a slot\";\n if (!propKeys.includes(key)) return \"not a prop\";\n if (Object.hasOwn(selectors, key)) return \"a bound prop\";\n return undefined;\n}\n\nfunction assertWritable(\n name: string,\n definition: RuntimeComponentDefinition,\n propKeys: readonly string[],\n selectors: Record<string, GenerativeUISelector>,\n where: string,\n) {\n const writable = definition.writable ?? [];\n const keys = new Set([\n ...propKeys,\n ...Object.keys(definition.events ?? {}),\n ...Object.keys(definition.slots ?? {}),\n ]);\n for (const key of writable) {\n const problem = writableProblem(key, definition, propKeys, selectors);\n if (problem) {\n throw new Error(\n `[generativeUI] writable key \"${key}\" of component \"${name}\" is ${problem} in ${where}.`,\n );\n }\n const setter = setterNameOf(key);\n if (keys.has(setter)) {\n throw new Error(\n `[generativeUI] the setter \"${setter}\" of writable key \"${key}\" is already a key of component \"${name}\" in ${where}.`,\n );\n }\n }\n}\n\nfunction assertDisjointKeys(\n name: string,\n definition: RuntimeComponentDefinition,\n propKeys: readonly string[],\n) {\n const seen = new Set<string>();\n const keys = [\n ...propKeys,\n ...Object.keys(definition.events ?? {}),\n ...Object.keys(definition.slots ?? {}),\n ];\n for (const key of keys) {\n if (RESERVED_KEYS.has(key)) {\n throw new Error(\n `[generativeUI] \"${key}\" is reserved by A2UI and cannot be a prop, event or slot of component \"${name}\".`,\n );\n }\n if (seen.has(key)) {\n throw new Error(\n `[generativeUI] \"${key}\" is declared as more than one of prop, event, slot on component \"${name}\".`,\n );\n }\n seen.add(key);\n }\n}\n\nfunction assertParameterOrder(\n name: string,\n definition: RuntimeComponentDefinition,\n propKeys: readonly string[],\n) {\n const order = definition.parameterOrder;\n if (order === undefined) return;\n const keys = new Set([\n ...propKeys,\n ...Object.keys(definition.slots ?? {}),\n ...Object.keys(definition.events ?? {}),\n ]);\n if (\n [...keys].some((key) => {\n const index = Number(key);\n return (\n Number.isInteger(index) &&\n index >= 0 &&\n index < 2 ** 32 - 1 &&\n String(index) === key\n );\n })\n ) {\n throw new Error(\n `[generativeUI] Component \"${name}\" with parameterOrder cannot declare integer-index keys: JSON object enumeration sorts them numerically before other keys, ignoring the requested order.`,\n );\n }\n if (\n !Array.isArray(order) ||\n new Set(order).size !== order.length ||\n order.some((key) => !keys.has(key))\n ) {\n throw new Error(\n `[generativeUI] parameterOrder of component \"${name}\" must contain unique declared prop, slot or event names.`,\n );\n }\n}\n\nfunction toManifest(\n definition: RuntimeComponentDefinition,\n modelProps: GenerativeUIJSONSchema,\n modelEvents: NonNullable<GenerativeUIComponentManifest[\"events\"]>,\n) {\n const manifest: GenerativeUIComponentManifest = { props: modelProps };\n if (definition.description) manifest.description = definition.description;\n if (Object.keys(modelEvents).length > 0) manifest.events = modelEvents;\n if (definition.slots) manifest.slots = { ...definition.slots };\n if (definition.parameterOrder !== undefined) {\n const visible = new Set([\n ...Object.keys(modelProps.properties ?? {}),\n ...Object.keys(definition.slots ?? {}),\n ...Object.keys(modelEvents),\n ]);\n manifest.parameterOrder = [\n ...new Set([\n ...definition.parameterOrder.filter((key) => visible.has(key)),\n ...visible,\n ]),\n ];\n }\n return manifest;\n}\n","/** True for a plain object: not null, not an array. Internal, not exported. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import type {\n GenerativeUI,\n GenerativeUIDefinitionsOf,\n GenerativeUIEventInput,\n UnionToIntersection,\n} from \"./catalog\";\n\nexport type GenerativeUIErrorCode =\n | \"function_not_found\"\n | \"function_conflict\"\n | \"invalid_arguments\"\n | \"handler_failed\"\n | \"invalid_event_args\"\n | \"event_forward_failed\"\n /** A function value or check could not be computed. */\n | \"expression_error\"\n /** A function the caller may not call: `openUrl` from the agent. */\n | \"invalid_function_call\"\n /** An event arrived while the agent was running: it was not sent. */\n | \"agent_busy\";\n\nexport class GenerativeUIError extends Error {\n readonly code: GenerativeUIErrorCode;\n constructor(code: GenerativeUIErrorCode, message: string) {\n super(message);\n this.name = \"GenerativeUIError\";\n this.code = code;\n }\n}\n\nexport type GenerativeUIInvokeResult =\n | { ok: true; result: unknown }\n | { ok: false; error: GenerativeUIError };\n\ntype Components<UI extends GenerativeUI<any>> =\n GenerativeUIDefinitionsOf<UI>[\"components\"];\n\ntype EventsOf<\n UI extends GenerativeUI<any>,\n Component extends keyof Components<UI>,\n> =\n Components<UI>[Component][\"events\"] extends Record<string, unknown>\n ? Components<UI>[Component][\"events\"]\n : {};\n\ntype IsUnion<T, U = T> = T extends unknown\n ? [U] extends [T]\n ? false\n : true\n : never;\n\n/** One member of a union. Used only after IsUnion proved the members equal. */\ntype OneOf<U> =\n UnionToIntersection<U extends unknown ? () => U : never> extends () => infer R\n ? R\n : never;\n\n/** Every event name that a component of the UI declares, bases included. */\nexport type GenerativeUIEventName<UI extends GenerativeUI<any>> = {\n [Component in keyof Components<UI>]: keyof EventsOf<UI, Component> & string;\n}[keyof Components<UI>];\n\ntype EventArgs<UI extends GenerativeUI<any>, Name extends string> = {\n [Component in keyof Components<UI>]: Name extends keyof EventsOf<\n UI,\n Component\n >\n ? GenerativeUIEventInput<\n Name,\n EventsOf<UI, Component>[Name],\n GenerativeUIDefinitionsOf<UI>[\"functions\"]\n >\n : never;\n}[keyof Components<UI>];\n\n/**\n * Type of an event prop as seen by a component, looked up by event name in\n * the generative UI that renders the component:\n * `onSubmit?: GenerativeUIEventHandler<typeof ui, \"onSubmit\">`.\n *\n * The argument is the event `parameters` input. A matched event without\n * `parameters` takes the input of its function.\n *\n * When components of the UI declare the event with different arguments, the\n * result is not callable and names the conflict.\n */\nexport type GenerativeUIEventHandler<\n UI extends GenerativeUI<any>,\n Name extends GenerativeUIEventName<UI>,\n> =\n true extends IsUnion<EventArgs<UI, Name>>\n ? {\n readonly error: `\"${Name}\" has different parameters on different components of this generative UI`;\n }\n : (args: OneOf<EventArgs<UI, Name>>) => Promise<GenerativeUIInvokeResult>;\n\nexport interface GenerativeUIErrorInfo {\n kind: \"render\" | \"props\" | \"operation\" | \"function\" | \"event\";\n surfaceId: string;\n componentId?: string;\n error: Error;\n}\n","import {\n GENERATIVE_UI_FUNCTIONS,\n isValidationResult,\n} from \"@copilotkit/shared\";\nimport type { A2UIValidationResult } from \"@copilotkit/shared\";\n\n/**\n * The renderer-side functions of the A2UI 1.0 basic catalog. Each one takes\n * resolved args (no bindings left in them) and gives a plain value. They\n * run synchronously, so a prop bound to one updates in the same render as\n * the data it reads. The signatures the model sees are in\n * `@copilotkit/shared` (`A2UI_BASIC_FUNCTIONS`).\n */\n\n/** Thrown for a bad call: an unknown function, bad args, or a bad value. */\nexport class ExpressionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ExpressionError\";\n }\n}\n\nexport type BasicFunction = (args: Record<string, unknown>) => unknown;\n\n/** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */\nexport function truthOf(value: unknown): boolean {\n if (isValidationResult(value)) return value.valid;\n return Boolean(value);\n}\n\nconst valid = (): A2UIValidationResult => ({ valid: true });\n/** A failed result. `code` names the failure, the same for every locale. */\nconst invalid = (message: string, code: string): A2UIValidationResult => ({\n valid: false,\n message,\n code,\n});\n\nfunction text(value: unknown) {\n if (value === undefined || value === null) return \"\";\n return typeof value === \"string\" ? value : String(value);\n}\n\nfunction numberOf(value: unknown) {\n if (typeof value === \"number\") return value;\n if (typeof value === \"string\" && value.trim() !== \"\") return Number(value);\n return Number.NaN;\n}\n\nfunction optionalNumber(value: unknown, name: string) {\n if (value === undefined || value === null) return undefined;\n const parsed = numberOf(value);\n if (Number.isNaN(parsed))\n throw new ExpressionError(`${name} must be a number`);\n return parsed;\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** The locale of the user. `undefined` lets Intl pick the default. */\nfunction locale() {\n return typeof navigator !== \"undefined\" ? navigator.language : undefined;\n}\n\nfunction numberFormat(\n args: Record<string, unknown>,\n options: Intl.NumberFormatOptions,\n) {\n const decimals = optionalNumber(args.decimals, \"decimals\");\n return new Intl.NumberFormat(locale(), {\n ...options,\n useGrouping: args.grouping !== false,\n ...(decimals === undefined\n ? {}\n : { minimumFractionDigits: decimals, maximumFractionDigits: decimals }),\n });\n}\n\n/** A date from an ISO string, a timestamp, or a Date. */\nfunction dateOf(value: unknown) {\n const date =\n value instanceof Date\n ? value\n : typeof value === \"number\"\n ? new Date(value)\n : typeof value === \"string\"\n ? new Date(\n /^\\d{4}-\\d{2}-\\d{2}$/.test(value) ? `${value}T00:00` : value,\n )\n : undefined;\n if (date === undefined || Number.isNaN(date.getTime())) {\n throw new ExpressionError(\"value must be a date\");\n }\n return date;\n}\n\nconst pad = (value: number, width: number) =>\n String(value).padStart(width, \"0\");\n\n/**\n * A TR35 field is a run of one letter (\"EEE\" is one abbreviated weekday,\n * not three), and text in single quotes is literal. Letters that are not\n * fields stay as they are.\n */\nconst DATE_FIELD = /([A-Za-z])\\1*|'(?:[^']|'')*'/g;\n\nfunction formatDatePattern(date: Date, pattern: string) {\n const parts = (options: Intl.DateTimeFormatOptions) =>\n new Intl.DateTimeFormat(locale(), options).format(date);\n const hours12 = date.getHours() % 12 || 12;\n const numeric = (value: number, width: number) =>\n width >= 2 ? pad(value, 2) : String(value);\n return pattern.replace(DATE_FIELD, (token) => {\n if (token.startsWith(\"'\")) return token.slice(1, -1).replace(/''/g, \"'\");\n const width = token.length;\n switch (token[0]) {\n case \"y\":\n return width === 2\n ? pad(date.getFullYear() % 100, 2)\n : String(date.getFullYear());\n case \"M\":\n if (width >= 4) return parts({ month: \"long\" });\n if (width === 3) return parts({ month: \"short\" });\n return numeric(date.getMonth() + 1, width);\n case \"d\":\n return numeric(date.getDate(), width);\n case \"E\":\n return parts({ weekday: width >= 4 ? \"long\" : \"short\" });\n case \"H\":\n return numeric(date.getHours(), width);\n case \"h\":\n return numeric(hours12, width);\n case \"m\":\n return pad(date.getMinutes(), 2);\n case \"s\":\n return pad(date.getSeconds(), 2);\n case \"a\":\n return date.getHours() < 12 ? \"AM\" : \"PM\";\n default:\n return token;\n }\n });\n}\n\n/** Opens an http(s) URL in a new tab. Any other scheme is refused. */\nexport function openUrlSafely(url: unknown) {\n if (typeof url !== \"string\" || url === \"\") {\n throw new ExpressionError(\"url must be a string\");\n }\n if (typeof window === \"undefined\") return;\n let parsed: URL;\n try {\n parsed = new URL(url, window.location.href);\n } catch {\n throw new ExpressionError(`\"${url}\" is not a URL`);\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n throw new ExpressionError(\n `openUrl takes only http(s) URLs, not ${parsed.protocol}`,\n );\n }\n window.open(parsed.href, \"_blank\", \"noopener,noreferrer\");\n}\n\n/**\n * The basic functions, except `formatString`, which needs the resolver.\n * `calc` and `series` are added by `resolve.ts`, which imports both.\n */\nexport const BASIC_FUNCTIONS: Record<string, BasicFunction> = {\n required: ({ value }) => {\n const isEmpty =\n value === undefined ||\n value === null ||\n value === \"\" ||\n (Array.isArray(value) && value.length === 0);\n return isEmpty ? invalid(\"Required\", \"required\") : valid();\n },\n regex: ({ value, pattern }) => {\n if (typeof pattern !== \"string\") {\n throw new ExpressionError(\"pattern must be a string\");\n }\n let expression: RegExp;\n try {\n expression = new RegExp(pattern, \"u\");\n } catch {\n throw new ExpressionError(`\"${pattern}\" is not a regular expression`);\n }\n return expression.test(text(value))\n ? valid()\n : invalid(\"Invalid format\", \"pattern\");\n },\n length: ({ value, min, max }) => {\n const size = text(value).length;\n const low = optionalNumber(min, \"min\");\n const high = optionalNumber(max, \"max\");\n if (low !== undefined && size < low)\n return invalid(`At least ${low} characters`, \"tooShort\");\n if (high !== undefined && size > high)\n return invalid(`At most ${high} characters`, \"tooLong\");\n return valid();\n },\n numeric: ({ value, min, max }) => {\n const parsed = numberOf(value);\n if (Number.isNaN(parsed)) return invalid(\"Must be a number\", \"notANumber\");\n const low = optionalNumber(min, \"min\");\n const high = optionalNumber(max, \"max\");\n if (low !== undefined && parsed < low)\n return invalid(`At least ${low}`, \"tooSmall\");\n if (high !== undefined && parsed > high)\n return invalid(`At most ${high}`, \"tooLarge\");\n return valid();\n },\n email: ({ value }) =>\n EMAIL.test(text(value))\n ? valid()\n : invalid(\"Invalid email address\", \"email\"),\n formatNumber: (args) => {\n const parsed = numberOf(args.value);\n if (Number.isNaN(parsed))\n throw new ExpressionError(\"value must be a number\");\n return numberFormat(args, {}).format(parsed);\n },\n formatCurrency: (args) => {\n const parsed = numberOf(args.value);\n if (Number.isNaN(parsed))\n throw new ExpressionError(\"value must be a number\");\n if (typeof args.currency !== \"string\" || args.currency === \"\") {\n throw new ExpressionError(\"currency must be an ISO 4217 code\");\n }\n try {\n return numberFormat(args, {\n style: \"currency\",\n currency: args.currency,\n }).format(parsed);\n } catch {\n throw new ExpressionError(`\"${args.currency}\" is not a currency code`);\n }\n },\n formatDate: ({ value, format }) => {\n if (typeof format !== \"string\") {\n throw new ExpressionError(\"format must be a string\");\n }\n return formatDatePattern(dateOf(value), format);\n },\n pluralize: (args) => {\n const parsed = numberOf(args.value);\n if (Number.isNaN(parsed))\n throw new ExpressionError(\"value must be a number\");\n const category = new Intl.PluralRules(locale()).select(parsed);\n const exact = parsed === 0 ? args.zero : undefined;\n const chosen = exact ?? args[category] ?? args.other;\n return text(chosen);\n },\n and: ({ values }) => {\n if (!Array.isArray(values))\n throw new ExpressionError(\"values must be a list\");\n return values.every(truthOf);\n },\n or: ({ values }) => {\n if (!Array.isArray(values))\n throw new ExpressionError(\"values must be a list\");\n return values.some(truthOf);\n },\n not: ({ value }) => !truthOf(value),\n openUrl: ({ url }) => {\n openUrlSafely(url);\n return undefined;\n },\n};\n\n/** True when the basic function `name` must run from a user gesture. */\nexport function requiresUserActivation(name: string) {\n return GENERATIVE_UI_FUNCTIONS[name]?.requiresUserActivation === true;\n}\n\n/** True when a basic function gives a ValidationResult. */\nexport function givesValidationResult(name: string) {\n return GENERATIVE_UI_FUNCTIONS[name]?.returnType === \"validationResult\";\n}\n","import type { ChildRef } from \"@copilotkit/shared\";\nimport type { Message } from \"@ag-ui/client\";\nimport {\n extractFenceOperations,\n flattenInformationalCards,\n getMarkdownOperationSurfaceId,\n prepareSurfaceOperations,\n segmentSurfaceProse,\n splitA2UIMarkdown,\n} from \"@copilotkit/core\";\nimport type { A2UIMarkdownOperation, ChildIdsOf } from \"@copilotkit/core\";\nimport {\n A2UI_VERSION,\n GENERATIVE_UI_CHAT_TARGET,\n GENERATIVE_UI_ROOT_ID,\n getOperationKind,\n validateOperation,\n childIdsAtRefs,\n collectChildRefs,\n hasBoundChildRef,\n} from \"@copilotkit/shared\";\nimport type {\n A2UIOperation,\n GenerativeUIFunctionManifest,\n GenerativeUIRejectedOperation,\n GenerativeUISurfaceContent,\n ValidateOperationOptions,\n} from \"@copilotkit/shared\";\nimport { catalogIdsOf } from \"../catalog\";\nimport type { GenerativeUI } from \"../catalog\";\nimport { toJsonSchema } from \"../json-schema\";\nimport type { GenerativeUISurfaceManager } from \"../surface-manager\";\nimport { isRecord } from \"../is-record\";\n\n/** What renders in place of one ```a2ui fence, in order. */\nexport type MarkdownFenceBlock =\n | { kind: \"markdown\"; markdown: string }\n | { kind: \"surface\"; surfaceId: string };\n\n/** The part of a generative UI that the markdown source reads. */\ntype MarkdownSourceUI = Pick<GenerativeUI, \"id\" | \"manifestComponents\">;\n\nexport interface BuildMarkdownSurfacesOptions {\n ui: MarkdownSourceUI;\n /** The declared functions. A `functionCall` must name one of them. */\n functions: Record<string, GenerativeUIFunctionManifest>;\n /**\n * The last message can still grow. Then an open fence in it is still\n * streaming: its last, unfinished operation is left out, and the surface\n * it creates has the status \"streaming\". Else an open fence is final.\n */\n running: boolean;\n /**\n * The results of the earlier builds of the same thread. A build then\n * parses only the fences that changed, and builds only the surfaces whose\n * operations changed. Left out, everything is built again.\n */\n cache?: MarkdownBuildCache;\n}\n\n/**\n * Values by key, from the latest build. A value that a build does not use\n * is dropped at the end of that build, so the cache does not grow.\n */\nclass BuildMemo<V> {\n private previous = new Map<string, V>();\n private current = new Map<string, V>();\n\n /**\n * The value of `key`. It is computed when no earlier value is there, or\n * when `isFresh` says that the earlier value is out of date.\n */\n get(\n key: string,\n compute: () => V,\n isFresh: (value: V) => boolean = () => true,\n ) {\n let value = this.current.get(key) ?? this.previous.get(key);\n if (value === undefined || !isFresh(value)) value = compute();\n this.current.set(key, value);\n return value;\n }\n\n endBuild() {\n this.previous = this.current;\n this.current = new Map();\n }\n}\n\n/** The surfaces that one draft gives, and the operations it was built from. */\ninterface BuiltDraft {\n operations: A2UIMarkdownOperation[];\n target: string;\n streaming: boolean;\n parts: SurfacePart[];\n contents: GenerativeUISurfaceContent[];\n}\n\n/** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */\nexport class MarkdownBuildCache {\n readonly segments = new BuildMemo<ReturnType<typeof splitA2UIMarkdown>>();\n readonly fences = new BuildMemo<{\n operations: A2UIMarkdownOperation[];\n functionCalls: A2UIMarkdownOperation[];\n }>();\n readonly drafts = new BuildMemo<BuiltDraft>();\n /** The copies of an operation for other surface ids, by operation. */\n readonly readdressed = new WeakMap<\n object,\n Map<string, A2UIMarkdownOperation>\n >();\n\n endBuild() {\n this.segments.endBuild();\n this.fences.endBuild();\n this.drafts.endBuild();\n }\n}\n\n/** True when both lists hold the same objects in the same order. */\nfunction sameItems<T>(a: readonly T[], b: readonly T[]) {\n return a.length === b.length && a.every((item, index) => item === b[index]);\n}\n\n/** One surface, collected from the fences of all messages. */\ninterface SurfaceDraft {\n surfaceId: string;\n target: string;\n operations: A2UIMarkdownOperation[];\n /** The fence that created the surface is still streaming. */\n streaming: boolean;\n}\n\n/** The surface content, or one surface of it after the prose lift. */\ntype SurfacePart =\n | { kind: \"markdown\"; markdown: string }\n | {\n kind: \"surface\";\n surfaceId: string;\n operations: A2UIMarkdownOperation[];\n };\n\nfunction isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n/** The key of one fence of one message. */\nexport function fenceKey(messageId: string, fenceIndex: number) {\n return `${messageId}:${fenceIndex}`;\n}\n\n/** One `callRendererFunction` line of a fence, in the order of the fences. */\nexport interface MarkdownFunctionCall {\n messageId: string;\n fenceIndex: number;\n /** The operation as the model wrote it. It is not validated yet. */\n operation: A2UIMarkdownOperation;\n}\n\n/**\n * The operations of a fence body. While the fence streams, the last object\n * can be unfinished. Of an unfinished updateComponents or createSurface, the\n * components that are complete render at once (a createSurface also keeps\n * its data model when all of it arrived). Any other unfinished object is\n * left out, because a part of a data model value can still change. A final\n * fence keeps what can be saved from an unfinished object.\n */\nfunction fenceOperations(text: string, isStreaming: boolean) {\n const parsed = extractFenceOperations(text);\n if (!isStreaming || parsed.partialObject === null) return parsed.operations;\n // The unfinished object is always the end of the text.\n const complete = extractFenceOperations(\n text.slice(0, text.length - parsed.partialObject.length),\n ).operations;\n const partial =\n parsed.operations.length > complete.length\n ? parsed.operations[parsed.operations.length - 1]\n : undefined;\n const canRenderPartial =\n partial !== undefined &&\n (isRecord(partial.updateComponents) || isRecord(partial.createSurface));\n return canRenderPartial ? [...complete, partial] : complete;\n}\n\n/**\n * An inline createSurface becomes a createSurface with only its surfaceId\n * and catalog, then an updateDataModel for its data model, then an\n * updateComponents for its components. The prose lift and the split per\n * component read only updateComponents, so they then work for an inline\n * surface too. A createSurface with a data model or components of a wrong\n * shape does not change, so that validation rejects it with the reason.\n */\nfunction expandInlineCreate(operations: A2UIMarkdownOperation[]) {\n return operations.flatMap((op) => {\n const create = op.createSurface;\n if (!isRecord(create)) return [op];\n const { dataModel, components, ...rest } = create;\n const hasData = isRecord(dataModel);\n const hasComponents = Array.isArray(components) && components.length > 0;\n const isWellFormed =\n (dataModel === undefined || hasData) &&\n (components === undefined || hasComponents);\n if (!isWellFormed || (!hasData && !hasComponents)) return [op];\n const { surfaceId } = create;\n const expanded: A2UIMarkdownOperation[] = [{ ...op, createSurface: rest }];\n if (hasData) {\n expanded.push({\n version: op.version,\n updateDataModel: { surfaceId, path: \"/\", value: dataModel },\n });\n }\n if (hasComponents) {\n expanded.push({\n version: op.version,\n updateComponents: { surfaceId, components },\n });\n }\n return expanded;\n });\n}\n\n/**\n * Each updateComponents becomes one operation per component, in order. The\n * complete components of a streaming line then give the same first\n * operations as the finished line, so the operation list only grows and the\n * manager never has to start the surface again.\n */\nfunction splitComponentUpdates(operations: A2UIMarkdownOperation[]) {\n return operations.flatMap((op) => {\n const update = op.updateComponents;\n if (!isRecord(update) || !Array.isArray(update.components)) return [op];\n if (update.components.length <= 1) return [op];\n return update.components.map((component) => ({\n ...op,\n updateComponents: { ...update, components: [component] },\n }));\n });\n}\n\n/** createSurface first, the other operations after it in their order. */\nfunction createSurfaceFirst(operations: A2UIMarkdownOperation[]) {\n const creates = operations.filter((op) => isRecord(op.createSurface));\n const others = operations.filter((op) => !isRecord(op.createSurface));\n return [...creates, ...others];\n}\n\n/** True when the component of `name` has the prop `prop`. */\nfunction hasProp(ui: MarkdownSourceUI, name: string, prop: string) {\n const properties = ui.manifestComponents[name]?.props.properties;\n return isRecord(properties) && Object.hasOwn(properties, prop);\n}\n\nconst childRefCache = new WeakMap<object, readonly ChildRef[]>();\n\n/** The ids in a slot value: an id, a list of ids, or a template. */\nfunction slotIds(value: unknown): string[] {\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) return value.filter(isString);\n return isRecord(value) && isString(value.componentId)\n ? [value.componentId]\n : [];\n}\n\n/**\n * A reader of the ids a component renders beyond `child` and `children`:\n * its declared slots (the `trigger` and `content` of a Modal) and its typed\n * child references (the `child` of each entry of `tabs`), from its catalog\n * entry. The prose lift follows these ids like `children`, so a panel is\n * never cut off from its Tabs. A reference that is bound to the data\n * model is \"unknown\": its ids exist only at render time.\n */\nfunction childIdsReader(ui: MarkdownSourceUI): ChildIdsOf {\n return (component) => {\n const name = component.component;\n // An own property only: \"constructor\" is not a component.\n const entry =\n typeof name === \"string\" && Object.hasOwn(ui.manifestComponents, name)\n ? ui.manifestComponents[name]\n : undefined;\n if (!entry) return [];\n const ids: string[] = [];\n for (const slot of Object.keys(entry.slots ?? {})) {\n if (slot !== \"child\" && slot !== \"children\") {\n ids.push(...slotIds(component[slot]));\n }\n }\n let refs = childRefCache.get(entry.props);\n if (!refs) {\n refs = collectChildRefs(entry.props);\n childRefCache.set(entry.props, refs);\n }\n if (refs.length === 0) return ids;\n if (hasBoundChildRef(component, refs)) return \"unknown\";\n return [...ids, ...childIdsAtRefs(component, refs)];\n };\n}\n\n/** Every component of the operations by id, last definition wins. */\nfunction collectComponents(operations: A2UIMarkdownOperation[]) {\n const byId = new Map<string, Record<string, unknown>>();\n for (const op of operations) {\n const update = op.updateComponents;\n const list = isRecord(update) ? update.components : undefined;\n if (!Array.isArray(list)) continue;\n for (const component of list) {\n if (isRecord(component) && isString(component.id)) {\n byId.set(component.id, component);\n }\n }\n }\n return [...byId.values()];\n}\n\n/**\n * The data model must not be shared between two surfaces. A data model\n * keeps the object it gets, so an input in one surface would change the\n * data of the other one.\n */\nfunction cloneData(value: unknown) {\n return value === undefined ? undefined : structuredClone(value);\n}\n\n/** The operation sent to `surfaceId`, with a copy of its data model value. */\nfunction readdress(op: A2UIMarkdownOperation, surfaceId: string) {\n const kind = getOperationKind(op);\n const payload = kind ? op[kind] : undefined;\n if (!kind || !isRecord(payload)) return op;\n const next: Record<string, unknown> = { ...payload, surfaceId };\n if (kind === \"updateDataModel\" && \"value\" in payload) {\n next.value = cloneData(payload.value);\n }\n return { ...op, [kind]: next };\n}\n\n/**\n * The operations of one sub-surface. Each updateComponents keeps only the\n * components of the sub-surface, with its own root. The other operations\n * are sent to the sub-surface. The order stays the same, so a new operation\n * of the fence only adds operations at the end.\n */\nfunction subSurfaceOperations(\n operations: A2UIMarkdownOperation[],\n components: Record<string, unknown>[],\n surfaceId: string,\n) {\n const root = components.find((c) => c.id === GENERATIVE_UI_ROOT_ID);\n const ids = new Set(components.map((c) => c.id));\n const out: A2UIMarkdownOperation[] = [];\n for (const op of operations) {\n const update = op.updateComponents;\n if (!isRecord(update) || !Array.isArray(update.components)) {\n out.push(readdress(op, surfaceId));\n continue;\n }\n const kept = update.components\n .filter((c) => isRecord(c) && ids.has(c.id))\n .map((c) => (isRecord(c) && c.id === GENERATIVE_UI_ROOT_ID ? root : c));\n if (kept.length === 0) continue;\n out.push({\n ...op,\n updateComponents: { ...update, surfaceId, components: kept },\n });\n }\n return out;\n}\n\n/**\n * Prose lift. Text components in the main stack of the surface (titles,\n * paragraphs, text lists and the dividers between them) become chat\n * markdown. The surface splits around them: the first surface keeps\n * `surfaceId`, the next ones are `<surfaceId>#1`, `<surfaceId>#2`, and so\n * on. A surface with no prose comes back as one part with the same\n * operations.\n */\nfunction liftProse(\n operations: A2UIMarkdownOperation[],\n surfaceId: string,\n childIds: ChildIdsOf,\n) {\n const components = collectComponents(operations);\n const segments = segmentSurfaceProse(components, { childIds });\n const [first] = segments;\n const isUnchanged =\n segments.length === 1 &&\n first?.kind === \"surface\" &&\n first.components === components;\n if (isUnchanged) {\n const whole: SurfacePart[] = [{ kind: \"surface\", surfaceId, operations }];\n return whole;\n }\n let surfaceIndex = 0;\n return segments.map((segment): SurfacePart => {\n if (segment.kind === \"markdown\") return segment;\n const id = surfaceIndex === 0 ? surfaceId : `${surfaceId}#${surfaceIndex}`;\n surfaceIndex++;\n return {\n kind: \"surface\",\n surfaceId: id,\n operations: subSurfaceOperations(operations, segment.components, id),\n };\n });\n}\n\n/** `validateOperation`, with the operation typed when it is valid. */\nfunction checkOperation(\n op: A2UIMarkdownOperation,\n options: ValidateOperationOptions,\n) {\n const validation = validateOperation(op, options);\n if (!validation.ok) return validation;\n // validateOperation checked the shape of `op`.\n return { ok: true as const, operation: op as A2UIOperation };\n}\n\n/**\n * The content of one surface. Each operation is validated against the\n * manifest. A valid operation goes in `operations`. A rejected one goes in\n * `rejected`, with its position and the reason.\n */\nfunction surfaceContent(\n surfaceId: string,\n draft: SurfaceDraft,\n operations: A2UIMarkdownOperation[],\n options: BuildMarkdownSurfacesOptions,\n) {\n const { ui, functions } = options;\n const knownSurfaces = new Set<string>();\n const manifest = {\n catalogId: ui.id,\n catalogIds: catalogIdsOf(ui),\n components: ui.manifestComponents,\n };\n const valid: A2UIOperation[] = [];\n const rejected: GenerativeUIRejectedOperation[] = [];\n operations.forEach((op, index) => {\n const result = checkOperation(op, { manifest, knownSurfaces, functions });\n if (!result.ok) {\n rejected.push({ index, reason: result.reason });\n return;\n }\n valid.push(result.operation);\n const kind = getOperationKind(result.operation);\n if (kind === \"createSurface\") knownSurfaces.add(surfaceId);\n if (kind === \"deleteSurface\") knownSurfaces.delete(surfaceId);\n });\n const create = valid.find(\n (op): op is Extract<A2UIOperation, { createSurface: unknown }> =>\n \"createSurface\" in op,\n );\n const content: GenerativeUISurfaceContent = {\n surfaceId,\n target: draft.target,\n catalogId: create?.createSurface.catalogId ?? ui.id,\n operations: valid,\n status: draft.streaming ? \"streaming\" : \"ready\",\n rejected,\n };\n return content;\n}\n\n/**\n * Builds the surfaces of a thread from the ```a2ui fences of its assistant\n * messages, in message order.\n *\n * - Operations are grouped by surfaceId across all messages. An operation\n * with no surfaceId goes to the first surface of its fence, else to\n * `<messageId>-<fenceIndex>`.\n * - The fence that first writes a surface creates it. The `target=<id>` of\n * that fence sets the target. With no target, the surface goes to the\n * chat.\n * - A later fence of the same reply for the same surfaceId updates it. A\n * later reply that reuses the id of a chat surface gets a surface of its\n * own, `<id>@<messageId>`. A page target is updated from any reply.\n * - The status is \"streaming\" while the creating fence streams, else\n * \"ready\".\n * - Each operation is validated with `validateOperation`. Rejected ones are\n * left out and listed in `rejected`.\n * - Chat surfaces get the prose lift: informational cards lose their box,\n * and prose becomes markdown that renders between sub-surfaces\n * (`<surfaceId>#<n>`). An inline createSurface is split into its\n * createSurface, updateDataModel and updateComponents first.\n * - A `callRendererFunction` line is not part of a surface. It goes to\n * `functionCalls`. A streaming line gives nothing, so a function never\n * runs with a part of its args.\n *\n * The function is pure. Call it again on each stream update. The manager\n * applies only the new operations, so unchanged surfaces do not render\n * again.\n *\n * @param messages - The messages of one thread.\n * @param options - The generative UI, its declared functions, and whether\n * the last message can still grow.\n * @returns `surfaces`, one content for each surface and sub-surface;\n * `fences`, the blocks that each fence renders, by `fenceKey` (a fence\n * that is not in `fences` renders nothing); `functionCalls`, the function\n * calls of the fences in order; and `parts`, the surface ids of the parts\n * of each surface, by surface id.\n *\n * @example\n * ```ts\n * const { surfaces } = buildMarkdownSurfaces(agent.messages, {\n * ui,\n * functions: {},\n * running: agent.isRunning,\n * });\n * for (const content of surfaces) manager.ingest(threadId, agentId, content);\n * ```\n */\nexport function buildMarkdownSurfaces(\n messages: readonly Message[],\n options: BuildMarkdownSurfacesOptions,\n) {\n const { ui, cache } = options;\n const drafts = new Map<string, SurfaceDraft>();\n // The same copy for the same operation and surface, so an unchanged draft\n // holds the same objects as in the last build.\n const readdressOnce = (op: A2UIMarkdownOperation, surfaceId: string) => {\n if (!cache) return readdress(op, surfaceId);\n let copies = cache.readdressed.get(op);\n if (!copies) {\n copies = new Map();\n cache.readdressed.set(op, copies);\n }\n let copy = copies.get(surfaceId);\n if (!copy) {\n copy = readdress(op, surfaceId);\n copies.set(surfaceId, copy);\n }\n return copy;\n };\n /** The surfaces that each fence created, in order. */\n const created = new Map<string, string[]>();\n const functionCalls: MarkdownFunctionCall[] = [];\n /** The message that owns each chat surface id, by the id the model wrote. */\n const chatOwners = new Map<string, string>();\n const lastMessage = messages[messages.length - 1];\n\n /**\n * A chat surface belongs to the reply that wrote it: the chat is a\n * transcript, so a later reply that reuses an id gets a surface of its\n * own (`<id>@<messageId>`) instead of changing the earlier reply. A fence\n * for a page target keeps its id, because a target is a place on the\n * page that a later reply updates on purpose.\n */\n const scopedSurfaceId = (\n requested: string,\n messageId: string,\n target: string | undefined,\n ) => {\n if (target !== undefined) return requested;\n const owner = chatOwners.get(requested);\n if (owner === undefined) {\n chatOwners.set(requested, messageId);\n return requested;\n }\n return owner === messageId ? requested : `${requested}@${messageId}`;\n };\n\n for (const message of messages) {\n if (message.role !== \"assistant\" || !isString(message.content)) continue;\n const isLastMessage = message === lastMessage;\n const content = message.content;\n const segments = cache\n ? cache.segments.get(content, () => splitA2UIMarkdown(content))\n : splitA2UIMarkdown(content);\n for (const segment of segments) {\n if (segment.type !== \"a2ui\") continue;\n const isStreaming = !segment.closed && isLastMessage && options.running;\n const parseFence = () => {\n const parsed = fenceOperations(segment.text, isStreaming);\n // The function calls do not depend on the surface id.\n const { functionCalls } = prepareSurfaceOperations({\n operations: parsed,\n fallbackSurfaceId: \"\",\n catalogId: ui.id,\n });\n return { operations: parsed, functionCalls };\n };\n const fence = cache\n ? cache.fences.get(`${isStreaming}:${segment.text}`, parseFence)\n : parseFence();\n const { operations } = fence;\n const key = fenceKey(message.id, segment.index);\n const fenceSurfaceId =\n operations.map(getMarkdownOperationSurfaceId).find(isString) ??\n `${message.id}-${segment.index}`;\n for (const operation of fence.functionCalls) {\n functionCalls.push({\n messageId: message.id,\n fenceIndex: segment.index,\n operation,\n });\n }\n // A function call is not part of a surface. A fence with only\n // function calls makes no surface and renders nothing.\n const surfaceOperations = operations.filter(\n (op) => getOperationKind(op) !== \"callRendererFunction\",\n );\n for (const op of surfaceOperations) {\n const requested = getMarkdownOperationSurfaceId(op) ?? fenceSurfaceId;\n const surfaceId = scopedSurfaceId(\n requested,\n message.id,\n segment.target,\n );\n let draft = drafts.get(surfaceId);\n if (!draft) {\n draft = {\n surfaceId,\n target: segment.target ?? GENERATIVE_UI_CHAT_TARGET,\n operations: [],\n streaming: isStreaming,\n };\n drafts.set(surfaceId, draft);\n created.set(key, [...(created.get(key) ?? []), surfaceId]);\n }\n draft.operations.push(\n surfaceId === requested ? op : readdressOnce(op, surfaceId),\n );\n }\n }\n }\n\n // Only a Card with a `variant` prop can become a section.\n const canFlattenCards = hasProp(ui, \"Card\", \"variant\");\n const surfaces: GenerativeUISurfaceContent[] = [];\n const partsBySurface = new Map<string, SurfacePart[]>();\n const childIds = childIdsReader(ui);\n const buildDraft = (draft: SurfaceDraft): BuiltDraft => {\n const prepared = prepareSurfaceOperations({\n operations: draft.operations,\n fallbackSurfaceId: draft.surfaceId,\n catalogId: ui.id,\n catalogIds: catalogIdsOf(ui),\n });\n const operations = splitComponentUpdates(\n expandInlineCreate(createSurfaceFirst(prepared.operations)),\n );\n const isChat = draft.target === GENERATIVE_UI_CHAT_TARGET;\n const parts: SurfacePart[] = isChat\n ? liftProse(\n canFlattenCards\n ? flattenInformationalCards(operations, { childIds })\n : operations,\n draft.surfaceId,\n childIds,\n )\n : [{ kind: \"surface\", surfaceId: draft.surfaceId, operations }];\n const contents = parts.flatMap((part) =>\n part.kind === \"surface\"\n ? [surfaceContent(part.surfaceId, draft, part.operations, options)]\n : [],\n );\n return { ...draft, parts, contents };\n };\n for (const draft of drafts.values()) {\n // A draft with the same operations, target and status as in the last\n // build gives the same surfaces, so they are not built again.\n const built = cache\n ? cache.drafts.get(\n draft.surfaceId,\n () => buildDraft(draft),\n (last) =>\n last.target === draft.target &&\n last.streaming === draft.streaming &&\n sameItems(last.operations, draft.operations),\n )\n : buildDraft(draft);\n partsBySurface.set(draft.surfaceId, built.parts);\n surfaces.push(...built.contents);\n }\n cache?.endBuild();\n\n /** The surface ids of the parts of each split surface, by surface id. */\n const parts = new Map<string, string[]>();\n for (const [surfaceId, surfaceParts] of partsBySurface) {\n const ids = surfaceParts.flatMap((part) =>\n part.kind === \"surface\" ? [part.surfaceId] : [],\n );\n parts.set(surfaceId, ids);\n }\n\n const fences = new Map<string, MarkdownFenceBlock[]>();\n for (const [key, surfaceIds] of created) {\n const blocks: MarkdownFenceBlock[] = [];\n for (const surfaceId of surfaceIds) {\n if (drafts.get(surfaceId)?.target !== GENERATIVE_UI_CHAT_TARGET) continue;\n for (const part of partsBySurface.get(surfaceId) ?? []) {\n blocks.push(\n part.kind === \"markdown\"\n ? part\n : { kind: \"surface\", surfaceId: part.surfaceId },\n );\n }\n }\n if (blocks.length > 0) fences.set(key, blocks);\n }\n\n return { surfaces, fences, functionCalls, parts };\n}\n\n/** The declared functions, as `validateOperation` takes them. */\nfunction declaredFunctions(ui: GenerativeUI) {\n const functions: Record<string, GenerativeUIFunctionManifest> = {};\n for (const [name, fn] of ui.functions) {\n try {\n functions[name] = {\n ...(fn.description ? { description: fn.description } : {}),\n parameters: toJsonSchema(fn.parameters),\n };\n } catch {\n // A schema that cannot become JSON Schema still names a function.\n functions[name] = { parameters: {} };\n }\n }\n return functions;\n}\n\n/** True when `list` starts with all the items of `prefix`. */\nfunction startsWith(list: string[], prefix: string[]) {\n return (\n list.length >= prefix.length &&\n prefix.every((item, index) => item === list[index])\n );\n}\n\n/** A content that deletes a surface that the fences no longer write. */\nfunction removalContent(surfaceId: string, catalogId: string) {\n const content: GenerativeUISurfaceContent = {\n surfaceId,\n target: GENERATIVE_UI_CHAT_TARGET,\n catalogId,\n status: \"ready\",\n rejected: [],\n operations: [\n { version: A2UI_VERSION, createSurface: { surfaceId, catalogId } },\n { version: A2UI_VERSION, deleteSurface: { surfaceId } },\n ],\n };\n return content;\n}\n\n/**\n * The markdown transport source of one surface manager. It turns the\n * messages of a thread into surfaces in the manager, and keeps the blocks\n * that each fence renders.\n */\nexport class MarkdownSurfaceSource {\n private readonly functions: Record<string, GenerativeUIFunctionManifest>;\n /** By thread: the blocks of each fence, from the latest sync. */\n private readonly fences = new Map<\n string,\n Map<string, MarkdownFenceBlock[]>\n >();\n /** By thread, then surface: the operations last ingested, as JSON. */\n private readonly ingested = new Map<string, Map<string, string[]>>();\n /** By thread, then surface: the content last ingested. */\n private readonly contents = new Map<\n string,\n Map<string, GenerativeUISurfaceContent>\n >();\n /** By thread: the results of the earlier builds. */\n private readonly caches = new Map<string, MarkdownBuildCache>();\n\n constructor(\n private readonly manager: GenerativeUISurfaceManager,\n private readonly ui: GenerativeUI,\n ) {\n this.functions = declaredFunctions(ui);\n }\n\n /**\n * Builds the surfaces of `threadId` from `messages` and gives them to the\n * manager. A surface that an earlier sync of the thread made, and that the\n * messages no longer write, is deleted. Other threads do not change.\n *\n * @param threadId - The thread of the messages.\n * @param agentId - The agent that owns the thread.\n * @param messages - All messages of the thread.\n * @param options - `running`: the last message can still grow.\n * @returns The function calls of the fences, in order. The source does\n * not run them.\n */\n sync(\n threadId: string,\n agentId: string | undefined,\n messages: readonly Message[],\n options: { running: boolean },\n ) {\n let cache = this.caches.get(threadId);\n if (!cache) {\n cache = new MarkdownBuildCache();\n this.caches.set(threadId, cache);\n }\n const result = buildMarkdownSurfaces(messages, {\n ui: this.ui,\n functions: this.functions,\n running: options.running,\n cache,\n });\n this.fences.set(threadId, result.fences);\n // The parts of a split surface share one data model, so an input in one\n // part drives a binding in another.\n for (const parts of result.parts.values()) {\n this.manager.linkSurfaces(threadId, parts);\n }\n const previous = this.ingested.get(threadId) ?? new Map<string, string[]>();\n const previousContents =\n this.contents.get(threadId) ??\n new Map<string, GenerativeUISurfaceContent>();\n const next = new Map<string, string[]>();\n const nextContents = new Map<string, GenerativeUISurfaceContent>();\n for (const content of result.surfaces) {\n nextContents.set(content.surfaceId, content);\n const before = previous.get(content.surfaceId);\n // The cache gives the same content object for a surface that did not\n // change, and the manager already has it.\n if (before && previousContents.get(content.surfaceId) === content) {\n next.set(content.surfaceId, before);\n continue;\n }\n const fingerprints = content.operations.map((op) => JSON.stringify(op));\n // The manager checks only the last operation that it applied. When an\n // earlier one changed (for example, the prose lift moved a split), an\n // empty content makes it start the surface again.\n if (before && !startsWith(fingerprints, before)) {\n this.manager.ingest(threadId, agentId, { ...content, operations: [] });\n }\n this.manager.ingest(threadId, agentId, content);\n next.set(content.surfaceId, fingerprints);\n }\n for (const surfaceId of previous.keys()) {\n if (next.has(surfaceId)) continue;\n this.manager.ingest(\n threadId,\n agentId,\n removalContent(surfaceId, this.ui.id),\n );\n }\n this.ingested.set(threadId, next);\n this.contents.set(threadId, nextContents);\n return result.functionCalls;\n }\n\n /**\n * The blocks that a fence renders in the chat, from the latest sync of the\n * thread. `undefined` when the fence renders nothing: it updates a surface\n * of an earlier fence, its surface is for a named target, or it has no\n * complete operation yet.\n */\n getFenceBlocks(threadId: string, messageId: string, fenceIndex: number) {\n return this.fences.get(threadId)?.get(fenceKey(messageId, fenceIndex));\n }\n}\n\nconst sources = new WeakMap<\n GenerativeUISurfaceManager,\n MarkdownSurfaceSource\n>();\n\n/**\n * The markdown source of a generative UI runtime. There is one source for\n * each surface manager. The root syncs it, and the chat messages read the\n * fence blocks from it.\n */\nexport function getMarkdownSurfaceSource(runtime: {\n manager: GenerativeUISurfaceManager;\n ui: GenerativeUI;\n}) {\n let source = sources.get(runtime.manager);\n if (!source) {\n source = new MarkdownSurfaceSource(runtime.manager, runtime.ui);\n sources.set(runtime.manager, source);\n }\n return source;\n}\n","import { ExpressionError, truthOf } from \"./functions\";\n\n/**\n * The two CopilotKit value functions that A2UI 1.0 lacks: `calc`, an\n * arithmetic expression over named args, and `series`, a computed list.\n * Both are catalog functions in the sense of the spec: a catalog may\n * declare functions beyond the basic ones, and the model learns them from\n * the schema. The expression language is small and closed: numbers,\n * strings, booleans, the args by name, `+ - * / %`, comparisons, `&& || !`,\n * `cond ? a : b`, parentheses, and min, max, round, floor, ceil, abs. No\n * property access, no assignment, no code.\n */\n\ntype Value = number | string | boolean | null;\nexport type CalcScope = Readonly<Record<string, unknown>>;\n\nconst MAX_SERIES = 1000;\n\n// ---- Lexer ----\n\ntype Token =\n | { kind: \"number\"; value: number }\n | { kind: \"string\"; value: string }\n | { kind: \"name\"; value: string }\n | { kind: \"op\"; value: string }\n | { kind: \"end\" };\n\nconst OPERATORS = [\n \"&&\",\n \"||\",\n \"==\",\n \"!=\",\n \"<=\",\n \">=\",\n \"<\",\n \">\",\n \"+\",\n \"-\",\n \"*\",\n \"/\",\n \"%\",\n \"(\",\n \")\",\n \",\",\n \"?\",\n \":\",\n \"!\",\n];\n\nfunction tokenize(source: string): Token[] {\n const tokens: Token[] = [];\n let i = 0;\n while (i < source.length) {\n const char = source[i];\n if (/\\s/.test(char)) {\n i++;\n continue;\n }\n if (/[0-9.]/.test(char)) {\n const match = /^\\d*\\.?\\d+(?:[eE][-+]?\\d+)?|^\\d+\\.?/.exec(source.slice(i));\n if (!match)\n throw new ExpressionError(\n `calc: bad number at \"${source.slice(i, i + 8)}\"`,\n );\n tokens.push({ kind: \"number\", value: Number(match[0]) });\n i += match[0].length;\n continue;\n }\n if (char === \"'\" || char === '\"') {\n let value = \"\";\n i++;\n while (i < source.length && source[i] !== char) {\n if (source[i] === \"\\\\\" && i + 1 < source.length) i++;\n value += source[i++];\n }\n if (i >= source.length)\n throw new ExpressionError(\"calc: unclosed string\");\n i++;\n tokens.push({ kind: \"string\", value });\n continue;\n }\n if (/[A-Za-z_]/.test(char)) {\n const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i))!;\n tokens.push({ kind: \"name\", value: match[0] });\n i += match[0].length;\n continue;\n }\n const op = OPERATORS.find((candidate) => source.startsWith(candidate, i));\n if (!op) throw new ExpressionError(`calc: unexpected \"${char}\"`);\n tokens.push({ kind: \"op\", value: op });\n i += op.length;\n }\n tokens.push({ kind: \"end\" });\n return tokens;\n}\n\n// ---- Values ----\n\nfunction numberOf(value: unknown, what: string): number {\n if (typeof value === \"number\") {\n if (!Number.isFinite(value))\n throw new ExpressionError(`calc: ${what} is not finite`);\n return value;\n }\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n if (value === null || value === undefined) {\n throw new ExpressionError(`calc: ${what} has no value`);\n }\n throw new ExpressionError(`calc: ${what} is not a number`);\n}\n\nfunction describe(value: unknown) {\n return typeof value === \"string\" ? `\"${value}\"` : String(value);\n}\n\nconst MATH: Record<string, (args: number[]) => number> = {\n min: (args) => Math.min(...args),\n max: (args) => Math.max(...args),\n abs: ([x]) => Math.abs(x),\n floor: ([x]) => Math.floor(x),\n ceil: ([x]) => Math.ceil(x),\n round: ([x, decimals = 0]) => {\n const factor = 10 ** Math.trunc(decimals);\n return Math.round(x * factor) / factor;\n },\n};\n\n// ---- Parser ----\n\nclass CalcParser {\n private pos = 0;\n\n constructor(\n private readonly tokens: Token[],\n private readonly scope: CalcScope,\n private readonly source: string,\n ) {}\n\n parse(): Value {\n const value = this.ternary();\n if (this.tokens[this.pos].kind !== \"end\") {\n this.fail(`unexpected \"${this.text(this.tokens[this.pos])}\"`);\n }\n return value;\n }\n\n private fail(what: string): never {\n throw new ExpressionError(`calc: ${what} in \"${this.source}\"`);\n }\n\n private text(token: Token) {\n return token.kind === \"end\" ? \"end\" : String(token.value);\n }\n\n private peekOp(...ops: string[]) {\n const token = this.tokens[this.pos];\n return token.kind === \"op\" && ops.includes(token.value)\n ? token.value\n : undefined;\n }\n\n private expectOp(op: string) {\n if (this.peekOp(op) === undefined) {\n this.fail(\n `expected \"${op}\" but found \"${this.text(this.tokens[this.pos])}\"`,\n );\n }\n this.pos++;\n }\n\n /**\n * Parses a part of the expression that the result does not need (the\n * other branch of `?:`, the right side of a decided `&&` or `||`). It\n * still has to be parsed to find where it ends, so syntax errors are\n * reported, but no value is checked or computed: `n == 0 ? 0 : 10 / n`\n * is a valid guard.\n */\n private skipped(parse: () => Value): null {\n this.skipDepth++;\n try {\n parse();\n } finally {\n this.skipDepth--;\n }\n return null;\n }\n\n /** Above 0 while parsing a part whose value is not needed. */\n private skipDepth = 0;\n\n /** The number of a value, or 0 while skipping. */\n private num(value: unknown, what: string) {\n return this.skipDepth > 0 ? 0 : numberOf(value, what);\n }\n\n private ternary(): Value {\n const condition = this.or();\n if (this.peekOp(\"?\") === undefined) return condition;\n this.pos++;\n const takesFirst = truthOf(condition);\n const whenTrue = takesFirst\n ? this.ternary()\n : this.skipped(() => this.ternary());\n this.expectOp(\":\");\n const whenFalse = takesFirst\n ? this.skipped(() => this.ternary())\n : this.ternary();\n return takesFirst ? whenTrue : whenFalse;\n }\n\n private or(): Value {\n let left = this.and();\n while (this.peekOp(\"||\")) {\n this.pos++;\n if (truthOf(left)) {\n this.skipped(() => this.and());\n left = true;\n } else {\n left = truthOf(this.and());\n }\n }\n return left;\n }\n\n private and(): Value {\n let left = this.equality();\n while (this.peekOp(\"&&\")) {\n this.pos++;\n if (!truthOf(left)) {\n this.skipped(() => this.equality());\n left = false;\n } else {\n left = truthOf(this.equality());\n }\n }\n return left;\n }\n\n private equality(): Value {\n let left = this.comparison();\n for (let op = this.peekOp(\"==\", \"!=\"); op; op = this.peekOp(\"==\", \"!=\")) {\n this.pos++;\n const right = this.comparison();\n const isEqual =\n typeof left === \"number\" || typeof right === \"number\"\n ? this.num(left, \"the left side of ==\") ===\n this.num(right, \"the right side of ==\")\n : left === right;\n left = op === \"==\" ? isEqual : !isEqual;\n }\n return left;\n }\n\n private comparison(): Value {\n let left = this.additive();\n for (\n let op = this.peekOp(\"<\", \"<=\", \">\", \">=\");\n op;\n op = this.peekOp(\"<\", \"<=\", \">\", \">=\")\n ) {\n this.pos++;\n const a = this.num(left, `the left side of ${op}`);\n const b = this.num(this.additive(), `the right side of ${op}`);\n left =\n op === \"<\" ? a < b : op === \"<=\" ? a <= b : op === \">\" ? a > b : a >= b;\n }\n return left;\n }\n\n private additive(): Value {\n let left = this.multiplicative();\n for (let op = this.peekOp(\"+\", \"-\"); op; op = this.peekOp(\"+\", \"-\")) {\n this.pos++;\n const right = this.multiplicative();\n if (\n op === \"+\" &&\n (typeof left === \"string\" || typeof right === \"string\")\n ) {\n left = `${left ?? \"\"}${right ?? \"\"}`;\n } else {\n const a = this.num(left, `the left side of ${op}`);\n const b = this.num(right, `the right side of ${op}`);\n left = op === \"+\" ? a + b : a - b;\n }\n }\n return left;\n }\n\n private multiplicative(): Value {\n let left = this.unary();\n for (\n let op = this.peekOp(\"*\", \"/\", \"%\");\n op;\n op = this.peekOp(\"*\", \"/\", \"%\")\n ) {\n this.pos++;\n const a = this.num(left, `the left side of ${op}`);\n const b = this.num(this.unary(), `the right side of ${op}`);\n if (op !== \"*\" && b === 0 && this.skipDepth === 0) {\n this.fail(\"division by zero\");\n }\n left = op === \"*\" ? a * b : op === \"/\" ? a / b : a % b;\n }\n return left;\n }\n\n private unary(): Value {\n if (this.peekOp(\"-\")) {\n this.pos++;\n return -this.num(this.unary(), \"the operand of -\");\n }\n if (this.peekOp(\"!\")) {\n this.pos++;\n return !truthOf(this.unary());\n }\n return this.primary();\n }\n\n private primary(): Value {\n const token = this.tokens[this.pos++];\n switch (token.kind) {\n case \"number\":\n return token.value;\n case \"string\":\n return token.value;\n case \"name\":\n return this.name(token.value);\n case \"op\":\n if (token.value === \"(\") {\n const value = this.ternary();\n this.expectOp(\")\");\n return value;\n }\n return this.fail(`unexpected \"${token.value}\"`);\n case \"end\":\n return this.fail(\"missing value\");\n }\n }\n\n private name(name: string): Value {\n if (name === \"true\") return true;\n if (name === \"false\") return false;\n if (name === \"null\") return null;\n if (this.peekOp(\"(\")) {\n this.pos++;\n const args: number[] = [];\n if (this.peekOp(\")\") === undefined) {\n for (;;) {\n args.push(this.num(this.ternary(), `an argument of ${name}`));\n if (this.peekOp(\",\") === undefined) break;\n this.pos++;\n }\n }\n this.expectOp(\")\");\n if (this.skipDepth > 0) return null;\n const fn = Object.prototype.hasOwnProperty.call(MATH, name)\n ? MATH[name]\n : undefined;\n if (!fn) this.fail(`unknown function ${name}`);\n if (args.length === 0) this.fail(`${name} needs an argument`);\n return fn(args);\n }\n if (this.skipDepth > 0) return null;\n if (!Object.prototype.hasOwnProperty.call(this.scope, name)) {\n this.fail(`unknown name ${name}; pass it as an arg`);\n }\n const value = this.scope[name];\n if (\n value !== null &&\n typeof value !== \"number\" &&\n typeof value !== \"string\" &&\n typeof value !== \"boolean\"\n ) {\n this.fail(\n `${name} is not a number, text or boolean (${describe(value)})`,\n );\n }\n return value as Value;\n }\n}\n\n/**\n * Evaluates `expression` with the names in `scope`. Gives a number, a\n * string, a boolean or null. Throws an {@link ExpressionError} for a bad\n * expression or a missing name.\n */\nexport function evaluateCalc(expression: unknown, scope: CalcScope): Value {\n if (typeof expression !== \"string\" || expression.trim() === \"\") {\n throw new ExpressionError(\"calc: expression must be a string\");\n }\n return new CalcParser(tokenize(expression), scope, expression).parse();\n}\n\n/** The `calc` function: the expression is `args.expression`, the rest is the scope. */\nexport function calc(args: Record<string, unknown>): Value {\n const { expression, ...scope } = args;\n return evaluateCalc(expression, scope);\n}\n\nconst WHOLE_EXPRESSION = /^\\$\\{([^}]*)\\}$/;\n\n/**\n * Fills `item` for one iteration: a string that is one `${...}` gives the\n * typed value of the expression, a string with `${...}` inside it is\n * interpolated as text, and objects and arrays are walked.\n */\nfunction fillItem(item: unknown, scope: CalcScope): unknown {\n if (typeof item === \"string\") {\n const whole = WHOLE_EXPRESSION.exec(item);\n if (whole) return evaluateCalc(whole[1], scope);\n return item.replace(/\\$\\{([^}]*)\\}/g, (_, expression: string) => {\n const value = evaluateCalc(expression, scope);\n return value === null ? \"\" : String(value);\n });\n }\n if (Array.isArray(item)) return item.map((entry) => fillItem(entry, scope));\n if (typeof item === \"object\" && item !== null) {\n return Object.fromEntries(\n Object.entries(item).map(([key, value]) => [key, fillItem(value, scope)]),\n );\n }\n return item;\n}\n\n/**\n * The `series` function: `count` copies of `item`, with the loop variable\n * (`variable`, default \"i\") counting from `start` (default 1) and the other\n * args in scope of the `${...}` expressions of the item.\n */\nexport function series(args: Record<string, unknown>): unknown[] {\n const { count, item, variable, start, ...scope } = args;\n const length = numberOf(count, \"count\");\n if (!Number.isInteger(length) || length < 0) {\n throw new ExpressionError(\"series: count must be a whole number\");\n }\n if (length > MAX_SERIES) {\n throw new ExpressionError(`series: count is at most ${MAX_SERIES}`);\n }\n if (item === undefined) throw new ExpressionError(\"series: item is required\");\n const name = variable === undefined ? \"i\" : variable;\n if (typeof name !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new ExpressionError(\"series: variable must be a name\");\n }\n const first = start === undefined ? 1 : numberOf(start, \"start\");\n return Array.from({ length }, (_, index) =>\n fillItem(item, { ...scope, [name]: first + index }),\n );\n}\n","import {\n A2UI_INDEX_FUNCTION,\n isActionBinding,\n isCallBinding,\n isPathBinding,\n isValidationResult,\n} from \"@copilotkit/shared\";\nimport { calc, series } from \"./calc\";\nimport {\n BASIC_FUNCTIONS,\n ExpressionError,\n givesValidationResult,\n requiresUserActivation,\n} from \"./functions\";\nimport { isRecord } from \"./is-record\";\n\n// The CopilotKit value functions join the registry here, because calc.ts\n// uses the error type and truthOf of functions.ts.\nBASIC_FUNCTIONS.calc = calc;\nBASIC_FUNCTIONS.series = series;\n// formatString needs the resolver. Inside a surface, `call()` below handles\n// it with the surface data; this entry serves the dispatcher, where the\n// agent calls it with literal args and no data model.\nconst NO_DATA: DataReader = { get: () => undefined };\nBASIC_FUNCTIONS.formatString = (args) =>\n resolveDynamicValue(\n { \"@call\": \"formatString\", args },\n { data: NO_DATA, basePath: undefined },\n ).value;\n\n/**\n * Resolves the dynamic values of A2UI 1.0 in a prop, an event context, or\n * a function argument: `{\"@path\"}` bindings read the data model,\n * `{\"@call\"}` values run a basic function, and `formatString` interpolates\n * `${...}` expressions. Objects and arrays are walked, so a binding can sit\n * at any depth. A value with nothing dynamic in it keeps its identity.\n */\n\n/** Reads the data model. The surface data model of web_core fits. */\nexport interface DataReader {\n get(path: string): unknown;\n}\n\nexport interface ResolveContext {\n data: DataReader;\n /**\n * The data model path of the template item this value belongs to, or\n * `undefined` outside of a template. Relative paths resolve against it.\n */\n basePath: string | undefined;\n}\n\nexport interface Resolved<T = unknown> {\n value: T;\n /** The absolute data model paths that the value read. */\n paths: Set<string>;\n}\n\n/** Adds one segment to a JSON pointer: (\"/items\", \"0\") gives \"/items/0\". */\nexport function joinPath(base: string, segment: string) {\n return base === \"/\" ? `/${segment}` : `${base}/${segment}`;\n}\n\n/**\n * The absolute data model path of a binding. A path without a leading \"/\"\n * is relative to the current template item, or to the root outside of one.\n */\nexport function resolvePath(path: string, basePath: string | undefined) {\n if (path.startsWith(\"/\")) return path;\n return joinPath(basePath ?? \"/\", path);\n}\n\n/**\n * The index of the template item at `basePath`: its last segment.\n * `undefined` outside of a template.\n */\nexport function templateIndex(basePath: string | undefined) {\n if (basePath === undefined) return undefined;\n const index = Number(basePath.slice(basePath.lastIndexOf(\"/\") + 1));\n return Number.isInteger(index) ? index : undefined;\n}\n\n/** The value of a ValidationResult where a boolean is expected. */\nfunction coerce(value: unknown, keep: boolean) {\n return !keep && isValidationResult(value) ? value.valid : value;\n}\n\ninterface Walk {\n context: ResolveContext;\n paths: Set<string>;\n}\n\n/**\n * Where a value sits with respect to `checks`: outside, in the `checks`\n * list, or in one check. Only the `condition` of a check keeps a validator\n * result as an object; an arg named `condition` elsewhere does not.\n */\ntype CheckScope = \"outside\" | \"list\" | \"check\";\n\n/**\n * Resolves `value`. `keepValidation` keeps a ValidationResult as it is; by\n * default it becomes its `valid` boolean, which is what every prop except\n * a check condition wants.\n */\nfunction walk(\n value: unknown,\n state: Walk,\n keepValidation: boolean,\n scope: CheckScope = \"outside\",\n): unknown {\n if (Array.isArray(value)) {\n let changed = false;\n const itemScope = scope === \"list\" ? \"check\" : \"outside\";\n const items = value.map((item) => {\n const next = walk(item, state, keepValidation, itemScope);\n if (next !== item) changed = true;\n return next;\n });\n return changed ? items : value;\n }\n if (!isRecord(value)) return value;\n if (isPathBinding(value)) {\n const path = resolvePath(value[\"@path\"], state.context.basePath);\n state.paths.add(path);\n // A data model value is what it is: an object with a `valid` field is\n // not a validator result. Only a validator call is coerced.\n return state.context.data.get(path);\n }\n if (isCallBinding(value)) return call(value, state, keepValidation);\n // An event binding is not a value. It is resolved when the event runs.\n if (isActionBinding(value)) return value;\n let changed = false;\n const entries = Object.entries(value).map(([key, item]) => {\n // Only the condition of a check consumes a ValidationResult as an object.\n const isCondition = scope === \"check\" && key === \"condition\";\n const next = walk(\n item,\n state,\n keepValidation || isCondition,\n key === \"checks\" ? \"list\" : \"outside\",\n );\n if (next !== item) changed = true;\n return [key, next] as const;\n });\n return changed ? Object.fromEntries(entries) : value;\n}\n\nfunction call(\n binding: { \"@call\": string; args?: Record<string, unknown> },\n state: Walk,\n keepValidation: boolean,\n) {\n const name = binding[\"@call\"];\n const rawArgs = binding.args ?? {};\n if (!isRecord(rawArgs)) {\n throw new ExpressionError(`the args of \"${name}\" must be an object`);\n }\n if (name === A2UI_INDEX_FUNCTION) {\n const index = templateIndex(state.context.basePath);\n if (index === undefined) return undefined;\n const offset = walk(rawArgs.offset, state, false);\n return index + (typeof offset === \"number\" ? offset : 0);\n }\n if (name === \"formatString\") {\n const template = walk(rawArgs.value, state, false);\n if (typeof template !== \"string\") {\n throw new ExpressionError(\"formatString takes a string value\");\n }\n return formatString(template, state);\n }\n const fn = Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name)\n ? BASIC_FUNCTIONS[name]\n : undefined;\n if (!fn) throw new ExpressionError(`\"${name}\" is not a basic function`);\n // A value is computed whenever the data changes, never from a gesture. A\n // function that needs one (openUrl) runs only as the functionCall of an\n // event, where the dispatcher checks the gesture.\n if (requiresUserActivation(name)) {\n throw new ExpressionError(\n `\"${name}\" is not a value; bind it as the functionCall of an event`,\n );\n }\n // A validator result in an arg becomes its boolean: `and`, `or`, `not` and\n // `calc` all want one, and a validator reads plain values anyway.\n const args = walk(rawArgs, state, false) as Record<string, unknown>;\n const result = fn(args);\n return givesValidationResult(name) ? coerce(result, keepValidation) : result;\n}\n\n/**\n * Resolves one dynamic value: the value with every binding and function\n * call replaced, plus the data model paths it read. Throws an\n * {@link ExpressionError} for a bad function call.\n */\n/** The options of a resolution. */\nexport interface ResolveOptions {\n /** Keep every validator result as an object. */\n keepValidation?: boolean;\n /**\n * True when `value` is the `checks` prop of a component: the condition\n * of each check then keeps its validator result as an object.\n */\n isChecks?: boolean;\n}\n\nexport function resolveDynamicValue<T = unknown>(\n value: unknown,\n context: ResolveContext,\n options: ResolveOptions = {},\n): Resolved<T> {\n const result = tryResolveDynamicValue<T>(value, context, options);\n if (!result.ok) throw result.error;\n return result;\n}\n\nexport type ResolveAttempt<T = unknown> =\n | ({ ok: true } & Resolved<T>)\n | {\n ok: false;\n error: Error;\n /** The paths read before the failure. A change there may fix it. */\n paths: Set<string>;\n };\n\n/**\n * Like {@link resolveDynamicValue}, but a failure comes back as a result\n * with the paths read so far, so the caller can keep watching them: a\n * function that fails on an empty field works once the user fills it.\n */\nexport function tryResolveDynamicValue<T = unknown>(\n value: unknown,\n context: ResolveContext,\n options: ResolveOptions = {},\n): ResolveAttempt<T> {\n const state: Walk = { context, paths: new Set() };\n try {\n const resolved = walk(\n value,\n state,\n options.keepValidation ?? false,\n options.isChecks ? \"list\" : \"outside\",\n ) as T;\n return { ok: true, value: resolved, paths: state.paths };\n } catch (error) {\n return {\n ok: false,\n error: error instanceof Error ? error : new Error(String(error)),\n paths: state.paths,\n };\n }\n}\n\n/** True when `value` holds a `{\"@path\"}` or `{\"@call\"}` at any depth. */\nexport function containsDynamicValue(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(containsDynamicValue);\n if (!isRecord(value)) return false;\n if (isPathBinding(value) || isCallBinding(value)) return true;\n if (isActionBinding(value)) return false;\n return Object.values(value).some(containsDynamicValue);\n}\n\n// ---- formatString ----\n\n/**\n * The `${...}` grammar of `formatString`:\n *\n * expression := path | literal | call\n * path := \"/\" segments | identifier (\"/\" segments)*\n * literal := 'text' | \"text\" | number | true | false | null\n * call := identifier \"(\" [ name \":\" expression (\",\" name \":\" expression)* ] \")\"\n *\n * A `\\${` in the template is a literal `${`.\n */\nfunction formatString(template: string, state: Walk) {\n let out = \"\";\n let index = 0;\n while (index < template.length) {\n const start = template.indexOf(\"${\", index);\n if (start === -1) {\n out += template.slice(index);\n break;\n }\n if (start > 0 && template[start - 1] === \"\\\\\") {\n out += `${template.slice(index, start - 1)}\\${`;\n index = start + 2;\n continue;\n }\n out += template.slice(index, start);\n const end = matchingBrace(template, start + 2);\n if (end === -1) throw new ExpressionError(\"formatString: unclosed ${\");\n const expression = template.slice(start + 2, end).trim();\n const parser = new ExpressionParser(expression, state);\n const value = parser.parse();\n out += value === undefined || value === null ? \"\" : String(value);\n index = end + 1;\n }\n return out;\n}\n\n/** The index of the `}` that closes the block opened at `from`, or -1. */\nfunction matchingBrace(template: string, from: number) {\n let depth = 1;\n let quote: string | undefined;\n for (let i = from; i < template.length; i++) {\n const char = template[i];\n if (quote) {\n if (char === \"\\\\\") i++;\n else if (char === quote) quote = undefined;\n continue;\n }\n if (char === \"'\" || char === '\"') quote = char;\n else if (char === \"{\") depth++;\n else if (char === \"}\" && --depth === 0) return i;\n }\n return -1;\n}\n\nconst IDENTIFIER = /@?[A-Za-z_][A-Za-z0-9_-]*/y;\nconst NUMBER = /-?\\d+(?:\\.\\d+)?/y;\nconst PATH_SEGMENT = /[^\\s,():'\"]+/y;\n\nclass ExpressionParser {\n private pos = 0;\n\n constructor(\n private readonly source: string,\n private readonly state: Walk,\n ) {}\n\n parse(): unknown {\n const value = this.expression();\n this.skipSpace();\n if (this.pos < this.source.length) {\n throw new ExpressionError(\n `formatString: unexpected \"${this.source.slice(this.pos)}\" in \\${${this.source}}`,\n );\n }\n return value;\n }\n\n private fail(what: string): never {\n throw new ExpressionError(`formatString: ${what} in \\${${this.source}}`);\n }\n\n private skipSpace() {\n while (this.pos < this.source.length && /\\s/.test(this.source[this.pos])) {\n this.pos++;\n }\n }\n\n private match(pattern: RegExp) {\n pattern.lastIndex = this.pos;\n const found = pattern.exec(this.source);\n if (!found) return undefined;\n this.pos = pattern.lastIndex;\n return found[0];\n }\n\n private expression(): unknown {\n this.skipSpace();\n const char = this.source[this.pos];\n if (char === undefined) this.fail(\"missing expression\");\n if (char === \"'\" || char === '\"') return this.quoted(char);\n if (char === \"/\") return this.path(this.match(PATH_SEGMENT) ?? \"/\");\n const number = this.match(NUMBER);\n if (number !== undefined) return Number(number);\n const name = this.match(IDENTIFIER);\n if (name === undefined) this.fail(`unexpected \"${char}\"`);\n if (name === \"true\") return true;\n if (name === \"false\") return false;\n if (name === \"null\") return null;\n this.skipSpace();\n if (this.source[this.pos] === \"(\") return this.call(name);\n // A system function such as @index needs no parentheses.\n if (name.startsWith(\"@\")) return call({ \"@call\": name }, this.state, false);\n // A relative path: \"name\" or \"name/more\".\n const rest = this.source[this.pos] === \"/\" ? this.match(PATH_SEGMENT) : \"\";\n return this.path(`${name}${rest ?? \"\"}`);\n }\n\n private quoted(quote: string) {\n let value = \"\";\n this.pos++;\n while (this.pos < this.source.length) {\n const char = this.source[this.pos++];\n if (char === \"\\\\\" && this.pos < this.source.length) {\n value += this.source[this.pos++];\n } else if (char === quote) {\n return value;\n } else {\n value += char;\n }\n }\n return this.fail(\"unclosed string\");\n }\n\n private path(path: string) {\n const absolute = resolvePath(path, this.state.context.basePath);\n this.state.paths.add(absolute);\n return this.state.context.data.get(absolute);\n }\n\n private call(name: string): unknown {\n this.pos++; // (\n const args: Record<string, unknown> = {};\n this.skipSpace();\n if (this.source[this.pos] === \")\") {\n this.pos++;\n return call({ \"@call\": name, args }, this.state, false);\n }\n for (;;) {\n this.skipSpace();\n const key = this.match(IDENTIFIER);\n if (key === undefined) this.fail(\"expected an argument name\");\n this.skipSpace();\n if (this.source[this.pos] !== \":\") this.fail(`expected \":\" after ${key}`);\n this.pos++;\n args[key] = this.expression();\n this.skipSpace();\n const next = this.source[this.pos++];\n if (next === \")\") break;\n if (next !== \",\") this.fail(`expected \",\" or \")\" after ${key}`);\n }\n return call({ \"@call\": name, args }, this.state, false);\n }\n}\n","import type { StandardSchemaV1 } from \"@copilotkit/shared\";\n\n/** Any Standard Schema: zod, Valibot, ArkType, and more. */\nexport type GenerativeUISchema = StandardSchemaV1;\n\n/** The output type of a schema: what validation gives back. */\nexport type SchemaOutput<Schema> =\n Schema extends StandardSchemaV1<any, infer Output> ? Output : never;\n\n/** The input type of a schema: what validation takes. */\nexport type SchemaInput<Schema> =\n Schema extends StandardSchemaV1<infer Input, any> ? Input : never;\n\nexport type ValidationResult =\n | { success: true; data: unknown }\n | { success: false; issues: readonly StandardSchemaV1.Issue[] };\n\nconst ASYNC_ISSUE: StandardSchemaV1.Issue = {\n message:\n \"the schema validates asynchronously; component props and state need a schema that validates synchronously\",\n};\n\nfunction toResult(result: StandardSchemaV1.Result<unknown>): ValidationResult {\n return result.issues\n ? { success: false, issues: result.issues }\n : { success: true, data: result.value };\n}\n\n/**\n * Validates `value` with `schema`. The result comes back at once when the\n * schema validates synchronously, else as a promise.\n */\nexport function validateSchema(\n schema: StandardSchemaV1,\n value: unknown,\n): ValidationResult | Promise<ValidationResult> {\n const result = schema[\"~standard\"].validate(value);\n return result instanceof Promise ? result.then(toResult) : toResult(result);\n}\n\n/**\n * Validates `value` synchronously, for code that runs during render. A\n * schema that validates asynchronously fails with an issue that says so.\n */\nexport function validateSchemaSync(\n schema: StandardSchemaV1,\n value: unknown,\n): ValidationResult {\n const result = validateSchema(schema, value);\n if (!(result instanceof Promise)) return result;\n // ponytail: the async result is dropped, because render cannot wait for it.\n result.catch(() => {});\n return { success: false, issues: [ASYNC_ISSUE] };\n}\n\n/** True for the issue that `validateSchemaSync` gives for an async schema. */\nexport function isAsyncIssue(issue: StandardSchemaV1.Issue) {\n return issue === ASYNC_ISSUE;\n}\n\n/** The first key of an issue path: the prop the issue is about. */\nexport function issueKey(issue: StandardSchemaV1.Issue) {\n const first = issue.path?.[0];\n const key = typeof first === \"object\" ? first.key : first;\n return key === undefined ? undefined : String(key);\n}\n\n/**\n * `props` without the top-level props whose `null` the schema rejected, or\n * `undefined` when there are none. A model writes `null` for \"not set\" (an\n * empty selection, a value it has not filled yet), and A2UI deletes a data\n * model key that is set to `null`, so a rejected `null` is read as an unset\n * prop. A prop whose schema accepts `null` keeps it.\n */\nexport function withoutRejectedNulls(\n props: Record<string, unknown>,\n issues: readonly StandardSchemaV1.Issue[],\n): Record<string, unknown> | undefined {\n const rejected = new Set<string>();\n for (const issue of issues) {\n const key = issueKey(issue);\n if (key !== undefined && issue.path?.length === 1 && props[key] === null) {\n rejected.add(key);\n }\n }\n if (rejected.size === 0) return undefined;\n return Object.fromEntries(\n Object.entries(props).filter(([key]) => !rejected.has(key)),\n );\n}\n\n/** `\"a.b: message; c: message\"`. A path-less issue gets `fallback`. */\nexport function formatIssues(\n issues: readonly StandardSchemaV1.Issue[],\n fallback = \"props\",\n) {\n return issues\n .map((issue) => {\n const path = (issue.path ?? [])\n .map((segment) =>\n String(typeof segment === \"object\" ? segment.key : segment),\n )\n .join(\".\");\n return `${path || fallback}: ${issue.message}`;\n })\n .join(\"; \");\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 \"./dispatcher\";\nimport type { GenerativeUIErrorInfo, GenerativeUIInvokeResult } from \"./errors\";\nimport type { GenerativeUISurfaceManager } from \"./surface-manager\";\nimport type { GenerativeUITheme } from \"./theme\";\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\n/**\n * Reports an error without ever throwing: `reportError` reaches host code\n * (`onError`), and a throwing host callback must not break rendering or an\n * event handler.\n */\nexport function reportErrorSafely(\n runtime: GenerativeUIRuntime,\n info: GenerativeUIErrorInfo,\n): void {\n try {\n runtime.reportError(info);\n } catch {\n // Intentionally swallowed: there is nowhere safe left to report to.\n }\n}\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 \"./schema\";\nimport type { SchemaInput, ValidationResult } from \"./schema\";\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 { GenerativeUINodeContext } from \"./runtime-context\";\n\n/**\n * The `accessibility` of the A2UI 1.0 component envelope, with its dynamic\n * values resolved. Every component may carry it next to `id` and\n * `component`; it is not a prop of the component.\n */\nexport interface GenerativeUIAccessibility {\n /** A short name for assistive technologies, 1 to 3 words. */\n label?: string;\n /** Instructions, format requirements, or what an action does. */\n description?: string;\n /** How screen readers announce changes (WAI-ARIA `aria-live`). */\n live?: \"off\" | \"polite\" | \"assertive\";\n /** True hides the component and its children from assistive technologies. */\n hidden?: boolean;\n}\n\n/** The ARIA attributes of a resolved `accessibility`, ready to spread. */\nexport interface GenerativeUIAriaAttributes {\n \"aria-label\"?: string;\n \"aria-description\"?: string;\n \"aria-live\"?: \"off\" | \"polite\" | \"assertive\";\n \"aria-hidden\"?: true;\n}\n\nconst LIVE = new Set([\"off\", \"polite\", \"assertive\"]);\n\n/**\n * The accessibility of a component from its resolved `accessibility`\n * value. Fields of the wrong type are left out: a label that is still a\n * binding, or a list, names nothing.\n */\nexport function readAccessibility(\n value: unknown,\n): GenerativeUIAccessibility | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n const { label, description, live, hidden } = value as Record<string, unknown>;\n const result: GenerativeUIAccessibility = {};\n if (typeof label === \"string\" && label !== \"\") result.label = label;\n if (typeof description === \"string\" && description !== \"\") {\n result.description = description;\n }\n if (typeof live === \"string\" && LIVE.has(live)) {\n result.live = live as GenerativeUIAccessibility[\"live\"];\n }\n if (typeof hidden === \"boolean\") result.hidden = hidden;\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\n/**\n * The ARIA attributes for an `accessibility`. `live: \"off\"` is written out:\n * a region inherits the live setting of its ancestors, and a `status` role\n * is live on its own, so only the explicit value silences it.\n *\n * @example\n * ```ts\n * accessibilityAttributes({ label: \"Totals\", live: \"polite\" });\n * // { \"aria-label\": \"Totals\", \"aria-live\": \"polite\" }\n * ```\n */\nexport function accessibilityAttributes(\n accessibility: GenerativeUIAccessibility | undefined,\n): GenerativeUIAriaAttributes {\n if (!accessibility) return {};\n const { label, description, live, hidden } = accessibility;\n return {\n ...(label === undefined ? {} : { \"aria-label\": label }),\n ...(description === undefined ? {} : { \"aria-description\": description }),\n ...(live === undefined ? {} : { \"aria-live\": live }),\n ...(hidden ? { \"aria-hidden\": true as const } : {}),\n };\n}\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\n/**\n * The role of a container that the envelope names. A generic element\n * cannot carry a name, so a label or a description makes it a `group`,\n * unless the component has a role of its own.\n */\nexport function namedRole(\n aria: GenerativeUIAriaAttributes,\n explicit: string | undefined,\n): string | undefined {\n if (explicit !== undefined) return explicit;\n const isNamed =\n aria[\"aria-label\"] !== undefined || aria[\"aria-description\"] !== undefined;\n return isNamed ? \"group\" : undefined;\n}\n\n/**\n * The part of the attributes for the focusable control of a labelled pair:\n * its name and its description. ARIA names are not inherited, so the\n * wrapper of a control cannot name it.\n */\nexport function controlAria(\n aria: GenerativeUIAriaAttributes,\n): Pick<GenerativeUIAriaAttributes, \"aria-label\" | \"aria-description\"> {\n const { \"aria-label\": label, \"aria-description\": description } = aria;\n return {\n ...(label === undefined ? {} : { \"aria-label\": label }),\n ...(description === undefined ? {} : { \"aria-description\": description }),\n };\n}\n\n/**\n * The part of the attributes for the wrapper around a control: hidden and\n * live cover the label and the control together.\n */\nexport function wrapperAria(\n aria: GenerativeUIAriaAttributes,\n): Pick<GenerativeUIAriaAttributes, \"aria-hidden\" | \"aria-live\"> {\n const { \"aria-hidden\": hidden, \"aria-live\": live } = aria;\n return {\n ...(hidden === undefined ? {} : { \"aria-hidden\": hidden }),\n ...(live === undefined ? {} : { \"aria-live\": live }),\n };\n}\n","import type {\n GenerativeUIActionBinding,\n GenerativeUIUserEvent,\n} from \"@copilotkit/shared\";\nimport { GenerativeUIError } from \"./errors\";\nimport { resolveDynamicValue } from \"./resolve\";\nimport type { ResolveContext } from \"./resolve\";\nimport type { GenerativeUIInvokeResult } from \"./errors\";\nimport type { GenerativeUIInvocationOrigin } from \"./dispatcher\";\nimport { reportErrorSafely } from \"./runtime-context\";\nimport type { GenerativeUIRuntime } from \"./runtime-context\";\nimport { formatIssues, validateSchema } from \"./schema\";\nimport type { GenerativeUISchema } from \"./schema\";\nimport type { ManagedSurface } from \"./surface-manager\";\n\n/** One call of an event prop by a component. */\ninterface EventCall {\n runtime: GenerativeUIRuntime;\n surface: ManagedSurface;\n componentId: string;\n /** The event prop name, for error messages. */\n name: string;\n /**\n * The event `parameters`. When absent, the args go on unchecked. That is\n * the case for a matched event without `parameters`: the function schema\n * checks them.\n */\n parameters?: GenerativeUISchema;\n args: unknown;\n}\n\n/**\n * The context of a running event binding: it reads the surface data model\n * and resolves relative paths against the template item of the component.\n * A function that needs a user gesture (openUrl) is not a value here\n * either; it runs through the dispatcher as the binding's functionCall.\n */\nfunction eventContext(\n surface: ManagedSurface,\n basePath: string | undefined,\n): ResolveContext {\n return { data: surface.model.dataModel, basePath };\n}\n\n/**\n * A value of an event binding with its dynamic values resolved: `{\"@path\"}`\n * bindings and function values, at any depth.\n */\nfunction resolveValue(\n surface: ManagedSurface,\n basePath: string | undefined,\n value: unknown,\n) {\n return resolveDynamicValue(value, eventContext(surface, basePath)).value;\n}\n\n/**\n * The entries of an args or context record, each resolved on its own. The\n * record is not resolved as a whole, because a record with one `event` or\n * `functionCall` key would look like an action binding and stay as it is.\n */\nfunction resolveValues(\n surface: ManagedSurface,\n basePath: string | undefined,\n values: Record<string, unknown> | undefined,\n) {\n return Object.fromEntries(\n Object.entries(values ?? {}).map(([key, value]) => [\n key,\n resolveValue(surface, basePath, value),\n ]),\n );\n}\n\n/**\n * The `userMessage` of an event binding, as text. A `{\"@path\"}` or a\n * function value is resolved. `undefined` when there is no message, or\n * the value is not a string.\n */\nfunction resolveUserMessage(\n surface: ManagedSurface,\n basePath: string | undefined,\n userMessage: unknown,\n) {\n const value = resolveValue(surface, basePath, userMessage);\n return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Validates the component's args with the event `parameters`, then runs\n * `send` with them. Never throws: every failure is reported and becomes\n * `{ ok: false, error }`.\n */\nasync function runEvent(\n call: EventCall,\n send: (\n componentArgs: unknown,\n origin: GenerativeUIInvocationOrigin,\n ) => Promise<GenerativeUIInvokeResult>,\n): Promise<GenerativeUIInvokeResult> {\n const { runtime, surface, componentId, name, parameters, args } = call;\n const origin = { surfaceId: surface.surfaceId, componentId };\n try {\n if (!parameters) return await send(args ?? {}, origin);\n // A schema that validates synchronously sends in the same tick.\n const result = validateSchema(parameters, args ?? {});\n const parsed = result instanceof Promise ? await result : result;\n if (!parsed.success) {\n const error = new GenerativeUIError(\n \"invalid_event_args\",\n `${name}: ${formatIssues(parsed.issues, \"args\")}`,\n );\n reportErrorSafely(runtime, { kind: \"event\", ...origin, error });\n return { ok: false, error };\n }\n return await send(parsed.data ?? {}, origin);\n } catch (cause) {\n const error = new GenerativeUIError(\n \"event_forward_failed\",\n `${name}: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n reportErrorSafely(runtime, { kind: \"event\", ...origin, error });\n return { ok: false, error };\n }\n}\n\n/**\n * Runs one call of an event that the model bound: validates the component's\n * args, merges them with the args from the binding (binding literals win),\n * then calls a declared function or forwards an agent event. Never throws.\n */\nexport function invokeBoundEvent(\n params: EventCall & {\n binding: GenerativeUIActionBinding;\n /** The template item path of the component, for relative paths. */\n basePath: string | undefined;\n },\n) {\n const { runtime, surface, binding, basePath } = params;\n return runEvent(params, (args, origin) => {\n // ponytail: the args are spread into the call. Args that are not an object are lost, as before.\n const componentArgs = args as Record<string, unknown>;\n if (\"functionCall\" in binding) {\n return runtime.dispatcher.invoke(\n binding.functionCall[\"@call\"],\n {\n ...componentArgs,\n ...resolveValues(surface, basePath, binding.functionCall.args),\n },\n origin,\n );\n }\n const { event } = binding;\n const forwarded: GenerativeUIUserEvent = {\n name: event.name,\n ...origin,\n timestamp: new Date().toISOString(),\n userMessage: resolveUserMessage(surface, basePath, event.userMessage),\n context: {\n ...componentArgs,\n ...resolveValues(surface, basePath, event.context),\n },\n };\n return runtime.forwardEvent(forwarded, surface.agentId);\n });\n}\n\n/**\n * Runs one call of an event that matches a declared function: validates the\n * component's args with the event `parameters` (if any), then calls the\n * function, which validates them with its own schema. Never throws.\n */\nexport function invokeMatchedEvent(\n params: EventCall & { functionName: string },\n) {\n const { runtime, functionName } = params;\n return runEvent(params, (componentArgs, origin) =>\n runtime.dispatcher.invoke(functionName, componentArgs, origin),\n );\n}\n","import type {\n BACKGROUNDS,\n BORDER_COLORS,\n RADII,\n TEXT_COLORS,\n} from \"./standard/tokens\";\n\ntype TextColor = (typeof TEXT_COLORS)[number];\ntype BorderColor = (typeof BORDER_COLORS)[number];\ntype Background = (typeof BACKGROUNDS)[number];\ntype Radius = Exclude<(typeof RADII)[number], \"full\">;\ntype Tint = \"info\" | \"warning\" | \"caution\" | \"success\" | \"danger\" | \"discovery\";\ntype ChartSeries = 1 | 2 | 3 | 4 | 5 | 6;\n\n/** Every CSS variable that the standard components read. */\nexport type GenerativeUIThemeVariable =\n | `--a2ui-color-text-${TextColor}`\n | `--a2ui-color-${Background}`\n | `--a2ui-color-border-${BorderColor}`\n | `--a2ui-color-${Tint}-soft`\n | `--a2ui-radius-${Radius}`\n | `--a2ui-chart-${ChartSeries}`\n | \"--a2ui-color-accent\"\n | \"--a2ui-color-on-accent\"\n | \"--a2ui-color-panel\"\n | \"--a2ui-color-control\"\n | \"--a2ui-color-focus\"\n | \"--a2ui-color-shimmer\"\n | \"--a2ui-color-chart-cursor\"\n | \"--a2ui-color-slider-track\"\n | \"--a2ui-color-badge-secondary\"\n | \"--a2ui-color-border-control\"\n | \"--a2ui-color-highlight-green\"\n | \"--a2ui-color-highlight-orange\"\n | \"--a2ui-color-highlight-pink\"\n | \"--a2ui-color-backdrop\"\n | \"--a2ui-color-overlay\"\n | \"--a2ui-color-rating\"\n | \"--a2ui-shadow-xs\"\n | \"--a2ui-shadow-sm\"\n | \"--a2ui-shadow-soft\"\n | \"--a2ui-shadow-md\"\n | \"--a2ui-font-family\"\n | \"--a2ui-heading-margin\"\n | \"--a2ui-block-margin\";\n\n/** Values for the theme variables. A name that is not one is a type error. */\nexport type GenerativeUIThemeVariables = {\n [Variable in GenerativeUIThemeVariable]?: string;\n};\n\n/** The values of one color scheme, plus the map style of that scheme. */\nexport type GenerativeUIThemeValues = GenerativeUIThemeVariables & {\n /** A MapLibre style URL for the Map component. */\n mapStyle?: string;\n};\n\n/**\n * The look of generated UI. Values at the top level apply in light and in\n * dark mode. Values in `dark` replace them in dark mode. Dark mode is on\n * when an ancestor of the surface has the `dark` class, like the CopilotKit\n * chat.\n *\n * @example\n * ```ts\n * const theme: GenerativeUITheme = {\n * \"--a2ui-color-accent\": \"#d97706\",\n * \"--a2ui-font-family\": \"Inter, sans-serif\",\n * dark: { \"--a2ui-color-panel\": \"#1f2937\" },\n * };\n * ```\n */\nexport type GenerativeUITheme = GenerativeUIThemeValues & {\n dark?: GenerativeUIThemeValues;\n};\n\n/**\n * The built-in dark values. The light values are the fallbacks in the\n * components, so a surface is light when no variable is set.\n */\nexport const DARK_THEME: GenerativeUIThemeVariables = {\n \"--a2ui-color-text-default\": \"#ececec\",\n \"--a2ui-color-text-prose\": \"#ececec\",\n \"--a2ui-color-text-primary\": \"#ececec\",\n \"--a2ui-color-text-emphasis\": \"#fff\",\n \"--a2ui-color-text-secondary\": \"#b4b4b4\",\n \"--a2ui-color-text-tertiary\": \"#8e8e8e\",\n \"--a2ui-color-text-success\": \"#4fd1a5\",\n \"--a2ui-color-text-info\": \"#6cb6ff\",\n \"--a2ui-color-text-warning\": \"#e3b341\",\n \"--a2ui-color-text-caution\": \"#e3b341\",\n \"--a2ui-color-text-danger\": \"#ff7b72\",\n \"--a2ui-color-text-discovery\": \"#bc9cff\",\n \"--a2ui-color-surface\": \"#1f1f1f\",\n \"--a2ui-color-surface-secondary\": \"#2a2a2a\",\n \"--a2ui-color-surface-tertiary\": \"#3a3a3a\",\n \"--a2ui-color-surface-elevated\": \"#262626\",\n \"--a2ui-color-surface-elevated-secondary\": \"#2f2f2f\",\n \"--a2ui-color-surface-inverted\": \"#f2f2f2\",\n \"--a2ui-color-surface-soft\": \"#232323\",\n \"--a2ui-color-info\": \"rgba(80, 160, 255, 0.14)\",\n \"--a2ui-color-warning\": \"rgba(240, 180, 60, 0.14)\",\n \"--a2ui-color-caution\": \"rgba(240, 180, 60, 0.14)\",\n \"--a2ui-color-success\": \"rgba(60, 200, 150, 0.14)\",\n \"--a2ui-color-danger\": \"rgba(255, 110, 100, 0.14)\",\n \"--a2ui-color-discovery\": \"rgba(170, 130, 255, 0.14)\",\n \"--a2ui-color-info-soft\": \"rgba(80, 160, 255, 0.08)\",\n \"--a2ui-color-warning-soft\": \"rgba(240, 180, 60, 0.08)\",\n \"--a2ui-color-caution-soft\": \"rgba(240, 180, 60, 0.08)\",\n \"--a2ui-color-success-soft\": \"rgba(60, 200, 150, 0.08)\",\n \"--a2ui-color-danger-soft\": \"rgba(255, 110, 100, 0.08)\",\n \"--a2ui-color-discovery-soft\": \"rgba(170, 130, 255, 0.08)\",\n \"--a2ui-color-info-solid\": \"#3b8eea\",\n \"--a2ui-color-warning-solid\": \"#c99a2e\",\n \"--a2ui-color-caution-solid\": \"#c99a2e\",\n \"--a2ui-color-success-solid\": \"#2fae86\",\n \"--a2ui-color-danger-solid\": \"#e5534b\",\n \"--a2ui-color-discovery-solid\": \"#9a6ff0\",\n \"--a2ui-color-border-default\": \"rgba(255, 255, 255, 0.12)\",\n \"--a2ui-color-border-subtle\": \"rgba(255, 255, 255, 0.06)\",\n \"--a2ui-color-border-strong\": \"#4a4a4a\",\n \"--a2ui-color-border-info\": \"#2f5f8f\",\n \"--a2ui-color-border-warning\": \"#6b5420\",\n \"--a2ui-color-border-caution\": \"#6b5420\",\n \"--a2ui-color-border-success\": \"#1f5f4b\",\n \"--a2ui-color-border-danger\": \"#7a2f2b\",\n \"--a2ui-color-border-discovery\": \"#4f3a80\",\n \"--a2ui-color-border-control\": \"rgba(255, 255, 255, 0.2)\",\n \"--a2ui-color-accent\": \"#f2f2f2\",\n \"--a2ui-color-on-accent\": \"#0d0d0d\",\n \"--a2ui-color-panel\": \"#262626\",\n \"--a2ui-color-control\": \"#2f2f2f\",\n \"--a2ui-color-focus\": \"#3b9bff\",\n \"--a2ui-color-shimmer\": \"rgba(255, 255, 255, 0.12)\",\n \"--a2ui-color-chart-cursor\": \"rgba(255, 255, 255, 0.06)\",\n \"--a2ui-color-slider-track\": \"rgba(255, 255, 255, 0.1)\",\n \"--a2ui-color-badge-secondary\": \"rgba(255, 255, 255, 0.08)\",\n \"--a2ui-color-highlight-green\": \"#1d4a37\",\n \"--a2ui-color-highlight-orange\": \"#4d3418\",\n \"--a2ui-color-highlight-pink\": \"#4d2338\",\n \"--a2ui-shadow-xs\": \"0 1px 2px rgba(0, 0, 0, 0.5)\",\n \"--a2ui-shadow-sm\": \"0 1px 3px rgba(0, 0, 0, 0.5)\",\n \"--a2ui-shadow-soft\": \"0 1px 3px rgba(0, 0, 0, 0.3)\",\n \"--a2ui-shadow-md\": \"0 4px 12px rgba(0, 0, 0, 0.4)\",\n};\n\nconst VARIABLE_NAME = /^--a2ui-[a-z0-9-]+$/;\n// A value goes into a stylesheet, so it must not be able to end the rule or\n// the element.\nconst UNSAFE_VALUE = /[{};<>]/;\n\n/** Matches the `dark` class on an ancestor of a surface, or on the surface. */\nconst DARK = \":where(.dark)\";\n\n/** The default dark values, as a rule that any theme rule beats. */\nexport const DARK_THEME_CSS = `:where(.dark .a2ui-surface,.a2ui-surface.dark){${declarations(DARK_THEME)}}`;\n\nfunction declarations(values: GenerativeUIThemeValues | undefined) {\n return Object.entries(values ?? {})\n .filter(\n ([name, value]) =>\n VARIABLE_NAME.test(name) &&\n typeof value === \"string\" &&\n !UNSAFE_VALUE.test(value),\n )\n .map(([name, value]) => `${name}:${value}`)\n .join(\";\");\n}\n\n/** A short, stable id for a stylesheet. */\nfunction hashOf(text: string) {\n let hash = 5381;\n for (let index = 0; index < text.length; index++) {\n hash = (hash * 33) ^ text.charCodeAt(index);\n }\n return `t${(hash >>> 0).toString(36)}`;\n}\n\n/**\n * The stylesheet of a theme: its values on the surfaces that carry its id,\n * then its dark values in dark mode. `undefined` when the theme sets no\n * variable. Values that could break out of the rule are left out.\n *\n * @example\n * ```ts\n * themeStyleSheet({ \"--a2ui-color-accent\": \"red\" });\n * // { id: \"t…\", css: '.a2ui-surface[data-a2ui-theme=\"t…\"]{--a2ui-color-accent:red}' }\n * ```\n */\nexport function themeStyleSheet(theme: GenerativeUITheme | undefined) {\n const { dark, ...base } = theme ?? {};\n const both = declarations(base);\n const darkOnly = declarations(dark);\n if (!both && !darkOnly) return undefined;\n const id = hashOf(`${both}|${darkOnly}`);\n // The class makes these rules win over an app rule on `.a2ui-surface`.\n const self = `.a2ui-surface[data-a2ui-theme=\"${id}\"]`;\n const rules = [\n both && `${self}{${both}}`,\n darkOnly && `${DARK} ${self},${self}${DARK}{${darkOnly}}`,\n ].filter(Boolean);\n return { id, css: rules.join(\"\") };\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 { joinPath, resolvePath, tryResolveDynamicValue } from \"./resolve\";\nimport {\n formatIssues,\n isAsyncIssue,\n issueKey,\n validateSchemaSync,\n withoutRejectedNulls,\n} from \"./schema\";\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 \"./errors\";\nimport { invokeBoundEvent, invokeMatchedEvent } from \"./events\";\nimport {\n GenerativeUINodeContext,\n reportErrorSafely,\n useRequiredGenerativeUIRuntime,\n} from \"./runtime-context\";\nimport type { GenerativeUIRuntime } from \"./runtime-context\";\nimport { themeStyleSheet } from \"./theme\";\nimport type {\n GenerativeUISurfaceManager,\n ManagedSurface,\n} from \"./surface-manager\";\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 \"./source\";\nimport type { MarkdownFenceBlock } from \"./source\";\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,wBAAa,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;CAClC,iCAAiC;CACjC,iCAAiC;CACjC,sCAAsC;CACtC,4CAA4C;CAC5C,yCAAyC;CACzC,uCAAuC;CACvC,6CACE;CACF,gDAAgD;CAChD,sDACE;CACF,uCAAuC;CACvC,2CAA2C;CAC3C,iDAAiD;CACjD,sCAAsC;CACtC,wCAAwC;CACxC,4CAA4C;CAC5C,4CAA4C;CAC5C,uCAAuC;CACvC,wCAAwC;CACxC,oCAAoC;CACpC,oCAAoC;CACpC,uCAAuC;CACvC,mCAAmC;C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