@copilotkit/react-core 2.0.0-rc.6 → 2.0.0-rc.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/MarkdownRendererContext-QFCldfW_.d.cts +34 -0
- package/dist/MarkdownRendererContext-QFCldfW_.d.cts.map +1 -0
- package/dist/MarkdownRendererContext-aK63ZFd-.d.mts +34 -0
- package/dist/MarkdownRendererContext-aK63ZFd-.d.mts.map +1 -0
- package/dist/MarkdownSurfaces-Do948N1P.cjs +141 -0
- package/dist/MarkdownSurfaces-Do948N1P.cjs.map +1 -0
- package/dist/MarkdownSurfaces-rtE9wRUP.mjs +135 -0
- package/dist/MarkdownSurfaces-rtE9wRUP.mjs.map +1 -0
- package/dist/ProviderMarkdown-D0eI0aPo.cjs +268 -0
- package/dist/ProviderMarkdown-D0eI0aPo.cjs.map +1 -0
- package/dist/ProviderMarkdown-epL7F3Vt.mjs +214 -0
- package/dist/ProviderMarkdown-epL7F3Vt.mjs.map +1 -0
- package/dist/accessibility-BLK-gE0R.mjs +129 -0
- package/dist/accessibility-BLK-gE0R.mjs.map +1 -0
- package/dist/accessibility-GnodqxkH.cjs +228 -0
- package/dist/accessibility-GnodqxkH.cjs.map +1 -0
- package/dist/chat-B1zczXUD.mjs +1476 -0
- package/dist/chat-B1zczXUD.mjs.map +1 -0
- package/dist/chat-BZ_bvAkg.d.mts +38 -0
- package/dist/chat-BZ_bvAkg.d.mts.map +1 -0
- package/dist/chat-CkFZMo5E.cjs +1579 -0
- package/dist/chat-CkFZMo5E.cjs.map +1 -0
- package/dist/chat-CpZVyF_t.d.cts +38 -0
- package/dist/chat-CpZVyF_t.d.cts.map +1 -0
- package/dist/context.cjs +75 -63
- package/dist/context.cjs.map +1 -1
- package/dist/context.d.cts +62 -107
- package/dist/context.d.cts.map +1 -1
- package/dist/context.d.mts +62 -107
- package/dist/context.d.mts.map +1 -1
- package/dist/context.mjs +76 -64
- package/dist/context.mjs.map +1 -1
- package/dist/generative-ui/map.cjs +26 -0
- package/dist/generative-ui/map.cjs.map +1 -0
- package/dist/generative-ui/map.d.cts +23 -0
- package/dist/generative-ui/map.d.cts.map +1 -0
- package/dist/generative-ui/map.d.mts +23 -0
- package/dist/generative-ui/map.d.mts.map +1 -0
- package/dist/generative-ui/map.mjs +24 -0
- package/dist/generative-ui/map.mjs.map +1 -0
- package/dist/generative-ui/native.cjs +67 -0
- package/dist/generative-ui/native.cjs.map +1 -0
- package/dist/generative-ui/native.d.cts +156 -0
- package/dist/generative-ui/native.d.cts.map +1 -0
- package/dist/generative-ui/native.d.mts +156 -0
- package/dist/generative-ui/native.d.mts.map +1 -0
- package/dist/generative-ui/native.mjs +25 -0
- package/dist/generative-ui/native.mjs.map +1 -0
- package/dist/generative-ui.cjs +33 -8088
- package/dist/generative-ui.cjs.map +1 -1
- package/dist/generative-ui.d.cts +2472 -4789
- package/dist/generative-ui.d.cts.map +1 -1
- package/dist/generative-ui.d.mts +2472 -4789
- package/dist/generative-ui.d.mts.map +1 -1
- package/dist/generative-ui.mjs +9 -8074
- package/dist/generative-ui.mjs.map +1 -1
- package/dist/headless.cjs +289 -1054
- package/dist/headless.cjs.map +1 -1
- package/dist/headless.d.cts +149 -372
- package/dist/headless.d.cts.map +1 -1
- package/dist/headless.d.mts +123 -237
- package/dist/headless.d.mts.map +1 -1
- package/dist/headless.mjs +283 -1054
- package/dist/headless.mjs.map +1 -1
- package/dist/hooks-D2H3iL0N.d.mts +84 -0
- package/dist/hooks-D2H3iL0N.d.mts.map +1 -0
- package/dist/hooks-Dy8HeEdr.d.cts +84 -0
- package/dist/hooks-Dy8HeEdr.d.cts.map +1 -0
- package/dist/index.cjs +8702 -13238
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +312 -872
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +311 -871
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1790 -7803
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +14075 -13828
- package/dist/index.umd.js.map +1 -1
- package/dist/refs-B5Dn59Pn.cjs +43 -0
- package/dist/refs-B5Dn59Pn.cjs.map +1 -0
- package/dist/refs-BW15wX_V.mjs +31 -0
- package/dist/refs-BW15wX_V.mjs.map +1 -0
- package/dist/runtime-context-B7f4M85q.d.mts +215 -0
- package/dist/runtime-context-B7f4M85q.d.mts.map +1 -0
- package/dist/runtime-context-CIkZS0ap.d.cts +215 -0
- package/dist/runtime-context-CIkZS0ap.d.cts.map +1 -0
- package/dist/standard-CSBR4FhM.mjs +5800 -0
- package/dist/standard-CSBR4FhM.mjs.map +1 -0
- package/dist/standard-DBjcBGyd.cjs +5796 -0
- package/dist/standard-DBjcBGyd.cjs.map +1 -0
- package/dist/use-generative-ui-root-CIp0ytE6.cjs +390 -0
- package/dist/use-generative-ui-root-CIp0ytE6.cjs.map +1 -0
- package/dist/use-generative-ui-root-oBqPa6uy.mjs +386 -0
- package/dist/use-generative-ui-root-oBqPa6uy.mjs.map +1 -0
- package/dist/v2/context.d.cts +28 -0
- package/dist/v2/context.d.mts +28 -0
- package/dist/v2/generative-ui/native.d.cts +112 -0
- package/dist/v2/generative-ui/native.d.mts +112 -0
- package/dist/v2/generative-ui.d.cts +96 -0
- package/dist/v2/generative-ui.d.mts +96 -0
- package/dist/v2/headless.d.cts +96 -0
- package/dist/v2/headless.d.mts +96 -0
- package/dist/v2/index.d.cts +2220 -0
- package/dist/v2/index.d.mts +2220 -0
- package/dist/v2/styles.css +5 -0
- package/package.json +116 -24
- package/dist/MarkdownRendererContext-B4Us6mwL.d.cts +0 -954
- package/dist/MarkdownRendererContext-B4Us6mwL.d.cts.map +0 -1
- package/dist/MarkdownRendererContext-CRKFzsEB.d.mts +0 -954
- package/dist/MarkdownRendererContext-CRKFzsEB.d.mts.map +0 -1
- package/dist/MarkdownSurfaces-Bd--93O1.mjs +0 -3676
- package/dist/MarkdownSurfaces-Bd--93O1.mjs.map +0 -1
- package/dist/MarkdownSurfaces-S4wfUl3J.cjs +0 -3991
- package/dist/MarkdownSurfaces-S4wfUl3J.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat-CkFZMo5E.cjs","names":["useShallowStableRef","CopilotChatDefaultLabels","ɵChatConfigurationStore","CopilotKitContext","noopSubscribe","useRequiredGenerativeUIRuntime","ɵanySchema","React","Component","useRequiredGenerativeUIRuntime","GENERATIVE_UI_ROOT_ID","A2UI_COMPONENT_ENVELOPE_KEYS","shallowEqual","GenerativeUINodeContext","useGenerativeUIRuntime","GENERATIVE_UI_CHAT_TARGET","GENERATIVE_UI_ACTIVITY_TYPE","GenerativeUISurfaceContentSchema","GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE","z","GENERATIVE_UI_RENDER_TOOL"],"sources":["../src/providers/CopilotChatConfigurationProvider.tsx","../src/generative-ui/hooks.ts","../src/generative-ui/activity.ts","../src/types/defineToolCallRenderer.ts","../src/generative-ui/host.tsx","../src/generative-ui/boundaries.tsx","../src/generative-ui/SurfaceView.tsx","../src/generative-ui/chat.tsx"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n CopilotChatDefaultLabels,\n ɵChatConfigurationStore,\n} from \"@copilotkit/core\";\nimport type { CopilotChatLabels } from \"@copilotkit/core\";\nimport { CopilotKitContext, useDefaultAgentId } from \"../context\";\n// Import from the leaf module (not ../lib/slots) so this provider stays lean in\n// the headless entry (issue #4893).\nimport { useShallowStableRef } from \"../lib/shallow-stable-ref\";\n\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 `<CopilotKitProvider>`'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 * Internal: the core store behind this value, so a nested provider can link\n * its own store to it.\n */\n ɵstore?: ɵChatConfigurationStore;\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 // Core owns thread, agent, modal and drawer resolution across the provider\n // chain. This component feeds it props during render (so the value is\n // current on the first pass), reports them after commit (so subscribers such\n // as nested stores and the open-thread registration hear about it), and\n // projects the snapshot into context.\n const providerAgentId = useDefaultAgentId();\n const options = {\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n providerAgentId,\n };\n const parentStore = parentConfig?.ɵstore ?? null;\n const [store] = useState(\n () => new ɵChatConfigurationStore(options, parentStore),\n );\n store.ɵsetOptions(options);\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n useEffect(() => {\n store.update({\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n providerAgentId,\n });\n }, [\n store,\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n providerAgentId,\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 useEffect(() => {\n if (copilotkit === undefined) return;\n return store.bindOpenThread(copilotkit);\n }, [copilotkit, store]);\n\n // A provider without its own modal shows the modal state in context above\n // it, which may be a ControlledModalOpenScope's host-controlled value.\n const ownsModal = isModalDefaultOpen !== undefined;\n const isModalOpen =\n ownsModal || !parentConfig\n ? snapshot.isModalOpen\n : parentConfig.isModalOpen;\n const setModalOpen =\n ownsModal || !parentConfig ? store.setModalOpen : parentConfig.setModalOpen;\n\n // Keyed on the snapshot's fields, not its identity: a drawer that\n // unregisters and re-registers in one commit yields an equal snapshot, and\n // a new context value there would re-run the drawer's effect forever.\n const {\n agentId: resolvedAgentId,\n threadId: resolvedThreadId,\n hasExplicitThreadId: resolvedHasExplicitThreadId,\n drawerOpen,\n drawerRegistered,\n } = snapshot;\n const configurationValue: CopilotChatConfigurationValue = useMemo(\n () => ({\n labels: mergedLabels,\n agentId: resolvedAgentId,\n threadId: resolvedThreadId,\n hasExplicitThreadId: resolvedHasExplicitThreadId,\n isModalOpen,\n setModalOpen,\n drawerOpen,\n setDrawerOpen: store.setDrawerOpen,\n drawerRegistered,\n registerDrawer: store.registerDrawer,\n ɵregisterModalCloser: store.registerModalCloser,\n setActiveThreadId: store.setActiveThreadId,\n startNewThread: store.startNewThread,\n ɵstore: store,\n }),\n [\n mergedLabels,\n resolvedAgentId,\n resolvedThreadId,\n resolvedHasExplicitThreadId,\n isModalOpen,\n setModalOpen,\n drawerOpen,\n drawerRegistered,\n store,\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","import { useEffect, useRef, useSyncExternalStore } from \"react\";\nimport type {\n GenerativeUI,\n GenerativeUIDefinitionsOf,\n GenerativeUIFunctionArgs,\n GenerativeUIFunctionName,\n GenerativeUIStateOf,\n} from \"./catalog\";\nimport { useRequiredGenerativeUIRuntime } from \"./runtime-context\";\nimport type { GenerativeUIRuntime } from \"./runtime-context\";\nimport { formatIssues, validateSchema } from \"@copilotkit/shared/generative-ui\";\nimport type {\n SchemaInput,\n ValidationResult,\n} from \"@copilotkit/shared/generative-ui\";\n\nconst noopSubscribe = () => () => {};\nconst zero = () => 0;\n\n/** Re-renders on any surface-manager change. */\nexport function useManagerVersion(runtime: GenerativeUIRuntime | null): number {\n return useSyncExternalStore(\n runtime?.manager.subscribe ?? noopSubscribe,\n runtime?.manager.getVersion ?? zero,\n zero,\n );\n}\n\n/** What `useGenerativeUIState` takes for one key: the input of its schema. */\ntype StateInput<\n UI extends GenerativeUI<any>,\n Key extends keyof GenerativeUIStateOf<UI>,\n> = SchemaInput<GenerativeUIDefinitionsOf<UI>[\"state\"][Key]>;\n\n/**\n * Experimental. Gives one key of the app state declared in\n * `createGenerativeUI({ state })` its value. Bound props of generated\n * components read it. The model does not see it.\n *\n * The key is set on mount and when the value changes (compared as JSON). It\n * is removed on unmount.\n *\n * @param ui - The object from `createGenerativeUI`. It gives the key and the\n * value their types.\n * @param key - A top-level key of `state`.\n * @param value - The value of that key. It must fit the key's schema.\n *\n * @example\n * ```tsx\n * useGenerativeUIState(storeUI, \"cart\", { count, total, coupon, items });\n * ```\n */\nexport function useGenerativeUIState<\n UI extends GenerativeUI<any>,\n Key extends keyof GenerativeUIStateOf<UI> & string,\n>(ui: UI, key: Key, value: StateInput<UI, Key>) {\n // ponytail: `ui` is for types only. The hook writes to the provider's generative UI and does not check that `ui` is that object.\n const runtime = useRequiredGenerativeUIRuntime();\n const serialized = JSON.stringify(value);\n useEffect(() => {\n const raw: unknown = JSON.parse(serialized ?? \"null\");\n let current = true;\n const apply = (parsed: ValidationResult) => {\n if (!current) return;\n if (parsed.success) {\n runtime.manager.setState(key, parsed.data);\n return;\n }\n // An invalid value is not stored. Bound props that read this key show the props fallback.\n runtime.manager.removeState(key);\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\n `[generativeUI] useGenerativeUIState: invalid value for \"${key}\": ${formatIssues(parsed.issues, \"value\")}`,\n );\n }\n };\n // Selectors get the parsed output, so schema defaults and transforms run\n // here. A schema that validates synchronously applies at once.\n const schema = runtime.ui.state.get(key);\n const parsed = schema\n ? validateSchema(schema, raw)\n : { success: true as const, data: raw };\n if (parsed instanceof Promise) void parsed.then(apply);\n else apply(parsed);\n return () => {\n current = false;\n };\n }, [runtime, key, serialized]);\n useEffect(() => () => runtime.manager.removeState(key), [runtime, key]);\n}\n\n/**\n * Experimental. Mounts the handler of a function declared in\n * `createGenerativeUI({ functions })`. Generated UI can call the function\n * only while exactly one handler for it is mounted.\n *\n * The handler gets the parsed arguments: schema defaults are set. It can\n * change on each render. The latest handler always runs, and the hook does\n * not register again.\n *\n * @param ui - The object from `createGenerativeUI`. It gives the name and the\n * handler arguments their types.\n * @param name - A key of `functions`.\n * @param handler - Runs when generated UI calls the function. Its return\n * value goes back to the caller as `{ ok: true, result }`.\n *\n * @example\n * ```tsx\n * useGenerativeUIFunction(storeUI, \"addToCart\", ({ productId, quantity }) =>\n * cart.addItem(productId, quantity),\n * );\n * ```\n */\nexport function useGenerativeUIFunction<\n UI extends GenerativeUI<any>,\n Name extends GenerativeUIFunctionName<UI>,\n>(\n ui: UI,\n name: Name,\n handler: (args: GenerativeUIFunctionArgs<UI, Name>) => unknown,\n) {\n // ponytail: `ui` is for types only. The hook registers with the provider's generative UI and does not check that `ui` is that object.\n const runtime = useRequiredGenerativeUIRuntime();\n const latest = useRef(handler);\n latest.current = handler;\n useEffect(() => runtime.dispatcher.register(name, latest), [runtime, name]);\n}\n","import { useLayoutEffect, useMemo } from \"react\";\nimport type {\n GenerativeUIRejectedOperation,\n GenerativeUISurfaceContent,\n} from \"@copilotkit/shared\";\nimport type { ManagedSurface } from \"@copilotkit/core/generative-ui\";\n\nexport {\n GenerativeUISurfaceContentSchema,\n parseGenerativeUISurfaceContent,\n} from \"@copilotkit/core/generative-ui\";\nexport type { ParsedGenerativeUISurfaceContent } from \"@copilotkit/core/generative-ui\";\nimport { withCause } from \"@copilotkit/shared/generative-ui\";\nimport { useManagerVersion } from \"./hooks\";\nimport type { GenerativeUIRuntime } from \"./runtime-context\";\n\n/**\n * The rejected operations of a surface (the runtime's first, then the\n * client's) and the error that goes with them, for a wrapper: a generic\n * message, with the same list as its `cause`. The `cause` is not enumerable,\n * so `JSON.stringify`, a spread and error reporters leave the list out.\n * `clientRejected` is appended to in place by the manager, so its length is\n * part of the key.\n */\nexport function useGenerativeUIRejected(\n serverRejected: readonly GenerativeUIRejectedOperation[] | undefined,\n clientRejected: readonly GenerativeUIRejectedOperation[] | undefined,\n): { rejected: GenerativeUIRejectedOperation[]; error: Error | undefined } {\n const clientRejectedCount = clientRejected?.length ?? 0;\n const rejected = useMemo(\n () => [...(serverRejected ?? []), ...(clientRejected ?? [])],\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [serverRejected, clientRejected, clientRejectedCount],\n );\n const error = useMemo(\n () =>\n rejected.length\n ? withCause(\n new Error(`${rejected.length} UI update(s) could not be shown`),\n rejected,\n )\n : undefined,\n [rejected],\n );\n return { rejected, error };\n}\n\n/**\n * What a renderer of one surface activity message shows: the surface (or the\n * failed surface whose `createSurface` was rejected), and its rejected\n * operations with their error (see {@link useGenerativeUIRejected}). It\n * ingests `content` into the manager (idempotent: the root ingests the\n * agent's messages too, and this covers an agent the root has not seen yet),\n * and renders again on every change of the manager.\n *\n * `surface` is undefined when there is no runtime, thread or content, when\n * the surface's target is not `target`, or when the surface does not exist\n * (the agent deleted it). Both rejected lists cover only the latest\n * `render_ui` call (see the manager's ingest).\n */\nexport function useGenerativeUIActivitySurface({\n runtime,\n threadId,\n agentId,\n content,\n target,\n}: {\n runtime: GenerativeUIRuntime | null;\n threadId: string | undefined;\n agentId: string | undefined;\n /** The parsed content; undefined when it is malformed. */\n content: GenerativeUISurfaceContent | undefined;\n /** The target whose surfaces this renderer shows. */\n target: string;\n}): {\n surface: ManagedSurface | undefined;\n rejected: GenerativeUIRejectedOperation[];\n error: Error | undefined;\n} {\n useManagerVersion(runtime);\n useLayoutEffect(() => {\n if (runtime && threadId && content) {\n runtime.manager.ingest(threadId, agentId, content);\n }\n }, [runtime, threadId, agentId, content]);\n const surface =\n runtime && threadId && content && content.target === target\n ? // A surface whose createSurface was rejected shows only the error.\n (runtime.manager.getSurface(threadId, content.surfaceId) ??\n runtime.manager.getFailedSurface(threadId, content.surfaceId))\n : undefined;\n const { rejected, error } = useGenerativeUIRejected(\n content?.rejected,\n surface?.clientRejected,\n );\n return { surface, rejected, error };\n}\n","import type React from \"react\";\nimport { ɵanySchema } from \"@copilotkit/shared\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport type { ToolCallRenderProps } from \"@copilotkit/core\";\nimport type { ReactToolCallRenderer } from \"./react-tool-call-renderer\";\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 a schema that accepts any value.\n */\n// Overload for wildcard tools without args\nexport function defineToolCallRenderer(def: {\n name: \"*\";\n render: (props: ToolCallRenderProps<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: ToolCallRenderProps<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 a schema that accepts any value\n const argsSchema = def.name === \"*\" && !def.args ? ɵanySchema : def.args;\n\n return {\n name: def.name,\n args: argsSchema,\n render: def.render,\n ...(def.agentId ? { agentId: def.agentId } : {}),\n ...(def.group ? { group: true } : {}),\n };\n}\n","import React, { createContext, useContext } from \"react\";\nimport type { ComponentType, ReactNode } from \"react\";\nimport { themeStyleSheet } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUITheme } from \"./runtime-context\";\nimport type { GenerativeUIAriaAttributes } from \"./accessibility\";\n\n/** Props of {@link GenerativeUIHost.SurfaceRoot}. */\nexport interface GenerativeUISurfaceRootProps {\n surfaceId: string;\n /** The theme of the provider (`generativeUI.theme`). */\n theme: GenerativeUITheme | undefined;\n children: ReactNode;\n}\n\n/** Props of {@link GenerativeUIHost.AccessibilityWrapper}. */\nexport interface GenerativeUIAccessibilityWrapperProps {\n /**\n * The hidden state and live region of the component's envelope. A label\n * or a description needs an element with a role, so the component applies\n * those itself.\n */\n attributes: Pick<GenerativeUIAriaAttributes, \"aria-hidden\" | \"aria-live\">;\n children: ReactNode;\n}\n\n/** Props of {@link GenerativeUIHost.NodeFallback}. */\nexport interface GenerativeUINodeFallbackProps {\n message: string;\n /**\n * The node that cannot be shown, or `\"surface\"` for a whole surface that\n * failed. The marker is in the id space: a node the model named\n * `\"surface\"` looks the same. The error report tells the two apart (a\n * surface failure has no `componentId`).\n */\n componentId: string;\n /** Renders the node again. Given for render failures only. */\n retry?: () => void;\n}\n\n/**\n * The few host elements that a surface draws itself, around the catalog's\n * components. The defaults are DOM elements, so a platform without a DOM\n * must supply its own host through `GenerativeUIHostContext`, above every\n * surface it renders. React Native does\n * (`@copilotkit/react-native/generative-ui`), so that the same renderer runs\n * on both.\n *\n * The host and its components must keep their identity across renders:\n * define them at module scope, or memoize them. React takes a new component\n * type for a different element: a `SurfaceRoot` written inline (for example\n * `host={{ ...base, SurfaceRoot: (p) => ... }}`) remounts every surface on\n * each render of its provider, and a new `AccessibilityWrapper` remounts\n * every wrapped component, so what the user typed into them is lost.\n */\nexport interface GenerativeUIHost {\n /** Wraps a whole surface. Must not remount when the theme changes. */\n SurfaceRoot: ComponentType<GenerativeUISurfaceRootProps>;\n /**\n * Wraps every component that has an accessibility envelope, unless its\n * definition applies the envelope itself (`accessibility: \"self\"`). It\n * wraps the component whatever the envelope's values, even with no\n * `hidden` or live region set, so it must render its children in the same\n * place in either case: a bound `hidden` that toggles must not remount\n * the component and lose its local state.\n */\n AccessibilityWrapper: ComponentType<GenerativeUIAccessibilityWrapperProps>;\n /**\n * Shown in place of a component that cannot be shown: it failed to render\n * (with `retry`), its props are invalid, its type is unknown, or it is a\n * cyclic reference. It also stands in for a whole surface that failed,\n * with `componentId: \"surface\"`. When the app sets\n * `errorBoundary.fallback`, that replaces it for render failures, and this\n * stands in only if the app's fallback throws. If this throws, the node\n * renders nothing and the error is reported, once for each message; it is\n * tried again with a new message, a new revision of the node or Retry.\n */\n NodeFallback: ComponentType<GenerativeUINodeFallbackProps>;\n}\n\nconst DISPLAY_CONTENTS = { display: \"contents\" } as const;\n\n/**\n * The root element is always there, so a theme change does not remount the\n * surface. `display: contents` keeps it out of the layout, and the CSS\n * variables still reach every component of the surface. The `a2ui-surface`\n * class scopes the standard catalog's surface CSS rules. The theme is a\n * stylesheet, not an inline style, so that its `dark` values can apply in\n * dark mode only. The values are checked in `themeStyleSheet`, and the HTML\n * is set as is, so the server render keeps the quotes of the rule.\n */\nfunction DomSurfaceRoot({\n surfaceId,\n theme,\n children,\n}: GenerativeUISurfaceRootProps) {\n const sheet = React.useMemo(() => themeStyleSheet(theme), [theme]);\n return (\n <div\n className=\"a2ui-surface\"\n data-generative-ui-root={surfaceId}\n data-a2ui-theme={sheet?.id}\n style={DISPLAY_CONTENTS}\n >\n {sheet ? <style dangerouslySetInnerHTML={{ __html: sheet.css }} /> : null}\n {children}\n </div>\n );\n}\n\nfunction DomAccessibilityWrapper({\n attributes,\n children,\n}: GenerativeUIAccessibilityWrapperProps) {\n return (\n <span data-a2ui-accessibility=\"\" style={DISPLAY_CONTENTS} {...attributes}>\n {children}\n </span>\n );\n}\n\nexport function DefaultNodeFallback({\n message,\n componentId,\n retry,\n}: GenerativeUINodeFallbackProps) {\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/** The DOM host: what a surface draws on the web. */\nexport const domGenerativeUIHost: GenerativeUIHost = {\n SurfaceRoot: DomSurfaceRoot,\n AccessibilityWrapper: DomAccessibilityWrapper,\n NodeFallback: DefaultNodeFallback,\n};\n\n/**\n * The host elements of the surfaces below. Defaults to the DOM host, so a\n * web app never sets it.\n */\nexport const GenerativeUIHostContext =\n createContext<GenerativeUIHost>(domGenerativeUIHost);\n\nexport function useGenerativeUIHost(): GenerativeUIHost {\n return useContext(GenerativeUIHostContext);\n}\n","import React, { Component, createContext, useContext } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { toError, withCause } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUIErrorInfo } from \"@copilotkit/shared/generative-ui\";\nimport { reportErrorSafely } from \"./runtime-context\";\nimport type { GenerativeUIRuntime } from \"./runtime-context\";\nimport { useGenerativeUIHost } from \"./host\";\n\nexport { toError, withCause };\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\n/**\n * The error that a fallback threw, told apart from the error of the\n * component it stood in for. The fallback's own error is the `cause`.\n */\nfunction fallbackError(error: Error, componentId: string | undefined) {\n const subject = componentId === undefined ? \"the surface\" : componentId;\n return withCause(\n new Error(`The error fallback of ${subject} threw: ${error.message}`),\n error,\n );\n}\n\n/**\n * What the boundaries of one surface have reported, so that each failure\n * is reported once per place until its content changes. A slot is one place\n * that can fail (a node's boundary, a fallback, the surface root); it keeps\n * the last failure it reported until it renders again without one. A\n * failure that comes back the same while the slot keeps failing (a new\n * revision that throws the same error, a fallback that throws again for the\n * same message) is not reported again; a different one is.\n *\n * A place that unmounts lets go of its slots, but not at once: React also\n * unmounts and mounts again what has not changed (StrictMode runs every\n * effect twice, <Activity> hides and shows a subtree, an ancestor remounts\n * its children). A slot that is let go of keeps its memory until new content\n * arrives (`settle`), and keeps it for good when its place mounts again\n * before that. So a node that goes away and comes back with new content\n * reports its failure again, and a node that only remounts does not.\n */\nexport interface GenerativeUIFailureLog {\n report(\n runtime: GenerativeUIRuntime,\n slot: string,\n info: GenerativeUIErrorInfo,\n /** What the failure happened for, such as the message a fallback showed. */\n context?: string,\n ): void;\n /** The slot rendered without a failure. */\n clear(slot: string): void;\n /** The place of the slot mounted (again). */\n retain(slot: string): void;\n /** The place of the slot unmounted: forget it at the next `settle`. */\n release(slot: string): void;\n /**\n * New content of the surface arrived: forget the slots let go of since.\n * `missed` is for content that arrived while no one was watching (an\n * <Activity> hid the whole surface): it also forgets the slots whose\n * places mounted again since they were let go of, because they mount\n * again, and report their failures again, before the surface can tell\n * that its content changed. Those reports were held back as repeats;\n * they are made now.\n */\n settle(missed?: boolean): void;\n}\n\nexport function createFailureLog(): GenerativeUIFailureLog {\n const last = new Map<string, string>();\n const released = new Set<string>();\n // Every slot let go of since the last settle, also the ones retained since.\n const releasedSinceSettle = new Set<string>();\n // Repeats held back for slots in `releasedSinceSettle`, which a missed\n // settle makes after all.\n const heldBack = new Map<\n string,\n {\n runtime: GenerativeUIRuntime;\n info: GenerativeUIErrorInfo;\n signature: string;\n }\n >();\n return {\n report(runtime, slot, info, context = \"\") {\n released.delete(slot);\n const signature = [\n info.kind,\n info.error.name,\n info.error.message,\n context,\n ].join(\"\\n\");\n if (last.get(slot) === signature) {\n if (releasedSinceSettle.has(slot)) {\n heldBack.set(slot, { runtime, info, signature });\n }\n return;\n }\n heldBack.delete(slot);\n last.set(slot, signature);\n reportErrorSafely(runtime, info);\n },\n clear(slot) {\n released.delete(slot);\n last.delete(slot);\n heldBack.delete(slot);\n },\n retain(slot) {\n released.delete(slot);\n },\n release(slot) {\n heldBack.delete(slot);\n if (!last.has(slot)) return;\n released.add(slot);\n releasedSinceSettle.add(slot);\n },\n settle(missed = false) {\n for (const slot of missed ? releasedSinceSettle : released) {\n last.delete(slot);\n }\n if (missed) {\n for (const [slot, { runtime, info, signature }] of heldBack) {\n if (!releasedSinceSettle.has(slot) || last.has(slot)) continue;\n last.set(slot, signature);\n reportErrorSafely(runtime, info);\n }\n }\n heldBack.clear();\n released.clear();\n releasedSinceSettle.clear();\n },\n };\n}\n\n/** Outside a surface, every failure is reported. */\nconst UNLOGGED: GenerativeUIFailureLog = {\n report: (runtime, _slot, info) => reportErrorSafely(runtime, info),\n clear: () => {},\n retain: () => {},\n release: () => {},\n settle: () => {},\n};\n\n/** The failure log of the surface being rendered; set by `SurfaceView`. */\nexport const GenerativeUIFailureLogContext =\n createContext<GenerativeUIFailureLog>(UNLOGGED);\n\nexport function useFailureLog(): GenerativeUIFailureLog {\n return useContext(GenerativeUIFailureLogContext);\n}\n\n/**\n * The slots of a failure log, per node place (one rendered copy of a node,\n * see `placeOf` in SurfaceView) and surface boundary.\n */\nexport const failureSlots = {\n /** A node's own render failure (its NodeBoundary). */\n node: (place: string) => `node ${place}`,\n /** The app's `errorBoundary.fallback` of a node. */\n appFallback: (place: string) => `app-fallback ${place}`,\n /** The host fallback shown for a node's render failure. */\n renderFallback: (place: string) => `render-fallback ${place}`,\n /**\n * The host fallback shown in place of a node that cannot render: invalid\n * props, unknown type, cyclic reference.\n */\n fallback: (place: string) => `fallback ${place}`,\n /**\n * The host fallback of a cyclic reference. A slot of its own, apart from\n * the fallback of a node that cannot render.\n */\n cycle: (place: string) => `cycle ${place}`,\n /** The invalid props of a node, reported once until they are valid. */\n props: (place: string) => `props ${place}`,\n surface: (level: string) => `surface ${level}`,\n surfaceFallback: (level: string) => `surface-fallback ${level}`,\n};\n\nfunction sameKeys(a: readonly unknown[], b: readonly unknown[]) {\n return a.length === b.length && a.every((value, i) => Object.is(value, b[i]));\n}\n\ninterface FallbackGuardProps {\n surfaceId: string;\n componentId?: string;\n runtime: GenerativeUIRuntime;\n log: GenerativeUIFailureLog;\n slot: string;\n /** What the fallback stands in for, so a new one is a new failure. */\n context: string;\n /**\n * A change of any of these gives a failed fallback another chance: the\n * message it shows and the revision of the node it stands in for.\n */\n resetKeys: readonly unknown[];\n /** Shown instead when the fallback throws. Must not throw itself. */\n replacement?: ReactNode;\n children: ReactNode;\n}\n\n/**\n * Wraps an error fallback. The fallback comes from the host or the app, so it\n * may throw too; then this renders `replacement` (nothing by default) and\n * reports the fallback's error, so that the failure stays inside the node\n * instead of reaching its parent, the chat or the host page. It renders no\n * element, so a working fallback looks the same.\n *\n * A failed fallback gets another chance when one of `resetKeys` changes (a\n * new message or a new revision of the node), and when the boundary above\n * it, if any, catches a new error (that remounts it). A fallback that\n * throws the same error again for the same message is not reported again.\n */\ninterface FallbackGuardState {\n failed: boolean;\n /** What the fallback threw, while `failed`. */\n error?: Error;\n resetKeys: readonly unknown[];\n}\n\nclass FallbackGuard extends Component<FallbackGuardProps, FallbackGuardState> {\n state: FallbackGuardState = {\n failed: false,\n resetKeys: this.props.resetKeys,\n };\n\n static getDerivedStateFromError(thrown: unknown) {\n return { failed: true, error: toError(thrown) };\n }\n\n static getDerivedStateFromProps(\n props: FallbackGuardProps,\n state: FallbackGuardState,\n ): Partial<FallbackGuardState> | null {\n return sameKeys(props.resetKeys, state.resetKeys)\n ? null\n : { failed: false, error: undefined, resetKeys: props.resetKeys };\n }\n\n private report(error: Error) {\n const { runtime, surfaceId, componentId, log, slot, context } = this.props;\n log.report(\n runtime,\n slot,\n {\n kind: \"render\",\n surfaceId,\n ...(componentId === undefined ? {} : { componentId }),\n error: fallbackError(error, componentId),\n },\n context,\n );\n }\n\n componentDidCatch(thrown: unknown) {\n this.report(this.state.error ?? toError(thrown));\n }\n\n componentDidMount() {\n if (!this.state.failed) {\n this.props.log.clear(this.props.slot);\n return;\n }\n // A remount that kept the failure (<Activity> showing the fallback\n // again) reports it again, as NodeBoundary does: the log drops it as a\n // repeat, unless the surface's content changed meanwhile.\n if (this.state.error) this.report(this.state.error);\n }\n\n componentDidUpdate() {\n if (!this.state.failed) this.props.log.clear(this.props.slot);\n }\n\n render() {\n return this.state.failed\n ? (this.props.replacement ?? null)\n : this.props.children;\n }\n}\n\n/**\n * The host's `NodeFallback`, guarded: when it throws, the node renders\n * nothing and the error is reported, and the parent node keeps rendering.\n * Every place that shows the host fallback goes through this.\n */\nexport function GuardedNodeFallback({\n surfaceId,\n componentId,\n runtime,\n message,\n retry,\n slot,\n revision,\n}: {\n surfaceId: string;\n /** The failed node, or `undefined` for the whole surface. */\n componentId: string | undefined;\n runtime: GenerativeUIRuntime;\n message: string;\n retry?: () => void;\n /** The failure-log slot of this fallback (see `failureSlots`). */\n slot: string;\n /**\n * The revision of the node shown in its place (its wire props object):\n * a fallback that failed is tried again for a new one.\n */\n revision?: unknown;\n}) {\n const { NodeFallback } = useGenerativeUIHost();\n const log = useFailureLog();\n return (\n <FallbackGuard\n surfaceId={surfaceId}\n componentId={componentId}\n runtime={runtime}\n log={log}\n slot={slot}\n context={message}\n resetKeys={[message, revision]}\n >\n <NodeFallback\n message={message}\n componentId={componentId ?? \"surface\"}\n retry={retry}\n />\n </FallbackGuard>\n );\n}\n\n/**\n * Calls the app's `errorBoundary.fallback` in a render of its own, so that\n * the guard above it catches what it throws.\n */\nfunction AppErrorFallback({\n render,\n ...props\n}: {\n render: NonNullable<GenerativeUIRuntime[\"errorFallback\"]>;\n error: Error;\n retry: () => void;\n surfaceId: string;\n componentId: string;\n}) {\n return <>{render(props)}</>;\n}\n\ninterface NodeBoundaryProps {\n surfaceId: string;\n componentId: string;\n /**\n * Where this copy of the node is in the surface: the place of its parent,\n * the slot it renders in, its id, and the template item path when it\n * renders inside a template. Names its failure-log slots.\n */\n place: string;\n /** Wire props object of the node; a new object means a new agent revision. */\n revision: unknown;\n runtime: GenerativeUIRuntime;\n log: GenerativeUIFailureLog;\n children: ReactNode;\n}\n\ninterface NodeBoundaryState {\n /** Always an Error: a thrown value is turned into one (see `toError`). */\n error: Error | null;\n revision: unknown;\n}\n\n/**\n * Per-node boundary. Resets on retry or a new agent revision, not on data\n * ticks. A failure that stays the same across revisions is reported once.\n */\nexport class NodeBoundary extends Component<\n NodeBoundaryProps,\n NodeBoundaryState\n> {\n state: NodeBoundaryState = { error: null, revision: this.props.revision };\n\n static getDerivedStateFromError(thrown: unknown): Partial<NodeBoundaryState> {\n return { error: toError(thrown) };\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(thrown: unknown) {\n const { runtime, surfaceId, componentId, log, place } = this.props;\n // A fallback shown in place of the node (invalid props) is gone now.\n log.clear(failureSlots.fallback(place));\n log.report(runtime, failureSlots.node(place), {\n kind: \"render\",\n surfaceId,\n componentId,\n error: this.state.error ?? toError(thrown),\n });\n }\n\n private slots() {\n const { place } = this.props;\n return [\n failureSlots.node(place),\n failureSlots.appFallback(place),\n failureSlots.renderFallback(place),\n ];\n }\n\n private clearSlots() {\n for (const slot of this.slots()) this.props.log.clear(slot);\n }\n\n componentDidMount() {\n // A remount of the same place (StrictMode, an ancestor that remounts)\n // keeps what the place reported.\n for (const slot of this.slots()) this.props.log.retain(slot);\n if (!this.state.error) {\n this.clearSlots();\n return;\n }\n // A remount that kept the failure (<Activity> showing the node again)\n // reports it again, as an effect that checks props does. The log drops\n // it as a repeat, unless the surface's content changed meanwhile.\n const { runtime, surfaceId, componentId, log, place } = this.props;\n log.report(runtime, failureSlots.node(place), {\n kind: \"render\",\n surfaceId,\n componentId,\n error: this.state.error,\n });\n }\n\n componentDidUpdate(prevProps: NodeBoundaryProps) {\n if (prevProps.place !== this.props.place) {\n // Another node in the same element (a single slot that names another\n // id): the old place went away.\n const { log } = this.props;\n log.release(failureSlots.node(prevProps.place));\n log.release(failureSlots.appFallback(prevProps.place));\n log.release(failureSlots.renderFallback(prevProps.place));\n for (const slot of this.slots()) log.retain(slot);\n }\n if (!this.state.error) this.clearSlots();\n }\n\n componentWillUnmount() {\n for (const slot of this.slots()) this.props.log.release(slot);\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, place, log } = this.props;\n const hostFallback = (\n <GuardedNodeFallback\n surfaceId={surfaceId}\n componentId={componentId}\n runtime={runtime}\n message={error.message}\n retry={this.retry}\n slot={failureSlots.renderFallback(place)}\n />\n );\n const fallback = runtime.errorFallback;\n if (!fallback) return hostFallback;\n // When the app's fallback throws, the host's one stands in, with Retry.\n return (\n <FallbackGuard\n surfaceId={surfaceId}\n componentId={componentId}\n runtime={runtime}\n log={log}\n slot={failureSlots.appFallback(place)}\n context={error.message}\n resetKeys={[error]}\n replacement={hostFallback}\n >\n <AppErrorFallback\n render={fallback}\n error={error}\n retry={this.retry}\n surfaceId={surfaceId}\n componentId={componentId}\n />\n </FallbackGuard>\n );\n }\n}\n\ninterface SurfaceBoundaryProps {\n surfaceId: string;\n runtime: GenerativeUIRuntime;\n log: GenerativeUIFailureLog;\n /** Which of the two boundaries of the surface: names its log slots. */\n level: \"outer\" | \"inner\";\n /**\n * Changes with each new content of the surface (new operations applied),\n * and not when the same content is delivered again; resets a failure.\n */\n revision: unknown;\n /**\n * Offer Retry in the fallback. The boundary around the host's root offers\n * it: the host's root may fail for a reason of its own that a retry can\n * clear. The one inside the root does not. It catches only failures of\n * the surface's own rendering of its root node, which come back the same\n * until the content changes, so a new content is what resets it; and on\n * the web its fallback stays the output it had before the host existed,\n * with no button.\n */\n retryable?: boolean;\n children: ReactNode;\n}\n\ninterface SurfaceBoundaryState {\n /** Always an Error: a thrown value is turned into one (see `toError`). */\n error: Error | null;\n revision: unknown;\n}\n\n/**\n * Surface boundary: a failure here must not reach the chat or the host page.\n * It resets on a new revision, and on Retry when `retryable`. A failure that\n * stays the same across revisions is reported once.\n */\nexport class SurfaceBoundary extends Component<\n SurfaceBoundaryProps,\n SurfaceBoundaryState\n> {\n state: SurfaceBoundaryState = { error: null, revision: this.props.revision };\n\n static getDerivedStateFromError(\n thrown: unknown,\n ): Partial<SurfaceBoundaryState> {\n return { error: toError(thrown) };\n }\n\n static getDerivedStateFromProps(\n props: SurfaceBoundaryProps,\n state: SurfaceBoundaryState,\n ): Partial<SurfaceBoundaryState> | null {\n return props.revision !== state.revision\n ? { error: null, revision: props.revision }\n : null;\n }\n\n componentDidCatch(thrown: unknown) {\n const { runtime, surfaceId, log, level } = this.props;\n log.report(runtime, failureSlots.surface(level), {\n kind: \"render\",\n surfaceId,\n error: this.state.error ?? toError(thrown),\n });\n }\n\n private clearSlots() {\n const { log, level } = this.props;\n log.clear(failureSlots.surface(level));\n log.clear(failureSlots.surfaceFallback(level));\n }\n\n componentDidMount() {\n if (!this.state.error) this.clearSlots();\n }\n\n componentDidUpdate() {\n if (!this.state.error) this.clearSlots();\n }\n\n private retry = () => this.setState({ error: null });\n\n render() {\n if (!this.state.error) return this.props.children;\n // The last boundary of the surface: the guard keeps a fallback that\n // throws from reaching the chat or the host page.\n return (\n <GuardedNodeFallback\n surfaceId={this.props.surfaceId}\n componentId={undefined}\n runtime={this.props.runtime}\n message=\"this generated UI failed to render\"\n retry={this.props.retryable ? this.retry : undefined}\n slot={failureSlots.surfaceFallback(this.props.level)}\n />\n );\n }\n}\n","import React, {\n memo,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n A2UI_COMPONENT_ENVELOPE_KEYS,\n GENERATIVE_UI_ROOT_ID,\n isActionBinding,\n isPathBinding,\n mapAtChildRef,\n} from \"@copilotkit/shared\";\nimport type {\n ChildRef,\n GenerativeUIActionBinding,\n GenerativeUITemplateChildren,\n} from \"@copilotkit/shared\";\nimport { shallowEqual } from \"../lib/shallow-stable-ref\";\nimport { setterNameOf } from \"./catalog\";\nimport type { ResolvedGenerativeUIComponent } from \"./catalog\";\nimport {\n joinPath,\n resolvePath,\n tryResolveDynamicValue,\n} from \"@copilotkit/core/generative-ui\";\nimport {\n formatIssues,\n hasOwnKey,\n isAsyncIssue,\n issueKey,\n validateSchemaSync,\n withoutRejectedNulls,\n} from \"@copilotkit/shared/generative-ui\";\nimport {\n createFailureLog,\n failureSlots,\n GenerativeUIFailureLogContext,\n GuardedNodeFallback,\n NodeBoundary,\n NodePlaceholder,\n SurfaceBoundary,\n toError,\n useFailureLog,\n} from \"./boundaries\";\nimport type { GenerativeUIFailureLog } from \"./boundaries\";\nimport { useGenerativeUIHost } from \"./host\";\nimport {\n accessibilityAttributes,\n readAccessibility,\n wrapperAria,\n} from \"./accessibility\";\nimport type { GenerativeUIAccessibility } from \"./accessibility\";\nimport type { GenerativeUIInvokeResult } from \"@copilotkit/shared/generative-ui\";\nimport {\n invokeBoundEvent,\n invokeMatchedEvent,\n} from \"@copilotkit/core/generative-ui\";\nimport {\n GenerativeUINodeContext,\n reportErrorSafely,\n useRequiredGenerativeUIRuntime,\n} from \"./runtime-context\";\nimport type { GenerativeUIRuntime } from \"./runtime-context\";\nimport type {\n ComponentModel,\n GenerativeUISurfaceManager,\n ManagedSurface,\n SurfaceModel,\n} from \"@copilotkit/core/generative-ui\";\n\nconst NO_ANCESTORS: readonly string[] = [];\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 // The host draws the root (on the web, a DOM element that carries the\n // theme's stylesheet). It is always there, so a theme change does not\n // remount the surface.\n const { SurfaceRoot } = useGenerativeUIHost();\n // A failed surface tries again with new content, as a failed node does\n // with new props. New content is a new operation applied: the manager\n // gives `surface.operations` a new array on every ingest, also one that\n // delivers the same operations again (a replay, a status change), so its\n // identity would retry (and report again) on every chunk. The count of\n // applied operations grows only with new ones, and an ingest that does\n // not extend them rebuilds the surface as a new object.\n const appliedCount = useSyncExternalStore(\n runtime.manager.subscribe,\n () => surface.operations.length,\n undefinedSnapshot,\n );\n const revision = useMemo(\n () => ({ surface, appliedCount }),\n [surface, appliedCount],\n );\n // What this surface reported, so that a failure that stays the same is\n // reported once, not on each revision. The log belongs to the surface:\n // a named target can show another surface in the same view, and that\n // surface's failures are its own, even the same error at the same place.\n const [scopedLog, setScopedLog] = useState(() => ({\n key: surface.key,\n log: createFailureLog(),\n }));\n let failureLog = scopedLog.log;\n if (scopedLog.key !== surface.key) {\n const next = { key: surface.key, log: createFailureLog() };\n setScopedLog(next);\n failureLog = next.log;\n }\n // A place that unmounted and did not mount again before new content of\n // this surface arrived went away: forget what it reported (see\n // GenerativeUIFailureLog). New content is a new applied operation\n // (`appliedCount` grows) or a rebuilt surface (a new object). The manager\n // also notifies for every other surface, for ingests that bring nothing\n // new, for `setState` and for target changes, none of which is new content\n // of this one; the user's data-model writes do not notify it at all.\n //\n // What the view last saw outlives the subscription: <Activity> disconnects\n // it while the surface is hidden, and content that arrived meanwhile is\n // settled as missed when the surface is shown again (the boundaries have\n // retained their slots by then). A layout effect, so that this runs before\n // the nodes' effects report their failures again.\n const { threadId, surfaceId } = surface;\n const { manager } = runtime;\n const seen = useRef<\n | { log: GenerativeUIFailureLog; current: unknown; applied: unknown }\n | undefined\n >(undefined);\n useLayoutEffect(() => {\n const contentOf = () => {\n const current = manager.getSurface(threadId, surfaceId);\n return { log: failureLog, current, applied: current?.operations.length };\n };\n const observe = (missed: boolean) => {\n const last = seen.current;\n const next = contentOf();\n seen.current = next;\n if (\n last?.log === failureLog &&\n (next.current !== last.current || next.applied !== last.applied)\n ) {\n failureLog.settle(missed);\n }\n };\n observe(true);\n return manager.subscribe(() => observe(false));\n }, [manager, threadId, surfaceId, failureLog]);\n // Two boundaries. The inner one sits inside the root, so a failed surface\n // keeps the root and its theme (on the web, the same output as before the\n // host existed). The outer one catches what the host's root throws itself,\n // which must not reach the chat or the host page, and offers Retry.\n return (\n <GenerativeUIFailureLogContext.Provider value={failureLog}>\n <SurfaceBoundary\n surfaceId={surface.surfaceId}\n runtime={runtime}\n log={failureLog}\n level=\"outer\"\n revision={revision}\n retryable\n >\n <SurfaceRoot surfaceId={surface.surfaceId} theme={runtime.theme}>\n <SurfaceBoundary\n surfaceId={surface.surfaceId}\n runtime={runtime}\n log={failureLog}\n level=\"inner\"\n revision={revision}\n >\n <NodeView\n surface={surface}\n componentId={GENERATIVE_UI_ROOT_ID}\n basePath={undefined}\n ancestors={NO_ANCESTORS}\n parentPlace=\"\"\n via=\"\"\n />\n </SurfaceBoundary>\n </SurfaceRoot>\n </SurfaceBoundary>\n </GenerativeUIFailureLogContext.Provider>\n );\n}\n\n/**\n * Resolves a component by id. Subscribes to the manager, which notifies\n * synchronously once an ingest has been fully applied, so every subscriber\n * (one per slotted child, or one per mount of the same surface) sees the\n * same, complete update. The components model has no events of its own.\n */\nfunction useComponentModel(\n manager: GenerativeUISurfaceManager,\n model: SurfaceModel,\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`: the manager notifies. */\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 // Quoted, so that an id or a path that holds the separators of a place\n // (`/`, `:`, `#`) cannot read as the place of another node.\n const item = basePath === undefined ? \"\" : JSON.stringify(basePath);\n return `${item}#${JSON.stringify(componentId)}`;\n}\n\n/**\n * Where one rendered copy of a node is: the place of its parent, the slot\n * or child reference of the parent it renders in, and its scoped id. Names\n * the node's failure-log slots. A scoped id alone is not enough: the same\n * id can render under two parents, and a cyclic reference repeats the\n * scoped id of an ancestor. Each copy keeps its own memory of what it\n * reported, so one copy that renders, goes away or remounts does not clear\n * the memory of another that still fails.\n */\nfunction placeOf(parentPlace: string, via: string, position: string) {\n return `${parentPlace}/${via === \"\" ? \"\" : JSON.stringify(via)}${position}`;\n}\n\nconst NodeView = memo(function NodeView({\n surface,\n componentId,\n basePath,\n ancestors,\n parentPlace,\n via,\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 /** The place of the parent (see `placeOf`); \"\" for the root. */\n parentPlace: string;\n /** The slot or child reference of the parent this node renders in. */\n via: string;\n}) {\n const runtime = useRequiredGenerativeUIRuntime();\n const log = useFailureLog();\n const component = useComponentModel(\n runtime.manager,\n surface.model,\n componentId,\n );\n const properties = useComponentProperties(runtime.manager, component);\n const position = scopedId(componentId, basePath);\n const place = placeOf(parentPlace, via, position);\n // A node that goes away takes the memory of its failures with it, so the\n // same failure in a node added later is reported. A node that only\n // remounts (StrictMode, <Activity>, an ancestor that remounts) keeps it:\n // the log forgets a slot let go of only once new content arrives.\n useEffect(() => {\n const slots = [\n failureSlots.fallback(place),\n failureSlots.cycle(place),\n failureSlots.props(place),\n ];\n for (const slot of slots) log.retain(slot);\n return () => {\n for (const slot of slots) log.release(slot);\n };\n }, [log, place]);\n // The fallbacks below get another chance with a new message or a new\n // revision of the node (`properties`): nothing above them remounts them.\n if (ancestors.includes(position)) {\n return (\n <GuardedNodeFallback\n surfaceId={surface.surfaceId}\n componentId={componentId}\n runtime={runtime}\n message={`cyclic reference to ${componentId}`}\n slot={failureSlots.cycle(place)}\n revision={properties}\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 <GuardedNodeFallback\n surfaceId={surface.surfaceId}\n componentId={componentId}\n runtime={runtime}\n message={`unknown component \"${component.type}\"`}\n slot={failureSlots.fallback(place)}\n revision={properties}\n />\n );\n }\n return (\n <NodeBoundary\n key={component.type}\n surfaceId={surface.surfaceId}\n componentId={componentId}\n place={place}\n revision={properties}\n runtime={runtime}\n log={log}\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 place={place}\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 parentPlace,\n via,\n}: {\n surface: ManagedSurface;\n template: GenerativeUITemplateChildren;\n basePath: string | undefined;\n ancestors: readonly string[];\n parentPlace: string;\n via: 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 parentPlace={parentPlace}\n via={via}\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. Bound props, events and\n * slots are left out, and so are the keys of the A2UI component envelope;\n * `accessibility` is resolved the same way and given on its own.\n *\n * A writable prop that is not bound to a path and that the component set\n * shows the local value from `overrides`, also when the model never set the\n * prop. That is intended: the user's edit wins over the model's literal\n * value, also over a newer literal the agent sends later, until the node\n * remounts. A literal is not data the agent and the user share; a prop\n * that both must write is bound to a path, and the setter writes the data\n * model.\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 hasOwnKey(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 the data model changes lists and objects\n // in 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 (the data model never replays the\n // current 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 } = toError(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 get the checked model props: the resolved values that\n * passed the props schema (without the nulls it rejected), not the\n * schema's parsed output, so its defaults and transforms are not applied\n * yet. They run again only when the state object or those 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. The exception is the issue that an async\n * props schema gives (`isAsyncIssue`): the render checks props\n * synchronously only, so the full check would fail the same way, and it is\n * reported here.\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 : !hasOwnKey(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 hasOwnKey(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 = hasOwnKey(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 that wins over the model's value until\n * the node remounts (see `useModelDataProps`). The setters keep their\n * 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 } = toError(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 place: 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 const via = `${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 parentPlace={place}\n via={via}\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 parentPlace={place}\n via={via}\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 parentPlace={place}\n via={via}\n />\n ));\n }\n }\n return slots;\n }, [\n surface,\n definition,\n properties,\n componentId,\n basePath,\n ancestors,\n place,\n ]);\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 place: string,\n) {\n return useMemo(() => {\n if (props === undefined || refs.length === 0) return props;\n const childAncestors = [...ancestors, scopedId(componentId, basePath)];\n const render = (\n kind: ChildRef[\"kind\"],\n value: unknown,\n via: string,\n ): 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 parentPlace={place}\n via={via}\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 parentPlace={place}\n via={via}\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 parentPlace={place}\n via={via}\n />\n ));\n };\n let result: unknown = props;\n for (const ref of refs) {\n // A path through an array (`\"*\"`) finds a reference in each item;\n // they are told apart by their order.\n let found = 0;\n const path = ref.path.join(\".\");\n result = mapAtChildRef(result, ref.path, (value) =>\n render(ref.kind, value, `${path}[${found++}]:`),\n );\n }\n return result as Record<string, unknown>;\n }, [surface, refs, props, componentId, basePath, ancestors, place]);\n}\n\nfunction ResolvedNode({\n surface,\n componentId,\n definition,\n properties,\n runtime,\n basePath,\n ancestors,\n place,\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 /** Where this copy of the node is (see `placeOf`). */\n place: string;\n}) {\n const { AccessibilityWrapper } = useGenerativeUIHost();\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 place,\n );\n const childRefProps = useChildRefProps(\n surface,\n definition.childRefs,\n dataProps.ok ? dataProps.props : undefined,\n componentId,\n basePath,\n ancestors,\n place,\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 const log = useFailureLog();\n\n // The node renders: a fallback that failed in its place before (invalid\n // props, an unknown type, a cycle) is a new failure if it fails again,\n // and so are invalid props.\n useEffect(() => {\n if (!problem) {\n log.clear(failureSlots.fallback(place));\n log.clear(failureSlots.props(place));\n }\n }, [problem, log, place]);\n\n // Through the failure log, so that the same problem is reported once,\n // also when this node remounts (a new type, a boundary that resets).\n useEffect(() => {\n if (problem) {\n log.report(runtime, failureSlots.props(place), {\n kind: \"props\",\n surfaceId: surface.surfaceId,\n componentId,\n error: new Error(`Invalid props: ${problem}`),\n });\n }\n }, [problem, log, place, runtime, surface.surfaceId, componentId]);\n\n if (!dataProps.ok) {\n return (\n <GuardedNodeFallback\n surfaceId={surface.surfaceId}\n componentId={componentId}\n runtime={runtime}\n message={`invalid props (${problem})`}\n slot={failureSlots.fallback(place)}\n revision={properties}\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 the host's AccessibilityWrapper (on the web, a span\n // with no box of its own). A label or a description needs an element with\n // a role, so the component sets those itself (the standard ones do; see\n // useGenerativeUIAccessibility).\n //\n // The wrapper is there whenever the component has an envelope, whatever\n // its values, so a bound `hidden` that flips does not remount the\n // component and lose what the user typed into it. A component that applies\n // the envelope itself (`accessibility: \"self\"`) gets no wrapper: a table\n // row or cell cannot sit in one.\n //\n // A component sent again with an envelope added or removed does remount.\n // On the web, a wrapper on every node would break the stylesheet's child\n // selectors (table rows and cells, the last text of a spaceBetween row),\n // and bound inputs keep their 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 <AccessibilityWrapper\n attributes={wrapperAria(accessibilityAttributes(accessibility))}\n >\n {rendered}\n </AccessibilityWrapper>\n ) : (\n rendered\n )}\n </GenerativeUINodeContext.Provider>\n );\n}\n","import React, { createContext, useContext, useEffect } from \"react\";\nimport type { ComponentType, ReactNode } from \"react\";\nimport * as 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 {\n GenerativeUISurfaceContentSchema,\n useGenerativeUIActivitySurface,\n} from \"./activity\";\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 error,\n children,\n}: GenerativeUIChatSurfaceProps) {\n return (\n <div\n data-generative-ui-chat-surface={surfaceId}\n className=\"cpk-generative-ui-chat-card\"\n >\n {children}\n {error && (\n <div role=\"alert\" className=\"cpk-generative-ui-chat-card-error\">\n Part of this UI couldn't be shown.\n </div>\n )}\n </div>\n );\n}\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 // 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 { surface, rejected, error } = useGenerativeUIActivitySurface({\n runtime,\n threadId,\n agentId: agent?.agentId,\n content,\n target: GENERATIVE_UI_CHAT_TARGET,\n });\n if (!surface) return null;\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 GenerativeUISurfaceContentSchema 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 // Built-in: app renderers win over it, and it goes when the feature does.\n return copilotkit.ɵaddBuiltInRenderToolCall(renderer);\n }, [copilotkit]);\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;AA2GA,MAAM,oDACgD,KAAK;AAkB3D,MAAa,oCAER,EACH,UACA,QACA,SACA,UACA,qBACA,yBACI;CACJ,MAAM,qCAA0B,yBAAyB;CAMzD,MAAM,eAAeA,0CAAoB,OAAO;CAChD,MAAM,yCACG;EACL,GAAGC;EACH,GAAG,cAAc;EACjB,GAAG;EACJ,GACD,CAAC,cAAc,cAAc,OAAO,CACrC;CAOD,MAAM,yEAAqC;CAC3C,MAAM,UAAU;EACd;EACA;EACA;EACA;EACA;EACD;CACD,MAAM,cAAc,cAAc,UAAU;CAC5C,MAAM,CAAC,mCACC,IAAIC,yCAAwB,SAAS,YAAY,CACxD;AACD,OAAM,YAAY,QAAQ;CAC1B,MAAM,2CACJ,MAAM,WACN,MAAM,aACN,MAAM,YACP;AACD,4BAAgB;AACd,QAAM,OAAO;GACX;GACA;GACA;GACA;GACA;GACD,CAAC;IACD;EACD;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;CAKF,MAAM,mCAAwBC,iDAAkB,EAAE;AAClD,4BAAgB;AACd,MAAI,eAAe,OAAW;AAC9B,SAAO,MAAM,eAAe,WAAW;IACtC,CAAC,YAAY,MAAM,CAAC;CAIvB,MAAM,YAAY,uBAAuB;CACzC,MAAM,cACJ,aAAa,CAAC,eACV,SAAS,cACT,aAAa;CACnB,MAAM,eACJ,aAAa,CAAC,eAAe,MAAM,eAAe,aAAa;CAKjE,MAAM,EACJ,SAAS,iBACT,UA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,MAAM,EAAE,SAAS,UAAU,UAAU,+BAA+B;EAClE;EACA;EACA,SAAS,OAAO;EAChB;EACA,QAAQC;EACT,CAAC;AACF,KAAI,CAAC,QAAS,QAAO;AACrB,QACE,2CAAC;EACC,WAAW,QAAQ;EACnB,aAAa,QAAQ,WAAW;EACzB;EACG;YAET,QAAQ,SAAS,OAAO,2CAAC,eAAqB,UAAW;GAClD;;AAId,SAAgB,qCAA+F;AAC7G,QAAO;EACL,cAAcC;EACd,SACEC;EACF,QACE;EACH;;;;;;;AAQH,SAAgB,iDAAwF;AACtG,QAAO;EACL,cAAcC;EACd,SAASC,IAAE,SAAS;EACpB,cAAc;EACf;;;AAIH,SAAgB,+BAAqC;CACnD,MAAM,EAAE,kEAA8B;AACtC,4BAAgB;EACd,MAAM,WAAW,uBAAuB;GACtC,MAAMC;GACN,MAAMD,IAAE,KAAK;GACb,cAAc,0EAAK;GACpB,CAAC;AAEF,SAAO,WAAW,0BAA0B,SAAS;IACpD,CAAC,WAAW,CAAC;AAChB,QAAO"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import React, { ReactNode } from "react";
|
|
2
|
+
import { GenerativeUIRejectedOperation, GenerativeUISurfaceContent } from "@copilotkit/shared";
|
|
3
|
+
import * as react_jsx_runtime0 from "react/jsx-runtime";
|
|
4
|
+
import { ActivityMessageRenderProps, ActivityMessageRendererDef } from "@copilotkit/core";
|
|
5
|
+
|
|
6
|
+
//#region src/types/react-activity-message-renderer.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* An activity message renderer for React: a React component that draws
|
|
9
|
+
* activity messages of one `activityType` (or `"*"` for any type). The
|
|
10
|
+
* component receives {@link ActivityMessageRenderProps}.
|
|
11
|
+
*
|
|
12
|
+
* @typeParam TActivityContent - The shape of the activity content.
|
|
13
|
+
*/
|
|
14
|
+
type ReactActivityMessageRenderer<TActivityContent> = ActivityMessageRendererDef<TActivityContent, React.ComponentType<ActivityMessageRenderProps<TActivityContent>>>;
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region src/generative-ui/chat.d.ts
|
|
17
|
+
interface GenerativeUIChatSurfaceProps {
|
|
18
|
+
surfaceId: string;
|
|
19
|
+
isStreaming: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Set when operations from the latest render_ui call were rejected. The
|
|
22
|
+
* message is user-facing; `error.cause` holds the same list as `rejected`.
|
|
23
|
+
*/
|
|
24
|
+
error?: Error;
|
|
25
|
+
/** Rejected operations from the latest render_ui call, with validator reasons. */
|
|
26
|
+
rejected: GenerativeUIRejectedOperation[];
|
|
27
|
+
children: ReactNode;
|
|
28
|
+
}
|
|
29
|
+
declare function DefaultGenerativeUIChatCard({
|
|
30
|
+
surfaceId,
|
|
31
|
+
error,
|
|
32
|
+
children
|
|
33
|
+
}: GenerativeUIChatSurfaceProps): react_jsx_runtime0.JSX.Element;
|
|
34
|
+
/** Hides the raw `render_ui` tool call; the surface activity owns the UX. */
|
|
35
|
+
declare function GenerativeUIToolCallRenderer(): null;
|
|
36
|
+
//#endregion
|
|
37
|
+
export { ReactActivityMessageRenderer as i, GenerativeUIChatSurfaceProps as n, GenerativeUIToolCallRenderer as r, DefaultGenerativeUIChatCard as t };
|
|
38
|
+
//# sourceMappingURL=chat-CpZVyF_t.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat-CpZVyF_t.d.cts","names":[],"sources":["../src/types/react-activity-message-renderer.ts","../src/generative-ui/chat.tsx"],"mappings":";;;;;;;;;;AAaA;;;KAAY,4BAAA,qBACV,0BAAA,CACE,gBAAA,EACA,KAAA,CAAM,aAAA,CAAc,0BAAA,CAA2B,gBAAA;;;UCSlC,4BAAA;EACf,SAAA;EACA,WAAA;EDdsC;;;;ECmBtC,KAAA,GAAQ,KAAA;EDhBN;ECkBF,QAAA,EAAU,6BAAA;EACV,QAAA,EAAU,SAAA;AAAA;AAAA,iBAOI,2BAAA,CAAA;EACd,SAAA;EACA,KAAA;EACA;AAAA,GACC,4BAAA,GAA4B,kBAAA,CAAA,GAAA,CAAA,OAAA;;iBA0Ef,4BAAA,CAAA"}
|
package/dist/context.cjs
CHANGED
|
@@ -5,98 +5,110 @@ let react = require("react");
|
|
|
5
5
|
let _copilotkit_core = require("@copilotkit/core");
|
|
6
6
|
|
|
7
7
|
//#region src/lib/react-core.ts
|
|
8
|
+
/**
|
|
9
|
+
* Wait for pending React state updates before the follow-up agent run.
|
|
10
|
+
*
|
|
11
|
+
* When a frontend tool handler calls setState(), React 18 batches the update
|
|
12
|
+
* and schedules a commit via its internal scheduler (MessageChannel). The
|
|
13
|
+
* useAgentContext hook registers context via useLayoutEffect, which runs
|
|
14
|
+
* synchronously after React commits that batch.
|
|
15
|
+
*
|
|
16
|
+
* Awaiting a zero-delay timeout yields to the macrotask queue. React's
|
|
17
|
+
* MessageChannel task runs first, committing the pending state and running
|
|
18
|
+
* useLayoutEffect (which updates the context store). The follow-up runAgent
|
|
19
|
+
* call then reads fresh context.
|
|
20
|
+
*/
|
|
21
|
+
function waitForReactCommit() {
|
|
22
|
+
return new Promise((resolve) => setTimeout(resolve, 0));
|
|
23
|
+
}
|
|
8
24
|
var CopilotKitCoreReact = class extends _copilotkit_core.CopilotKitCore {
|
|
25
|
+
_renderers;
|
|
9
26
|
constructor(config) {
|
|
10
|
-
super(
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
this.
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
this.
|
|
27
|
+
super({
|
|
28
|
+
...config,
|
|
29
|
+
ɵwaitForFrameworkUpdates: waitForReactCommit
|
|
30
|
+
});
|
|
31
|
+
this._renderers = new _copilotkit_core.ɵRendererRegistry({
|
|
32
|
+
toolCalls: config.renderToolCalls,
|
|
33
|
+
activity: config.renderActivityMessages,
|
|
34
|
+
custom: config.renderCustomMessages
|
|
35
|
+
});
|
|
36
|
+
this._renderers.subscribe((kind) => this.notifyRenderersChanged(kind));
|
|
37
|
+
this.ɵsubscribeToInterruptPayload(() => {
|
|
38
|
+
this.notifySubscribers((subscriber) => {
|
|
39
|
+
return subscriber.onInterruptElementChanged?.({
|
|
40
|
+
copilotkit: this,
|
|
41
|
+
interruptElement: this.interruptElement
|
|
42
|
+
});
|
|
43
|
+
}, "Subscriber onInterruptElementChanged error:");
|
|
44
|
+
});
|
|
20
45
|
}
|
|
21
46
|
get renderCustomMessages() {
|
|
22
|
-
return this.
|
|
47
|
+
return this._renderers.custom;
|
|
23
48
|
}
|
|
24
49
|
get renderActivityMessages() {
|
|
25
|
-
return this.
|
|
50
|
+
return this._renderers.activity;
|
|
26
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* Prop, hook and built-in renderers merged. For one name and agentId, a
|
|
54
|
+
* hook renderer wins over a prop one, and both win over a built-in one.
|
|
55
|
+
*/
|
|
27
56
|
get renderToolCalls() {
|
|
28
|
-
|
|
29
|
-
if (this._cachedMergedRenderToolCalls) return this._cachedMergedRenderToolCalls;
|
|
30
|
-
const merged = /* @__PURE__ */ new Map();
|
|
31
|
-
for (const rc of this._renderToolCalls) merged.set(`${rc.agentId ?? ""}:${rc.name}`, rc);
|
|
32
|
-
for (const [key, rc] of this._hookRenderToolCalls) merged.set(key, rc);
|
|
33
|
-
this._cachedMergedRenderToolCalls = Array.from(merged.values());
|
|
34
|
-
return this._cachedMergedRenderToolCalls;
|
|
57
|
+
return this._renderers.toolCalls;
|
|
35
58
|
}
|
|
36
59
|
setRenderActivityMessages(renderers) {
|
|
37
|
-
this.
|
|
60
|
+
this._renderers.setActivity(renderers);
|
|
38
61
|
}
|
|
39
62
|
setRenderCustomMessages(renderers) {
|
|
40
|
-
this.
|
|
63
|
+
this._renderers.setCustom(renderers);
|
|
41
64
|
}
|
|
42
65
|
setRenderToolCalls(renderToolCalls) {
|
|
43
|
-
this.
|
|
44
|
-
this._cachedMergedRenderToolCalls = null;
|
|
45
|
-
this._notifyRenderToolCallsChanged();
|
|
66
|
+
this._renderers.setPropToolCalls(renderToolCalls);
|
|
46
67
|
}
|
|
47
68
|
addHookRenderToolCall(entry) {
|
|
48
|
-
|
|
49
|
-
this._hookRenderToolCalls.set(key, entry);
|
|
50
|
-
this._cachedMergedRenderToolCalls = null;
|
|
51
|
-
this._notifyRenderToolCallsChanged();
|
|
69
|
+
this._renderers.addHookToolCall(entry);
|
|
52
70
|
}
|
|
53
71
|
removeHookRenderToolCall(name, agentId) {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
72
|
+
this._renderers.removeHookToolCall(name, agentId);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* @internal Add a renderer for a tool a built-in feature owns
|
|
76
|
+
* (generative UI). Prop and hook renderers with the same name and agent win
|
|
77
|
+
* over it, and `setRenderToolCalls` never removes it.
|
|
78
|
+
*
|
|
79
|
+
* @returns A function that removes the renderer.
|
|
80
|
+
*/
|
|
81
|
+
ɵaddBuiltInRenderToolCall(entry) {
|
|
82
|
+
return this._renderers.addBuiltInToolCall(entry);
|
|
59
83
|
}
|
|
60
|
-
|
|
84
|
+
notifyRenderersChanged(kind) {
|
|
61
85
|
this.notifySubscribers((subscriber) => {
|
|
62
86
|
const reactSubscriber = subscriber;
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
87
|
+
switch (kind) {
|
|
88
|
+
case "toolCalls": return reactSubscriber.onRenderToolCallsChanged?.({
|
|
89
|
+
copilotkit: this,
|
|
90
|
+
renderToolCalls: this.renderToolCalls
|
|
91
|
+
});
|
|
92
|
+
case "activity": return reactSubscriber.onRenderActivityMessagesChanged?.({
|
|
93
|
+
copilotkit: this,
|
|
94
|
+
renderActivityMessages: this.renderActivityMessages
|
|
95
|
+
});
|
|
96
|
+
case "custom": return reactSubscriber.onRenderCustomMessagesChanged?.({
|
|
97
|
+
copilotkit: this,
|
|
98
|
+
renderCustomMessages: this.renderCustomMessages
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}, `Subscriber renderer change (${kind}) error:`);
|
|
68
102
|
}
|
|
69
103
|
get interruptElement() {
|
|
70
|
-
return this
|
|
104
|
+
return this.ɵinterruptPayload;
|
|
71
105
|
}
|
|
72
106
|
setInterruptElement(element) {
|
|
73
|
-
this
|
|
74
|
-
this.notifySubscribers((subscriber) => {
|
|
75
|
-
subscriber.onInterruptElementChanged?.({
|
|
76
|
-
copilotkit: this,
|
|
77
|
-
interruptElement: this._interruptElement
|
|
78
|
-
});
|
|
79
|
-
}, "Subscriber onInterruptElementChanged error:");
|
|
107
|
+
this.ɵsetInterruptPayload(element);
|
|
80
108
|
}
|
|
81
109
|
subscribe(subscriber) {
|
|
82
110
|
return super.subscribe(subscriber);
|
|
83
111
|
}
|
|
84
|
-
/**
|
|
85
|
-
* Wait for pending React state updates before the follow-up agent run.
|
|
86
|
-
*
|
|
87
|
-
* When a frontend tool handler calls setState(), React 18 batches the update
|
|
88
|
-
* and schedules a commit via its internal scheduler (MessageChannel). The
|
|
89
|
-
* useAgentContext hook registers context via useLayoutEffect, which runs
|
|
90
|
-
* synchronously after React commits that batch.
|
|
91
|
-
*
|
|
92
|
-
* Awaiting a zero-delay timeout yields to the macrotask queue. React's
|
|
93
|
-
* MessageChannel task runs first, committing the pending state and running
|
|
94
|
-
* useLayoutEffect (which updates the context store). The follow-up runAgent
|
|
95
|
-
* call then reads fresh context.
|
|
96
|
-
*/
|
|
97
|
-
async waitForPendingFrameworkUpdates() {
|
|
98
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
99
|
-
}
|
|
100
112
|
};
|
|
101
113
|
|
|
102
114
|
//#endregion
|
package/dist/context.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.cjs","names":["CopilotKitCore"],"sources":["../src/lib/react-core.ts","../src/context.ts"],"sourcesContent":["import React from \"react\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\nimport { CopilotKitCore } from \"@copilotkit/core\";\nimport type {\n CopilotKitCoreConfig,\n CopilotKitCoreSubscriber,\n CopilotKitCoreSubscription,\n} from \"@copilotkit/core\";\n\nexport interface CopilotKitCoreReactConfig extends CopilotKitCoreConfig {\n // Add any additional configuration properties specific to the React implementation\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n\n // Add custom message renderers\n renderCustomMessages?: ReactCustomMessageRenderer[];\n}\n\nexport interface CopilotKitCoreReactSubscriber extends CopilotKitCoreSubscriber {\n onRenderToolCallsChanged?: (event: {\n copilotkit: CopilotKitCore;\n renderToolCalls: ReactToolCallRenderer<any>[];\n }) => void | Promise<void>;\n onInterruptElementChanged?: (event: {\n copilotkit: CopilotKitCore;\n interruptElement: React.ReactElement | null;\n }) => void | Promise<void>;\n}\n\nexport class CopilotKitCoreReact extends CopilotKitCore {\n private _renderToolCalls: ReactToolCallRenderer<any>[] = [];\n private _hookRenderToolCalls: Map<string, ReactToolCallRenderer<any>> =\n new Map();\n private _cachedMergedRenderToolCalls: ReactToolCallRenderer<any>[] | null =\n null;\n private _renderCustomMessages: ReactCustomMessageRenderer[] = [];\n private _renderActivityMessages: ReactActivityMessageRenderer<any>[] = [];\n private _interruptElement: React.ReactElement | null = null;\n\n constructor(config: CopilotKitCoreReactConfig) {\n super(config);\n this._renderToolCalls = config.renderToolCalls ?? [];\n this._renderCustomMessages = config.renderCustomMessages ?? [];\n this._renderActivityMessages = config.renderActivityMessages ?? [];\n }\n\n get renderCustomMessages(): Readonly<ReactCustomMessageRenderer[]> {\n return this._renderCustomMessages;\n }\n\n get renderActivityMessages(): Readonly<ReactActivityMessageRenderer<any>>[] {\n return this._renderActivityMessages;\n }\n\n get renderToolCalls(): Readonly<ReactToolCallRenderer<any>>[] {\n if (this._hookRenderToolCalls.size === 0) {\n return this._renderToolCalls;\n }\n if (this._cachedMergedRenderToolCalls) {\n return this._cachedMergedRenderToolCalls;\n }\n // Merge: hook entries override prop entries with the same key\n const merged = new Map<string, ReactToolCallRenderer<any>>();\n for (const rc of this._renderToolCalls) {\n merged.set(`${rc.agentId ?? \"\"}:${rc.name}`, rc);\n }\n for (const [key, rc] of this._hookRenderToolCalls) {\n merged.set(key, rc);\n }\n this._cachedMergedRenderToolCalls = Array.from(merged.values());\n return this._cachedMergedRenderToolCalls;\n }\n\n setRenderActivityMessages(\n renderers: ReactActivityMessageRenderer<any>[],\n ): void {\n this._renderActivityMessages = renderers;\n }\n\n setRenderCustomMessages(renderers: ReactCustomMessageRenderer[]): void {\n this._renderCustomMessages = renderers;\n }\n\n setRenderToolCalls(renderToolCalls: ReactToolCallRenderer<any>[]): void {\n this._renderToolCalls = renderToolCalls;\n this._cachedMergedRenderToolCalls = null;\n this._notifyRenderToolCallsChanged();\n }\n\n addHookRenderToolCall(entry: ReactToolCallRenderer<any>): void {\n const key = `${entry.agentId ?? \"\"}:${entry.name}`;\n this._hookRenderToolCalls.set(key, entry);\n this._cachedMergedRenderToolCalls = null;\n this._notifyRenderToolCallsChanged();\n }\n\n removeHookRenderToolCall(name: string, agentId?: string): void {\n const key = `${agentId ?? \"\"}:${name}`;\n if (this._hookRenderToolCalls.delete(key)) {\n this._cachedMergedRenderToolCalls = null;\n this._notifyRenderToolCallsChanged();\n }\n }\n\n private _notifyRenderToolCallsChanged(): void {\n void this.notifySubscribers((subscriber) => {\n const reactSubscriber = subscriber as CopilotKitCoreReactSubscriber;\n if (reactSubscriber.onRenderToolCallsChanged) {\n reactSubscriber.onRenderToolCallsChanged({\n copilotkit: this,\n renderToolCalls: this.renderToolCalls,\n });\n }\n }, \"Subscriber onRenderToolCallsChanged error:\");\n }\n\n get interruptElement(): React.ReactElement | null {\n return this._interruptElement;\n }\n\n setInterruptElement(element: React.ReactElement | null): void {\n this._interruptElement = element;\n void this.notifySubscribers((subscriber) => {\n const reactSubscriber = subscriber as CopilotKitCoreReactSubscriber;\n reactSubscriber.onInterruptElementChanged?.({\n copilotkit: this,\n interruptElement: this._interruptElement,\n });\n }, \"Subscriber onInterruptElementChanged error:\");\n }\n\n // Override to accept React-specific subscriber type\n subscribe(\n subscriber: CopilotKitCoreReactSubscriber,\n ): CopilotKitCoreSubscription {\n return super.subscribe(subscriber);\n }\n\n /**\n * Wait for pending React state updates before the follow-up agent run.\n *\n * When a frontend tool handler calls setState(), React 18 batches the update\n * and schedules a commit via its internal scheduler (MessageChannel). The\n * useAgentContext hook registers context via useLayoutEffect, which runs\n * synchronously after React commits that batch.\n *\n * Awaiting a zero-delay timeout yields to the macrotask queue. React's\n * MessageChannel task runs first, committing the pending state and running\n * useLayoutEffect (which updates the context store). The follow-up runAgent\n * call then reads fresh context.\n */\n async waitForPendingFrameworkUpdates(): Promise<void> {\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n }\n}\n","\"use client\";\n\nimport { createContext, useContext, useEffect, useReducer } from \"react\";\nimport { CopilotKitCoreReact } from \"./lib/react-core\";\nimport type { CopilotKitCoreReactConfig } from \"./lib/react-core\";\nimport type { LicenseContextValue } from \"@copilotkit/shared\";\n\n// Re-export so headless.ts (and consumers) reference the same type declaration.\nexport { CopilotKitCoreReact };\nexport type { CopilotKitCoreReactConfig };\n\nexport interface CopilotKitContextValue {\n copilotkit: CopilotKitCoreReact;\n /**\n * Whether CopilotKit should automatically mount Intelligence indicators.\n * Defaults to true when omitted for compatibility with custom providers.\n */\n showIntelligenceIndicator?: boolean;\n /**\n * Set of tool call IDs currently being executed.\n * This is tracked at the provider level to ensure tool execution events\n * are captured even before child components mount.\n */\n executingToolCallIds: ReadonlySet<string>;\n}\n\nexport const EMPTY_SET: ReadonlySet<string> = new Set();\n\nexport const CopilotKitContext = createContext<CopilotKitContextValue | null>(\n null,\n);\n\nexport const useCopilotKit = (): CopilotKitContextValue => {\n const context = useContext(CopilotKitContext);\n const [, forceUpdate] = useReducer((x: number) => x + 1, 0);\n\n if (!context) {\n throw new Error(\"useCopilotKit must be used within CopilotKitProvider\");\n }\n useEffect(() => {\n const subscription = context.copilotkit.subscribe({\n onRuntimeConnectionStatusChanged: () => {\n forceUpdate();\n },\n onHeadersChanged: () => {\n forceUpdate();\n },\n });\n return () => {\n subscription.unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return context;\n};\n\n// License context — shared between web and RN providers.\n// Default is permissive (all features allowed) — providers override via createLicenseContextValue.\n// Inlined here to avoid a runtime import from @copilotkit/shared, which pulls in\n// Node-only deps (jose) that break React Native's Metro bundler.\nexport const LicenseContext = createContext<LicenseContextValue>({\n status: null,\n license: null,\n checkFeature: () => true,\n getLimit: () => null,\n} as LicenseContextValue);\n\nexport const useLicenseContext = (): LicenseContextValue =>\n useContext(LicenseContext);\n\n// Provider-level default agent id, published by `<CopilotKitProvider agentId>`.\n//\n// This is a context of its own rather than a `CopilotChatConfigurationProvider`\n// rendered at the root, because that provider also owns a thread: it resolves a\n// threadId (minting a UUID when none is given) and the top-most one owns the\n// imperative active-thread override. Rendering it around the whole application\n// would hand every `<CopilotChat>` the same inherited threadId, so two sibling\n// chats would share one transcript. A bare string context carries the agent\n// default and nothing else.\n//\n// It is the LAST fallback before `DEFAULT_AGENT_ID`, so an explicit `agentId`\n// argument, a `<CopilotChat agentId>`, and a `<CopilotChatConfigurationProvider\n// agentId>` all still win.\nexport const CopilotKitAgentIdContext = createContext<string | undefined>(\n undefined,\n);\n\nexport const useDefaultAgentId = (): string | undefined =>\n useContext(CopilotKitAgentIdContext);\n"],"mappings":";;;;;;;AAiCA,IAAa,sBAAb,cAAyCA,gCAAe;CAUtD,YAAY,QAAmC;AAC7C,QAAM,OAAO;0BAV0C,EAAE;8CAEzD,IAAI,KAAK;sCAET;+BAC4D,EAAE;iCACO,EAAE;2BAClB;AAIrD,OAAK,mBAAmB,OAAO,mBAAmB,EAAE;AACpD,OAAK,wBAAwB,OAAO,wBAAwB,EAAE;AAC9D,OAAK,0BAA0B,OAAO,0BAA0B,EA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zB,EAAK,KAAK,mBAAmB,eAAe;AAE1C,GADwB,WACR,4BAA4B;IAC1C,YAAY;IACZ,kBAAkB,KAAK;IACxB,CAAC;KACD,8CAA8C;;CAInD,UACE,YAC4B;AAC5B,SAAO,MAAM,UAAU,WAAW;;;;;;;;;;;;;;;CAgBpC,MAAM,iCAAgD;AACpD,QAAM,IAAI,SAAe,YAAY,WAAW,SAAS,EAAE,CAAC;;;;;;AClIhE,MAAa,4BAAiC,IAAI,KAAK;AAEvD,MAAa,6CACX,KACD;AAED,MAAa,sBAA8C;CACzD,MAAM,gCAAqB,kBAAkB;CAC7C,MAAM,GAAG,sCAA2B,MAAc,IAAI,GAAG,EAAE;AAE3D,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,uDAAuD;AAEzE,4BAAgB;EACd,MAAM,eAAe,QAAQ,WAAW,UAAU;GAChD,wCAAwC;AACtC,iBAAa;;GAEf,wBAAwB;AACtB,iBAAa;;GAEhB,CAAC;AACF,eAAa;AACX,gBAAa,aAAa;;IAG3B,EAAE,CAAC;AAEN,QAAO;;AAOT,MAAa,0CAAoD;CAC/D,QAAQ;CACR,SAAS;CACT,oBAAoB;CACpB,gBAAgB;CACjB,CAAwB;AAEzB,MAAa,gDACA,eAAe;AAe5B,MAAa,oDACX,OACD;AAED,MAAa,gDACA,yBAAyB"}
|
|
1
|
+
{"version":3,"file":"context.cjs","names":["CopilotKitCore","ɵRendererRegistry"],"sources":["../src/lib/react-core.ts","../src/context.ts"],"sourcesContent":["import React from \"react\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\nimport { CopilotKitCore, ɵRendererRegistry } from \"@copilotkit/core\";\nimport type {\n CopilotKitCoreConfig,\n CopilotKitCoreSubscriber,\n CopilotKitCoreSubscription,\n ɵRendererKind,\n} from \"@copilotkit/core\";\n\nexport interface CopilotKitCoreReactConfig extends CopilotKitCoreConfig {\n // Add any additional configuration properties specific to the React implementation\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n\n // Add custom message renderers\n renderCustomMessages?: ReactCustomMessageRenderer[];\n}\n\nexport interface CopilotKitCoreReactSubscriber extends CopilotKitCoreSubscriber {\n onRenderToolCallsChanged?: (event: {\n copilotkit: CopilotKitCore;\n renderToolCalls: readonly ReactToolCallRenderer<any>[];\n }) => void | Promise<void>;\n onRenderActivityMessagesChanged?: (event: {\n copilotkit: CopilotKitCore;\n renderActivityMessages: readonly ReactActivityMessageRenderer<any>[];\n }) => void | Promise<void>;\n onRenderCustomMessagesChanged?: (event: {\n copilotkit: CopilotKitCore;\n renderCustomMessages: readonly ReactCustomMessageRenderer[];\n }) => void | Promise<void>;\n onInterruptElementChanged?: (event: {\n copilotkit: CopilotKitCore;\n interruptElement: React.ReactElement | null;\n }) => void | Promise<void>;\n}\n\n/**\n * Wait for pending React state updates before the follow-up agent run.\n *\n * When a frontend tool handler calls setState(), React 18 batches the update\n * and schedules a commit via its internal scheduler (MessageChannel). The\n * useAgentContext hook registers context via useLayoutEffect, which runs\n * synchronously after React commits that batch.\n *\n * Awaiting a zero-delay timeout yields to the macrotask queue. React's\n * MessageChannel task runs first, committing the pending state and running\n * useLayoutEffect (which updates the context store). The follow-up runAgent\n * call then reads fresh context.\n */\nfunction waitForReactCommit() {\n return new Promise<void>((resolve) => setTimeout(resolve, 0));\n}\n\nexport class CopilotKitCoreReact extends CopilotKitCore {\n private readonly _renderers: ɵRendererRegistry<\n ReactToolCallRenderer<any>,\n ReactActivityMessageRenderer<any>,\n ReactCustomMessageRenderer\n >;\n\n constructor(config: CopilotKitCoreReactConfig) {\n super({\n ...config,\n ɵwaitForFrameworkUpdates: waitForReactCommit,\n });\n this._renderers = new ɵRendererRegistry({\n toolCalls: config.renderToolCalls,\n activity: config.renderActivityMessages,\n custom: config.renderCustomMessages,\n });\n this._renderers.subscribe((kind) => this.notifyRenderersChanged(kind));\n // The element lives in core's generic interrupt slot; keep the React\n // subscriber event for existing listeners.\n this.ɵsubscribeToInterruptPayload(() => {\n void this.notifySubscribers((subscriber) => {\n const reactSubscriber = subscriber as CopilotKitCoreReactSubscriber;\n return reactSubscriber.onInterruptElementChanged?.({\n copilotkit: this,\n interruptElement: this.interruptElement,\n });\n }, \"Subscriber onInterruptElementChanged error:\");\n });\n }\n\n get renderCustomMessages() {\n return this._renderers.custom;\n }\n\n get renderActivityMessages() {\n return this._renderers.activity;\n }\n\n /**\n * Prop, hook and built-in renderers merged. For one name and agentId, a\n * hook renderer wins over a prop one, and both win over a built-in one.\n */\n get renderToolCalls() {\n return this._renderers.toolCalls;\n }\n\n setRenderActivityMessages(\n renderers: ReactActivityMessageRenderer<any>[],\n ): void {\n this._renderers.setActivity(renderers);\n }\n\n setRenderCustomMessages(renderers: ReactCustomMessageRenderer[]): void {\n this._renderers.setCustom(renderers);\n }\n\n setRenderToolCalls(renderToolCalls: ReactToolCallRenderer<any>[]): void {\n this._renderers.setPropToolCalls(renderToolCalls);\n }\n\n addHookRenderToolCall(entry: ReactToolCallRenderer<any>): void {\n this._renderers.addHookToolCall(entry);\n }\n\n removeHookRenderToolCall(name: string, agentId?: string): void {\n this._renderers.removeHookToolCall(name, agentId);\n }\n\n /**\n * @internal Add a renderer for a tool a built-in feature owns\n * (generative UI). Prop and hook renderers with the same name and agent win\n * over it, and `setRenderToolCalls` never removes it.\n *\n * @returns A function that removes the renderer.\n */\n ɵaddBuiltInRenderToolCall(entry: ReactToolCallRenderer): () => void {\n return this._renderers.addBuiltInToolCall(entry);\n }\n\n private notifyRenderersChanged(kind: ɵRendererKind): void {\n void this.notifySubscribers((subscriber) => {\n const reactSubscriber = subscriber as CopilotKitCoreReactSubscriber;\n switch (kind) {\n case \"toolCalls\":\n return reactSubscriber.onRenderToolCallsChanged?.({\n copilotkit: this,\n renderToolCalls: this.renderToolCalls,\n });\n case \"activity\":\n return reactSubscriber.onRenderActivityMessagesChanged?.({\n copilotkit: this,\n renderActivityMessages: this.renderActivityMessages,\n });\n case \"custom\":\n return reactSubscriber.onRenderCustomMessagesChanged?.({\n copilotkit: this,\n renderCustomMessages: this.renderCustomMessages,\n });\n }\n }, `Subscriber renderer change (${kind}) error:`);\n }\n\n get interruptElement(): React.ReactElement | null {\n return this.ɵinterruptPayload as React.ReactElement | null;\n }\n\n setInterruptElement(element: React.ReactElement | null): void {\n this.ɵsetInterruptPayload(element);\n }\n\n // Override to accept React-specific subscriber type\n subscribe(\n subscriber: CopilotKitCoreReactSubscriber,\n ): CopilotKitCoreSubscription {\n return super.subscribe(subscriber);\n }\n}\n","\"use client\";\n\nimport { createContext, useContext, useEffect, useReducer } from \"react\";\nimport { CopilotKitCoreReact } from \"./lib/react-core\";\nimport type { CopilotKitCoreReactConfig } from \"./lib/react-core\";\nimport type { LicenseContextValue } from \"@copilotkit/shared\";\n\n// Re-export so headless.ts (and consumers) reference the same type declaration.\nexport { CopilotKitCoreReact };\nexport type { CopilotKitCoreReactConfig };\n\nexport interface CopilotKitContextValue {\n copilotkit: CopilotKitCoreReact;\n /**\n * Whether CopilotKit should automatically mount Intelligence indicators.\n * Defaults to true when omitted for compatibility with custom providers.\n */\n showIntelligenceIndicator?: boolean;\n /**\n * Set of tool call IDs currently being executed.\n * This is tracked at the provider level to ensure tool execution events\n * are captured even before child components mount.\n */\n executingToolCallIds: ReadonlySet<string>;\n}\n\nexport const EMPTY_SET: ReadonlySet<string> = new Set();\n\nexport const CopilotKitContext = createContext<CopilotKitContextValue | null>(\n null,\n);\n\nexport const useCopilotKit = (): CopilotKitContextValue => {\n const context = useContext(CopilotKitContext);\n const [, forceUpdate] = useReducer((x: number) => x + 1, 0);\n\n if (!context) {\n throw new Error(\"useCopilotKit must be used within CopilotKitProvider\");\n }\n useEffect(() => {\n const subscription = context.copilotkit.subscribe({\n onRuntimeConnectionStatusChanged: () => {\n forceUpdate();\n },\n onHeadersChanged: () => {\n forceUpdate();\n },\n });\n return () => {\n subscription.unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return context;\n};\n\n// License context — shared between web and RN providers.\n// Default is permissive (all features allowed) — providers override via createLicenseContextValue.\n// Inlined here to avoid a runtime import from @copilotkit/shared, which pulls in\n// Node-only deps (jose) that break React Native's Metro bundler.\nexport const LicenseContext = createContext<LicenseContextValue>({\n status: null,\n license: null,\n checkFeature: () => true,\n getLimit: () => null,\n} as LicenseContextValue);\n\nexport const useLicenseContext = (): LicenseContextValue =>\n useContext(LicenseContext);\n\n// Provider-level default agent id, published by `<CopilotKitProvider agentId>`.\n//\n// This is a context of its own rather than a `CopilotChatConfigurationProvider`\n// rendered at the root, because that provider also owns a thread: it resolves a\n// threadId (minting a UUID when none is given) and the top-most one owns the\n// imperative active-thread override. Rendering it around the whole application\n// would hand every `<CopilotChat>` the same inherited threadId, so two sibling\n// chats would share one transcript. A bare string context carries the agent\n// default and nothing else.\n//\n// It is the LAST fallback before `DEFAULT_AGENT_ID`, so an explicit `agentId`\n// argument, a `<CopilotChat agentId>`, and a `<CopilotChatConfigurationProvider\n// agentId>` all still win.\nexport const CopilotKitAgentIdContext = createContext<string | undefined>(\n undefined,\n);\n\nexport const useDefaultAgentId = (): string | undefined =>\n useContext(CopilotKitAgentIdContext);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuDA,SAAS,qBAAqB;AAC5B,QAAO,IAAI,SAAe,YAAY,WAAW,SAAS,EAAE,CAAC;;AAG/D,IAAa,sBAAb,cAAyCA,gCAAe;CACtD,AAAiB;CAMjB,YAAY,QAAmC;AAC7C,QAAM;GACJ,GAAG;GACH,0BAA0B;GAC3B,CAAC;AACF,OAAK,aAAa,IAAIC,mCAAkB;GACtC,WAAW,OAAO;GAClB,UAAU,OAAO;GACjB,QAAQ,OAAO;GAChB,CAAC;AACF,OAAK,WAAW,WAAW,SAAS,KAAK,uBAAuB,KAAK,CAAC;AAGtE,OAAK,mCAAmC;AACtC,GAAK,KAAK,mBAAmB,eAA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