@copilotkit/react-core 1.55.0-next.9 → 1.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +36 -6
  2. package/dist/{copilotkit-DeOzjPsb.mjs → copilotkit-BY5S1-0P.mjs} +2402 -552
  3. package/dist/copilotkit-BY5S1-0P.mjs.map +1 -0
  4. package/dist/{copilotkit-BqcyhQjT.d.mts → copilotkit-BuhSUZHb.d.mts} +228 -17
  5. package/dist/copilotkit-BuhSUZHb.d.mts.map +1 -0
  6. package/dist/{copilotkit-BDNjFNmk.cjs → copilotkit-Bz5-ImDl.cjs} +2421 -541
  7. package/dist/copilotkit-Bz5-ImDl.cjs.map +1 -0
  8. package/dist/{copilotkit-l-IBF4Xp.d.cts → copilotkit-dwDWYpya.d.cts} +228 -17
  9. package/dist/copilotkit-dwDWYpya.d.cts.map +1 -0
  10. package/dist/index.cjs +1 -1
  11. package/dist/index.d.cts +1 -1
  12. package/dist/index.d.mts +1 -1
  13. package/dist/index.mjs +1 -1
  14. package/dist/index.umd.js +1400 -238
  15. package/dist/index.umd.js.map +1 -1
  16. package/dist/v2/index.cjs +13 -1
  17. package/dist/v2/index.css +1 -1
  18. package/dist/v2/index.d.cts +3 -3
  19. package/dist/v2/index.d.mts +3 -3
  20. package/dist/v2/index.mjs +3 -2
  21. package/dist/v2/index.umd.js +2442 -552
  22. package/dist/v2/index.umd.js.map +1 -1
  23. package/package.json +62 -54
  24. package/scripts/scope-preflight.mjs +1 -2
  25. package/src/components/CopilotListeners.tsx +41 -8
  26. package/src/components/copilot-provider/copilotkit-props.tsx +4 -2
  27. package/src/components/toast/toast-provider.tsx +269 -194
  28. package/src/v2/__tests__/A2UIMessageRenderer.test.tsx +86 -22
  29. package/src/v2/__tests__/utils/test-helpers.tsx +67 -0
  30. package/src/v2/a2ui/A2UICatalogContext.tsx +79 -0
  31. package/src/v2/a2ui/A2UIMessageRenderer.tsx +125 -37
  32. package/src/v2/a2ui/A2UIToolCallRenderer.tsx +290 -0
  33. package/src/v2/components/CopilotKitInspector.tsx +2 -0
  34. package/src/v2/components/OpenGenerativeUIRenderer.tsx +598 -0
  35. package/src/v2/components/__tests__/OpenGenerativeUIRenderer.test.tsx +665 -0
  36. package/src/v2/components/chat/CopilotChat.tsx +193 -50
  37. package/src/v2/components/chat/CopilotChatAssistantMessage.tsx +17 -2
  38. package/src/v2/components/chat/CopilotChatAttachmentQueue.tsx +481 -0
  39. package/src/v2/components/chat/CopilotChatAttachmentRenderer.tsx +139 -0
  40. package/src/v2/components/chat/CopilotChatInput.tsx +146 -77
  41. package/src/v2/components/chat/CopilotChatMessageView.tsx +253 -149
  42. package/src/v2/components/chat/CopilotChatSuggestionView.tsx +1 -0
  43. package/src/v2/components/chat/CopilotChatUserMessage.tsx +54 -0
  44. package/src/v2/components/chat/CopilotChatView.tsx +179 -66
  45. package/src/v2/components/chat/__tests__/CopilotChat.attachments.test.tsx +168 -0
  46. package/src/v2/components/chat/__tests__/CopilotChatActivityRendering.e2e.test.tsx +63 -2
  47. package/src/v2/components/chat/__tests__/CopilotChatInput.test.tsx +544 -1
  48. package/src/v2/components/chat/__tests__/CopilotChatPerf.e2e.test.tsx +268 -0
  49. package/src/v2/components/chat/__tests__/CopilotChatPropsRerender.e2e.test.tsx +249 -0
  50. package/src/v2/components/chat/__tests__/MCPAppsActivityRenderer.e2e.test.tsx +43 -2
  51. package/src/v2/components/chat/__tests__/copilot-chat-throttle.test.tsx +138 -0
  52. package/src/v2/components/chat/index.ts +9 -0
  53. package/src/v2/components/chat/scroll-element-context.ts +13 -0
  54. package/src/v2/hooks/__tests__/use-agent-throttle.test.tsx +1003 -0
  55. package/src/v2/hooks/__tests__/use-attachments.test.tsx +169 -0
  56. package/src/v2/hooks/__tests__/use-threads.test.tsx +54 -0
  57. package/src/v2/hooks/index.ts +5 -0
  58. package/src/v2/hooks/use-agent.tsx +95 -10
  59. package/src/v2/hooks/use-attachments.tsx +269 -0
  60. package/src/v2/hooks/use-frontend-tool.tsx +5 -2
  61. package/src/v2/hooks/use-render-activity-message.tsx +9 -2
  62. package/src/v2/hooks/use-threads.tsx +35 -15
  63. package/src/v2/index.ts +5 -1
  64. package/src/v2/lib/__tests__/processPartialHtml.test.ts +112 -0
  65. package/src/v2/lib/__tests__/slots.test.ts +56 -0
  66. package/src/v2/lib/processPartialHtml.ts +45 -0
  67. package/src/v2/lib/slots.tsx +42 -1
  68. package/src/v2/providers/CopilotChatConfigurationProvider.tsx +9 -3
  69. package/src/v2/providers/CopilotKitProvider.tsx +268 -32
  70. package/src/v2/providers/SandboxFunctionsContext.ts +10 -0
  71. package/src/v2/providers/__tests__/CopilotKitProvider.sandboxFunctions.test.tsx +198 -0
  72. package/src/v2/providers/__tests__/CopilotKitProvider.test.tsx +71 -0
  73. package/src/v2/providers/index.ts +7 -0
  74. package/src/v2/styles/globals.css +2 -1
  75. package/src/v2/types/index.ts +1 -0
  76. package/src/v2/types/sandbox-function.ts +11 -0
  77. package/dist/copilotkit-BDNjFNmk.cjs.map +0 -1
  78. package/dist/copilotkit-BqcyhQjT.d.mts.map +0 -1
  79. package/dist/copilotkit-DeOzjPsb.mjs.map +0 -1
  80. package/dist/copilotkit-l-IBF4Xp.d.cts.map +0 -1
  81. package/src/v2/components/__tests__/license-warning-banner.test.tsx +0 -46
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","names":["DEFAULT_AGENT_ID","React","z","z","DEFAULT_SURFACE_ID","A2UIProvider","A2UIRenderer","CopilotKitCore","COPILOT_CLOUD_CHAT_URL","viewerTheme","z","React","ToolCallStatus","useRenderToolCall","DEFAULT_AGENT_ID","HttpAgent","DEFAULT_AGENT_ID","CopilotKitCoreRuntimeConnectionStatus","ProxiedCopilotRuntimeAgent","useFrontendTool","z","useHumanInTheLoop","React","DEFAULT_AGENT_ID","DEFAULT_AGENT_ID","emptyCopilotContext","React","setsHaveIntersection","React","Severity","CopilotKitApiDiscoveryError","CopilotKitRemoteEndpointDiscoveryError","CopilotKitAgentDiscoveryError","CopilotKitError","ErrorVisibility","CopilotKitErrorCode","Severity","CopilotKitErrorCode","COPILOT_CLOUD_API_URL","COPILOT_CLOUD_PUBLIC_API_KEY_HEADER","ReactMarkdown","React","CopilotKitError","CopilotKitLowLevelError","CopilotKitV2Provider","COPILOT_CLOUD_CHAT_URL","COPILOT_CLOUD_PUBLIC_API_KEY_HEADER","React","ConfigurationError","MissingPublicApiKeyError","useRenderToolCall","HttpAgent","AGUIConnectNotImplementedError","CopilotKitCoreRuntimeConnectionStatus","DeprecatedGqlMessage","CopilotKitError","CopilotKitErrorCode","Severity","ErrorVisibility","React","React","ToolCallStatus","CopilotKitError","CopilotKitErrorCode","CopilotKitAgentDiscoveryError","CopilotRuntimeClient","ErrorVisibility","CopilotKitError","CopilotKitErrorCode","CopilotKitApiDiscoveryError","CopilotKitRemoteEndpointDiscoveryError","CopilotKitAgentDiscoveryError","React","Fragment","MetaEventName","React","ActionInputAvailability","TextMessage","Role","CopilotRuntimeClient","CopilotRequestType"],"sources":["../src/v2/providers/CopilotChatConfigurationProvider.tsx","../src/v2/components/CopilotKitInspector.tsx","../src/v2/components/license-warning-banner.tsx","../src/v2/components/MCPAppsActivityRenderer.tsx","../src/v2/a2ui/A2UIMessageRenderer.tsx","../src/v2/lib/react-core.ts","../src/v2/providers/CopilotKitProvider.tsx","../src/v2/hooks/use-render-tool-call.tsx","../src/v2/hooks/use-agent.tsx","../src/v2/hooks/use-render-custom-messages.tsx","../src/v2/hooks/use-frontend-tool.tsx","../src/v2/types/defineToolCallRenderer.ts","../src/v2/hooks/use-human-in-the-loop.tsx","../src/v2/hooks/use-suggestions.tsx","../src/v2/hooks/use-configure-suggestions.tsx","../src/v2/hooks/use-interrupt.tsx","../src/context/copilot-context.tsx","../src/hooks/use-tree.ts","../src/hooks/use-flat-category-store.ts","../src/context/copilot-messages-context.tsx","../src/components/toast/toast-provider.tsx","../src/utils/dev-console.ts","../src/components/copilot-provider/copilot-messages.tsx","../src/components/usage-banner.tsx","../src/utils/suggestions-constants.ts","../src/lib/status-checker.ts","../src/components/toast/exclamation-mark-icon.tsx","../src/components/error-boundary/error-utils.tsx","../src/components/error-boundary/error-boundary.tsx","../src/context/coagent-state-renders-context.tsx","../src/context/threads-context.tsx","../src/hooks/use-coagent-state-render-bridge.helpers.ts","../src/hooks/use-coagent-state-render-registry.ts","../src/hooks/use-coagent-state-render-bridge.tsx","../src/components/CopilotListeners.tsx","../src/components/copilot-provider/copilotkit.tsx","../src/hooks/use-lazy-tool-renderer.tsx","../src/hooks/use-copilot-chat_internal.ts","../src/hooks/use-copilot-chat.ts","../src/hooks/use-copilot-chat-headless_c.ts","../src/hooks/use-frontend-tool.ts","../src/hooks/use-render-tool-call.ts","../src/hooks/use-human-in-the-loop.ts","../src/hooks/use-copilot-action.ts","../src/hooks/use-coagent-state-render.ts","../src/hooks/use-make-copilot-document-readable.ts","../src/hooks/use-copilot-readable.ts","../src/hooks/use-agent-nodename.ts","../src/hooks/use-coagent.ts","../src/hooks/use-copilot-runtime-client.ts","../src/hooks/use-copilot-authenticated-action.ts","../src/hooks/use-langgraph-interrupt.ts","../src/hooks/use-copilot-additional-instructions.ts","../src/hooks/use-default-tool.ts","../src/hooks/use-copilot-chat-suggestions.tsx","../src/types/frontend-action.ts","../src/lib/copilot-task.ts"],"sourcesContent":["import React, {\n createContext,\n useCallback,\n useContext,\n ReactNode,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { DEFAULT_AGENT_ID, randomUUID } from \"@copilotkit/shared\";\n\n// Default labels\nexport const CopilotChatDefaultLabels = {\n chatInputPlaceholder: \"Type a message...\",\n chatInputToolbarStartTranscribeButtonLabel: \"Transcribe\",\n chatInputToolbarCancelTranscribeButtonLabel: \"Cancel\",\n chatInputToolbarFinishTranscribeButtonLabel: \"Finish\",\n chatInputToolbarAddButtonLabel: \"Add photos or files\",\n chatInputToolbarToolsButtonLabel: \"Tools\",\n assistantMessageToolbarCopyCodeLabel: \"Copy\",\n assistantMessageToolbarCopyCodeCopiedLabel: \"Copied\",\n assistantMessageToolbarCopyMessageLabel: \"Copy\",\n assistantMessageToolbarThumbsUpLabel: \"Good response\",\n assistantMessageToolbarThumbsDownLabel: \"Bad response\",\n assistantMessageToolbarReadAloudLabel: \"Read aloud\",\n assistantMessageToolbarRegenerateLabel: \"Regenerate\",\n userMessageToolbarCopyMessageLabel: \"Copy\",\n userMessageToolbarEditMessageLabel: \"Edit\",\n chatDisclaimerText:\n \"AI can make mistakes. Please verify important information.\",\n chatToggleOpenLabel: \"Open chat\",\n chatToggleCloseLabel: \"Close chat\",\n modalHeaderTitle: \"CopilotKit Chat\",\n welcomeMessageText: \"How can I help you today?\",\n};\n\nexport type CopilotChatLabels = typeof CopilotChatDefaultLabels;\n\n// Define the full configuration interface\nexport interface CopilotChatConfigurationValue {\n labels: CopilotChatLabels;\n agentId: string;\n threadId: string;\n isModalOpen: boolean;\n setModalOpen: (open: boolean) => void;\n}\n\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 isModalDefaultOpen?: boolean;\n}\n\n// Provider component\nexport const CopilotChatConfigurationProvider: React.FC<\n CopilotChatConfigurationProviderProps\n> = ({ children, labels, agentId, threadId, isModalDefaultOpen }) => {\n const parentConfig = useContext(CopilotChatConfiguration);\n\n const mergedLabels: CopilotChatLabels = useMemo(\n () => ({\n ...CopilotChatDefaultLabels,\n ...(parentConfig?.labels ?? {}),\n ...(labels ?? {}),\n }),\n [labels, parentConfig?.labels],\n );\n\n const resolvedAgentId = agentId ?? parentConfig?.agentId ?? DEFAULT_AGENT_ID;\n\n const resolvedThreadId = useMemo(() => {\n if (threadId) {\n return threadId;\n }\n if (parentConfig?.threadId) {\n return parentConfig.threadId;\n }\n return randomUUID();\n }, [threadId, parentConfig?.threadId]);\n\n const resolvedDefaultOpen = isModalDefaultOpen ?? true;\n\n const [internalModalOpen, setInternalModalOpen] =\n useState<boolean>(resolvedDefaultOpen);\n\n const hasExplicitDefault = isModalDefaultOpen !== undefined;\n\n // When this provider owns its modal state, wrap the setter so that changes\n // propagate upward to any ancestor provider. This allows an outer\n // CopilotChatConfigurationProvider (e.g. a user's layout-level provider) to\n // observe open/close events that originate deep in the tree — fixing the\n // \"outer hook always returns true\" regression (CPK-7152 Behavior B).\n const setAndSync = useCallback(\n (open: boolean) => {\n setInternalModalOpen(open);\n parentConfig?.setModalOpen(open);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [parentConfig?.setModalOpen],\n );\n\n // Sync parent → child: when an ancestor's modal state is changed externally\n // (e.g. the user calls setModalOpen from an outer hook), reflect that change\n // in our own state so the sidebar/popup responds accordingly.\n // Skip the initial mount so that our own isModalDefaultOpen is respected and\n // not immediately overwritten by the parent's current value.\n const isMounted = useRef(false);\n useEffect(() => {\n if (!hasExplicitDefault) return;\n if (!isMounted.current) {\n isMounted.current = true;\n return;\n }\n if (parentConfig?.isModalOpen === undefined) return;\n setInternalModalOpen(parentConfig.isModalOpen);\n }, [parentConfig?.isModalOpen, hasExplicitDefault]);\n\n const resolvedIsModalOpen = hasExplicitDefault\n ? internalModalOpen\n : (parentConfig?.isModalOpen ?? internalModalOpen);\n const resolvedSetModalOpen = hasExplicitDefault\n ? setAndSync\n : (parentConfig?.setModalOpen ?? setInternalModalOpen);\n\n const configurationValue: CopilotChatConfigurationValue = useMemo(\n () => ({\n labels: mergedLabels,\n agentId: resolvedAgentId,\n threadId: resolvedThreadId,\n isModalOpen: resolvedIsModalOpen,\n setModalOpen: resolvedSetModalOpen,\n }),\n [\n mergedLabels,\n resolvedAgentId,\n resolvedThreadId,\n resolvedIsModalOpen,\n resolvedSetModalOpen,\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","import * as React from \"react\";\nimport { createComponent } from \"@lit-labs/react\";\nimport type { CopilotKitCore } from \"@copilotkit/core\";\n\ntype CopilotKitInspectorBaseProps = {\n core?: CopilotKitCore | null;\n [key: string]: unknown;\n};\n\ntype InspectorComponent = React.ComponentType<CopilotKitInspectorBaseProps>;\n\nexport interface CopilotKitInspectorProps extends CopilotKitInspectorBaseProps {}\n\nexport const CopilotKitInspector: React.FC<CopilotKitInspectorProps> = ({\n core,\n ...rest\n}) => {\n const [InspectorComponent, setInspectorComponent] =\n React.useState<InspectorComponent | null>(null);\n\n React.useEffect(() => {\n let mounted = true;\n\n // Load the web component only on the client to keep SSR output stable.\n import(\"@copilotkit/web-inspector\").then((mod) => {\n mod.defineWebInspector?.();\n\n const Component = createComponent({\n tagName: mod.WEB_INSPECTOR_TAG,\n elementClass: mod.WebInspectorElement,\n react: React,\n }) as InspectorComponent;\n\n if (mounted) {\n setInspectorComponent(() => Component);\n }\n });\n\n return () => {\n mounted = false;\n };\n }, []);\n\n // During SSR (and until the client finishes loading), render nothing to keep markup consistent.\n if (!InspectorComponent) return null;\n\n return <InspectorComponent {...rest} core={core ?? null} />;\n};\n\nCopilotKitInspector.displayName = \"CopilotKitInspector\";\n","import React from \"react\";\n\ninterface LicenseWarningBannerProps {\n type:\n | \"no_license\"\n | \"expired\"\n | \"expiring\"\n | \"invalid\"\n | \"feature_unlicensed\";\n featureName?: string;\n expiryDate?: string;\n graceRemaining?: number;\n onDismiss?: () => void;\n}\n\nconst BANNER_STYLES: Record<string, React.CSSProperties> = {\n base: {\n position: \"fixed\",\n bottom: \"8px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 99999,\n display: \"inline-flex\",\n alignItems: \"center\",\n gap: \"12px\",\n whiteSpace: \"nowrap\",\n padding: \"8px 16px\",\n fontSize: \"13px\",\n fontFamily:\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif\",\n borderRadius: \"6px\",\n boxShadow: \"0 2px 8px rgba(0, 0, 0, 0.15)\",\n },\n info: {\n backgroundColor: \"#eff6ff\",\n border: \"1px solid #93c5fd\",\n color: \"#1e40af\",\n },\n warning: {\n backgroundColor: \"#fffbeb\",\n border: \"1px solid #fbbf24\",\n color: \"#92400e\",\n },\n critical: {\n backgroundColor: \"#fef2f2\",\n border: \"1px solid #fca5a5\",\n color: \"#991b1b\",\n },\n};\n\nfunction getSeverityStyle(severity: string): React.CSSProperties {\n switch (severity) {\n case \"warning\":\n return BANNER_STYLES.warning;\n case \"critical\":\n return BANNER_STYLES.critical;\n default:\n return BANNER_STYLES.info;\n }\n}\n\nfunction BannerShell({\n severity,\n message,\n actionLabel,\n actionUrl,\n onDismiss,\n}: {\n severity: string;\n message: string;\n actionLabel: string;\n actionUrl: string;\n onDismiss?: () => void;\n}) {\n return (\n <div style={{ ...BANNER_STYLES.base, ...getSeverityStyle(severity) }}>\n <span>{message}</span>\n <div style={{ display: \"flex\", gap: \"8px\", alignItems: \"center\" }}>\n <a\n href={actionUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n style={{\n fontWeight: 600,\n textDecoration: \"underline\",\n color: \"inherit\",\n }}\n >\n {actionLabel}\n </a>\n {onDismiss && (\n <button\n onClick={onDismiss}\n style={{\n background: \"none\",\n border: \"none\",\n cursor: \"pointer\",\n color: \"inherit\",\n fontSize: \"16px\",\n }}\n >\n ×\n </button>\n )}\n </div>\n </div>\n );\n}\n\nexport function LicenseWarningBanner({\n type,\n featureName,\n expiryDate,\n graceRemaining,\n onDismiss,\n}: LicenseWarningBannerProps) {\n switch (type) {\n case \"no_license\":\n return (\n <BannerShell\n severity=\"info\"\n message=\"Powered by CopilotKit\"\n actionLabel=\"Get a license\"\n actionUrl=\"https://copilotkit.ai/pricing\"\n onDismiss={onDismiss}\n />\n );\n case \"feature_unlicensed\":\n return (\n <BannerShell\n severity=\"warning\"\n message={`⚠ The \"${featureName}\" feature requires a CopilotKit license.`}\n actionLabel=\"Get a license\"\n actionUrl=\"https://copilotkit.ai/pricing\"\n onDismiss={onDismiss}\n />\n );\n case \"expiring\":\n return (\n <BannerShell\n severity=\"warning\"\n message={`Your CopilotKit license expires in ${graceRemaining} day${graceRemaining !== 1 ? \"s\" : \"\"}. Please renew.`}\n actionLabel=\"Renew\"\n actionUrl=\"https://cloud.copilotkit.ai\"\n onDismiss={onDismiss}\n />\n );\n case \"expired\":\n return (\n <BannerShell\n severity=\"critical\"\n message={`Your CopilotKit license expired${expiryDate ? ` on ${expiryDate}` : \"\"}. Please renew at copilotkit.ai/pricing`}\n actionLabel=\"Renew now\"\n actionUrl=\"https://copilotkit.ai/pricing\"\n onDismiss={onDismiss}\n />\n );\n case \"invalid\":\n return (\n <BannerShell\n severity=\"critical\"\n message=\"Invalid CopilotKit license token. Please check your configuration.\"\n actionLabel=\"Get a license\"\n actionUrl=\"https://copilotkit.ai/pricing\"\n onDismiss={onDismiss}\n />\n );\n default:\n return null;\n }\n}\n\nexport function InlineFeatureWarning({ featureName }: { featureName: string }) {\n return (\n <div\n style={{\n padding: \"8px 12px\",\n backgroundColor: \"#fffbeb\",\n border: \"1px solid #fbbf24\",\n borderRadius: \"6px\",\n fontSize: \"13px\",\n color: \"#92400e\",\n fontFamily:\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif\",\n }}\n >\n ⚠ The &quot;{featureName}&quot; feature requires a CopilotKit license.{\" \"}\n <a\n href=\"https://copilotkit.ai/pricing\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n style={{ color: \"#b45309\", textDecoration: \"underline\" }}\n >\n Get one at copilotkit.ai/pricing\n </a>\n </div>\n );\n}\n","\"use client\";\n\nimport React, { useEffect, useRef, useState, useCallback } from \"react\";\nimport { z } from \"zod\";\nimport type { AbstractAgent, RunAgentResult } from \"@ag-ui/client\";\n\n// Protocol version supported\nconst PROTOCOL_VERSION = \"2025-06-18\";\n\n// Build sandbox proxy HTML with optional extra CSP domains from resource metadata\nfunction buildSandboxHTML(extraCspDomains?: string[]): string {\n const baseScriptSrc =\n \"'self' 'wasm-unsafe-eval' 'unsafe-inline' 'unsafe-eval' blob: data: http://localhost:* https://localhost:*\";\n const baseFrameSrc = \"* blob: data: http://localhost:* https://localhost:*\";\n const extra = extraCspDomains?.length ? \" \" + extraCspDomains.join(\" \") : \"\";\n const scriptSrc = baseScriptSrc + extra;\n const frameSrc = baseFrameSrc + extra;\n\n return `<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'self'; img-src * data: blob: 'unsafe-inline'; media-src * blob: data:; font-src * blob: data:; script-src ${scriptSrc}; style-src * blob: data: 'unsafe-inline'; connect-src *; frame-src ${frameSrc}; base-uri 'self';\" />\n<style>html,body{margin:0;padding:0;height:100%;width:100%;overflow:hidden}*{box-sizing:border-box}iframe{background-color:transparent;border:none;padding:0;overflow:hidden;width:100%;height:100%}</style>\n</head>\n<body>\n<script>\nif(window.self===window.top){throw new Error(\"This file must be used in an iframe.\")}\nconst inner=document.createElement(\"iframe\");\ninner.style=\"width:100%;height:100%;border:none;\";\ninner.setAttribute(\"sandbox\",\"allow-scripts allow-same-origin allow-forms\");\ndocument.body.appendChild(inner);\nwindow.addEventListener(\"message\",async(event)=>{\nif(event.source===window.parent){\nif(event.data&&event.data.method===\"ui/notifications/sandbox-resource-ready\"){\nconst{html,sandbox}=event.data.params;\nif(typeof sandbox===\"string\")inner.setAttribute(\"sandbox\",sandbox);\nif(typeof html===\"string\")inner.srcdoc=html;\n}else if(inner&&inner.contentWindow){\ninner.contentWindow.postMessage(event.data,\"*\");\n}\n}else if(event.source===inner.contentWindow){\nwindow.parent.postMessage(event.data,\"*\");\n}\n});\nwindow.parent.postMessage({jsonrpc:\"2.0\",method:\"ui/notifications/sandbox-proxy-ready\",params:{}},\"*\");\n</script>\n</body>\n</html>`;\n}\n\n/**\n * Queue for serializing MCP app requests to an agent.\n * Ensures requests wait for the agent to stop running and are processed one at a time.\n */\nclass MCPAppsRequestQueue {\n private queues = new Map<\n string,\n Array<{\n execute: () => Promise<RunAgentResult>;\n resolve: (result: RunAgentResult) => void;\n reject: (error: Error) => void;\n }>\n >();\n private processing = new Map<string, boolean>();\n\n /**\n * Add a request to the queue for a specific agent thread.\n * Returns a promise that resolves when the request completes.\n */\n async enqueue(\n agent: AbstractAgent,\n request: () => Promise<RunAgentResult>,\n ): Promise<RunAgentResult> {\n const threadId = agent.threadId || \"default\";\n\n return new Promise((resolve, reject) => {\n // Get or create queue for this thread\n let queue = this.queues.get(threadId);\n if (!queue) {\n queue = [];\n this.queues.set(threadId, queue);\n }\n\n // Add request to queue\n queue.push({ execute: request, resolve, reject });\n\n // Start processing if not already running\n this.processQueue(threadId, agent);\n });\n }\n\n private async processQueue(\n threadId: string,\n agent: AbstractAgent,\n ): Promise<void> {\n // If already processing this queue, return\n if (this.processing.get(threadId)) {\n return;\n }\n\n this.processing.set(threadId, true);\n\n try {\n const queue = this.queues.get(threadId);\n if (!queue) return;\n\n while (queue.length > 0) {\n const item = queue[0]!;\n\n try {\n // Wait for any active run to complete before processing\n await this.waitForAgentIdle(agent);\n\n // Execute the request\n const result = await item.execute();\n item.resolve(result);\n } catch (error) {\n item.reject(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n\n // Remove processed item\n queue.shift();\n }\n } finally {\n this.processing.set(threadId, false);\n }\n }\n\n private waitForAgentIdle(agent: AbstractAgent): Promise<void> {\n return new Promise((resolve) => {\n if (!agent.isRunning) {\n resolve();\n return;\n }\n\n let done = false;\n const finish = () => {\n if (done) return;\n done = true;\n clearInterval(checkInterval);\n sub.unsubscribe();\n resolve();\n };\n\n const sub = agent.subscribe({\n onRunFinalized: finish,\n onRunFailed: finish,\n });\n\n // Fallback for reconnect scenarios where events don't fire\n const checkInterval = setInterval(() => {\n if (!agent.isRunning) finish();\n }, 500);\n });\n }\n}\n\n// Global queue instance for all MCP app requests\nconst mcpAppsRequestQueue = new MCPAppsRequestQueue();\n\n/**\n * Activity type for MCP Apps events - must match the middleware's MCPAppsActivityType\n */\nexport const MCPAppsActivityType = \"mcp-apps\";\n\n// Zod schema for activity content validation (middleware 0.0.2 format)\nexport const MCPAppsActivityContentSchema = z.object({\n result: z.object({\n content: z.array(z.any()).optional(),\n structuredContent: z.any().optional(),\n isError: z.boolean().optional(),\n }),\n // Resource URI to fetch (e.g., \"ui://server/dashboard\")\n resourceUri: z.string(),\n // MD5 hash of server config (renamed from serverId in 0.0.1)\n serverHash: z.string(),\n // Optional stable server ID from config (takes precedence over serverHash)\n serverId: z.string().optional(),\n // Original tool input arguments\n toolInput: z.record(z.unknown()).optional(),\n});\n\nexport type MCPAppsActivityContent = z.infer<\n typeof MCPAppsActivityContentSchema\n>;\n\n// Type for the resource fetched from the server\ninterface FetchedResource {\n uri: string;\n mimeType?: string;\n text?: string;\n blob?: string;\n _meta?: {\n ui?: {\n prefersBorder?: boolean;\n csp?: {\n connectDomains?: string[];\n resourceDomains?: string[];\n };\n };\n };\n}\n\ninterface JSONRPCRequest {\n jsonrpc: \"2.0\";\n id: string | number;\n method: string;\n params?: Record<string, unknown>;\n}\n\ninterface JSONRPCResponse {\n jsonrpc: \"2.0\";\n id: string | number;\n result?: unknown;\n error?: { code: number; message: string };\n}\n\ninterface JSONRPCNotification {\n jsonrpc: \"2.0\";\n method: string;\n params?: Record<string, unknown>;\n}\n\ntype JSONRPCMessage = JSONRPCRequest | JSONRPCResponse | JSONRPCNotification;\n\nfunction isRequest(msg: JSONRPCMessage): msg is JSONRPCRequest {\n return \"id\" in msg && \"method\" in msg;\n}\n\nfunction isNotification(msg: JSONRPCMessage): msg is JSONRPCNotification {\n return !(\"id\" in msg) && \"method\" in msg;\n}\n\n/**\n * Props for the activity renderer component\n */\ninterface MCPAppsActivityRendererProps {\n activityType: string;\n content: MCPAppsActivityContent;\n message: unknown; // ActivityMessage from @ag-ui/core\n agent: AbstractAgent | undefined;\n}\n\n/**\n * MCP Apps Extension Activity Renderer\n *\n * Renders MCP Apps UI in a sandboxed iframe with full protocol support.\n * Fetches resource content on-demand via proxied MCP requests.\n */\nexport const MCPAppsActivityRenderer: React.FC<MCPAppsActivityRendererProps> =\n function MCPAppsActivityRenderer({ content, agent }) {\n const containerRef = useRef<HTMLDivElement>(null);\n const iframeRef = useRef<HTMLIFrameElement | null>(null);\n const [iframeReady, setIframeReady] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [iframeSize, setIframeSize] = useState<{\n width?: number;\n height?: number;\n }>({});\n const [fetchedResource, setFetchedResource] =\n useState<FetchedResource | null>(null);\n\n // Use refs for values that shouldn't trigger re-renders but need latest values\n const contentRef = useRef(content);\n contentRef.current = content;\n\n // Store agent in a ref for use in async handlers\n const agentRef = useRef(agent);\n agentRef.current = agent;\n\n // Ref to track fetch state - survives StrictMode remounts\n const fetchStateRef = useRef<{\n inProgress: boolean;\n promise: Promise<FetchedResource | null> | null;\n resourceUri: string | null;\n }>({ inProgress: false, promise: null, resourceUri: null });\n\n // Callback to send a message to the iframe\n const sendToIframe = useCallback((msg: JSONRPCMessage) => {\n if (iframeRef.current?.contentWindow) {\n console.log(\"[MCPAppsRenderer] Sending to iframe:\", msg);\n iframeRef.current.contentWindow.postMessage(msg, \"*\");\n }\n }, []);\n\n // Callback to send a JSON-RPC response\n const sendResponse = useCallback(\n (id: string | number, result: unknown) => {\n sendToIframe({\n jsonrpc: \"2.0\",\n id,\n result,\n });\n },\n [sendToIframe],\n );\n\n // Callback to send a JSON-RPC error response\n const sendErrorResponse = useCallback(\n (id: string | number, code: number, message: string) => {\n sendToIframe({\n jsonrpc: \"2.0\",\n id,\n error: { code, message },\n });\n },\n [sendToIframe],\n );\n\n // Callback to send a notification\n const sendNotification = useCallback(\n (method: string, params?: Record<string, unknown>) => {\n sendToIframe({\n jsonrpc: \"2.0\",\n method,\n params: params || {},\n });\n },\n [sendToIframe],\n );\n\n // Effect 0: Fetch the resource content on mount\n // Uses ref-based deduplication to handle React StrictMode double-mounting\n useEffect(() => {\n const { resourceUri, serverHash, serverId } = content;\n\n // Check if we already have a fetch in progress for this resource\n // This handles StrictMode double-mounting - second mount reuses first mount's promise\n if (\n fetchStateRef.current.inProgress &&\n fetchStateRef.current.resourceUri === resourceUri\n ) {\n // Reuse the existing promise\n fetchStateRef.current.promise\n ?.then((resource) => {\n if (resource) {\n setFetchedResource(resource);\n setIsLoading(false);\n }\n })\n .catch((err) => {\n setError(err instanceof Error ? err : new Error(String(err)));\n setIsLoading(false);\n });\n return;\n }\n\n if (!agent) {\n setError(new Error(\"No agent available to fetch resource\"));\n setIsLoading(false);\n return;\n }\n\n // Mark fetch as in progress\n fetchStateRef.current.inProgress = true;\n fetchStateRef.current.resourceUri = resourceUri;\n\n // Create the fetch promise using the queue to serialize requests\n const fetchPromise = (async (): Promise<FetchedResource | null> => {\n try {\n // Use queue to wait for agent to be idle and serialize requests\n const runResult = await mcpAppsRequestQueue.enqueue(agent, () =>\n agent.runAgent({\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId, // optional, takes precedence if provided\n method: \"resources/read\",\n params: { uri: resourceUri },\n },\n },\n }),\n );\n\n // Extract resource from result\n // The response format is: { contents: [{ uri, mimeType, text?, blob?, _meta? }] }\n const resultData = runResult.result as\n | { contents?: FetchedResource[] }\n | undefined;\n const resource = resultData?.contents?.[0];\n\n if (!resource) {\n throw new Error(\"No resource content in response\");\n }\n\n return resource;\n } catch (err) {\n console.error(\"[MCPAppsRenderer] Failed to fetch resource:\", err);\n throw err;\n } finally {\n // Mark fetch as complete\n fetchStateRef.current.inProgress = false;\n }\n })();\n\n // Store the promise for potential reuse\n fetchStateRef.current.promise = fetchPromise;\n\n // Handle the result\n fetchPromise\n .then((resource) => {\n if (resource) {\n setFetchedResource(resource);\n setIsLoading(false);\n }\n })\n .catch((err) => {\n setError(err instanceof Error ? err : new Error(String(err)));\n setIsLoading(false);\n });\n\n // No cleanup needed - we want the fetch to complete even if StrictMode unmounts\n }, [agent, content]);\n\n // Effect 1: Setup sandbox proxy iframe and communication (after resource is fetched)\n useEffect(() => {\n // Wait for resource to be fetched\n if (isLoading || !fetchedResource) {\n return;\n }\n\n // Capture container reference at effect start (refs are cleared during unmount)\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n let mounted = true;\n let messageHandler: ((event: MessageEvent) => void) | null = null;\n let initialListener: ((event: MessageEvent) => void) | null = null;\n let createdIframe: HTMLIFrameElement | null = null;\n\n const setup = async () => {\n try {\n // Create sandbox proxy iframe\n const iframe = document.createElement(\"iframe\");\n createdIframe = iframe; // Track for cleanup\n iframe.style.width = \"100%\";\n iframe.style.height = \"100px\"; // Start small, will be resized by size-changed notification\n iframe.style.border = \"none\";\n iframe.style.backgroundColor = \"transparent\";\n iframe.style.display = \"block\";\n iframe.setAttribute(\n \"sandbox\",\n \"allow-scripts allow-same-origin allow-forms\",\n );\n\n // Wait for sandbox proxy to be ready\n const sandboxReady = new Promise<void>((resolve) => {\n initialListener = (event: MessageEvent) => {\n if (event.source === iframe.contentWindow) {\n if (\n event.data?.method === \"ui/notifications/sandbox-proxy-ready\"\n ) {\n if (initialListener) {\n window.removeEventListener(\"message\", initialListener);\n initialListener = null;\n }\n resolve();\n }\n }\n };\n window.addEventListener(\"message\", initialListener);\n });\n\n // Check mounted before adding to DOM (handles StrictMode double-mount)\n if (!mounted) {\n if (initialListener) {\n window.removeEventListener(\"message\", initialListener);\n initialListener = null;\n }\n return;\n }\n\n // Build sandbox HTML with CSP domains from resource metadata\n const cspDomains = fetchedResource._meta?.ui?.csp?.resourceDomains;\n iframe.srcdoc = buildSandboxHTML(cspDomains);\n iframeRef.current = iframe;\n container.appendChild(iframe);\n\n // Wait for sandbox proxy to signal ready\n await sandboxReady;\n if (!mounted) return;\n\n console.log(\"[MCPAppsRenderer] Sandbox proxy ready\");\n\n // Setup message handler for JSON-RPC messages from the inner iframe\n messageHandler = async (event: MessageEvent) => {\n if (event.source !== iframe.contentWindow) return;\n\n const msg = event.data as JSONRPCMessage;\n if (!msg || typeof msg !== \"object\" || msg.jsonrpc !== \"2.0\")\n return;\n\n console.log(\"[MCPAppsRenderer] Received from iframe:\", msg);\n\n // Handle requests (need response)\n if (isRequest(msg)) {\n switch (msg.method) {\n case \"ui/initialize\": {\n // Respond with host capabilities\n sendResponse(msg.id, {\n protocolVersion: PROTOCOL_VERSION,\n hostInfo: {\n name: \"CopilotKit MCP Apps Host\",\n version: \"1.0.0\",\n },\n hostCapabilities: {\n openLinks: {},\n logging: {},\n },\n hostContext: {\n theme: \"light\",\n platform: \"web\",\n },\n });\n break;\n }\n\n case \"ui/message\": {\n // Add message to CopilotKit chat\n const currentAgent = agentRef.current;\n\n if (!currentAgent) {\n console.warn(\n \"[MCPAppsRenderer] ui/message: No agent available\",\n );\n sendResponse(msg.id, { isError: false });\n break;\n }\n\n try {\n const params = msg.params as {\n role?: string;\n content?: Array<{ type: string; text?: string }>;\n };\n\n // Extract text content from the message\n const textContent =\n params.content\n ?.filter((c) => c.type === \"text\" && c.text)\n .map((c) => c.text)\n .join(\"\\n\") || \"\";\n\n if (textContent) {\n currentAgent.addMessage({\n id: crypto.randomUUID(),\n role: (params.role as \"user\" | \"assistant\") || \"user\",\n content: textContent,\n });\n }\n sendResponse(msg.id, { isError: false });\n } catch (err) {\n console.error(\"[MCPAppsRenderer] ui/message error:\", err);\n sendResponse(msg.id, { isError: true });\n }\n break;\n }\n\n case \"ui/open-link\": {\n // Open URL in new tab\n const url = msg.params?.url as string | undefined;\n if (url) {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n sendResponse(msg.id, { isError: false });\n } else {\n sendErrorResponse(msg.id, -32602, \"Missing url parameter\");\n }\n break;\n }\n\n case \"tools/call\": {\n // Proxy tool call to MCP server via agent.runAgent()\n const { serverHash, serverId } = contentRef.current;\n const currentAgent = agentRef.current;\n\n if (!serverHash) {\n sendErrorResponse(\n msg.id,\n -32603,\n \"No server hash available for proxying\",\n );\n break;\n }\n\n if (!currentAgent) {\n sendErrorResponse(\n msg.id,\n -32603,\n \"No agent available for proxying\",\n );\n break;\n }\n\n try {\n // Use queue to wait for agent to be idle and serialize requests\n const runResult = await mcpAppsRequestQueue.enqueue(\n currentAgent,\n () =>\n currentAgent.runAgent({\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId, // optional, takes precedence if provided\n method: \"tools/call\",\n params: msg.params,\n },\n },\n }),\n );\n\n // The result from runAgent contains the MCP response\n sendResponse(msg.id, runResult.result || {});\n } catch (err) {\n console.error(\"[MCPAppsRenderer] tools/call error:\", err);\n sendErrorResponse(msg.id, -32603, String(err));\n }\n break;\n }\n\n default:\n sendErrorResponse(\n msg.id,\n -32601,\n `Method not found: ${msg.method}`,\n );\n }\n }\n\n // Handle notifications (no response needed)\n if (isNotification(msg)) {\n switch (msg.method) {\n case \"ui/notifications/initialized\": {\n console.log(\"[MCPAppsRenderer] Inner iframe initialized\");\n if (mounted) {\n setIframeReady(true);\n }\n break;\n }\n\n case \"ui/notifications/size-changed\": {\n const { width, height } = msg.params || {};\n console.log(\"[MCPAppsRenderer] Size change:\", {\n width,\n height,\n });\n if (mounted) {\n setIframeSize({\n width: typeof width === \"number\" ? width : undefined,\n height: typeof height === \"number\" ? height : undefined,\n });\n }\n break;\n }\n\n case \"notifications/message\": {\n // Logging notification from the app\n console.log(\"[MCPAppsRenderer] App log:\", msg.params);\n break;\n }\n }\n }\n };\n\n window.addEventListener(\"message\", messageHandler);\n\n // Extract HTML content from fetched resource\n let html: string;\n if (fetchedResource.text) {\n html = fetchedResource.text;\n } else if (fetchedResource.blob) {\n html = atob(fetchedResource.blob);\n } else {\n throw new Error(\"Resource has no text or blob content\");\n }\n\n // Send the resource content to the sandbox proxy\n sendNotification(\"ui/notifications/sandbox-resource-ready\", { html });\n } catch (err) {\n console.error(\"[MCPAppsRenderer] Setup error:\", err);\n if (mounted) {\n setError(err instanceof Error ? err : new Error(String(err)));\n }\n }\n };\n\n setup();\n\n return () => {\n mounted = false;\n // Clean up initial listener if still active\n if (initialListener) {\n window.removeEventListener(\"message\", initialListener);\n initialListener = null;\n }\n if (messageHandler) {\n window.removeEventListener(\"message\", messageHandler);\n }\n // Remove the iframe we created (using tracked reference, not DOM query)\n // This works even if containerRef.current is null during unmount\n if (createdIframe) {\n createdIframe.remove();\n createdIframe = null;\n }\n iframeRef.current = null;\n };\n }, [\n isLoading,\n fetchedResource,\n sendNotification,\n sendResponse,\n sendErrorResponse,\n ]);\n\n // Effect 2: Update iframe size when it changes\n useEffect(() => {\n if (iframeRef.current) {\n if (iframeSize.width !== undefined) {\n // Use minWidth with min() to allow expansion but cap at 100%\n iframeRef.current.style.minWidth = `min(${iframeSize.width}px, 100%)`;\n iframeRef.current.style.width = \"100%\";\n }\n if (iframeSize.height !== undefined) {\n iframeRef.current.style.height = `${iframeSize.height}px`;\n }\n }\n }, [iframeSize]);\n\n // Effect 3: Send tool input when iframe ready\n useEffect(() => {\n if (iframeReady && content.toolInput) {\n console.log(\"[MCPAppsRenderer] Sending tool input:\", content.toolInput);\n sendNotification(\"ui/notifications/tool-input\", {\n arguments: content.toolInput,\n });\n }\n }, [iframeReady, content.toolInput, sendNotification]);\n\n // Effect 4: Send tool result when iframe ready\n useEffect(() => {\n if (iframeReady && content.result) {\n console.log(\"[MCPAppsRenderer] Sending tool result:\", content.result);\n sendNotification(\"ui/notifications/tool-result\", content.result);\n }\n }, [iframeReady, content.result, sendNotification]);\n\n // Determine border styling based on prefersBorder metadata from fetched resource\n // true = show border/background, false = none, undefined = host decides (we default to none)\n const prefersBorder = fetchedResource?._meta?.ui?.prefersBorder;\n const borderStyle =\n prefersBorder === true\n ? {\n borderRadius: \"8px\",\n backgroundColor: \"#f9f9f9\",\n border: \"1px solid #e0e0e0\",\n }\n : {};\n\n return (\n <div\n ref={containerRef}\n style={{\n width: \"100%\",\n height: iframeSize.height ? `${iframeSize.height}px` : \"auto\",\n minHeight: \"100px\",\n overflow: \"hidden\",\n position: \"relative\",\n ...borderStyle,\n }}\n >\n {isLoading && (\n <div style={{ padding: \"1rem\", color: \"#666\" }}>Loading...</div>\n )}\n {error && (\n <div style={{ color: \"red\", padding: \"1rem\" }}>\n Error: {error.message}\n </div>\n )}\n </div>\n );\n };\n","import { useCopilotKit } from \"../providers\";\nimport type { ReactActivityMessageRenderer } from \"../types/react-activity-message-renderer\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { z } from \"zod\";\nimport {\n A2UIProvider,\n useA2UIActions,\n A2UIRenderer,\n initializeDefaultCatalog,\n injectStyles,\n DEFAULT_SURFACE_ID,\n} from \"@copilotkit/a2ui-renderer\";\nimport type { Theme, A2UIClientEventMessage } from \"@copilotkit/a2ui-renderer\";\n\n// Initialize the React renderer's component catalog and styles once\nlet initialized = false;\nfunction ensureInitialized() {\n if (!initialized) {\n initializeDefaultCatalog();\n injectStyles();\n initialized = true;\n }\n}\n\nexport type A2UIMessageRendererOptions = {\n theme: Theme;\n};\n\nexport function createA2UIMessageRenderer(\n options: A2UIMessageRendererOptions,\n): ReactActivityMessageRenderer<any> {\n const { theme } = options;\n\n return {\n activityType: \"a2ui-surface\",\n content: z.any(),\n render: ({ content, agent }) => {\n ensureInitialized();\n\n const [operations, setOperations] = useState<any[]>([]);\n const lastSignatureRef = useRef<string | null>(null);\n const { copilotkit } = useCopilotKit();\n\n useEffect(() => {\n if (!content || !Array.isArray(content.operations)) {\n lastSignatureRef.current = null;\n setOperations([]);\n return;\n }\n\n const incoming = content.operations as any[];\n const signature = stringifyOperations(incoming);\n\n if (signature && signature === lastSignatureRef.current) {\n return;\n }\n\n lastSignatureRef.current = signature;\n setOperations(incoming);\n }, [content]);\n\n // Group operations by surface ID\n const groupedOperations = useMemo(() => {\n const groups = new Map<string, any[]>();\n\n for (const operation of operations) {\n const surfaceId =\n getOperationSurfaceId(operation) ?? DEFAULT_SURFACE_ID;\n\n if (!groups.has(surfaceId)) {\n groups.set(surfaceId, []);\n }\n groups.get(surfaceId)!.push(operation);\n }\n\n return groups;\n }, [operations]);\n\n if (!groupedOperations.size) {\n return null;\n }\n\n return (\n <div className=\"cpk:flex cpk:min-h-0 cpk:flex-1 cpk:flex-col cpk:gap-6 cpk:overflow-auto cpk:py-6\">\n {Array.from(groupedOperations.entries()).map(([surfaceId, ops]) => (\n <ReactSurfaceHost\n key={surfaceId}\n surfaceId={surfaceId}\n operations={ops}\n theme={theme}\n agent={agent}\n copilotkit={copilotkit}\n />\n ))}\n </div>\n );\n },\n };\n}\n\ntype ReactSurfaceHostProps = {\n surfaceId: string;\n operations: any[];\n theme: Theme;\n agent: any;\n copilotkit: any;\n};\n\n/**\n * Renders a single A2UI surface using the React renderer.\n * Wraps A2UIProvider + A2UIRenderer and bridges actions back to CopilotKit.\n */\nfunction ReactSurfaceHost({\n surfaceId,\n operations,\n theme,\n agent,\n copilotkit,\n}: ReactSurfaceHostProps) {\n // Bridge: when the React renderer dispatches an action, send it to CopilotKit\n const handleAction = useCallback(\n async (message: A2UIClientEventMessage) => {\n if (!agent) return;\n\n try {\n console.info(\"[A2UI] Action dispatched\", message.userAction);\n\n copilotkit.setProperties({\n ...(copilotkit.properties ?? {}),\n a2uiAction: message,\n });\n\n await copilotkit.runAgent({ agent });\n } finally {\n if (copilotkit.properties) {\n const { a2uiAction, ...rest } = copilotkit.properties;\n copilotkit.setProperties(rest);\n }\n }\n },\n [agent, copilotkit],\n );\n\n return (\n <div className=\"cpk:flex cpk:w-full cpk:flex-none cpk:flex-col cpk:gap-4\">\n <A2UIProvider onAction={handleAction} theme={theme}>\n <SurfaceMessageProcessor\n surfaceId={surfaceId}\n operations={operations}\n />\n <A2UIRenderer surfaceId={surfaceId} className=\"cpk:flex cpk:flex-1\" />\n </A2UIProvider>\n </div>\n );\n}\n\n/**\n * Processes A2UI operations into the provider's message processor.\n * Must be a child of A2UIProvider to access the actions context.\n */\nfunction SurfaceMessageProcessor({\n surfaceId,\n operations,\n}: {\n surfaceId: string;\n operations: any[];\n}) {\n const { processMessages } = useA2UIActions();\n const lastProcessedRef = useRef<string>(\"\");\n\n useEffect(() => {\n const key = `${surfaceId}-${JSON.stringify(operations)}`;\n if (key === lastProcessedRef.current) return;\n lastProcessedRef.current = key;\n\n processMessages(operations);\n }, [processMessages, surfaceId, operations]);\n\n return null;\n}\n\nfunction getOperationSurfaceId(operation: any): string | null {\n if (!operation || typeof operation !== \"object\") {\n return null;\n }\n\n if (typeof operation.surfaceId === \"string\") {\n return operation.surfaceId;\n }\n\n return (\n operation?.beginRendering?.surfaceId ??\n operation?.surfaceUpdate?.surfaceId ??\n operation?.dataModelUpdate?.surfaceId ??\n operation?.deleteSurface?.surfaceId ??\n null\n );\n}\n\nfunction stringifyOperations(ops: any[]): string | null {\n try {\n return JSON.stringify(ops);\n } catch (error) {\n return null;\n }\n}\n","import React from \"react\";\nimport { ReactActivityMessageRenderer, ReactToolCallRenderer } from \"../types\";\nimport { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\nimport {\n CopilotKitCore,\n type CopilotKitCoreConfig,\n type CopilotKitCoreSubscriber,\n type 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 type { AbstractAgent } from \"@ag-ui/client\";\nimport type { FrontendTool } from \"@copilotkit/core\";\nimport type React from \"react\";\nimport {\n createContext,\n useContext,\n type ReactNode,\n useMemo,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from \"react\";\nimport { z } from \"zod\";\nimport { CopilotKitInspector } from \"../components/CopilotKitInspector\";\nimport { LicenseWarningBanner } from \"../components/license-warning-banner\";\nimport {\n createLicenseContextValue,\n type LicenseContextValue,\n} from \"@copilotkit/shared\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport {\n MCPAppsActivityContentSchema,\n MCPAppsActivityRenderer,\n MCPAppsActivityType,\n} from \"../components/MCPAppsActivityRenderer\";\nimport { createA2UIMessageRenderer } from \"../a2ui/A2UIMessageRenderer\";\nimport { viewerTheme } from \"@copilotkit/a2ui-renderer\";\nimport type { Theme as A2UITheme } from \"@copilotkit/a2ui-renderer\";\nimport { CopilotKitCoreReact } from \"../lib/react-core\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\n\nconst HEADER_NAME = \"X-CopilotCloud-Public-Api-Key\";\nconst COPILOT_CLOUD_CHAT_URL = \"https://api.cloud.copilotkit.ai/copilotkit/v1\";\n\n// Define the context value interface - idiomatic React naming\nexport interface CopilotKitContextValue {\n copilotkit: CopilotKitCoreReact;\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\n// Empty set for default context value\nconst EMPTY_SET: ReadonlySet<string> = new Set();\n\n// Create the CopilotKit context\nconst CopilotKitContext = createContext<CopilotKitContextValue>({\n copilotkit: null!,\n executingToolCallIds: EMPTY_SET,\n});\n\nconst LicenseContext = createContext<LicenseContextValue>(\n createLicenseContextValue(null),\n);\n\nexport const useLicenseContext = (): LicenseContextValue =>\n useContext(LicenseContext);\n\n// Provider props interface\nexport interface CopilotKitProviderProps {\n children: ReactNode;\n runtimeUrl?: string;\n headers?: Record<string, string>;\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /**\n * The Copilot Cloud public API key.\n */\n publicApiKey?: string;\n /**\n * Alias for `publicApiKey`\n **/\n publicLicenseKey?: string;\n /**\n * Signed license token for offline verification of premium features.\n * Obtain from https://cloud.copilotkit.ai.\n */\n licenseToken?: string;\n properties?: Record<string, unknown>;\n useSingleEndpoint?: boolean;\n agents__unsafe_dev_only?: Record<string, AbstractAgent>;\n selfManagedAgents?: Record<string, AbstractAgent>;\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n renderCustomMessages?: ReactCustomMessageRenderer[];\n frontendTools?: ReactFrontendTool[];\n humanInTheLoop?: ReactHumanInTheLoop[];\n showDevConsole?: boolean | \"auto\";\n /**\n * Error handler called when CopilotKit encounters an error.\n * Fires for all error types (runtime connection failures, agent errors, tool errors).\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Configuration for the A2UI (Agent-to-UI) renderer.\n * The built-in A2UI renderer is activated automatically when the runtime reports\n * that `a2ui` is configured in `CopilotRuntime`. This prop is optional and only\n * needed if you want to override the default theme.\n *\n * @example\n * ```tsx\n * <CopilotKit runtimeUrl=\"/api/copilotkit\" a2ui={{ theme: myCustomTheme }}>\n * {children}\n * </CopilotKit>\n * ```\n */\n a2ui?: {\n /**\n * Override the default A2UI viewer theme.\n * When omitted, the built-in `viewerTheme` from `@copilotkit/a2ui-renderer` is used.\n */\n theme?: A2UITheme;\n };\n}\n\n// Small helper to normalize array props to a stable reference and warn\nfunction useStableArrayProp<T>(\n prop: T[] | undefined,\n warningMessage?: string,\n isMeaningfulChange?: (initial: T[], next: T[]) => boolean,\n): T[] {\n const empty = useMemo<T[]>(() => [], []);\n const value = prop ?? empty;\n const initial = useRef(value);\n\n useEffect(() => {\n if (\n warningMessage &&\n value !== initial.current &&\n (isMeaningfulChange ? isMeaningfulChange(initial.current, value) : true)\n ) {\n console.error(warningMessage);\n }\n }, [value, warningMessage]);\n\n return value;\n}\n\n// Provider component\nexport const CopilotKitProvider: React.FC<CopilotKitProviderProps> = ({\n children,\n runtimeUrl,\n headers = {},\n credentials,\n publicApiKey,\n publicLicenseKey,\n licenseToken,\n properties = {},\n agents__unsafe_dev_only: agents = {},\n selfManagedAgents = {},\n renderToolCalls,\n renderActivityMessages,\n renderCustomMessages,\n frontendTools,\n humanInTheLoop,\n showDevConsole = false,\n useSingleEndpoint = false,\n onError,\n a2ui,\n}) => {\n const [shouldRenderInspector, setShouldRenderInspector] = useState(false);\n const [runtimeA2UIEnabled, setRuntimeA2UIEnabled] = useState(false);\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n string | undefined\n >(undefined);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n return;\n }\n\n if (showDevConsole === true) {\n // Explicitly show the inspector\n setShouldRenderInspector(true);\n } else if (showDevConsole === \"auto\") {\n // Show on localhost or 127.0.0.1 only\n const localhostHosts = new Set([\"localhost\", \"127.0.0.1\"]);\n if (localhostHosts.has(window.location.hostname)) {\n setShouldRenderInspector(true);\n } else {\n setShouldRenderInspector(false);\n }\n } else {\n // showDevConsole is false or undefined (default false)\n setShouldRenderInspector(false);\n }\n }, [showDevConsole]);\n\n // Normalize array props to stable references with clear dev warnings\n const renderToolCallsList = useStableArrayProp<ReactToolCallRenderer<any>>(\n renderToolCalls,\n \"renderToolCalls must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n (initial, next) => {\n // Only warn if the shape (names+agentId) changed. Allow identity changes\n // to support updated closures from parents (e.g., Storybook state).\n const key = (rc?: ReactToolCallRenderer<unknown>) =>\n `${rc?.agentId ?? \"\"}:${rc?.name ?? \"\"}`;\n const setFrom = (arr: ReactToolCallRenderer<unknown>[]) =>\n new Set(arr.map(key));\n const a = setFrom(initial);\n const b = setFrom(next);\n if (a.size !== b.size) return true;\n for (const k of a) if (!b.has(k)) return true;\n return false;\n },\n );\n\n const renderCustomMessagesList =\n useStableArrayProp<ReactCustomMessageRenderer>(\n renderCustomMessages,\n \"renderCustomMessages must be a stable array.\",\n );\n\n const renderActivityMessagesList = useStableArrayProp<\n ReactActivityMessageRenderer<any>\n >(renderActivityMessages, \"renderActivityMessages must be a stable array.\");\n\n // Built-in activity renderers that are always included\n const builtInActivityRenderers = useMemo<\n ReactActivityMessageRenderer<any>[]\n >(() => {\n const renderers: ReactActivityMessageRenderer<any>[] = [\n {\n activityType: MCPAppsActivityType,\n content: MCPAppsActivityContentSchema,\n render: MCPAppsActivityRenderer,\n },\n ];\n\n if (runtimeA2UIEnabled) {\n renderers.unshift(\n createA2UIMessageRenderer({ theme: a2ui?.theme ?? viewerTheme }),\n );\n }\n\n return renderers;\n }, [runtimeA2UIEnabled, a2ui]);\n\n // Combine user-provided activity renderers with built-in ones\n // User-provided renderers take precedence (come first) so they can override built-ins\n const allActivityRenderers = useMemo(() => {\n return [...renderActivityMessagesList, ...builtInActivityRenderers];\n }, [renderActivityMessagesList, builtInActivityRenderers]);\n\n const resolvedPublicKey = publicApiKey ?? publicLicenseKey;\n const mergedAgents = useMemo(\n () => ({ ...agents, ...selfManagedAgents }),\n [agents, selfManagedAgents],\n );\n const hasLocalAgents = mergedAgents && Object.keys(mergedAgents).length > 0;\n\n // Merge a provided publicApiKey into headers (without overwriting an explicit header).\n const mergedHeaders = useMemo(() => {\n if (!resolvedPublicKey) return headers;\n if (headers[HEADER_NAME]) return headers;\n return {\n ...headers,\n [HEADER_NAME]: resolvedPublicKey,\n };\n }, [headers, resolvedPublicKey]);\n\n if (!runtimeUrl && !resolvedPublicKey && !hasLocalAgents) {\n const message =\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\";\n if (process.env.NODE_ENV === \"production\") {\n throw new Error(message);\n } else {\n // In dev/test we warn but allow to facilitate local agents and unit tests.\n console.warn(message);\n }\n }\n\n const chatApiEndpoint =\n runtimeUrl ?? (resolvedPublicKey ? COPILOT_CLOUD_CHAT_URL : undefined);\n\n const frontendToolsList = useStableArrayProp<ReactFrontendTool>(\n frontendTools,\n \"frontendTools must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n );\n const humanInTheLoopList = useStableArrayProp<ReactHumanInTheLoop>(\n humanInTheLoop,\n \"humanInTheLoop must be a stable array. If you want to dynamically add or remove human-in-the-loop tools, use `useHumanInTheLoop` instead.\",\n );\n\n // Note: warnings for array identity changes are handled by useStableArrayProp\n\n // Process humanInTheLoop tools to create handlers and add render components\n const processedHumanInTheLoopTools = useMemo(() => {\n const processedTools: FrontendTool[] = [];\n const processedRenderToolCalls: ReactToolCallRenderer<unknown>[] = [];\n\n humanInTheLoopList.forEach((tool) => {\n // Create a promise-based handler for each human-in-the-loop tool\n const frontendTool: FrontendTool = {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n followUp: tool.followUp,\n ...(tool.agentId && { agentId: tool.agentId }),\n handler: async () => {\n // This handler will be replaced by the hook when it runs\n // For provider-level tools, we create a basic handler that waits for user interaction\n return new Promise((resolve) => {\n // The actual implementation will be handled by the render component\n // This is a placeholder that the hook will override\n console.warn(\n `Human-in-the-loop tool '${tool.name}' called but no interactive handler is set up.`,\n );\n resolve(undefined);\n });\n },\n };\n processedTools.push(frontendTool);\n\n // Add the render component to renderToolCalls\n if (tool.render) {\n processedRenderToolCalls.push({\n name: tool.name,\n args: tool.parameters!,\n render: tool.render,\n ...(tool.agentId && { agentId: tool.agentId }),\n } as ReactToolCallRenderer<unknown>);\n }\n });\n\n return { tools: processedTools, renderToolCalls: processedRenderToolCalls };\n }, [humanInTheLoopList]);\n\n // Combine all tools for CopilotKitCore\n const allTools = useMemo(() => {\n const tools: FrontendTool[] = [];\n\n // Add frontend tools\n tools.push(...frontendToolsList);\n\n // Add processed human-in-the-loop tools\n tools.push(...processedHumanInTheLoopTools.tools);\n\n return tools;\n }, [frontendToolsList, processedHumanInTheLoopTools]);\n\n // Combine all render tool calls\n const allRenderToolCalls = useMemo(() => {\n const combined: ReactToolCallRenderer<unknown>[] = [...renderToolCallsList];\n\n // Add render components from frontend tools\n frontendToolsList.forEach((tool) => {\n if (tool.render) {\n // For wildcard tools without parameters, default to z.any()\n const args =\n tool.parameters || (tool.name === \"*\" ? z.any() : undefined);\n if (args) {\n combined.push({\n name: tool.name,\n args: args,\n render: tool.render,\n } as ReactToolCallRenderer<unknown>);\n }\n }\n });\n\n // Add render components from human-in-the-loop tools\n combined.push(...processedHumanInTheLoopTools.renderToolCalls);\n\n return combined;\n }, [renderToolCallsList, frontendToolsList, processedHumanInTheLoopTools]);\n\n // Stable instance: created once for the provider lifetime.\n // Updates are applied via setter effects below rather than recreating the instance.\n const copilotkitRef = useRef<CopilotKitCoreReact | null>(null);\n if (copilotkitRef.current === null) {\n copilotkitRef.current = new CopilotKitCoreReact({\n runtimeUrl: chatApiEndpoint,\n runtimeTransport: useSingleEndpoint ? \"single\" : \"rest\",\n headers: mergedHeaders,\n credentials,\n properties,\n agents__unsafe_dev_only: mergedAgents,\n tools: allTools,\n renderToolCalls: allRenderToolCalls,\n renderActivityMessages: allActivityRenderers,\n renderCustomMessages: renderCustomMessagesList,\n });\n }\n const copilotkit = copilotkitRef.current;\n\n // Sync runtime-reported state once runtime info is fetched\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeA2UIEnabled(copilotkit.a2uiEnabled);\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // Subscribe to render tool calls changes to force re-renders\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onRenderToolCallsChanged: () => {\n forceUpdate();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // Track executing tool call IDs at the provider level.\n // This is critical for HITL reconnection: when connecting to a thread with\n // pending tool calls, the onToolExecutionStart event fires before child components\n // (like CopilotChatToolCallsView) mount. By tracking at the provider level,\n // we ensure the executing state is captured and available when children mount.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // onError subscription — forward core errors to user callback\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n\n const subscription = copilotkit.subscribe({\n onError: (event) => {\n onErrorRef.current?.({\n error: event.error,\n code: event.code,\n context: event.context,\n });\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n useEffect(() => {\n copilotkit.setRuntimeUrl(chatApiEndpoint);\n copilotkit.setRuntimeTransport(useSingleEndpoint ? \"single\" : \"rest\");\n copilotkit.setHeaders(mergedHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(properties);\n copilotkit.setAgents__unsafe_dev_only(mergedAgents);\n }, [\n copilotkit,\n chatApiEndpoint,\n mergedHeaders,\n credentials,\n properties,\n mergedAgents,\n useSingleEndpoint,\n ]);\n\n // Sync render/tool arrays to the stable instance via setters.\n // On mount, the constructor already receives the correct initial values,\n // so we skip the first invocation. This is critical because child hooks\n // (e.g., useFrontendTool, useHumanInTheLoop) register tools dynamically\n // via addTool()/setRenderToolCalls() in their own effects, which fire\n // BEFORE parent effects (React fires effects bottom-up). If the parent\n // setter effects ran on mount, they would overwrite the children's tools.\n const didMountRef = useRef(false);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setTools(allTools);\n }, [copilotkit, allTools]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderToolCalls(allRenderToolCalls);\n }, [copilotkit, allRenderToolCalls]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderActivityMessages(allActivityRenderers);\n }, [copilotkit, allActivityRenderers]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderCustomMessages(renderCustomMessagesList);\n }, [copilotkit, renderCustomMessagesList]);\n\n // Mark mount complete — must be declared AFTER the setter effects\n // so it runs last in the effect queue on the initial mount cycle.\n useEffect(() => {\n didMountRef.current = true;\n }, []);\n\n const contextValue = useMemo<CopilotKitContextValue>(\n () => ({ copilotkit, executingToolCallIds }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(null),\n [],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n {children}\n {shouldRenderInspector ? (\n <CopilotKitInspector core={copilotkit} />\n ) : null}\n {/* License warnings — driven by server-reported status */}\n {runtimeLicenseStatus === \"none\" && !resolvedPublicKey && (\n <LicenseWarningBanner type=\"no_license\" />\n )}\n {runtimeLicenseStatus === \"expired\" && (\n <LicenseWarningBanner type=\"expired\" />\n )}\n {runtimeLicenseStatus === \"invalid\" && (\n <LicenseWarningBanner type=\"invalid\" />\n )}\n {runtimeLicenseStatus === \"expiring\" && (\n <LicenseWarningBanner type=\"expiring\" />\n )}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n\n// Hook to use the CopilotKit instance - returns the full context value\nexport const useCopilotKit = (): CopilotKitContextValue => {\n const context = useContext(CopilotKitContext);\n const [, forceUpdate] = useReducer((x) => 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 });\n return () => {\n subscription.unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return context;\n};\n","import React, { useCallback, useMemo, useSyncExternalStore } from \"react\";\nimport { ToolCall, ToolMessage } from \"@ag-ui/core\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\nimport { partialJSONParse } from \"@copilotkit/shared\";\nimport { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\n\nexport interface UseRenderToolCallProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n}\n\n/**\n * Props for the memoized ToolCallRenderer component\n */\ninterface ToolCallRendererProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n RenderComponent: ReactToolCallRenderer<unknown>[\"render\"];\n isExecuting: boolean;\n}\n\n/**\n * Memoized component that renders a single tool call.\n * This prevents unnecessary re-renders when parent components update\n * but the tool call data hasn't changed.\n */\nconst ToolCallRenderer = React.memo(\n function ToolCallRenderer({\n toolCall,\n toolMessage,\n RenderComponent,\n isExecuting,\n }: ToolCallRendererProps) {\n // Memoize args based on the arguments string to maintain stable reference\n const args = useMemo(\n () => partialJSONParse(toolCall.function.arguments),\n [toolCall.function.arguments],\n );\n\n const toolName = toolCall.function.name;\n\n // Render based on status to preserve discriminated union type inference\n if (toolMessage) {\n return (\n <RenderComponent\n name={toolName}\n args={args}\n status={ToolCallStatus.Complete}\n result={toolMessage.content}\n />\n );\n } else if (isExecuting) {\n return (\n <RenderComponent\n name={toolName}\n args={args}\n status={ToolCallStatus.Executing}\n result={undefined}\n />\n );\n } else {\n return (\n <RenderComponent\n name={toolName}\n args={args}\n status={ToolCallStatus.InProgress}\n result={undefined}\n />\n );\n }\n },\n // Custom comparison function to prevent re-renders when tool call data hasn't changed\n (prevProps, nextProps) => {\n // Compare tool call identity and content\n if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;\n if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name)\n return false;\n if (\n prevProps.toolCall.function.arguments !==\n nextProps.toolCall.function.arguments\n )\n return false;\n\n // Compare tool message (result)\n const prevResult = prevProps.toolMessage?.content;\n const nextResult = nextProps.toolMessage?.content;\n if (prevResult !== nextResult) return false;\n\n // Compare executing state\n if (prevProps.isExecuting !== nextProps.isExecuting) return false;\n\n // Compare render component reference\n if (prevProps.RenderComponent !== nextProps.RenderComponent) return false;\n\n return true;\n },\n);\n\n/**\n * Hook that returns a function to render tool calls based on the render functions\n * defined in CopilotKitProvider.\n *\n * @returns A function that takes a tool call and optional tool message and returns the rendered component\n */\nexport function useRenderToolCall() {\n const { copilotkit, executingToolCallIds } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const agentId = config?.agentId ?? DEFAULT_AGENT_ID;\n\n // Subscribe to render tool calls changes using useSyncExternalStore\n // This ensures we always have the latest value, even if subscriptions run in any order\n const renderToolCalls = useSyncExternalStore(\n (callback) => {\n return copilotkit.subscribe({\n onRenderToolCallsChanged: callback,\n }).unsubscribe;\n },\n () => copilotkit.renderToolCalls,\n () => copilotkit.renderToolCalls,\n );\n\n // Note: executingToolCallIds is now provided by CopilotKitProvider context.\n // This is critical for HITL reconnection: when connecting to a thread with\n // pending tool calls, the onToolExecutionStart event fires before child components\n // mount. By tracking at the provider level, the executing state is already\n // available when this hook first runs.\n\n const renderToolCall = useCallback(\n ({\n toolCall,\n toolMessage,\n }: UseRenderToolCallProps): React.ReactElement | null => {\n // Find the render config for this tool call by name\n // For rendering, we show all tool calls regardless of agentId\n // The agentId scoping only affects handler execution (in core)\n // Priority order:\n // 1. Exact match by name (prefer agent-specific if multiple exist)\n // 2. Wildcard (*) renderer\n const exactMatches = renderToolCalls.filter(\n (rc) => rc.name === toolCall.function.name,\n );\n\n // If multiple renderers with same name exist, prefer the one matching our agentId\n const renderConfig =\n exactMatches.find((rc) => rc.agentId === agentId) ||\n exactMatches.find((rc) => !rc.agentId) ||\n exactMatches[0] ||\n renderToolCalls.find((rc) => rc.name === \"*\");\n\n if (!renderConfig) {\n return null;\n }\n\n const RenderComponent = renderConfig.render;\n const isExecuting = executingToolCallIds.has(toolCall.id);\n\n // Use the memoized ToolCallRenderer component to prevent unnecessary re-renders\n return (\n <ToolCallRenderer\n key={toolCall.id}\n toolCall={toolCall}\n toolMessage={toolMessage}\n RenderComponent={RenderComponent}\n isExecuting={isExecuting}\n />\n );\n },\n [renderToolCalls, executingToolCallIds, agentId],\n );\n\n return renderToolCall;\n}\n","import { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { useMemo, useEffect, useReducer, useRef } from \"react\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\nimport { AbstractAgent, HttpAgent } from \"@ag-ui/client\";\nimport {\n ProxiedCopilotRuntimeAgent,\n CopilotKitCoreRuntimeConnectionStatus,\n} from \"@copilotkit/core\";\n\nexport enum UseAgentUpdate {\n OnMessagesChanged = \"OnMessagesChanged\",\n OnStateChanged = \"OnStateChanged\",\n OnRunStatusChanged = \"OnRunStatusChanged\",\n}\n\nconst ALL_UPDATES: UseAgentUpdate[] = [\n UseAgentUpdate.OnMessagesChanged,\n UseAgentUpdate.OnStateChanged,\n UseAgentUpdate.OnRunStatusChanged,\n];\n\nexport interface UseAgentProps {\n agentId?: string;\n threadId?: string;\n updates?: UseAgentUpdate[];\n}\n\n/**\n * Clone a registry agent for per-thread isolation.\n * Copies agent configuration (transport, headers, etc.) but resets conversation\n * state (messages, threadId, state) so each thread starts fresh.\n */\nfunction cloneForThread(\n source: AbstractAgent,\n threadId: string,\n headers: Record<string, string>,\n): AbstractAgent {\n const clone = source.clone();\n if (clone === source) {\n throw new Error(\n `useAgent: ${source.constructor.name}.clone() returned the same instance. ` +\n `clone() must return a new, independent object.`,\n );\n }\n clone.threadId = threadId;\n clone.setMessages([]);\n clone.setState({});\n if (clone instanceof HttpAgent) {\n clone.headers = { ...headers };\n }\n return clone;\n}\n\n/**\n * Module-level WeakMap: registryAgent → (threadId → clone).\n * Shared across all useAgent() calls so that every component using the same\n * (agentId, threadId) pair receives the same agent instance. Using WeakMap\n * ensures the clone map is garbage-collected when the registry agent is\n * replaced (e.g. after reconnect or hot-reload).\n */\nexport const globalThreadCloneMap = new WeakMap<\n AbstractAgent,\n Map<string, AbstractAgent>\n>();\n\n/**\n * Look up an existing per-thread clone without creating one.\n * Returns undefined when no clone has been created yet for this pair.\n */\nexport function getThreadClone(\n registryAgent: AbstractAgent | undefined | null,\n threadId: string | undefined | null,\n): AbstractAgent | undefined {\n if (!registryAgent || !threadId) return undefined;\n return globalThreadCloneMap.get(registryAgent)?.get(threadId);\n}\n\nfunction getOrCreateThreadClone(\n existing: AbstractAgent,\n threadId: string,\n headers: Record<string, string>,\n): AbstractAgent {\n let byThread = globalThreadCloneMap.get(existing);\n if (!byThread) {\n byThread = new Map();\n globalThreadCloneMap.set(existing, byThread);\n }\n const cached = byThread.get(threadId);\n if (cached) return cached;\n\n const clone = cloneForThread(existing, threadId, headers);\n byThread.set(threadId, clone);\n return clone;\n}\n\nexport function useAgent({ agentId, threadId, updates }: UseAgentProps = {}) {\n agentId ??= DEFAULT_AGENT_ID;\n\n const { copilotkit } = useCopilotKit();\n // Fall back to the enclosing CopilotChatConfigurationProvider's threadId so\n // that useAgent() called without explicit threadId (e.g. inside a custom\n // message renderer) automatically uses the same per-thread clone as the\n // CopilotChat component it lives within.\n const chatConfig = useCopilotChatConfiguration();\n threadId ??= chatConfig?.threadId;\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n const updateFlags = useMemo(\n () => updates ?? ALL_UPDATES,\n [JSON.stringify(updates)],\n );\n\n // Cache provisional agents to avoid creating new references on every render\n // while the runtime is still connecting. A new reference would cascade into\n // CopilotChat's connectAgent effect, causing unnecessary HTTP calls.\n const provisionalAgentCache = useRef<Map<string, ProxiedCopilotRuntimeAgent>>(\n new Map(),\n );\n\n const agent: AbstractAgent = useMemo(() => {\n // Use a composite key when threadId is provided so that different threads\n // for the same agent get independent instances.\n const cacheKey = threadId ? `${agentId}:${threadId}` : agentId;\n\n const existing = copilotkit.getAgent(agentId);\n if (existing) {\n // Real agent found — clear any cached provisionals for this key and the\n // bare agentId key (handles the case where a provisional was created\n // before threadId was available, then the component re-renders with one).\n provisionalAgentCache.current.delete(cacheKey);\n provisionalAgentCache.current.delete(agentId);\n\n if (!threadId) {\n // No threadId — return the shared registry agent (original behavior)\n return existing;\n }\n\n // threadId provided — return the shared per-thread clone.\n // The global WeakMap ensures all components using the same\n // (registryAgent, threadId) pair receive the same instance, so state\n // mutations (addMessage, setState) are visible everywhere. The WeakMap\n // entry is GC-collected automatically when the registry agent is replaced.\n return getOrCreateThreadClone(existing, threadId, copilotkit.headers);\n }\n\n const isRuntimeConfigured = copilotkit.runtimeUrl !== undefined;\n const status = copilotkit.runtimeConnectionStatus;\n\n // While runtime is not yet synced, return a provisional runtime agent\n if (\n isRuntimeConfigured &&\n (status === CopilotKitCoreRuntimeConnectionStatus.Disconnected ||\n status === CopilotKitCoreRuntimeConnectionStatus.Connecting)\n ) {\n // Return cached provisional if available (keeps reference stable)\n const cached = provisionalAgentCache.current.get(cacheKey);\n if (cached) {\n // Update headers on the cached agent in case they changed\n cached.headers = { ...copilotkit.headers };\n return cached;\n }\n\n const provisional = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: copilotkit.runtimeUrl,\n agentId,\n transport: copilotkit.runtimeTransport,\n runtimeMode: \"pending\",\n });\n // Apply current headers so runs/connects inherit them\n provisional.headers = { ...copilotkit.headers };\n if (threadId) {\n provisional.threadId = threadId;\n }\n provisionalAgentCache.current.set(cacheKey, provisional);\n return provisional;\n }\n\n // Runtime is in Error state — return a provisional agent instead of throwing.\n // The error has already been emitted through the subscriber system\n // (RUNTIME_INFO_FETCH_FAILED). Throwing here would crash the React tree;\n // returning a provisional agent lets onError handlers fire while keeping\n // the app alive.\n if (\n isRuntimeConfigured &&\n status === CopilotKitCoreRuntimeConnectionStatus.Error\n ) {\n // Cache the provisional so that dep changes while in Error state (e.g.\n // headers update) return the same agent reference, matching the\n // Disconnected/Connecting path and preventing spurious re-subscriptions.\n const cached = provisionalAgentCache.current.get(cacheKey);\n if (cached) {\n cached.headers = { ...copilotkit.headers };\n return cached;\n }\n const provisional = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: copilotkit.runtimeUrl,\n agentId,\n transport: copilotkit.runtimeTransport,\n runtimeMode: \"pending\",\n });\n provisional.headers = { ...copilotkit.headers };\n if (threadId) {\n provisional.threadId = threadId;\n }\n provisionalAgentCache.current.set(cacheKey, provisional);\n return provisional;\n }\n\n // No runtime configured and agent doesn't exist — this is a configuration error.\n const knownAgents = Object.keys(copilotkit.agents ?? {});\n const runtimePart = isRuntimeConfigured\n ? `runtimeUrl=${copilotkit.runtimeUrl}`\n : \"no runtimeUrl\";\n throw new Error(\n `useAgent: Agent '${agentId}' not found after runtime sync (${runtimePart}). ` +\n (knownAgents.length\n ? `Known agents: [${knownAgents.join(\", \")}]`\n : \"No agents registered.\") +\n \" Verify your runtime /info and/or agents__unsafe_dev_only.\",\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n agentId,\n threadId,\n copilotkit.agents,\n copilotkit.runtimeConnectionStatus,\n copilotkit.runtimeUrl,\n copilotkit.runtimeTransport,\n JSON.stringify(copilotkit.headers),\n ]);\n\n useEffect(() => {\n if (updateFlags.length === 0) {\n return;\n }\n\n const handlers: Parameters<AbstractAgent[\"subscribe\"]>[0] = {};\n\n if (updateFlags.includes(UseAgentUpdate.OnMessagesChanged)) {\n // Content stripping for immutableContent renderers is handled by CopilotKitCoreReact\n handlers.onMessagesChanged = () => {\n forceUpdate();\n };\n }\n\n if (updateFlags.includes(UseAgentUpdate.OnStateChanged)) {\n handlers.onStateChanged = forceUpdate;\n }\n\n if (updateFlags.includes(UseAgentUpdate.OnRunStatusChanged)) {\n handlers.onRunInitialized = forceUpdate;\n handlers.onRunFinalized = forceUpdate;\n handlers.onRunFailed = forceUpdate;\n }\n\n const subscription = agent.subscribe(handlers);\n return () => subscription.unsubscribe();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agent, forceUpdate, JSON.stringify(updateFlags)]);\n\n // Keep HttpAgent headers fresh without mutating inside useMemo, which is\n // unsafe in concurrent mode (React may invoke useMemo multiple times and\n // discard intermediate results, but mutations always land).\n useEffect(() => {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...copilotkit.headers };\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agent, JSON.stringify(copilotkit.headers)]);\n\n return {\n agent,\n };\n}\n","import { useCopilotChatConfiguration, useCopilotKit } from \"../providers\";\nimport { getThreadClone } from \"./use-agent\";\nimport { ReactCustomMessageRendererPosition } from \"../types/react-custom-message-renderer\";\nimport { Message } from \"@ag-ui/core\";\n\ninterface UseRenderCustomMessagesParams {\n message: Message;\n position: ReactCustomMessageRendererPosition;\n}\n\nexport function useRenderCustomMessages() {\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n\n if (!config) {\n return null;\n }\n\n const { agentId, threadId } = config;\n\n const customMessageRenderers = copilotkit.renderCustomMessages\n .filter(\n (renderer) =>\n renderer.agentId === undefined || renderer.agentId === agentId,\n )\n .sort((a, b) => {\n const aHasAgent = a.agentId !== undefined;\n const bHasAgent = b.agentId !== undefined;\n if (aHasAgent === bHasAgent) return 0;\n return aHasAgent ? -1 : 1;\n });\n\n return function (params: UseRenderCustomMessagesParams) {\n if (!customMessageRenderers.length) {\n return null;\n }\n const { message, position } = params;\n const resolvedRunId =\n copilotkit.getRunIdForMessage(agentId, threadId, message.id) ??\n copilotkit.getRunIdsForThread(agentId, threadId).slice(-1)[0];\n const runId = resolvedRunId ?? `missing-run-id:${message.id}`;\n // Prefer the per-thread clone so that agent.messages reflects the actual\n // conversation state (messages live on the clone, not the registry agent).\n // Fall back to the registry agent when no clone exists (no threadId).\n const registryAgent = copilotkit.getAgent(agentId);\n const agent = getThreadClone(registryAgent, threadId) ?? registryAgent;\n if (!agent) {\n throw new Error(\"Agent not found\");\n }\n\n const messagesIdsInRun = resolvedRunId\n ? agent.messages\n .filter(\n (msg) =>\n copilotkit.getRunIdForMessage(agentId, threadId, msg.id) ===\n resolvedRunId,\n )\n .map((msg) => msg.id)\n : [message.id];\n\n const rawMessageIndex = agent.messages.findIndex(\n (msg) => msg.id === message.id,\n );\n const messageIndex = rawMessageIndex >= 0 ? rawMessageIndex : 0;\n const messageIndexInRun = resolvedRunId\n ? Math.max(messagesIdsInRun.indexOf(message.id), 0)\n : 0;\n const numberOfMessagesInRun = resolvedRunId ? messagesIdsInRun.length : 1;\n const stateSnapshot = resolvedRunId\n ? copilotkit.getStateByRun(agentId, threadId, resolvedRunId)\n : undefined;\n\n let result = null;\n for (const renderer of customMessageRenderers) {\n if (!renderer.render) {\n continue;\n }\n const Component = renderer.render;\n result = (\n <Component\n key={`${runId}-${message.id}-${position}`}\n message={message}\n position={position}\n runId={runId}\n messageIndex={messageIndex}\n messageIndexInRun={messageIndexInRun}\n numberOfMessagesInRun={numberOfMessagesInRun}\n agentId={agentId}\n stateSnapshot={stateSnapshot}\n />\n );\n if (result) {\n break;\n }\n }\n return result;\n };\n}\n","import { useEffect } from \"react\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\n\nconst EMPTY_DEPS: ReadonlyArray<unknown> = [];\n\nexport function useFrontendTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactFrontendTool<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n const extraDeps = deps ?? EMPTY_DEPS;\n\n useEffect(() => {\n const name = tool.name;\n\n // Always register/override the tool for this name on mount\n if (copilotkit.getTool({ toolName: name, agentId: tool.agentId })) {\n console.warn(\n `Tool '${name}' already exists for agent '${tool.agentId || \"global\"}'. Overriding with latest registration.`,\n );\n copilotkit.removeTool(name, tool.agentId);\n }\n copilotkit.addTool(tool);\n\n // Register/override renderer by name and agentId through core\n if (tool.render && tool.parameters) {\n copilotkit.addHookRenderToolCall({\n name,\n args: tool.parameters,\n agentId: tool.agentId,\n render: tool.render,\n });\n }\n\n return () => {\n copilotkit.removeTool(name, tool.agentId);\n // we are intentionally not removing the render here so that the tools can still render in the chat history\n };\n // Depend on stable keys by default and allow callers to opt into\n // additional dependencies for dynamic tool configuration.\n // tool.available is included so toggling availability re-registers the tool.\n }, [tool.name, tool.available, copilotkit, extraDeps.length, ...extraDeps]);\n}\n","import React from \"react\";\nimport { z } from \"zod\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { ReactToolCallRenderer } from \"./react-tool-call-renderer\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\n\n/**\n * Helper to define a type-safe tool call renderer entry.\n * - Accepts a single object whose keys match ReactToolCallRenderer's fields: { name, args, render, agentId? }.\n * - Derives `args` type from the provided schema (any Standard Schema V1 compatible library).\n * - Ensures the render function param type exactly matches ReactToolCallRenderer<T>[\"render\"]'s param.\n * - For wildcard tools (name: \"*\"), args is optional and defaults to z.any()\n */\ntype RenderProps<T> =\n | {\n name: string;\n args: Partial<T>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n }\n | {\n name: string;\n args: T;\n status: ToolCallStatus.Executing;\n result: undefined;\n }\n | {\n name: string;\n args: T;\n status: ToolCallStatus.Complete;\n result: string;\n };\n\n// Overload for wildcard tools without args\nexport function defineToolCallRenderer(def: {\n name: \"*\";\n render: (props: RenderProps<any>) => React.ReactElement;\n agentId?: string;\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: (props: RenderProps<InferSchemaOutput<S>>) => React.ReactElement;\n agentId?: string;\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;\n agentId?: string;\n}): ReactToolCallRenderer<any> {\n // For wildcard tools, default to z.any() if no args provided\n const argsSchema = def.name === \"*\" && !def.args ? z.any() : def.args;\n\n return {\n name: def.name,\n args: argsSchema,\n render: def.render as React.ComponentType<any>,\n ...(def.agentId ? { agentId: def.agentId } : {}),\n };\n}\n","import { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\nimport { useCallback, useEffect, useRef } from \"react\";\nimport React from \"react\";\nimport { useFrontendTool } from \"./use-frontend-tool\";\n\nexport function useHumanInTheLoop<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactHumanInTheLoop<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n const resolvePromiseRef = useRef<((result: unknown) => void) | null>(null);\n\n const respond = useCallback(async (result: unknown) => {\n if (resolvePromiseRef.current) {\n resolvePromiseRef.current(result);\n resolvePromiseRef.current = null;\n }\n }, []);\n\n const handler = useCallback(async () => {\n return new Promise((resolve) => {\n resolvePromiseRef.current = resolve;\n });\n }, []);\n\n const RenderComponent: ReactToolCallRenderer<T>[\"render\"] = useCallback(\n (props) => {\n const ToolComponent = tool.render;\n\n // Enhance props based on current status\n if (props.status === \"inProgress\") {\n const enhancedProps = {\n ...props,\n name: tool.name,\n description: tool.description || \"\",\n respond: undefined,\n };\n return React.createElement(ToolComponent, enhancedProps);\n } else if (props.status === \"executing\") {\n const enhancedProps = {\n ...props,\n name: tool.name,\n description: tool.description || \"\",\n respond,\n };\n return React.createElement(ToolComponent, enhancedProps);\n } else if (props.status === \"complete\") {\n const enhancedProps = {\n ...props,\n name: tool.name,\n description: tool.description || \"\",\n respond: undefined,\n };\n return React.createElement(ToolComponent, enhancedProps);\n }\n\n // Fallback - just render with original props\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return React.createElement(ToolComponent, props as any);\n },\n [tool.render, tool.name, tool.description, respond],\n );\n\n const frontendTool: ReactFrontendTool<T> = {\n ...tool,\n handler,\n render: RenderComponent,\n };\n\n useFrontendTool(frontendTool, deps);\n\n // Human-in-the-loop tools should remove their renderer on unmount\n // since they can't respond to user interactions anymore\n useEffect(() => {\n return () => {\n copilotkit.removeHookRenderToolCall(tool.name, tool.agentId);\n };\n }, [copilotkit, tool.name, tool.agentId]);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { Suggestion } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\n\nexport interface UseSuggestionsOptions {\n agentId?: string;\n}\n\nexport interface UseSuggestionsResult {\n suggestions: Suggestion[];\n reloadSuggestions: () => void;\n clearSuggestions: () => void;\n isLoading: boolean;\n}\n\nexport function useSuggestions({\n agentId,\n}: UseSuggestionsOptions = {}): UseSuggestionsResult {\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const resolvedAgentId = useMemo(\n () => agentId ?? config?.agentId ?? DEFAULT_AGENT_ID,\n [agentId, config?.agentId],\n );\n\n const [suggestions, setSuggestions] = useState<Suggestion[]>(() => {\n const result = copilotkit.getSuggestions(resolvedAgentId);\n return result.suggestions;\n });\n const [isLoading, setIsLoading] = useState(() => {\n const result = copilotkit.getSuggestions(resolvedAgentId);\n return result.isLoading;\n });\n\n useEffect(() => {\n const result = copilotkit.getSuggestions(resolvedAgentId);\n setSuggestions(result.suggestions);\n setIsLoading(result.isLoading);\n }, [copilotkit, resolvedAgentId]);\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onSuggestionsChanged: ({ agentId: changedAgentId, suggestions }) => {\n if (changedAgentId !== resolvedAgentId) {\n return;\n }\n setSuggestions(suggestions);\n },\n onSuggestionsStartedLoading: ({ agentId: changedAgentId }) => {\n if (changedAgentId !== resolvedAgentId) {\n return;\n }\n setIsLoading(true);\n },\n onSuggestionsFinishedLoading: ({ agentId: changedAgentId }) => {\n if (changedAgentId !== resolvedAgentId) {\n return;\n }\n setIsLoading(false);\n },\n onSuggestionsConfigChanged: () => {\n const result = copilotkit.getSuggestions(resolvedAgentId);\n setSuggestions(result.suggestions);\n setIsLoading(result.isLoading);\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit, resolvedAgentId]);\n\n const reloadSuggestions = useCallback(() => {\n copilotkit.reloadSuggestions(resolvedAgentId);\n // Loading state is handled by onSuggestionsStartedLoading event\n }, [copilotkit, resolvedAgentId]);\n\n const clearSuggestions = useCallback(() => {\n copilotkit.clearSuggestions(resolvedAgentId);\n // State updates are handled by onSuggestionsChanged event\n }, [copilotkit, resolvedAgentId]);\n\n return {\n suggestions,\n reloadSuggestions,\n clearSuggestions,\n isLoading,\n };\n}\n","import { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\nimport {\n DynamicSuggestionsConfig,\n StaticSuggestionsConfig,\n SuggestionsConfig,\n Suggestion,\n} from \"@copilotkit/core\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> &\n Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<\n StaticSuggestionsConfig,\n \"suggestions\"\n> & {\n suggestions: StaticSuggestionInput[];\n};\n\ntype SuggestionsConfigInput =\n | DynamicSuggestionsConfig\n | StaticSuggestionsConfigInput;\n\nexport function useConfigureSuggestions(\n config: SuggestionsConfigInput | null | undefined,\n deps?: ReadonlyArray<unknown>,\n): void {\n const { copilotkit } = useCopilotKit();\n const chatConfig = useCopilotChatConfiguration();\n const extraDeps = deps ?? [];\n\n const resolvedConsumerAgentId = useMemo(\n () => chatConfig?.agentId ?? DEFAULT_AGENT_ID,\n [chatConfig?.agentId],\n );\n\n const rawConsumerAgentId = useMemo(\n () =>\n config ? (config as SuggestionsConfigInput).consumerAgentId : undefined,\n [config],\n );\n\n const normalizationCacheRef = useRef<{\n serialized: string | null;\n config: SuggestionsConfig | null;\n }>({\n serialized: null,\n config: null,\n });\n\n const { normalizedConfig, serializedConfig } = useMemo(() => {\n if (!config) {\n normalizationCacheRef.current = { serialized: null, config: null };\n return { normalizedConfig: null, serializedConfig: null };\n }\n\n if (config.available === \"disabled\") {\n normalizationCacheRef.current = { serialized: null, config: null };\n return { normalizedConfig: null, serializedConfig: null };\n }\n\n let built: SuggestionsConfig;\n if (isDynamicConfig(config)) {\n built = {\n ...config,\n } satisfies DynamicSuggestionsConfig;\n } else {\n const normalizedSuggestions = normalizeStaticSuggestions(\n config.suggestions,\n );\n const baseConfig: StaticSuggestionsConfig = {\n ...config,\n suggestions: normalizedSuggestions,\n };\n built = baseConfig;\n }\n\n const serialized = JSON.stringify(built);\n const cache = normalizationCacheRef.current;\n if (cache.serialized === serialized && cache.config) {\n return { normalizedConfig: cache.config, serializedConfig: serialized };\n }\n\n normalizationCacheRef.current = { serialized, config: built };\n return { normalizedConfig: built, serializedConfig: serialized };\n }, [config, resolvedConsumerAgentId, ...extraDeps]);\n const latestConfigRef = useRef<SuggestionsConfig | null>(null);\n latestConfigRef.current = normalizedConfig;\n const previousSerializedConfigRef = useRef<string | null>(null);\n\n const targetAgentId = useMemo(() => {\n if (!normalizedConfig) {\n return resolvedConsumerAgentId;\n }\n const consumer = (\n normalizedConfig as StaticSuggestionsConfig | DynamicSuggestionsConfig\n ).consumerAgentId;\n if (!consumer || consumer === \"*\") {\n return resolvedConsumerAgentId;\n }\n return consumer;\n }, [normalizedConfig, resolvedConsumerAgentId]);\n\n const isGlobalConfig =\n rawConsumerAgentId === undefined || rawConsumerAgentId === \"*\";\n\n const requestReload = useCallback(() => {\n if (!normalizedConfig) {\n return;\n }\n\n if (isGlobalConfig) {\n const agents = Object.values(copilotkit.agents ?? {});\n for (const entry of agents) {\n const agentId = entry.agentId;\n if (!agentId) {\n continue;\n }\n if (!entry.isRunning) {\n copilotkit.reloadSuggestions(agentId);\n }\n }\n return;\n }\n\n if (!targetAgentId) {\n return;\n }\n\n copilotkit.reloadSuggestions(targetAgentId);\n }, [copilotkit, isGlobalConfig, normalizedConfig, targetAgentId]);\n\n useEffect(() => {\n if (!serializedConfig || !latestConfigRef.current) {\n return;\n }\n\n const id = copilotkit.addSuggestionsConfig(latestConfigRef.current);\n\n requestReload();\n\n return () => {\n copilotkit.removeSuggestionsConfig(id);\n };\n }, [copilotkit, serializedConfig, requestReload]);\n\n useEffect(() => {\n if (!normalizedConfig) {\n previousSerializedConfigRef.current = null;\n return;\n }\n if (\n serializedConfig &&\n previousSerializedConfigRef.current === serializedConfig\n ) {\n return;\n }\n if (serializedConfig) {\n previousSerializedConfigRef.current = serializedConfig;\n }\n requestReload();\n }, [normalizedConfig, requestReload, serializedConfig]);\n\n useEffect(() => {\n if (!normalizedConfig || extraDeps.length === 0) {\n return;\n }\n requestReload();\n }, [extraDeps.length, normalizedConfig, requestReload, ...extraDeps]);\n}\n\nfunction isDynamicConfig(\n config: SuggestionsConfigInput,\n): config is DynamicSuggestionsConfig {\n return \"instructions\" in config;\n}\n\nfunction normalizeStaticSuggestions(\n suggestions: StaticSuggestionInput[],\n): Suggestion[] {\n return suggestions.map((suggestion) => ({\n ...suggestion,\n isLoading: suggestion.isLoading ?? false,\n }));\n}\n","import React, {\n useState,\n useEffect,\n useCallback,\n useMemo,\n useRef,\n} from \"react\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useAgent } from \"./use-agent\";\nimport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n} from \"../types/interrupt\";\n\nexport type { InterruptEvent, InterruptRenderProps, InterruptHandlerProps };\n\nconst INTERRUPT_EVENT_NAME = \"on_interrupt\";\n\ntype InterruptHandlerFn<TValue, TResult> = (\n props: InterruptHandlerProps<TValue>,\n) => TResult | PromiseLike<TResult>;\n\ntype InterruptResultFromHandler<THandler> = THandler extends (\n ...args: never[]\n) => infer TResult\n ? TResult extends PromiseLike<infer TResolved>\n ? TResolved | null\n : TResult | null\n : null;\n\ntype InterruptResult<TValue, TResult> = InterruptResultFromHandler<\n InterruptHandlerFn<TValue, TResult>\n>;\n\ntype InterruptRenderInChat = boolean | undefined;\n\ntype UseInterruptReturn<TRenderInChat extends InterruptRenderInChat> =\n TRenderInChat extends false\n ? React.ReactElement | null\n : TRenderInChat extends true | undefined\n ? void\n : React.ReactElement | null | void;\n\nexport function isPromiseLike<TValue>(\n value: TValue | PromiseLike<TValue>,\n): value is PromiseLike<TValue> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") &&\n value !== null &&\n typeof Reflect.get(value, \"then\") === \"function\"\n );\n}\n\n/**\n * Configuration options for `useInterrupt`.\n */\ninterface UseInterruptConfigBase<TValue = unknown, TResult = never> {\n /**\n * Render function for the interrupt UI.\n *\n * This is called once an interrupt is finalized and accepted by `enabled` (if provided).\n * Use `resolve` from render props to resume the agent run with user input.\n */\n render: (\n props: InterruptRenderProps<TValue, InterruptResult<TValue, TResult>>,\n ) => React.ReactElement;\n /**\n * Optional pre-render handler invoked when an interrupt is received.\n *\n * Return either a sync value or an async value to pass into `render` as `result`.\n * Rejecting/throwing falls back to `result = null`.\n */\n handler?: InterruptHandlerFn<TValue, TResult>;\n /**\n * Optional predicate to filter which interrupts should be handled by this hook.\n * Return `false` to ignore an interrupt.\n */\n enabled?: (event: InterruptEvent<TValue>) => boolean;\n /** Optional agent id. Defaults to the current configured chat agent. */\n agentId?: string;\n}\n\nexport interface UseInterruptInChatConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. Set to false to render it yourself. */\n renderInChat?: true;\n}\n\nexport interface UseInterruptExternalConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. Set to false to render it yourself. */\n renderInChat: false;\n}\n\nexport interface UseInterruptDynamicConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** Dynamic boolean mode. When non-literal, return type is a union. */\n renderInChat: boolean;\n}\n\nexport type UseInterruptConfig<\n TValue = unknown,\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n> = UseInterruptConfigBase<TValue, TResult> & {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. Set to false to render it yourself. */\n renderInChat?: TRenderInChat;\n};\n\n/**\n * Handles agent interrupts (`on_interrupt`) with optional filtering, preprocessing, and resume behavior.\n *\n * The hook listens to custom events on the active agent, stores interrupt payloads per run,\n * and surfaces a render callback once the run finalizes. Call `resolve` from your UI to resume\n * execution with user-provided data.\n *\n * - `renderInChat: true` (default): the element is published into `<CopilotChat>` and this hook returns `void`.\n * - `renderInChat: false`: the hook returns the interrupt element so you can place it anywhere in your component tree.\n *\n * `event.value` is typed as `any` since the interrupt payload shape depends on your agent.\n * Type-narrow it in your callbacks (e.g. `handler`, `enabled`, `render`) as needed.\n *\n * @typeParam TResult - Inferred from `handler` return type. Exposed as `result` in `render`.\n * @param config - Interrupt configuration (renderer, optional handler/filter, and render mode).\n * @returns When `renderInChat` is `false`, returns the interrupt element (or `null` when idle).\n * Otherwise returns `void` and publishes the element into chat. In `render`, `result` is always\n * either the handler's resolved return value or `null` (including when no handler is provided,\n * when filtering skips the interrupt, or when handler execution fails).\n *\n * @example\n * ```tsx\n * import { useInterrupt } from \"@copilotkit/react-core/v2\";\n *\n * function InterruptUI() {\n * useInterrupt({\n * render: ({ event, resolve }) => (\n * <div>\n * <p>{event.value.question}</p>\n * <button onClick={() => resolve({ approved: true })}>Approve</button>\n * <button onClick={() => resolve({ approved: false })}>Reject</button>\n * </div>\n * ),\n * });\n *\n * return null;\n * }\n * ```\n *\n * @example\n * ```tsx\n * import { useInterrupt } from \"@copilotkit/react-core/v2\";\n *\n * function CustomPanel() {\n * const interruptElement = useInterrupt({\n * renderInChat: false,\n * enabled: (event) => event.value.startsWith(\"approval:\"),\n * handler: async ({ event }) => ({ label: event.value.toUpperCase() }),\n * render: ({ event, result, resolve }) => (\n * <aside>\n * <strong>{result?.label ?? \"\"}</strong>\n * <button onClick={() => resolve({ value: event.value })}>Continue</button>\n * </aside>\n * ),\n * });\n *\n * return <>{interruptElement}</>;\n * }\n * ```\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport function useInterrupt<\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n>(\n config: UseInterruptConfig<any, TResult, TRenderInChat>,\n): UseInterruptReturn<TRenderInChat> {\n /* eslint-enable @typescript-eslint/no-explicit-any */\n const { copilotkit } = useCopilotKit();\n const { agent } = useAgent({ agentId: config.agentId });\n const [pendingEvent, setPendingEvent] = useState<InterruptEvent | null>(null);\n const pendingEventRef = useRef(pendingEvent);\n pendingEventRef.current = pendingEvent;\n const [handlerResult, setHandlerResult] =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n useState<InterruptResult<any, TResult>>(null);\n\n useEffect(() => {\n let localInterrupt: InterruptEvent | null = null;\n\n const subscription = agent.subscribe({\n onCustomEvent: ({ event }) => {\n if (event.name === INTERRUPT_EVENT_NAME) {\n localInterrupt = { name: event.name, value: event.value };\n }\n },\n onRunStartedEvent: () => {\n localInterrupt = null;\n setPendingEvent(null);\n },\n onRunFinalized: () => {\n if (localInterrupt) {\n setPendingEvent(localInterrupt);\n localInterrupt = null;\n }\n },\n onRunFailed: () => {\n localInterrupt = null;\n },\n });\n\n return () => subscription.unsubscribe();\n }, [agent]);\n\n const resolve = useCallback(\n (response: unknown) => {\n setPendingEvent(null);\n copilotkit.runAgent({\n agent,\n forwardedProps: {\n command: {\n resume: response,\n interruptEvent: pendingEventRef.current?.value,\n },\n },\n });\n },\n [agent, copilotkit],\n );\n\n useEffect(() => {\n // No interrupt to process — reset any stale handler result from a previous interrupt\n if (!pendingEvent) {\n setHandlerResult(null);\n return;\n }\n // Interrupt exists but the consumer's filter rejects it — treat as no-op\n if (config.enabled && !config.enabled(pendingEvent)) {\n setHandlerResult(null);\n return;\n }\n const handler = config.handler;\n // No handler provided — skip straight to rendering with a null result\n if (!handler) {\n setHandlerResult(null);\n return;\n }\n\n let cancelled = false;\n const maybePromise = handler({\n event: pendingEvent,\n resolve,\n });\n\n // If the handler returns a promise/thenable, wait for resolution before setting result.\n if (isPromiseLike(maybePromise)) {\n Promise.resolve(maybePromise)\n .then((resolved) => {\n if (!cancelled) setHandlerResult(resolved);\n })\n .catch(() => {\n if (!cancelled) setHandlerResult(null);\n });\n } else {\n setHandlerResult(maybePromise);\n }\n\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pendingEvent, config.enabled, config.handler, resolve]);\n\n const element = useMemo(() => {\n if (!pendingEvent) return null;\n if (config.enabled && !config.enabled(pendingEvent)) return null;\n\n return config.render({\n event: pendingEvent,\n result: handlerResult,\n resolve,\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pendingEvent, handlerResult, config.enabled, config.render, resolve]);\n\n // Publish to core for in-chat rendering\n useEffect(() => {\n if (config.renderInChat === false) return;\n copilotkit.setInterruptElement(element);\n return () => copilotkit.setInterruptElement(null);\n }, [element, config.renderInChat, copilotkit]);\n\n // Only return element when rendering outside chat\n if (config.renderInChat === false) {\n return element as UseInterruptReturn<TRenderInChat>;\n }\n\n return undefined as UseInterruptReturn<TRenderInChat>;\n}\n","import {\n CopilotCloudConfig,\n FunctionCallHandler,\n CopilotErrorHandler,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport {\n CoAgentStateRender,\n CoAgentStateRenderProps,\n} from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetter,\n QueuedInterruptEvent,\n} from \"../types/interrupt-action\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Optional configuration for connecting to Model Context Protocol (MCP) servers.\n * This is typically derived from the CopilotKitProps and used internally.\n * @experimental\n */\n mcpServers?: Array<{ endpoint: string; apiKey?: string }>;\n}\n\nexport type InChatRenderFunction<\n TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>,\n> = (props: TProps) => string | React.JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | React.JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\nexport type ContextTree = Tree;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // registered actions for component-based rendering\n setRegisteredActions: (actionConfig: any) => string;\n removeRegisteredAction: (actionKey: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (\n context: string,\n parentId?: string,\n categories?: string[],\n ) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (\n documents: DocumentPointer[],\n categories: string[],\n ) => string;\n\n // document context\n addDocumentContext: (\n documentPointer: DocumentPointer,\n categories?: string[],\n ) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: {\n [key: string]: CopilotChatSuggestionConfiguration;\n };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n additionalInstructions?: string[];\n setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean;\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<\n React.SetStateAction<Record<string, CoagentState>>\n >;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Partial<Pick<ForwardedParametersInput, \"temperature\">>;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<\n React.SetStateAction<Record<ActionName, AuthState>>\n >;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n interruptActions: Record<string, LangGraphInterruptRender>;\n setInterruptAction: LangGraphInterruptActionSetter;\n removeInterruptAction: (actionId: string) => void;\n interruptEventQueue: Record<string, QueuedInterruptEvent[]>;\n addInterruptEvent: (queuedEvent: QueuedInterruptEvent) => void;\n resolveInterruptEvent: (\n threadId: string,\n eventId: string,\n response: string,\n ) => void;\n\n /**\n * Optional trace handler for comprehensive debugging and observability.\n */\n onError: CopilotErrorHandler;\n\n // banner error state\n bannerError: CopilotKitError | null;\n setBannerError: React.Dispatch<React.SetStateAction<CopilotKitError | null>>;\n // Internal error handlers\n // These are used to handle errors that occur during the execution of the chat.\n // They are not intended for use by the developer. A component can register itself an error listener to be activated somewhere else as needed\n internalErrorHandlers: Record<string, CopilotErrorHandler>;\n setInternalErrorHandler: (\n handler: Record<string, CopilotErrorHandler>,\n ) => void;\n removeInternalErrorHandler: (id: string) => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n setRegisteredActions: () => \"\",\n removeRegisteredAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n getAllContext: () => [],\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n additionalInstructions: [],\n setAdditionalInstructions: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\n \"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\",\n );\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: false,\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n interruptActions: {},\n setInterruptAction: () => {},\n removeInterruptAction: () => {},\n interruptEventQueue: {},\n addInterruptEvent: () => {},\n resolveInterruptEvent: () => {},\n onError: () => {},\n bannerError: null,\n setBannerError: () => {},\n internalErrorHandlers: {},\n setInternalErrorHandler: () => {},\n removeInternalErrorHandler: () => {},\n};\n\nexport const CopilotContext =\n React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\",\n );\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\n \"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\",\n );\n}\n","import { randomId } from \"@copilotkit/shared\";\nimport { useCallback, useReducer } from \"react\";\n\nexport type TreeNodeId = string;\n\nexport interface TreeNode {\n id: TreeNodeId;\n value: string;\n children: TreeNode[];\n parentId?: TreeNodeId;\n categories: Set<string>;\n}\n\nexport type Tree = TreeNode[];\n\nexport interface UseTreeReturn {\n tree: Tree;\n addElement: (\n value: string,\n categories: string[],\n parentId?: TreeNodeId,\n ) => TreeNodeId;\n printTree: (categories: string[]) => string;\n removeElement: (id: TreeNodeId) => void;\n getAllElements: () => Tree;\n}\n\nconst findNode = (nodes: Tree, id: TreeNodeId): TreeNode | undefined => {\n for (const node of nodes) {\n if (node.id === id) {\n return node;\n }\n const result = findNode(node.children, id);\n if (result) {\n return result;\n }\n }\n return undefined;\n};\n\nconst removeNode = (nodes: Tree, id: TreeNodeId): Tree => {\n return nodes.reduce((result: Tree, node) => {\n if (node.id !== id) {\n const newNode = { ...node, children: removeNode(node.children, id) };\n result.push(newNode);\n }\n return result;\n }, []);\n};\n\nconst addNode = (\n nodes: Tree,\n newNode: TreeNode,\n parentId?: TreeNodeId,\n): Tree => {\n if (!parentId) {\n return [...nodes, newNode];\n }\n return nodes.map((node) => {\n if (node.id === parentId) {\n return { ...node, children: [...node.children, newNode] };\n } else if (node.children.length) {\n return { ...node, children: addNode(node.children, newNode, parentId) };\n }\n return node;\n });\n};\n\nconst treeIndentationRepresentation = (\n index: number,\n indentLevel: number,\n): string => {\n if (indentLevel === 0) {\n return (index + 1).toString();\n } else if (indentLevel === 1) {\n return String.fromCharCode(65 + index); // 65 is the ASCII value for 'A'\n } else if (indentLevel === 2) {\n return String.fromCharCode(97 + index); // 97 is the ASCII value for 'a'\n } else {\n return \"-\";\n }\n};\n\nconst printNode = (node: TreeNode, prefix = \"\", indentLevel = 0): string => {\n const indent = \" \".repeat(3).repeat(indentLevel);\n\n const prefixPlusIndentLength = prefix.length + indent.length;\n const subsequentLinesPrefix = \" \".repeat(prefixPlusIndentLength);\n\n const valueLines = node.value.split(\"\\n\");\n\n const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;\n const outputSubsequentLines = valueLines\n .slice(1)\n .map((line) => `${subsequentLinesPrefix}${line}`)\n .join(\"\\n\");\n\n let output = `${outputFirstLine}\\n`;\n if (outputSubsequentLines) {\n output += `${outputSubsequentLines}\\n`;\n }\n\n const childPrePrefix = \" \".repeat(prefix.length);\n\n node.children.forEach(\n (child, index) =>\n (output += printNode(\n child,\n `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `,\n indentLevel + 1,\n )),\n );\n return output;\n};\n\n// Action types\ntype Action =\n | {\n type: \"ADD_NODE\";\n value: string;\n parentId?: string;\n id: string;\n categories: string[];\n }\n | { type: \"REMOVE_NODE\"; id: string };\n\n// Reducer function\nfunction treeReducer(state: Tree, action: Action): Tree {\n switch (action.type) {\n case \"ADD_NODE\": {\n const { value, parentId, id: newNodeId } = action;\n const newNode: TreeNode = {\n id: newNodeId,\n value,\n children: [],\n categories: new Set(action.categories),\n };\n\n try {\n return addNode(state, newNode, parentId);\n } catch (error) {\n console.error(`Error while adding node with id ${newNodeId}: ${error}`);\n return state;\n }\n }\n case \"REMOVE_NODE\":\n return removeNode(state, action.id);\n default:\n return state;\n }\n}\n\n// useTree hook\nconst useTree = (): UseTreeReturn => {\n const [tree, dispatch] = useReducer(treeReducer, []);\n\n const addElement = useCallback(\n (value: string, categories: string[], parentId?: string): TreeNodeId => {\n const newNodeId = randomId(); // Generate new ID outside of dispatch\n dispatch({\n type: \"ADD_NODE\",\n value,\n parentId,\n id: newNodeId,\n categories: categories,\n });\n return newNodeId; // Return the new ID\n },\n [],\n );\n\n const removeElement = useCallback((id: TreeNodeId): void => {\n dispatch({ type: \"REMOVE_NODE\", id });\n }, []);\n\n const getAllElements = useCallback(() => {\n return tree;\n }, [tree]);\n\n const printTree = useCallback(\n (categories: string[]): string => {\n const categoriesSet = new Set(categories);\n\n let output = \"\";\n tree.forEach((node, index) => {\n // if the node does not have any of the desired categories, continue to the next node\n if (!setsHaveIntersection(categoriesSet, node.categories)) {\n return;\n }\n\n // add a new line before each node except the first one\n if (index !== 0) {\n output += \"\\n\";\n }\n\n output += printNode(\n node,\n `${treeIndentationRepresentation(index, 0)}. `,\n );\n });\n return output;\n },\n [tree],\n );\n\n return { tree, addElement, printTree, removeElement, getAllElements };\n};\n\nexport default useTree;\n\nfunction setsHaveIntersection<T>(setA: Set<T>, setB: Set<T>): boolean {\n const [smallerSet, largerSet] =\n setA.size <= setB.size ? [setA, setB] : [setB, setA];\n\n for (let item of smallerSet) {\n if (largerSet.has(item)) {\n return true;\n }\n }\n\n return false;\n}\n","import { useCallback, useReducer } from \"react\";\nimport { randomId } from \"@copilotkit/shared\";\n\nexport type FlatCategoryStoreId = string;\n\nexport interface UseFlatCategoryStoreReturn<T> {\n addElement: (value: T, categories: string[]) => FlatCategoryStoreId;\n removeElement: (id: FlatCategoryStoreId) => void;\n allElements: (categories: string[]) => T[];\n}\n\ninterface FlatCategoryStoreElement<T> {\n id: FlatCategoryStoreId;\n value: T;\n categories: Set<string>;\n}\n\nconst useFlatCategoryStore = <T>(): UseFlatCategoryStoreReturn<T> => {\n const [elements, dispatch] = useReducer(\n flatCategoryStoreReducer<T>,\n new Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>(),\n );\n\n const addElement = useCallback(\n (value: T, categories: string[]): FlatCategoryStoreId => {\n const newId = randomId();\n dispatch({\n type: \"ADD_ELEMENT\",\n value,\n id: newId,\n categories,\n });\n return newId;\n },\n [],\n );\n\n const removeElement = useCallback((id: FlatCategoryStoreId): void => {\n dispatch({ type: \"REMOVE_ELEMENT\", id });\n }, []);\n\n const allElements = useCallback(\n (categories: string[]): T[] => {\n const categoriesSet = new Set(categories);\n const result: T[] = [];\n elements.forEach((element) => {\n if (setsHaveIntersection(categoriesSet, element.categories)) {\n result.push(element.value);\n }\n });\n return result;\n },\n [elements],\n );\n\n return { addElement, removeElement, allElements };\n};\n\nexport default useFlatCategoryStore;\n\n// Action types\ntype Action<T> =\n | {\n type: \"ADD_ELEMENT\";\n value: T;\n id: FlatCategoryStoreId;\n categories: string[];\n }\n | { type: \"REMOVE_ELEMENT\"; id: FlatCategoryStoreId };\n\n// Reducer\nfunction flatCategoryStoreReducer<T>(\n state: Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>,\n action: Action<T>,\n): Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>> {\n switch (action.type) {\n case \"ADD_ELEMENT\": {\n const { value, id, categories } = action;\n const newElement: FlatCategoryStoreElement<T> = {\n id,\n value,\n categories: new Set(categories),\n };\n const newState = new Map(state);\n newState.set(id, newElement);\n return newState;\n }\n case \"REMOVE_ELEMENT\": {\n const newState = new Map(state);\n newState.delete(action.id);\n return newState;\n }\n default:\n return state;\n }\n}\n\nfunction setsHaveIntersection<T>(setA: Set<T>, setB: Set<T>): boolean {\n const [smallerSet, largerSet] =\n setA.size <= setB.size ? [setA, setB] : [setB, setA];\n\n for (let item of smallerSet) {\n if (largerSet.has(item)) {\n return true;\n }\n }\n\n return false;\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport React from \"react\";\nimport { Suggestion } from \"@copilotkit/core\";\n\nexport interface CopilotMessagesContextParams {\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>; // suggestions state\n suggestions: Suggestion[];\n setSuggestions: React.Dispatch<React.SetStateAction<Suggestion[]>>;\n}\n\nconst emptyCopilotContext: CopilotMessagesContextParams = {\n messages: [],\n setMessages: () => [],\n // suggestions state\n suggestions: [],\n setSuggestions: () => [],\n};\n\nexport const CopilotMessagesContext =\n React.createContext<CopilotMessagesContextParams>(emptyCopilotContext);\n\nexport function useCopilotMessagesContext(): CopilotMessagesContextParams {\n const context = React.useContext(CopilotMessagesContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`\",\n );\n }\n return context;\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { PartialBy, CopilotKitError, Severity } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(\n null,\n );\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id))\n return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\n \"addGraphQLErrorsToast is deprecated. All errors now show as banners.\",\n );\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(\n /'message':\\s*'([^']+)'/,\n );\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() =>\n window.open(url, \"_blank\", \"noopener,noreferrer\")\n }\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform =\n \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n","function isLocalhost(): boolean {\n if (typeof window === \"undefined\") return false;\n\n return (\n window.location.hostname === \"localhost\" ||\n window.location.hostname === \"127.0.0.1\" ||\n window.location.hostname === \"0.0.0.0\"\n );\n}\n\nexport function shouldShowDevConsole(showDevConsole?: boolean): boolean {\n // If explicitly set, use that value\n if (showDevConsole !== undefined) {\n return showDevConsole;\n }\n\n // If not set, default to true on localhost\n return isLocalhost();\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport {\n ReactNode,\n useEffect,\n useState,\n useRef,\n useCallback,\n useMemo,\n createContext,\n useContext,\n} from \"react\";\nimport { CopilotMessagesContext } from \"../../context/copilot-messages-context\";\nimport {\n loadMessagesFromJsonRepresentation,\n Message,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useCopilotContext } from \"../../context/copilot-context\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { shouldShowDevConsole } from \"../../utils/dev-console\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n} from \"@copilotkit/shared\";\nimport { Suggestion } from \"@copilotkit/core\";\n\n// Helper to determine if error should show as banner based on visibility and legacy patterns\nfunction shouldShowAsBanner(gqlError: GraphQLError): boolean {\n const extensions = gqlError.extensions;\n if (!extensions) return false;\n\n // Priority 1: Check error code for discovery errors (these should always be banners)\n const code = extensions.code as CopilotKitErrorCode;\n if (\n code === CopilotKitErrorCode.AGENT_NOT_FOUND ||\n code === CopilotKitErrorCode.API_NOT_FOUND ||\n code === CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND ||\n code === CopilotKitErrorCode.CONFIGURATION_ERROR ||\n code === CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR ||\n code === CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR\n ) {\n return true;\n }\n\n // Priority 2: Check banner visibility\n if (extensions.visibility === ErrorVisibility.BANNER) {\n return true;\n }\n\n // Priority 3: Check for critical errors that should be banners regardless of formal classification\n const errorMessage = gqlError.message.toLowerCase();\n if (\n errorMessage.includes(\"api key\") ||\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"unauthorized\") ||\n errorMessage.includes(\"authentication\") ||\n errorMessage.includes(\"incorrect api key\")\n ) {\n return true;\n }\n\n // Priority 4: Legacy stack trace detection for discovery errors\n const originalError = extensions.originalError as any;\n if (originalError?.stack) {\n return (\n originalError.stack.includes(\"CopilotApiDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")\n );\n }\n\n return false;\n}\n\n/**\n * MessagesTap is used to mitigate performance issues when we only need\n * a snapshot of the messages, not a continuously updating stream of messages.\n */\n\nexport type MessagesTap = {\n getMessagesFromTap: () => Message[];\n updateTapMessages: (messages: Message[]) => void;\n};\n\nconst MessagesTapContext = createContext<MessagesTap | null>(null);\n\nexport function useMessagesTap() {\n const tap = useContext(MessagesTapContext);\n if (!tap)\n throw new Error(\"useMessagesTap must be used inside <MessagesTapProvider>\");\n return tap;\n}\n\nexport function MessagesTapProvider({\n children,\n}: {\n children: React.ReactNode;\n}) {\n const messagesRef = useRef<Message[]>([]);\n\n const tapRef = useRef<MessagesTap>({\n getMessagesFromTap: () => messagesRef.current,\n updateTapMessages: (messages: Message[]) => {\n messagesRef.current = messages;\n },\n });\n\n return (\n <MessagesTapContext.Provider value={tapRef.current}>\n {children}\n </MessagesTapContext.Provider>\n );\n}\n\n/**\n * CopilotKit messages context.\n */\n\nexport function CopilotMessages({ children }: { children: ReactNode }) {\n const [messages, setMessages] = useState<Message[]>([]);\n const lastLoadedThreadId = useRef<string>(undefined!);\n const lastLoadedAgentName = useRef<string>(undefined!);\n const lastLoadedMessages = useRef<string>(undefined!);\n\n const { updateTapMessages } = useMessagesTap();\n\n const { threadId, agentSession, showDevConsole, onError, copilotApiConfig } =\n useCopilotContext();\n const { setBannerError } = useToast();\n\n // Helper function to trace UI errors (similar to useCopilotRuntimeClient)\n const traceUIError = useCallback(\n async (error: CopilotKitError, originalError?: any) => {\n // Just check if onError and publicApiKey are defined\n if (!onError || !copilotApiConfig.publicApiKey) return;\n\n try {\n const traceEvent = {\n type: \"error\" as const,\n timestamp: Date.now(),\n context: {\n source: \"ui\" as const,\n request: {\n operation: \"loadAgentState\",\n url: copilotApiConfig.chatApiEndpoint,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent:\n typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : undefined,\n stackTrace:\n originalError instanceof Error\n ? originalError.stack\n : undefined,\n },\n },\n error,\n };\n await onError(traceEvent);\n } catch (traceError) {\n console.error(\"Error in CopilotMessages onError handler:\", traceError);\n }\n },\n [onError, copilotApiConfig.publicApiKey, copilotApiConfig.chatApiEndpoint],\n );\n\n const createStructuredError = (\n gqlError: GraphQLError,\n ): CopilotKitError | null => {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n\n // Priority: Check stack trace for discovery errors first\n if (originalError?.stack) {\n if (originalError.stack.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({\n message: originalError.message,\n });\n }\n if (\n originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\")\n ) {\n return new CopilotKitRemoteEndpointDiscoveryError({\n message: originalError.message,\n });\n }\n if (originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n }\n\n // Fallback: Use the formal error code if available\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n return null;\n };\n\n const handleGraphQLErrors = useCallback(\n (error: any) => {\n if (error.graphQLErrors?.length) {\n const graphQLErrors = error.graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole);\n\n if (!isDev) {\n console.error(\n \"CopilotKit Error (hidden in production):\",\n gqlError.message,\n );\n return;\n }\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // All other errors (including DEV_ONLY) show as banners for consistency\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the structured error\n traceUIError(ckError, gqlError);\n } else {\n // Fallback: create a generic error for unstructured GraphQL errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n }\n }\n },\n [setBannerError, showDevConsole, traceUIError],\n );\n\n useEffect(() => {\n updateTapMessages(messages);\n }, [messages, updateTapMessages]);\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [suggestions, setSuggestions] = useState<Suggestion[]>([]);\n\n return (\n <CopilotMessagesContext.Provider\n value={{\n messages,\n setMessages,\n suggestions,\n setSuggestions,\n }}\n >\n {memoizedChildren}\n </CopilotMessagesContext.Provider>\n );\n}\n","import {\n Severity,\n CopilotKitError,\n ErrorVisibility,\n CopilotKitErrorCode,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface UsageBannerProps {\n severity?: Severity;\n message?: string | React.ReactNode;\n onClose?: () => void;\n actions?: {\n primary?: {\n label: string;\n onClick: () => void;\n };\n secondary?: {\n label: string;\n onClick: () => void;\n };\n };\n}\n\nexport function UsageBanner({\n severity = Severity.CRITICAL,\n message = \"\",\n onClose,\n actions,\n}: UsageBannerProps) {\n if (!message || !severity) {\n return null;\n }\n\n const themes = {\n [Severity.INFO]: {\n bg: \"#f8fafc\",\n border: \"#e2e8f0\",\n text: \"#475569\",\n accent: \"#3b82f6\",\n },\n [Severity.WARNING]: {\n bg: \"#fffbeb\",\n border: \"#fbbf24\",\n text: \"#92400e\",\n accent: \"#f59e0b\",\n },\n [Severity.CRITICAL]: {\n bg: \"#fef2f2\",\n border: \"#fecaca\",\n text: \"#dc2626\",\n accent: \"#ef4444\",\n },\n };\n\n const theme = themes[severity];\n\n return (\n <>\n <style>\n {`\n @keyframes slideUp {\n from { opacity: 0; transform: translateX(-50%) translateY(8px); }\n to { opacity: 1; transform: translateX(-50%) translateY(0); }\n }\n \n .usage-banner {\n position: fixed;\n bottom: 24px;\n left: 50%;\n transform: translateX(-50%);\n width: min(600px, calc(100vw - 32px));\n z-index: 10000;\n animation: slideUp 0.2s cubic-bezier(0.16, 1, 0.3, 1);\n }\n \n .banner-content {\n background: linear-gradient(135deg, ${theme.bg} 0%, ${theme.bg}f5 100%);\n border: 1px solid ${theme.border};\n border-radius: 12px;\n padding: 18px 20px;\n box-shadow: \n 0 4px 24px rgba(0, 0, 0, 0.08),\n 0 2px 8px rgba(0, 0, 0, 0.04),\n inset 0 1px 0 rgba(255, 255, 255, 0.7);\n display: flex;\n align-items: center;\n gap: 16px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n backdrop-filter: blur(12px);\n position: relative;\n overflow: hidden;\n }\n \n .banner-content::before {\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n height: 1px;\n background: linear-gradient(90deg, transparent, ${theme.accent}40, transparent);\n }\n \n .banner-message {\n color: ${theme.text};\n font-size: 14px;\n line-height: 1.5;\n font-weight: 500;\n flex: 1;\n letter-spacing: -0.01em;\n }\n \n .close-btn {\n background: rgba(0, 0, 0, 0.05);\n border: none;\n color: ${theme.text};\n cursor: pointer;\n padding: 0;\n border-radius: 6px;\n opacity: 0.6;\n transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);\n font-size: 14px;\n line-height: 1;\n flex-shrink: 0;\n width: 24px;\n height: 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n \n .close-btn:hover {\n opacity: 1;\n background: rgba(0, 0, 0, 0.08);\n transform: scale(1.05);\n }\n \n .btn-primary {\n background: linear-gradient(135deg, ${theme.accent} 0%, ${theme.accent}e6 100%);\n color: white;\n border: none;\n border-radius: 8px;\n padding: 10px 18px;\n font-size: 13px;\n font-weight: 600;\n cursor: pointer;\n transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);\n font-family: inherit;\n flex-shrink: 0;\n box-shadow: \n 0 2px 8px ${theme.accent}30,\n inset 0 1px 0 rgba(255, 255, 255, 0.2);\n letter-spacing: -0.01em;\n }\n \n .btn-primary:hover {\n transform: translateY(-1px) scale(1.02);\n box-shadow: \n 0 4px 12px ${theme.accent}40,\n inset 0 1px 0 rgba(255, 255, 255, 0.25);\n }\n \n .btn-primary:active {\n transform: translateY(0) scale(0.98);\n transition: all 0.08s cubic-bezier(0.16, 1, 0.3, 1);\n }\n \n @media (max-width: 640px) {\n .usage-banner {\n width: calc(100vw - 24px);\n }\n \n .banner-content {\n padding: 16px;\n gap: 12px;\n }\n \n .banner-message {\n font-size: 13px;\n line-height: 1.45;\n }\n \n .btn-primary {\n padding: 8px 14px;\n font-size: 12px;\n }\n \n .close-btn {\n width: 22px;\n height: 22px;\n font-size: 12px;\n }\n }\n `}\n </style>\n\n <div className=\"usage-banner\">\n <div className=\"banner-content\">\n <div className=\"banner-message\">{message}</div>\n {actions?.primary && (\n <button className=\"btn-primary\" onClick={actions.primary.onClick}>\n {actions.primary.label}\n </button>\n )}\n {onClose && (\n <button className=\"close-btn\" onClick={onClose} title=\"Close\">\n ×\n </button>\n )}\n </div>\n </div>\n </>\n );\n}\n\n// Get action button based on error type\nexport const getErrorActions = (error: CopilotKitError) => {\n switch (error.code) {\n case CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR:\n return {\n primary: {\n label: \"Show me how\",\n onClick: () =>\n window.open(\n \"https://docs.copilotkit.ai/premium#how-do-i-get-access-to-premium-features\",\n \"_blank\",\n \"noopener,noreferrer\",\n ),\n },\n };\n case CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR:\n return {\n primary: {\n label: \"Upgrade\",\n onClick: () =>\n window.open(\n \"https://cloud.copilotkit.ai\",\n \"_blank\",\n \"noopener,noreferrer\",\n ),\n },\n };\n default:\n return undefined;\n }\n};\n\nexport function renderCopilotKitUsage(\n error: CopilotKitError,\n onClose?: () => void,\n) {\n // Route based on error visibility level\n if (error.visibility !== ErrorVisibility.BANNER) {\n return null;\n }\n\n return (\n <UsageBanner\n severity={error.severity || Severity.CRITICAL}\n message={error.message}\n onClose={onClose}\n actions={getErrorActions(error)}\n />\n );\n}\n","/**\n * Constants for suggestions retry logic\n */\n\nexport const SUGGESTION_RETRY_CONFIG = {\n MAX_RETRIES: 3,\n COOLDOWN_MS: 5000, // 5 seconds\n} as const;\n","import {\n COPILOT_CLOUD_API_URL,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n Severity,\n} from \"@copilotkit/shared\";\n\nconst STATUS_CHECK_INTERVAL = 1000 * 60 * 5; // 5 minutes\n\nexport type Status = {\n severity: Severity;\n message: string;\n};\n\nexport class StatusChecker {\n private activeKey: string | null = null;\n private intervalId: ReturnType<typeof setInterval> | null = null;\n private instanceCount = 0;\n private lastResponse: Status | null = null;\n\n async start(\n publicApiKey: string,\n onUpdate?: (status: Status | null) => void,\n ) {\n this.instanceCount++;\n if (this.activeKey === publicApiKey) return;\n\n if (this.intervalId) clearInterval(this.intervalId);\n\n const checkStatus = async () => {\n try {\n const response = await fetch(`${COPILOT_CLOUD_API_URL}/ciu`, {\n method: \"GET\",\n headers: {\n [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey,\n },\n }).then((response) => response.json() as Promise<Status>);\n this.lastResponse = response;\n onUpdate?.(response);\n return response;\n } catch (error) {\n // Silently fail\n return null;\n }\n };\n\n const initialResponse = await checkStatus();\n this.intervalId = setInterval(checkStatus, STATUS_CHECK_INTERVAL);\n this.activeKey = publicApiKey;\n return initialResponse;\n }\n\n getLastResponse() {\n return this.lastResponse;\n }\n\n stop() {\n this.instanceCount--;\n if (this.instanceCount === 0) {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = null;\n this.activeKey = null;\n this.lastResponse = null;\n }\n }\n }\n}\n","import React from \"react\";\n\nexport const ExclamationMarkIcon = ({\n className,\n style,\n}: {\n className?: string;\n style?: React.CSSProperties;\n}) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={`lucide lucide-circle-alert ${className ? className : \"\"}`}\n style={style}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"12\" x2=\"12\" y1=\"8\" y2=\"12\" />\n <line x1=\"12\" x2=\"12.01\" y1=\"16\" y2=\"16\" />\n </svg>\n);\n","import React, { useCallback } from \"react\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { ExclamationMarkIcon } from \"../toast/exclamation-mark-icon\";\nimport ReactMarkdown from \"react-markdown\";\n\ninterface OriginalError {\n message?: string;\n stack?: string;\n}\n\nexport function ErrorToast({ errors }: { errors: (Error | GraphQLError)[] }) {\n const errorsToRender = errors.map((error, idx) => {\n const originalError =\n \"extensions\" in error\n ? (error.extensions?.originalError as undefined | OriginalError)\n : {};\n const message = originalError?.message ?? error.message;\n const code =\n \"extensions\" in error ? (error.extensions?.code as string) : null;\n\n return (\n <div\n key={idx}\n style={{\n marginTop: idx === 0 ? 0 : 10,\n marginBottom: 14,\n }}\n >\n <ExclamationMarkIcon style={{ marginBottom: 4 }} />\n\n {code && (\n <div\n style={{\n fontWeight: \"600\",\n marginBottom: 4,\n }}\n >\n Copilot Runtime Error:{\" \"}\n <span style={{ fontFamily: \"monospace\", fontWeight: \"normal\" }}>\n {code}\n </span>\n </div>\n )}\n <ReactMarkdown>{message}</ReactMarkdown>\n </div>\n );\n });\n return (\n <div\n style={{\n fontSize: \"13px\",\n maxWidth: \"600px\",\n }}\n >\n {errorsToRender}\n <div style={{ fontSize: \"11px\", opacity: 0.75 }}>\n NOTE: This error only displays during local development.\n </div>\n </div>\n );\n}\n\nexport function useErrorToast() {\n const { addToast } = useToast();\n\n return useCallback(\n (errors: (Error | GraphQLError)[]) => {\n const errorId = errors\n .map((err) => {\n const message =\n \"extensions\" in err\n ? (err.extensions?.originalError as any)?.message || err.message\n : err.message;\n const stack = err.stack || \"\";\n return btoa(message + stack).slice(0, 32); // Create hash from message + stack\n })\n .join(\"|\");\n\n addToast({\n type: \"error\",\n id: errorId, // Toast libraries typically dedupe by id\n message: <ErrorToast errors={errors} />,\n });\n },\n [addToast],\n );\n}\n\nexport function useAsyncCallback<T extends (...args: any[]) => Promise<any>>(\n callback: T,\n deps: Parameters<typeof useCallback>[1],\n) {\n const addErrorToast = useErrorToast();\n return useCallback(async (...args: Parameters<T>) => {\n try {\n return await callback(...args);\n } catch (error) {\n console.error(\"Error in async callback:\", error);\n // @ts-ignore\n addErrorToast([error]);\n throw error;\n }\n }, deps);\n}\n","import React, { useEffect } from \"react\";\nimport { Severity, CopilotKitError } from \"@copilotkit/shared\";\nimport { StatusChecker } from \"../../lib/status-checker\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { useErrorToast } from \"./error-utils\";\n\nconst statusChecker = new StatusChecker();\n\ninterface Props {\n children: React.ReactNode;\n publicApiKey?: string;\n showUsageBanner?: boolean;\n}\n\ninterface State {\n hasError: boolean;\n error?: CopilotKitError;\n status?: {\n severity: Severity;\n message: string;\n };\n}\n\nexport class CopilotErrorBoundary extends React.Component<Props, State> {\n constructor(props: Props) {\n super(props);\n this.state = {\n hasError: false,\n };\n }\n\n static getDerivedStateFromError(error: CopilotKitError): State {\n return { hasError: true, error };\n }\n\n componentDidMount() {\n if (this.props.publicApiKey) {\n statusChecker.start(this.props.publicApiKey, (newStatus) => {\n this.setState((prevState) => {\n if (newStatus?.severity !== prevState.status?.severity) {\n return { status: newStatus ?? undefined };\n }\n return null;\n });\n });\n }\n }\n\n componentWillUnmount() {\n statusChecker.stop();\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(\"CopilotKit Error:\", error, errorInfo);\n }\n\n render() {\n if (this.state.hasError) {\n if (this.state.error instanceof CopilotKitError) {\n return (\n <>\n {this.props.children}\n {this.props.showUsageBanner && (\n <UsageBanner\n severity={\n this.state.status?.severity ?? this.state.error.severity\n }\n message={this.state.status?.message ?? this.state.error.message}\n actions={getErrorActions(this.state.error)}\n />\n )}\n </>\n );\n }\n throw this.state.error;\n }\n\n return this.props.children;\n }\n}\n\nexport function ErrorToast({\n error,\n children,\n}: {\n error?: Error;\n children: React.ReactNode;\n}) {\n const addErrorToast = useErrorToast();\n\n useEffect(() => {\n if (error) {\n addErrorToast([error]);\n }\n }, [error, addErrorToast]);\n\n if (!error) throw error;\n return children;\n}\n","import React, {\n createContext,\n useContext,\n useCallback,\n useState,\n useRef,\n ReactNode,\n RefObject,\n} from \"react\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\n\ninterface StateRenderClaim {\n stateRenderId: string;\n stateSnapshot?: any;\n runId?: string;\n messageIndex?: number;\n locked?: boolean;\n}\n\ntype ClaimsRef = Record<string, StateRenderClaim>;\n\nexport interface CoAgentStateRendersContextValue {\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (\n id: string,\n stateRender: CoAgentStateRender<any>,\n ) => void;\n removeCoAgentStateRender: (id: string) => void;\n claimsRef: RefObject<ClaimsRef>;\n}\n\nconst CoAgentStateRendersContext = createContext<\n CoAgentStateRendersContextValue | undefined\n>(undefined);\n\nexport function CoAgentStateRendersProvider({\n children,\n}: {\n children: ReactNode;\n}) {\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n\n const setCoAgentStateRender = useCallback(\n (id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => ({\n ...prevPoints,\n [id]: stateRender,\n }));\n },\n [],\n );\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const claimsRef = useRef<ClaimsRef>({});\n\n return (\n <CoAgentStateRendersContext.Provider\n value={{\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n claimsRef,\n }}\n >\n {children}\n </CoAgentStateRendersContext.Provider>\n );\n}\n\nexport function useCoAgentStateRenders() {\n const context = useContext(CoAgentStateRendersContext);\n if (!context) {\n throw new Error(\n \"useCoAgentStateRenders must be used within CoAgentStateRendersProvider\",\n );\n }\n return context;\n}\n\nexport { CoAgentStateRendersContext };\n","import React, {\n createContext,\n useContext,\n useState,\n ReactNode,\n SetStateAction,\n} from \"react\";\nimport { randomUUID } from \"@copilotkit/shared\";\n\nexport interface ThreadsContextValue {\n threadId: string;\n setThreadId: (value: SetStateAction<string>) => void;\n}\n\nconst ThreadsContext = createContext<ThreadsContextValue | undefined>(\n undefined,\n);\n\nexport interface ThreadsProviderProps {\n children: ReactNode;\n threadId?: string;\n}\n\nexport function ThreadsProvider({\n children,\n threadId: explicitThreadId,\n}: ThreadsProviderProps) {\n const [internalThreadId, setThreadId] = useState<string>(() => randomUUID());\n\n const threadId = explicitThreadId ?? internalThreadId;\n\n return (\n <ThreadsContext.Provider\n value={{\n threadId,\n setThreadId,\n }}\n >\n {children}\n </ThreadsContext.Provider>\n );\n}\n\nexport function useThreads() {\n const context = useContext(ThreadsContext);\n if (!context) {\n throw new Error(\"useThreads must be used within ThreadsProvider\");\n }\n return context;\n}\n\nexport { ThreadsContext };\n","import { dataToUUID, parseJson } from \"@copilotkit/shared\";\n\nexport enum RenderStatus {\n InProgress = \"inProgress\",\n Complete = \"complete\",\n}\n\nexport enum ClaimAction {\n Create = \"create\",\n Override = \"override\",\n Existing = \"existing\",\n Block = \"block\",\n}\n\nexport interface StateRenderContext {\n agentId: string;\n stateRenderId: string;\n messageId: string;\n runId: string;\n messageIndex?: number;\n}\n\nexport interface Claim {\n stateRenderId: string;\n runId?: string;\n stateSnapshot?: any;\n locked?: boolean;\n messageIndex?: number;\n}\n\nexport type ClaimsByMessageId = Record<string, Claim>;\n\nexport interface ClaimResolution {\n canRender: boolean;\n action: ClaimAction;\n nextClaim?: Claim;\n lockOthers?: boolean;\n updateRunId?: string;\n}\n\nexport interface SnapshotCaches {\n byStateRenderAndRun: Record<string, any>;\n byMessageId: Record<string, any>;\n}\n\nexport interface SnapshotSelectionInput {\n messageId: string;\n messageName?: string;\n allowLiveState?: boolean;\n skipLatestCache?: boolean;\n stateRenderId?: string;\n effectiveRunId: string;\n stateSnapshotProp?: any;\n agentState?: any;\n agentMessages?: Array<{ id: string; role?: string }>;\n existingClaim?: Claim;\n caches: SnapshotCaches;\n}\n\nexport interface SnapshotSelectionResult {\n snapshot?: any;\n hasSnapshotKeys: boolean;\n cachedSnapshot?: any;\n allowEmptySnapshot?: boolean;\n snapshotForClaim?: any;\n}\n\nfunction getStateWithoutConstantKeys(state: any) {\n if (!state) return {};\n const { messages, tools, copilotkit, ...stateWithoutConstantKeys } = state;\n return stateWithoutConstantKeys;\n}\n\n// Function that compares states, without the constant keys\nexport function areStatesEquals(a: any, b: any) {\n if ((a && !b) || (!a && b)) return false;\n const { messages, tools, copilotkit, ...aWithoutConstantKeys } = a;\n const {\n messages: bMessages,\n tools: bTools,\n copilotkit: bCopilotkit,\n ...bWithoutConstantKeys\n } = b;\n\n return (\n JSON.stringify(aWithoutConstantKeys) ===\n JSON.stringify(bWithoutConstantKeys)\n );\n}\n\nexport function isPlaceholderMessageId(messageId: string | undefined) {\n return !!messageId && messageId.startsWith(\"coagent-state-render-\");\n}\n\nexport function isPlaceholderMessageName(messageName: string | undefined) {\n return messageName === \"coagent-state-render\";\n}\n\nexport function readCachedMessageEntry(entry: any): {\n snapshot?: any;\n runId?: string;\n} {\n if (!entry || typeof entry !== \"object\") {\n return { snapshot: entry, runId: undefined };\n }\n const snapshot = \"snapshot\" in entry ? entry.snapshot : entry;\n const runId = \"runId\" in entry ? entry.runId : undefined;\n return { snapshot, runId };\n}\n\nexport function getEffectiveRunId({\n existingClaimRunId,\n cachedMessageRunId,\n runId,\n}: {\n existingClaimRunId?: string;\n cachedMessageRunId?: string;\n runId?: string;\n}) {\n return existingClaimRunId || cachedMessageRunId || runId || \"pending\";\n}\n\n/**\n * Resolve whether a message can claim a render slot.\n * This is a pure decision function; the caller applies claim mutations.\n */\nexport function resolveClaim({\n claims,\n context,\n stateSnapshot,\n}: {\n claims: ClaimsByMessageId;\n context: StateRenderContext;\n stateSnapshot?: any;\n}): ClaimResolution {\n const { messageId, stateRenderId, runId, messageIndex } = context;\n const existing = claims[messageId];\n\n if (existing) {\n const canRender = existing.stateRenderId === stateRenderId;\n const shouldUpdateRunId =\n canRender && runId && (!existing.runId || existing.runId === \"pending\");\n return {\n canRender,\n action: canRender ? ClaimAction.Existing : ClaimAction.Block,\n updateRunId: shouldUpdateRunId ? runId : undefined,\n };\n }\n\n const normalizedRunId = runId ?? \"pending\";\n const renderClaimedByOtherMessageEntry = Object.entries(claims).find(\n ([, claim]) =>\n claim.stateRenderId === stateRenderId &&\n (claim.runId ?? \"pending\") === normalizedRunId &&\n dataToUUID(getStateWithoutConstantKeys(claim.stateSnapshot)) ===\n dataToUUID(getStateWithoutConstantKeys(stateSnapshot)),\n );\n\n const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry?.[1];\n const claimedMessageId = renderClaimedByOtherMessageEntry?.[0];\n\n if (renderClaimedByOtherMessage) {\n if (\n messageIndex !== undefined &&\n renderClaimedByOtherMessage.messageIndex !== undefined &&\n messageIndex > renderClaimedByOtherMessage.messageIndex\n ) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers:\n runId === renderClaimedByOtherMessage.runId ||\n isPlaceholderMessageId(claimedMessageId),\n };\n }\n\n if (\n runId &&\n renderClaimedByOtherMessage.runId &&\n runId !== renderClaimedByOtherMessage.runId\n ) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers: isPlaceholderMessageId(claimedMessageId),\n };\n }\n\n if (isPlaceholderMessageId(claimedMessageId)) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers: true,\n };\n }\n\n if (\n stateSnapshot &&\n renderClaimedByOtherMessage.stateSnapshot &&\n !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, stateSnapshot)\n ) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId },\n };\n }\n\n return { canRender: false, action: ClaimAction.Block };\n }\n\n if (!runId) {\n return { canRender: false, action: ClaimAction.Block };\n }\n\n return {\n canRender: true,\n action: ClaimAction.Create,\n nextClaim: { stateRenderId, runId, messageIndex },\n };\n}\n\n/**\n * Select the best snapshot to render for this message.\n * Priority order is:\n * 1) explicit message snapshot\n * 2) live agent state (latest assistant only)\n * 3) cached snapshot for message\n * 4) cached snapshot for stateRenderId+runId\n * 5) last cached snapshot for stateRenderId\n */\nexport function selectSnapshot({\n messageId,\n messageName,\n allowLiveState,\n skipLatestCache,\n stateRenderId,\n effectiveRunId,\n stateSnapshotProp,\n agentState,\n agentMessages,\n existingClaim,\n caches,\n}: SnapshotSelectionInput): SnapshotSelectionResult {\n const lastAssistantId = agentMessages\n ? [...agentMessages].reverse().find((msg) => msg.role === \"assistant\")?.id\n : undefined;\n const latestSnapshot =\n stateRenderId !== undefined\n ? caches.byStateRenderAndRun[`${stateRenderId}::latest`]\n : undefined;\n const messageIndex = agentMessages\n ? agentMessages.findIndex((msg) => msg.id === messageId)\n : -1;\n const messageRole =\n messageIndex >= 0 && agentMessages\n ? agentMessages[messageIndex]?.role\n : undefined;\n let previousUserMessageId: string | undefined;\n if (messageIndex > 0 && agentMessages) {\n for (let i = messageIndex - 1; i >= 0; i -= 1) {\n if (agentMessages[i]?.role === \"user\") {\n previousUserMessageId = agentMessages[i]?.id;\n break;\n }\n }\n }\n const liveStateIsStale =\n stateSnapshotProp === undefined &&\n latestSnapshot !== undefined &&\n agentState !== undefined &&\n areStatesEquals(latestSnapshot, agentState);\n const shouldUseLiveState =\n (Boolean(allowLiveState) ||\n !lastAssistantId ||\n messageId === lastAssistantId) &&\n !liveStateIsStale;\n const snapshot = stateSnapshotProp\n ? parseJson(stateSnapshotProp, stateSnapshotProp)\n : shouldUseLiveState\n ? agentState\n : undefined;\n const hasSnapshotKeys = !!(snapshot && Object.keys(snapshot).length > 0);\n const allowEmptySnapshot =\n snapshot !== undefined &&\n !hasSnapshotKeys &&\n (stateSnapshotProp !== undefined || shouldUseLiveState);\n\n const messageCacheEntry = caches.byMessageId[messageId];\n const cachedMessageSnapshot =\n readCachedMessageEntry(messageCacheEntry).snapshot;\n const cacheKey =\n stateRenderId !== undefined\n ? `${stateRenderId}::${effectiveRunId}`\n : undefined;\n let cachedSnapshot = cachedMessageSnapshot ?? caches.byMessageId[messageId];\n if (\n cachedSnapshot === undefined &&\n cacheKey &&\n caches.byStateRenderAndRun[cacheKey] !== undefined\n ) {\n cachedSnapshot = caches.byStateRenderAndRun[cacheKey];\n }\n if (\n cachedSnapshot === undefined &&\n stateRenderId &&\n previousUserMessageId &&\n caches.byStateRenderAndRun[\n `${stateRenderId}::pending:${previousUserMessageId}`\n ] !== undefined\n ) {\n cachedSnapshot =\n caches.byStateRenderAndRun[\n `${stateRenderId}::pending:${previousUserMessageId}`\n ];\n }\n if (\n cachedSnapshot === undefined &&\n !skipLatestCache &&\n stateRenderId &&\n messageRole !== \"assistant\" &&\n (stateSnapshotProp !== undefined ||\n (agentState && Object.keys(agentState).length > 0))\n ) {\n cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::latest`];\n }\n\n const snapshotForClaim = existingClaim?.locked\n ? (existingClaim.stateSnapshot ?? cachedSnapshot)\n : hasSnapshotKeys\n ? snapshot\n : (existingClaim?.stateSnapshot ?? cachedSnapshot);\n\n return {\n snapshot,\n hasSnapshotKeys,\n cachedSnapshot,\n allowEmptySnapshot,\n snapshotForClaim,\n };\n}\n","import { useEffect } from \"react\";\nimport {\n areStatesEquals,\n ClaimAction,\n getEffectiveRunId,\n isPlaceholderMessageId,\n isPlaceholderMessageName,\n readCachedMessageEntry,\n resolveClaim,\n selectSnapshot,\n type Claim,\n type ClaimsByMessageId,\n type SnapshotCaches,\n type StateRenderContext,\n} from \"./use-coagent-state-render-bridge.helpers\";\n\nexport interface StateRenderRegistryInput {\n agentId: string;\n stateRenderId?: string;\n message: { id: string; runId?: string; name?: string };\n messageIndex?: number;\n stateSnapshot?: any;\n agentState?: any;\n agentMessages?: Array<{ id: string; role?: string }>;\n claimsRef: React.MutableRefObject<Record<string, Claim>>;\n}\n\nexport interface StateRenderRegistryResult {\n canRender: boolean;\n}\n\nconst LAST_SNAPSHOTS_BY_RENDER_AND_RUN = \"__lastSnapshotsByStateRenderIdAndRun\";\nconst LAST_SNAPSHOTS_BY_MESSAGE = \"__lastSnapshotsByMessageId\";\n\ntype SnapshotByMessageEntry = { snapshot: any; runId?: string } | any;\ntype ClaimsStore = Record<string, Claim> & {\n [LAST_SNAPSHOTS_BY_RENDER_AND_RUN]?: Record<string, any>;\n [LAST_SNAPSHOTS_BY_MESSAGE]?: Record<string, SnapshotByMessageEntry>;\n};\n\nfunction getClaimsStore(\n claimsRef: React.MutableRefObject<Record<string, Claim>>,\n): ClaimsStore {\n return claimsRef.current as ClaimsStore;\n}\n\nfunction getSnapshotCaches(\n claimsRef: React.MutableRefObject<Record<string, Claim>>,\n): SnapshotCaches {\n const store = getClaimsStore(claimsRef);\n return {\n byStateRenderAndRun: store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {},\n byMessageId: store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {},\n };\n}\n\nexport function useStateRenderRegistry({\n agentId,\n stateRenderId,\n message,\n messageIndex,\n stateSnapshot,\n agentState,\n agentMessages,\n claimsRef,\n}: StateRenderRegistryInput): StateRenderRegistryResult {\n const store = getClaimsStore(claimsRef);\n const runId = message.runId;\n const cachedMessageEntry = store[LAST_SNAPSHOTS_BY_MESSAGE]?.[message.id];\n const { runId: cachedMessageRunId } =\n readCachedMessageEntry(cachedMessageEntry);\n const existingClaimRunId = claimsRef.current[message.id]?.runId;\n const effectiveRunId = getEffectiveRunId({\n existingClaimRunId,\n cachedMessageRunId,\n runId,\n });\n\n useEffect(() => {\n return () => {\n const existingClaim = claimsRef.current[message.id];\n if (\n existingClaim?.stateSnapshot &&\n Object.keys(existingClaim.stateSnapshot).length > 0\n ) {\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${existingClaim.stateRenderId}::${existingClaim.runId ?? \"pending\"}`;\n snapshotCache[cacheKey] = existingClaim.stateSnapshot;\n snapshotCache[`${existingClaim.stateRenderId}::latest`] =\n existingClaim.stateSnapshot;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = {\n snapshot: existingClaim.stateSnapshot,\n runId: existingClaim.runId ?? effectiveRunId,\n };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n }\n delete claimsRef.current[message.id];\n };\n }, [claimsRef, effectiveRunId, message.id]);\n\n if (!stateRenderId) {\n return { canRender: false };\n }\n\n const caches = getSnapshotCaches(claimsRef);\n const existingClaim = claimsRef.current[message.id] as Claim | undefined;\n\n const { snapshot, hasSnapshotKeys, allowEmptySnapshot, snapshotForClaim } =\n selectSnapshot({\n messageId: message.id,\n messageName: message.name,\n allowLiveState:\n isPlaceholderMessageName(message.name) ||\n isPlaceholderMessageId(message.id),\n skipLatestCache:\n isPlaceholderMessageName(message.name) ||\n isPlaceholderMessageId(message.id),\n stateRenderId,\n effectiveRunId,\n stateSnapshotProp: stateSnapshot,\n agentState,\n agentMessages,\n existingClaim,\n caches,\n });\n\n const resolution = resolveClaim({\n claims: claimsRef.current as ClaimsByMessageId,\n context: {\n agentId,\n messageId: message.id,\n stateRenderId,\n runId: effectiveRunId,\n messageIndex,\n } satisfies StateRenderContext,\n stateSnapshot: snapshotForClaim,\n });\n\n if (resolution.action === ClaimAction.Block) {\n return { canRender: false };\n }\n\n if (resolution.updateRunId && claimsRef.current[message.id]) {\n claimsRef.current[message.id].runId = resolution.updateRunId;\n }\n\n if (resolution.nextClaim) {\n claimsRef.current[message.id] = resolution.nextClaim;\n }\n\n if (resolution.lockOthers) {\n Object.entries(claimsRef.current).forEach(([id, claim]) => {\n if (id !== message.id && claim.stateRenderId === stateRenderId) {\n claim.locked = true;\n }\n });\n }\n\n if (existingClaim && !existingClaim.locked && agentMessages?.length) {\n const indexInAgentMessages = agentMessages.findIndex(\n (msg: any) => msg.id === message.id,\n );\n if (\n indexInAgentMessages >= 0 &&\n indexInAgentMessages < agentMessages.length - 1\n ) {\n existingClaim.locked = true;\n }\n }\n\n const existingSnapshot = claimsRef.current[message.id].stateSnapshot;\n const snapshotChanged =\n stateSnapshot &&\n existingSnapshot !== undefined &&\n !areStatesEquals(existingSnapshot, snapshot);\n\n if (\n snapshot &&\n (stateSnapshot || hasSnapshotKeys || allowEmptySnapshot) &&\n (!claimsRef.current[message.id].locked || snapshotChanged)\n ) {\n if (!claimsRef.current[message.id].locked || snapshotChanged) {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${stateRenderId}::${effectiveRunId}`;\n snapshotCache[cacheKey] = snapshot;\n snapshotCache[`${stateRenderId}::latest`] = snapshot;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = { snapshot, runId: effectiveRunId };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n if (stateSnapshot) {\n claimsRef.current[message.id].locked = true;\n }\n }\n } else if (snapshotForClaim) {\n const existingSnapshot = claimsRef.current[message.id].stateSnapshot;\n if (!existingSnapshot) {\n claimsRef.current[message.id].stateSnapshot = snapshotForClaim;\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${stateRenderId}::${effectiveRunId}`;\n snapshotCache[cacheKey] = snapshotForClaim;\n snapshotCache[`${stateRenderId}::latest`] = snapshotForClaim;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = {\n snapshot: snapshotForClaim,\n runId: effectiveRunId,\n };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n }\n }\n\n return { canRender: true };\n}\n","import { ReactCustomMessageRendererPosition, useAgent } from \"../v2\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useCoAgentStateRenders } from \"../context\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { RenderStatus } from \"./use-coagent-state-render-bridge.helpers\";\nimport { useStateRenderRegistry } from \"./use-coagent-state-render-registry\";\n\n/**\n * Bridge hook that connects agent state renders to chat messages.\n *\n * ## Purpose\n * This hook finds matching state render configurations (registered via useCoAgentStateRender)\n * and returns UI to render in chat.\n * It ensures each state render appears bound to a specific message, preventing duplicates while\n * allowing re-binding when the underlying state changes significantly.\n *\n * ## Message-ID-Based Claiming System\n *\n * ### The Problem\n * Multiple bridge component instances render simultaneously (one per message). Without coordination,\n * they would all try to render the same state render, causing duplicates.\n *\n * ### The Solution: Message-ID Claims with State Comparison\n * Each state render is \"claimed\" by exactly one **message ID** (not runId):\n *\n * **Claim Structure**: `claimsRef.current[messageId] = { stateRenderId, runId, stateSnapshot, locked }`\n *\n * **Primary binding is by messageId because**:\n * - runId is not always available immediately (starts as \"pending\")\n * - messageId is the stable identifier throughout the message lifecycle\n * - Claims persist across component remounts via context ref\n *\n * ### Claiming Logic Flow\n *\n * 1. **Message already has a claim**:\n * - Check if the claim matches the current stateRenderId\n * - If yes → render (this message owns this render)\n * - Update runId if it was \"pending\" and now available\n *\n * 2. **State render claimed by another message**:\n * - Compare state snapshots (ignoring constant keys: messages, tools, copilotkit)\n * - If states are identical → block rendering (duplicate)\n * - **If states are different → allow claiming** (new data, new message)\n * - This handles cases where the same render type shows different states in different messages\n *\n * 3. **Unclaimed state render**:\n * - Only allow claiming if runId is \"pending\" (initial render)\n * - If runId is real but no claim exists → block (edge case protection)\n * - Create new claim: `claimsRef.current[messageId] = { stateRenderId, runId }`\n *\n * ### State Snapshot Locking\n *\n * Once a state snapshot is captured and locked for a message:\n * - The UI always renders with the locked snapshot (not live agent.state)\n * - Prevents UI from appearing \"wiped\" during state transitions\n * - Locked when: stateSnapshot prop is available (from message persistence)\n * - Unlocked state: can still update from live agent.state\n *\n * ### Synchronous Claiming (Ref-based)\n *\n * Claims are stored in a context-level ref (not React state):\n * - Multiple bridges render in the same tick\n * - State updates are async - would allow duplicates before update completes\n * - Ref provides immediate, synchronous claim checking\n * - Survives component remounts (stored in context, not component)\n *\n * ## Flow Example\n *\n * ```\n * Time 1: Message A renders, runId=undefined, state={progress: 50%}\n * → effectiveRunId = \"pending\"\n * → Claims: claimsRef[\"msgA\"] = { stateRenderId: \"tasks\", runId: \"pending\", stateSnapshot: {progress: 50%} }\n * → Renders UI with 50% progress\n *\n * Time 2: Message B renders, runId=undefined, same state\n * → Checks: \"tasks\" already claimed by msgA with same state\n * → Returns null (blocked - duplicate)\n *\n * Time 3: Real runId appears (e.g., \"run-123\")\n * → Updates claim: claimsRef[\"msgA\"].runId = \"run-123\"\n * → Message A continues rendering\n *\n * Time 4: Agent processes more, state={progress: 100%}\n * → Message A: locked to 50% (stateSnapshot locked)\n * → Message C renders with state={progress: 100%}\n * → Checks: \"tasks\" claimed by msgA but state is DIFFERENT (50% vs 100%)\n * → Allows new claim: claimsRef[\"msgC\"] = { stateRenderId: \"tasks\", runId: \"run-123\", stateSnapshot: {progress: 100%} }\n * → Both messages render independently with their own snapshots\n * ```\n */\nexport interface CoAgentStateRenderBridgeProps {\n message: any;\n position: ReactCustomMessageRendererPosition;\n runId: string;\n messageIndex: number;\n messageIndexInRun: number;\n numberOfMessagesInRun: number;\n agentId: string;\n stateSnapshot: any;\n}\n\nexport function useCoagentStateRenderBridge(\n agentId: string,\n props: CoAgentStateRenderBridgeProps,\n) {\n const { stateSnapshot, message } = props;\n const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();\n const { agent } = useAgent({ agentId });\n const [nodeName, setNodeName] = useState<string | undefined>(undefined);\n const [, forceUpdate] = useState(0);\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStateChanged: () => {\n forceUpdate((value) => value + 1);\n },\n onStepStartedEvent: ({ event }) => {\n if (event.stepName !== nodeName) {\n setNodeName(event.stepName);\n }\n },\n onStepFinishedEvent: ({ event }) => {\n if (event.stepName === nodeName) {\n setNodeName(undefined);\n }\n },\n };\n\n const { unsubscribe } = agent.subscribe(subscriber);\n return () => {\n unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agentId, nodeName]);\n\n const getStateRender = useCallback(\n (messageId: string) => {\n return Object.entries(coAgentStateRenders).find(\n ([stateRenderId, stateRender]) => {\n if (claimsRef.current[messageId]) {\n return stateRenderId === claimsRef.current[messageId].stateRenderId;\n }\n const matchingAgentName = stateRender.name === agentId;\n const matchesNodeContext = stateRender.nodeName\n ? stateRender.nodeName === nodeName\n : true;\n return matchingAgentName && matchesNodeContext;\n },\n );\n },\n [coAgentStateRenders, nodeName, agentId],\n );\n const stateRenderEntry = useMemo(\n () => getStateRender(message.id),\n [getStateRender, message.id],\n );\n const stateRenderId = stateRenderEntry?.[0];\n const stateRender = stateRenderEntry?.[1];\n\n const registryMessage = {\n ...message,\n runId: props.runId ?? message.runId,\n };\n const { canRender } = useStateRenderRegistry({\n agentId,\n stateRenderId,\n message: registryMessage,\n messageIndex: props.messageIndex,\n stateSnapshot,\n agentState: agent?.state,\n agentMessages: agent?.messages,\n claimsRef,\n });\n\n return useMemo(() => {\n if (!stateRender || !stateRenderId) {\n return null;\n }\n if (!canRender) {\n return null;\n }\n\n if (stateRender.handler) {\n stateRender.handler({\n state: stateSnapshot\n ? parseJson(stateSnapshot, stateSnapshot)\n : (agent?.state ?? {}),\n nodeName: nodeName ?? \"\",\n });\n }\n\n if (stateRender.render) {\n const status = agent?.isRunning\n ? RenderStatus.InProgress\n : RenderStatus.Complete;\n\n if (typeof stateRender.render === \"string\") return stateRender.render;\n\n return stateRender.render({\n status,\n // Always use state from claim, to make sure the state does not seem \"wiped\" for a fraction of a second\n state: claimsRef.current[message.id].stateSnapshot ?? {},\n nodeName: nodeName ?? \"\",\n });\n }\n }, [\n stateRender,\n stateRenderId,\n agent?.state,\n agent?.isRunning,\n nodeName,\n message.id,\n stateSnapshot,\n canRender,\n ]);\n}\n\nexport function CoAgentStateRenderBridge(props: CoAgentStateRenderBridgeProps) {\n return useCoagentStateRenderBridge(props.agentId, props);\n}\n","import { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { useAgent, useCopilotChatConfiguration, useCopilotKit } from \"../v2\";\nimport { CopilotKitError, parseJson } from \"@copilotkit/shared\";\nimport { useCopilotContext } from \"../context\";\nimport {\n AbstractAgent,\n AgentSubscriber,\n AGUIConnectNotImplementedError,\n} from \"@ag-ui/client\";\nimport { useErrorToast } from \"./error-boundary/error-utils\";\nimport { CopilotKitCoreSubscriber } from \"@copilotkit/core\";\nimport { useToast } from \"./toast/toast-provider\";\nimport { CopilotKitLowLevelError } from \"@copilotkit/shared\";\n\nconst usePredictStateSubscription = (agent?: AbstractAgent) => {\n const predictStateToolsRef = useRef<\n {\n tool: string;\n state_key: string;\n tool_argument: string;\n }[]\n >([]);\n\n const getSubscriber = useCallback(\n (agent: AbstractAgent): AgentSubscriber => ({\n onCustomEvent: ({ event }) => {\n if (event.name === \"PredictState\") {\n predictStateToolsRef.current = event.value;\n }\n },\n onToolCallArgsEvent: ({ partialToolCallArgs, toolCallName }) => {\n predictStateToolsRef.current.forEach((t) => {\n if (t?.tool !== toolCallName) return;\n\n const emittedState =\n typeof partialToolCallArgs === \"string\"\n ? parseJson(\n partialToolCallArgs as unknown as string,\n partialToolCallArgs,\n )\n : partialToolCallArgs;\n\n agent.setState({\n [t.state_key]: emittedState[t.state_key],\n });\n });\n },\n }),\n [],\n );\n\n useEffect(() => {\n if (!agent) return;\n\n const subscriber = getSubscriber(agent);\n const { unsubscribe } = agent.subscribe(subscriber);\n return () => {\n unsubscribe();\n };\n }, [agent, getSubscriber]);\n};\n\nexport function CopilotListeners() {\n const { copilotkit } = useCopilotKit();\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId;\n const { setBannerError } = useToast();\n\n const { agent } = useAgent({ agentId: resolvedAgentId });\n\n usePredictStateSubscription(agent);\n\n useEffect(() => {\n const subscriber: CopilotKitCoreSubscriber = {\n onError: ({ error }) => {\n setBannerError(\n new CopilotKitLowLevelError({\n error,\n message: error.message,\n url: typeof window !== \"undefined\" ? window.location.href : \"\",\n }),\n );\n },\n };\n const subscription = copilotkit.subscribe(subscriber);\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit?.subscribe]);\n\n return null;\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n SetStateAction,\n} from \"react\";\nimport {\n CopilotChatConfigurationProvider,\n CopilotKitInspector,\n CopilotKitProvider as CopilotKitV2Provider,\n useCopilotKit,\n} from \"../../v2\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\n useCopilotContext,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport {\n CopilotChatSuggestionConfiguration,\n DocumentPointer,\n} from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n CopilotKitError,\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages, MessagesTapProvider } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetterArgs,\n QueuedInterruptEvent,\n} from \"../../types/interrupt-action\";\nimport { CoAgentStateRendersProvider } from \"../../context/coagent-state-renders-context\";\nimport { CoAgentStateRenderBridge } from \"../../hooks/use-coagent-state-render-bridge\";\nimport { ThreadsProvider, useThreads } from \"../../context/threads-context\";\nimport { CopilotListeners } from \"../CopilotListeners\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n const showInspector = shouldShowDevConsole(props.enableInspector);\n\n // Use API key if provided, otherwise use the license key\n const publicApiKey = props.publicApiKey || props.publicLicenseKey;\n\n const renderArr = useMemo(() => [{ render: CoAgentStateRenderBridge }], []);\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary\n publicApiKey={publicApiKey}\n showUsageBanner={enabled}\n >\n <ThreadsProvider threadId={props.threadId}>\n <CopilotKitV2Provider\n {...props}\n showDevConsole={showInspector}\n renderCustomMessages={renderArr}\n useSingleEndpoint={props.useSingleEndpoint ?? true}\n >\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotKitV2Provider>\n </ThreadsProvider>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\n/**\n * Bridge component that subscribes to v2.x copilotkit core error events\n * and forwards them to v1.x error handling system.\n * This ensures only ONE subscription exists regardless of how many times\n * Chat components are rendered.\n */\nfunction CopilotKitErrorBridge() {\n const { copilotkit } = useCopilotKit();\n const { onError, copilotApiConfig } = useCopilotContext();\n\n useEffect(() => {\n if (!copilotkit) return;\n\n const subscription = copilotkit.subscribe({\n onError: async (event) => {\n // Convert v2.x error event to v1.x CopilotErrorEvent format\n const errorEvent: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"agent\",\n request: {\n operation: event.code || \"unknown\",\n url: copilotApiConfig?.chatApiEndpoint,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent:\n typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : undefined,\n stackTrace: event.error.stack,\n },\n // Add additional context from v2.x event\n ...event.context,\n },\n error: event.error,\n };\n\n try {\n await onError(errorEvent);\n } catch (handlerError) {\n console.error(\"Error in onError handler:\", handlerError);\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit, onError, copilotApiConfig]);\n\n return null;\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n // Use license key as API key if provided, otherwise use the API key\n const publicApiKey = props.publicLicenseKey || props.publicApiKey;\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>(\n {},\n );\n\n // State for registered actions from useCopilotAction\n const [registeredActionConfigs, setRegisteredActionConfigs] = useState<\n Map<string, { type: string; action: any; component: any }>\n >(new Map());\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<\n string[]\n >([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n // Compute all the functions and properties that we need to pass\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(\n Object.values(customEntryPoints || actions),\n );\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (\n documentPointer: DocumentPointer,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? {\n [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]:\n copilotApiConfig.publicApiKey,\n }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const [internalErrorHandlers, _setInternalErrorHandler] = useState<\n Record<string, CopilotErrorHandler>\n >({});\n const setInternalErrorHandler = useCallback(\n (handler: Record<string, CopilotErrorHandler>) => {\n _setInternalErrorHandler((prev: Record<string, CopilotErrorHandler>) => ({\n ...prev,\n ...handler,\n }));\n },\n [],\n );\n const removeInternalErrorHandler = useCallback((key: string) => {\n _setInternalErrorHandler((prev) => {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n });\n }, []);\n\n // Keep latest values in refs\n const onErrorRef = useRef<CopilotErrorHandler | undefined>(props.onError);\n useEffect(() => {\n onErrorRef.current = props.onError;\n }, [props.onError]);\n\n const internalHandlersRef = useRef<Record<string, CopilotErrorHandler>>({});\n useEffect(() => {\n internalHandlersRef.current = internalErrorHandlers;\n }, [internalErrorHandlers]);\n\n const handleErrors = useCallback(\n async (error: CopilotErrorEvent) => {\n if (copilotApiConfig.publicApiKey && onErrorRef.current) {\n try {\n await onErrorRef.current(error);\n } catch (e) {\n console.error(\"Error in public onError handler:\", e);\n }\n }\n const handlers = Object.values(internalHandlersRef.current);\n await Promise.all(\n handlers.map((h) =>\n Promise.resolve(h(error)).catch((e) =>\n console.error(\"Error in internal error handler:\", e),\n ),\n ),\n );\n },\n [copilotApiConfig.publicApiKey],\n );\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] =\n useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<\n Record<string, CoagentState>\n >({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((\n prev: Record<string, CoagentState>,\n ) => Record<string, CoagentState>),\n ) => {\n const newValue =\n typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(\n initialAgentSession,\n );\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const { threadId, setThreadId: setInternalThreadId } = useThreads();\n\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\n \"Cannot call setThreadId() when threadId is provided via props.\",\n );\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = shouldShowDevConsole(props.showDevConsole);\n\n const [interruptActions, _setInterruptActions] = useState<\n Record<string, LangGraphInterruptRender>\n >({});\n const setInterruptAction = useCallback(\n (action: LangGraphInterruptActionSetterArgs) => {\n _setInterruptActions((prev) => {\n if (action == null || !action.id) {\n // Cannot set action without id\n return prev;\n }\n return {\n ...prev,\n [action.id]: {\n ...(prev[action.id] ?? {}),\n ...action,\n } as LangGraphInterruptRender,\n };\n });\n },\n [],\n );\n const removeInterruptAction = useCallback((actionId: string): void => {\n _setInterruptActions((prev) => {\n const { [actionId]: _, ...rest } = prev;\n return rest;\n });\n }, []);\n\n const [interruptEventQueue, setInterruptEventQueue] = useState<\n Record<string, QueuedInterruptEvent[]>\n >({});\n\n const addInterruptEvent = useCallback((queuedEvent: QueuedInterruptEvent) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[queuedEvent.threadId] || [];\n return {\n ...prev,\n [queuedEvent.threadId]: [...threadQueue, queuedEvent],\n };\n });\n }, []);\n\n const resolveInterruptEvent = useCallback(\n (threadId: string, eventId: string, response: string) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[threadId] || [];\n return {\n ...prev,\n [threadId]: threadQueue.map((queuedEvent) =>\n queuedEvent.eventId === eventId\n ? { ...queuedEvent, event: { ...queuedEvent.event, response } }\n : queuedEvent,\n ),\n };\n });\n },\n [],\n );\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved =\n typeof newExtensions === \"function\"\n ? newExtensions(prev)\n : newExtensions;\n const isSameLength =\n Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved =\n typeof newAuthStates === \"function\"\n ? newAuthStates(prev)\n : newAuthStates;\n const isSameLength =\n Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n const handleSetRegisteredActions = useCallback(\n (actionConfig: any): string => {\n const key = actionConfig.action.name || randomUUID();\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.set(key, actionConfig);\n return newMap;\n });\n return key;\n },\n [],\n );\n\n const handleRemoveRegisteredAction = useCallback((actionKey: string) => {\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.delete(actionKey);\n return newMap;\n });\n }, []);\n\n // Component to render all registered actions\n const RegisteredActionsRenderer = useMemo(() => {\n return () => (\n <>\n {Array.from(registeredActionConfigs.entries()).map(([key, config]) => {\n const Component = config.component;\n return <Component key={key} action={config.action} />;\n })}\n </>\n );\n }, [registeredActionConfigs]);\n\n const copilotContextValue = useMemo(\n () => ({\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n setRegisteredActions: handleSetRegisteredActions,\n removeRegisteredAction: handleRemoveRegisteredAction,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n interruptActions,\n setInterruptAction,\n removeInterruptAction,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n bannerError,\n setBannerError,\n onError: handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n }),\n [\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n handleSetRegisteredActions,\n handleRemoveRegisteredAction,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig,\n isLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n additionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n availableAgents,\n props.authConfig_c,\n authStates,\n updateAuthStates,\n extensions,\n updateExtensions,\n interruptActions,\n setInterruptAction,\n removeInterruptAction,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n bannerError,\n handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n ],\n );\n\n return (\n <CopilotChatConfigurationProvider\n // labels={labels}\n // isModalDefaultOpen={isModalDefaultOpen}\n agentId={props.agent ?? \"default\"}\n threadId={threadId}\n >\n <CopilotContext.Provider value={copilotContextValue}>\n <CopilotListeners />\n <CopilotKitErrorBridge />\n <CoAgentStateRendersProvider>\n <MessagesTapProvider>\n <CopilotMessages>\n <React.Fragment key=\"children\">{memoizedChildren}</React.Fragment>\n <RegisteredActionsRenderer key=\"actions\" />\n </CopilotMessages>\n </MessagesTapProvider>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </CoAgentStateRendersProvider>\n </CopilotContext.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(\n actions: FrontendAction<any>[],\n): FunctionCallHandler {\n return async ({\n name,\n args,\n }: {\n name: string;\n args: Record<string, any>;\n }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n // Check if we have either a runtimeUrl or one of the API keys\n const hasApiKey = props.publicApiKey || props.publicLicenseKey;\n\n if (!props.runtimeUrl && !hasApiKey) {\n throw new ConfigurationError(\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\",\n );\n }\n\n if (cloudFeatures.length > 0 && !hasApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n","import { useRenderToolCall } from \"../v2\";\nimport { AIMessage, Message, ToolResult } from \"@copilotkit/shared\";\nimport React, { useCallback } from \"react\";\n\nexport function useLazyToolRenderer(): (\n message?: AIMessage,\n messages?: Message[],\n) => null | (() => ReturnType<ReturnType<typeof useRenderToolCall>> | null) {\n const renderToolCall = useRenderToolCall();\n\n return useCallback(\n (message?: AIMessage, messages?: Message[]) => {\n if (!message?.toolCalls?.length) return null;\n\n const toolCall = message.toolCalls[0];\n if (!toolCall) return null;\n\n const toolMessage = messages?.find(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id,\n ) as ToolResult;\n\n return () =>\n renderToolCall({\n toolCall,\n toolMessage,\n });\n },\n [renderToolCall],\n );\n}\n","import React, {\n useRef,\n useEffect,\n useCallback,\n useMemo,\n useState,\n createElement,\n} from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { Message } from \"@copilotkit/shared\";\nimport {\n gqlToAGUI,\n Message as DeprecatedGqlMessage,\n} from \"@copilotkit/runtime-client-gql\";\nimport {\n useAgent,\n useCopilotChatConfiguration,\n useCopilotKit,\n useRenderCustomMessages,\n useSuggestions,\n} from \"../v2\";\nimport {\n Suggestion,\n CopilotKitCoreRuntimeConnectionStatus,\n} from \"@copilotkit/core\";\nimport { useLazyToolRenderer } from \"./use-lazy-tool-renderer\";\nimport {\n AbstractAgent,\n AGUIConnectNotImplementedError,\n HttpAgent,\n} from \"@ag-ui/client\";\nimport {\n CoAgentStateRenderBridge,\n type CoAgentStateRenderBridgeProps,\n} from \"./use-coagent-state-render-bridge\";\n\n/**\n * The type of suggestions to use in the chat.\n *\n * `auto` - Suggestions are generated automatically.\n * `manual` - Suggestions are controlled programmatically.\n * `SuggestionItem[]` - Static suggestions array.\n */\nexport type ChatSuggestions =\n | \"auto\"\n | \"manual\"\n | Omit<Suggestion, \"isLoading\">[];\n\nexport interface AppendMessageOptions {\n /**\n * Whether to run the chat completion after appending the message. Defaults to `true`.\n */\n followUp?: boolean;\n /**\n * Whether to clear the suggestions after appending the message. Defaults to `true`.\n */\n clearSuggestions?: boolean;\n}\n\nexport interface OnStopGenerationArguments {\n /**\n * The name of the currently executing agent.\n */\n currentAgentName: string | undefined;\n\n /**\n * The messages in the chat.\n */\n messages: Message[];\n}\n\nexport type OnReloadMessagesArguments = OnStopGenerationArguments & {\n /**\n * The message on which \"regenerate\" was pressed\n */\n messageId: string;\n};\n\nexport type OnStopGeneration = (args: OnStopGenerationArguments) => void;\n\nexport type OnReloadMessages = (args: OnReloadMessagesArguments) => void;\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Initial messages to populate the chat with.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n\n /**\n * Disables inclusion of CopilotKit’s default system message. When true, no system message is sent (this also suppresses any custom message from <code>makeSystemMessage</code>).\n */\n disableSystemMessage?: boolean;\n /**\n * Controls the behavior of suggestions in the chat interface.\n *\n * `auto` (default) - Suggestions are generated automatically:\n * - When the chat is first opened (empty state)\n * - After each message exchange completes\n * - Uses configuration from `useCopilotChatSuggestions` hooks\n *\n * `manual` - Suggestions are controlled programmatically:\n * - Use `setSuggestions()` to set custom suggestions\n * - Use `generateSuggestions()` to trigger AI generation\n * - Access via `useCopilotChat` hook\n *\n * `SuggestionItem[]` - Static suggestions array:\n * - Always shows the same suggestions\n * - No AI generation involved\n */\n suggestions?: ChatSuggestions;\n\n onInProgress?: (isLoading: boolean) => void;\n onSubmitMessage?: (messageContent: string) => Promise<void> | void;\n onStopGeneration?: OnStopGeneration;\n onReloadMessages?: OnReloadMessages;\n}\n\nexport interface MCPServerConfig {\n endpoint: string;\n apiKey?: string;\n}\n\n// Old suggestion item interface, for returning from useCopilotChatInternal\ninterface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport interface UseCopilotChatReturn {\n /**\n * @deprecated use `messages` instead, this is an old non ag-ui version of the messages\n * Array of messages currently visible in the chat interface\n *\n * This is the visible messages, not the raw messages from the runtime client.\n */\n visibleMessages: DeprecatedGqlMessage[];\n\n /**\n * The messages that are currently in the chat in AG-UI format.\n */\n messages: Message[];\n\n /** @deprecated use `sendMessage` in `useCopilotChatHeadless_c` instead. This will be removed in a future major version. */\n appendMessage: (\n message: DeprecatedGqlMessage,\n options?: AppendMessageOptions,\n ) => Promise<void>;\n\n /**\n * Send a new message to the chat\n *\n * ```tsx\n * await sendMessage({\n * id: \"123\",\n * role: \"user\",\n * content: \"Hello, process this request\",\n * });\n * ```\n */\n sendMessage: (\n message: Message,\n options?: AppendMessageOptions,\n ) => Promise<void>;\n\n /**\n * Replace all messages in the chat\n *\n * ```tsx\n * setMessages([\n * { id: \"123\", role: \"user\", content: \"Hello, process this request\" },\n * { id: \"456\", role: \"assistant\", content: \"Hello, I'm the assistant\" },\n * ]);\n * ```\n *\n * **Deprecated** non-ag-ui version:\n *\n * ```tsx\n * setMessages([\n * new TextMessage({\n * content: \"Hello, process this request\",\n * role: gqlRole.User,\n * }),\n * new TextMessage({\n * content: \"Hello, I'm the assistant\",\n * role: gqlRole.Assistant,\n * ]);\n * ```\n *\n */\n setMessages: (messages: Message[] | DeprecatedGqlMessage[]) => void;\n\n /**\n * Remove a specific message by ID\n *\n * ```tsx\n * deleteMessage(\"123\");\n * ```\n */\n deleteMessage: (messageId: string) => void;\n\n /**\n * Regenerate the response for a specific message\n *\n * ```tsx\n * reloadMessages(\"123\");\n * ```\n */\n reloadMessages: (messageId: string) => Promise<void>;\n\n /**\n * Stop the current message generation\n *\n * ```tsx\n * if (isLoading) {\n * stopGeneration();\n * }\n * ```\n */\n stopGeneration: () => void;\n\n /**\n * Clear all messages and reset chat state\n *\n * ```tsx\n * reset();\n * console.log(messages); // []\n * ```\n */\n reset: () => void;\n\n /**\n * Whether the chat is currently generating a response\n *\n * ```tsx\n * if (isLoading) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isLoading: boolean;\n\n /**\n * Whether the chat agent is available to generate responses\n *\n * ```tsx\n * if (isAvailable) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isAvailable: boolean;\n\n /** Manually trigger chat completion (advanced usage) */\n runChatCompletion: () => Promise<Message[]>;\n\n /** MCP (Model Context Protocol) server configurations */\n mcpServers: MCPServerConfig[];\n\n /** Update MCP server configurations */\n setMcpServers: (mcpServers: MCPServerConfig[]) => void;\n\n /**\n * Current suggestions array\n * Use this to read the current suggestions or in conjunction with setSuggestions for manual control\n */\n suggestions: Suggestion[];\n\n /**\n * Manually set suggestions\n * Useful for manual mode or custom suggestion workflows\n */\n setSuggestions: (suggestions: Omit<Suggestion, \"isLoading\">[]) => void;\n\n /**\n * Trigger AI-powered suggestion generation\n * Uses configurations from useCopilotChatSuggestions hooks\n * Respects global debouncing - only one generation can run at a time\n *\n * ```tsx\n * generateSuggestions();\n * console.log(suggestions); // [suggestion1, suggestion2, suggestion3]\n * ```\n */\n generateSuggestions: () => Promise<void>;\n\n /**\n * Clear all current suggestions\n * Also resets suggestion generation state\n */\n resetSuggestions: () => void;\n\n /** Whether suggestions are currently being generated */\n isLoadingSuggestions: boolean;\n\n /** Interrupt content for human-in-the-loop workflows */\n interrupt: string | React.ReactElement | null;\n\n agent?: ReturnType<typeof useAgent>[\"agent\"];\n\n threadId?: string;\n}\n\nexport function useCopilotChatInternal({\n suggestions,\n onInProgress,\n onSubmitMessage,\n onStopGeneration,\n onReloadMessages,\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const { copilotkit } = useCopilotKit();\n const { threadId, agentSession } = useCopilotContext();\n const existingConfig = useCopilotChatConfiguration();\n const [agentAvailable, setAgentAvailable] = useState(false);\n\n // Apply priority: props > existing config > defaults\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const { agent } = useAgent({\n agentId: resolvedAgentId,\n threadId: existingConfig?.threadId,\n });\n\n // Track the last agent instance we called connect() on. Without this,\n // connect() fires on every render where status is Connected — including\n // unrelated context re-renders and StrictMode double-invocations.\n // The ref is reset in the cleanup so that remounts (StrictMode, real\n // unmount/remount) always trigger a fresh connect.\n const lastConnectedAgentRef = useRef<AbstractAgent | null>(null);\n\n useEffect(() => {\n let detached = false;\n\n // Create a fresh AbortController so we can cancel the HTTP request on cleanup.\n // Mirrors the V2 CopilotChat pattern: HttpAgent uses abortController.signal in\n // its fetch config. connectAgent() does NOT create a new AbortController\n // automatically, so we must set one before connecting.\n const connectAbortController = new AbortController();\n if (agent instanceof HttpAgent) {\n agent.abortController = connectAbortController;\n }\n\n const connect = async (agent: AbstractAgent) => {\n setAgentAvailable(false);\n try {\n await copilotkit.connectAgent({ agent });\n // Guard against setting state after cleanup (e.g. React StrictMode unmount)\n if (!detached) {\n setAgentAvailable(true);\n }\n } catch (error) {\n // Ignore errors from aborted connections (e.g. React StrictMode cleanup)\n if (detached) return;\n if (error instanceof AGUIConnectNotImplementedError) {\n // connect not implemented, ignore\n } else {\n console.error(\"CopilotChat: connectAgent failed\", error);\n // Error will be reported through subscription\n }\n }\n };\n if (\n agent &&\n agent !== lastConnectedAgentRef.current &&\n copilotkit.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ) {\n lastConnectedAgentRef.current = agent;\n connect(agent);\n }\n return () => {\n // Abort the HTTP request and detach the active run.\n // This is critical for React StrictMode which unmounts+remounts in dev,\n // preventing duplicate /connect requests from reaching the server.\n // Reset the ref so remounts always trigger a fresh connect.\n lastConnectedAgentRef.current = null;\n detached = true;\n connectAbortController.abort();\n agent?.detachActiveRun();\n };\n }, [\n existingConfig?.threadId,\n agent,\n copilotkit,\n copilotkit.runtimeConnectionStatus,\n resolvedAgentId,\n ]);\n\n useEffect(() => {\n onInProgress?.(Boolean(agent?.isRunning));\n }, [agent?.isRunning, onInProgress]);\n\n // Subscribe to copilotkit.interruptElement so the v1 return type stays\n // reactive. The element is published by useInterrupt (v2) when user code\n // calls useLangGraphInterrupt({ render, ... }).\n const [interrupt, setInterrupt] = useState<React.ReactElement | null>(null);\n useEffect(() => {\n setInterrupt(copilotkit.interruptElement);\n const subscription = copilotkit.subscribe({\n onInterruptElementChanged: ({ interruptElement }) => {\n setInterrupt(interruptElement);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const reset = () => {\n agent?.setMessages([]);\n agent?.setState(null);\n };\n\n const deleteMessage = useCallback(\n (messageId: string) => {\n const filteredMessages = (agent?.messages ?? []).filter(\n (message) => message.id !== messageId,\n );\n agent?.setMessages(filteredMessages);\n },\n [agent?.setMessages, agent?.messages],\n );\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const currentSuggestions = useSuggestions({ agentId: resolvedAgentId });\n\n const reload = useAsyncCallback(\n async (reloadMessageId: string): Promise<void> => {\n if (!agent) return;\n const messages = agent?.messages ?? [];\n const isLoading = agent.isRunning;\n if (isLoading || messages.length === 0) {\n return;\n }\n\n const reloadMessageIndex = messages.findIndex(\n (msg) => msg.id === reloadMessageId,\n );\n if (reloadMessageIndex === -1) {\n console.warn(`Message with id ${reloadMessageId} not found`);\n return;\n }\n\n const reloadMessageRole = messages[reloadMessageIndex].role;\n if (reloadMessageRole !== \"assistant\") {\n console.warn(\n `Regenerate cannot be performed on ${reloadMessageRole} role`,\n );\n return;\n }\n let historyCutoff: Message[] = [messages[0]];\n\n if (messages.length > 2 && reloadMessageIndex !== 0) {\n // message to regenerate from is now first.\n // Work backwards to find the first the closest user message\n const lastUserMessageBeforeRegenerate = messages\n .slice(0, reloadMessageIndex)\n .reverse()\n .find((msg) => msg.role === \"user\");\n\n if (!lastUserMessageBeforeRegenerate) {\n historyCutoff = [messages[0]];\n } else {\n const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(\n (msg) => msg.id === lastUserMessageBeforeRegenerate.id,\n );\n // Include the user message, remove everything after it\n historyCutoff = messages.slice(\n 0,\n indexOfLastUserMessageBeforeRegenerate + 1,\n );\n }\n } else if (messages.length > 2 && reloadMessageIndex === 0) {\n historyCutoff = [messages[0], messages[1]];\n }\n\n agent?.setMessages(historyCutoff);\n\n if (agent) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed during reload\", error);\n // Error will be reported through subscription\n }\n }\n return;\n },\n [\n agent?.messages.length,\n agent?.isRunning,\n agent?.setMessages,\n copilotkit?.runAgent,\n ],\n );\n\n const latestSendMessageFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n if (!agent) return;\n const followUp = options?.followUp ?? true;\n if (options?.clearSuggestions) {\n copilotkit.clearSuggestions(resolvedAgentId);\n }\n\n // Call onSubmitMessage BEFORE adding message and running agent\n // This allows users to perform actions (e.g., open chat window) before agent starts processing\n if (onSubmitMessage) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : message.content && \"text\" in message.content\n ? message.content.text\n : message.content && \"filename\" in message.content\n ? message.content.filename\n : \"\";\n try {\n await onSubmitMessage(content);\n } catch (error) {\n console.error(\"Error in onSubmitMessage:\", error);\n }\n }\n\n agent?.addMessage(message);\n if (followUp) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\n // Error will be reported through subscription\n }\n }\n },\n [agent, copilotkit, resolvedAgentId, onSubmitMessage],\n );\n\n const latestAppendFunc = useAsyncCallback(\n async (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => {\n return latestSendMessageFunc(gqlToAGUI([message])[0], options);\n },\n [latestSendMessageFunc],\n );\n\n const latestSetMessagesFunc = useCallback(\n (messages: Message[] | DeprecatedGqlMessage[]) => {\n if (\n messages.every((message) => message instanceof DeprecatedGqlMessage)\n ) {\n return agent?.setMessages?.(gqlToAGUI(messages));\n }\n return agent?.setMessages?.(messages);\n },\n [agent?.setMessages, agent],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(\n async (messageId: string) => {\n onReloadMessages?.({\n messageId,\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return await latestReload.current(messageId);\n },\n [latestReload, agent, onReloadMessages],\n );\n\n const latestStopFunc = useCallback(() => {\n onStopGeneration?.({\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return agent?.abortRun?.();\n }, [onStopGeneration, agent]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n const lazyToolRendered = useLazyToolRenderer();\n const renderCustomMessage = useRenderCustomMessages();\n const legacyCustomMessageRenderer = useLegacyCoagentRenderer({\n copilotkit,\n agent,\n agentId: resolvedAgentId,\n threadId: existingConfig?.threadId ?? threadId,\n });\n const allMessages = agent?.messages ?? [];\n const resolvedMessages = useMemo(() => {\n let processedMessages = allMessages.map((message) => {\n if (message.role !== \"assistant\") {\n return message;\n }\n\n const lazyRendered = lazyToolRendered(message, allMessages);\n if (lazyRendered) {\n const renderedGenUi = lazyRendered();\n if (renderedGenUi) {\n return { ...message, generativeUI: () => renderedGenUi };\n }\n }\n\n const bridgeRenderer =\n legacyCustomMessageRenderer || renderCustomMessage\n ? () => {\n if (legacyCustomMessageRenderer) {\n return legacyCustomMessageRenderer({\n message,\n position: \"before\",\n });\n }\n try {\n return (\n renderCustomMessage?.({ message, position: \"before\" }) ?? null\n );\n } catch (error) {\n console.warn(\n \"[CopilotKit] renderCustomMessages failed, falling back to legacy renderer\",\n error,\n );\n return null;\n }\n }\n : null;\n\n if (bridgeRenderer) {\n // Attach a position so react-ui can render the custom UI above the assistant content.\n return {\n ...message,\n generativeUI: bridgeRenderer,\n generativeUIPosition: \"before\" as const,\n };\n }\n return message;\n });\n\n const hasAssistantMessages = processedMessages.some(\n (msg) => msg.role === \"assistant\",\n );\n const canUseCustomRenderer = Boolean(\n renderCustomMessage && copilotkit?.getAgent?.(resolvedAgentId),\n );\n const placeholderRenderer = legacyCustomMessageRenderer\n ? legacyCustomMessageRenderer\n : canUseCustomRenderer\n ? renderCustomMessage\n : null;\n\n const shouldRenderPlaceholder =\n Boolean(agent?.isRunning) ||\n Boolean(agent?.state && Object.keys(agent.state).length);\n\n const effectiveThreadId = threadId ?? agent?.threadId ?? \"default\";\n let latestUserIndex = -1;\n for (let i = processedMessages.length - 1; i >= 0; i -= 1) {\n if (processedMessages[i].role === \"user\") {\n latestUserIndex = i;\n break;\n }\n }\n const latestUserMessageId =\n latestUserIndex >= 0 ? processedMessages[latestUserIndex].id : undefined;\n const currentRunId = latestUserMessageId\n ? copilotkit.getRunIdForMessage(\n resolvedAgentId,\n effectiveThreadId,\n latestUserMessageId,\n ) || `pending:${latestUserMessageId}`\n : undefined;\n const hasAssistantForCurrentRun =\n latestUserIndex >= 0\n ? processedMessages\n .slice(latestUserIndex + 1)\n .some((msg) => msg.role === \"assistant\")\n : hasAssistantMessages;\n\n // Insert a placeholder assistant message so state snapshots can render before any\n // assistant text exists for the current run.\n if (\n placeholderRenderer &&\n shouldRenderPlaceholder &&\n !hasAssistantForCurrentRun\n ) {\n const placeholderId = currentRunId\n ? `coagent-state-render-${resolvedAgentId}-${currentRunId}`\n : `coagent-state-render-${resolvedAgentId}`;\n const placeholderMessage: Message = {\n id: placeholderId,\n role: \"assistant\",\n content: \"\",\n name: \"coagent-state-render\",\n runId: currentRunId,\n };\n processedMessages = [\n ...processedMessages,\n {\n ...placeholderMessage,\n generativeUIPosition: \"before\" as const,\n generativeUI: () =>\n placeholderRenderer({\n message: placeholderMessage,\n position: \"before\",\n }),\n } as Message,\n ];\n }\n\n return processedMessages;\n }, [\n agent?.messages,\n lazyToolRendered,\n allMessages,\n renderCustomMessage,\n legacyCustomMessageRenderer,\n resolvedAgentId,\n copilotkit,\n agent?.isRunning,\n agent?.state,\n ]);\n\n const renderedSuggestions = useMemo(() => {\n if (Array.isArray(suggestions)) {\n return {\n suggestions: suggestions.map((s) => ({ ...s, isLoading: false })),\n isLoading: false,\n };\n }\n return currentSuggestions;\n }, [suggestions, currentSuggestions]);\n\n // @ts-ignore\n return {\n messages: resolvedMessages,\n sendMessage: latestSendMessageFunc,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n isAvailable: agentAvailable,\n isLoading: Boolean(agent?.isRunning),\n // mcpServers,\n // setMcpServers,\n suggestions: renderedSuggestions.suggestions,\n setSuggestions: (suggestions: Omit<Suggestion, \"isLoading\">[]) =>\n copilotkit.addSuggestionsConfig({ suggestions }),\n generateSuggestions: async () =>\n copilotkit.reloadSuggestions(resolvedAgentId),\n resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),\n isLoadingSuggestions: renderedSuggestions.isLoading,\n interrupt,\n agent,\n threadId,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\ntype LegacyRenderParams = {\n message: Message;\n position: \"before\" | \"after\";\n};\n\ntype LegacyRenderer = ((args: LegacyRenderParams) => any) | null;\n\nfunction useLegacyCoagentRenderer({\n copilotkit,\n agent,\n agentId,\n threadId,\n}: {\n copilotkit: ReturnType<typeof useCopilotKit>[\"copilotkit\"];\n agent?: AbstractAgent;\n agentId: string;\n threadId?: string;\n}): LegacyRenderer {\n return useMemo(() => {\n if (!copilotkit || !agent) {\n return null;\n }\n\n return ({ message, position }: LegacyRenderParams) => {\n const effectiveThreadId = threadId ?? agent.threadId ?? \"default\";\n const providedRunId = (message as any).runId as string | undefined;\n const existingRunId = providedRunId\n ? providedRunId\n : copilotkit.getRunIdForMessage(agentId, effectiveThreadId, message.id);\n const runId = existingRunId || `pending:${message.id}`;\n const messageIndex = Math.max(\n agent.messages.findIndex((msg) => msg.id === message.id),\n 0,\n );\n\n const bridgeProps: CoAgentStateRenderBridgeProps = {\n message: message as any,\n position,\n runId,\n messageIndex,\n messageIndexInRun: 0,\n numberOfMessagesInRun: 1,\n agentId,\n stateSnapshot: (message as any).state,\n };\n\n return createElement(CoAgentStateRenderBridge, bridgeProps) as any;\n };\n }, [agent, agentId, copilotkit, threadId]);\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n","/**\n * `useCopilotChat` is a lightweight React hook for headless chat interactions.\n * Perfect for controlling the prebuilt chat components programmatically.\n *\n * **Open Source Friendly** - Works without requiring a free public license key.\n *\n * <Callout title=\"Looking for fully headless UI?\">\n * Get started with [useCopilotChatHeadless_c](https://docs.copilotkit.ai/reference/v1/hooks/useCopilotChatHeadless_c).\n * </Callout>\n *\n * ## Use Cases\n *\n * - **Programmatic Messaging**: Send messages without displaying chat UI\n * - **Programmatic control**: Control prebuilt component programmatically\n * - **Background Operations**: Trigger AI interactions in the background\n * - **Fire-and-Forget**: Send messages without needing to read responses\n *\n * ## Usage\n *\n * ```tsx\n * import { TextMessage, MessageRole } from \"@copilotkit/runtime-client-gql\";\n *\n * const { appendMessage } = useCopilotChat();\n *\n * // Example usage without naming conflicts\n * const handleSendMessage = async (content: string) => {\n * await appendMessage(\n * new TextMessage({\n * role: MessageRole.User,\n * content,\n * })\n * );\n * };\n * ```\n *\n * ## Return Values\n * The following properties are returned from the hook:\n *\n * <PropertyReference name=\"visibleMessages\" type=\"DeprecatedGqlMessage[]\" deprecated>\n * Array of messages in old non-AG-UI format, use for compatibility only\n * </PropertyReference>\n *\n * <PropertyReference name=\"appendMessage\" type=\"(message: DeprecatedGqlMessage, options?) => Promise<void>\" deprecated>\n * Append message using old format, use `sendMessage` instead\n * </PropertyReference>\n *\n * <PropertyReference name=\"reloadMessages\" type=\"(messageId: string) => Promise<void>\">\n * Regenerate the response for a specific message by ID\n * </PropertyReference>\n *\n * <PropertyReference name=\"stopGeneration\" type=\"() => void\">\n * Stop the current message generation process\n * </PropertyReference>\n *\n * <PropertyReference name=\"reset\" type=\"() => void\">\n * Clear all messages and reset chat state completely\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoading\" type=\"boolean\">\n * Whether the chat is currently generating a response\n * </PropertyReference>\n *\n * <PropertyReference name=\"runChatCompletion\" type=\"() => Promise<Message[]>\">\n * Manually trigger chat completion for advanced usage\n * </PropertyReference>\n *\n * <PropertyReference name=\"mcpServers\" type=\"MCPServerConfig[]\">\n * Array of Model Context Protocol server configurations\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMcpServers\" type=\"(servers: MCPServerConfig[]) => void\">\n * Update MCP server configurations for enhanced context\n * </PropertyReference>\n */\n\nimport {\n UseCopilotChatOptions,\n useCopilotChatInternal,\n UseCopilotChatReturn as UseCopilotChatReturnInternal,\n} from \"./use-copilot-chat_internal\";\n\n// Create a type that excludes message-related properties from the internal type\nexport type UseCopilotChatReturn = Omit<\n UseCopilotChatReturnInternal,\n | \"messages\"\n | \"sendMessage\"\n | \"suggestions\"\n | \"setSuggestions\"\n | \"generateSuggestions\"\n | \"isLoadingSuggestions\"\n | \"resetSuggestions\"\n | \"interrupt\"\n | \"setMessages\"\n | \"deleteMessage\"\n>;\n\n/**\n * A lightweight React hook for headless chat interactions.\n * Perfect for programmatic messaging, background operations, and custom UI implementations.\n *\n * **Open Source Friendly** - Works without requiring a `publicApiKey`.\n */\n// TODO: Do we need this? If so, does it work properly? test.\nexport function useCopilotChat(\n options: UseCopilotChatOptions = {},\n): UseCopilotChatReturn {\n const {\n visibleMessages,\n appendMessage,\n reloadMessages,\n stopGeneration,\n reset,\n isLoading,\n isAvailable,\n runChatCompletion,\n mcpServers,\n setMcpServers,\n } = useCopilotChatInternal(options);\n\n return {\n visibleMessages,\n appendMessage,\n reloadMessages,\n stopGeneration,\n reset,\n isLoading,\n isAvailable,\n runChatCompletion,\n mcpServers,\n setMcpServers,\n };\n}\n","/**\n * `useCopilotChatHeadless_c` is for building fully custom UI (headless UI) implementations.\n *\n * <Callout title=\"This is a premium-only feature\">\n * Sign up for free on [Copilot Cloud](https://cloud.copilotkit.ai) to get your public license key or read more about <a href=\"/premium/overview\">premium features</a>.\n *\n * Usage is generous, **free** to get started, and works with **either self-hosted or Copilot Cloud** environments.\n * </Callout>\n *\n * ## Key Features\n *\n * - **Fully headless**: Build your own fully custom UI's for your agentic applications.\n * - **Advanced Suggestions**: Direct access to suggestions array with full control\n * - **Interrupt Handling**: Support for advanced interrupt functionality\n * - **MCP Server Support**: Model Context Protocol server configurations\n * - **Chat Controls**: Complete set of chat management functions\n * - **Loading States**: Comprehensive loading state management\n *\n *\n * ## Usage\n *\n * ### Basic Setup\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n * import { useCopilotChatHeadless_c } from \"@copilotkit/react-core\";\n *\n * export function App() {\n * return (\n * <CopilotKit publicApiKey=\"your-free-public-license-key\">\n * <YourComponent />\n * </CopilotKit>\n * );\n * }\n *\n * export function YourComponent() {\n * const { messages, sendMessage, isLoading } = useCopilotChatHeadless_c();\n *\n * const handleSendMessage = async () => {\n * await sendMessage({\n * id: \"123\",\n * role: \"user\",\n * content: \"Hello World\",\n * });\n * };\n *\n * return (\n * <div>\n * {messages.map(msg => <div key={msg.id}>{msg.content}</div>)}\n * <button onClick={handleSendMessage} disabled={isLoading}>\n * Send Message\n * </button>\n * </div>\n * );\n * }\n * ```\n *\n * ### Working with Suggestions\n *\n * ```tsx\n * import { useCopilotChatHeadless_c, useCopilotChatSuggestions } from \"@copilotkit/react-core\";\n *\n * export function SuggestionExample() {\n * const {\n * suggestions,\n * setSuggestions,\n * generateSuggestions,\n * isLoadingSuggestions\n * } = useCopilotChatHeadless_c();\n *\n * // Configure AI suggestion generation\n * useCopilotChatSuggestions({\n * instructions: \"Suggest helpful actions based on the current context\",\n * maxSuggestions: 3\n * });\n *\n * return (\n * <div>\n * {suggestions.map(suggestion => (\n * <button key={suggestion.title}>{suggestion.title}</button>\n * ))}\n * <button onClick={generateSuggestions} disabled={isLoadingSuggestions}>\n * Generate Suggestions\n * </button>\n * </div>\n * );\n * }\n * ```\n *\n * ## Return Values\n * The following properties are returned from the hook:\n *\n * <PropertyReference name=\"messages\" type=\"Message[]\">\n * The messages currently in the chat in AG-UI format\n * </PropertyReference>\n *\n * <PropertyReference name=\"sendMessage\" type=\"(message: Message, options?) => Promise<void>\">\n * Send a new message to the chat and trigger AI response\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMessages\" type=\"(messages: Message[] | DeprecatedGqlMessage[]) => void\">\n * Replace all messages in the chat with new array\n * </PropertyReference>\n *\n * <PropertyReference name=\"deleteMessage\" type=\"(messageId: string) => void\">\n * Remove a specific message by ID from the chat\n * </PropertyReference>\n *\n * <PropertyReference name=\"reloadMessages\" type=\"(messageId: string) => Promise<void>\">\n * Regenerate the response for a specific message by ID\n * </PropertyReference>\n *\n * <PropertyReference name=\"stopGeneration\" type=\"() => void\">\n * Stop the current message generation process\n * </PropertyReference>\n *\n * <PropertyReference name=\"reset\" type=\"() => void\">\n * Clear all messages and reset chat state completely\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoading\" type=\"boolean\">\n * Whether the chat is currently generating a response\n * </PropertyReference>\n *\n * <PropertyReference name=\"runChatCompletion\" type=\"() => Promise<Message[]>\">\n * Manually trigger chat completion for advanced usage\n * </PropertyReference>\n *\n * <PropertyReference name=\"mcpServers\" type=\"MCPServerConfig[]\">\n * Array of Model Context Protocol server configurations\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMcpServers\" type=\"(servers: MCPServerConfig[]) => void\">\n * Update MCP server configurations for enhanced context\n * </PropertyReference>\n *\n * <PropertyReference name=\"suggestions\" type=\"SuggestionItem[]\">\n * Current suggestions array for reading or manual control\n * </PropertyReference>\n *\n * <PropertyReference name=\"setSuggestions\" type=\"(suggestions: SuggestionItem[]) => void\">\n * Manually set suggestions for custom workflows\n * </PropertyReference>\n *\n * <PropertyReference name=\"generateSuggestions\" type=\"() => Promise<void>\">\n * Trigger AI-powered suggestion generation using configured settings\n * </PropertyReference>\n *\n * <PropertyReference name=\"resetSuggestions\" type=\"() => void\">\n * Clear all current suggestions and reset generation state\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoadingSuggestions\" type=\"boolean\">\n * Whether suggestions are currently being generated\n * </PropertyReference>\n *\n * <PropertyReference name=\"interrupt\" type=\"string | React.ReactElement | null\">\n * Interrupt content for human-in-the-loop workflows\n * </PropertyReference>\n */\nimport { useEffect } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport {\n useCopilotChatInternal,\n defaultSystemMessage,\n UseCopilotChatOptions as UseCopilotChatOptions_c,\n UseCopilotChatReturn as UseCopilotChatReturn_c,\n MCPServerConfig,\n} from \"./use-copilot-chat_internal\";\n\nimport {\n ErrorVisibility,\n Severity,\n CopilotKitError,\n CopilotKitErrorCode,\n styledConsole,\n} from \"@copilotkit/shared\";\n\n// Non-functional fallback implementation\nconst createNonFunctionalReturn = (): UseCopilotChatReturn_c => ({\n visibleMessages: [],\n messages: [],\n sendMessage: async () => {},\n appendMessage: async () => {},\n setMessages: () => {},\n deleteMessage: () => {},\n reloadMessages: async () => {},\n stopGeneration: () => {},\n reset: () => {},\n isLoading: false,\n isAvailable: false,\n runChatCompletion: async () => [],\n mcpServers: [],\n setMcpServers: () => {},\n suggestions: [],\n setSuggestions: () => {},\n generateSuggestions: async () => {},\n resetSuggestions: () => {},\n isLoadingSuggestions: false,\n interrupt: null,\n});\n/**\n * Enterprise React hook that provides complete chat functionality for fully custom UI implementations.\n * Includes all advanced features like direct message access, suggestions array, interrupt handling, and MCP support.\n *\n * **Requires a publicApiKey** - Sign up for free at https://cloud.copilotkit.ai/\n *\n * @param options - Configuration options for the chat\n * @returns Complete chat interface with all enterprise features\n *\n * @example\n * ```tsx\n * const { messages, sendMessage, suggestions, interrupt } = useCopilotChatHeadless_c();\n * ```\n */\nfunction useCopilotChatHeadless_c(\n options: UseCopilotChatOptions_c = {},\n): UseCopilotChatReturn_c {\n const { copilotApiConfig, setBannerError } = useCopilotContext();\n\n // Check if publicApiKey is available\n const hasPublicApiKey = Boolean(copilotApiConfig.publicApiKey);\n\n // Always call the internal hook (follows rules of hooks)\n const internalResult = useCopilotChatInternal(options);\n\n // Set banner error when no public API key is provided\n useEffect(() => {\n if (!hasPublicApiKey) {\n setBannerError(\n new CopilotKitError({\n message:\n // add link to documentation here\n \"You're using useCopilotChatHeadless_c, a premium-only feature, which offers extensive headless chat capabilities. To continue, you'll need to provide a free public license key.\",\n code: CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,\n severity: Severity.WARNING,\n visibility: ErrorVisibility.BANNER,\n }),\n );\n styledConsole.logCopilotKitPlatformMessage();\n } else {\n setBannerError(null); // Clear banner when API key is provided\n }\n }, [hasPublicApiKey]); // Removed setBannerError dependency\n\n // Return internal result if publicApiKey is available, otherwise return fallback\n if (hasPublicApiKey) {\n return internalResult;\n }\n\n // Return non-functional fallback when no publicApiKey\n return createNonFunctionalReturn();\n}\n\nexport { defaultSystemMessage, useCopilotChatHeadless_c };\nexport type {\n UseCopilotChatOptions_c,\n UseCopilotChatReturn_c,\n MCPServerConfig,\n};\n\nconst noKeyWarning = () => {\n styledConsole.logCopilotKitPlatformMessage();\n};\n","import React, { useEffect, useMemo, useRef } from \"react\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport {\n Parameter,\n getZodParameters,\n MappedParameterTypes,\n} from \"@copilotkit/shared\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport {\n type ReactFrontendTool,\n useFrontendTool as useFrontendToolVNext,\n} from \"../v2\";\n\ntype FrontendToolOptions<T extends Parameter[] | []> = ReactFrontendTool<\n MappedParameterTypes<T>\n>;\ntype FrontendToolRenderArgs<T extends Parameter[] | []> =\n | {\n name: string;\n args: Partial<MappedParameterTypes<T>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n }\n | {\n name: string;\n args: MappedParameterTypes<T>;\n status: ToolCallStatus.Executing;\n result: undefined;\n }\n | {\n name: string;\n args: MappedParameterTypes<T>;\n status: ToolCallStatus.Complete;\n result: string;\n };\n\nexport type UseFrontendToolArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n} & Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\" | \"handler\" | \"followUp\" | \"render\"\n>;\n\nexport function useFrontendTool<const T extends Parameter[] = []>(\n tool: UseFrontendToolArgs<T>,\n dependencies?: any[],\n) {\n const { name, description, parameters, render, followUp, available } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderRef = useRef<typeof render>(render);\n\n useEffect(() => {\n renderRef.current = render;\n }, [render, ...(dependencies ?? [])]);\n\n const normalizedRender: FrontendToolOptions<T>[\"render\"] | undefined =\n useMemo(() => {\n if (typeof render === \"undefined\") {\n return undefined;\n }\n\n return ((args: FrontendToolRenderArgs<T>) => {\n const currentRender = renderRef.current;\n\n if (typeof currentRender === \"undefined\") {\n return null;\n }\n\n if (typeof currentRender === \"string\") {\n return React.createElement(React.Fragment, null, currentRender);\n }\n\n const renderArgs = {\n ...args,\n result:\n typeof args.result === \"string\"\n ? parseJson(args.result, args.result)\n : args.result,\n } as ActionRenderProps<T>;\n\n const rendered = currentRender(renderArgs);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n }) as FrontendToolOptions<T>[\"render\"];\n }, []);\n\n // Handler ref to avoid stale closures\n const handlerRef = useRef<typeof tool.handler>(tool.handler);\n\n useEffect(() => {\n handlerRef.current = tool.handler;\n }, [tool.handler, ...(dependencies ?? [])]);\n\n const normalizedHandler = tool.handler\n ? (args: MappedParameterTypes<T>) => handlerRef.current?.(args)\n : undefined;\n\n useFrontendToolVNext<MappedParameterTypes<T>>({\n name,\n description,\n parameters: zodParameters,\n handler: normalizedHandler,\n followUp,\n render: normalizedRender,\n available: available === undefined ? undefined : available !== \"disabled\",\n });\n}\n","import { type Parameter, getZodParameters } from \"@copilotkit/shared\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { defineToolCallRenderer, useCopilotKit } from \"../v2\";\nimport type React from \"react\";\nimport { useEffect, useRef } from \"react\";\nimport {\n type ActionRenderProps,\n type ActionRenderPropsNoArgs,\n ActionRenderPropsWait,\n type FrontendAction,\n} from \"../types\";\n\ntype ToolCallRendererDefinition = Parameters<typeof defineToolCallRenderer>[0];\n\nexport type UseRenderToolCallArgs<T extends Parameter[] | [] = []> = Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\"\n> & {\n available?: \"disabled\" | \"enabled\";\n render: T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => React.ReactElement\n : (props: ActionRenderProps<T>) => React.ReactElement;\n};\n\nexport function useRenderToolCall<const T extends Parameter[] | [] = []>(\n tool: UseRenderToolCallArgs<T>,\n dependencies?: any[],\n) {\n const { copilotkit } = useCopilotKit();\n\n // Track whether we've already added this renderer to avoid duplicates\n const hasAddedRef = useRef(false);\n\n useEffect(() => {\n const { name, parameters, render } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderToolCall =\n name === \"*\"\n ? defineToolCallRenderer({\n name: \"*\",\n render: ((args) => {\n return render({\n ...args,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n })\n : defineToolCallRenderer({\n name,\n args: zodParameters,\n render: ((args) => {\n return render({\n ...args,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n });\n\n // Remove any existing renderer with the same name\n const existingIndex = copilotkit.renderToolCalls.findIndex(\n (r) => r.name === name,\n );\n if (existingIndex !== -1) {\n copilotkit.renderToolCalls.splice(existingIndex, 1);\n }\n\n // Add the new renderer\n copilotkit.renderToolCalls.push(renderToolCall);\n hasAddedRef.current = true;\n\n // Cleanup: remove this renderer when the component unmounts or tool changes\n return () => {\n if (hasAddedRef.current) {\n const index = copilotkit.renderToolCalls.findIndex(\n (r) => r.name === name,\n );\n if (index !== -1) {\n copilotkit.renderToolCalls.splice(index, 1);\n }\n hasAddedRef.current = false;\n }\n };\n }, [tool, ...(dependencies ?? [])]);\n}\n","import {\n ActionRenderProps,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types\";\nimport {\n CopilotKitError,\n CopilotKitErrorCode,\n MappedParameterTypes,\n Parameter,\n getZodParameters,\n parseJson,\n} from \"@copilotkit/shared\";\nimport { useHumanInTheLoop as useHumanInTheLoopVNext } from \"../v2\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport React, {\n ComponentType,\n FunctionComponent,\n useEffect,\n useRef,\n} from \"react\";\n\ntype HumanInTheLoopOptions = Parameters<typeof useHumanInTheLoopVNext>[0];\ntype HumanInTheLoopRender = HumanInTheLoopOptions[\"render\"];\ntype HumanInTheLoopRenderArgs = HumanInTheLoopRender extends (\n props: infer P,\n) => any\n ? P\n : never;\n\nexport type UseHumanInTheLoopArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n render: FrontendAction<T>[\"renderAndWaitForResponse\"];\n followUp?: FrontendAction<T>[\"followUp\"];\n} & Pick<FrontendAction<T>, \"name\" | \"description\" | \"parameters\">;\n\ntype HitlRendererArgs =\n | {\n name: string;\n description: string;\n args: Partial<Record<string, unknown>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n respond: undefined;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Executing;\n result: undefined;\n respond: (result: unknown) => Promise<void>;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Complete;\n result: string;\n respond: undefined;\n };\ntype HitlRenderer = FunctionComponent<HitlRendererArgs>;\n\nexport function useHumanInTheLoop<const T extends Parameter[] | [] = []>(\n tool: UseHumanInTheLoopArgs<T>,\n dependencies?: any[],\n) {\n const { render, ...toolRest } = tool;\n const { name, description, parameters, followUp } = toolRest;\n const zodParameters = getZodParameters(parameters);\n const renderRef = useRef<HitlRenderer | null>(null);\n\n useEffect(() => {\n renderRef.current = (args: HitlRendererArgs): React.ReactElement | null => {\n if (typeof render === \"string\") {\n return React.createElement(React.Fragment, null, render);\n }\n\n if (!render) {\n return null;\n }\n\n const renderProps: ActionRenderPropsWait<T> = (() => {\n const mappedArgs = args.args as unknown as MappedParameterTypes<T>;\n\n switch (args.status) {\n case ToolCallStatus.InProgress:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: undefined,\n };\n case ToolCallStatus.Executing:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: () => {},\n };\n case ToolCallStatus.Complete:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n handler: undefined,\n };\n default:\n throw new CopilotKitError({\n code: CopilotKitErrorCode.UNKNOWN,\n message: `Invalid tool call status: ${(args as unknown as { status: string }).status}`,\n });\n }\n })();\n\n const rendered = render(renderProps);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n };\n }, [render, ...(dependencies ?? [])]);\n\n useHumanInTheLoopVNext({\n name,\n description,\n followUp,\n parameters: zodParameters,\n render: ((args: HumanInTheLoopRenderArgs) =>\n renderRef.current?.(args as HitlRendererArgs) ??\n null) as HumanInTheLoopOptions[\"render\"],\n });\n}\n","/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { useEffect, useRef, useState } from \"react\";\nimport { Parameter } from \"@copilotkit/shared\";\nimport {\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport { useFrontendTool, UseFrontendToolArgs } from \"./use-frontend-tool\";\nimport {\n useRenderToolCall,\n UseRenderToolCallArgs,\n} from \"./use-render-tool-call\";\nimport {\n useHumanInTheLoop,\n UseHumanInTheLoopArgs,\n} from \"./use-human-in-the-loop\";\nimport { useCopilotContext } from \"../context\";\n\n// Helper to determine which component and action config to use\nfunction getActionConfig<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n) {\n if (action.name === \"*\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n\n if (\"renderAndWaitForResponse\" in action || \"renderAndWait\" in action) {\n let render = action.render;\n if (!render && \"renderAndWaitForResponse\" in action) {\n // @ts-expect-error -- renderAndWaitForResponse is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWaitForResponse;\n }\n if (!render && \"renderAndWait\" in action) {\n // @ts-expect-error -- renderAndWait is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWait;\n }\n\n return {\n type: \"hitl\" as const,\n action: { ...action, render } as UseHumanInTheLoopArgs<T>,\n };\n }\n\n if (\"available\" in action) {\n if (action.available === \"enabled\" || action.available === \"remote\") {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n if (action.available === \"frontend\" || action.available === \"disabled\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n }\n\n if (\"handler\" in action) {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n\n throw new Error(\"Invalid action configuration\");\n}\n\n/**\n * useCopilotAction is a legacy hook maintained for backwards compatibility.\n *\n * To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),\n * we use a registration pattern:\n * 1. This hook registers the action configuration with the CopilotContext\n * 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper\n * 3. React properly manages hook state since components are rendered, not conditionally called\n *\n * This allows action types to change between renders without corrupting React's hook state.\n */\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const [initialActionConfig] = useState(getActionConfig(action));\n const currentActionConfig = getActionConfig(action);\n\n /**\n * Calling hooks conditionally violates React's Rules of Hooks. This rule exists because\n * React maintains the call stack for hooks like useEffect or useState, and conditionally\n * calling a hook would result in inconsistent call stacks between renders.\n *\n * Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the\n * supplied parameters. In order to avoid breaking React's call stack tracking, while\n * breaking the Rule of Hooks, we use a ref to store the initial action configuration\n * and throw an error if the _configuration_ changes such that we would call a different hook.\n */\n if (initialActionConfig.type !== currentActionConfig.type) {\n throw new Error(\"Action configuration changed between renders\");\n }\n\n switch (currentActionConfig.type) {\n case \"render\":\n return useRenderToolCall(currentActionConfig.action, dependencies);\n case \"hitl\":\n return useHumanInTheLoop(currentActionConfig.action, dependencies);\n case \"frontend\":\n return useFrontendTool(currentActionConfig.action, dependencies);\n default:\n throw new Error(\"Invalid action configuration\");\n }\n}\n","/**\n * The useCoAgentStateRender hook allows you to render UI or text based components on a Agentic Copilot's state in the chat.\n * This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgentStateRender } from \"@copilotkit/react-core\";\n *\n * type YourAgentState = {\n * agent_state_property: string;\n * }\n *\n * useCoAgentStateRender<YourAgentState>({\n * name: \"basic_agent\",\n * nodeName: \"optionally_specify_a_specific_node\",\n * render: ({ status, state, nodeName }) => {\n * return (\n * <YourComponent\n * agentStateProperty={state.agent_state_property}\n * status={status}\n * nodeName={nodeName}\n * />\n * );\n * },\n * });\n * ```\n *\n * This allows for you to render UI components or text based on what is happening within the agent.\n *\n * ### Example\n * A great example of this is in our Perplexity Clone where we render the progress of an agent's internet search as it is happening.\n * You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).\n *\n * <Callout type=\"info\">\n * This example is hosted on Vercel and may take a few seconds to load.\n * </Callout>\n *\n * <iframe src=\"https://examples-coagents-ai-researcher-ui.vercel.app/\" className=\"w-full rounded-lg border h-[700px] my-4\" />\n */\n\nimport { useRef, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { randomId, CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCoAgentStateRenders } from \"../context/coagent-state-renders-context\";\n\n/**\n * This hook is used to render agent state with custom UI components or text. This is particularly\n * useful for showing intermediate state or progress during Agentic Copilot operations.\n * To get started using rendering intermediate state through this hook, checkout the documentation.\n *\n * https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates\n */\n\n// We implement useCoAgentStateRender dependency handling so that\n// the developer has the option to not provide any dependencies.\n// see useCopilotAction for more details about this approach.\nexport function useCoAgentStateRender<T = any>(\n action: CoAgentStateRender<T>,\n dependencies?: any[],\n): void {\n const { chatComponentsCache, availableAgents } = useContext(CopilotContext);\n const {\n setCoAgentStateRender,\n removeCoAgentStateRender,\n coAgentStateRenders,\n } = useCoAgentStateRenders();\n const idRef = useRef<string>(randomId());\n const { setBannerError, addToast } = useToast();\n\n useEffect(() => {\n if (\n availableAgents?.length &&\n !availableAgents.some((a) => a.name === action.name)\n ) {\n const message = `(useCoAgentStateRender): Agent \"${action.name}\" not found. Make sure the agent exists and is properly configured.`;\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: action.name,\n availableAgents: availableAgents.map((a) => ({\n name: a.name,\n id: a.id,\n })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coAgentStateRenders[idRef.current]) {\n coAgentStateRenders[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n // Check for duplicates by comparing against all other actions\n const currentId = idRef.current;\n const hasDuplicate = Object.entries(coAgentStateRenders).some(\n ([id, otherAction]) => {\n // Skip comparing with self\n if (id === currentId) return false;\n\n // Different agent names are never duplicates\n if (otherAction.name !== action.name) return false;\n\n // Same agent names:\n const hasNodeName = !!action.nodeName;\n const hasOtherNodeName = !!otherAction.nodeName;\n\n // If neither has nodeName, they're duplicates\n if (!hasNodeName && !hasOtherNodeName) return true;\n\n // If one has nodeName and other doesn't, they're not duplicates\n if (hasNodeName !== hasOtherNodeName) return false;\n\n // If both have nodeName, they're duplicates only if the names match\n return action.nodeName === otherAction.nodeName;\n },\n );\n\n if (hasDuplicate) {\n const message = action.nodeName\n ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden`\n : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;\n\n addToast({\n type: \"warning\",\n message,\n id: `dup-action-${action.name}`,\n });\n }\n }, [coAgentStateRenders]);\n\n useEffect(() => {\n setCoAgentStateRender(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n return () => {\n removeCoAgentStateRender(idRef.current);\n };\n }, [\n setCoAgentStateRender,\n removeCoAgentStateRender,\n action.name,\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n","import { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useCopilotContext();\n const idRef = useRef<string>(undefined!);\n\n useEffect(() => {\n const id = addDocumentContext(document, categories);\n idRef.current = id;\n\n return () => {\n removeDocumentContext(id);\n };\n }, [addDocumentContext, removeDocumentContext, ...dependencies]);\n\n return idRef.current;\n}\n","/**\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotReadable accepts a single string argument\n * representing any piece of app state, making it available for the Copilot to use\n * as context when responding to user input.\n *\n * ```tsx\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotReadable({\n * description: \"The list of employees\",\n * value: employees,\n * });\n * }\n * ```\n *\n * ### Nested Components\n *\n * Optionally, you can maintain the hierarchical structure of information by passing\n * `parentId`. This allows you to use `useCopilotReadable` in nested components:\n *\n * ```tsx /employeeContextId/1 {17,23}\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * function Employee(props: EmployeeProps) {\n * const { employeeName, workProfile, metadata } = props;\n *\n * // propagate any information to copilot\n * const employeeContextId = useCopilotReadable({\n * description: \"Employee name\",\n * value: employeeName\n * });\n *\n * // Pass a parentID to maintain a hierarchical structure.\n * // Especially useful with child React components, list elements, etc.\n * useCopilotReadable({\n * description: \"Work profile\",\n * value: workProfile.description(),\n * parentId: employeeContextId\n * });\n *\n * useCopilotReadable({\n * description: \"Employee metadata\",\n * value: metadata.description(),\n * parentId: employeeContextId\n * });\n *\n * return (\n * // Render as usual...\n * );\n * }\n * ```\n */\nimport { useCopilotKit } from \"../v2\";\nimport { useEffect, useRef } from \"react\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context. Object values are automatically stringified.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * Whether the context is available to the Copilot.\n */\n available?: \"enabled\" | \"disabled\";\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n { description, value, convert, available }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { copilotkit } = useCopilotKit();\n const ctxIdRef = useRef<string | undefined>(undefined);\n useEffect(() => {\n if (!copilotkit) return;\n\n const found = Object.entries(copilotkit.context).find(([id, ctxItem]) => {\n return JSON.stringify({ description, value }) == JSON.stringify(ctxItem);\n });\n if (found) {\n ctxIdRef.current = found[0];\n if (available === \"disabled\") copilotkit.removeContext(ctxIdRef.current);\n return;\n }\n if (!found && available === \"disabled\") return;\n\n ctxIdRef.current = copilotkit.addContext({\n description,\n value: (convert ?? JSON.stringify)(value),\n });\n\n return () => {\n if (!ctxIdRef.current) return;\n copilotkit.removeContext(ctxIdRef.current);\n };\n }, [description, value, convert]);\n\n return ctxIdRef.current;\n}\n","import { useEffect, useRef } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgent } from \"../v2\";\n\nexport function useAgentNodeName(agentName?: string) {\n const { agent } = useAgent({ agentId: agentName });\n const nodeNameRef = useRef<string>(\"start\");\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStepStartedEvent: ({ event }) => {\n nodeNameRef.current = event.stepName;\n },\n onRunStartedEvent: () => {\n nodeNameRef.current = \"start\";\n },\n onRunFinishedEvent: () => {\n nodeNameRef.current = \"end\";\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent]);\n\n return nodeNameRef.current;\n}\n","/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Message } from \"@copilotkit/shared\";\nimport { useAgent, useCopilotKit } from \"../v2\";\nimport { type AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<\n T,\n> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (...args: any[]) => Promise<any>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(\n options: UseCoagentOptions<T>,\n): UseCoagentReturnType<T> {\n const { agent } = useAgent({ agentId: options.name });\n const { copilotkit } = useCopilotKit();\n const nodeName = useAgentNodeName(options.name);\n\n const handleStateUpdate = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n if (!agent) return;\n\n if (typeof newState === \"function\") {\n const updater = newState as (prevState: T | undefined) => T;\n agent.setState(updater(agent.state));\n } else {\n agent.setState({ ...agent.state, ...newState });\n }\n },\n [agent?.state, agent?.setState],\n );\n\n useEffect(() => {\n if (!options.config && !options.configurable) return;\n\n let config = options.config ?? {};\n if (options.configurable) {\n config = {\n ...config,\n configurable: {\n ...options.configurable,\n ...config.configurable,\n },\n };\n }\n copilotkit.setProperties(config);\n }, [options.config, options.configurable]);\n\n const externalStateStr = useMemo(\n () =>\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : undefined,\n [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : undefined,\n ],\n );\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (\n agent?.state &&\n isExternalStateManagement(options) &&\n JSON.stringify(options.state) !== JSON.stringify(agent.state)\n ) {\n handleStateUpdate(options.state);\n }\n }, [agent, externalStateStr, handleStateUpdate]);\n\n const hasStateValues = useCallback((value?: Record<string, any>) => {\n return Boolean(value && Object.keys(value).length);\n }, []);\n\n const initialStateRef = useRef<any>(\n isExternalStateManagement(options)\n ? options.state\n : \"initialState\" in options\n ? options.initialState\n : undefined,\n );\n\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n initialStateRef.current = options.state;\n } else if (\"initialState\" in options) {\n initialStateRef.current = options.initialState;\n }\n }, [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : \"initialState\" in options\n ? JSON.stringify(options.initialState)\n : undefined,\n ]);\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStateChanged: (args: any) => {\n if (isExternalStateManagement(options)) {\n options.setState(args.state);\n }\n },\n onRunInitialized: (args: any) => {\n const runHasState = hasStateValues(args.state);\n if (runHasState) {\n handleStateUpdate(args.state);\n return;\n }\n\n if (hasStateValues(agent.state)) {\n return;\n }\n\n if (initialStateRef.current !== undefined) {\n handleStateUpdate(initialStateRef.current);\n }\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent, handleStateUpdate, hasStateValues]);\n\n // Return a consistent shape whether or not the agent is available\n return useMemo<UseCoagentReturnType<T>>(() => {\n if (!agent) {\n const noop = () => {};\n const noopAsync = async () => {};\n const initialState =\n // prefer externally provided state if available\n (\"state\" in options && (options as any).state) ??\n // then initialState if provided\n (\"initialState\" in options && (options as any).initialState) ??\n ({} as T);\n return {\n name: options.name,\n nodeName,\n threadId: undefined,\n running: false,\n state: initialState as T,\n setState: noop,\n start: noop,\n stop: noop,\n run: noopAsync,\n };\n }\n\n return {\n name: agent?.agentId ?? options.name,\n nodeName,\n threadId: agent.threadId,\n running: agent.isRunning,\n state: agent.state,\n setState: handleStateUpdate,\n // TODO: start and run both have same thing. need to figure out\n start: agent.runAgent,\n stop: agent.abortRun,\n run: agent.runAgent,\n };\n }, [\n agent?.state,\n agent?.runAgent,\n agent?.abortRun,\n agent?.runAgent,\n agent?.threadId,\n agent?.isRunning,\n agent?.agentId,\n handleStateUpdate,\n options.name,\n ]);\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n","import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo, useRef } from \"react\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n CopilotErrorHandler,\n CopilotErrorEvent,\n} from \"@copilotkit/shared\";\nimport { shouldShowDevConsole } from \"../utils/dev-console\";\n\nexport interface CopilotRuntimeClientHookOptions extends CopilotRuntimeClientOptions {\n showDevConsole?: boolean;\n onError: CopilotErrorHandler;\n}\n\nexport const useCopilotRuntimeClient = (\n options: CopilotRuntimeClientHookOptions,\n) => {\n const { setBannerError } = useToast();\n const { showDevConsole, onError, ...runtimeOptions } = options;\n\n // Deduplication state for structured errors\n const lastStructuredErrorRef = useRef<{\n message: string;\n timestamp: number;\n } | null>(null);\n\n // Helper function to trace UI errors\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\n try {\n const errorEvent: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"ui\",\n request: {\n operation: \"runtimeClient\",\n url: runtimeOptions.url,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent:\n typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : undefined,\n stackTrace:\n originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onError(errorEvent);\n } catch (error) {\n console.error(\"Error in onError handler:\", error);\n }\n };\n\n const runtimeClient = useMemo(() => {\n return new CopilotRuntimeClient({\n ...runtimeOptions,\n handleGQLErrors: (error) => {\n if ((error as any).graphQLErrors?.length) {\n const graphQLErrors = (error as any).graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // All errors (including DEV_ONLY) show as banners for consistency\n // Deduplicate to prevent spam\n const now = Date.now();\n const errorMessage = gqlError.message;\n if (\n lastStructuredErrorRef.current &&\n lastStructuredErrorRef.current.message === errorMessage &&\n now - lastStructuredErrorRef.current.timestamp < 150\n ) {\n return; // Skip duplicate\n }\n lastStructuredErrorRef.current = {\n message: errorMessage,\n timestamp: now,\n };\n\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the error\n traceUIError(ckError, gqlError);\n // TODO: if onError & renderError should work without key, insert here\n } else {\n // Fallback for unstructured errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n // TODO: if onError & renderError should work without key, insert here\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n // TODO: if onError & renderError should work without key, insert here\n }\n },\n handleGQLWarning: (message: string) => {\n console.warn(message);\n // Show warnings as banners too for consistency\n const warningError = new CopilotKitError({\n message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(warningError);\n },\n });\n }, [runtimeOptions, setBannerError, onError]);\n\n return runtimeClient;\n};\n\n// Create appropriate structured error from GraphQL error\nfunction createStructuredError(gqlError: GraphQLError): CopilotKitError | null {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n // Legacy error detection by stack trace\n if (originalError?.stack?.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message });\n }\n if (\n originalError?.stack?.includes(\"CopilotKitRemoteEndpointDiscoveryError\")\n ) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n\n return null;\n}\n","import { Parameter } from \"@copilotkit/shared\";\nimport { Fragment, useCallback, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { FrontendAction, ActionRenderProps } from \"../types/frontend-action\";\nimport { useCopilotAction } from \"./use-copilot-action\";\nimport React from \"react\";\n\n/**\n * Hook to create an authenticated action that requires user sign-in before execution.\n *\n * @remarks\n * This feature is only available when using CopilotKit's hosted cloud service.\n * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.\n *\n * @param action - The frontend action to be wrapped with authentication\n * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed\n */\nexport function useCopilotAuthenticatedAction_c<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();\n const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);\n\n const executeAction = useCallback(\n (props: ActionRenderProps<Parameter[]>) => {\n if (typeof action.render === \"function\") {\n return action.render(props);\n }\n return action.render || React.createElement(Fragment);\n },\n [action],\n );\n\n const wrappedRender = useCallback(\n (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {\n const isAuthenticated = Object.values(authStates_c || {}).some(\n (state) => state.status === \"authenticated\",\n );\n\n if (!isAuthenticated) {\n // Store action details for later execution\n pendingActionRef.current = props;\n\n return authConfig_c?.SignInComponent\n ? React.createElement(authConfig_c.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates_c?.((prev) => ({\n ...prev,\n [action.name]: authState,\n }));\n if (pendingActionRef.current) {\n executeAction(pendingActionRef.current);\n pendingActionRef.current = null;\n }\n },\n })\n : React.createElement(Fragment);\n }\n\n return executeAction(props);\n },\n [action, authStates_c, setAuthStates_c],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\n}\n","import React, { useCallback, useRef } from \"react\";\nimport { LangGraphInterruptRender } from \"../types/interrupt-action\";\nimport { useInterrupt, useCopilotChatConfiguration } from \"../v2\";\nimport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n} from \"../v2\";\nimport { MetaEventName } from \"@copilotkit/runtime-client-gql\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\nimport type { AgentSession } from \"../context/copilot-context\";\n\n/**\n * Transforms a v2 InterruptEvent into the v1 LangGraphInterruptEvent shape\n * expected by existing useLangGraphInterrupt callbacks.\n */\nfunction toV1Event<TEventValue>(event: InterruptEvent<TEventValue>) {\n const value =\n typeof event.value === \"string\"\n ? parseJson(event.value, event.value)\n : event.value;\n return {\n name: MetaEventName.LangGraphInterruptEvent,\n type: \"MetaEvent\" as const,\n value,\n };\n}\n\nexport function useLangGraphInterrupt<TEventValue = any>(\n action: Omit<LangGraphInterruptRender<TEventValue>, \"id\">,\n _dependencies?: any[],\n) {\n const actionRef = useRef(action);\n // Update ref synchronously during render so it's always current\n // when callbacks read from it (useEffect would be one tick late).\n actionRef.current = action;\n\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId =\n action.agentId ?? existingConfig?.agentId ?? \"default\";\n const threadId = existingConfig?.threadId;\n const nodeName = useAgentNodeName(resolvedAgentId);\n\n // Keep agentMetadata in a ref so stable callbacks always see current values.\n const metadataRef = useRef<AgentSession>({\n agentName: resolvedAgentId,\n threadId,\n nodeName,\n });\n metadataRef.current = {\n agentName: resolvedAgentId,\n threadId,\n nodeName,\n };\n\n // Stable callback references that always read the latest action from the ref.\n // This prevents useInterrupt's internal useMemo/useEffect from seeing new\n // function identities on every render, which would cause an infinite loop.\n const render = useCallback(\n ({ event, result, resolve }: InterruptRenderProps<TEventValue>) => {\n const renderFn = actionRef.current.render;\n if (!renderFn) return React.createElement(React.Fragment);\n const rendered = renderFn({\n event: toV1Event(event) as any,\n result,\n resolve: (r) => resolve(r),\n });\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n return rendered;\n },\n [],\n );\n\n // Handler always delegates to the ref — if no handler is set at call time,\n // the optional chaining returns undefined which useInterrupt treats as null.\n const handler = useCallback(\n ({ event, resolve }: InterruptHandlerProps<TEventValue>) => {\n return actionRef.current.handler?.({\n event: toV1Event(event) as any,\n resolve: (r) => resolve(r),\n });\n },\n [],\n );\n\n const enabled = useCallback((event: InterruptEvent<TEventValue>) => {\n if (!actionRef.current.enabled) return true;\n return actionRef.current.enabled({\n eventValue: toV1Event(event).value,\n agentMetadata: metadataRef.current,\n });\n }, []);\n\n useInterrupt({\n render,\n handler,\n enabled,\n agentId: resolvedAgentId,\n });\n}\n","/**\n * `useCopilotAdditionalInstructions` is a React hook that provides additional instructions\n * to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotAdditionalInstructions accepts a single string argument\n * representing the instructions to be added to the Copilot.\n *\n * ```tsx\n * import { useCopilotAdditionalInstructions } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * useCopilotAdditionalInstructions({\n * instructions: \"Do not answer questions about the weather.\",\n * });\n * }\n * ```\n *\n * ### Conditional Usage\n *\n * You can also conditionally add instructions based on the state of your app.\n *\n * ```tsx\n * import { useCopilotAdditionalInstructions } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [showInstructions, setShowInstructions] = useState(false);\n *\n * useCopilotAdditionalInstructions({\n * available: showInstructions ? \"enabled\" : \"disabled\",\n * instructions: \"Do not answer questions about the weather.\",\n * });\n * }\n * ```\n */\nimport { useEffect } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\n\n/**\n * Options for the useCopilotAdditionalInstructions hook.\n */\nexport interface UseCopilotAdditionalInstructionsOptions {\n /**\n * The instructions to be added to the Copilot. Will be added to the instructions like so:\n *\n * ```txt\n * You are a helpful assistant.\n * Additionally, follow these instructions:\n * - Do not answer questions about the weather.\n * - Do not answer questions about the stock market.\n * ```\n */\n instructions: string;\n\n /**\n * Whether the instructions are available to the Copilot.\n */\n available?: \"enabled\" | \"disabled\";\n}\n\n/**\n * Adds the given instructions to the Copilot context.\n */\nexport function useCopilotAdditionalInstructions(\n {\n instructions,\n available = \"enabled\",\n }: UseCopilotAdditionalInstructionsOptions,\n dependencies?: any[],\n) {\n const { setAdditionalInstructions } = useCopilotContext();\n\n useEffect(() => {\n if (available === \"disabled\") return;\n\n setAdditionalInstructions((prevInstructions) => [\n ...(prevInstructions || []),\n instructions,\n ]);\n\n return () => {\n setAdditionalInstructions(\n (prevInstructions) =>\n prevInstructions?.filter(\n (instruction) => instruction !== instructions,\n ) || [],\n );\n };\n }, [\n available,\n instructions,\n setAdditionalInstructions,\n ...(dependencies || []),\n ]);\n}\n","import { useCopilotAction } from \"./use-copilot-action\";\nimport { CatchAllFrontendAction } from \"../types/frontend-action\";\n\nexport function useDefaultTool(\n tool: Omit<CatchAllFrontendAction, \"name\">,\n dependencies?: any[],\n) {\n // Use the existing useCopilotAction hook\n useCopilotAction(\n { ...tool, name: \"*\" } satisfies CatchAllFrontendAction,\n dependencies,\n );\n}\n","/**\n * <Callout type=\"warning\">\n * useCopilotChatSuggestions is experimental. The interface is not final and\n * can change without notice.\n * </Callout>\n *\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * <br/>\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-chat-suggestions/use-copilot-chat-suggestions.gif\" width=\"500\" />\n *\n * ## Usage\n *\n * ### Install Dependencies\n *\n * This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.\n *\n * ```shell npm2yarn \\\"@copilotkit/react-ui\"\\\n * npm install @copilotkit/react-core @copilotkit/react-ui\n * ```\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChatSuggestions } from \"@copilotkit/react-ui\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotChatSuggestions({\n * instructions: `The following employees are on duty: ${JSON.stringify(employees)}`,\n * });\n * }\n * ```\n *\n * ### Dependency Management\n *\n * ```tsx\n * import { useCopilotChatSuggestions } from \"@copilotkit/react-ui\";\n *\n * export function MyComponent() {\n * useCopilotChatSuggestions(\n * {\n * instructions: \"Suggest the most relevant next actions.\",\n * },\n * [appState],\n * );\n * }\n * ```\n *\n * In the example above, the suggestions are generated based on the given instructions.\n * The hook monitors `appState`, and updates suggestions accordingly whenever it changes.\n *\n * ### Behavior and Lifecycle\n *\n * The hook registers the configuration with the chat context upon component mount and\n * removes it on unmount, ensuring a clean and efficient lifecycle management.\n */\nimport {\n useConfigureSuggestions,\n useCopilotChatConfiguration,\n useCopilotKit,\n useSuggestions,\n} from \"../v2\";\nimport { useEffect } from \"react\";\nimport { StaticSuggestionsConfig, Suggestion } from \"@copilotkit/core\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> &\n Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<\n StaticSuggestionsConfig,\n \"suggestions\"\n> & {\n suggestions: StaticSuggestionInput[];\n};\n\ntype DynamicSuggestionsConfigInput = {\n /**\n * A prompt or instructions for the GPT to generate suggestions.\n */\n instructions: string;\n /**\n * The minimum number of suggestions to generate. Defaults to `1`.\n * @default 1\n */\n minSuggestions?: number;\n /**\n * The maximum number of suggestions to generate. Defaults to `3`.\n * @default 1\n */\n maxSuggestions?: number;\n\n /**\n * Whether the suggestions are available. Defaults to `enabled`.\n * @default enabled\n */\n available?:\n | \"enabled\"\n | \"disabled\"\n | \"always\"\n | \"before-first-message\"\n | \"after-first-message\";\n\n /**\n * An optional class name to apply to the suggestions.\n */\n className?: string;\n};\n\nexport type UseCopilotChatSuggestionsConfiguration =\n | DynamicSuggestionsConfigInput\n | StaticSuggestionsConfigInput;\n\nexport function useCopilotChatSuggestions(\n config: UseCopilotChatSuggestionsConfiguration,\n dependencies: any[] = [],\n) {\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n\n const available =\n (config.available === \"enabled\" ? \"always\" : config.available) ??\n \"before-first-message\";\n\n const finalSuggestionConfig = {\n ...config,\n available,\n consumerAgentId: resolvedAgentId, // Use chatConfig.agentId here\n };\n useConfigureSuggestions(finalSuggestionConfig, dependencies);\n}\n","import { ActionInputAvailability } from \"@copilotkit/runtime-client-gql\";\nimport {\n Action,\n Parameter,\n MappedParameterTypes,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingState<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: any;\n}\n\ninterface InProgressStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n}\n\nexport type ActionRenderProps<T extends Parameter[] | [] = []> =\n | CompleteState<T>\n | ExecutingState<T>\n | InProgressState<T>;\n\nexport type ActionRenderPropsNoArgs<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgs<T>\n | ExecutingStateNoArgs<T>\n | InProgressStateNoArgs<T>;\n\nexport type ActionRenderPropsWait<T extends Parameter[] | [] = []> =\n | CompleteStateWait<T>\n | ExecutingStateWait<T>\n | InProgressStateWait<T>;\n\nexport type ActionRenderPropsNoArgsWait<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgsWait<T>\n | ExecutingStateNoArgsWait<T>\n | InProgressStateNoArgsWait<T>;\n\nexport type CatchAllActionRenderProps<T extends Parameter[] | [] = []> =\n | (CompleteState<T> & {\n name: string;\n })\n | (ExecutingState<T> & {\n name: string;\n })\n | (InProgressState<T> & {\n name: string;\n });\n\nexport type FrontendActionAvailability =\n | \"disabled\"\n | \"enabled\"\n | \"remote\"\n | \"frontend\";\n\nexport type FrontendAction<\n T extends Parameter[] | [] = [],\n N extends string = string,\n> = Action<T> & {\n name: Exclude<N, \"*\">;\n /**\n * @deprecated Use `available` instead.\n */\n disabled?: boolean;\n available?: FrontendActionAvailability;\n pairedAction?: string;\n followUp?: boolean;\n} & (\n | {\n render?:\n | string\n | (T extends []\n ? (\n props: ActionRenderPropsNoArgs<T>,\n ) => string | React.ReactElement\n : (props: ActionRenderProps<T>) => string | React.ReactElement);\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: never;\n renderAndWaitForResponse?: never;\n }\n | {\n render?: never;\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n renderAndWaitForResponse?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n handler?: never;\n }\n );\n\nexport type CatchAllFrontendAction = {\n name: \"*\";\n render: (props: CatchAllActionRenderProps<any>) => React.ReactElement;\n};\n\nexport type RenderFunctionStatus = ActionRenderProps<any>[\"status\"];\n\nexport function processActionsForRuntimeRequest(\n actions: FrontendAction<any>[],\n) {\n const filteredActions = actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled &&\n action.disabled !== true &&\n action.name !== \"*\" &&\n action.available != \"frontend\" &&\n !action.pairedAction,\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined =\n ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(\n actionParametersToJsonSchema(action.parameters || []),\n ),\n available,\n };\n });\n return filteredActions;\n}\n","/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/v1/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/v1/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/examples/v1/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport {\n FrontendAction,\n processActionsForRuntimeRequest,\n} from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n private forwardedParameters?: ForwardedParametersInput;\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n this.forwardedParameters = config.forwardedParameters;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions\n ? Object.assign({}, context.actions)\n : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString =\n (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString(\n [],\n defaultCopilotContextCategories,\n );\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(\n filterAgentStateMessages(messages),\n ),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n toolChoice: \"required\",\n ...(this.forwardedParameters ?? {}),\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(\n contextString: string,\n instructions: string,\n): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAaA,MAAa,2BAA2B;EACtC,sBAAsB;EACtB,4CAA4C;EAC5C,6CAA6C;EAC7C,6CAA6C;EAC7C,gCAAgC;EAChC,kCAAkC;EAClC,sCAAsC;EACtC,4CAA4C;EAC5C,yCAAyC;EACzC,sCAAsC;EACtC,wCAAwC;EACxC,uCAAuC;EACvC,wCAAwC;EACxC,oCAAoC;EACpC,oCAAoC;EACpC,oBACE;EACF,qBAAqB;EACrB,sBAAsB;EACtB,kBAAkB;EAClB,oBAAoB;EACrB;CAcD,MAAM,oDACgD,KAAK;CAY3D,MAAa,oCAER,EAAE,UAAU,QAAQ,SAAS,UAAU,yBAAyB;;EACnE,MAAM,qCAA0B,yBAAyB;EAEzD,MAAM,wCACE;;UAAC;IACL,GAAG;IACH,uFAAI,aAAc,6EAAU,EAAE;IAC9B,GAAI,gDAAU,EAAE;IACjB;KACD,CAAC,oEAAQ,aAAc,OAAO,CAC/B;EAED,MAAM,0BAAkB,+GAAW,aAAc,8CAAWA;EAE5D,MAAM,4CAAiC;AACrC,OAAI,SACF,QAAO;AAET,mEAAI,aAAc,SAChB,QAAO,aAAa;AAEtB,8CAAmB;KAClB,CAAC,sEAAU,aAAc,SAAS,CAAC;EAItC,MAAM,CAAC,mBAAmB,4CAFE,oFAAsB,KAGV;EAExC,MAAM,qBAAqB,uBAAuB;EAOlD,MAAM,qCACH,SAAkB;AACjB,wBAAqB,KAAK;AAC1B,oEAAc,aAAa,KAAK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O;;;;;;;;EAQP,cAAc;;;;;;;;;;;;EAYd,aAAa"}
1
+ {"version":3,"file":"index.umd.js","names":["React","DEFAULT_AGENT_ID","React","z","z","React","ToolCallStatus","z","DEFAULT_SURFACE_ID","A2UIProvider","A2UIRenderer","z","z","A2UI_SCHEMA_CONTEXT_DESCRIPTION","A2UI_DEFAULT_GENERATION_GUIDELINES","A2UI_DEFAULT_DESIGN_GUIDELINES","CopilotKitCore","COPILOT_CLOUD_CHAT_URL","viewerTheme","z","React","ToolCallStatus","useRenderToolCall","DEFAULT_AGENT_ID","HttpAgent","DEFAULT_AGENT_ID","CopilotKitCoreRuntimeConnectionStatus","ProxiedCopilotRuntimeAgent","useFrontendTool","useHumanInTheLoop","React","DEFAULT_AGENT_ID","DEFAULT_AGENT_ID","emptyCopilotContext","React","setsHaveIntersection","React","Severity","CopilotKitApiDiscoveryError","CopilotKitRemoteEndpointDiscoveryError","CopilotKitAgentDiscoveryError","CopilotKitError","ErrorVisibility","CopilotKitErrorCode","Severity","CopilotKitErrorCode","COPILOT_CLOUD_API_URL","COPILOT_CLOUD_PUBLIC_API_KEY_HEADER","ReactMarkdown","React","CopilotKitError","CopilotKitLowLevelError","CopilotKitV2Provider","COPILOT_CLOUD_CHAT_URL","COPILOT_CLOUD_PUBLIC_API_KEY_HEADER","React","ConfigurationError","MissingPublicApiKeyError","useRenderToolCall","HttpAgent","AGUIConnectNotImplementedError","CopilotKitCoreRuntimeConnectionStatus","DeprecatedGqlMessage","CopilotKitError","CopilotKitErrorCode","Severity","ErrorVisibility","React","React","ToolCallStatus","CopilotKitError","CopilotKitErrorCode","CopilotKitAgentDiscoveryError","CopilotRuntimeClient","ErrorVisibility","CopilotKitError","CopilotKitErrorCode","CopilotKitApiDiscoveryError","CopilotKitRemoteEndpointDiscoveryError","CopilotKitAgentDiscoveryError","React","Fragment","MetaEventName","React","ActionInputAvailability","TextMessage","Role","CopilotRuntimeClient","CopilotRequestType"],"sources":["../src/v2/lib/slots.tsx","../src/v2/providers/CopilotChatConfigurationProvider.tsx","../src/v2/components/CopilotKitInspector.tsx","../src/v2/components/license-warning-banner.tsx","../src/v2/components/MCPAppsActivityRenderer.tsx","../src/v2/providers/SandboxFunctionsContext.ts","../src/v2/lib/processPartialHtml.ts","../src/v2/components/OpenGenerativeUIRenderer.tsx","../src/v2/a2ui/A2UIMessageRenderer.tsx","../src/v2/types/defineToolCallRenderer.ts","../src/v2/a2ui/A2UIToolCallRenderer.tsx","../src/v2/hooks/use-agent-context.tsx","../src/v2/a2ui/A2UICatalogContext.tsx","../src/v2/lib/react-core.ts","../src/v2/providers/CopilotKitProvider.tsx","../src/v2/hooks/use-render-tool-call.tsx","../src/v2/hooks/use-agent.tsx","../src/v2/hooks/use-render-custom-messages.tsx","../src/v2/hooks/use-frontend-tool.tsx","../src/v2/hooks/use-human-in-the-loop.tsx","../src/v2/hooks/use-suggestions.tsx","../src/v2/hooks/use-configure-suggestions.tsx","../src/v2/hooks/use-interrupt.tsx","../src/context/copilot-context.tsx","../src/hooks/use-tree.ts","../src/hooks/use-flat-category-store.ts","../src/context/copilot-messages-context.tsx","../src/components/toast/toast-provider.tsx","../src/utils/dev-console.ts","../src/components/copilot-provider/copilot-messages.tsx","../src/components/usage-banner.tsx","../src/utils/suggestions-constants.ts","../src/lib/status-checker.ts","../src/components/toast/exclamation-mark-icon.tsx","../src/components/error-boundary/error-utils.tsx","../src/components/error-boundary/error-boundary.tsx","../src/context/coagent-state-renders-context.tsx","../src/context/threads-context.tsx","../src/hooks/use-coagent-state-render-bridge.helpers.ts","../src/hooks/use-coagent-state-render-registry.ts","../src/hooks/use-coagent-state-render-bridge.tsx","../src/components/CopilotListeners.tsx","../src/components/copilot-provider/copilotkit.tsx","../src/hooks/use-lazy-tool-renderer.tsx","../src/hooks/use-copilot-chat_internal.ts","../src/hooks/use-copilot-chat.ts","../src/hooks/use-copilot-chat-headless_c.ts","../src/hooks/use-frontend-tool.ts","../src/hooks/use-render-tool-call.ts","../src/hooks/use-human-in-the-loop.ts","../src/hooks/use-copilot-action.ts","../src/hooks/use-coagent-state-render.ts","../src/hooks/use-make-copilot-document-readable.ts","../src/hooks/use-copilot-readable.ts","../src/hooks/use-agent-nodename.ts","../src/hooks/use-coagent.ts","../src/hooks/use-copilot-runtime-client.ts","../src/hooks/use-copilot-authenticated-action.ts","../src/hooks/use-langgraph-interrupt.ts","../src/hooks/use-copilot-additional-instructions.ts","../src/hooks/use-default-tool.ts","../src/hooks/use-copilot-chat-suggestions.tsx","../src/types/frontend-action.ts","../src/lib/copilot-task.ts"],"sourcesContent":["import React, { useRef } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\n\n/** Existing union (unchanged) */\nexport type SlotValue<C extends React.ComponentType<any>> =\n | C\n | string\n | Partial<React.ComponentProps<C>>;\n\n/**\n * Shallow equality comparison for objects.\n */\nexport function shallowEqual<T extends Record<string, unknown>>(\n obj1: T,\n obj2: T,\n): boolean {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n\n if (keys1.length !== keys2.length) return false;\n\n for (const key of keys1) {\n if (obj1[key] !== obj2[key]) return false;\n }\n\n return true;\n}\n\n/**\n * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,\n * class instances, and other exotic objects that happen to have typeof \"object\".\n */\nfunction isPlainObject(obj: unknown): obj is Record<string, unknown> {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n Object.prototype.toString.call(obj) === \"[object Object]\"\n );\n}\n\n/**\n * Returns the same reference as long as the value is shallowly equal to the\n * previous render's value.\n *\n * - Identical references bail out immediately (O(1)).\n * - Plain objects ({}) are shallow-compared key-by-key.\n * - Arrays, Dates, class instances, functions, and primitives are compared by\n * reference only — shallowEqual is never called on non-plain objects, which\n * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).\n *\n * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow\n * equality check isn't defeated by a new object reference on every render.\n */\nexport function useShallowStableRef<T>(value: T): T {\n const ref = useRef(value);\n\n // 1. Identical reference — bail early, no comparison needed.\n if (ref.current === value) return ref.current;\n\n // 2. Both are plain objects — shallow-compare to detect structural equality.\n if (isPlainObject(ref.current) && isPlainObject(value)) {\n if (shallowEqual(ref.current, value)) return ref.current;\n }\n\n // 3. Different values (or non-comparable types) — update the ref.\n ref.current = value;\n return ref.current;\n}\n\n/** Utility: concrete React elements for every slot */\ntype SlotElements<S> = { [K in keyof S]: React.ReactElement };\n\nexport type WithSlots<\n S extends Record<string, React.ComponentType<any>>,\n Rest = {},\n> = {\n /** Per‑slot overrides */\n [K in keyof S]?: SlotValue<S[K]>;\n} & {\n children?: (props: SlotElements<S> & Rest) => React.ReactNode;\n} & Omit<Rest, \"children\">;\n\n/**\n * Check if a value is a React component type (function, class, forwardRef, memo, etc.)\n */\nexport function isReactComponentType(\n value: unknown,\n): value is React.ComponentType<any> {\n if (typeof value === \"function\") {\n return true;\n }\n // forwardRef, memo, lazy have $$typeof but are not valid elements\n if (\n value &&\n typeof value === \"object\" &&\n \"$$typeof\" in value &&\n !React.isValidElement(value)\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * Internal function to render a slot value as a React element (non-memoized).\n */\nfunction renderSlotElement(\n slot: SlotValue<React.ComponentType<any>> | undefined,\n DefaultComponent: React.ComponentType<any>,\n props: Record<string, unknown>,\n): React.ReactElement {\n if (typeof slot === \"string\") {\n // When slot is a string, treat it as a className and merge with existing className\n const existingClassName = props.className as string | undefined;\n return React.createElement(DefaultComponent, {\n ...props,\n className: twMerge(existingClassName, slot),\n });\n }\n\n // Check if slot is a React component type (function, forwardRef, memo, etc.)\n if (isReactComponentType(slot)) {\n return React.createElement(slot, props);\n }\n\n // If slot is a plain object (not a React element), treat it as props override\n if (slot && typeof slot === \"object\" && !React.isValidElement(slot)) {\n return React.createElement(DefaultComponent, {\n ...props,\n ...slot,\n });\n }\n\n return React.createElement(DefaultComponent, props);\n}\n\n/**\n * Internal memoized wrapper component for renderSlot.\n * Uses forwardRef to support ref forwarding.\n */\nconst MemoizedSlotWrapper = React.memo(\n React.forwardRef<unknown, any>(function MemoizedSlotWrapper(props, ref) {\n const { $slot, $component, ...rest } = props;\n const propsWithRef: Record<string, unknown> =\n ref !== null ? { ...rest, ref } : rest;\n return renderSlotElement($slot, $component, propsWithRef);\n }),\n (prev: any, next: any) => {\n // Compare slot and component references\n if (prev.$slot !== next.$slot) return false;\n if (prev.$component !== next.$component) return false;\n\n // Shallow compare remaining props (ref is handled separately by React)\n const { $slot: _ps, $component: _pc, ...prevRest } = prev;\n const { $slot: _ns, $component: _nc, ...nextRest } = next;\n return shallowEqual(\n prevRest as Record<string, unknown>,\n nextRest as Record<string, unknown>,\n );\n },\n);\n\n/**\n * Renders a slot value as a memoized React element.\n * Automatically prevents unnecessary re-renders using shallow prop comparison.\n * Supports ref forwarding.\n *\n * @example\n * renderSlot(customInput, CopilotChatInput, { onSubmit: handleSubmit })\n */\nexport function renderSlot<\n C extends React.ComponentType<any>,\n P = React.ComponentProps<C>,\n>(\n slot: SlotValue<C> | undefined,\n DefaultComponent: C,\n props: P,\n): React.ReactElement {\n return React.createElement(MemoizedSlotWrapper, {\n ...props,\n $slot: slot,\n $component: DefaultComponent,\n } as any);\n}\n","import React, {\n createContext,\n useCallback,\n useContext,\n ReactNode,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { DEFAULT_AGENT_ID, randomUUID } from \"@copilotkit/shared\";\nimport { useShallowStableRef } from \"../lib/slots\";\n\n// Default labels\nexport const CopilotChatDefaultLabels = {\n chatInputPlaceholder: \"Type a message...\",\n chatInputToolbarStartTranscribeButtonLabel: \"Transcribe\",\n chatInputToolbarCancelTranscribeButtonLabel: \"Cancel\",\n chatInputToolbarFinishTranscribeButtonLabel: \"Finish\",\n chatInputToolbarAddButtonLabel: \"Add attachments\",\n chatInputToolbarToolsButtonLabel: \"Tools\",\n assistantMessageToolbarCopyCodeLabel: \"Copy\",\n assistantMessageToolbarCopyCodeCopiedLabel: \"Copied\",\n assistantMessageToolbarCopyMessageLabel: \"Copy\",\n assistantMessageToolbarThumbsUpLabel: \"Good response\",\n assistantMessageToolbarThumbsDownLabel: \"Bad response\",\n assistantMessageToolbarReadAloudLabel: \"Read aloud\",\n assistantMessageToolbarRegenerateLabel: \"Regenerate\",\n userMessageToolbarCopyMessageLabel: \"Copy\",\n userMessageToolbarEditMessageLabel: \"Edit\",\n chatDisclaimerText:\n \"AI can make mistakes. Please verify important information.\",\n chatToggleOpenLabel: \"Open chat\",\n chatToggleCloseLabel: \"Close chat\",\n modalHeaderTitle: \"CopilotKit Chat\",\n welcomeMessageText: \"How can I help you today?\",\n};\n\nexport type CopilotChatLabels = typeof CopilotChatDefaultLabels;\n\n// Define the full configuration interface\nexport interface CopilotChatConfigurationValue {\n labels: CopilotChatLabels;\n agentId: string;\n threadId: string;\n isModalOpen: boolean;\n setModalOpen: (open: boolean) => void;\n}\n\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 isModalDefaultOpen?: boolean;\n}\n\n// Provider component\nexport const CopilotChatConfigurationProvider: React.FC<\n CopilotChatConfigurationProviderProps\n> = ({ children, labels, agentId, threadId, isModalDefaultOpen }) => {\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 const resolvedAgentId = agentId ?? parentConfig?.agentId ?? DEFAULT_AGENT_ID;\n\n const resolvedThreadId = useMemo(() => {\n if (threadId) {\n return threadId;\n }\n if (parentConfig?.threadId) {\n return parentConfig.threadId;\n }\n return randomUUID();\n }, [threadId, parentConfig?.threadId]);\n\n const resolvedDefaultOpen = isModalDefaultOpen ?? true;\n\n const [internalModalOpen, setInternalModalOpen] =\n useState<boolean>(resolvedDefaultOpen);\n\n const hasExplicitDefault = isModalDefaultOpen !== undefined;\n\n // When this provider owns its modal state, wrap the setter so that changes\n // propagate upward to any ancestor provider. This allows an outer\n // CopilotChatConfigurationProvider (e.g. a user's layout-level provider) to\n // observe open/close events that originate deep in the tree — fixing the\n // \"outer hook always returns true\" regression (CPK-7152 Behavior B).\n const setAndSync = useCallback(\n (open: boolean) => {\n setInternalModalOpen(open);\n parentConfig?.setModalOpen(open);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [parentConfig?.setModalOpen],\n );\n\n // Sync parent → child: when an ancestor's modal state is changed externally\n // (e.g. the user calls setModalOpen from an outer hook), reflect that change\n // in our own state so the sidebar/popup responds accordingly.\n // Skip the initial mount so that our own isModalDefaultOpen is respected and\n // not immediately overwritten by the parent's current value.\n const isMounted = useRef(false);\n useEffect(() => {\n if (!hasExplicitDefault) return;\n if (!isMounted.current) {\n isMounted.current = true;\n return;\n }\n if (parentConfig?.isModalOpen === undefined) return;\n setInternalModalOpen(parentConfig.isModalOpen);\n }, [parentConfig?.isModalOpen, hasExplicitDefault]);\n\n const resolvedIsModalOpen = hasExplicitDefault\n ? internalModalOpen\n : (parentConfig?.isModalOpen ?? internalModalOpen);\n const resolvedSetModalOpen = hasExplicitDefault\n ? setAndSync\n : (parentConfig?.setModalOpen ?? setInternalModalOpen);\n\n const configurationValue: CopilotChatConfigurationValue = useMemo(\n () => ({\n labels: mergedLabels,\n agentId: resolvedAgentId,\n threadId: resolvedThreadId,\n isModalOpen: resolvedIsModalOpen,\n setModalOpen: resolvedSetModalOpen,\n }),\n [\n mergedLabels,\n resolvedAgentId,\n resolvedThreadId,\n resolvedIsModalOpen,\n resolvedSetModalOpen,\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","import * as React from \"react\";\nimport { createComponent } from \"@lit-labs/react\";\nimport type { CopilotKitCore } from \"@copilotkit/core\";\nimport type { Anchor } from \"@copilotkit/web-inspector\";\n\ntype CopilotKitInspectorBaseProps = {\n core?: CopilotKitCore | null;\n defaultAnchor?: Anchor;\n [key: string]: unknown;\n};\n\ntype InspectorComponent = React.ComponentType<CopilotKitInspectorBaseProps>;\n\nexport interface CopilotKitInspectorProps extends CopilotKitInspectorBaseProps {}\n\nexport const CopilotKitInspector: React.FC<CopilotKitInspectorProps> = ({\n core,\n ...rest\n}) => {\n const [InspectorComponent, setInspectorComponent] =\n React.useState<InspectorComponent | null>(null);\n\n React.useEffect(() => {\n let mounted = true;\n\n // Load the web component only on the client to keep SSR output stable.\n import(\"@copilotkit/web-inspector\").then((mod) => {\n mod.defineWebInspector?.();\n\n const Component = createComponent({\n tagName: mod.WEB_INSPECTOR_TAG,\n elementClass: mod.WebInspectorElement,\n react: React,\n }) as InspectorComponent;\n\n if (mounted) {\n setInspectorComponent(() => Component);\n }\n });\n\n return () => {\n mounted = false;\n };\n }, []);\n\n // During SSR (and until the client finishes loading), render nothing to keep markup consistent.\n if (!InspectorComponent) return null;\n\n return <InspectorComponent {...rest} core={core ?? null} />;\n};\n\nCopilotKitInspector.displayName = \"CopilotKitInspector\";\n","import React from \"react\";\n\ninterface LicenseWarningBannerProps {\n type:\n | \"no_license\"\n | \"expired\"\n | \"expiring\"\n | \"invalid\"\n | \"feature_unlicensed\";\n featureName?: string;\n expiryDate?: string;\n graceRemaining?: number;\n onDismiss?: () => void;\n}\n\nconst BANNER_STYLES: Record<string, React.CSSProperties> = {\n base: {\n position: \"fixed\",\n bottom: \"8px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 99999,\n display: \"inline-flex\",\n alignItems: \"center\",\n gap: \"12px\",\n whiteSpace: \"nowrap\",\n padding: \"8px 16px\",\n fontSize: \"13px\",\n fontFamily:\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif\",\n borderRadius: \"6px\",\n boxShadow: \"0 2px 8px rgba(0, 0, 0, 0.15)\",\n },\n info: {\n backgroundColor: \"#eff6ff\",\n border: \"1px solid #93c5fd\",\n color: \"#1e40af\",\n },\n warning: {\n backgroundColor: \"#fffbeb\",\n border: \"1px solid #fbbf24\",\n color: \"#92400e\",\n },\n critical: {\n backgroundColor: \"#fef2f2\",\n border: \"1px solid #fca5a5\",\n color: \"#991b1b\",\n },\n};\n\nfunction getSeverityStyle(severity: string): React.CSSProperties {\n switch (severity) {\n case \"warning\":\n return BANNER_STYLES.warning;\n case \"critical\":\n return BANNER_STYLES.critical;\n default:\n return BANNER_STYLES.info;\n }\n}\n\nfunction BannerShell({\n severity,\n message,\n actionLabel,\n actionUrl,\n onDismiss,\n}: {\n severity: string;\n message: string;\n actionLabel: string;\n actionUrl: string;\n onDismiss?: () => void;\n}) {\n return (\n <div style={{ ...BANNER_STYLES.base, ...getSeverityStyle(severity) }}>\n <span>{message}</span>\n <div style={{ display: \"flex\", gap: \"8px\", alignItems: \"center\" }}>\n <a\n href={actionUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n style={{\n fontWeight: 600,\n textDecoration: \"underline\",\n color: \"inherit\",\n }}\n >\n {actionLabel}\n </a>\n {onDismiss && (\n <button\n onClick={onDismiss}\n style={{\n background: \"none\",\n border: \"none\",\n cursor: \"pointer\",\n color: \"inherit\",\n fontSize: \"16px\",\n }}\n >\n ×\n </button>\n )}\n </div>\n </div>\n );\n}\n\nexport function LicenseWarningBanner({\n type,\n featureName,\n expiryDate,\n graceRemaining,\n onDismiss,\n}: LicenseWarningBannerProps) {\n switch (type) {\n case \"no_license\":\n return (\n <BannerShell\n severity=\"info\"\n message=\"Powered by CopilotKit\"\n actionLabel=\"Get a license\"\n actionUrl=\"https://copilotkit.ai/pricing\"\n onDismiss={onDismiss}\n />\n );\n case \"feature_unlicensed\":\n return (\n <BannerShell\n severity=\"warning\"\n message={`⚠ The \"${featureName}\" feature requires a CopilotKit license.`}\n actionLabel=\"Get a license\"\n actionUrl=\"https://copilotkit.ai/pricing\"\n onDismiss={onDismiss}\n />\n );\n case \"expiring\":\n return (\n <BannerShell\n severity=\"warning\"\n message={`Your CopilotKit license expires in ${graceRemaining} day${graceRemaining !== 1 ? \"s\" : \"\"}. Please renew.`}\n actionLabel=\"Renew\"\n actionUrl=\"https://cloud.copilotkit.ai\"\n onDismiss={onDismiss}\n />\n );\n case \"expired\":\n return (\n <BannerShell\n severity=\"critical\"\n message={`Your CopilotKit license expired${expiryDate ? ` on ${expiryDate}` : \"\"}. Please renew at copilotkit.ai/pricing`}\n actionLabel=\"Renew now\"\n actionUrl=\"https://copilotkit.ai/pricing\"\n onDismiss={onDismiss}\n />\n );\n case \"invalid\":\n return (\n <BannerShell\n severity=\"critical\"\n message=\"Invalid CopilotKit license token. Please check your configuration.\"\n actionLabel=\"Get a license\"\n actionUrl=\"https://copilotkit.ai/pricing\"\n onDismiss={onDismiss}\n />\n );\n default:\n return null;\n }\n}\n\nexport function InlineFeatureWarning({ featureName }: { featureName: string }) {\n return (\n <div\n style={{\n padding: \"8px 12px\",\n backgroundColor: \"#fffbeb\",\n border: \"1px solid #fbbf24\",\n borderRadius: \"6px\",\n fontSize: \"13px\",\n color: \"#92400e\",\n fontFamily:\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif\",\n }}\n >\n ⚠ The &quot;{featureName}&quot; feature requires a CopilotKit license.{\" \"}\n <a\n href=\"https://copilotkit.ai/pricing\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n style={{ color: \"#b45309\", textDecoration: \"underline\" }}\n >\n Get one at copilotkit.ai/pricing\n </a>\n </div>\n );\n}\n","\"use client\";\n\nimport React, { useEffect, useRef, useState, useCallback } from \"react\";\nimport { z } from \"zod\";\nimport type { AbstractAgent, RunAgentResult } from \"@ag-ui/client\";\n\n// Protocol version supported\nconst PROTOCOL_VERSION = \"2025-06-18\";\n\n// Build sandbox proxy HTML with optional extra CSP domains from resource metadata\nfunction buildSandboxHTML(extraCspDomains?: string[]): string {\n const baseScriptSrc =\n \"'self' 'wasm-unsafe-eval' 'unsafe-inline' 'unsafe-eval' blob: data: http://localhost:* https://localhost:*\";\n const baseFrameSrc = \"* blob: data: http://localhost:* https://localhost:*\";\n const extra = extraCspDomains?.length ? \" \" + extraCspDomains.join(\" \") : \"\";\n const scriptSrc = baseScriptSrc + extra;\n const frameSrc = baseFrameSrc + extra;\n\n return `<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'self'; img-src * data: blob: 'unsafe-inline'; media-src * blob: data:; font-src * blob: data:; script-src ${scriptSrc}; style-src * blob: data: 'unsafe-inline'; connect-src *; frame-src ${frameSrc}; base-uri 'self';\" />\n<style>html,body{margin:0;padding:0;height:100%;width:100%;overflow:hidden}*{box-sizing:border-box}iframe{background-color:transparent;border:none;padding:0;overflow:hidden;width:100%;height:100%}</style>\n</head>\n<body>\n<script>\nif(window.self===window.top){throw new Error(\"This file must be used in an iframe.\")}\nconst inner=document.createElement(\"iframe\");\ninner.style=\"width:100%;height:100%;border:none;\";\ninner.setAttribute(\"sandbox\",\"allow-scripts allow-same-origin allow-forms\");\ndocument.body.appendChild(inner);\nwindow.addEventListener(\"message\",async(event)=>{\nif(event.source===window.parent){\nif(event.data&&event.data.method===\"ui/notifications/sandbox-resource-ready\"){\nconst{html,sandbox}=event.data.params;\nif(typeof sandbox===\"string\")inner.setAttribute(\"sandbox\",sandbox);\nif(typeof html===\"string\")inner.srcdoc=html;\n}else if(inner&&inner.contentWindow){\ninner.contentWindow.postMessage(event.data,\"*\");\n}\n}else if(event.source===inner.contentWindow){\nwindow.parent.postMessage(event.data,\"*\");\n}\n});\nwindow.parent.postMessage({jsonrpc:\"2.0\",method:\"ui/notifications/sandbox-proxy-ready\",params:{}},\"*\");\n</script>\n</body>\n</html>`;\n}\n\n/**\n * Queue for serializing MCP app requests to an agent.\n * Ensures requests wait for the agent to stop running and are processed one at a time.\n */\nclass MCPAppsRequestQueue {\n private queues = new Map<\n string,\n Array<{\n execute: () => Promise<RunAgentResult>;\n resolve: (result: RunAgentResult) => void;\n reject: (error: Error) => void;\n }>\n >();\n private processing = new Map<string, boolean>();\n\n /**\n * Add a request to the queue for a specific agent thread.\n * Returns a promise that resolves when the request completes.\n */\n async enqueue(\n agent: AbstractAgent,\n request: () => Promise<RunAgentResult>,\n ): Promise<RunAgentResult> {\n const threadId = agent.threadId || \"default\";\n\n return new Promise((resolve, reject) => {\n // Get or create queue for this thread\n let queue = this.queues.get(threadId);\n if (!queue) {\n queue = [];\n this.queues.set(threadId, queue);\n }\n\n // Add request to queue\n queue.push({ execute: request, resolve, reject });\n\n // Start processing if not already running\n this.processQueue(threadId, agent);\n });\n }\n\n private async processQueue(\n threadId: string,\n agent: AbstractAgent,\n ): Promise<void> {\n // If already processing this queue, return\n if (this.processing.get(threadId)) {\n return;\n }\n\n this.processing.set(threadId, true);\n\n try {\n const queue = this.queues.get(threadId);\n if (!queue) return;\n\n while (queue.length > 0) {\n const item = queue[0]!;\n\n try {\n // Wait for any active run to complete before processing\n await this.waitForAgentIdle(agent);\n\n // Execute the request\n const result = await item.execute();\n item.resolve(result);\n } catch (error) {\n item.reject(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n\n // Remove processed item\n queue.shift();\n }\n } finally {\n this.processing.set(threadId, false);\n }\n }\n\n private waitForAgentIdle(agent: AbstractAgent): Promise<void> {\n return new Promise((resolve) => {\n if (!agent.isRunning) {\n resolve();\n return;\n }\n\n let done = false;\n const finish = () => {\n if (done) return;\n done = true;\n clearInterval(checkInterval);\n sub.unsubscribe();\n resolve();\n };\n\n const sub = agent.subscribe({\n onRunFinalized: finish,\n onRunFailed: finish,\n });\n\n // Fallback for reconnect scenarios where events don't fire\n const checkInterval = setInterval(() => {\n if (!agent.isRunning) finish();\n }, 500);\n });\n }\n}\n\n// Global queue instance for all MCP app requests\nconst mcpAppsRequestQueue = new MCPAppsRequestQueue();\n\n/**\n * Activity type for MCP Apps events - must match the middleware's MCPAppsActivityType\n */\nexport const MCPAppsActivityType = \"mcp-apps\";\n\n// Zod schema for activity content validation (middleware 0.0.2 format)\nexport const MCPAppsActivityContentSchema = z.object({\n result: z.object({\n content: z.array(z.any()).optional(),\n structuredContent: z.any().optional(),\n isError: z.boolean().optional(),\n }),\n // Resource URI to fetch (e.g., \"ui://server/dashboard\")\n resourceUri: z.string(),\n // MD5 hash of server config (renamed from serverId in 0.0.1)\n serverHash: z.string(),\n // Optional stable server ID from config (takes precedence over serverHash)\n serverId: z.string().optional(),\n // Original tool input arguments\n toolInput: z.record(z.unknown()).optional(),\n});\n\nexport type MCPAppsActivityContent = z.infer<\n typeof MCPAppsActivityContentSchema\n>;\n\n// Type for the resource fetched from the server\ninterface FetchedResource {\n uri: string;\n mimeType?: string;\n text?: string;\n blob?: string;\n _meta?: {\n ui?: {\n prefersBorder?: boolean;\n csp?: {\n connectDomains?: string[];\n resourceDomains?: string[];\n };\n };\n };\n}\n\ninterface JSONRPCRequest {\n jsonrpc: \"2.0\";\n id: string | number;\n method: string;\n params?: Record<string, unknown>;\n}\n\ninterface JSONRPCResponse {\n jsonrpc: \"2.0\";\n id: string | number;\n result?: unknown;\n error?: { code: number; message: string };\n}\n\ninterface JSONRPCNotification {\n jsonrpc: \"2.0\";\n method: string;\n params?: Record<string, unknown>;\n}\n\ntype JSONRPCMessage = JSONRPCRequest | JSONRPCResponse | JSONRPCNotification;\n\nfunction isRequest(msg: JSONRPCMessage): msg is JSONRPCRequest {\n return \"id\" in msg && \"method\" in msg;\n}\n\nfunction isNotification(msg: JSONRPCMessage): msg is JSONRPCNotification {\n return !(\"id\" in msg) && \"method\" in msg;\n}\n\n/**\n * Props for the activity renderer component\n */\ninterface MCPAppsActivityRendererProps {\n activityType: string;\n content: MCPAppsActivityContent;\n message: unknown; // ActivityMessage from @ag-ui/core\n agent: AbstractAgent | undefined;\n}\n\n/**\n * MCP Apps Extension Activity Renderer\n *\n * Renders MCP Apps UI in a sandboxed iframe with full protocol support.\n * Fetches resource content on-demand via proxied MCP requests.\n */\nexport const MCPAppsActivityRenderer: React.FC<MCPAppsActivityRendererProps> =\n function MCPAppsActivityRenderer({ content, agent }) {\n const containerRef = useRef<HTMLDivElement>(null);\n const iframeRef = useRef<HTMLIFrameElement | null>(null);\n const [iframeReady, setIframeReady] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [iframeSize, setIframeSize] = useState<{\n width?: number;\n height?: number;\n }>({});\n const [fetchedResource, setFetchedResource] =\n useState<FetchedResource | null>(null);\n\n // Use refs for values that shouldn't trigger re-renders but need latest values\n const contentRef = useRef(content);\n contentRef.current = content;\n\n // Store agent in a ref for use in async handlers\n const agentRef = useRef(agent);\n agentRef.current = agent;\n\n // Ref to track fetch state - survives StrictMode remounts\n const fetchStateRef = useRef<{\n inProgress: boolean;\n promise: Promise<FetchedResource | null> | null;\n resourceUri: string | null;\n }>({ inProgress: false, promise: null, resourceUri: null });\n\n // Callback to send a message to the iframe\n const sendToIframe = useCallback((msg: JSONRPCMessage) => {\n if (iframeRef.current?.contentWindow) {\n console.log(\"[MCPAppsRenderer] Sending to iframe:\", msg);\n iframeRef.current.contentWindow.postMessage(msg, \"*\");\n }\n }, []);\n\n // Callback to send a JSON-RPC response\n const sendResponse = useCallback(\n (id: string | number, result: unknown) => {\n sendToIframe({\n jsonrpc: \"2.0\",\n id,\n result,\n });\n },\n [sendToIframe],\n );\n\n // Callback to send a JSON-RPC error response\n const sendErrorResponse = useCallback(\n (id: string | number, code: number, message: string) => {\n sendToIframe({\n jsonrpc: \"2.0\",\n id,\n error: { code, message },\n });\n },\n [sendToIframe],\n );\n\n // Callback to send a notification\n const sendNotification = useCallback(\n (method: string, params?: Record<string, unknown>) => {\n sendToIframe({\n jsonrpc: \"2.0\",\n method,\n params: params || {},\n });\n },\n [sendToIframe],\n );\n\n // Effect 0: Fetch the resource content on mount\n // Uses ref-based deduplication to handle React StrictMode double-mounting\n useEffect(() => {\n const { resourceUri, serverHash, serverId } = content;\n\n // Check if we already have a fetch in progress for this resource\n // This handles StrictMode double-mounting - second mount reuses first mount's promise\n if (\n fetchStateRef.current.inProgress &&\n fetchStateRef.current.resourceUri === resourceUri\n ) {\n // Reuse the existing promise\n fetchStateRef.current.promise\n ?.then((resource) => {\n if (resource) {\n setFetchedResource(resource);\n setIsLoading(false);\n }\n })\n .catch((err) => {\n setError(err instanceof Error ? err : new Error(String(err)));\n setIsLoading(false);\n });\n return;\n }\n\n if (!agent) {\n setError(new Error(\"No agent available to fetch resource\"));\n setIsLoading(false);\n return;\n }\n\n // Mark fetch as in progress\n fetchStateRef.current.inProgress = true;\n fetchStateRef.current.resourceUri = resourceUri;\n\n // Create the fetch promise using the queue to serialize requests\n const fetchPromise = (async (): Promise<FetchedResource | null> => {\n try {\n // Use queue to wait for agent to be idle and serialize requests\n const runResult = await mcpAppsRequestQueue.enqueue(agent, () =>\n agent.runAgent({\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId, // optional, takes precedence if provided\n method: \"resources/read\",\n params: { uri: resourceUri },\n },\n },\n }),\n );\n\n // Extract resource from result\n // The response format is: { contents: [{ uri, mimeType, text?, blob?, _meta? }] }\n const resultData = runResult.result as\n | { contents?: FetchedResource[] }\n | undefined;\n const resource = resultData?.contents?.[0];\n\n if (!resource) {\n throw new Error(\"No resource content in response\");\n }\n\n return resource;\n } catch (err) {\n console.error(\"[MCPAppsRenderer] Failed to fetch resource:\", err);\n throw err;\n } finally {\n // Mark fetch as complete\n fetchStateRef.current.inProgress = false;\n }\n })();\n\n // Store the promise for potential reuse\n fetchStateRef.current.promise = fetchPromise;\n\n // Handle the result\n fetchPromise\n .then((resource) => {\n if (resource) {\n setFetchedResource(resource);\n setIsLoading(false);\n }\n })\n .catch((err) => {\n setError(err instanceof Error ? err : new Error(String(err)));\n setIsLoading(false);\n });\n\n // No cleanup needed - we want the fetch to complete even if StrictMode unmounts\n }, [agent, content]);\n\n // Effect 1: Setup sandbox proxy iframe and communication (after resource is fetched)\n useEffect(() => {\n // Wait for resource to be fetched\n if (isLoading || !fetchedResource) {\n return;\n }\n\n // Capture container reference at effect start (refs are cleared during unmount)\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n let mounted = true;\n let messageHandler: ((event: MessageEvent) => void) | null = null;\n let initialListener: ((event: MessageEvent) => void) | null = null;\n let createdIframe: HTMLIFrameElement | null = null;\n\n const setup = async () => {\n try {\n // Create sandbox proxy iframe\n const iframe = document.createElement(\"iframe\");\n createdIframe = iframe; // Track for cleanup\n iframe.style.width = \"100%\";\n iframe.style.height = \"100px\"; // Start small, will be resized by size-changed notification\n iframe.style.border = \"none\";\n iframe.style.backgroundColor = \"transparent\";\n iframe.style.display = \"block\";\n iframe.setAttribute(\n \"sandbox\",\n \"allow-scripts allow-same-origin allow-forms\",\n );\n\n // Wait for sandbox proxy to be ready\n const sandboxReady = new Promise<void>((resolve) => {\n initialListener = (event: MessageEvent) => {\n if (event.source === iframe.contentWindow) {\n if (\n event.data?.method === \"ui/notifications/sandbox-proxy-ready\"\n ) {\n if (initialListener) {\n window.removeEventListener(\"message\", initialListener);\n initialListener = null;\n }\n resolve();\n }\n }\n };\n window.addEventListener(\"message\", initialListener);\n });\n\n // Check mounted before adding to DOM (handles StrictMode double-mount)\n if (!mounted) {\n if (initialListener) {\n window.removeEventListener(\"message\", initialListener);\n initialListener = null;\n }\n return;\n }\n\n // Build sandbox HTML with CSP domains from resource metadata\n const cspDomains = fetchedResource._meta?.ui?.csp?.resourceDomains;\n iframe.srcdoc = buildSandboxHTML(cspDomains);\n iframeRef.current = iframe;\n container.appendChild(iframe);\n\n // Wait for sandbox proxy to signal ready\n await sandboxReady;\n if (!mounted) return;\n\n console.log(\"[MCPAppsRenderer] Sandbox proxy ready\");\n\n // Setup message handler for JSON-RPC messages from the inner iframe\n messageHandler = async (event: MessageEvent) => {\n if (event.source !== iframe.contentWindow) return;\n\n const msg = event.data as JSONRPCMessage;\n if (!msg || typeof msg !== \"object\" || msg.jsonrpc !== \"2.0\")\n return;\n\n console.log(\"[MCPAppsRenderer] Received from iframe:\", msg);\n\n // Handle requests (need response)\n if (isRequest(msg)) {\n switch (msg.method) {\n case \"ui/initialize\": {\n // Respond with host capabilities\n sendResponse(msg.id, {\n protocolVersion: PROTOCOL_VERSION,\n hostInfo: {\n name: \"CopilotKit MCP Apps Host\",\n version: \"1.0.0\",\n },\n hostCapabilities: {\n openLinks: {},\n logging: {},\n },\n hostContext: {\n theme: \"light\",\n platform: \"web\",\n },\n });\n break;\n }\n\n case \"ui/message\": {\n // Add message to CopilotKit chat\n const currentAgent = agentRef.current;\n\n if (!currentAgent) {\n console.warn(\n \"[MCPAppsRenderer] ui/message: No agent available\",\n );\n sendResponse(msg.id, { isError: false });\n break;\n }\n\n try {\n const params = msg.params as {\n role?: string;\n content?: Array<{ type: string; text?: string }>;\n };\n\n // Extract text content from the message\n const textContent =\n params.content\n ?.filter((c) => c.type === \"text\" && c.text)\n .map((c) => c.text)\n .join(\"\\n\") || \"\";\n\n if (textContent) {\n currentAgent.addMessage({\n id: crypto.randomUUID(),\n role: (params.role as \"user\" | \"assistant\") || \"user\",\n content: textContent,\n });\n }\n sendResponse(msg.id, { isError: false });\n } catch (err) {\n console.error(\"[MCPAppsRenderer] ui/message error:\", err);\n sendResponse(msg.id, { isError: true });\n }\n break;\n }\n\n case \"ui/open-link\": {\n // Open URL in new tab\n const url = msg.params?.url as string | undefined;\n if (url) {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n sendResponse(msg.id, { isError: false });\n } else {\n sendErrorResponse(msg.id, -32602, \"Missing url parameter\");\n }\n break;\n }\n\n case \"tools/call\": {\n // Proxy tool call to MCP server via agent.runAgent()\n const { serverHash, serverId } = contentRef.current;\n const currentAgent = agentRef.current;\n\n if (!serverHash) {\n sendErrorResponse(\n msg.id,\n -32603,\n \"No server hash available for proxying\",\n );\n break;\n }\n\n if (!currentAgent) {\n sendErrorResponse(\n msg.id,\n -32603,\n \"No agent available for proxying\",\n );\n break;\n }\n\n try {\n // Use queue to wait for agent to be idle and serialize requests\n const runResult = await mcpAppsRequestQueue.enqueue(\n currentAgent,\n () =>\n currentAgent.runAgent({\n forwardedProps: {\n __proxiedMCPRequest: {\n serverHash,\n serverId, // optional, takes precedence if provided\n method: \"tools/call\",\n params: msg.params,\n },\n },\n }),\n );\n\n // The result from runAgent contains the MCP response\n sendResponse(msg.id, runResult.result || {});\n } catch (err) {\n console.error(\"[MCPAppsRenderer] tools/call error:\", err);\n sendErrorResponse(msg.id, -32603, String(err));\n }\n break;\n }\n\n default:\n sendErrorResponse(\n msg.id,\n -32601,\n `Method not found: ${msg.method}`,\n );\n }\n }\n\n // Handle notifications (no response needed)\n if (isNotification(msg)) {\n switch (msg.method) {\n case \"ui/notifications/initialized\": {\n console.log(\"[MCPAppsRenderer] Inner iframe initialized\");\n if (mounted) {\n setIframeReady(true);\n }\n break;\n }\n\n case \"ui/notifications/size-changed\": {\n const { width, height } = msg.params || {};\n console.log(\"[MCPAppsRenderer] Size change:\", {\n width,\n height,\n });\n if (mounted) {\n setIframeSize({\n width: typeof width === \"number\" ? width : undefined,\n height: typeof height === \"number\" ? height : undefined,\n });\n }\n break;\n }\n\n case \"notifications/message\": {\n // Logging notification from the app\n console.log(\"[MCPAppsRenderer] App log:\", msg.params);\n break;\n }\n }\n }\n };\n\n window.addEventListener(\"message\", messageHandler);\n\n // Extract HTML content from fetched resource\n let html: string;\n if (fetchedResource.text) {\n html = fetchedResource.text;\n } else if (fetchedResource.blob) {\n html = atob(fetchedResource.blob);\n } else {\n throw new Error(\"Resource has no text or blob content\");\n }\n\n // Send the resource content to the sandbox proxy\n sendNotification(\"ui/notifications/sandbox-resource-ready\", { html });\n } catch (err) {\n console.error(\"[MCPAppsRenderer] Setup error:\", err);\n if (mounted) {\n setError(err instanceof Error ? err : new Error(String(err)));\n }\n }\n };\n\n setup();\n\n return () => {\n mounted = false;\n // Clean up initial listener if still active\n if (initialListener) {\n window.removeEventListener(\"message\", initialListener);\n initialListener = null;\n }\n if (messageHandler) {\n window.removeEventListener(\"message\", messageHandler);\n }\n // Remove the iframe we created (using tracked reference, not DOM query)\n // This works even if containerRef.current is null during unmount\n if (createdIframe) {\n createdIframe.remove();\n createdIframe = null;\n }\n iframeRef.current = null;\n };\n }, [\n isLoading,\n fetchedResource,\n sendNotification,\n sendResponse,\n sendErrorResponse,\n ]);\n\n // Effect 2: Update iframe size when it changes\n useEffect(() => {\n if (iframeRef.current) {\n if (iframeSize.width !== undefined) {\n // Use minWidth with min() to allow expansion but cap at 100%\n iframeRef.current.style.minWidth = `min(${iframeSize.width}px, 100%)`;\n iframeRef.current.style.width = \"100%\";\n }\n if (iframeSize.height !== undefined) {\n iframeRef.current.style.height = `${iframeSize.height}px`;\n }\n }\n }, [iframeSize]);\n\n // Effect 3: Send tool input when iframe ready\n useEffect(() => {\n if (iframeReady && content.toolInput) {\n console.log(\"[MCPAppsRenderer] Sending tool input:\", content.toolInput);\n sendNotification(\"ui/notifications/tool-input\", {\n arguments: content.toolInput,\n });\n }\n }, [iframeReady, content.toolInput, sendNotification]);\n\n // Effect 4: Send tool result when iframe ready\n useEffect(() => {\n if (iframeReady && content.result) {\n console.log(\"[MCPAppsRenderer] Sending tool result:\", content.result);\n sendNotification(\"ui/notifications/tool-result\", content.result);\n }\n }, [iframeReady, content.result, sendNotification]);\n\n // Determine border styling based on prefersBorder metadata from fetched resource\n // true = show border/background, false = none, undefined = host decides (we default to none)\n const prefersBorder = fetchedResource?._meta?.ui?.prefersBorder;\n const borderStyle =\n prefersBorder === true\n ? {\n borderRadius: \"8px\",\n backgroundColor: \"#f9f9f9\",\n border: \"1px solid #e0e0e0\",\n }\n : {};\n\n return (\n <div\n ref={containerRef}\n style={{\n width: \"100%\",\n height: iframeSize.height ? `${iframeSize.height}px` : \"auto\",\n minHeight: \"100px\",\n overflow: \"hidden\",\n position: \"relative\",\n ...borderStyle,\n }}\n >\n {isLoading && (\n <div style={{ padding: \"1rem\", color: \"#666\" }}>Loading...</div>\n )}\n {error && (\n <div style={{ color: \"red\", padding: \"1rem\" }}>\n Error: {error.message}\n </div>\n )}\n </div>\n );\n };\n","import { createContext, useContext } from \"react\";\nimport type { SandboxFunction } from \"../types/sandbox-function\";\n\nexport const SandboxFunctionsContext = createContext<\n readonly SandboxFunction[]\n>([]);\n\nexport function useSandboxFunctions(): readonly SandboxFunction[] {\n return useContext(SandboxFunctionsContext);\n}\n","/**\n * Extracts all complete `<style>` blocks from the raw HTML.\n * Returns the concatenated style tags, suitable for injection into `<head>`.\n */\nexport function extractCompleteStyles(html: string): string {\n const matches = html.match(/<style\\b[^>]*>[\\s\\S]*?<\\/style>/gi);\n return matches ? matches.join(\"\") : \"\";\n}\n\n/**\n * Processes raw accumulated HTML for safe preview via innerHTML injection.\n * Pure function, no DOM dependencies.\n *\n * Pipeline (order matters):\n * 1. Strip incomplete tag at end\n * 2. Strip complete <style>, <script>, and <head> blocks\n * 3. Strip incomplete <style>/<script>/<head> blocks\n * 4. Strip incomplete HTML entities\n * 5. Extract body content (or use full string if no <body>)\n */\nexport function processPartialHtml(html: string): string {\n let result = html;\n\n // 1. Strip incomplete tag at end — e.g. `<div class=\"fo`\n result = result.replace(/<[^>]*$/, \"\");\n\n // 2. Strip complete <style>, <script>, and <head> blocks\n result = result.replace(/<(style|script|head)\\b[^>]*>[\\s\\S]*?<\\/\\1>/gi, \"\");\n\n // 3. Strip incomplete <style>/<script>/<head> blocks (opening tag, no close)\n result = result.replace(/<(style|script|head)\\b[^>]*>[\\s\\S]*$/gi, \"\");\n\n // 4. Strip incomplete HTML entities — e.g. `&amp` without semicolon\n result = result.replace(/&[a-zA-Z0-9#]*$/, \"\");\n\n // 5. Extract body content\n const bodyMatch = result.match(/<body[^>]*>([\\s\\S]*)/i);\n if (bodyMatch) {\n result = bodyMatch[1]!;\n // Strip </body> and everything after\n result = result.replace(/<\\/body>[\\s\\S]*/i, \"\");\n }\n\n return result;\n}\n","\"use client\";\n\nimport React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { z } from \"zod\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport { useSandboxFunctions } from \"../providers/SandboxFunctionsContext\";\nimport {\n processPartialHtml,\n extractCompleteStyles,\n} from \"../lib/processPartialHtml\";\n\nexport const OpenGenerativeUIActivityType = \"open-generative-ui\";\n\nexport const OpenGenerativeUIContentSchema = z.object({\n initialHeight: z.number().optional(),\n generating: z.boolean().optional(),\n css: z.string().optional(),\n cssComplete: z.boolean().optional(),\n html: z.array(z.string()).optional(),\n htmlComplete: z.boolean().optional(),\n jsFunctions: z.string().optional(),\n jsFunctionsComplete: z.boolean().optional(),\n jsExpressions: z.array(z.string()).optional(),\n jsExpressionsComplete: z.boolean().optional(),\n});\n\nexport type OpenGenerativeUIContent = z.infer<\n typeof OpenGenerativeUIContentSchema\n>;\n\n/**\n * Schema for the generateSandboxedUi tool call arguments.\n * Used by the frontend tool renderer to display placeholder messages.\n */\nexport const GenerateSandboxedUiArgsSchema = z.object({\n initialHeight: z.number().optional(),\n placeholderMessages: z.array(z.string()).optional(),\n css: z.string().optional(),\n html: z.string().optional(),\n jsFunctions: z.string().optional(),\n jsExpressions: z.array(z.string()).optional(),\n});\n\nexport type GenerateSandboxedUiArgs = z.infer<\n typeof GenerateSandboxedUiArgsSchema\n>;\n\ninterface OpenGenerativeUIActivityRendererProps {\n activityType: string;\n content: OpenGenerativeUIContent;\n message: unknown;\n agent: unknown;\n}\n\nconst THROTTLE_MS = 1000;\n\n/**\n * Returns true when the inner component should re-render immediately\n * (no throttle delay).\n */\nfunction shouldFlushImmediately(\n prev: OpenGenerativeUIContent | null,\n next: OpenGenerativeUIContent,\n): boolean {\n // CSS finished — switch from placeholder to preview\n if (next.cssComplete && (!prev || !prev.cssComplete)) return true;\n // Streaming done\n if (next.htmlComplete) return true;\n // Generation finished\n if (next.generating === false) return true;\n // jsFunctions appeared\n if (next.jsFunctions && (!prev || !prev.jsFunctions)) return true;\n // jsExpressions grew\n if ((next.jsExpressions?.length ?? 0) > (prev?.jsExpressions?.length ?? 0))\n return true;\n // First html chunk arrived (first preview — no delay)\n if (next.html?.length && (!prev || !prev.html?.length)) return true;\n return false;\n}\n\n/**\n * Outer wrapper — absorbs every parent re-render but only forwards\n * throttled content snapshots to the memoized inner component.\n */\nexport const OpenGenerativeUIActivityRenderer: React.FC<OpenGenerativeUIActivityRendererProps> =\n function OpenGenerativeUIActivityRenderer({ content }) {\n const latestContentRef = useRef(content);\n latestContentRef.current = content;\n\n const [throttledContent, setThrottledContent] =\n useState<OpenGenerativeUIContent>(content);\n const throttledContentRef = useRef(throttledContent);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Synchronous state adjustment during render (React-approved pattern).\n // When shouldFlushImmediately is true, update state before commit so the\n // inner component sees the new content in the same render pass — no extra\n // async cycle that would break test timing.\n if (throttledContentRef.current !== content) {\n if (shouldFlushImmediately(throttledContentRef.current, content)) {\n if (timerRef.current !== null) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }\n throttledContentRef.current = content;\n setThrottledContent(content);\n }\n }\n\n const flush = useCallback(() => {\n timerRef.current = null;\n const latest = latestContentRef.current;\n throttledContentRef.current = latest;\n setThrottledContent(latest);\n }, []);\n\n // Schedule throttled updates for non-immediate content changes\n useEffect(() => {\n // Already up to date (initial render or synchronous flush above)\n if (throttledContentRef.current === content) return;\n\n // Schedule a throttled flush if none pending\n if (timerRef.current === null) {\n timerRef.current = setTimeout(flush, THROTTLE_MS);\n }\n }, [content, flush]);\n\n // Cleanup timer on unmount\n useEffect(() => {\n return () => {\n if (timerRef.current !== null) {\n clearTimeout(timerRef.current);\n }\n };\n }, []);\n\n return <OpenGenerativeUIActivityRendererInner content={throttledContent} />;\n };\n\n// ---------------------------------------------------------------------------\n// Inner component — all the expensive work, protected by React.memo\n// ---------------------------------------------------------------------------\n\ninterface InnerProps {\n content: OpenGenerativeUIContent;\n}\n\nfunction ensureHead(html: string): string {\n if (/<head[\\s>]/i.test(html)) return html;\n return `<head></head>${html}`;\n}\n\nfunction injectCssIntoHtml(html: string, css: string): string {\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx !== -1) {\n return (\n html.slice(0, headCloseIdx) +\n `<style>${css}</style>` +\n html.slice(headCloseIdx)\n );\n }\n return `<head><style>${css}</style></head>${html}`;\n}\n\nconst OpenGenerativeUIActivityRendererInner = React.memo(\n function OpenGenerativeUIActivityRendererInner({ content }: InnerProps) {\n const initialHeight = content.initialHeight ?? 200;\n const [autoHeight, setAutoHeight] = useState<number | null>(null);\n const sandboxFunctions = useSandboxFunctions();\n\n const localApi = useMemo(() => {\n const api: Record<string, Function> = {};\n for (const fn of sandboxFunctions) {\n api[fn.name] = fn.handler;\n }\n return api;\n }, [sandboxFunctions]);\n\n // Join html chunks only when streaming is complete\n const fullHtml =\n content.htmlComplete && content.html?.length\n ? content.html.join(\"\")\n : undefined;\n\n // CSS from the dedicated parameter (available once cssComplete)\n const css = content.cssComplete ? content.css : undefined;\n\n // Derived state for preview streaming — gate on cssComplete so we\n // show the placeholder until styles are ready.\n const cssReady = !!content.cssComplete;\n const partialHtml =\n !content.htmlComplete && content.html?.length\n ? content.html.join(\"\")\n : undefined;\n const previewBody = partialHtml\n ? processPartialHtml(partialHtml)\n : undefined;\n const previewStyles = partialHtml ? extractCompleteStyles(partialHtml) : \"\";\n const hasPreview = cssReady && !!previewBody?.trim();\n const hasVisibleSandbox = !!fullHtml || hasPreview;\n\n const containerRef = useRef<HTMLDivElement>(null);\n const sandboxRef = useRef<{\n run: (code: string | Function) => Promise<unknown>;\n destroy: () => void;\n iframe: HTMLIFrameElement;\n } | null>(null);\n const previewSandboxRef = useRef<{\n run: (code: string | Function) => Promise<unknown>;\n destroy: () => void;\n iframe: HTMLIFrameElement;\n } | null>(null);\n const previewReadyRef = useRef(false);\n const sandboxReadyRef = useRef(false);\n const executedIndexRef = useRef(0);\n const pendingQueueRef = useRef<string[]>([]);\n const jsFunctionsInjectedRef = useRef(false);\n\n // Effect 0 — Preview sandbox creation\n useEffect(() => {\n const container = containerRef.current;\n if (!container || fullHtml || !hasPreview || previewSandboxRef.current)\n return;\n\n let cancelled = false;\n\n import(\"@jetbrains/websandbox\")\n .then((mod: any) => {\n if (cancelled) return;\n\n const Websandbox = mod.default?.default ?? mod.default;\n const sandbox = Websandbox.create(\n {},\n {\n frameContainer: container,\n frameContent: \"<head></head><body></body>\",\n allowAdditionalAttributes: \"\",\n },\n );\n previewSandboxRef.current = sandbox;\n\n sandbox.iframe.style.width = \"100%\";\n sandbox.iframe.style.height = \"100%\";\n sandbox.iframe.style.border = \"none\";\n sandbox.iframe.style.backgroundColor = \"transparent\";\n\n sandbox.promise.then(() => {\n if (cancelled) return;\n previewReadyRef.current = true;\n\n // Prevent scrollbars inside preview iframe\n sandbox.run(`\n var s = document.createElement('style');\n s.textContent = 'html, body { overflow: hidden !important; }';\n document.head.appendChild(s);\n `);\n\n // Inject CSS from the dedicated parameter + any inline styles from HTML\n const headParts: string[] = [];\n if (css) headParts.push(`<style>${css}</style>`);\n if (previewStyles) headParts.push(previewStyles);\n if (headParts.length) {\n sandbox.run(\n `document.head.innerHTML = ${JSON.stringify(headParts.join(\"\"))}`,\n );\n }\n if (previewBody) {\n sandbox.run(\n `document.body.innerHTML = ${JSON.stringify(previewBody)}`,\n );\n }\n });\n })\n .catch((err: unknown) => {\n console.error(\n \"[OpenGenerativeUI] Failed to load sandbox module:\",\n err,\n );\n });\n\n return () => {\n cancelled = true;\n };\n }, [hasPreview, fullHtml]); // eslint-disable-line react-hooks/exhaustive-deps\n\n // Effect 0b — Preview content updates (body + styles)\n useEffect(() => {\n if (!previewSandboxRef.current || !previewReadyRef.current) return;\n const headParts: string[] = [];\n if (css) headParts.push(`<style>${css}</style>`);\n if (previewStyles) headParts.push(previewStyles);\n if (headParts.length) {\n previewSandboxRef.current.run(\n `document.head.innerHTML = ${JSON.stringify(headParts.join(\"\"))}`,\n );\n }\n if (!previewBody) return;\n previewSandboxRef.current.run(\n `document.body.innerHTML = ${JSON.stringify(previewBody)}`,\n );\n }, [previewBody, previewStyles, css]);\n\n // Effect 1 — Final sandbox lifecycle (depends on fullHtml)\n useEffect(() => {\n const container = containerRef.current;\n if (!container || !fullHtml) return;\n\n // Destroy preview sandbox when transitioning to final\n if (previewSandboxRef.current) {\n previewSandboxRef.current.destroy();\n previewSandboxRef.current = null;\n previewReadyRef.current = false;\n }\n\n let cancelled = false;\n\n // Reset state for new html\n executedIndexRef.current = 0;\n jsFunctionsInjectedRef.current = false;\n sandboxReadyRef.current = false;\n pendingQueueRef.current = [];\n\n // Dynamic import to avoid SSR issues (websandbox references `self` at module level)\n const htmlContent = css ? injectCssIntoHtml(fullHtml, css) : fullHtml;\n import(\"@jetbrains/websandbox\")\n .then((mod: any) => {\n if (cancelled) return;\n\n // websandbox ships a UMD bundle with its own webpack `default` export.\n // Consumer bundlers (e.g. Next.js webpack) wrap CJS under another `.default`,\n // resulting in mod.default.default for the actual Websandbox class.\n const Websandbox = mod.default?.default ?? mod.default;\n const sandbox = Websandbox.create(localApi, {\n frameContainer: container,\n frameContent: ensureHead(htmlContent),\n allowAdditionalAttributes: \"\",\n });\n sandboxRef.current = sandbox;\n\n // Style the iframe to fill container\n sandbox.iframe.style.width = \"100%\";\n sandbox.iframe.style.height = \"100%\";\n sandbox.iframe.style.border = \"none\";\n sandbox.iframe.style.backgroundColor = \"transparent\";\n\n sandbox.promise.then(() => {\n if (cancelled) return;\n sandboxReadyRef.current = true;\n\n // Prevent scrollbars — the container auto-sizes to fit content\n sandbox.run(`\n var s = document.createElement('style');\n s.textContent = 'html, body { overflow: hidden !important; }';\n document.head.appendChild(s);\n `);\n\n // Flush pending queue\n const queue = pendingQueueRef.current;\n pendingQueueRef.current = [];\n for (const code of queue) {\n sandbox.run(code);\n }\n });\n })\n .catch((err: unknown) => {\n console.error(\n \"[OpenGenerativeUI] Failed to load sandbox module:\",\n err,\n );\n });\n\n return () => {\n cancelled = true;\n // Destroy preview sandbox if it still exists\n if (previewSandboxRef.current) {\n previewSandboxRef.current.destroy();\n previewSandboxRef.current = null;\n previewReadyRef.current = false;\n }\n if (sandboxRef.current) {\n sandboxRef.current.destroy();\n sandboxRef.current = null;\n }\n sandboxReadyRef.current = false;\n setAutoHeight(null);\n };\n }, [fullHtml, css, localApi]);\n\n // Effect 2 — jsFunctions injection (depends on content.jsFunctions)\n useEffect(() => {\n if (!content.jsFunctions || jsFunctionsInjectedRef.current) return;\n jsFunctionsInjectedRef.current = true;\n\n const sandbox = sandboxRef.current;\n if (sandboxReadyRef.current && sandbox) {\n sandbox.run(content.jsFunctions);\n } else {\n pendingQueueRef.current.push(content.jsFunctions);\n }\n }, [content.jsFunctions]);\n\n // Effect 3 — jsExpressions execution (depends on content.jsExpressions?.length)\n useEffect(() => {\n const expressions = content.jsExpressions;\n if (!expressions || expressions.length === 0) return;\n\n const startIndex = executedIndexRef.current;\n if (startIndex >= expressions.length) return;\n\n const newExprs = expressions.slice(startIndex);\n executedIndexRef.current = expressions.length;\n\n const sandbox = sandboxRef.current;\n if (sandboxReadyRef.current && sandbox) {\n (async () => {\n for (const expr of newExprs) {\n await sandbox.run(expr);\n }\n })();\n } else {\n pendingQueueRef.current.push(...newExprs);\n }\n }, [content.jsExpressions?.length]);\n\n // Effect 4 — One-shot height measurement (fires once when generation completes)\n // Uses body.scrollHeight (not documentElement.scrollHeight) because the latter\n // is clamped to the iframe viewport and can never shrink below the current size.\n const generationDone = content.generating === false;\n useEffect(() => {\n const sandbox = sandboxRef.current;\n if (!generationDone || !sandbox) return;\n\n let handled = false;\n const onMessage = (e: MessageEvent) => {\n if (handled) return;\n if (\n e.source === sandbox.iframe.contentWindow &&\n e.data?.type === \"__ck_resize\"\n ) {\n handled = true;\n setAutoHeight(e.data.height);\n window.removeEventListener(\"message\", onMessage);\n }\n };\n window.addEventListener(\"message\", onMessage);\n\n const measureOnce = `\n (function() {\n var s = document.createElement('style');\n s.textContent = 'body { height: auto !important; min-height: 0 !important; }';\n document.head.appendChild(s);\n var h = document.body.scrollHeight;\n var cs = getComputedStyle(document.body);\n h += parseFloat(cs.marginTop) || 0;\n h += parseFloat(cs.marginBottom) || 0;\n s.remove();\n parent.postMessage({ type: \"__ck_resize\", height: Math.ceil(h) }, \"*\");\n })();\n `;\n\n if (sandboxReadyRef.current) {\n sandbox.run(measureOnce);\n } else {\n pendingQueueRef.current.push(measureOnce);\n }\n\n return () => {\n window.removeEventListener(\"message\", onMessage);\n };\n }, [generationDone]);\n\n const height = autoHeight ?? initialHeight;\n\n const isGenerating = content.generating !== false;\n\n return (\n <div\n ref={containerRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: `${height}px`,\n borderRadius: \"8px\",\n backgroundColor: hasVisibleSandbox ? \"transparent\" : \"#f5f5f5\",\n border: hasVisibleSandbox ? \"none\" : \"1px solid #e0e0e0\",\n display: hasVisibleSandbox ? \"block\" : \"flex\",\n alignItems: hasVisibleSandbox ? undefined : \"center\",\n justifyContent: hasVisibleSandbox ? undefined : \"center\",\n overflow: \"hidden\",\n }}\n >\n {isGenerating && (\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n zIndex: 10,\n pointerEvents: \"all\",\n backgroundColor: \"rgba(255, 255, 255, 0.5)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n <svg\n width=\"48\"\n height=\"48\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n style={{ animation: \"ck-spin 1s linear infinite\" }}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" stroke=\"#e0e0e0\" strokeWidth=\"3\" />\n <path\n d=\"M12 2a10 10 0 0 1 10 10\"\n stroke=\"#999\"\n strokeWidth=\"3\"\n strokeLinecap=\"round\"\n />\n </svg>\n <style>{`@keyframes ck-spin { to { transform: rotate(360deg) } }`}</style>\n </div>\n )}\n </div>\n );\n },\n (prev, next) => prev.content === next.content,\n);\n\n/**\n * Frontend tool renderer for generateSandboxedUi.\n * Displays placeholder messages while the UI is being generated.\n */\nexport const OpenGenerativeUIToolRenderer: React.FC<\n | {\n name: string;\n args: Partial<GenerateSandboxedUiArgs>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n }\n | {\n name: string;\n args: GenerateSandboxedUiArgs;\n status: ToolCallStatus.Executing;\n result: undefined;\n }\n | {\n name: string;\n args: GenerateSandboxedUiArgs;\n status: ToolCallStatus.Complete;\n result: string;\n }\n> = function OpenGenerativeUIToolRenderer(props) {\n const [visibleMessageIndex, setVisibleMessageIndex] = useState(0);\n const prevMessageCountRef = useRef(0);\n\n const messages = props.args.placeholderMessages;\n\n // Cycle through placeholder messages\n useEffect(() => {\n if (!messages || messages.length === 0) return;\n\n // When a new message streams in, jump to it immediately\n if (messages.length !== prevMessageCountRef.current) {\n prevMessageCountRef.current = messages.length;\n setVisibleMessageIndex(messages.length - 1);\n }\n\n // Auto-cycle every 3s while still in progress\n if (props.status === ToolCallStatus.Complete) return;\n const timer = setInterval(() => {\n setVisibleMessageIndex((i) => (i + 1) % messages.length);\n }, 5000);\n return () => clearInterval(timer);\n }, [messages?.length, props.status]);\n\n // Don't render anything once complete — the activity renderer handles the UI\n if (props.status === ToolCallStatus.Complete) return null;\n\n if (!messages || messages.length === 0) return null;\n\n return (\n <div\n style={{\n padding: \"8px 12px\",\n color: \"#999\",\n fontSize: \"14px\",\n }}\n >\n {messages[visibleMessageIndex] ?? messages[0]}\n </div>\n );\n};\n","import { useCopilotKit } from \"../providers\";\nimport type { ReactActivityMessageRenderer } from \"../types/react-activity-message-renderer\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { z } from \"zod\";\nimport {\n A2UIProvider,\n useA2UIActions,\n useA2UIError,\n A2UIRenderer,\n initializeDefaultCatalog,\n injectStyles,\n DEFAULT_SURFACE_ID,\n} from \"@copilotkit/a2ui-renderer\";\nimport type { Theme, A2UIClientEventMessage } from \"@copilotkit/a2ui-renderer\";\n\n/**\n * The container key used to wrap A2UI operations for explicit detection.\n * Must match A2UI_OPERATIONS_KEY in @ag-ui/a2ui-middleware and copilotkit.a2ui (Python).\n */\nconst A2UI_OPERATIONS_KEY = \"a2ui_operations\";\n\n// Initialize the React renderer's component catalog and styles once\nlet initialized = false;\nfunction ensureInitialized() {\n if (!initialized) {\n initializeDefaultCatalog();\n injectStyles();\n initialized = true;\n }\n}\n\n/**\n * User action with dataContextPath, as dispatched by A2UI components.\n */\nexport type A2UIUserAction = {\n name: string;\n sourceComponentId: string;\n surfaceId: string;\n timestamp: string;\n context?: Record<string, unknown>;\n dataContextPath?: string;\n};\n\nexport type A2UIMessageRendererOptions = {\n theme: Theme;\n /** Optional component catalog to pass to A2UIProvider */\n catalog?: any;\n /** Optional custom loading component shown while A2UI surface is generating. */\n loadingComponent?: React.ComponentType;\n};\n\nexport function createA2UIMessageRenderer(\n options: A2UIMessageRendererOptions,\n): ReactActivityMessageRenderer<any> {\n const { theme, catalog, loadingComponent } = options;\n\n return {\n activityType: \"a2ui-surface\",\n content: z.any(),\n render: ({ content, agent }) => {\n ensureInitialized();\n\n const [operations, setOperations] = useState<any[]>([]);\n const { copilotkit } = useCopilotKit();\n\n const lastContentRef = useRef<unknown>(null);\n useEffect(() => {\n // Skip if same content reference\n if (content === lastContentRef.current) return;\n lastContentRef.current = content;\n\n const incoming = content?.[A2UI_OPERATIONS_KEY];\n if (!content || !Array.isArray(incoming)) {\n setOperations([]);\n return;\n }\n\n setOperations(incoming);\n }, [content]);\n\n // Group operations by surface ID\n const groupedOperations = useMemo(() => {\n const groups = new Map<string, any[]>();\n\n for (const operation of operations) {\n const surfaceId =\n getOperationSurfaceId(operation) ?? DEFAULT_SURFACE_ID;\n\n if (!groups.has(surfaceId)) {\n groups.set(surfaceId, []);\n }\n groups.get(surfaceId)!.push(operation);\n }\n\n return groups;\n }, [operations]);\n\n if (!groupedOperations.size) {\n // Show loading state while A2UI surface is being generated\n const LoadingComponent = loadingComponent ?? DefaultA2UILoading;\n return <LoadingComponent />;\n }\n\n return (\n <div className=\"cpk:flex cpk:min-h-0 cpk:flex-1 cpk:flex-col cpk:gap-6 cpk:overflow-auto cpk:py-6\">\n {Array.from(groupedOperations.entries()).map(([surfaceId, ops]) => (\n <ReactSurfaceHost\n key={surfaceId}\n surfaceId={surfaceId}\n operations={ops}\n theme={theme}\n agent={agent}\n copilotkit={copilotkit}\n catalog={catalog}\n />\n ))}\n </div>\n );\n },\n };\n}\n\ntype ReactSurfaceHostProps = {\n surfaceId: string;\n operations: any[];\n theme: Theme;\n agent: any;\n copilotkit: any;\n /** Optional component catalog to pass to A2UIProvider */\n catalog?: any;\n};\n\n/**\n * Renders a single A2UI surface using the React renderer.\n * Wraps A2UIProvider + A2UIRenderer and bridges actions back to CopilotKit.\n */\nfunction ReactSurfaceHost({\n surfaceId,\n operations,\n theme,\n agent,\n copilotkit,\n catalog,\n}: ReactSurfaceHostProps) {\n // Bridge: when the React renderer dispatches an action, forward to CopilotKit\n const handleAction = useCallback(\n async (message: A2UIClientEventMessage) => {\n if (!agent) return;\n\n const action = message.userAction as A2UIUserAction | undefined;\n\n try {\n copilotkit.setProperties({\n ...(copilotkit.properties ?? {}),\n a2uiAction: message,\n });\n\n await copilotkit.runAgent({ agent });\n } finally {\n if (copilotkit.properties) {\n const { a2uiAction, ...rest } = copilotkit.properties;\n copilotkit.setProperties(rest);\n }\n }\n },\n [agent, copilotkit],\n );\n\n return (\n <div className=\"cpk:flex cpk:w-full cpk:flex-none cpk:flex-col cpk:gap-4\">\n <A2UIProvider onAction={handleAction} theme={theme} catalog={catalog}>\n <SurfaceMessageProcessor\n surfaceId={surfaceId}\n operations={operations}\n />\n <A2UISurfaceOrError surfaceId={surfaceId} />\n </A2UIProvider>\n </div>\n );\n}\n\n/**\n * Renders the A2UI surface, or an error message if processing failed.\n * Must be a child of A2UIProvider to access the error state.\n */\nfunction A2UISurfaceOrError({ surfaceId }: { surfaceId: string }) {\n const error = useA2UIError();\n if (error) {\n return (\n <div className=\"cpk:rounded-lg cpk:border cpk:border-red-200 cpk:bg-red-50 cpk:p-3 cpk:text-sm cpk:text-red-700\">\n A2UI render error: {error}\n </div>\n );\n }\n return <A2UIRenderer surfaceId={surfaceId} className=\"cpk:flex cpk:flex-1\" />;\n}\n\n/**\n * Processes A2UI operations into the provider's message processor.\n * Must be a child of A2UIProvider to access the actions context.\n */\nfunction SurfaceMessageProcessor({\n surfaceId,\n operations,\n}: {\n surfaceId: string;\n operations: any[];\n}) {\n const { processMessages, getSurface } = useA2UIActions();\n const lastHashRef = useRef<string>(\"\");\n useEffect(() => {\n // Skip if operations haven't actually changed (deep compare via hash).\n // ACTIVITY_DELTA + ACTIVITY_SNAPSHOT can trigger multiple renders with\n // the same logical content but different object references.\n const hash = JSON.stringify(operations);\n if (hash === lastHashRef.current) return;\n lastHashRef.current = hash;\n\n // Filter out createSurface if the surface already exists — the\n // MessageProcessor throws on duplicate createSurface, but content\n // snapshots always include the full operation list.\n const existing = getSurface(surfaceId);\n const ops = existing\n ? operations.filter((op) => !op?.createSurface)\n : operations;\n\n // Error handling is done inside A2UIProvider.processMessages\n processMessages(ops);\n }, [processMessages, getSurface, surfaceId, operations]);\n\n return null;\n}\n\n/**\n * Default loading component shown while an A2UI surface is generating.\n * Displays an animated shimmer skeleton.\n */\nfunction DefaultA2UILoading() {\n return (\n <div\n className=\"cpk:flex cpk:flex-col cpk:gap-3 cpk:rounded-xl cpk:border cpk:border-gray-100 cpk:bg-gray-50/50 cpk:p-5\"\n style={{ minHeight: 120 }}\n >\n <div className=\"cpk:flex cpk:items-center cpk:gap-2\">\n <div\n className=\"cpk:h-3 cpk:w-3 cpk:rounded-full cpk:bg-gray-200\"\n style={{\n animation: \"cpk-a2ui-pulse 1.5s ease-in-out infinite\",\n }}\n />\n <span className=\"cpk:text-xs cpk:font-medium cpk:text-gray-400\">\n Generating UI...\n </span>\n </div>\n <div className=\"cpk:flex cpk:flex-col cpk:gap-2\">\n {[0.8, 0.6, 0.4].map((width, i) => (\n <div\n key={i}\n className=\"cpk:h-3 cpk:rounded cpk:bg-gray-200/70\"\n style={{\n width: `${width * 100}%`,\n animation: `cpk-a2ui-pulse 1.5s ease-in-out ${i * 0.15}s infinite`,\n }}\n />\n ))}\n </div>\n <style>{`\n @keyframes cpk-a2ui-pulse {\n 0%, 100% { opacity: 0.4; }\n 50% { opacity: 1; }\n }\n `}</style>\n </div>\n );\n}\n\nfunction getOperationSurfaceId(operation: any): string | null {\n if (!operation || typeof operation !== \"object\") {\n return null;\n }\n\n if (typeof operation.surfaceId === \"string\") {\n return operation.surfaceId;\n }\n\n // v0.9 message keys\n return (\n operation?.createSurface?.surfaceId ??\n operation?.updateComponents?.surfaceId ??\n operation?.updateDataModel?.surfaceId ??\n operation?.deleteSurface?.surfaceId ??\n null\n );\n}\n","import React from \"react\";\nimport { z } from \"zod\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { ReactToolCallRenderer } from \"./react-tool-call-renderer\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\n\n/**\n * Helper to define a type-safe tool call renderer entry.\n * - Accepts a single object whose keys match ReactToolCallRenderer's fields: { name, args, render, agentId? }.\n * - Derives `args` type from the provided schema (any Standard Schema V1 compatible library).\n * - Ensures the render function param type exactly matches ReactToolCallRenderer<T>[\"render\"]'s param.\n * - For wildcard tools (name: \"*\"), args is optional and defaults to z.any()\n */\ntype RenderProps<T> =\n | {\n name: string;\n args: Partial<T>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n }\n | {\n name: string;\n args: T;\n status: ToolCallStatus.Executing;\n result: undefined;\n }\n | {\n name: string;\n args: T;\n status: ToolCallStatus.Complete;\n result: string;\n };\n\n// Overload for wildcard tools without args\nexport function defineToolCallRenderer(def: {\n name: \"*\";\n render: (props: RenderProps<any>) => React.ReactElement;\n agentId?: string;\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: (props: RenderProps<InferSchemaOutput<S>>) => React.ReactElement;\n agentId?: string;\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;\n agentId?: string;\n}): ReactToolCallRenderer<any> {\n // For wildcard tools, default to z.any() if no args provided\n const argsSchema = def.name === \"*\" && !def.args ? z.any() : def.args;\n\n return {\n name: def.name,\n args: argsSchema,\n render: def.render as React.ComponentType<any>,\n ...(def.agentId ? { agentId: def.agentId } : {}),\n };\n}\n","import React, { useEffect, useRef } from \"react\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { defineToolCallRenderer } from \"../types/defineToolCallRenderer\";\nimport { z } from \"zod\";\n\n/**\n * Tool name used by the dynamic A2UI generation secondary LLM.\n * This renderer is auto-registered when A2UI is enabled.\n */\nexport const RENDER_A2UI_TOOL_NAME = \"render_a2ui\";\n\ninterface A2UIProgressProps {\n parameters: unknown;\n}\n\n/**\n * Built-in progress indicator for dynamic A2UI generation.\n * Shows a skeleton wireframe that progressively reveals as tokens stream in.\n *\n * Registered automatically when A2UI is enabled. Users can override by\n * providing their own `useRenderTool({ name: \"render_a2ui\", ... })`.\n */\nfunction A2UIProgressIndicator({ parameters }: A2UIProgressProps) {\n const lastRef = useRef({ time: 0, tokens: 0 });\n const now = Date.now();\n\n let { tokens } = lastRef.current;\n if (now - lastRef.current.time > 200) {\n const chars = JSON.stringify(parameters ?? {}).length;\n tokens = Math.round(chars / 4);\n lastRef.current = { time: now, tokens };\n }\n\n const phase = tokens < 50 ? 0 : tokens < 200 ? 1 : tokens < 400 ? 2 : 3;\n\n return (\n <div style={{ margin: \"12px 0\", maxWidth: 320 }}>\n <div\n style={{\n position: \"relative\",\n overflow: \"hidden\",\n borderRadius: 12,\n border: \"1px solid rgba(228,228,231,0.8)\",\n backgroundColor: \"#fff\",\n boxShadow: \"0 1px 2px rgba(0,0,0,0.04)\",\n padding: \"16px 18px 14px\",\n }}\n >\n {/* Top bar */}\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: 8,\n marginBottom: 12,\n }}\n >\n <div style={{ display: \"flex\", gap: 4 }}>\n <Dot />\n <Dot />\n <Dot />\n </div>\n <Bar\n w={64}\n h={6}\n bg=\"#e4e4e7\"\n opacity={phase >= 1 ? 1 : 0.4}\n transition=\"opacity 0.5s\"\n />\n </div>\n\n {/* Skeleton lines */}\n <div style={{ display: \"grid\", gap: 7 }}>\n <Row show={phase >= 0}>\n <Bar w={36} h={7} bg=\"rgba(147,197,253,0.7)\" anim={0} />\n <Bar w={80} h={7} bg=\"rgba(219,234,254,0.8)\" anim={0.2} />\n </Row>\n <Row show={phase >= 0} delay={0.1}>\n <Spacer />\n <Dot />\n <Bar w={100} h={7} bg=\"rgba(24,24,27,0.2)\" anim={0.3} />\n </Row>\n <Row show={phase >= 1} delay={0.15}>\n <Spacer />\n <Bar w={48} h={7} bg=\"rgba(24,24,27,0.15)\" anim={0.1} />\n <Bar w={40} h={7} bg=\"rgba(153,246,228,0.6)\" anim={0.5} />\n <Bar w={56} h={7} bg=\"rgba(147,197,253,0.6)\" anim={0.3} />\n </Row>\n <Row show={phase >= 1} delay={0.2}>\n <Spacer />\n <Dot />\n <Bar w={60} h={7} bg=\"rgba(24,24,27,0.15)\" anim={0.4} />\n </Row>\n <Row show={phase >= 2} delay={0.25}>\n <Bar w={40} h={7} bg=\"rgba(153,246,228,0.5)\" anim={0.2} />\n <Dot />\n <Bar w={48} h={7} bg=\"rgba(24,24,27,0.15)\" anim={0.6} />\n <Bar w={64} h={7} bg=\"rgba(147,197,253,0.5)\" anim={0.1} />\n </Row>\n <Row show={phase >= 2} delay={0.3}>\n <Bar w={36} h={7} bg=\"rgba(147,197,253,0.6)\" anim={0.5} />\n <Bar w={36} h={7} bg=\"rgba(24,24,27,0.12)\" anim={0.7} />\n </Row>\n <Row show={phase >= 3} delay={0.35}>\n <Dot />\n <Bar w={44} h={7} bg=\"rgba(24,24,27,0.18)\" anim={0.3} />\n <Dot />\n <Bar w={56} h={7} bg=\"rgba(153,246,228,0.5)\" anim={0.8} />\n <Bar w={48} h={7} bg=\"rgba(147,197,253,0.5)\" anim={0.4} />\n </Row>\n </div>\n\n {/* Shimmer */}\n <div\n style={{\n pointerEvents: \"none\",\n position: \"absolute\",\n inset: 0,\n background:\n \"linear-gradient(105deg, transparent 0%, transparent 40%, rgba(255,255,255,0.6) 50%, transparent 60%, transparent 100%)\",\n backgroundSize: \"250% 100%\",\n animation: \"cpk-a2ui-sweep 3s ease-in-out infinite\",\n }}\n />\n </div>\n\n {/* Label */}\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n gap: 8,\n marginTop: 8,\n }}\n >\n <span\n style={{\n fontSize: 12,\n color: \"#a1a1aa\",\n letterSpacing: \"0.025em\",\n }}\n >\n Building interface\n </span>\n {tokens > 0 && (\n <span\n style={{\n fontSize: 11,\n color: \"#d4d4d8\",\n fontVariantNumeric: \"tabular-nums\",\n }}\n >\n ~{tokens.toLocaleString()} tokens\n </span>\n )}\n </div>\n\n <style>{`\n @keyframes cpk-a2ui-fade {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n @keyframes cpk-a2ui-sweep {\n 0% { background-position: 250% 0; }\n 100% { background-position: -250% 0; }\n }\n `}</style>\n </div>\n );\n}\n\n// --- Primitives ---\n\nfunction Dot() {\n return (\n <div\n style={{\n width: 7,\n height: 7,\n borderRadius: \"50%\",\n backgroundColor: \"#d4d4d8\",\n flexShrink: 0,\n }}\n />\n );\n}\n\nfunction Spacer() {\n return <div style={{ width: 12 }} />;\n}\n\nfunction Bar({\n w,\n h,\n bg,\n anim,\n opacity,\n transition,\n}: {\n w: number;\n h: number;\n bg: string;\n anim?: number;\n opacity?: number;\n transition?: string;\n}) {\n return (\n <div\n style={{\n width: w,\n height: h,\n borderRadius: 9999,\n backgroundColor: bg,\n ...(anim !== undefined\n ? { animation: `cpk-a2ui-fade 2.4s ease-in-out ${anim}s infinite` }\n : {}),\n ...(opacity !== undefined ? { opacity } : {}),\n ...(transition ? { transition } : {}),\n }}\n />\n );\n}\n\nfunction Row({\n children,\n show,\n delay = 0,\n}: {\n children: React.ReactNode;\n show: boolean;\n delay?: number;\n}) {\n return (\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: 6,\n opacity: show ? 1 : 0,\n transition: `opacity 0.4s ${delay}s`,\n }}\n >\n {children}\n </div>\n );\n}\n\n// --- Hook entry point ---\n\n/**\n * Registers the built-in `render_a2ui` tool call renderer via the props-based\n * `setRenderToolCalls` mechanism (not `useRenderTool`).\n *\n * This ensures user-registered `useRenderTool({ name: \"render_a2ui\", ... })`\n * hooks automatically override the built-in, since the merge logic in\n * react-core.ts gives hook-based entries priority over prop-based entries.\n */\nexport function A2UIBuiltInToolCallRenderer(): null {\n const { copilotkit } = useCopilotKit();\n\n useEffect(() => {\n const renderer = defineToolCallRenderer({\n name: RENDER_A2UI_TOOL_NAME,\n args: z.any(),\n render: ({ status, args: parameters }) => {\n if (status === \"complete\") return <></>;\n const params = parameters as any;\n // Hide skeleton once the A2UI surface has enough data to render.\n // For data-bound surfaces: items array is populated.\n // For dashboard-style surfaces: components array has multiple entries\n // (meaning the streaming path is emitting activity snapshots).\n const items = params?.items;\n if (Array.isArray(items) && items.length > 0) return <></>;\n const components = params?.components;\n if (Array.isArray(components) && components.length > 2) return <></>;\n return <A2UIProgressIndicator parameters={parameters} />;\n },\n });\n\n // Register via props-based mechanism so useRenderTool hooks take priority\n const existing = (copilotkit as any)._renderToolCalls ?? [];\n copilotkit.setRenderToolCalls([\n ...existing.filter((rc: any) => rc.name !== RENDER_A2UI_TOOL_NAME),\n renderer,\n ]);\n }, [copilotkit]);\n\n return null;\n}\n","import { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useLayoutEffect, useMemo } from \"react\";\n\n/**\n * Represents any value that can be serialized to JSON.\n */\nexport type JsonSerializable =\n | string\n | number\n | boolean\n | null\n | JsonSerializable[]\n | { [key: string]: JsonSerializable };\n\n/**\n * Context configuration for useAgentContext.\n * Accepts any JSON-serializable value which will be converted to a string.\n */\nexport interface AgentContextInput {\n /** A human-readable description of what this context represents */\n description: string;\n /** The context value - will be converted to a JSON string if not already a string */\n value: JsonSerializable;\n}\n\nexport function useAgentContext(context: AgentContextInput) {\n const { description, value } = context;\n const { copilotkit } = useCopilotKit();\n\n const stringValue = useMemo(() => {\n if (typeof value === \"string\") {\n return value;\n }\n return JSON.stringify(value);\n }, [value]);\n\n useLayoutEffect(() => {\n if (!copilotkit) return;\n\n const id = copilotkit.addContext({ description, value: stringValue });\n return () => {\n copilotkit.removeContext(id);\n };\n }, [description, stringValue, copilotkit]);\n}\n","\"use client\";\n\nimport {\n buildCatalogContextValue,\n A2UI_SCHEMA_CONTEXT_DESCRIPTION,\n extractCatalogComponentSchemas,\n} from \"@copilotkit/a2ui-renderer\";\nimport {\n A2UI_DEFAULT_GENERATION_GUIDELINES,\n A2UI_DEFAULT_DESIGN_GUIDELINES,\n} from \"@copilotkit/shared\";\nimport { useAgentContext } from \"../hooks/use-agent-context\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useLayoutEffect, useMemo } from \"react\";\n\n/**\n * Renders agent context describing the available A2UI catalog and custom components.\n * Only mount this component when A2UI is enabled.\n *\n * When `includeSchema` is true, the full component schemas (JSON Schema) are also\n * sent as context using the same description key as the A2UI middleware, so the\n * middleware can optionally overwrite it with a server-side schema.\n */\nexport function A2UICatalogContext({\n catalog,\n includeSchema,\n}: {\n catalog?: any;\n includeSchema?: boolean;\n}) {\n const contextValue = buildCatalogContextValue(catalog);\n\n useAgentContext({\n description:\n \"A2UI catalog capabilities: available catalog IDs and custom component definitions the client can render.\",\n value: contextValue,\n });\n\n // When includeSchema is true, send full component schemas in the same format\n // as the A2UI middleware so it can overwrite with a server-side schema if needed.\n const { copilotkit } = useCopilotKit();\n const schemaValue = useMemo(\n () =>\n includeSchema !== false\n ? JSON.stringify(extractCatalogComponentSchemas(catalog))\n : null,\n [catalog, includeSchema],\n );\n\n useLayoutEffect(() => {\n if (!copilotkit || !schemaValue) return;\n const ids: string[] = [];\n ids.push(\n copilotkit.addContext({\n description: A2UI_SCHEMA_CONTEXT_DESCRIPTION,\n value: schemaValue,\n }),\n );\n ids.push(\n copilotkit.addContext({\n description:\n \"A2UI generation guidelines — protocol rules, tool arguments, path rules, data model format, and form/two-way-binding instructions.\",\n value: A2UI_DEFAULT_GENERATION_GUIDELINES,\n }),\n );\n ids.push(\n copilotkit.addContext({\n description:\n \"A2UI design guidelines — visual design rules, component hierarchy tips, and action handler patterns.\",\n value: A2UI_DEFAULT_DESIGN_GUIDELINES,\n }),\n );\n return () => {\n for (const id of ids) copilotkit.removeContext(id);\n };\n }, [copilotkit, schemaValue]);\n\n return null;\n}\n","import React from \"react\";\nimport { ReactActivityMessageRenderer, ReactToolCallRenderer } from \"../types\";\nimport { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\nimport {\n CopilotKitCore,\n type CopilotKitCoreConfig,\n type CopilotKitCoreSubscriber,\n type 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 type { AbstractAgent } from \"@ag-ui/client\";\nimport type { FrontendTool } from \"@copilotkit/core\";\nimport type React from \"react\";\nimport {\n createContext,\n useContext,\n type ReactNode,\n useMemo,\n useEffect,\n useLayoutEffect,\n useReducer,\n useRef,\n useState,\n} from \"react\";\nimport { z } from \"zod\";\nimport { CopilotKitInspector } from \"../components/CopilotKitInspector\";\nimport type { Anchor } from \"@copilotkit/web-inspector\";\nimport { LicenseWarningBanner } from \"../components/license-warning-banner\";\nimport {\n createLicenseContextValue,\n type LicenseContextValue,\n} from \"@copilotkit/shared\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport {\n MCPAppsActivityContentSchema,\n MCPAppsActivityRenderer,\n MCPAppsActivityType,\n} from \"../components/MCPAppsActivityRenderer\";\nimport {\n OpenGenerativeUIActivityType,\n OpenGenerativeUIContentSchema,\n OpenGenerativeUIActivityRenderer,\n OpenGenerativeUIToolRenderer,\n GenerateSandboxedUiArgsSchema,\n} from \"../components/OpenGenerativeUIRenderer\";\nimport { createA2UIMessageRenderer } from \"../a2ui/A2UIMessageRenderer\";\nimport { A2UIBuiltInToolCallRenderer } from \"../a2ui/A2UIToolCallRenderer\";\nimport { A2UICatalogContext } from \"../a2ui/A2UICatalogContext\";\nimport { viewerTheme } from \"@copilotkit/a2ui-renderer\";\nimport type { Theme as A2UITheme } from \"@copilotkit/a2ui-renderer\";\nimport { CopilotKitCoreReact } from \"../lib/react-core\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\nimport type { SandboxFunction } from \"../types/sandbox-function\";\nimport { SandboxFunctionsContext } from \"./SandboxFunctionsContext\";\nimport { schemaToJsonSchema } from \"@copilotkit/shared\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\n\nconst HEADER_NAME = \"X-CopilotCloud-Public-Api-Key\";\nconst COPILOT_CLOUD_CHAT_URL = \"https://api.cloud.copilotkit.ai/copilotkit/v1\";\n\nconst DEFAULT_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follow these design principles inspired by shadcn/ui:\n\n- Use a minimal, flat aesthetic. Avoid drop shadows and gradients — rely on subtle borders (1px solid, light gray like #e5e7eb) to define surfaces.\n- Neutral base palette: white backgrounds, zinc/slate gray text (#09090b for headings, #71717a for secondary text). One accent color for interactive elements.\n- Use system font stacks (system-ui, -apple-system, sans-serif) at readable sizes (14px body, 600 weight for headings). Tight line-heights.\n- Small, consistent border-radius (6–8px). Cards and containers use border, not shadow, for separation.\n- Buttons: solid fill for primary (dark bg, white text), outline for secondary (border + transparent bg). Subtle hover state (slight opacity or background shift).\n- Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.\n- Minimal transitions (150ms) for hover/focus states only. No decorative animations.\n- Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;\n\nconst GENERATE_SANDBOXED_UI_DESCRIPTION =\n \"Generate sandboxed UI. \" +\n \"IMPORTANT: The generated code runs in a sandboxed iframe WITHOUT same-origin access. \" +\n \"Do NOT use localStorage, sessionStorage, document.cookie, IndexedDB, or fetch/XMLHttpRequest to same-origin URLs. \" +\n \"To communicate with the host application, use Websandbox.connection.remote.<functionName>(args) which returns a Promise.\\n\\n\" +\n \"You CAN use external libraries from CDNs by including <script> or <link> tags in the HTML <head> (e.g., Chart.js, D3, Three.js, x-data-spreadsheet, etc.). \" +\n \"CDN resources load normally inside the sandbox.\\n\\n\" +\n \"PARAMETER ORDER IS CRITICAL — generate parameters in exactly this order:\\n\" +\n \"1. initialHeight + placeholderMessages (shown to user while generating)\\n\" +\n \"2. css (all styles FIRST — the user sees a placeholder until CSS is complete)\\n\" +\n \"3. html (streams in live — the user watches the UI build as HTML is generated)\\n\" +\n \"4. jsFunctions (reusable helper functions)\\n\" +\n \"5. jsExpressions (applied one-by-one — the user sees each expression take effect)\";\n\n// Define the context value interface - idiomatic React naming\nexport interface CopilotKitContextValue {\n copilotkit: CopilotKitCoreReact;\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\n// Empty set for default context value\nconst EMPTY_SET: ReadonlySet<string> = new Set();\n\n// Create the CopilotKit context\nconst CopilotKitContext = createContext<CopilotKitContextValue>({\n copilotkit: null!,\n executingToolCallIds: EMPTY_SET,\n});\n\nconst LicenseContext = createContext<LicenseContextValue>(\n createLicenseContextValue(null),\n);\n\nexport const useLicenseContext = (): LicenseContextValue =>\n useContext(LicenseContext);\n\n// Provider props interface\nexport interface CopilotKitProviderProps {\n children: ReactNode;\n runtimeUrl?: string;\n headers?: Record<string, string>;\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /**\n * The Copilot Cloud public API key.\n */\n publicApiKey?: string;\n /**\n * Alias for `publicApiKey`\n **/\n publicLicenseKey?: string;\n /**\n * Signed license token for offline verification of premium features.\n * Obtain from https://cloud.copilotkit.ai.\n */\n licenseToken?: string;\n properties?: Record<string, unknown>;\n useSingleEndpoint?: boolean;\n agents__unsafe_dev_only?: Record<string, AbstractAgent>;\n selfManagedAgents?: Record<string, AbstractAgent>;\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n renderCustomMessages?: ReactCustomMessageRenderer[];\n frontendTools?: ReactFrontendTool[];\n humanInTheLoop?: ReactHumanInTheLoop[];\n /**\n * Configuration for OpenGenerativeUI — sandboxed UI generated by the LLM.\n *\n * @example\n * ```tsx\n * <CopilotKit\n * runtimeUrl=\"/api/copilotkit\"\n * openGenerativeUI={{\n * sandboxFunctions: [{ name: \"addToCart\", description: \"…\", parameters: schema, handler: fn }],\n * }}\n * >\n * ```\n */\n openGenerativeUI?: {\n /**\n * Functions made available inside sandboxed iframes.\n * Each function is described to the LLM via agent context and exposed\n * via websandbox's `localApi`.\n *\n * Inside the iframe, call them with:\n * ```js\n * await Websandbox.connection.remote.<functionName>(args)\n * ```\n */\n sandboxFunctions?: SandboxFunction[];\n /**\n * Design guidelines injected as agent context for the `generateSandboxedUi` tool.\n * Override this to control the visual style of generated UIs.\n *\n * A sensible default is provided if omitted.\n */\n designSkill?: string;\n };\n showDevConsole?: boolean | \"auto\";\n /**\n * Error handler called when CopilotKit encounters an error.\n * Fires for all error types (runtime connection failures, agent errors, tool errors).\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Configuration for the A2UI (Agent-to-UI) renderer.\n * The built-in A2UI renderer is activated automatically when the runtime reports\n * that `a2ui` is configured in `CopilotRuntime`. This prop is optional and only\n * needed if you want to override the default theme.\n *\n * @example\n * ```tsx\n * <CopilotKit runtimeUrl=\"/api/copilotkit\" a2ui={{ theme: myCustomTheme }}>\n * {children}\n * </CopilotKit>\n * ```\n */\n a2ui?: {\n /**\n * Override the default A2UI viewer theme.\n * When omitted, the built-in `viewerTheme` from `@copilotkit/a2ui-renderer` is used.\n */\n theme?: A2UITheme;\n /**\n * Optional component catalog to pass to the A2UI renderer.\n * When omitted, the default basicCatalog is used.\n */\n catalog?: any;\n /**\n * Optional custom loading component shown while an A2UI surface is generating.\n * When omitted, a default animated skeleton is shown.\n */\n loadingComponent?: React.ComponentType;\n /**\n * When true (the default), the full component schemas from the catalog are\n * sent as agent context so the agent knows what components and props are\n * available. The A2UI middleware can overwrite this with a server-side\n * schema if configured. Set to false to disable.\n */\n includeSchema?: boolean;\n };\n /**\n * Default throttle interval (in milliseconds) for `useAgent` re-renders\n * triggered by `OnMessagesChanged` notifications. This value is used as\n * a fallback when neither the `useAgent()` hook nor `<CopilotChat>` /\n * `<CopilotSidebar>` / `<CopilotPopup>` specify an explicit `throttleMs`.\n *\n * @default undefined (components/hooks without an explicit throttleMs will be unthrottled)\n */\n defaultThrottleMs?: number;\n /**\n * Default anchor corner for the inspector button and window.\n * Only used on first load before the user drags to a custom position.\n * Defaults to `{ horizontal: \"right\", vertical: \"top\" }`.\n */\n inspectorDefaultAnchor?: Anchor;\n}\n\n// Small helper to normalize array props to a stable reference and warn\nfunction useStableArrayProp<T>(\n prop: T[] | undefined,\n warningMessage?: string,\n isMeaningfulChange?: (initial: T[], next: T[]) => boolean,\n): T[] {\n const empty = useMemo<T[]>(() => [], []);\n const value = prop ?? empty;\n const initial = useRef(value);\n\n useEffect(() => {\n if (\n warningMessage &&\n value !== initial.current &&\n (isMeaningfulChange ? isMeaningfulChange(initial.current, value) : true)\n ) {\n console.error(warningMessage);\n }\n }, [value, warningMessage]);\n\n return value;\n}\n\n// Provider component\nexport const CopilotKitProvider: React.FC<CopilotKitProviderProps> = ({\n children,\n runtimeUrl,\n headers = {},\n credentials,\n publicApiKey,\n publicLicenseKey,\n licenseToken,\n properties = {},\n agents__unsafe_dev_only: agents = {},\n selfManagedAgents = {},\n renderToolCalls,\n renderActivityMessages,\n renderCustomMessages,\n frontendTools,\n humanInTheLoop,\n openGenerativeUI,\n showDevConsole = false,\n useSingleEndpoint,\n onError,\n a2ui,\n defaultThrottleMs,\n inspectorDefaultAnchor,\n}) => {\n const [shouldRenderInspector, setShouldRenderInspector] = useState(false);\n const [runtimeA2UIEnabled, setRuntimeA2UIEnabled] = useState(false);\n const [runtimeOpenGenUIEnabled, setRuntimeOpenGenUIEnabled] = useState(false);\n const openGenUIActive = runtimeOpenGenUIEnabled || !!openGenerativeUI;\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n string | undefined\n >(undefined);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n return;\n }\n\n if (showDevConsole === true) {\n // Explicitly show the inspector\n setShouldRenderInspector(true);\n } else if (showDevConsole === \"auto\") {\n // Show on localhost or 127.0.0.1 only\n const localhostHosts = new Set([\"localhost\", \"127.0.0.1\"]);\n if (localhostHosts.has(window.location.hostname)) {\n setShouldRenderInspector(true);\n } else {\n setShouldRenderInspector(false);\n }\n } else {\n // showDevConsole is false or undefined (default false)\n setShouldRenderInspector(false);\n }\n }, [showDevConsole]);\n\n // Normalize array props to stable references with clear dev warnings\n const renderToolCallsList = useStableArrayProp<ReactToolCallRenderer<any>>(\n renderToolCalls,\n \"renderToolCalls must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n (initial, next) => {\n // Only warn if the shape (names+agentId) changed. Allow identity changes\n // to support updated closures from parents (e.g., Storybook state).\n const key = (rc?: ReactToolCallRenderer<unknown>) =>\n `${rc?.agentId ?? \"\"}:${rc?.name ?? \"\"}`;\n const setFrom = (arr: ReactToolCallRenderer<unknown>[]) =>\n new Set(arr.map(key));\n const a = setFrom(initial);\n const b = setFrom(next);\n if (a.size !== b.size) return true;\n for (const k of a) if (!b.has(k)) return true;\n return false;\n },\n );\n\n const renderCustomMessagesList =\n useStableArrayProp<ReactCustomMessageRenderer>(\n renderCustomMessages,\n \"renderCustomMessages must be a stable array.\",\n );\n\n const renderActivityMessagesList = useStableArrayProp<\n ReactActivityMessageRenderer<any>\n >(renderActivityMessages, \"renderActivityMessages must be a stable array.\");\n\n // Built-in activity renderers that are always included\n const builtInActivityRenderers = useMemo<\n ReactActivityMessageRenderer<any>[]\n >(() => {\n const renderers: ReactActivityMessageRenderer<any>[] = [\n {\n activityType: MCPAppsActivityType,\n content: MCPAppsActivityContentSchema,\n render: MCPAppsActivityRenderer,\n },\n ];\n\n if (openGenUIActive) {\n renderers.push({\n activityType: OpenGenerativeUIActivityType,\n content: OpenGenerativeUIContentSchema,\n render: OpenGenerativeUIActivityRenderer,\n });\n }\n\n if (runtimeA2UIEnabled) {\n renderers.unshift(\n createA2UIMessageRenderer({\n theme: a2ui?.theme ?? viewerTheme,\n catalog: a2ui?.catalog,\n loadingComponent: a2ui?.loadingComponent,\n }),\n );\n }\n\n return renderers;\n }, [runtimeA2UIEnabled, openGenUIActive, a2ui]);\n\n // Combine user-provided activity renderers with built-in ones\n // User-provided renderers take precedence (come first) so they can override built-ins\n const allActivityRenderers = useMemo(() => {\n return [...renderActivityMessagesList, ...builtInActivityRenderers];\n }, [renderActivityMessagesList, builtInActivityRenderers]);\n\n const resolvedPublicKey = publicApiKey ?? publicLicenseKey;\n const mergedAgents = useMemo(\n () => ({ ...agents, ...selfManagedAgents }),\n [agents, selfManagedAgents],\n );\n const hasLocalAgents = mergedAgents && Object.keys(mergedAgents).length > 0;\n\n // Merge a provided publicApiKey into headers (without overwriting an explicit header).\n const mergedHeaders = useMemo(() => {\n if (!resolvedPublicKey) return headers;\n if (headers[HEADER_NAME]) return headers;\n return {\n ...headers,\n [HEADER_NAME]: resolvedPublicKey,\n };\n }, [headers, resolvedPublicKey]);\n\n if (!runtimeUrl && !resolvedPublicKey && !hasLocalAgents) {\n const message =\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\";\n if (process.env.NODE_ENV === \"production\") {\n throw new Error(message);\n } else {\n // In dev/test we warn but allow to facilitate local agents and unit tests.\n console.warn(message);\n }\n }\n\n const chatApiEndpoint =\n runtimeUrl ?? (resolvedPublicKey ? COPILOT_CLOUD_CHAT_URL : undefined);\n\n const frontendToolsList = useStableArrayProp<ReactFrontendTool>(\n frontendTools,\n \"frontendTools must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n );\n const humanInTheLoopList = useStableArrayProp<ReactHumanInTheLoop>(\n humanInTheLoop,\n \"humanInTheLoop must be a stable array. If you want to dynamically add or remove human-in-the-loop tools, use `useHumanInTheLoop` instead.\",\n );\n const sandboxFunctionsList = useStableArrayProp<SandboxFunction>(\n openGenerativeUI?.sandboxFunctions,\n \"openGenerativeUI.sandboxFunctions must be a stable array.\",\n );\n\n // Note: warnings for array identity changes are handled by useStableArrayProp\n\n // Process humanInTheLoop tools to create handlers and add render components\n const processedHumanInTheLoopTools = useMemo(() => {\n const processedTools: FrontendTool[] = [];\n const processedRenderToolCalls: ReactToolCallRenderer<unknown>[] = [];\n\n humanInTheLoopList.forEach((tool) => {\n // Create a promise-based handler for each human-in-the-loop tool\n const frontendTool: FrontendTool = {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n followUp: tool.followUp,\n ...(tool.agentId && { agentId: tool.agentId }),\n handler: async () => {\n // This handler will be replaced by the hook when it runs\n // For provider-level tools, we create a basic handler that waits for user interaction\n return new Promise((resolve) => {\n // The actual implementation will be handled by the render component\n // This is a placeholder that the hook will override\n console.warn(\n `Human-in-the-loop tool '${tool.name}' called but no interactive handler is set up.`,\n );\n resolve(undefined);\n });\n },\n };\n processedTools.push(frontendTool);\n\n // Add the render component to renderToolCalls\n if (tool.render) {\n processedRenderToolCalls.push({\n name: tool.name,\n args: tool.parameters!,\n render: tool.render,\n ...(tool.agentId && { agentId: tool.agentId }),\n } as ReactToolCallRenderer<unknown>);\n }\n });\n\n return { tools: processedTools, renderToolCalls: processedRenderToolCalls };\n }, [humanInTheLoopList]);\n\n // Built-in frontend tool for generateSandboxedUi — registered only when the runtime has openGenerativeUI enabled\n const builtInFrontendTools = useMemo<ReactFrontendTool[]>(() => {\n if (!openGenUIActive) return [];\n return [\n {\n name: \"generateSandboxedUi\",\n description: GENERATE_SANDBOXED_UI_DESCRIPTION,\n parameters: GenerateSandboxedUiArgsSchema,\n handler: async () => \"UI generated\",\n followUp: true,\n render: OpenGenerativeUIToolRenderer,\n },\n ];\n }, [openGenUIActive]);\n\n // Combine all tools for CopilotKitCore\n const allTools = useMemo(() => {\n const tools: FrontendTool[] = [];\n\n // Add frontend tools (user-provided + built-in)\n tools.push(...frontendToolsList);\n tools.push(...builtInFrontendTools);\n\n // Add processed human-in-the-loop tools\n tools.push(...processedHumanInTheLoopTools.tools);\n\n return tools;\n }, [frontendToolsList, builtInFrontendTools, processedHumanInTheLoopTools]);\n\n // Combine all render tool calls\n const allRenderToolCalls = useMemo(() => {\n const combined: ReactToolCallRenderer<unknown>[] = [...renderToolCallsList];\n\n // Add render components from frontend tools (user-provided + built-in)\n [...frontendToolsList, ...builtInFrontendTools].forEach((tool) => {\n if (tool.render) {\n // For wildcard tools without parameters, default to z.any()\n const args =\n tool.parameters || (tool.name === \"*\" ? z.any() : undefined);\n if (args) {\n combined.push({\n name: tool.name,\n args: args,\n render: tool.render,\n } as ReactToolCallRenderer<unknown>);\n }\n }\n });\n\n // Add render components from human-in-the-loop tools\n combined.push(...processedHumanInTheLoopTools.renderToolCalls);\n\n return combined;\n }, [\n renderToolCallsList,\n frontendToolsList,\n builtInFrontendTools,\n processedHumanInTheLoopTools,\n ]);\n\n // Stable instance: created once for the provider lifetime.\n // Updates are applied via setter effects below rather than recreating the instance.\n const copilotkitRef = useRef<CopilotKitCoreReact | null>(null);\n if (copilotkitRef.current === null) {\n copilotkitRef.current = new CopilotKitCoreReact({\n runtimeUrl: chatApiEndpoint,\n runtimeTransport:\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n headers: mergedHeaders,\n credentials,\n properties,\n agents__unsafe_dev_only: mergedAgents,\n tools: allTools,\n renderToolCalls: allRenderToolCalls,\n renderActivityMessages: allActivityRenderers,\n renderCustomMessages: renderCustomMessagesList,\n });\n // Set initial defaultThrottleMs synchronously so child hooks see the\n // correct value on their first render (before useEffect fires).\n if (defaultThrottleMs !== undefined) {\n copilotkitRef.current.setDefaultThrottleMs(defaultThrottleMs);\n }\n }\n const copilotkit = copilotkitRef.current;\n\n // Sync runtime feature flags from the core once runtime info is fetched\n useEffect(() => {\n // Check current value immediately (may already be set before subscription)\n setRuntimeA2UIEnabled(copilotkit.a2uiEnabled);\n const subscription = copilotkit.subscribe({\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeA2UIEnabled(copilotkit.a2uiEnabled);\n setRuntimeOpenGenUIEnabled(copilotkit.openGenerativeUIEnabled);\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // Subscribe to render tool calls changes to force re-renders\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onRenderToolCallsChanged: () => {\n forceUpdate();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // Track executing tool call IDs at the provider level.\n // This is critical for HITL reconnection: when connecting to a thread with\n // pending tool calls, the onToolExecutionStart event fires before child components\n // (like CopilotChatToolCallsView) mount. By tracking at the provider level,\n // we ensure the executing state is captured and available when children mount.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // onError subscription — forward core errors to user callback\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n\n const subscription = copilotkit.subscribe({\n onError: (event) => {\n onErrorRef.current?.({\n error: event.error,\n code: event.code,\n context: event.context,\n });\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n useEffect(() => {\n copilotkit.setRuntimeUrl(chatApiEndpoint);\n copilotkit.setRuntimeTransport(\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n );\n copilotkit.setHeaders(mergedHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(properties);\n copilotkit.setAgents__unsafe_dev_only(mergedAgents);\n }, [\n copilotkit,\n chatApiEndpoint,\n mergedHeaders,\n credentials,\n properties,\n mergedAgents,\n useSingleEndpoint,\n ]);\n\n // Sync render/tool arrays to the stable instance via setters.\n // On mount, the constructor already receives the correct initial values,\n // so we skip the first invocation. This is critical because child hooks\n // (e.g., useFrontendTool, useHumanInTheLoop) register tools dynamically\n // via addTool()/setRenderToolCalls() in their own effects, which fire\n // BEFORE parent effects (React fires effects bottom-up). If the parent\n // setter effects ran on mount, they would overwrite the children's tools.\n const didMountRef = useRef(false);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setTools(allTools);\n }, [copilotkit, allTools]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderToolCalls(allRenderToolCalls);\n }, [copilotkit, allRenderToolCalls]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderActivityMessages(allActivityRenderers);\n }, [copilotkit, allActivityRenderers]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderCustomMessages(renderCustomMessagesList);\n }, [copilotkit, renderCustomMessagesList]);\n\n // Mark mount complete — must be declared AFTER the setter effects\n // so it runs last in the effect queue on the initial mount cycle.\n useEffect(() => {\n didMountRef.current = true;\n }, []);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (below the\n // ref init) so child hooks see the correct value on their first render.\n // This effect handles subsequent updates when the prop changes.\n useEffect(() => {\n if (\n defaultThrottleMs !== undefined &&\n (!Number.isFinite(defaultThrottleMs) || defaultThrottleMs < 0)\n ) {\n console.error(\n `CopilotKitProvider: defaultThrottleMs must be a non-negative finite number, got ${defaultThrottleMs}. ` +\n `useAgent hooks without an explicit throttleMs will fall back to unthrottled.`,\n );\n }\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Register design skill as agent context for the generateSandboxedUi tool\n const designSkill = openGenerativeUI?.designSkill ?? DEFAULT_DESIGN_SKILL;\n\n useLayoutEffect(() => {\n if (!copilotkit || !openGenUIActive) return;\n\n const id = copilotkit.addContext({\n description:\n \"Design guidelines for the generateSandboxedUi tool. Follow these when building UI.\",\n value: designSkill,\n });\n return () => {\n copilotkit.removeContext(id);\n };\n }, [copilotkit, designSkill, openGenUIActive]);\n\n // Register sandbox functions as agent context so the LLM knows how to call them\n const sandboxFunctionsDescriptors = useMemo(() => {\n if (sandboxFunctionsList.length === 0) return null;\n return JSON.stringify(\n sandboxFunctionsList.map((fn) => ({\n name: fn.name,\n description: fn.description,\n parameters: schemaToJsonSchema(fn.parameters, { zodToJsonSchema }),\n })),\n );\n }, [sandboxFunctionsList]);\n\n useLayoutEffect(() => {\n if (!copilotkit || !sandboxFunctionsDescriptors || !openGenUIActive) return;\n\n const id = copilotkit.addContext({\n description:\n \"Sandbox functions available in generated sandboxed UI code. Call via: await Websandbox.connection.remote.<functionName>(args)\",\n value: sandboxFunctionsDescriptors,\n });\n return () => {\n copilotkit.removeContext(id);\n };\n }, [copilotkit, sandboxFunctionsDescriptors, openGenUIActive]);\n\n const contextValue = useMemo<CopilotKitContextValue>(\n () => ({ copilotkit, executingToolCallIds }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(null),\n [],\n );\n\n return (\n <SandboxFunctionsContext.Provider value={sandboxFunctionsList}>\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n {runtimeA2UIEnabled && <A2UIBuiltInToolCallRenderer />}\n {runtimeA2UIEnabled && (\n <A2UICatalogContext\n catalog={a2ui?.catalog}\n includeSchema={a2ui?.includeSchema}\n />\n )}\n {children}\n {shouldRenderInspector ? (\n <CopilotKitInspector\n core={copilotkit}\n defaultAnchor={inspectorDefaultAnchor}\n />\n ) : null}\n {/* License warnings — driven by server-reported status */}\n {runtimeLicenseStatus === \"none\" && !resolvedPublicKey && (\n <LicenseWarningBanner type=\"no_license\" />\n )}\n {runtimeLicenseStatus === \"expired\" && (\n <LicenseWarningBanner type=\"expired\" />\n )}\n {runtimeLicenseStatus === \"invalid\" && (\n <LicenseWarningBanner type=\"invalid\" />\n )}\n {runtimeLicenseStatus === \"expiring\" && (\n <LicenseWarningBanner type=\"expiring\" />\n )}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n </SandboxFunctionsContext.Provider>\n );\n};\n\n// Hook to use the CopilotKit instance - returns the full context value\nexport const useCopilotKit = (): CopilotKitContextValue => {\n const context = useContext(CopilotKitContext);\n const [, forceUpdate] = useReducer((x) => 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 });\n return () => {\n subscription.unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return context;\n};\n","import React, { useCallback, useMemo, useSyncExternalStore } from \"react\";\nimport { ToolCall, ToolMessage } from \"@ag-ui/core\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\nimport { partialJSONParse } from \"@copilotkit/shared\";\nimport { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\n\nexport interface UseRenderToolCallProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n}\n\n/**\n * Props for the memoized ToolCallRenderer component\n */\ninterface ToolCallRendererProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n RenderComponent: ReactToolCallRenderer<unknown>[\"render\"];\n isExecuting: boolean;\n}\n\n/**\n * Memoized component that renders a single tool call.\n * This prevents unnecessary re-renders when parent components update\n * but the tool call data hasn't changed.\n */\nconst ToolCallRenderer = React.memo(\n function ToolCallRenderer({\n toolCall,\n toolMessage,\n RenderComponent,\n isExecuting,\n }: ToolCallRendererProps) {\n // Memoize args based on the arguments string to maintain stable reference\n const args = useMemo(\n () => partialJSONParse(toolCall.function.arguments),\n [toolCall.function.arguments],\n );\n\n const toolName = toolCall.function.name;\n\n // Render based on status to preserve discriminated union type inference\n if (toolMessage) {\n return (\n <RenderComponent\n name={toolName}\n args={args}\n status={ToolCallStatus.Complete}\n result={toolMessage.content}\n />\n );\n } else if (isExecuting) {\n return (\n <RenderComponent\n name={toolName}\n args={args}\n status={ToolCallStatus.Executing}\n result={undefined}\n />\n );\n } else {\n return (\n <RenderComponent\n name={toolName}\n args={args}\n status={ToolCallStatus.InProgress}\n result={undefined}\n />\n );\n }\n },\n // Custom comparison function to prevent re-renders when tool call data hasn't changed\n (prevProps, nextProps) => {\n // Compare tool call identity and content\n if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;\n if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name)\n return false;\n if (\n prevProps.toolCall.function.arguments !==\n nextProps.toolCall.function.arguments\n )\n return false;\n\n // Compare tool message (result)\n const prevResult = prevProps.toolMessage?.content;\n const nextResult = nextProps.toolMessage?.content;\n if (prevResult !== nextResult) return false;\n\n // Compare executing state\n if (prevProps.isExecuting !== nextProps.isExecuting) return false;\n\n // Compare render component reference\n if (prevProps.RenderComponent !== nextProps.RenderComponent) return false;\n\n return true;\n },\n);\n\n/**\n * Hook that returns a function to render tool calls based on the render functions\n * defined in CopilotKitProvider.\n *\n * @returns A function that takes a tool call and optional tool message and returns the rendered component\n */\nexport function useRenderToolCall() {\n const { copilotkit, executingToolCallIds } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const agentId = config?.agentId ?? DEFAULT_AGENT_ID;\n\n // Subscribe to render tool calls changes using useSyncExternalStore\n // This ensures we always have the latest value, even if subscriptions run in any order\n const renderToolCalls = useSyncExternalStore(\n (callback) => {\n return copilotkit.subscribe({\n onRenderToolCallsChanged: callback,\n }).unsubscribe;\n },\n () => copilotkit.renderToolCalls,\n () => copilotkit.renderToolCalls,\n );\n\n // Note: executingToolCallIds is now provided by CopilotKitProvider context.\n // This is critical for HITL reconnection: when connecting to a thread with\n // pending tool calls, the onToolExecutionStart event fires before child components\n // mount. By tracking at the provider level, the executing state is already\n // available when this hook first runs.\n\n const renderToolCall = useCallback(\n ({\n toolCall,\n toolMessage,\n }: UseRenderToolCallProps): React.ReactElement | null => {\n // Find the render config for this tool call by name\n // For rendering, we show all tool calls regardless of agentId\n // The agentId scoping only affects handler execution (in core)\n // Priority order:\n // 1. Exact match by name (prefer agent-specific if multiple exist)\n // 2. Wildcard (*) renderer\n const exactMatches = renderToolCalls.filter(\n (rc) => rc.name === toolCall.function.name,\n );\n\n // If multiple renderers with same name exist, prefer the one matching our agentId\n const renderConfig =\n exactMatches.find((rc) => rc.agentId === agentId) ||\n exactMatches.find((rc) => !rc.agentId) ||\n exactMatches[0] ||\n renderToolCalls.find((rc) => rc.name === \"*\");\n\n if (!renderConfig) {\n return null;\n }\n\n const RenderComponent = renderConfig.render;\n const isExecuting = executingToolCallIds.has(toolCall.id);\n\n // Use the memoized ToolCallRenderer component to prevent unnecessary re-renders\n return (\n <ToolCallRenderer\n key={toolCall.id}\n toolCall={toolCall}\n toolMessage={toolMessage}\n RenderComponent={RenderComponent}\n isExecuting={isExecuting}\n />\n );\n },\n [renderToolCalls, executingToolCallIds, agentId],\n );\n\n return renderToolCall;\n}\n","import { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { useMemo, useEffect, useReducer, useRef } from \"react\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\nimport { AbstractAgent, HttpAgent } from \"@ag-ui/client\";\nimport {\n ProxiedCopilotRuntimeAgent,\n CopilotKitCoreRuntimeConnectionStatus,\n} from \"@copilotkit/core\";\n\nexport enum UseAgentUpdate {\n OnMessagesChanged = \"OnMessagesChanged\",\n OnStateChanged = \"OnStateChanged\",\n OnRunStatusChanged = \"OnRunStatusChanged\",\n}\n\nconst ALL_UPDATES: UseAgentUpdate[] = [\n UseAgentUpdate.OnMessagesChanged,\n UseAgentUpdate.OnStateChanged,\n UseAgentUpdate.OnRunStatusChanged,\n];\n\nexport interface UseAgentProps {\n agentId?: string;\n threadId?: string;\n updates?: UseAgentUpdate[];\n /**\n * Throttle interval (in milliseconds) for React re-renders triggered by\n * `OnMessagesChanged` notifications. Useful to reduce re-render frequency\n * during high-frequency message updates such as streaming.\n *\n * Uses leading+trailing: first update fires immediately, subsequent updates\n * within the window are coalesced, and a trailing timer ensures the most\n * recent update fires after the window expires. The trailing edge restarts\n * the throttle window, so no two renders occur within `throttleMs` of each\n * other. Cleanup on unmount cancels any pending trailing timer.\n *\n * Must be a non-negative finite number. Negative or non-finite values fall\n * back to unthrottled behavior with a `console.error`. Only affects\n * `OnMessagesChanged` updates — `OnStateChanged` and `OnRunStatusChanged`\n * always fire immediately. If `updates` does not include\n * `OnMessagesChanged`, this property has no effect.\n *\n * Default: `0` (no throttle).\n */\n throttleMs?: number;\n}\n\n/**\n * Clone a registry agent for per-thread isolation.\n * Copies agent configuration (transport, headers, etc.) but resets conversation\n * state (messages, threadId, state) so each thread starts fresh.\n */\nfunction cloneForThread(\n source: AbstractAgent,\n threadId: string,\n headers: Record<string, string>,\n): AbstractAgent {\n const clone = source.clone();\n if (clone === source) {\n throw new Error(\n `useAgent: ${source.constructor.name}.clone() returned the same instance. ` +\n `clone() must return a new, independent object.`,\n );\n }\n clone.threadId = threadId;\n clone.setMessages([]);\n clone.setState({});\n if (clone instanceof HttpAgent) {\n clone.headers = { ...headers };\n }\n return clone;\n}\n\n/**\n * Module-level WeakMap: registryAgent → (threadId → clone).\n * Shared across all useAgent() calls so that every component using the same\n * (agentId, threadId) pair receives the same agent instance. Using WeakMap\n * ensures the clone map is garbage-collected when the registry agent is\n * replaced (e.g. after reconnect or hot-reload).\n */\nexport const globalThreadCloneMap = new WeakMap<\n AbstractAgent,\n Map<string, AbstractAgent>\n>();\n\n/**\n * Look up an existing per-thread clone without creating one.\n * Returns undefined when no clone has been created yet for this pair.\n */\nexport function getThreadClone(\n registryAgent: AbstractAgent | undefined | null,\n threadId: string | undefined | null,\n): AbstractAgent | undefined {\n if (!registryAgent || !threadId) return undefined;\n return globalThreadCloneMap.get(registryAgent)?.get(threadId);\n}\n\nfunction getOrCreateThreadClone(\n existing: AbstractAgent,\n threadId: string,\n headers: Record<string, string>,\n): AbstractAgent {\n let byThread = globalThreadCloneMap.get(existing);\n if (!byThread) {\n byThread = new Map();\n globalThreadCloneMap.set(existing, byThread);\n }\n const cached = byThread.get(threadId);\n if (cached) return cached;\n\n const clone = cloneForThread(existing, threadId, headers);\n byThread.set(threadId, clone);\n return clone;\n}\n\nexport function useAgent({\n agentId,\n threadId,\n updates,\n throttleMs,\n}: UseAgentProps = {}) {\n agentId ??= DEFAULT_AGENT_ID;\n\n const { copilotkit } = useCopilotKit();\n const providerThrottleMs = copilotkit.defaultThrottleMs;\n // Fall back to the enclosing CopilotChatConfigurationProvider's threadId so\n // that useAgent() called without explicit threadId (e.g. inside a custom\n // message renderer) automatically uses the same per-thread clone as the\n // CopilotChat component it lives within.\n const chatConfig = useCopilotChatConfiguration();\n threadId ??= chatConfig?.threadId;\n\n const effectiveThrottleMs = useMemo(() => {\n const resolved = throttleMs ?? providerThrottleMs ?? 0;\n if (!Number.isFinite(resolved) || resolved < 0) {\n // When both throttleMs and providerThrottleMs are undefined, resolved\n // is 0 which passes validation — so one of them must be defined here.\n const source =\n throttleMs !== undefined\n ? \"hook-level throttleMs\"\n : \"provider-level defaultThrottleMs\";\n console.error(\n `useAgent: ${source} must be a non-negative finite number, got ${resolved}. Falling back to unthrottled.`,\n );\n return 0;\n }\n return resolved;\n }, [throttleMs, providerThrottleMs]);\n\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n const updateFlags = useMemo(\n () => updates ?? ALL_UPDATES,\n [JSON.stringify(updates)],\n );\n\n // Cache provisional agents to avoid creating new references on every render\n // while the runtime is still connecting. A new reference would cascade into\n // CopilotChat's connectAgent effect, causing unnecessary HTTP calls.\n const provisionalAgentCache = useRef<Map<string, ProxiedCopilotRuntimeAgent>>(\n new Map(),\n );\n\n const agent: AbstractAgent = useMemo(() => {\n // Use a composite key when threadId is provided so that different threads\n // for the same agent get independent instances.\n const cacheKey = threadId ? `${agentId}:${threadId}` : agentId;\n\n const existing = copilotkit.getAgent(agentId);\n if (existing) {\n // Real agent found — clear any cached provisionals for this key and the\n // bare agentId key (handles the case where a provisional was created\n // before threadId was available, then the component re-renders with one).\n provisionalAgentCache.current.delete(cacheKey);\n provisionalAgentCache.current.delete(agentId);\n\n if (!threadId) {\n // No threadId — return the shared registry agent (original behavior)\n return existing;\n }\n\n // threadId provided — return the shared per-thread clone.\n // The global WeakMap ensures all components using the same\n // (registryAgent, threadId) pair receive the same instance, so state\n // mutations (addMessage, setState) are visible everywhere. The WeakMap\n // entry is GC-collected automatically when the registry agent is replaced.\n return getOrCreateThreadClone(existing, threadId, copilotkit.headers);\n }\n\n const isRuntimeConfigured = copilotkit.runtimeUrl !== undefined;\n const status = copilotkit.runtimeConnectionStatus;\n\n // While runtime is not yet synced, return a provisional runtime agent\n if (\n isRuntimeConfigured &&\n (status === CopilotKitCoreRuntimeConnectionStatus.Disconnected ||\n status === CopilotKitCoreRuntimeConnectionStatus.Connecting)\n ) {\n // Return cached provisional if available (keeps reference stable)\n const cached = provisionalAgentCache.current.get(cacheKey);\n if (cached) {\n // Update headers on the cached agent in case they changed\n cached.headers = { ...copilotkit.headers };\n return cached;\n }\n\n const provisional = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: copilotkit.runtimeUrl,\n agentId,\n transport: copilotkit.runtimeTransport,\n runtimeMode: \"pending\",\n });\n // Apply current headers so runs/connects inherit them\n provisional.headers = { ...copilotkit.headers };\n if (threadId) {\n provisional.threadId = threadId;\n }\n provisionalAgentCache.current.set(cacheKey, provisional);\n return provisional;\n }\n\n // Runtime is in Error state — return a provisional agent instead of throwing.\n // The error has already been emitted through the subscriber system\n // (RUNTIME_INFO_FETCH_FAILED). Throwing here would crash the React tree;\n // returning a provisional agent lets onError handlers fire while keeping\n // the app alive.\n if (\n isRuntimeConfigured &&\n status === CopilotKitCoreRuntimeConnectionStatus.Error\n ) {\n // Cache the provisional so that dep changes while in Error state (e.g.\n // headers update) return the same agent reference, matching the\n // Disconnected/Connecting path and preventing spurious re-subscriptions.\n const cached = provisionalAgentCache.current.get(cacheKey);\n if (cached) {\n cached.headers = { ...copilotkit.headers };\n return cached;\n }\n const provisional = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: copilotkit.runtimeUrl,\n agentId,\n transport: copilotkit.runtimeTransport,\n runtimeMode: \"pending\",\n });\n provisional.headers = { ...copilotkit.headers };\n if (threadId) {\n provisional.threadId = threadId;\n }\n provisionalAgentCache.current.set(cacheKey, provisional);\n return provisional;\n }\n\n // No runtime configured and agent doesn't exist — this is a configuration error.\n const knownAgents = Object.keys(copilotkit.agents ?? {});\n const runtimePart = isRuntimeConfigured\n ? `runtimeUrl=${copilotkit.runtimeUrl}`\n : \"no runtimeUrl\";\n throw new Error(\n `useAgent: Agent '${agentId}' not found after runtime sync (${runtimePart}). ` +\n (knownAgents.length\n ? `Known agents: [${knownAgents.join(\", \")}]`\n : \"No agents registered.\") +\n \" Verify your runtime /info and/or agents__unsafe_dev_only.\",\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n agentId,\n threadId,\n copilotkit.agents,\n copilotkit.runtimeConnectionStatus,\n copilotkit.runtimeUrl,\n copilotkit.runtimeTransport,\n JSON.stringify(copilotkit.headers),\n ]);\n\n useEffect(() => {\n if (updateFlags.length === 0) return;\n\n const handlers: Parameters<AbstractAgent[\"subscribe\"]>[0] = {};\n let timerId: ReturnType<typeof setTimeout> | null = null;\n let active = true;\n\n if (updateFlags.includes(UseAgentUpdate.OnMessagesChanged)) {\n const ms = effectiveThrottleMs;\n if (ms > 0) {\n // Throttled onMessagesChanged: leading+trailing pattern.\n // First notification fires immediately, subsequent ones within the\n // window are coalesced. Trailing timer fires after the window to\n // ensure the final state is rendered.\n let throttleActive = false;\n // Tracks whether a notification arrived during the throttle window,\n // so the trailing timer knows whether a re-render is needed.\n let pending = false;\n\n const throttledNotify = () => {\n if (!active) return;\n if (!throttleActive) {\n // Leading edge — fire immediately and start the throttle window\n throttleActive = true;\n pending = false;\n forceUpdate();\n timerId = setTimeout(function trailingEdge() {\n timerId = null;\n if (active && pending) {\n // Trailing edge — fire and restart the window\n pending = false;\n forceUpdate();\n timerId = setTimeout(trailingEdge, ms);\n } else {\n // No pending notifications — end the window\n throttleActive = false;\n }\n }, ms);\n } else {\n pending = true;\n }\n };\n\n handlers.onMessagesChanged = throttledNotify;\n } else {\n handlers.onMessagesChanged = forceUpdate;\n }\n }\n\n if (updateFlags.includes(UseAgentUpdate.OnStateChanged)) {\n handlers.onStateChanged = forceUpdate;\n }\n\n if (updateFlags.includes(UseAgentUpdate.OnRunStatusChanged)) {\n handlers.onRunInitialized = forceUpdate;\n handlers.onRunFinalized = forceUpdate;\n handlers.onRunFailed = forceUpdate;\n }\n\n const subscription = agent.subscribe(handlers);\n return () => {\n active = false;\n if (timerId !== null) {\n clearTimeout(timerId);\n }\n subscription.unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agent, forceUpdate, effectiveThrottleMs, updateFlags]);\n\n // Keep HttpAgent headers fresh without mutating inside useMemo, which is\n // unsafe in concurrent mode (React may invoke useMemo multiple times and\n // discard intermediate results, but mutations always land).\n useEffect(() => {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...copilotkit.headers };\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agent, JSON.stringify(copilotkit.headers)]);\n\n return {\n agent,\n };\n}\n","import { useCopilotChatConfiguration, useCopilotKit } from \"../providers\";\nimport { getThreadClone } from \"./use-agent\";\nimport { ReactCustomMessageRendererPosition } from \"../types/react-custom-message-renderer\";\nimport { Message } from \"@ag-ui/core\";\n\ninterface UseRenderCustomMessagesParams {\n message: Message;\n position: ReactCustomMessageRendererPosition;\n}\n\nexport function useRenderCustomMessages() {\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n\n if (!config) {\n return null;\n }\n\n const { agentId, threadId } = config;\n\n const customMessageRenderers = copilotkit.renderCustomMessages\n .filter(\n (renderer) =>\n renderer.agentId === undefined || renderer.agentId === agentId,\n )\n .sort((a, b) => {\n const aHasAgent = a.agentId !== undefined;\n const bHasAgent = b.agentId !== undefined;\n if (aHasAgent === bHasAgent) return 0;\n return aHasAgent ? -1 : 1;\n });\n\n return function (params: UseRenderCustomMessagesParams) {\n if (!customMessageRenderers.length) {\n return null;\n }\n const { message, position } = params;\n const resolvedRunId =\n copilotkit.getRunIdForMessage(agentId, threadId, message.id) ??\n copilotkit.getRunIdsForThread(agentId, threadId).slice(-1)[0];\n const runId = resolvedRunId ?? `missing-run-id:${message.id}`;\n // Prefer the per-thread clone so that agent.messages reflects the actual\n // conversation state (messages live on the clone, not the registry agent).\n // Fall back to the registry agent when no clone exists (no threadId).\n const registryAgent = copilotkit.getAgent(agentId);\n const agent = getThreadClone(registryAgent, threadId) ?? registryAgent;\n if (!agent) {\n throw new Error(\"Agent not found\");\n }\n\n const messagesIdsInRun = resolvedRunId\n ? agent.messages\n .filter(\n (msg) =>\n copilotkit.getRunIdForMessage(agentId, threadId, msg.id) ===\n resolvedRunId,\n )\n .map((msg) => msg.id)\n : [message.id];\n\n const rawMessageIndex = agent.messages.findIndex(\n (msg) => msg.id === message.id,\n );\n const messageIndex = rawMessageIndex >= 0 ? rawMessageIndex : 0;\n const messageIndexInRun = resolvedRunId\n ? Math.max(messagesIdsInRun.indexOf(message.id), 0)\n : 0;\n const numberOfMessagesInRun = resolvedRunId ? messagesIdsInRun.length : 1;\n const stateSnapshot = resolvedRunId\n ? copilotkit.getStateByRun(agentId, threadId, resolvedRunId)\n : undefined;\n\n let result = null;\n for (const renderer of customMessageRenderers) {\n if (!renderer.render) {\n continue;\n }\n const Component = renderer.render;\n result = (\n <Component\n key={`${runId}-${message.id}-${position}`}\n message={message}\n position={position}\n runId={runId}\n messageIndex={messageIndex}\n messageIndexInRun={messageIndexInRun}\n numberOfMessagesInRun={numberOfMessagesInRun}\n agentId={agentId}\n stateSnapshot={stateSnapshot}\n />\n );\n if (result) {\n break;\n }\n }\n return result;\n };\n}\n","import { useEffect } from \"react\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\n\nconst EMPTY_DEPS: ReadonlyArray<unknown> = [];\n\nexport function useFrontendTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactFrontendTool<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n const extraDeps = deps ?? EMPTY_DEPS;\n\n useEffect(() => {\n const name = tool.name;\n\n // Always register/override the tool for this name on mount\n if (copilotkit.getTool({ toolName: name, agentId: tool.agentId })) {\n console.warn(\n `Tool '${name}' already exists for agent '${tool.agentId || \"global\"}'. Overriding with latest registration.`,\n );\n copilotkit.removeTool(name, tool.agentId);\n }\n copilotkit.addTool(tool);\n\n // Register/override renderer by name and agentId through core.\n // The render function is registered even when tool.parameters is\n // undefined — tools like HITL confirm dialogs have no parameters\n // but still need their UI rendered in the chat.\n if (tool.render) {\n copilotkit.addHookRenderToolCall({\n name,\n args: tool.parameters,\n agentId: tool.agentId,\n render: tool.render,\n });\n }\n\n return () => {\n copilotkit.removeTool(name, tool.agentId);\n // we are intentionally not removing the render here so that the tools can still render in the chat history\n };\n // Depend on stable keys by default and allow callers to opt into\n // additional dependencies for dynamic tool configuration.\n // tool.available is included so toggling availability re-registers the tool.\n }, [tool.name, tool.available, copilotkit, extraDeps.length, ...extraDeps]);\n}\n","import { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\nimport { useCallback, useEffect, useRef } from \"react\";\nimport React from \"react\";\nimport { useFrontendTool } from \"./use-frontend-tool\";\n\nexport function useHumanInTheLoop<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactHumanInTheLoop<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n const resolvePromiseRef = useRef<((result: unknown) => void) | null>(null);\n\n const respond = useCallback(async (result: unknown) => {\n if (resolvePromiseRef.current) {\n resolvePromiseRef.current(result);\n resolvePromiseRef.current = null;\n }\n }, []);\n\n const handler = useCallback(async () => {\n return new Promise((resolve) => {\n resolvePromiseRef.current = resolve;\n });\n }, []);\n\n const RenderComponent: ReactToolCallRenderer<T>[\"render\"] = useCallback(\n (props) => {\n const ToolComponent = tool.render;\n\n // Enhance props based on current status\n if (props.status === \"inProgress\") {\n const enhancedProps = {\n ...props,\n name: tool.name,\n description: tool.description || \"\",\n respond: undefined,\n };\n return React.createElement(ToolComponent, enhancedProps);\n } else if (props.status === \"executing\") {\n const enhancedProps = {\n ...props,\n name: tool.name,\n description: tool.description || \"\",\n respond,\n };\n return React.createElement(ToolComponent, enhancedProps);\n } else if (props.status === \"complete\") {\n const enhancedProps = {\n ...props,\n name: tool.name,\n description: tool.description || \"\",\n respond: undefined,\n };\n return React.createElement(ToolComponent, enhancedProps);\n }\n\n // Fallback - just render with original props\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return React.createElement(ToolComponent, props as any);\n },\n [tool.render, tool.name, tool.description, respond],\n );\n\n const frontendTool: ReactFrontendTool<T> = {\n ...tool,\n handler,\n render: RenderComponent,\n };\n\n useFrontendTool(frontendTool, deps);\n\n // Human-in-the-loop tools should remove their renderer on unmount\n // since they can't respond to user interactions anymore\n useEffect(() => {\n return () => {\n copilotkit.removeHookRenderToolCall(tool.name, tool.agentId);\n };\n }, [copilotkit, tool.name, tool.agentId]);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { Suggestion } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\n\nexport interface UseSuggestionsOptions {\n agentId?: string;\n}\n\nexport interface UseSuggestionsResult {\n suggestions: Suggestion[];\n reloadSuggestions: () => void;\n clearSuggestions: () => void;\n isLoading: boolean;\n}\n\nexport function useSuggestions({\n agentId,\n}: UseSuggestionsOptions = {}): UseSuggestionsResult {\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const resolvedAgentId = useMemo(\n () => agentId ?? config?.agentId ?? DEFAULT_AGENT_ID,\n [agentId, config?.agentId],\n );\n\n const [suggestions, setSuggestions] = useState<Suggestion[]>(() => {\n const result = copilotkit.getSuggestions(resolvedAgentId);\n return result.suggestions;\n });\n const [isLoading, setIsLoading] = useState(() => {\n const result = copilotkit.getSuggestions(resolvedAgentId);\n return result.isLoading;\n });\n\n useEffect(() => {\n const result = copilotkit.getSuggestions(resolvedAgentId);\n setSuggestions(result.suggestions);\n setIsLoading(result.isLoading);\n }, [copilotkit, resolvedAgentId]);\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onSuggestionsChanged: ({ agentId: changedAgentId, suggestions }) => {\n if (changedAgentId !== resolvedAgentId) {\n return;\n }\n setSuggestions(suggestions);\n },\n onSuggestionsStartedLoading: ({ agentId: changedAgentId }) => {\n if (changedAgentId !== resolvedAgentId) {\n return;\n }\n setIsLoading(true);\n },\n onSuggestionsFinishedLoading: ({ agentId: changedAgentId }) => {\n if (changedAgentId !== resolvedAgentId) {\n return;\n }\n setIsLoading(false);\n },\n onSuggestionsConfigChanged: () => {\n const result = copilotkit.getSuggestions(resolvedAgentId);\n setSuggestions(result.suggestions);\n setIsLoading(result.isLoading);\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit, resolvedAgentId]);\n\n const reloadSuggestions = useCallback(() => {\n copilotkit.reloadSuggestions(resolvedAgentId);\n // Loading state is handled by onSuggestionsStartedLoading event\n }, [copilotkit, resolvedAgentId]);\n\n const clearSuggestions = useCallback(() => {\n copilotkit.clearSuggestions(resolvedAgentId);\n // State updates are handled by onSuggestionsChanged event\n }, [copilotkit, resolvedAgentId]);\n\n return {\n suggestions,\n reloadSuggestions,\n clearSuggestions,\n isLoading,\n };\n}\n","import { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\nimport {\n DynamicSuggestionsConfig,\n StaticSuggestionsConfig,\n SuggestionsConfig,\n Suggestion,\n} from \"@copilotkit/core\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> &\n Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<\n StaticSuggestionsConfig,\n \"suggestions\"\n> & {\n suggestions: StaticSuggestionInput[];\n};\n\ntype SuggestionsConfigInput =\n | DynamicSuggestionsConfig\n | StaticSuggestionsConfigInput;\n\nexport function useConfigureSuggestions(\n config: SuggestionsConfigInput | null | undefined,\n deps?: ReadonlyArray<unknown>,\n): void {\n const { copilotkit } = useCopilotKit();\n const chatConfig = useCopilotChatConfiguration();\n const extraDeps = deps ?? [];\n\n const resolvedConsumerAgentId = useMemo(\n () => chatConfig?.agentId ?? DEFAULT_AGENT_ID,\n [chatConfig?.agentId],\n );\n\n const rawConsumerAgentId = useMemo(\n () =>\n config ? (config as SuggestionsConfigInput).consumerAgentId : undefined,\n [config],\n );\n\n const normalizationCacheRef = useRef<{\n serialized: string | null;\n config: SuggestionsConfig | null;\n }>({\n serialized: null,\n config: null,\n });\n\n const { normalizedConfig, serializedConfig } = useMemo(() => {\n if (!config) {\n normalizationCacheRef.current = { serialized: null, config: null };\n return { normalizedConfig: null, serializedConfig: null };\n }\n\n if (config.available === \"disabled\") {\n normalizationCacheRef.current = { serialized: null, config: null };\n return { normalizedConfig: null, serializedConfig: null };\n }\n\n let built: SuggestionsConfig;\n if (isDynamicConfig(config)) {\n built = {\n ...config,\n } satisfies DynamicSuggestionsConfig;\n } else {\n const normalizedSuggestions = normalizeStaticSuggestions(\n config.suggestions,\n );\n const baseConfig: StaticSuggestionsConfig = {\n ...config,\n suggestions: normalizedSuggestions,\n };\n built = baseConfig;\n }\n\n const serialized = JSON.stringify(built);\n const cache = normalizationCacheRef.current;\n if (cache.serialized === serialized && cache.config) {\n return { normalizedConfig: cache.config, serializedConfig: serialized };\n }\n\n normalizationCacheRef.current = { serialized, config: built };\n return { normalizedConfig: built, serializedConfig: serialized };\n }, [config, resolvedConsumerAgentId, ...extraDeps]);\n const latestConfigRef = useRef<SuggestionsConfig | null>(null);\n latestConfigRef.current = normalizedConfig;\n const previousSerializedConfigRef = useRef<string | null>(null);\n\n const targetAgentId = useMemo(() => {\n if (!normalizedConfig) {\n return resolvedConsumerAgentId;\n }\n const consumer = (\n normalizedConfig as StaticSuggestionsConfig | DynamicSuggestionsConfig\n ).consumerAgentId;\n if (!consumer || consumer === \"*\") {\n return resolvedConsumerAgentId;\n }\n return consumer;\n }, [normalizedConfig, resolvedConsumerAgentId]);\n\n const isGlobalConfig =\n rawConsumerAgentId === undefined || rawConsumerAgentId === \"*\";\n\n const requestReload = useCallback(() => {\n if (!normalizedConfig) {\n return;\n }\n\n if (isGlobalConfig) {\n const agents = Object.values(copilotkit.agents ?? {});\n for (const entry of agents) {\n const agentId = entry.agentId;\n if (!agentId) {\n continue;\n }\n if (!entry.isRunning) {\n copilotkit.reloadSuggestions(agentId);\n }\n }\n return;\n }\n\n if (!targetAgentId) {\n return;\n }\n\n copilotkit.reloadSuggestions(targetAgentId);\n }, [copilotkit, isGlobalConfig, normalizedConfig, targetAgentId]);\n\n useEffect(() => {\n if (!serializedConfig || !latestConfigRef.current) {\n return;\n }\n\n const id = copilotkit.addSuggestionsConfig(latestConfigRef.current);\n\n requestReload();\n\n return () => {\n copilotkit.removeSuggestionsConfig(id);\n };\n }, [copilotkit, serializedConfig, requestReload]);\n\n useEffect(() => {\n if (!normalizedConfig) {\n previousSerializedConfigRef.current = null;\n return;\n }\n if (\n serializedConfig &&\n previousSerializedConfigRef.current === serializedConfig\n ) {\n return;\n }\n if (serializedConfig) {\n previousSerializedConfigRef.current = serializedConfig;\n }\n requestReload();\n }, [normalizedConfig, requestReload, serializedConfig]);\n\n useEffect(() => {\n if (!normalizedConfig || extraDeps.length === 0) {\n return;\n }\n requestReload();\n }, [extraDeps.length, normalizedConfig, requestReload, ...extraDeps]);\n}\n\nfunction isDynamicConfig(\n config: SuggestionsConfigInput,\n): config is DynamicSuggestionsConfig {\n return \"instructions\" in config;\n}\n\nfunction normalizeStaticSuggestions(\n suggestions: StaticSuggestionInput[],\n): Suggestion[] {\n return suggestions.map((suggestion) => ({\n ...suggestion,\n isLoading: suggestion.isLoading ?? false,\n }));\n}\n","import React, {\n useState,\n useEffect,\n useCallback,\n useMemo,\n useRef,\n} from \"react\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\nimport { useAgent } from \"./use-agent\";\nimport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n} from \"../types/interrupt\";\n\nexport type { InterruptEvent, InterruptRenderProps, InterruptHandlerProps };\n\nconst INTERRUPT_EVENT_NAME = \"on_interrupt\";\n\ntype InterruptHandlerFn<TValue, TResult> = (\n props: InterruptHandlerProps<TValue>,\n) => TResult | PromiseLike<TResult>;\n\ntype InterruptResultFromHandler<THandler> = THandler extends (\n ...args: never[]\n) => infer TResult\n ? TResult extends PromiseLike<infer TResolved>\n ? TResolved | null\n : TResult | null\n : null;\n\ntype InterruptResult<TValue, TResult> = InterruptResultFromHandler<\n InterruptHandlerFn<TValue, TResult>\n>;\n\ntype InterruptRenderInChat = boolean | undefined;\n\ntype UseInterruptReturn<TRenderInChat extends InterruptRenderInChat> =\n TRenderInChat extends false\n ? React.ReactElement | null\n : TRenderInChat extends true | undefined\n ? void\n : React.ReactElement | null | void;\n\nexport function isPromiseLike<TValue>(\n value: TValue | PromiseLike<TValue>,\n): value is PromiseLike<TValue> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") &&\n value !== null &&\n typeof Reflect.get(value, \"then\") === \"function\"\n );\n}\n\n/**\n * Configuration options for `useInterrupt`.\n */\ninterface UseInterruptConfigBase<TValue = unknown, TResult = never> {\n /**\n * Render function for the interrupt UI.\n *\n * This is called once an interrupt is finalized and accepted by `enabled` (if provided).\n * Use `resolve` from render props to resume the agent run with user input.\n */\n render: (\n props: InterruptRenderProps<TValue, InterruptResult<TValue, TResult>>,\n ) => React.ReactElement;\n /**\n * Optional pre-render handler invoked when an interrupt is received.\n *\n * Return either a sync value or an async value to pass into `render` as `result`.\n * Rejecting/throwing falls back to `result = null`.\n */\n handler?: InterruptHandlerFn<TValue, TResult>;\n /**\n * Optional predicate to filter which interrupts should be handled by this hook.\n * Return `false` to ignore an interrupt.\n */\n enabled?: (event: InterruptEvent<TValue>) => boolean;\n /** Optional agent id. Defaults to the current configured chat agent. */\n agentId?: string;\n}\n\nexport interface UseInterruptInChatConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. Set to false to render it yourself. */\n renderInChat?: true;\n}\n\nexport interface UseInterruptExternalConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. Set to false to render it yourself. */\n renderInChat: false;\n}\n\nexport interface UseInterruptDynamicConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** Dynamic boolean mode. When non-literal, return type is a union. */\n renderInChat: boolean;\n}\n\nexport type UseInterruptConfig<\n TValue = unknown,\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n> = UseInterruptConfigBase<TValue, TResult> & {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. Set to false to render it yourself. */\n renderInChat?: TRenderInChat;\n};\n\n/**\n * Handles agent interrupts (`on_interrupt`) with optional filtering, preprocessing, and resume behavior.\n *\n * The hook listens to custom events on the active agent, stores interrupt payloads per run,\n * and surfaces a render callback once the run finalizes. Call `resolve` from your UI to resume\n * execution with user-provided data.\n *\n * - `renderInChat: true` (default): the element is published into `<CopilotChat>` and this hook returns `void`.\n * - `renderInChat: false`: the hook returns the interrupt element so you can place it anywhere in your component tree.\n *\n * `event.value` is typed as `any` since the interrupt payload shape depends on your agent.\n * Type-narrow it in your callbacks (e.g. `handler`, `enabled`, `render`) as needed.\n *\n * @typeParam TResult - Inferred from `handler` return type. Exposed as `result` in `render`.\n * @param config - Interrupt configuration (renderer, optional handler/filter, and render mode).\n * @returns When `renderInChat` is `false`, returns the interrupt element (or `null` when idle).\n * Otherwise returns `void` and publishes the element into chat. In `render`, `result` is always\n * either the handler's resolved return value or `null` (including when no handler is provided,\n * when filtering skips the interrupt, or when handler execution fails).\n *\n * @example\n * ```tsx\n * import { useInterrupt } from \"@copilotkit/react-core/v2\";\n *\n * function InterruptUI() {\n * useInterrupt({\n * render: ({ event, resolve }) => (\n * <div>\n * <p>{event.value.question}</p>\n * <button onClick={() => resolve({ approved: true })}>Approve</button>\n * <button onClick={() => resolve({ approved: false })}>Reject</button>\n * </div>\n * ),\n * });\n *\n * return null;\n * }\n * ```\n *\n * @example\n * ```tsx\n * import { useInterrupt } from \"@copilotkit/react-core/v2\";\n *\n * function CustomPanel() {\n * const interruptElement = useInterrupt({\n * renderInChat: false,\n * enabled: (event) => event.value.startsWith(\"approval:\"),\n * handler: async ({ event }) => ({ label: event.value.toUpperCase() }),\n * render: ({ event, result, resolve }) => (\n * <aside>\n * <strong>{result?.label ?? \"\"}</strong>\n * <button onClick={() => resolve({ value: event.value })}>Continue</button>\n * </aside>\n * ),\n * });\n *\n * return <>{interruptElement}</>;\n * }\n * ```\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport function useInterrupt<\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n>(\n config: UseInterruptConfig<any, TResult, TRenderInChat>,\n): UseInterruptReturn<TRenderInChat> {\n /* eslint-enable @typescript-eslint/no-explicit-any */\n const { copilotkit } = useCopilotKit();\n const { agent } = useAgent({ agentId: config.agentId });\n const [pendingEvent, setPendingEvent] = useState<InterruptEvent | null>(null);\n const pendingEventRef = useRef(pendingEvent);\n pendingEventRef.current = pendingEvent;\n const [handlerResult, setHandlerResult] =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n useState<InterruptResult<any, TResult>>(null);\n\n useEffect(() => {\n let localInterrupt: InterruptEvent | null = null;\n\n const subscription = agent.subscribe({\n onCustomEvent: ({ event }) => {\n if (event.name === INTERRUPT_EVENT_NAME) {\n localInterrupt = { name: event.name, value: event.value };\n }\n },\n onRunStartedEvent: () => {\n localInterrupt = null;\n setPendingEvent(null);\n },\n onRunFinalized: () => {\n if (localInterrupt) {\n setPendingEvent(localInterrupt);\n localInterrupt = null;\n }\n },\n onRunFailed: () => {\n localInterrupt = null;\n },\n });\n\n return () => subscription.unsubscribe();\n }, [agent]);\n\n const resolve = useCallback(\n (response: unknown) => {\n setPendingEvent(null);\n copilotkit.runAgent({\n agent,\n forwardedProps: {\n command: {\n resume: response,\n interruptEvent: pendingEventRef.current?.value,\n },\n },\n });\n },\n [agent, copilotkit],\n );\n\n useEffect(() => {\n // No interrupt to process — reset any stale handler result from a previous interrupt\n if (!pendingEvent) {\n setHandlerResult(null);\n return;\n }\n // Interrupt exists but the consumer's filter rejects it — treat as no-op\n if (config.enabled && !config.enabled(pendingEvent)) {\n setHandlerResult(null);\n return;\n }\n const handler = config.handler;\n // No handler provided — skip straight to rendering with a null result\n if (!handler) {\n setHandlerResult(null);\n return;\n }\n\n let cancelled = false;\n const maybePromise = handler({\n event: pendingEvent,\n resolve,\n });\n\n // If the handler returns a promise/thenable, wait for resolution before setting result.\n if (isPromiseLike(maybePromise)) {\n Promise.resolve(maybePromise)\n .then((resolved) => {\n if (!cancelled) setHandlerResult(resolved);\n })\n .catch(() => {\n if (!cancelled) setHandlerResult(null);\n });\n } else {\n setHandlerResult(maybePromise);\n }\n\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pendingEvent, config.enabled, config.handler, resolve]);\n\n const element = useMemo(() => {\n if (!pendingEvent) return null;\n if (config.enabled && !config.enabled(pendingEvent)) return null;\n\n return config.render({\n event: pendingEvent,\n result: handlerResult,\n resolve,\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pendingEvent, handlerResult, config.enabled, config.render, resolve]);\n\n // Publish to core for in-chat rendering\n useEffect(() => {\n if (config.renderInChat === false) return;\n copilotkit.setInterruptElement(element);\n return () => copilotkit.setInterruptElement(null);\n }, [element, config.renderInChat, copilotkit]);\n\n // Only return element when rendering outside chat\n if (config.renderInChat === false) {\n return element as UseInterruptReturn<TRenderInChat>;\n }\n\n return undefined as UseInterruptReturn<TRenderInChat>;\n}\n","import {\n CopilotCloudConfig,\n FunctionCallHandler,\n CopilotErrorHandler,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport {\n CoAgentStateRender,\n CoAgentStateRenderProps,\n} from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetter,\n QueuedInterruptEvent,\n} from \"../types/interrupt-action\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Optional configuration for connecting to Model Context Protocol (MCP) servers.\n * This is typically derived from the CopilotKitProps and used internally.\n * @experimental\n */\n mcpServers?: Array<{ endpoint: string; apiKey?: string }>;\n}\n\nexport type InChatRenderFunction<\n TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>,\n> = (props: TProps) => string | React.JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | React.JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\nexport type ContextTree = Tree;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // registered actions for component-based rendering\n setRegisteredActions: (actionConfig: any) => string;\n removeRegisteredAction: (actionKey: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (\n context: string,\n parentId?: string,\n categories?: string[],\n ) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (\n documents: DocumentPointer[],\n categories: string[],\n ) => string;\n\n // document context\n addDocumentContext: (\n documentPointer: DocumentPointer,\n categories?: string[],\n ) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: {\n [key: string]: CopilotChatSuggestionConfiguration;\n };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n additionalInstructions?: string[];\n setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean;\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<\n React.SetStateAction<Record<string, CoagentState>>\n >;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Partial<Pick<ForwardedParametersInput, \"temperature\">>;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<\n React.SetStateAction<Record<ActionName, AuthState>>\n >;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n interruptActions: Record<string, LangGraphInterruptRender>;\n setInterruptAction: LangGraphInterruptActionSetter;\n removeInterruptAction: (actionId: string) => void;\n interruptEventQueue: Record<string, QueuedInterruptEvent[]>;\n addInterruptEvent: (queuedEvent: QueuedInterruptEvent) => void;\n resolveInterruptEvent: (\n threadId: string,\n eventId: string,\n response: string,\n ) => void;\n\n /**\n * Optional trace handler for comprehensive debugging and observability.\n */\n onError: CopilotErrorHandler;\n\n // banner error state\n bannerError: CopilotKitError | null;\n setBannerError: React.Dispatch<React.SetStateAction<CopilotKitError | null>>;\n // Internal error handlers\n // These are used to handle errors that occur during the execution of the chat.\n // They are not intended for use by the developer. A component can register itself an error listener to be activated somewhere else as needed\n internalErrorHandlers: Record<string, CopilotErrorHandler>;\n setInternalErrorHandler: (\n handler: Record<string, CopilotErrorHandler>,\n ) => void;\n removeInternalErrorHandler: (id: string) => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n setRegisteredActions: () => \"\",\n removeRegisteredAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n getAllContext: () => [],\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n additionalInstructions: [],\n setAdditionalInstructions: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\n \"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\",\n );\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: false,\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n interruptActions: {},\n setInterruptAction: () => {},\n removeInterruptAction: () => {},\n interruptEventQueue: {},\n addInterruptEvent: () => {},\n resolveInterruptEvent: () => {},\n onError: () => {},\n bannerError: null,\n setBannerError: () => {},\n internalErrorHandlers: {},\n setInternalErrorHandler: () => {},\n removeInternalErrorHandler: () => {},\n};\n\nexport const CopilotContext =\n React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\",\n );\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\n \"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\",\n );\n}\n","import { randomId } from \"@copilotkit/shared\";\nimport { useCallback, useReducer } from \"react\";\n\nexport type TreeNodeId = string;\n\nexport interface TreeNode {\n id: TreeNodeId;\n value: string;\n children: TreeNode[];\n parentId?: TreeNodeId;\n categories: Set<string>;\n}\n\nexport type Tree = TreeNode[];\n\nexport interface UseTreeReturn {\n tree: Tree;\n addElement: (\n value: string,\n categories: string[],\n parentId?: TreeNodeId,\n ) => TreeNodeId;\n printTree: (categories: string[]) => string;\n removeElement: (id: TreeNodeId) => void;\n getAllElements: () => Tree;\n}\n\nconst findNode = (nodes: Tree, id: TreeNodeId): TreeNode | undefined => {\n for (const node of nodes) {\n if (node.id === id) {\n return node;\n }\n const result = findNode(node.children, id);\n if (result) {\n return result;\n }\n }\n return undefined;\n};\n\nconst removeNode = (nodes: Tree, id: TreeNodeId): Tree => {\n return nodes.reduce((result: Tree, node) => {\n if (node.id !== id) {\n const newNode = { ...node, children: removeNode(node.children, id) };\n result.push(newNode);\n }\n return result;\n }, []);\n};\n\nconst addNode = (\n nodes: Tree,\n newNode: TreeNode,\n parentId?: TreeNodeId,\n): Tree => {\n if (!parentId) {\n return [...nodes, newNode];\n }\n return nodes.map((node) => {\n if (node.id === parentId) {\n return { ...node, children: [...node.children, newNode] };\n } else if (node.children.length) {\n return { ...node, children: addNode(node.children, newNode, parentId) };\n }\n return node;\n });\n};\n\nconst treeIndentationRepresentation = (\n index: number,\n indentLevel: number,\n): string => {\n if (indentLevel === 0) {\n return (index + 1).toString();\n } else if (indentLevel === 1) {\n return String.fromCharCode(65 + index); // 65 is the ASCII value for 'A'\n } else if (indentLevel === 2) {\n return String.fromCharCode(97 + index); // 97 is the ASCII value for 'a'\n } else {\n return \"-\";\n }\n};\n\nconst printNode = (node: TreeNode, prefix = \"\", indentLevel = 0): string => {\n const indent = \" \".repeat(3).repeat(indentLevel);\n\n const prefixPlusIndentLength = prefix.length + indent.length;\n const subsequentLinesPrefix = \" \".repeat(prefixPlusIndentLength);\n\n const valueLines = node.value.split(\"\\n\");\n\n const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;\n const outputSubsequentLines = valueLines\n .slice(1)\n .map((line) => `${subsequentLinesPrefix}${line}`)\n .join(\"\\n\");\n\n let output = `${outputFirstLine}\\n`;\n if (outputSubsequentLines) {\n output += `${outputSubsequentLines}\\n`;\n }\n\n const childPrePrefix = \" \".repeat(prefix.length);\n\n node.children.forEach(\n (child, index) =>\n (output += printNode(\n child,\n `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `,\n indentLevel + 1,\n )),\n );\n return output;\n};\n\n// Action types\ntype Action =\n | {\n type: \"ADD_NODE\";\n value: string;\n parentId?: string;\n id: string;\n categories: string[];\n }\n | { type: \"REMOVE_NODE\"; id: string };\n\n// Reducer function\nfunction treeReducer(state: Tree, action: Action): Tree {\n switch (action.type) {\n case \"ADD_NODE\": {\n const { value, parentId, id: newNodeId } = action;\n const newNode: TreeNode = {\n id: newNodeId,\n value,\n children: [],\n categories: new Set(action.categories),\n };\n\n try {\n return addNode(state, newNode, parentId);\n } catch (error) {\n console.error(`Error while adding node with id ${newNodeId}: ${error}`);\n return state;\n }\n }\n case \"REMOVE_NODE\":\n return removeNode(state, action.id);\n default:\n return state;\n }\n}\n\n// useTree hook\nconst useTree = (): UseTreeReturn => {\n const [tree, dispatch] = useReducer(treeReducer, []);\n\n const addElement = useCallback(\n (value: string, categories: string[], parentId?: string): TreeNodeId => {\n const newNodeId = randomId(); // Generate new ID outside of dispatch\n dispatch({\n type: \"ADD_NODE\",\n value,\n parentId,\n id: newNodeId,\n categories: categories,\n });\n return newNodeId; // Return the new ID\n },\n [],\n );\n\n const removeElement = useCallback((id: TreeNodeId): void => {\n dispatch({ type: \"REMOVE_NODE\", id });\n }, []);\n\n const getAllElements = useCallback(() => {\n return tree;\n }, [tree]);\n\n const printTree = useCallback(\n (categories: string[]): string => {\n const categoriesSet = new Set(categories);\n\n let output = \"\";\n tree.forEach((node, index) => {\n // if the node does not have any of the desired categories, continue to the next node\n if (!setsHaveIntersection(categoriesSet, node.categories)) {\n return;\n }\n\n // add a new line before each node except the first one\n if (index !== 0) {\n output += \"\\n\";\n }\n\n output += printNode(\n node,\n `${treeIndentationRepresentation(index, 0)}. `,\n );\n });\n return output;\n },\n [tree],\n );\n\n return { tree, addElement, printTree, removeElement, getAllElements };\n};\n\nexport default useTree;\n\nfunction setsHaveIntersection<T>(setA: Set<T>, setB: Set<T>): boolean {\n const [smallerSet, largerSet] =\n setA.size <= setB.size ? [setA, setB] : [setB, setA];\n\n for (let item of smallerSet) {\n if (largerSet.has(item)) {\n return true;\n }\n }\n\n return false;\n}\n","import { useCallback, useReducer } from \"react\";\nimport { randomId } from \"@copilotkit/shared\";\n\nexport type FlatCategoryStoreId = string;\n\nexport interface UseFlatCategoryStoreReturn<T> {\n addElement: (value: T, categories: string[]) => FlatCategoryStoreId;\n removeElement: (id: FlatCategoryStoreId) => void;\n allElements: (categories: string[]) => T[];\n}\n\ninterface FlatCategoryStoreElement<T> {\n id: FlatCategoryStoreId;\n value: T;\n categories: Set<string>;\n}\n\nconst useFlatCategoryStore = <T>(): UseFlatCategoryStoreReturn<T> => {\n const [elements, dispatch] = useReducer(\n flatCategoryStoreReducer<T>,\n new Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>(),\n );\n\n const addElement = useCallback(\n (value: T, categories: string[]): FlatCategoryStoreId => {\n const newId = randomId();\n dispatch({\n type: \"ADD_ELEMENT\",\n value,\n id: newId,\n categories,\n });\n return newId;\n },\n [],\n );\n\n const removeElement = useCallback((id: FlatCategoryStoreId): void => {\n dispatch({ type: \"REMOVE_ELEMENT\", id });\n }, []);\n\n const allElements = useCallback(\n (categories: string[]): T[] => {\n const categoriesSet = new Set(categories);\n const result: T[] = [];\n elements.forEach((element) => {\n if (setsHaveIntersection(categoriesSet, element.categories)) {\n result.push(element.value);\n }\n });\n return result;\n },\n [elements],\n );\n\n return { addElement, removeElement, allElements };\n};\n\nexport default useFlatCategoryStore;\n\n// Action types\ntype Action<T> =\n | {\n type: \"ADD_ELEMENT\";\n value: T;\n id: FlatCategoryStoreId;\n categories: string[];\n }\n | { type: \"REMOVE_ELEMENT\"; id: FlatCategoryStoreId };\n\n// Reducer\nfunction flatCategoryStoreReducer<T>(\n state: Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>,\n action: Action<T>,\n): Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>> {\n switch (action.type) {\n case \"ADD_ELEMENT\": {\n const { value, id, categories } = action;\n const newElement: FlatCategoryStoreElement<T> = {\n id,\n value,\n categories: new Set(categories),\n };\n const newState = new Map(state);\n newState.set(id, newElement);\n return newState;\n }\n case \"REMOVE_ELEMENT\": {\n const newState = new Map(state);\n newState.delete(action.id);\n return newState;\n }\n default:\n return state;\n }\n}\n\nfunction setsHaveIntersection<T>(setA: Set<T>, setB: Set<T>): boolean {\n const [smallerSet, largerSet] =\n setA.size <= setB.size ? [setA, setB] : [setB, setA];\n\n for (let item of smallerSet) {\n if (largerSet.has(item)) {\n return true;\n }\n }\n\n return false;\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport React from \"react\";\nimport { Suggestion } from \"@copilotkit/core\";\n\nexport interface CopilotMessagesContextParams {\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>; // suggestions state\n suggestions: Suggestion[];\n setSuggestions: React.Dispatch<React.SetStateAction<Suggestion[]>>;\n}\n\nconst emptyCopilotContext: CopilotMessagesContextParams = {\n messages: [],\n setMessages: () => [],\n // suggestions state\n suggestions: [],\n setSuggestions: () => [],\n};\n\nexport const CopilotMessagesContext =\n React.createContext<CopilotMessagesContextParams>(emptyCopilotContext);\n\nexport function useCopilotMessagesContext(): CopilotMessagesContextParams {\n const context = React.useContext(CopilotMessagesContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`\",\n );\n }\n return context;\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { PartialBy, CopilotKitError, Severity } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nfunction formatBannerMessage(message: string): string {\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(/'message':\\s*'([^']+)'/);\n if (jsonMatch) {\n return jsonMatch[1];\n }\n\n // Strip technical garbage but keep the meaningful message\n let cleaned = message.split(\" - \")[0];\n cleaned = cleaned.split(\": Error code\")[0];\n cleaned = cleaned.replace(/:\\s*\\d{3}$/, \"\");\n cleaned = cleaned.replace(/See more:.*$/g, \"\");\n cleaned = cleaned.trim();\n\n return cleaned || \"An error occurred.\";\n}\n\nfunction extractUrl(message: string): { url: string; text: string } | null {\n const markdownMatch = /\\[([^\\]]+)\\]\\(([^)]+)\\)/.exec(message);\n if (markdownMatch) {\n return { url: markdownMatch[2], text: \"See More\" };\n }\n const plainMatch = /(https?:\\/\\/[^\\s)]+)/.exec(message);\n if (plainMatch) {\n return {\n url: plainMatch[0].replace(/[.,;:'\"]*$/, \"\"),\n text: \"See More\",\n };\n }\n return null;\n}\n\nfunction BannerErrorDisplay({\n bannerError,\n onDismiss,\n}: {\n bannerError: CopilotKitError;\n onDismiss: () => void;\n}) {\n const [detailsExpanded, setDetailsExpanded] = useState(false);\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n // Extract optional error details attached by CopilotListeners\n const details = (bannerError as any).details as\n | {\n code?: string;\n context?: Record<string, any>;\n stack?: string;\n originalMessage?: string;\n }\n | undefined;\n\n const link = extractUrl(bannerError.message);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {formatBannerMessage(bannerError.message)}\n </div>\n\n {link && (\n <button\n onClick={() =>\n window.open(link.url, \"_blank\", \"noopener,noreferrer\")\n }\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {link.text}\n </button>\n )}\n\n {details && (\n <button\n onClick={() => setDetailsExpanded(!detailsExpanded)}\n style={{\n background: \"transparent\",\n border: `1px solid ${colors.border}`,\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n color: colors.text,\n flexShrink: 0,\n transition: \"all 0.2s ease\",\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n {detailsExpanded ? \"Hide Details\" : \"Show Details\"}\n </button>\n )}\n </div>\n </div>\n <button\n onClick={onDismiss}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n x\n </button>\n </div>\n\n {detailsExpanded && details && (\n <div\n style={{\n marginTop: \"10px\",\n padding: \"10px\",\n background: \"rgba(0, 0, 0, 0.04)\",\n borderRadius: \"6px\",\n fontSize: \"11px\",\n fontFamily: \"monospace\",\n color: colors.text,\n lineHeight: \"1.5\",\n maxHeight: \"200px\",\n overflowY: \"auto\",\n whiteSpace: \"pre-wrap\",\n wordBreak: \"break-all\",\n }}\n >\n {details.code && (\n <div>\n <strong>Code:</strong> {details.code}\n </div>\n )}\n {details.originalMessage && (\n <div style={{ marginTop: \"4px\" }}>\n <strong>Message:</strong> {details.originalMessage}\n </div>\n )}\n {details.context && Object.keys(details.context).length > 0 && (\n <div style={{ marginTop: \"4px\" }}>\n <strong>Context:</strong>{\" \"}\n {JSON.stringify(details.context, null, 2)}\n </div>\n )}\n {details.stack && (\n <div style={{ marginTop: \"4px\", opacity: 0.7 }}>\n <strong>Stack:</strong>\n {\"\\n\"}\n {details.stack}\n </div>\n )}\n </div>\n )}\n </div>\n );\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(\n null,\n );\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id))\n return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\n \"addGraphQLErrorsToast is deprecated. All errors now show as banners.\",\n );\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError && (\n <BannerErrorDisplay\n bannerError={bannerError}\n onDismiss={() => setBannerError(null)}\n />\n )}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n","function isLocalhost(): boolean {\n if (typeof window === \"undefined\") return false;\n\n return (\n window.location.hostname === \"localhost\" ||\n window.location.hostname === \"127.0.0.1\" ||\n window.location.hostname === \"0.0.0.0\"\n );\n}\n\nexport function shouldShowDevConsole(showDevConsole?: boolean): boolean {\n // If explicitly set, use that value\n if (showDevConsole !== undefined) {\n return showDevConsole;\n }\n\n // If not set, default to true on localhost\n return isLocalhost();\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport {\n ReactNode,\n useEffect,\n useState,\n useRef,\n useCallback,\n useMemo,\n createContext,\n useContext,\n} from \"react\";\nimport { CopilotMessagesContext } from \"../../context/copilot-messages-context\";\nimport {\n loadMessagesFromJsonRepresentation,\n Message,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useCopilotContext } from \"../../context/copilot-context\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { shouldShowDevConsole } from \"../../utils/dev-console\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n} from \"@copilotkit/shared\";\nimport { Suggestion } from \"@copilotkit/core\";\n\n// Helper to determine if error should show as banner based on visibility and legacy patterns\nfunction shouldShowAsBanner(gqlError: GraphQLError): boolean {\n const extensions = gqlError.extensions;\n if (!extensions) return false;\n\n // Priority 1: Check error code for discovery errors (these should always be banners)\n const code = extensions.code as CopilotKitErrorCode;\n if (\n code === CopilotKitErrorCode.AGENT_NOT_FOUND ||\n code === CopilotKitErrorCode.API_NOT_FOUND ||\n code === CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND ||\n code === CopilotKitErrorCode.CONFIGURATION_ERROR ||\n code === CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR ||\n code === CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR\n ) {\n return true;\n }\n\n // Priority 2: Check banner visibility\n if (extensions.visibility === ErrorVisibility.BANNER) {\n return true;\n }\n\n // Priority 3: Check for critical errors that should be banners regardless of formal classification\n const errorMessage = gqlError.message.toLowerCase();\n if (\n errorMessage.includes(\"api key\") ||\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"unauthorized\") ||\n errorMessage.includes(\"authentication\") ||\n errorMessage.includes(\"incorrect api key\")\n ) {\n return true;\n }\n\n // Priority 4: Legacy stack trace detection for discovery errors\n const originalError = extensions.originalError as any;\n if (originalError?.stack) {\n return (\n originalError.stack.includes(\"CopilotApiDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")\n );\n }\n\n return false;\n}\n\n/**\n * MessagesTap is used to mitigate performance issues when we only need\n * a snapshot of the messages, not a continuously updating stream of messages.\n */\n\nexport type MessagesTap = {\n getMessagesFromTap: () => Message[];\n updateTapMessages: (messages: Message[]) => void;\n};\n\nconst MessagesTapContext = createContext<MessagesTap | null>(null);\n\nexport function useMessagesTap() {\n const tap = useContext(MessagesTapContext);\n if (!tap)\n throw new Error(\"useMessagesTap must be used inside <MessagesTapProvider>\");\n return tap;\n}\n\nexport function MessagesTapProvider({\n children,\n}: {\n children: React.ReactNode;\n}) {\n const messagesRef = useRef<Message[]>([]);\n\n const tapRef = useRef<MessagesTap>({\n getMessagesFromTap: () => messagesRef.current,\n updateTapMessages: (messages: Message[]) => {\n messagesRef.current = messages;\n },\n });\n\n return (\n <MessagesTapContext.Provider value={tapRef.current}>\n {children}\n </MessagesTapContext.Provider>\n );\n}\n\n/**\n * CopilotKit messages context.\n */\n\nexport function CopilotMessages({ children }: { children: ReactNode }) {\n const [messages, setMessages] = useState<Message[]>([]);\n const lastLoadedThreadId = useRef<string>(undefined!);\n const lastLoadedAgentName = useRef<string>(undefined!);\n const lastLoadedMessages = useRef<string>(undefined!);\n\n const { updateTapMessages } = useMessagesTap();\n\n const { threadId, agentSession, showDevConsole, onError, copilotApiConfig } =\n useCopilotContext();\n const { setBannerError } = useToast();\n\n // Helper function to trace UI errors (similar to useCopilotRuntimeClient)\n const traceUIError = useCallback(\n async (error: CopilotKitError, originalError?: any) => {\n // Just check if onError and publicApiKey are defined\n if (!onError || !copilotApiConfig.publicApiKey) return;\n\n try {\n const traceEvent = {\n type: \"error\" as const,\n timestamp: Date.now(),\n context: {\n source: \"ui\" as const,\n request: {\n operation: \"loadAgentState\",\n url: copilotApiConfig.chatApiEndpoint,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent:\n typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : undefined,\n stackTrace:\n originalError instanceof Error\n ? originalError.stack\n : undefined,\n },\n },\n error,\n };\n await onError(traceEvent);\n } catch (traceError) {\n console.error(\"Error in CopilotMessages onError handler:\", traceError);\n }\n },\n [onError, copilotApiConfig.publicApiKey, copilotApiConfig.chatApiEndpoint],\n );\n\n const createStructuredError = (\n gqlError: GraphQLError,\n ): CopilotKitError | null => {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n\n // Priority: Check stack trace for discovery errors first\n if (originalError?.stack) {\n if (originalError.stack.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({\n message: originalError.message,\n });\n }\n if (\n originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\")\n ) {\n return new CopilotKitRemoteEndpointDiscoveryError({\n message: originalError.message,\n });\n }\n if (originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n }\n\n // Fallback: Use the formal error code if available\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n return null;\n };\n\n const handleGraphQLErrors = useCallback(\n (error: any) => {\n if (error.graphQLErrors?.length) {\n const graphQLErrors = error.graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole);\n\n if (!isDev) {\n console.error(\n \"CopilotKit Error (hidden in production):\",\n gqlError.message,\n );\n return;\n }\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // All other errors (including DEV_ONLY) show as banners for consistency\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the structured error\n traceUIError(ckError, gqlError);\n } else {\n // Fallback: create a generic error for unstructured GraphQL errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n }\n }\n },\n [setBannerError, showDevConsole, traceUIError],\n );\n\n useEffect(() => {\n updateTapMessages(messages);\n }, [messages, updateTapMessages]);\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [suggestions, setSuggestions] = useState<Suggestion[]>([]);\n\n return (\n <CopilotMessagesContext.Provider\n value={{\n messages,\n setMessages,\n suggestions,\n setSuggestions,\n }}\n >\n {memoizedChildren}\n </CopilotMessagesContext.Provider>\n );\n}\n","import {\n Severity,\n CopilotKitError,\n ErrorVisibility,\n CopilotKitErrorCode,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface UsageBannerProps {\n severity?: Severity;\n message?: string | React.ReactNode;\n onClose?: () => void;\n actions?: {\n primary?: {\n label: string;\n onClick: () => void;\n };\n secondary?: {\n label: string;\n onClick: () => void;\n };\n };\n}\n\nexport function UsageBanner({\n severity = Severity.CRITICAL,\n message = \"\",\n onClose,\n actions,\n}: UsageBannerProps) {\n if (!message || !severity) {\n return null;\n }\n\n const themes = {\n [Severity.INFO]: {\n bg: \"#f8fafc\",\n border: \"#e2e8f0\",\n text: \"#475569\",\n accent: \"#3b82f6\",\n },\n [Severity.WARNING]: {\n bg: \"#fffbeb\",\n border: \"#fbbf24\",\n text: \"#92400e\",\n accent: \"#f59e0b\",\n },\n [Severity.CRITICAL]: {\n bg: \"#fef2f2\",\n border: \"#fecaca\",\n text: \"#dc2626\",\n accent: \"#ef4444\",\n },\n };\n\n const theme = themes[severity];\n\n return (\n <>\n <style>\n {`\n @keyframes slideUp {\n from { opacity: 0; transform: translateX(-50%) translateY(8px); }\n to { opacity: 1; transform: translateX(-50%) translateY(0); }\n }\n \n .usage-banner {\n position: fixed;\n bottom: 24px;\n left: 50%;\n transform: translateX(-50%);\n width: min(600px, calc(100vw - 32px));\n z-index: 10000;\n animation: slideUp 0.2s cubic-bezier(0.16, 1, 0.3, 1);\n }\n \n .banner-content {\n background: linear-gradient(135deg, ${theme.bg} 0%, ${theme.bg}f5 100%);\n border: 1px solid ${theme.border};\n border-radius: 12px;\n padding: 18px 20px;\n box-shadow: \n 0 4px 24px rgba(0, 0, 0, 0.08),\n 0 2px 8px rgba(0, 0, 0, 0.04),\n inset 0 1px 0 rgba(255, 255, 255, 0.7);\n display: flex;\n align-items: center;\n gap: 16px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n backdrop-filter: blur(12px);\n position: relative;\n overflow: hidden;\n }\n \n .banner-content::before {\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n height: 1px;\n background: linear-gradient(90deg, transparent, ${theme.accent}40, transparent);\n }\n \n .banner-message {\n color: ${theme.text};\n font-size: 14px;\n line-height: 1.5;\n font-weight: 500;\n flex: 1;\n letter-spacing: -0.01em;\n }\n \n .close-btn {\n background: rgba(0, 0, 0, 0.05);\n border: none;\n color: ${theme.text};\n cursor: pointer;\n padding: 0;\n border-radius: 6px;\n opacity: 0.6;\n transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);\n font-size: 14px;\n line-height: 1;\n flex-shrink: 0;\n width: 24px;\n height: 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n \n .close-btn:hover {\n opacity: 1;\n background: rgba(0, 0, 0, 0.08);\n transform: scale(1.05);\n }\n \n .btn-primary {\n background: linear-gradient(135deg, ${theme.accent} 0%, ${theme.accent}e6 100%);\n color: white;\n border: none;\n border-radius: 8px;\n padding: 10px 18px;\n font-size: 13px;\n font-weight: 600;\n cursor: pointer;\n transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);\n font-family: inherit;\n flex-shrink: 0;\n box-shadow: \n 0 2px 8px ${theme.accent}30,\n inset 0 1px 0 rgba(255, 255, 255, 0.2);\n letter-spacing: -0.01em;\n }\n \n .btn-primary:hover {\n transform: translateY(-1px) scale(1.02);\n box-shadow: \n 0 4px 12px ${theme.accent}40,\n inset 0 1px 0 rgba(255, 255, 255, 0.25);\n }\n \n .btn-primary:active {\n transform: translateY(0) scale(0.98);\n transition: all 0.08s cubic-bezier(0.16, 1, 0.3, 1);\n }\n \n @media (max-width: 640px) {\n .usage-banner {\n width: calc(100vw - 24px);\n }\n \n .banner-content {\n padding: 16px;\n gap: 12px;\n }\n \n .banner-message {\n font-size: 13px;\n line-height: 1.45;\n }\n \n .btn-primary {\n padding: 8px 14px;\n font-size: 12px;\n }\n \n .close-btn {\n width: 22px;\n height: 22px;\n font-size: 12px;\n }\n }\n `}\n </style>\n\n <div className=\"usage-banner\">\n <div className=\"banner-content\">\n <div className=\"banner-message\">{message}</div>\n {actions?.primary && (\n <button className=\"btn-primary\" onClick={actions.primary.onClick}>\n {actions.primary.label}\n </button>\n )}\n {onClose && (\n <button className=\"close-btn\" onClick={onClose} title=\"Close\">\n ×\n </button>\n )}\n </div>\n </div>\n </>\n );\n}\n\n// Get action button based on error type\nexport const getErrorActions = (error: CopilotKitError) => {\n switch (error.code) {\n case CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR:\n return {\n primary: {\n label: \"Show me how\",\n onClick: () =>\n window.open(\n \"https://docs.copilotkit.ai/premium#how-do-i-get-access-to-premium-features\",\n \"_blank\",\n \"noopener,noreferrer\",\n ),\n },\n };\n case CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR:\n return {\n primary: {\n label: \"Upgrade\",\n onClick: () =>\n window.open(\n \"https://cloud.copilotkit.ai\",\n \"_blank\",\n \"noopener,noreferrer\",\n ),\n },\n };\n default:\n return undefined;\n }\n};\n\nexport function renderCopilotKitUsage(\n error: CopilotKitError,\n onClose?: () => void,\n) {\n // Route based on error visibility level\n if (error.visibility !== ErrorVisibility.BANNER) {\n return null;\n }\n\n return (\n <UsageBanner\n severity={error.severity || Severity.CRITICAL}\n message={error.message}\n onClose={onClose}\n actions={getErrorActions(error)}\n />\n );\n}\n","/**\n * Constants for suggestions retry logic\n */\n\nexport const SUGGESTION_RETRY_CONFIG = {\n MAX_RETRIES: 3,\n COOLDOWN_MS: 5000, // 5 seconds\n} as const;\n","import {\n COPILOT_CLOUD_API_URL,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n Severity,\n} from \"@copilotkit/shared\";\n\nconst STATUS_CHECK_INTERVAL = 1000 * 60 * 5; // 5 minutes\n\nexport type Status = {\n severity: Severity;\n message: string;\n};\n\nexport class StatusChecker {\n private activeKey: string | null = null;\n private intervalId: ReturnType<typeof setInterval> | null = null;\n private instanceCount = 0;\n private lastResponse: Status | null = null;\n\n async start(\n publicApiKey: string,\n onUpdate?: (status: Status | null) => void,\n ) {\n this.instanceCount++;\n if (this.activeKey === publicApiKey) return;\n\n if (this.intervalId) clearInterval(this.intervalId);\n\n const checkStatus = async () => {\n try {\n const response = await fetch(`${COPILOT_CLOUD_API_URL}/ciu`, {\n method: \"GET\",\n headers: {\n [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey,\n },\n }).then((response) => response.json() as Promise<Status>);\n this.lastResponse = response;\n onUpdate?.(response);\n return response;\n } catch (error) {\n // Silently fail\n return null;\n }\n };\n\n const initialResponse = await checkStatus();\n this.intervalId = setInterval(checkStatus, STATUS_CHECK_INTERVAL);\n this.activeKey = publicApiKey;\n return initialResponse;\n }\n\n getLastResponse() {\n return this.lastResponse;\n }\n\n stop() {\n this.instanceCount--;\n if (this.instanceCount === 0) {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = null;\n this.activeKey = null;\n this.lastResponse = null;\n }\n }\n }\n}\n","import React from \"react\";\n\nexport const ExclamationMarkIcon = ({\n className,\n style,\n}: {\n className?: string;\n style?: React.CSSProperties;\n}) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={`lucide lucide-circle-alert ${className ? className : \"\"}`}\n style={style}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"12\" x2=\"12\" y1=\"8\" y2=\"12\" />\n <line x1=\"12\" x2=\"12.01\" y1=\"16\" y2=\"16\" />\n </svg>\n);\n","import React, { useCallback } from \"react\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { ExclamationMarkIcon } from \"../toast/exclamation-mark-icon\";\nimport ReactMarkdown from \"react-markdown\";\n\ninterface OriginalError {\n message?: string;\n stack?: string;\n}\n\nexport function ErrorToast({ errors }: { errors: (Error | GraphQLError)[] }) {\n const errorsToRender = errors.map((error, idx) => {\n const originalError =\n \"extensions\" in error\n ? (error.extensions?.originalError as undefined | OriginalError)\n : {};\n const message = originalError?.message ?? error.message;\n const code =\n \"extensions\" in error ? (error.extensions?.code as string) : null;\n\n return (\n <div\n key={idx}\n style={{\n marginTop: idx === 0 ? 0 : 10,\n marginBottom: 14,\n }}\n >\n <ExclamationMarkIcon style={{ marginBottom: 4 }} />\n\n {code && (\n <div\n style={{\n fontWeight: \"600\",\n marginBottom: 4,\n }}\n >\n Copilot Runtime Error:{\" \"}\n <span style={{ fontFamily: \"monospace\", fontWeight: \"normal\" }}>\n {code}\n </span>\n </div>\n )}\n <ReactMarkdown>{message}</ReactMarkdown>\n </div>\n );\n });\n return (\n <div\n style={{\n fontSize: \"13px\",\n maxWidth: \"600px\",\n }}\n >\n {errorsToRender}\n <div style={{ fontSize: \"11px\", opacity: 0.75 }}>\n NOTE: This error only displays during local development.\n </div>\n </div>\n );\n}\n\nexport function useErrorToast() {\n const { addToast } = useToast();\n\n return useCallback(\n (errors: (Error | GraphQLError)[]) => {\n const errorId = errors\n .map((err) => {\n const message =\n \"extensions\" in err\n ? (err.extensions?.originalError as any)?.message || err.message\n : err.message;\n const stack = err.stack || \"\";\n return btoa(message + stack).slice(0, 32); // Create hash from message + stack\n })\n .join(\"|\");\n\n addToast({\n type: \"error\",\n id: errorId, // Toast libraries typically dedupe by id\n message: <ErrorToast errors={errors} />,\n });\n },\n [addToast],\n );\n}\n\nexport function useAsyncCallback<T extends (...args: any[]) => Promise<any>>(\n callback: T,\n deps: Parameters<typeof useCallback>[1],\n) {\n const addErrorToast = useErrorToast();\n return useCallback(async (...args: Parameters<T>) => {\n try {\n return await callback(...args);\n } catch (error) {\n console.error(\"Error in async callback:\", error);\n // @ts-ignore\n addErrorToast([error]);\n throw error;\n }\n }, deps);\n}\n","import React, { useEffect } from \"react\";\nimport { Severity, CopilotKitError } from \"@copilotkit/shared\";\nimport { StatusChecker } from \"../../lib/status-checker\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { useErrorToast } from \"./error-utils\";\n\nconst statusChecker = new StatusChecker();\n\ninterface Props {\n children: React.ReactNode;\n publicApiKey?: string;\n showUsageBanner?: boolean;\n}\n\ninterface State {\n hasError: boolean;\n error?: CopilotKitError;\n status?: {\n severity: Severity;\n message: string;\n };\n}\n\nexport class CopilotErrorBoundary extends React.Component<Props, State> {\n constructor(props: Props) {\n super(props);\n this.state = {\n hasError: false,\n };\n }\n\n static getDerivedStateFromError(error: CopilotKitError): State {\n return { hasError: true, error };\n }\n\n componentDidMount() {\n if (this.props.publicApiKey) {\n statusChecker.start(this.props.publicApiKey, (newStatus) => {\n this.setState((prevState) => {\n if (newStatus?.severity !== prevState.status?.severity) {\n return { status: newStatus ?? undefined };\n }\n return null;\n });\n });\n }\n }\n\n componentWillUnmount() {\n statusChecker.stop();\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(\"CopilotKit Error:\", error, errorInfo);\n }\n\n render() {\n if (this.state.hasError) {\n if (this.state.error instanceof CopilotKitError) {\n return (\n <>\n {this.props.children}\n {this.props.showUsageBanner && (\n <UsageBanner\n severity={\n this.state.status?.severity ?? this.state.error.severity\n }\n message={this.state.status?.message ?? this.state.error.message}\n actions={getErrorActions(this.state.error)}\n />\n )}\n </>\n );\n }\n throw this.state.error;\n }\n\n return this.props.children;\n }\n}\n\nexport function ErrorToast({\n error,\n children,\n}: {\n error?: Error;\n children: React.ReactNode;\n}) {\n const addErrorToast = useErrorToast();\n\n useEffect(() => {\n if (error) {\n addErrorToast([error]);\n }\n }, [error, addErrorToast]);\n\n if (!error) throw error;\n return children;\n}\n","import React, {\n createContext,\n useContext,\n useCallback,\n useState,\n useRef,\n ReactNode,\n RefObject,\n} from \"react\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\n\ninterface StateRenderClaim {\n stateRenderId: string;\n stateSnapshot?: any;\n runId?: string;\n messageIndex?: number;\n locked?: boolean;\n}\n\ntype ClaimsRef = Record<string, StateRenderClaim>;\n\nexport interface CoAgentStateRendersContextValue {\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (\n id: string,\n stateRender: CoAgentStateRender<any>,\n ) => void;\n removeCoAgentStateRender: (id: string) => void;\n claimsRef: RefObject<ClaimsRef>;\n}\n\nconst CoAgentStateRendersContext = createContext<\n CoAgentStateRendersContextValue | undefined\n>(undefined);\n\nexport function CoAgentStateRendersProvider({\n children,\n}: {\n children: ReactNode;\n}) {\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n\n const setCoAgentStateRender = useCallback(\n (id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => ({\n ...prevPoints,\n [id]: stateRender,\n }));\n },\n [],\n );\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const claimsRef = useRef<ClaimsRef>({});\n\n return (\n <CoAgentStateRendersContext.Provider\n value={{\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n claimsRef,\n }}\n >\n {children}\n </CoAgentStateRendersContext.Provider>\n );\n}\n\nexport function useCoAgentStateRenders() {\n const context = useContext(CoAgentStateRendersContext);\n if (!context) {\n throw new Error(\n \"useCoAgentStateRenders must be used within CoAgentStateRendersProvider\",\n );\n }\n return context;\n}\n\nexport { CoAgentStateRendersContext };\n","import React, {\n createContext,\n useContext,\n useState,\n ReactNode,\n SetStateAction,\n} from \"react\";\nimport { randomUUID } from \"@copilotkit/shared\";\n\nexport interface ThreadsContextValue {\n threadId: string;\n setThreadId: (value: SetStateAction<string>) => void;\n}\n\nconst ThreadsContext = createContext<ThreadsContextValue | undefined>(\n undefined,\n);\n\nexport interface ThreadsProviderProps {\n children: ReactNode;\n threadId?: string;\n}\n\nexport function ThreadsProvider({\n children,\n threadId: explicitThreadId,\n}: ThreadsProviderProps) {\n const [internalThreadId, setThreadId] = useState<string>(() => randomUUID());\n\n const threadId = explicitThreadId ?? internalThreadId;\n\n return (\n <ThreadsContext.Provider\n value={{\n threadId,\n setThreadId,\n }}\n >\n {children}\n </ThreadsContext.Provider>\n );\n}\n\nexport function useThreads() {\n const context = useContext(ThreadsContext);\n if (!context) {\n throw new Error(\"useThreads must be used within ThreadsProvider\");\n }\n return context;\n}\n\nexport { ThreadsContext };\n","import { dataToUUID, parseJson } from \"@copilotkit/shared\";\n\nexport enum RenderStatus {\n InProgress = \"inProgress\",\n Complete = \"complete\",\n}\n\nexport enum ClaimAction {\n Create = \"create\",\n Override = \"override\",\n Existing = \"existing\",\n Block = \"block\",\n}\n\nexport interface StateRenderContext {\n agentId: string;\n stateRenderId: string;\n messageId: string;\n runId: string;\n messageIndex?: number;\n}\n\nexport interface Claim {\n stateRenderId: string;\n runId?: string;\n stateSnapshot?: any;\n locked?: boolean;\n messageIndex?: number;\n}\n\nexport type ClaimsByMessageId = Record<string, Claim>;\n\nexport interface ClaimResolution {\n canRender: boolean;\n action: ClaimAction;\n nextClaim?: Claim;\n lockOthers?: boolean;\n updateRunId?: string;\n}\n\nexport interface SnapshotCaches {\n byStateRenderAndRun: Record<string, any>;\n byMessageId: Record<string, any>;\n}\n\nexport interface SnapshotSelectionInput {\n messageId: string;\n messageName?: string;\n allowLiveState?: boolean;\n skipLatestCache?: boolean;\n stateRenderId?: string;\n effectiveRunId: string;\n stateSnapshotProp?: any;\n agentState?: any;\n agentMessages?: Array<{ id: string; role?: string }>;\n existingClaim?: Claim;\n caches: SnapshotCaches;\n}\n\nexport interface SnapshotSelectionResult {\n snapshot?: any;\n hasSnapshotKeys: boolean;\n cachedSnapshot?: any;\n allowEmptySnapshot?: boolean;\n snapshotForClaim?: any;\n}\n\nfunction getStateWithoutConstantKeys(state: any) {\n if (!state) return {};\n const { messages, tools, copilotkit, ...stateWithoutConstantKeys } = state;\n return stateWithoutConstantKeys;\n}\n\n// Function that compares states, without the constant keys\nexport function areStatesEquals(a: any, b: any) {\n if ((a && !b) || (!a && b)) return false;\n const { messages, tools, copilotkit, ...aWithoutConstantKeys } = a;\n const {\n messages: bMessages,\n tools: bTools,\n copilotkit: bCopilotkit,\n ...bWithoutConstantKeys\n } = b;\n\n return (\n JSON.stringify(aWithoutConstantKeys) ===\n JSON.stringify(bWithoutConstantKeys)\n );\n}\n\nexport function isPlaceholderMessageId(messageId: string | undefined) {\n return !!messageId && messageId.startsWith(\"coagent-state-render-\");\n}\n\nexport function isPlaceholderMessageName(messageName: string | undefined) {\n return messageName === \"coagent-state-render\";\n}\n\nexport function readCachedMessageEntry(entry: any): {\n snapshot?: any;\n runId?: string;\n} {\n if (!entry || typeof entry !== \"object\") {\n return { snapshot: entry, runId: undefined };\n }\n const snapshot = \"snapshot\" in entry ? entry.snapshot : entry;\n const runId = \"runId\" in entry ? entry.runId : undefined;\n return { snapshot, runId };\n}\n\nexport function getEffectiveRunId({\n existingClaimRunId,\n cachedMessageRunId,\n runId,\n}: {\n existingClaimRunId?: string;\n cachedMessageRunId?: string;\n runId?: string;\n}) {\n return existingClaimRunId || cachedMessageRunId || runId || \"pending\";\n}\n\n/**\n * Resolve whether a message can claim a render slot.\n * This is a pure decision function; the caller applies claim mutations.\n */\nexport function resolveClaim({\n claims,\n context,\n stateSnapshot,\n}: {\n claims: ClaimsByMessageId;\n context: StateRenderContext;\n stateSnapshot?: any;\n}): ClaimResolution {\n const { messageId, stateRenderId, runId, messageIndex } = context;\n const existing = claims[messageId];\n\n if (existing) {\n const canRender = existing.stateRenderId === stateRenderId;\n const shouldUpdateRunId =\n canRender && runId && (!existing.runId || existing.runId === \"pending\");\n return {\n canRender,\n action: canRender ? ClaimAction.Existing : ClaimAction.Block,\n updateRunId: shouldUpdateRunId ? runId : undefined,\n };\n }\n\n const normalizedRunId = runId ?? \"pending\";\n const renderClaimedByOtherMessageEntry = Object.entries(claims).find(\n ([, claim]) =>\n claim.stateRenderId === stateRenderId &&\n (claim.runId ?? \"pending\") === normalizedRunId &&\n dataToUUID(getStateWithoutConstantKeys(claim.stateSnapshot)) ===\n dataToUUID(getStateWithoutConstantKeys(stateSnapshot)),\n );\n\n const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry?.[1];\n const claimedMessageId = renderClaimedByOtherMessageEntry?.[0];\n\n if (renderClaimedByOtherMessage) {\n if (\n messageIndex !== undefined &&\n renderClaimedByOtherMessage.messageIndex !== undefined &&\n messageIndex > renderClaimedByOtherMessage.messageIndex\n ) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers:\n runId === renderClaimedByOtherMessage.runId ||\n isPlaceholderMessageId(claimedMessageId),\n };\n }\n\n if (\n runId &&\n renderClaimedByOtherMessage.runId &&\n runId !== renderClaimedByOtherMessage.runId\n ) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers: isPlaceholderMessageId(claimedMessageId),\n };\n }\n\n if (isPlaceholderMessageId(claimedMessageId)) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers: true,\n };\n }\n\n if (\n stateSnapshot &&\n renderClaimedByOtherMessage.stateSnapshot &&\n !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, stateSnapshot)\n ) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId },\n };\n }\n\n return { canRender: false, action: ClaimAction.Block };\n }\n\n if (!runId) {\n return { canRender: false, action: ClaimAction.Block };\n }\n\n return {\n canRender: true,\n action: ClaimAction.Create,\n nextClaim: { stateRenderId, runId, messageIndex },\n };\n}\n\n/**\n * Select the best snapshot to render for this message.\n * Priority order is:\n * 1) explicit message snapshot\n * 2) live agent state (latest assistant only)\n * 3) cached snapshot for message\n * 4) cached snapshot for stateRenderId+runId\n * 5) last cached snapshot for stateRenderId\n */\nexport function selectSnapshot({\n messageId,\n messageName,\n allowLiveState,\n skipLatestCache,\n stateRenderId,\n effectiveRunId,\n stateSnapshotProp,\n agentState,\n agentMessages,\n existingClaim,\n caches,\n}: SnapshotSelectionInput): SnapshotSelectionResult {\n const lastAssistantId = agentMessages\n ? [...agentMessages].reverse().find((msg) => msg.role === \"assistant\")?.id\n : undefined;\n const latestSnapshot =\n stateRenderId !== undefined\n ? caches.byStateRenderAndRun[`${stateRenderId}::latest`]\n : undefined;\n const messageIndex = agentMessages\n ? agentMessages.findIndex((msg) => msg.id === messageId)\n : -1;\n const messageRole =\n messageIndex >= 0 && agentMessages\n ? agentMessages[messageIndex]?.role\n : undefined;\n let previousUserMessageId: string | undefined;\n if (messageIndex > 0 && agentMessages) {\n for (let i = messageIndex - 1; i >= 0; i -= 1) {\n if (agentMessages[i]?.role === \"user\") {\n previousUserMessageId = agentMessages[i]?.id;\n break;\n }\n }\n }\n const liveStateIsStale =\n stateSnapshotProp === undefined &&\n latestSnapshot !== undefined &&\n agentState !== undefined &&\n areStatesEquals(latestSnapshot, agentState);\n const shouldUseLiveState =\n (Boolean(allowLiveState) ||\n !lastAssistantId ||\n messageId === lastAssistantId) &&\n !liveStateIsStale;\n const snapshot = stateSnapshotProp\n ? parseJson(stateSnapshotProp, stateSnapshotProp)\n : shouldUseLiveState\n ? agentState\n : undefined;\n const hasSnapshotKeys = !!(snapshot && Object.keys(snapshot).length > 0);\n const allowEmptySnapshot =\n snapshot !== undefined &&\n !hasSnapshotKeys &&\n (stateSnapshotProp !== undefined || shouldUseLiveState);\n\n const messageCacheEntry = caches.byMessageId[messageId];\n const cachedMessageSnapshot =\n readCachedMessageEntry(messageCacheEntry).snapshot;\n const cacheKey =\n stateRenderId !== undefined\n ? `${stateRenderId}::${effectiveRunId}`\n : undefined;\n let cachedSnapshot = cachedMessageSnapshot ?? caches.byMessageId[messageId];\n if (\n cachedSnapshot === undefined &&\n cacheKey &&\n caches.byStateRenderAndRun[cacheKey] !== undefined\n ) {\n cachedSnapshot = caches.byStateRenderAndRun[cacheKey];\n }\n if (\n cachedSnapshot === undefined &&\n stateRenderId &&\n previousUserMessageId &&\n caches.byStateRenderAndRun[\n `${stateRenderId}::pending:${previousUserMessageId}`\n ] !== undefined\n ) {\n cachedSnapshot =\n caches.byStateRenderAndRun[\n `${stateRenderId}::pending:${previousUserMessageId}`\n ];\n }\n if (\n cachedSnapshot === undefined &&\n !skipLatestCache &&\n stateRenderId &&\n messageRole !== \"assistant\" &&\n (stateSnapshotProp !== undefined ||\n (agentState && Object.keys(agentState).length > 0))\n ) {\n cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::latest`];\n }\n\n const snapshotForClaim = existingClaim?.locked\n ? (existingClaim.stateSnapshot ?? cachedSnapshot)\n : hasSnapshotKeys\n ? snapshot\n : (existingClaim?.stateSnapshot ?? cachedSnapshot);\n\n return {\n snapshot,\n hasSnapshotKeys,\n cachedSnapshot,\n allowEmptySnapshot,\n snapshotForClaim,\n };\n}\n","import { useEffect } from \"react\";\nimport {\n areStatesEquals,\n ClaimAction,\n getEffectiveRunId,\n isPlaceholderMessageId,\n isPlaceholderMessageName,\n readCachedMessageEntry,\n resolveClaim,\n selectSnapshot,\n type Claim,\n type ClaimsByMessageId,\n type SnapshotCaches,\n type StateRenderContext,\n} from \"./use-coagent-state-render-bridge.helpers\";\n\nexport interface StateRenderRegistryInput {\n agentId: string;\n stateRenderId?: string;\n message: { id: string; runId?: string; name?: string };\n messageIndex?: number;\n stateSnapshot?: any;\n agentState?: any;\n agentMessages?: Array<{ id: string; role?: string }>;\n claimsRef: React.MutableRefObject<Record<string, Claim>>;\n}\n\nexport interface StateRenderRegistryResult {\n canRender: boolean;\n}\n\nconst LAST_SNAPSHOTS_BY_RENDER_AND_RUN = \"__lastSnapshotsByStateRenderIdAndRun\";\nconst LAST_SNAPSHOTS_BY_MESSAGE = \"__lastSnapshotsByMessageId\";\n\ntype SnapshotByMessageEntry = { snapshot: any; runId?: string } | any;\ntype ClaimsStore = Record<string, Claim> & {\n [LAST_SNAPSHOTS_BY_RENDER_AND_RUN]?: Record<string, any>;\n [LAST_SNAPSHOTS_BY_MESSAGE]?: Record<string, SnapshotByMessageEntry>;\n};\n\nfunction getClaimsStore(\n claimsRef: React.MutableRefObject<Record<string, Claim>>,\n): ClaimsStore {\n return claimsRef.current as ClaimsStore;\n}\n\nfunction getSnapshotCaches(\n claimsRef: React.MutableRefObject<Record<string, Claim>>,\n): SnapshotCaches {\n const store = getClaimsStore(claimsRef);\n return {\n byStateRenderAndRun: store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {},\n byMessageId: store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {},\n };\n}\n\nexport function useStateRenderRegistry({\n agentId,\n stateRenderId,\n message,\n messageIndex,\n stateSnapshot,\n agentState,\n agentMessages,\n claimsRef,\n}: StateRenderRegistryInput): StateRenderRegistryResult {\n const store = getClaimsStore(claimsRef);\n const runId = message.runId;\n const cachedMessageEntry = store[LAST_SNAPSHOTS_BY_MESSAGE]?.[message.id];\n const { runId: cachedMessageRunId } =\n readCachedMessageEntry(cachedMessageEntry);\n const existingClaimRunId = claimsRef.current[message.id]?.runId;\n const effectiveRunId = getEffectiveRunId({\n existingClaimRunId,\n cachedMessageRunId,\n runId,\n });\n\n useEffect(() => {\n return () => {\n const existingClaim = claimsRef.current[message.id];\n if (\n existingClaim?.stateSnapshot &&\n Object.keys(existingClaim.stateSnapshot).length > 0\n ) {\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${existingClaim.stateRenderId}::${existingClaim.runId ?? \"pending\"}`;\n snapshotCache[cacheKey] = existingClaim.stateSnapshot;\n snapshotCache[`${existingClaim.stateRenderId}::latest`] =\n existingClaim.stateSnapshot;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = {\n snapshot: existingClaim.stateSnapshot,\n runId: existingClaim.runId ?? effectiveRunId,\n };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n }\n delete claimsRef.current[message.id];\n };\n }, [claimsRef, effectiveRunId, message.id]);\n\n if (!stateRenderId) {\n return { canRender: false };\n }\n\n const caches = getSnapshotCaches(claimsRef);\n const existingClaim = claimsRef.current[message.id] as Claim | undefined;\n\n const { snapshot, hasSnapshotKeys, allowEmptySnapshot, snapshotForClaim } =\n selectSnapshot({\n messageId: message.id,\n messageName: message.name,\n allowLiveState:\n isPlaceholderMessageName(message.name) ||\n isPlaceholderMessageId(message.id),\n skipLatestCache:\n isPlaceholderMessageName(message.name) ||\n isPlaceholderMessageId(message.id),\n stateRenderId,\n effectiveRunId,\n stateSnapshotProp: stateSnapshot,\n agentState,\n agentMessages,\n existingClaim,\n caches,\n });\n\n const resolution = resolveClaim({\n claims: claimsRef.current as ClaimsByMessageId,\n context: {\n agentId,\n messageId: message.id,\n stateRenderId,\n runId: effectiveRunId,\n messageIndex,\n } satisfies StateRenderContext,\n stateSnapshot: snapshotForClaim,\n });\n\n if (resolution.action === ClaimAction.Block) {\n return { canRender: false };\n }\n\n if (resolution.updateRunId && claimsRef.current[message.id]) {\n claimsRef.current[message.id].runId = resolution.updateRunId;\n }\n\n if (resolution.nextClaim) {\n claimsRef.current[message.id] = resolution.nextClaim;\n }\n\n if (resolution.lockOthers) {\n Object.entries(claimsRef.current).forEach(([id, claim]) => {\n if (id !== message.id && claim.stateRenderId === stateRenderId) {\n claim.locked = true;\n }\n });\n }\n\n if (existingClaim && !existingClaim.locked && agentMessages?.length) {\n const indexInAgentMessages = agentMessages.findIndex(\n (msg: any) => msg.id === message.id,\n );\n if (\n indexInAgentMessages >= 0 &&\n indexInAgentMessages < agentMessages.length - 1\n ) {\n existingClaim.locked = true;\n }\n }\n\n const existingSnapshot = claimsRef.current[message.id].stateSnapshot;\n const snapshotChanged =\n stateSnapshot &&\n existingSnapshot !== undefined &&\n !areStatesEquals(existingSnapshot, snapshot);\n\n if (\n snapshot &&\n (stateSnapshot || hasSnapshotKeys || allowEmptySnapshot) &&\n (!claimsRef.current[message.id].locked || snapshotChanged)\n ) {\n if (!claimsRef.current[message.id].locked || snapshotChanged) {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${stateRenderId}::${effectiveRunId}`;\n snapshotCache[cacheKey] = snapshot;\n snapshotCache[`${stateRenderId}::latest`] = snapshot;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = { snapshot, runId: effectiveRunId };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n if (stateSnapshot) {\n claimsRef.current[message.id].locked = true;\n }\n }\n } else if (snapshotForClaim) {\n const existingSnapshot = claimsRef.current[message.id].stateSnapshot;\n if (!existingSnapshot) {\n claimsRef.current[message.id].stateSnapshot = snapshotForClaim;\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${stateRenderId}::${effectiveRunId}`;\n snapshotCache[cacheKey] = snapshotForClaim;\n snapshotCache[`${stateRenderId}::latest`] = snapshotForClaim;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = {\n snapshot: snapshotForClaim,\n runId: effectiveRunId,\n };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n }\n }\n\n return { canRender: true };\n}\n","import { ReactCustomMessageRendererPosition, useAgent } from \"../v2\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useCoAgentStateRenders } from \"../context\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { RenderStatus } from \"./use-coagent-state-render-bridge.helpers\";\nimport { useStateRenderRegistry } from \"./use-coagent-state-render-registry\";\n\n/**\n * Bridge hook that connects agent state renders to chat messages.\n *\n * ## Purpose\n * This hook finds matching state render configurations (registered via useCoAgentStateRender)\n * and returns UI to render in chat.\n * It ensures each state render appears bound to a specific message, preventing duplicates while\n * allowing re-binding when the underlying state changes significantly.\n *\n * ## Message-ID-Based Claiming System\n *\n * ### The Problem\n * Multiple bridge component instances render simultaneously (one per message). Without coordination,\n * they would all try to render the same state render, causing duplicates.\n *\n * ### The Solution: Message-ID Claims with State Comparison\n * Each state render is \"claimed\" by exactly one **message ID** (not runId):\n *\n * **Claim Structure**: `claimsRef.current[messageId] = { stateRenderId, runId, stateSnapshot, locked }`\n *\n * **Primary binding is by messageId because**:\n * - runId is not always available immediately (starts as \"pending\")\n * - messageId is the stable identifier throughout the message lifecycle\n * - Claims persist across component remounts via context ref\n *\n * ### Claiming Logic Flow\n *\n * 1. **Message already has a claim**:\n * - Check if the claim matches the current stateRenderId\n * - If yes → render (this message owns this render)\n * - Update runId if it was \"pending\" and now available\n *\n * 2. **State render claimed by another message**:\n * - Compare state snapshots (ignoring constant keys: messages, tools, copilotkit)\n * - If states are identical → block rendering (duplicate)\n * - **If states are different → allow claiming** (new data, new message)\n * - This handles cases where the same render type shows different states in different messages\n *\n * 3. **Unclaimed state render**:\n * - Only allow claiming if runId is \"pending\" (initial render)\n * - If runId is real but no claim exists → block (edge case protection)\n * - Create new claim: `claimsRef.current[messageId] = { stateRenderId, runId }`\n *\n * ### State Snapshot Locking\n *\n * Once a state snapshot is captured and locked for a message:\n * - The UI always renders with the locked snapshot (not live agent.state)\n * - Prevents UI from appearing \"wiped\" during state transitions\n * - Locked when: stateSnapshot prop is available (from message persistence)\n * - Unlocked state: can still update from live agent.state\n *\n * ### Synchronous Claiming (Ref-based)\n *\n * Claims are stored in a context-level ref (not React state):\n * - Multiple bridges render in the same tick\n * - State updates are async - would allow duplicates before update completes\n * - Ref provides immediate, synchronous claim checking\n * - Survives component remounts (stored in context, not component)\n *\n * ## Flow Example\n *\n * ```\n * Time 1: Message A renders, runId=undefined, state={progress: 50%}\n * → effectiveRunId = \"pending\"\n * → Claims: claimsRef[\"msgA\"] = { stateRenderId: \"tasks\", runId: \"pending\", stateSnapshot: {progress: 50%} }\n * → Renders UI with 50% progress\n *\n * Time 2: Message B renders, runId=undefined, same state\n * → Checks: \"tasks\" already claimed by msgA with same state\n * → Returns null (blocked - duplicate)\n *\n * Time 3: Real runId appears (e.g., \"run-123\")\n * → Updates claim: claimsRef[\"msgA\"].runId = \"run-123\"\n * → Message A continues rendering\n *\n * Time 4: Agent processes more, state={progress: 100%}\n * → Message A: locked to 50% (stateSnapshot locked)\n * → Message C renders with state={progress: 100%}\n * → Checks: \"tasks\" claimed by msgA but state is DIFFERENT (50% vs 100%)\n * → Allows new claim: claimsRef[\"msgC\"] = { stateRenderId: \"tasks\", runId: \"run-123\", stateSnapshot: {progress: 100%} }\n * → Both messages render independently with their own snapshots\n * ```\n */\nexport interface CoAgentStateRenderBridgeProps {\n message: any;\n position: ReactCustomMessageRendererPosition;\n runId: string;\n messageIndex: number;\n messageIndexInRun: number;\n numberOfMessagesInRun: number;\n agentId: string;\n stateSnapshot: any;\n}\n\nexport function useCoagentStateRenderBridge(\n agentId: string,\n props: CoAgentStateRenderBridgeProps,\n) {\n const { stateSnapshot, message } = props;\n const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();\n const { agent } = useAgent({ agentId });\n const [nodeName, setNodeName] = useState<string | undefined>(undefined);\n const [, forceUpdate] = useState(0);\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStateChanged: () => {\n forceUpdate((value) => value + 1);\n },\n onStepStartedEvent: ({ event }) => {\n if (event.stepName !== nodeName) {\n setNodeName(event.stepName);\n }\n },\n onStepFinishedEvent: ({ event }) => {\n if (event.stepName === nodeName) {\n setNodeName(undefined);\n }\n },\n };\n\n const { unsubscribe } = agent.subscribe(subscriber);\n return () => {\n unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agentId, nodeName]);\n\n const getStateRender = useCallback(\n (messageId: string) => {\n return Object.entries(coAgentStateRenders).find(\n ([stateRenderId, stateRender]) => {\n if (claimsRef.current[messageId]) {\n return stateRenderId === claimsRef.current[messageId].stateRenderId;\n }\n const matchingAgentName = stateRender.name === agentId;\n const matchesNodeContext = stateRender.nodeName\n ? stateRender.nodeName === nodeName\n : true;\n return matchingAgentName && matchesNodeContext;\n },\n );\n },\n [coAgentStateRenders, nodeName, agentId],\n );\n const stateRenderEntry = useMemo(\n () => getStateRender(message.id),\n [getStateRender, message.id],\n );\n const stateRenderId = stateRenderEntry?.[0];\n const stateRender = stateRenderEntry?.[1];\n\n const registryMessage = {\n ...message,\n runId: props.runId ?? message.runId,\n };\n const { canRender } = useStateRenderRegistry({\n agentId,\n stateRenderId,\n message: registryMessage,\n messageIndex: props.messageIndex,\n stateSnapshot,\n agentState: agent?.state,\n agentMessages: agent?.messages,\n claimsRef,\n });\n\n return useMemo(() => {\n if (!stateRender || !stateRenderId) {\n return null;\n }\n if (!canRender) {\n return null;\n }\n\n if (stateRender.handler) {\n stateRender.handler({\n state: stateSnapshot\n ? parseJson(stateSnapshot, stateSnapshot)\n : (agent?.state ?? {}),\n nodeName: nodeName ?? \"\",\n });\n }\n\n if (stateRender.render) {\n const status = agent?.isRunning\n ? RenderStatus.InProgress\n : RenderStatus.Complete;\n\n if (typeof stateRender.render === \"string\") return stateRender.render;\n\n return stateRender.render({\n status,\n // Always use state from claim, to make sure the state does not seem \"wiped\" for a fraction of a second\n state: claimsRef.current[message.id].stateSnapshot ?? {},\n nodeName: nodeName ?? \"\",\n });\n }\n }, [\n stateRender,\n stateRenderId,\n agent?.state,\n agent?.isRunning,\n nodeName,\n message.id,\n stateSnapshot,\n canRender,\n ]);\n}\n\nexport function CoAgentStateRenderBridge(props: CoAgentStateRenderBridgeProps) {\n return useCoagentStateRenderBridge(props.agentId, props);\n}\n","import { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { useAgent, useCopilotChatConfiguration, useCopilotKit } from \"../v2\";\nimport { CopilotKitError, parseJson } from \"@copilotkit/shared\";\nimport { useCopilotContext } from \"../context\";\nimport {\n AbstractAgent,\n AgentSubscriber,\n AGUIConnectNotImplementedError,\n} from \"@ag-ui/client\";\nimport { useErrorToast } from \"./error-boundary/error-utils\";\nimport { CopilotKitCoreSubscriber } from \"@copilotkit/core\";\nimport { useToast } from \"./toast/toast-provider\";\nimport { CopilotKitLowLevelError } from \"@copilotkit/shared\";\n\nconst usePredictStateSubscription = (agent?: AbstractAgent) => {\n const predictStateToolsRef = useRef<\n {\n tool: string;\n state_key: string;\n tool_argument: string;\n }[]\n >([]);\n\n const getSubscriber = useCallback(\n (agent: AbstractAgent): AgentSubscriber => ({\n onCustomEvent: ({ event }) => {\n if (event.name === \"PredictState\") {\n predictStateToolsRef.current = event.value;\n }\n },\n onToolCallArgsEvent: ({ partialToolCallArgs, toolCallName }) => {\n predictStateToolsRef.current.forEach((t) => {\n if (t?.tool !== toolCallName) return;\n\n const emittedState =\n typeof partialToolCallArgs === \"string\"\n ? parseJson(\n partialToolCallArgs as unknown as string,\n partialToolCallArgs,\n )\n : partialToolCallArgs;\n\n agent.setState({\n [t.state_key]: emittedState[t.state_key],\n });\n });\n },\n }),\n [],\n );\n\n useEffect(() => {\n if (!agent) return;\n\n const subscriber = getSubscriber(agent);\n const { unsubscribe } = agent.subscribe(subscriber);\n return () => {\n unsubscribe();\n };\n }, [agent, getSubscriber]);\n};\n\nexport function CopilotListeners() {\n const { copilotkit } = useCopilotKit();\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId;\n const { setBannerError } = useToast();\n\n const { agent } = useAgent({ agentId: resolvedAgentId });\n\n usePredictStateSubscription(agent);\n\n useEffect(() => {\n const subscriber: CopilotKitCoreSubscriber = {\n onError: ({ error, code, context }) => {\n // Silently ignore abort errors (e.g. from navigation during active requests)\n if (\n error.name === \"AbortError\" ||\n error.message === \"Fetch is aborted\" ||\n error.message === \"signal is aborted without reason\" ||\n error.message === \"component unmounted\" ||\n !error.message\n ) {\n return;\n }\n\n // Always log full error details in development\n if (process.env.NODE_ENV === \"development\") {\n console.error(\n \"[CopilotKit] Agent error:\",\n error.message,\n \"\\n Code:\",\n code,\n \"\\n Context:\",\n context,\n \"\\n Stack:\",\n error.stack,\n );\n }\n\n const ckError = new CopilotKitLowLevelError({\n error,\n message: error.message,\n url: typeof window !== \"undefined\" ? window.location.href : \"\",\n });\n\n // Attach original error details for the banner to display\n (ckError as any).details = {\n code,\n context,\n stack: error.stack,\n originalMessage: error.message,\n };\n\n setBannerError(ckError);\n },\n };\n const subscription = copilotkit.subscribe(subscriber);\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit?.subscribe]);\n\n return null;\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n SetStateAction,\n} from \"react\";\nimport {\n CopilotChatConfigurationProvider,\n CopilotKitInspector,\n CopilotKitProvider as CopilotKitV2Provider,\n useCopilotKit,\n} from \"../../v2\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\n useCopilotContext,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport {\n CopilotChatSuggestionConfiguration,\n DocumentPointer,\n} from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n CopilotKitError,\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages, MessagesTapProvider } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetterArgs,\n QueuedInterruptEvent,\n} from \"../../types/interrupt-action\";\nimport { CoAgentStateRendersProvider } from \"../../context/coagent-state-renders-context\";\nimport { CoAgentStateRenderBridge } from \"../../hooks/use-coagent-state-render-bridge\";\nimport { ThreadsProvider, useThreads } from \"../../context/threads-context\";\nimport { CopilotListeners } from \"../CopilotListeners\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n const showInspector = shouldShowDevConsole(props.enableInspector);\n\n // Use API key if provided, otherwise use the license key\n const publicApiKey = props.publicApiKey || props.publicLicenseKey;\n\n const renderArr = useMemo(() => [{ render: CoAgentStateRenderBridge }], []);\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary\n publicApiKey={publicApiKey}\n showUsageBanner={enabled}\n >\n <ThreadsProvider threadId={props.threadId}>\n <CopilotKitV2Provider\n {...props}\n showDevConsole={showInspector}\n renderCustomMessages={renderArr}\n useSingleEndpoint={props.useSingleEndpoint ?? true}\n >\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotKitV2Provider>\n </ThreadsProvider>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\n/**\n * Bridge component that subscribes to v2.x copilotkit core error events\n * and forwards them to v1.x error handling system.\n * This ensures only ONE subscription exists regardless of how many times\n * Chat components are rendered.\n */\nfunction CopilotKitErrorBridge() {\n const { copilotkit } = useCopilotKit();\n const { onError, copilotApiConfig } = useCopilotContext();\n\n useEffect(() => {\n if (!copilotkit) return;\n\n const subscription = copilotkit.subscribe({\n onError: async (event) => {\n // Convert v2.x error event to v1.x CopilotErrorEvent format\n const errorEvent: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"agent\",\n request: {\n operation: event.code || \"unknown\",\n url: copilotApiConfig?.chatApiEndpoint,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent:\n typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : undefined,\n stackTrace: event.error.stack,\n },\n // Add additional context from v2.x event\n ...event.context,\n },\n error: event.error,\n };\n\n try {\n await onError(errorEvent);\n } catch (handlerError) {\n console.error(\"Error in onError handler:\", handlerError);\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit, onError, copilotApiConfig]);\n\n return null;\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n // Use license key as API key if provided, otherwise use the API key\n const publicApiKey = props.publicLicenseKey || props.publicApiKey;\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>(\n {},\n );\n\n // State for registered actions from useCopilotAction\n const [registeredActionConfigs, setRegisteredActionConfigs] = useState<\n Map<string, { type: string; action: any; component: any }>\n >(new Map());\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<\n string[]\n >([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n // Compute all the functions and properties that we need to pass\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(\n Object.values(customEntryPoints || actions),\n );\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (\n documentPointer: DocumentPointer,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? {\n [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]:\n copilotApiConfig.publicApiKey,\n }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const [internalErrorHandlers, _setInternalErrorHandler] = useState<\n Record<string, CopilotErrorHandler>\n >({});\n const setInternalErrorHandler = useCallback(\n (handler: Record<string, CopilotErrorHandler>) => {\n _setInternalErrorHandler((prev: Record<string, CopilotErrorHandler>) => ({\n ...prev,\n ...handler,\n }));\n },\n [],\n );\n const removeInternalErrorHandler = useCallback((key: string) => {\n _setInternalErrorHandler((prev) => {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n });\n }, []);\n\n // Keep latest values in refs\n const onErrorRef = useRef<CopilotErrorHandler | undefined>(props.onError);\n useEffect(() => {\n onErrorRef.current = props.onError;\n }, [props.onError]);\n\n const internalHandlersRef = useRef<Record<string, CopilotErrorHandler>>({});\n useEffect(() => {\n internalHandlersRef.current = internalErrorHandlers;\n }, [internalErrorHandlers]);\n\n const handleErrors = useCallback(\n async (error: CopilotErrorEvent) => {\n if (copilotApiConfig.publicApiKey && onErrorRef.current) {\n try {\n await onErrorRef.current(error);\n } catch (e) {\n console.error(\"Error in public onError handler:\", e);\n }\n }\n const handlers = Object.values(internalHandlersRef.current);\n await Promise.all(\n handlers.map((h) =>\n Promise.resolve(h(error)).catch((e) =>\n console.error(\"Error in internal error handler:\", e),\n ),\n ),\n );\n },\n [copilotApiConfig.publicApiKey],\n );\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] =\n useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<\n Record<string, CoagentState>\n >({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((\n prev: Record<string, CoagentState>,\n ) => Record<string, CoagentState>),\n ) => {\n const newValue =\n typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(\n initialAgentSession,\n );\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const { threadId, setThreadId: setInternalThreadId } = useThreads();\n\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\n \"Cannot call setThreadId() when threadId is provided via props.\",\n );\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = shouldShowDevConsole(props.showDevConsole);\n\n const [interruptActions, _setInterruptActions] = useState<\n Record<string, LangGraphInterruptRender>\n >({});\n const setInterruptAction = useCallback(\n (action: LangGraphInterruptActionSetterArgs) => {\n _setInterruptActions((prev) => {\n if (action == null || !action.id) {\n // Cannot set action without id\n return prev;\n }\n return {\n ...prev,\n [action.id]: {\n ...(prev[action.id] ?? {}),\n ...action,\n } as LangGraphInterruptRender,\n };\n });\n },\n [],\n );\n const removeInterruptAction = useCallback((actionId: string): void => {\n _setInterruptActions((prev) => {\n const { [actionId]: _, ...rest } = prev;\n return rest;\n });\n }, []);\n\n const [interruptEventQueue, setInterruptEventQueue] = useState<\n Record<string, QueuedInterruptEvent[]>\n >({});\n\n const addInterruptEvent = useCallback((queuedEvent: QueuedInterruptEvent) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[queuedEvent.threadId] || [];\n return {\n ...prev,\n [queuedEvent.threadId]: [...threadQueue, queuedEvent],\n };\n });\n }, []);\n\n const resolveInterruptEvent = useCallback(\n (threadId: string, eventId: string, response: string) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[threadId] || [];\n return {\n ...prev,\n [threadId]: threadQueue.map((queuedEvent) =>\n queuedEvent.eventId === eventId\n ? { ...queuedEvent, event: { ...queuedEvent.event, response } }\n : queuedEvent,\n ),\n };\n });\n },\n [],\n );\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved =\n typeof newExtensions === \"function\"\n ? newExtensions(prev)\n : newExtensions;\n const isSameLength =\n Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved =\n typeof newAuthStates === \"function\"\n ? newAuthStates(prev)\n : newAuthStates;\n const isSameLength =\n Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n const handleSetRegisteredActions = useCallback(\n (actionConfig: any): string => {\n const key = actionConfig.action.name || randomUUID();\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.set(key, actionConfig);\n return newMap;\n });\n return key;\n },\n [],\n );\n\n const handleRemoveRegisteredAction = useCallback((actionKey: string) => {\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.delete(actionKey);\n return newMap;\n });\n }, []);\n\n // Component to render all registered actions\n const RegisteredActionsRenderer = useMemo(() => {\n return () => (\n <>\n {Array.from(registeredActionConfigs.entries()).map(([key, config]) => {\n const Component = config.component;\n return <Component key={key} action={config.action} />;\n })}\n </>\n );\n }, [registeredActionConfigs]);\n\n const copilotContextValue = useMemo(\n () => ({\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n setRegisteredActions: handleSetRegisteredActions,\n removeRegisteredAction: handleRemoveRegisteredAction,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n interruptActions,\n setInterruptAction,\n removeInterruptAction,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n bannerError,\n setBannerError,\n onError: handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n }),\n [\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n handleSetRegisteredActions,\n handleRemoveRegisteredAction,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig,\n isLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n additionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n availableAgents,\n props.authConfig_c,\n authStates,\n updateAuthStates,\n extensions,\n updateExtensions,\n interruptActions,\n setInterruptAction,\n removeInterruptAction,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n bannerError,\n handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n ],\n );\n\n return (\n <CopilotChatConfigurationProvider\n // labels={labels}\n // isModalDefaultOpen={isModalDefaultOpen}\n agentId={props.agent ?? \"default\"}\n threadId={threadId}\n >\n <CopilotContext.Provider value={copilotContextValue}>\n <CopilotListeners />\n <CopilotKitErrorBridge />\n <CoAgentStateRendersProvider>\n <MessagesTapProvider>\n <CopilotMessages>\n <React.Fragment key=\"children\">{memoizedChildren}</React.Fragment>\n <RegisteredActionsRenderer key=\"actions\" />\n </CopilotMessages>\n </MessagesTapProvider>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </CoAgentStateRendersProvider>\n </CopilotContext.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(\n actions: FrontendAction<any>[],\n): FunctionCallHandler {\n return async ({\n name,\n args,\n }: {\n name: string;\n args: Record<string, any>;\n }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n // Check if we have either a runtimeUrl or one of the API keys\n const hasApiKey = props.publicApiKey || props.publicLicenseKey;\n\n if (!props.runtimeUrl && !hasApiKey) {\n throw new ConfigurationError(\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\",\n );\n }\n\n if (cloudFeatures.length > 0 && !hasApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n","import { useRenderToolCall } from \"../v2\";\nimport { AIMessage, Message, ToolResult } from \"@copilotkit/shared\";\nimport React, { useCallback } from \"react\";\n\nexport function useLazyToolRenderer(): (\n message?: AIMessage,\n messages?: Message[],\n) => null | (() => ReturnType<ReturnType<typeof useRenderToolCall>> | null) {\n const renderToolCall = useRenderToolCall();\n\n return useCallback(\n (message?: AIMessage, messages?: Message[]) => {\n if (!message?.toolCalls?.length) return null;\n\n const toolCall = message.toolCalls[0];\n if (!toolCall) return null;\n\n const toolMessage = messages?.find(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id,\n ) as ToolResult;\n\n return () =>\n renderToolCall({\n toolCall,\n toolMessage,\n });\n },\n [renderToolCall],\n );\n}\n","import React, {\n useRef,\n useEffect,\n useCallback,\n useMemo,\n useState,\n createElement,\n} from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { Message } from \"@copilotkit/shared\";\nimport {\n gqlToAGUI,\n Message as DeprecatedGqlMessage,\n} from \"@copilotkit/runtime-client-gql\";\nimport {\n useAgent,\n useCopilotChatConfiguration,\n useCopilotKit,\n useRenderCustomMessages,\n useSuggestions,\n} from \"../v2\";\nimport {\n Suggestion,\n CopilotKitCoreRuntimeConnectionStatus,\n} from \"@copilotkit/core\";\nimport { useLazyToolRenderer } from \"./use-lazy-tool-renderer\";\nimport {\n AbstractAgent,\n AGUIConnectNotImplementedError,\n HttpAgent,\n} from \"@ag-ui/client\";\nimport {\n CoAgentStateRenderBridge,\n type CoAgentStateRenderBridgeProps,\n} from \"./use-coagent-state-render-bridge\";\n\n/**\n * The type of suggestions to use in the chat.\n *\n * `auto` - Suggestions are generated automatically.\n * `manual` - Suggestions are controlled programmatically.\n * `SuggestionItem[]` - Static suggestions array.\n */\nexport type ChatSuggestions =\n | \"auto\"\n | \"manual\"\n | Omit<Suggestion, \"isLoading\">[];\n\nexport interface AppendMessageOptions {\n /**\n * Whether to run the chat completion after appending the message. Defaults to `true`.\n */\n followUp?: boolean;\n /**\n * Whether to clear the suggestions after appending the message. Defaults to `true`.\n */\n clearSuggestions?: boolean;\n}\n\nexport interface OnStopGenerationArguments {\n /**\n * The name of the currently executing agent.\n */\n currentAgentName: string | undefined;\n\n /**\n * The messages in the chat.\n */\n messages: Message[];\n}\n\nexport type OnReloadMessagesArguments = OnStopGenerationArguments & {\n /**\n * The message on which \"regenerate\" was pressed\n */\n messageId: string;\n};\n\nexport type OnStopGeneration = (args: OnStopGenerationArguments) => void;\n\nexport type OnReloadMessages = (args: OnReloadMessagesArguments) => void;\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Initial messages to populate the chat with.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n\n /**\n * Disables inclusion of CopilotKit’s default system message. When true, no system message is sent (this also suppresses any custom message from <code>makeSystemMessage</code>).\n */\n disableSystemMessage?: boolean;\n /**\n * Controls the behavior of suggestions in the chat interface.\n *\n * `auto` (default) - Suggestions are generated automatically:\n * - When the chat is first opened (empty state)\n * - After each message exchange completes\n * - Uses configuration from `useCopilotChatSuggestions` hooks\n *\n * `manual` - Suggestions are controlled programmatically:\n * - Use `setSuggestions()` to set custom suggestions\n * - Use `generateSuggestions()` to trigger AI generation\n * - Access via `useCopilotChat` hook\n *\n * `SuggestionItem[]` - Static suggestions array:\n * - Always shows the same suggestions\n * - No AI generation involved\n */\n suggestions?: ChatSuggestions;\n\n onInProgress?: (isLoading: boolean) => void;\n onSubmitMessage?: (messageContent: string) => Promise<void> | void;\n onStopGeneration?: OnStopGeneration;\n onReloadMessages?: OnReloadMessages;\n}\n\nexport interface MCPServerConfig {\n endpoint: string;\n apiKey?: string;\n}\n\n// Old suggestion item interface, for returning from useCopilotChatInternal\ninterface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport interface UseCopilotChatReturn {\n /**\n * @deprecated use `messages` instead, this is an old non ag-ui version of the messages\n * Array of messages currently visible in the chat interface\n *\n * This is the visible messages, not the raw messages from the runtime client.\n */\n visibleMessages: DeprecatedGqlMessage[];\n\n /**\n * The messages that are currently in the chat in AG-UI format.\n */\n messages: Message[];\n\n /** @deprecated use `sendMessage` in `useCopilotChatHeadless_c` instead. This will be removed in a future major version. */\n appendMessage: (\n message: DeprecatedGqlMessage,\n options?: AppendMessageOptions,\n ) => Promise<void>;\n\n /**\n * Send a new message to the chat\n *\n * ```tsx\n * await sendMessage({\n * id: \"123\",\n * role: \"user\",\n * content: \"Hello, process this request\",\n * });\n * ```\n */\n sendMessage: (\n message: Message,\n options?: AppendMessageOptions,\n ) => Promise<void>;\n\n /**\n * Replace all messages in the chat\n *\n * ```tsx\n * setMessages([\n * { id: \"123\", role: \"user\", content: \"Hello, process this request\" },\n * { id: \"456\", role: \"assistant\", content: \"Hello, I'm the assistant\" },\n * ]);\n * ```\n *\n * **Deprecated** non-ag-ui version:\n *\n * ```tsx\n * setMessages([\n * new TextMessage({\n * content: \"Hello, process this request\",\n * role: gqlRole.User,\n * }),\n * new TextMessage({\n * content: \"Hello, I'm the assistant\",\n * role: gqlRole.Assistant,\n * ]);\n * ```\n *\n */\n setMessages: (messages: Message[] | DeprecatedGqlMessage[]) => void;\n\n /**\n * Remove a specific message by ID\n *\n * ```tsx\n * deleteMessage(\"123\");\n * ```\n */\n deleteMessage: (messageId: string) => void;\n\n /**\n * Regenerate the response for a specific message\n *\n * ```tsx\n * reloadMessages(\"123\");\n * ```\n */\n reloadMessages: (messageId: string) => Promise<void>;\n\n /**\n * Stop the current message generation\n *\n * ```tsx\n * if (isLoading) {\n * stopGeneration();\n * }\n * ```\n */\n stopGeneration: () => void;\n\n /**\n * Clear all messages and reset chat state\n *\n * ```tsx\n * reset();\n * console.log(messages); // []\n * ```\n */\n reset: () => void;\n\n /**\n * Whether the chat is currently generating a response\n *\n * ```tsx\n * if (isLoading) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isLoading: boolean;\n\n /**\n * Whether the chat agent is available to generate responses\n *\n * ```tsx\n * if (isAvailable) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isAvailable: boolean;\n\n /** Manually trigger chat completion (advanced usage) */\n runChatCompletion: () => Promise<Message[]>;\n\n /** MCP (Model Context Protocol) server configurations */\n mcpServers: MCPServerConfig[];\n\n /** Update MCP server configurations */\n setMcpServers: (mcpServers: MCPServerConfig[]) => void;\n\n /**\n * Current suggestions array\n * Use this to read the current suggestions or in conjunction with setSuggestions for manual control\n */\n suggestions: Suggestion[];\n\n /**\n * Manually set suggestions\n * Useful for manual mode or custom suggestion workflows\n */\n setSuggestions: (suggestions: Omit<Suggestion, \"isLoading\">[]) => void;\n\n /**\n * Trigger AI-powered suggestion generation\n * Uses configurations from useCopilotChatSuggestions hooks\n * Respects global debouncing - only one generation can run at a time\n *\n * ```tsx\n * generateSuggestions();\n * console.log(suggestions); // [suggestion1, suggestion2, suggestion3]\n * ```\n */\n generateSuggestions: () => Promise<void>;\n\n /**\n * Clear all current suggestions\n * Also resets suggestion generation state\n */\n resetSuggestions: () => void;\n\n /** Whether suggestions are currently being generated */\n isLoadingSuggestions: boolean;\n\n /** Interrupt content for human-in-the-loop workflows */\n interrupt: string | React.ReactElement | null;\n\n agent?: ReturnType<typeof useAgent>[\"agent\"];\n\n threadId?: string;\n}\n\nexport function useCopilotChatInternal({\n suggestions,\n onInProgress,\n onSubmitMessage,\n onStopGeneration,\n onReloadMessages,\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const { copilotkit } = useCopilotKit();\n const { threadId, agentSession } = useCopilotContext();\n const existingConfig = useCopilotChatConfiguration();\n const [agentAvailable, setAgentAvailable] = useState(false);\n\n // Apply priority: props > existing config > defaults\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const { agent } = useAgent({\n agentId: resolvedAgentId,\n threadId: existingConfig?.threadId,\n });\n\n // Track the last agent instance we called connect() on. Without this,\n // connect() fires on every render where status is Connected — including\n // unrelated context re-renders and StrictMode double-invocations.\n // The ref is reset in the cleanup so that remounts (StrictMode, real\n // unmount/remount) always trigger a fresh connect.\n const lastConnectedAgentRef = useRef<AbstractAgent | null>(null);\n\n useEffect(() => {\n let detached = false;\n\n // Create a fresh AbortController so we can cancel the HTTP request on cleanup.\n // Mirrors the V2 CopilotChat pattern: HttpAgent uses abortController.signal in\n // its fetch config. connectAgent() does NOT create a new AbortController\n // automatically, so we must set one before connecting.\n const connectAbortController = new AbortController();\n if (agent instanceof HttpAgent) {\n agent.abortController = connectAbortController;\n }\n\n const connect = async (agent: AbstractAgent) => {\n setAgentAvailable(false);\n try {\n await copilotkit.connectAgent({ agent });\n // Guard against setting state after cleanup (e.g. React StrictMode unmount)\n if (!detached) {\n setAgentAvailable(true);\n }\n } catch (error) {\n // Ignore errors from aborted connections (e.g. React StrictMode cleanup)\n if (detached) return;\n if (error instanceof AGUIConnectNotImplementedError) {\n // connect not implemented, ignore\n } else {\n console.error(\"CopilotChat: connectAgent failed\", error);\n // Error will be reported through subscription\n }\n }\n };\n if (\n agent &&\n agent !== lastConnectedAgentRef.current &&\n copilotkit.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ) {\n lastConnectedAgentRef.current = agent;\n connect(agent);\n }\n return () => {\n // Abort the HTTP request and detach the active run.\n // This is critical for React StrictMode which unmounts+remounts in dev,\n // preventing duplicate /connect requests from reaching the server.\n // Reset the ref so remounts always trigger a fresh connect.\n lastConnectedAgentRef.current = null;\n detached = true;\n connectAbortController.abort();\n agent?.detachActiveRun();\n };\n }, [\n existingConfig?.threadId,\n agent,\n copilotkit,\n copilotkit.runtimeConnectionStatus,\n resolvedAgentId,\n ]);\n\n useEffect(() => {\n onInProgress?.(Boolean(agent?.isRunning));\n }, [agent?.isRunning, onInProgress]);\n\n // Subscribe to copilotkit.interruptElement so the v1 return type stays\n // reactive. The element is published by useInterrupt (v2) when user code\n // calls useLangGraphInterrupt({ render, ... }).\n const [interrupt, setInterrupt] = useState<React.ReactElement | null>(null);\n useEffect(() => {\n setInterrupt(copilotkit.interruptElement);\n const subscription = copilotkit.subscribe({\n onInterruptElementChanged: ({ interruptElement }) => {\n setInterrupt(interruptElement);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const reset = () => {\n agent?.setMessages([]);\n agent?.setState(null);\n };\n\n const deleteMessage = useCallback(\n (messageId: string) => {\n const filteredMessages = (agent?.messages ?? []).filter(\n (message) => message.id !== messageId,\n );\n agent?.setMessages(filteredMessages);\n },\n [agent?.setMessages, agent?.messages],\n );\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const currentSuggestions = useSuggestions({ agentId: resolvedAgentId });\n\n const reload = useAsyncCallback(\n async (reloadMessageId: string): Promise<void> => {\n if (!agent) return;\n const messages = agent?.messages ?? [];\n const isLoading = agent.isRunning;\n if (isLoading || messages.length === 0) {\n return;\n }\n\n const reloadMessageIndex = messages.findIndex(\n (msg) => msg.id === reloadMessageId,\n );\n if (reloadMessageIndex === -1) {\n console.warn(`Message with id ${reloadMessageId} not found`);\n return;\n }\n\n const reloadMessageRole = messages[reloadMessageIndex].role;\n if (reloadMessageRole !== \"assistant\") {\n console.warn(\n `Regenerate cannot be performed on ${reloadMessageRole} role`,\n );\n return;\n }\n let historyCutoff: Message[] = [messages[0]];\n\n if (messages.length > 2 && reloadMessageIndex !== 0) {\n // message to regenerate from is now first.\n // Work backwards to find the first the closest user message\n const lastUserMessageBeforeRegenerate = messages\n .slice(0, reloadMessageIndex)\n .reverse()\n .find((msg) => msg.role === \"user\");\n\n if (!lastUserMessageBeforeRegenerate) {\n historyCutoff = [messages[0]];\n } else {\n const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(\n (msg) => msg.id === lastUserMessageBeforeRegenerate.id,\n );\n // Include the user message, remove everything after it\n historyCutoff = messages.slice(\n 0,\n indexOfLastUserMessageBeforeRegenerate + 1,\n );\n }\n } else if (messages.length > 2 && reloadMessageIndex === 0) {\n historyCutoff = [messages[0], messages[1]];\n }\n\n agent?.setMessages(historyCutoff);\n\n if (agent) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed during reload\", error);\n // Error will be reported through subscription\n }\n }\n return;\n },\n [\n agent?.messages.length,\n agent?.isRunning,\n agent?.setMessages,\n copilotkit?.runAgent,\n ],\n );\n\n const latestSendMessageFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n if (!agent) return;\n const followUp = options?.followUp ?? true;\n if (options?.clearSuggestions) {\n copilotkit.clearSuggestions(resolvedAgentId);\n }\n\n // Call onSubmitMessage BEFORE adding message and running agent\n // This allows users to perform actions (e.g., open chat window) before agent starts processing\n if (onSubmitMessage) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : message.content && \"text\" in message.content\n ? message.content.text\n : message.content && \"filename\" in message.content\n ? message.content.filename\n : \"\";\n try {\n await onSubmitMessage(content);\n } catch (error) {\n console.error(\"Error in onSubmitMessage:\", error);\n }\n }\n\n agent?.addMessage(message);\n if (followUp) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\n // Error will be reported through subscription\n }\n }\n },\n [agent, copilotkit, resolvedAgentId, onSubmitMessage],\n );\n\n const latestAppendFunc = useAsyncCallback(\n async (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => {\n return latestSendMessageFunc(gqlToAGUI([message])[0], options);\n },\n [latestSendMessageFunc],\n );\n\n const latestSetMessagesFunc = useCallback(\n (messages: Message[] | DeprecatedGqlMessage[]) => {\n if (\n messages.every((message) => message instanceof DeprecatedGqlMessage)\n ) {\n return agent?.setMessages?.(gqlToAGUI(messages));\n }\n return agent?.setMessages?.(messages);\n },\n [agent?.setMessages, agent],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(\n async (messageId: string) => {\n onReloadMessages?.({\n messageId,\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return await latestReload.current(messageId);\n },\n [latestReload, agent, onReloadMessages],\n );\n\n const latestStopFunc = useCallback(() => {\n onStopGeneration?.({\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return agent?.abortRun?.();\n }, [onStopGeneration, agent]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n const lazyToolRendered = useLazyToolRenderer();\n const renderCustomMessage = useRenderCustomMessages();\n const legacyCustomMessageRenderer = useLegacyCoagentRenderer({\n copilotkit,\n agent,\n agentId: resolvedAgentId,\n threadId: existingConfig?.threadId ?? threadId,\n });\n const allMessages = agent?.messages ?? [];\n const resolvedMessages = useMemo(() => {\n let processedMessages = allMessages.map((message) => {\n if (message.role !== \"assistant\") {\n return message;\n }\n\n const lazyRendered = lazyToolRendered(message, allMessages);\n if (lazyRendered) {\n const renderedGenUi = lazyRendered();\n if (renderedGenUi) {\n return { ...message, generativeUI: () => renderedGenUi };\n }\n }\n\n const bridgeRenderer =\n legacyCustomMessageRenderer || renderCustomMessage\n ? () => {\n if (legacyCustomMessageRenderer) {\n return legacyCustomMessageRenderer({\n message,\n position: \"before\",\n });\n }\n try {\n return (\n renderCustomMessage?.({ message, position: \"before\" }) ?? null\n );\n } catch (error) {\n console.warn(\n \"[CopilotKit] renderCustomMessages failed, falling back to legacy renderer\",\n error,\n );\n return null;\n }\n }\n : null;\n\n if (bridgeRenderer) {\n // Attach a position so react-ui can render the custom UI above the assistant content.\n return {\n ...message,\n generativeUI: bridgeRenderer,\n generativeUIPosition: \"before\" as const,\n };\n }\n return message;\n });\n\n const hasAssistantMessages = processedMessages.some(\n (msg) => msg.role === \"assistant\",\n );\n const canUseCustomRenderer = Boolean(\n renderCustomMessage && copilotkit?.getAgent?.(resolvedAgentId),\n );\n const placeholderRenderer = legacyCustomMessageRenderer\n ? legacyCustomMessageRenderer\n : canUseCustomRenderer\n ? renderCustomMessage\n : null;\n\n const shouldRenderPlaceholder =\n Boolean(agent?.isRunning) ||\n Boolean(agent?.state && Object.keys(agent.state).length);\n\n const effectiveThreadId = threadId ?? agent?.threadId ?? \"default\";\n let latestUserIndex = -1;\n for (let i = processedMessages.length - 1; i >= 0; i -= 1) {\n if (processedMessages[i].role === \"user\") {\n latestUserIndex = i;\n break;\n }\n }\n const latestUserMessageId =\n latestUserIndex >= 0 ? processedMessages[latestUserIndex].id : undefined;\n const currentRunId = latestUserMessageId\n ? copilotkit.getRunIdForMessage(\n resolvedAgentId,\n effectiveThreadId,\n latestUserMessageId,\n ) || `pending:${latestUserMessageId}`\n : undefined;\n const hasAssistantForCurrentRun =\n latestUserIndex >= 0\n ? processedMessages\n .slice(latestUserIndex + 1)\n .some((msg) => msg.role === \"assistant\")\n : hasAssistantMessages;\n\n // Insert a placeholder assistant message so state snapshots can render before any\n // assistant text exists for the current run.\n if (\n placeholderRenderer &&\n shouldRenderPlaceholder &&\n !hasAssistantForCurrentRun\n ) {\n const placeholderId = currentRunId\n ? `coagent-state-render-${resolvedAgentId}-${currentRunId}`\n : `coagent-state-render-${resolvedAgentId}`;\n const placeholderMessage: Message = {\n id: placeholderId,\n role: \"assistant\",\n content: \"\",\n name: \"coagent-state-render\",\n runId: currentRunId,\n };\n processedMessages = [\n ...processedMessages,\n {\n ...placeholderMessage,\n generativeUIPosition: \"before\" as const,\n generativeUI: () =>\n placeholderRenderer({\n message: placeholderMessage,\n position: \"before\",\n }),\n } as Message,\n ];\n }\n\n return processedMessages;\n }, [\n agent?.messages,\n lazyToolRendered,\n allMessages,\n renderCustomMessage,\n legacyCustomMessageRenderer,\n resolvedAgentId,\n copilotkit,\n agent?.isRunning,\n agent?.state,\n ]);\n\n const renderedSuggestions = useMemo(() => {\n if (Array.isArray(suggestions)) {\n return {\n suggestions: suggestions.map((s) => ({ ...s, isLoading: false })),\n isLoading: false,\n };\n }\n return currentSuggestions;\n }, [suggestions, currentSuggestions]);\n\n // @ts-ignore\n return {\n messages: resolvedMessages,\n sendMessage: latestSendMessageFunc,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n isAvailable: agentAvailable,\n isLoading: Boolean(agent?.isRunning),\n // mcpServers,\n // setMcpServers,\n suggestions: renderedSuggestions.suggestions,\n setSuggestions: (suggestions: Omit<Suggestion, \"isLoading\">[]) =>\n copilotkit.addSuggestionsConfig({ suggestions }),\n generateSuggestions: async () =>\n copilotkit.reloadSuggestions(resolvedAgentId),\n resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),\n isLoadingSuggestions: renderedSuggestions.isLoading,\n interrupt,\n agent,\n threadId,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\ntype LegacyRenderParams = {\n message: Message;\n position: \"before\" | \"after\";\n};\n\ntype LegacyRenderer = ((args: LegacyRenderParams) => any) | null;\n\nfunction useLegacyCoagentRenderer({\n copilotkit,\n agent,\n agentId,\n threadId,\n}: {\n copilotkit: ReturnType<typeof useCopilotKit>[\"copilotkit\"];\n agent?: AbstractAgent;\n agentId: string;\n threadId?: string;\n}): LegacyRenderer {\n return useMemo(() => {\n if (!copilotkit || !agent) {\n return null;\n }\n\n return ({ message, position }: LegacyRenderParams) => {\n const effectiveThreadId = threadId ?? agent.threadId ?? \"default\";\n const providedRunId = (message as any).runId as string | undefined;\n const existingRunId = providedRunId\n ? providedRunId\n : copilotkit.getRunIdForMessage(agentId, effectiveThreadId, message.id);\n const runId = existingRunId || `pending:${message.id}`;\n const messageIndex = Math.max(\n agent.messages.findIndex((msg) => msg.id === message.id),\n 0,\n );\n\n const bridgeProps: CoAgentStateRenderBridgeProps = {\n message: message as any,\n position,\n runId,\n messageIndex,\n messageIndexInRun: 0,\n numberOfMessagesInRun: 1,\n agentId,\n stateSnapshot: (message as any).state,\n };\n\n return createElement(CoAgentStateRenderBridge, bridgeProps) as any;\n };\n }, [agent, agentId, copilotkit, threadId]);\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n","/**\n * `useCopilotChat` is a lightweight React hook for headless chat interactions.\n * Perfect for controlling the prebuilt chat components programmatically.\n *\n * **Open Source Friendly** - Works without requiring a free public license key.\n *\n * <Callout title=\"Looking for fully headless UI?\">\n * Get started with [useCopilotChatHeadless_c](https://docs.copilotkit.ai/reference/v1/hooks/useCopilotChatHeadless_c).\n * </Callout>\n *\n * ## Use Cases\n *\n * - **Programmatic Messaging**: Send messages without displaying chat UI\n * - **Programmatic control**: Control prebuilt component programmatically\n * - **Background Operations**: Trigger AI interactions in the background\n * - **Fire-and-Forget**: Send messages without needing to read responses\n *\n * ## Usage\n *\n * ```tsx\n * import { TextMessage, MessageRole } from \"@copilotkit/runtime-client-gql\";\n *\n * const { appendMessage } = useCopilotChat();\n *\n * // Example usage without naming conflicts\n * const handleSendMessage = async (content: string) => {\n * await appendMessage(\n * new TextMessage({\n * role: MessageRole.User,\n * content,\n * })\n * );\n * };\n * ```\n *\n * ## Return Values\n * The following properties are returned from the hook:\n *\n * <PropertyReference name=\"visibleMessages\" type=\"DeprecatedGqlMessage[]\" deprecated>\n * Array of messages in old non-AG-UI format, use for compatibility only\n * </PropertyReference>\n *\n * <PropertyReference name=\"appendMessage\" type=\"(message: DeprecatedGqlMessage, options?) => Promise<void>\" deprecated>\n * Append message using old format, use `sendMessage` instead\n * </PropertyReference>\n *\n * <PropertyReference name=\"reloadMessages\" type=\"(messageId: string) => Promise<void>\">\n * Regenerate the response for a specific message by ID\n * </PropertyReference>\n *\n * <PropertyReference name=\"stopGeneration\" type=\"() => void\">\n * Stop the current message generation process\n * </PropertyReference>\n *\n * <PropertyReference name=\"reset\" type=\"() => void\">\n * Clear all messages and reset chat state completely\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoading\" type=\"boolean\">\n * Whether the chat is currently generating a response\n * </PropertyReference>\n *\n * <PropertyReference name=\"runChatCompletion\" type=\"() => Promise<Message[]>\">\n * Manually trigger chat completion for advanced usage\n * </PropertyReference>\n *\n * <PropertyReference name=\"mcpServers\" type=\"MCPServerConfig[]\">\n * Array of Model Context Protocol server configurations\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMcpServers\" type=\"(servers: MCPServerConfig[]) => void\">\n * Update MCP server configurations for enhanced context\n * </PropertyReference>\n */\n\nimport {\n UseCopilotChatOptions,\n useCopilotChatInternal,\n UseCopilotChatReturn as UseCopilotChatReturnInternal,\n} from \"./use-copilot-chat_internal\";\n\n// Create a type that excludes message-related properties from the internal type\nexport type UseCopilotChatReturn = Omit<\n UseCopilotChatReturnInternal,\n | \"messages\"\n | \"sendMessage\"\n | \"suggestions\"\n | \"setSuggestions\"\n | \"generateSuggestions\"\n | \"isLoadingSuggestions\"\n | \"resetSuggestions\"\n | \"interrupt\"\n | \"setMessages\"\n | \"deleteMessage\"\n>;\n\n/**\n * A lightweight React hook for headless chat interactions.\n * Perfect for programmatic messaging, background operations, and custom UI implementations.\n *\n * **Open Source Friendly** - Works without requiring a `publicApiKey`.\n */\n// TODO: Do we need this? If so, does it work properly? test.\nexport function useCopilotChat(\n options: UseCopilotChatOptions = {},\n): UseCopilotChatReturn {\n const {\n visibleMessages,\n appendMessage,\n reloadMessages,\n stopGeneration,\n reset,\n isLoading,\n isAvailable,\n runChatCompletion,\n mcpServers,\n setMcpServers,\n } = useCopilotChatInternal(options);\n\n return {\n visibleMessages,\n appendMessage,\n reloadMessages,\n stopGeneration,\n reset,\n isLoading,\n isAvailable,\n runChatCompletion,\n mcpServers,\n setMcpServers,\n };\n}\n","/**\n * `useCopilotChatHeadless_c` is for building fully custom UI (headless UI) implementations.\n *\n * <Callout title=\"This is a premium-only feature\">\n * Sign up for free on [Copilot Cloud](https://cloud.copilotkit.ai) to get your public license key or read more about <a href=\"/premium/overview\">premium features</a>.\n *\n * Usage is generous, **free** to get started, and works with **either self-hosted or Copilot Cloud** environments.\n * </Callout>\n *\n * ## Key Features\n *\n * - **Fully headless**: Build your own fully custom UI's for your agentic applications.\n * - **Advanced Suggestions**: Direct access to suggestions array with full control\n * - **Interrupt Handling**: Support for advanced interrupt functionality\n * - **MCP Server Support**: Model Context Protocol server configurations\n * - **Chat Controls**: Complete set of chat management functions\n * - **Loading States**: Comprehensive loading state management\n *\n *\n * ## Usage\n *\n * ### Basic Setup\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n * import { useCopilotChatHeadless_c } from \"@copilotkit/react-core\";\n *\n * export function App() {\n * return (\n * <CopilotKit publicApiKey=\"your-free-public-license-key\">\n * <YourComponent />\n * </CopilotKit>\n * );\n * }\n *\n * export function YourComponent() {\n * const { messages, sendMessage, isLoading } = useCopilotChatHeadless_c();\n *\n * const handleSendMessage = async () => {\n * await sendMessage({\n * id: \"123\",\n * role: \"user\",\n * content: \"Hello World\",\n * });\n * };\n *\n * return (\n * <div>\n * {messages.map(msg => <div key={msg.id}>{msg.content}</div>)}\n * <button onClick={handleSendMessage} disabled={isLoading}>\n * Send Message\n * </button>\n * </div>\n * );\n * }\n * ```\n *\n * ### Working with Suggestions\n *\n * ```tsx\n * import { useCopilotChatHeadless_c, useCopilotChatSuggestions } from \"@copilotkit/react-core\";\n *\n * export function SuggestionExample() {\n * const {\n * suggestions,\n * setSuggestions,\n * generateSuggestions,\n * isLoadingSuggestions\n * } = useCopilotChatHeadless_c();\n *\n * // Configure AI suggestion generation\n * useCopilotChatSuggestions({\n * instructions: \"Suggest helpful actions based on the current context\",\n * maxSuggestions: 3\n * });\n *\n * return (\n * <div>\n * {suggestions.map(suggestion => (\n * <button key={suggestion.title}>{suggestion.title}</button>\n * ))}\n * <button onClick={generateSuggestions} disabled={isLoadingSuggestions}>\n * Generate Suggestions\n * </button>\n * </div>\n * );\n * }\n * ```\n *\n * ## Return Values\n * The following properties are returned from the hook:\n *\n * <PropertyReference name=\"messages\" type=\"Message[]\">\n * The messages currently in the chat in AG-UI format\n * </PropertyReference>\n *\n * <PropertyReference name=\"sendMessage\" type=\"(message: Message, options?) => Promise<void>\">\n * Send a new message to the chat and trigger AI response\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMessages\" type=\"(messages: Message[] | DeprecatedGqlMessage[]) => void\">\n * Replace all messages in the chat with new array\n * </PropertyReference>\n *\n * <PropertyReference name=\"deleteMessage\" type=\"(messageId: string) => void\">\n * Remove a specific message by ID from the chat\n * </PropertyReference>\n *\n * <PropertyReference name=\"reloadMessages\" type=\"(messageId: string) => Promise<void>\">\n * Regenerate the response for a specific message by ID\n * </PropertyReference>\n *\n * <PropertyReference name=\"stopGeneration\" type=\"() => void\">\n * Stop the current message generation process\n * </PropertyReference>\n *\n * <PropertyReference name=\"reset\" type=\"() => void\">\n * Clear all messages and reset chat state completely\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoading\" type=\"boolean\">\n * Whether the chat is currently generating a response\n * </PropertyReference>\n *\n * <PropertyReference name=\"runChatCompletion\" type=\"() => Promise<Message[]>\">\n * Manually trigger chat completion for advanced usage\n * </PropertyReference>\n *\n * <PropertyReference name=\"mcpServers\" type=\"MCPServerConfig[]\">\n * Array of Model Context Protocol server configurations\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMcpServers\" type=\"(servers: MCPServerConfig[]) => void\">\n * Update MCP server configurations for enhanced context\n * </PropertyReference>\n *\n * <PropertyReference name=\"suggestions\" type=\"SuggestionItem[]\">\n * Current suggestions array for reading or manual control\n * </PropertyReference>\n *\n * <PropertyReference name=\"setSuggestions\" type=\"(suggestions: SuggestionItem[]) => void\">\n * Manually set suggestions for custom workflows\n * </PropertyReference>\n *\n * <PropertyReference name=\"generateSuggestions\" type=\"() => Promise<void>\">\n * Trigger AI-powered suggestion generation using configured settings\n * </PropertyReference>\n *\n * <PropertyReference name=\"resetSuggestions\" type=\"() => void\">\n * Clear all current suggestions and reset generation state\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoadingSuggestions\" type=\"boolean\">\n * Whether suggestions are currently being generated\n * </PropertyReference>\n *\n * <PropertyReference name=\"interrupt\" type=\"string | React.ReactElement | null\">\n * Interrupt content for human-in-the-loop workflows\n * </PropertyReference>\n */\nimport { useEffect } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport {\n useCopilotChatInternal,\n defaultSystemMessage,\n UseCopilotChatOptions as UseCopilotChatOptions_c,\n UseCopilotChatReturn as UseCopilotChatReturn_c,\n MCPServerConfig,\n} from \"./use-copilot-chat_internal\";\n\nimport {\n ErrorVisibility,\n Severity,\n CopilotKitError,\n CopilotKitErrorCode,\n styledConsole,\n} from \"@copilotkit/shared\";\n\n// Non-functional fallback implementation\nconst createNonFunctionalReturn = (): UseCopilotChatReturn_c => ({\n visibleMessages: [],\n messages: [],\n sendMessage: async () => {},\n appendMessage: async () => {},\n setMessages: () => {},\n deleteMessage: () => {},\n reloadMessages: async () => {},\n stopGeneration: () => {},\n reset: () => {},\n isLoading: false,\n isAvailable: false,\n runChatCompletion: async () => [],\n mcpServers: [],\n setMcpServers: () => {},\n suggestions: [],\n setSuggestions: () => {},\n generateSuggestions: async () => {},\n resetSuggestions: () => {},\n isLoadingSuggestions: false,\n interrupt: null,\n});\n/**\n * Enterprise React hook that provides complete chat functionality for fully custom UI implementations.\n * Includes all advanced features like direct message access, suggestions array, interrupt handling, and MCP support.\n *\n * **Requires a publicApiKey** - Sign up for free at https://cloud.copilotkit.ai/\n *\n * @param options - Configuration options for the chat\n * @returns Complete chat interface with all enterprise features\n *\n * @example\n * ```tsx\n * const { messages, sendMessage, suggestions, interrupt } = useCopilotChatHeadless_c();\n * ```\n */\nfunction useCopilotChatHeadless_c(\n options: UseCopilotChatOptions_c = {},\n): UseCopilotChatReturn_c {\n const { copilotApiConfig, setBannerError } = useCopilotContext();\n\n // Check if publicApiKey is available\n const hasPublicApiKey = Boolean(copilotApiConfig.publicApiKey);\n\n // Always call the internal hook (follows rules of hooks)\n const internalResult = useCopilotChatInternal(options);\n\n // Set banner error when no public API key is provided\n useEffect(() => {\n if (!hasPublicApiKey) {\n setBannerError(\n new CopilotKitError({\n message:\n // add link to documentation here\n \"You're using useCopilotChatHeadless_c, a premium-only feature, which offers extensive headless chat capabilities. To continue, you'll need to provide a free public license key.\",\n code: CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,\n severity: Severity.WARNING,\n visibility: ErrorVisibility.BANNER,\n }),\n );\n styledConsole.logCopilotKitPlatformMessage();\n } else {\n setBannerError(null); // Clear banner when API key is provided\n }\n }, [hasPublicApiKey]); // Removed setBannerError dependency\n\n // Return internal result if publicApiKey is available, otherwise return fallback\n if (hasPublicApiKey) {\n return internalResult;\n }\n\n // Return non-functional fallback when no publicApiKey\n return createNonFunctionalReturn();\n}\n\nexport { defaultSystemMessage, useCopilotChatHeadless_c };\nexport type {\n UseCopilotChatOptions_c,\n UseCopilotChatReturn_c,\n MCPServerConfig,\n};\n\nconst noKeyWarning = () => {\n styledConsole.logCopilotKitPlatformMessage();\n};\n","import React, { useEffect, useMemo, useRef } from \"react\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport {\n Parameter,\n getZodParameters,\n MappedParameterTypes,\n} from \"@copilotkit/shared\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport {\n type ReactFrontendTool,\n useFrontendTool as useFrontendToolVNext,\n} from \"../v2\";\n\ntype FrontendToolOptions<T extends Parameter[] | []> = ReactFrontendTool<\n MappedParameterTypes<T>\n>;\ntype FrontendToolRenderArgs<T extends Parameter[] | []> =\n | {\n name: string;\n args: Partial<MappedParameterTypes<T>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n }\n | {\n name: string;\n args: MappedParameterTypes<T>;\n status: ToolCallStatus.Executing;\n result: undefined;\n }\n | {\n name: string;\n args: MappedParameterTypes<T>;\n status: ToolCallStatus.Complete;\n result: string;\n };\n\nexport type UseFrontendToolArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n} & Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\" | \"handler\" | \"followUp\" | \"render\"\n>;\n\nexport function useFrontendTool<const T extends Parameter[] = []>(\n tool: UseFrontendToolArgs<T>,\n dependencies?: any[],\n) {\n const { name, description, parameters, render, followUp, available } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderRef = useRef<typeof render>(render);\n\n useEffect(() => {\n renderRef.current = render;\n }, [render, ...(dependencies ?? [])]);\n\n const normalizedRender: FrontendToolOptions<T>[\"render\"] | undefined =\n useMemo(() => {\n if (typeof render === \"undefined\") {\n return undefined;\n }\n\n return ((args: FrontendToolRenderArgs<T>) => {\n const currentRender = renderRef.current;\n\n if (typeof currentRender === \"undefined\") {\n return null;\n }\n\n if (typeof currentRender === \"string\") {\n return React.createElement(React.Fragment, null, currentRender);\n }\n\n const renderArgs = {\n ...args,\n result:\n typeof args.result === \"string\"\n ? parseJson(args.result, args.result)\n : args.result,\n } as ActionRenderProps<T>;\n\n const rendered = currentRender(renderArgs);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n }) as FrontendToolOptions<T>[\"render\"];\n }, []);\n\n // Handler ref to avoid stale closures\n const handlerRef = useRef<typeof tool.handler>(tool.handler);\n\n useEffect(() => {\n handlerRef.current = tool.handler;\n }, [tool.handler, ...(dependencies ?? [])]);\n\n const normalizedHandler = tool.handler\n ? (args: MappedParameterTypes<T>) => handlerRef.current?.(args)\n : undefined;\n\n useFrontendToolVNext<MappedParameterTypes<T>>({\n name,\n description,\n parameters: zodParameters,\n handler: normalizedHandler,\n followUp,\n render: normalizedRender,\n available: available === undefined ? undefined : available !== \"disabled\",\n });\n}\n","import { type Parameter, getZodParameters } from \"@copilotkit/shared\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { defineToolCallRenderer, useCopilotKit } from \"../v2\";\nimport type React from \"react\";\nimport { useEffect, useRef } from \"react\";\nimport {\n type ActionRenderProps,\n type ActionRenderPropsNoArgs,\n ActionRenderPropsWait,\n type FrontendAction,\n} from \"../types\";\n\ntype ToolCallRendererDefinition = Parameters<typeof defineToolCallRenderer>[0];\n\nexport type UseRenderToolCallArgs<T extends Parameter[] | [] = []> = Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\"\n> & {\n available?: \"disabled\" | \"enabled\";\n render: T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => React.ReactElement\n : (props: ActionRenderProps<T>) => React.ReactElement;\n};\n\nexport function useRenderToolCall<const T extends Parameter[] | [] = []>(\n tool: UseRenderToolCallArgs<T>,\n dependencies?: any[],\n) {\n const { copilotkit } = useCopilotKit();\n\n // Track whether we've already added this renderer to avoid duplicates\n const hasAddedRef = useRef(false);\n\n useEffect(() => {\n const { name, parameters, render } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderToolCall =\n name === \"*\"\n ? defineToolCallRenderer({\n name: \"*\",\n render: ((args) => {\n return render({\n ...args,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n })\n : defineToolCallRenderer({\n name,\n args: zodParameters,\n render: ((args) => {\n return render({\n ...args,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n });\n\n // Remove any existing renderer with the same name\n const existingIndex = copilotkit.renderToolCalls.findIndex(\n (r) => r.name === name,\n );\n if (existingIndex !== -1) {\n copilotkit.renderToolCalls.splice(existingIndex, 1);\n }\n\n // Add the new renderer\n copilotkit.renderToolCalls.push(renderToolCall);\n hasAddedRef.current = true;\n\n // Cleanup: remove this renderer when the component unmounts or tool changes\n return () => {\n if (hasAddedRef.current) {\n const index = copilotkit.renderToolCalls.findIndex(\n (r) => r.name === name,\n );\n if (index !== -1) {\n copilotkit.renderToolCalls.splice(index, 1);\n }\n hasAddedRef.current = false;\n }\n };\n }, [tool, ...(dependencies ?? [])]);\n}\n","import {\n ActionRenderProps,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types\";\nimport {\n CopilotKitError,\n CopilotKitErrorCode,\n MappedParameterTypes,\n Parameter,\n getZodParameters,\n parseJson,\n} from \"@copilotkit/shared\";\nimport { useHumanInTheLoop as useHumanInTheLoopVNext } from \"../v2\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport React, {\n ComponentType,\n FunctionComponent,\n useEffect,\n useRef,\n} from \"react\";\n\ntype HumanInTheLoopOptions = Parameters<typeof useHumanInTheLoopVNext>[0];\ntype HumanInTheLoopRender = HumanInTheLoopOptions[\"render\"];\ntype HumanInTheLoopRenderArgs = HumanInTheLoopRender extends (\n props: infer P,\n) => any\n ? P\n : never;\n\nexport type UseHumanInTheLoopArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n render: FrontendAction<T>[\"renderAndWaitForResponse\"];\n followUp?: FrontendAction<T>[\"followUp\"];\n} & Pick<FrontendAction<T>, \"name\" | \"description\" | \"parameters\">;\n\ntype HitlRendererArgs =\n | {\n name: string;\n description: string;\n args: Partial<Record<string, unknown>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n respond: undefined;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Executing;\n result: undefined;\n respond: (result: unknown) => Promise<void>;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Complete;\n result: string;\n respond: undefined;\n };\ntype HitlRenderer = FunctionComponent<HitlRendererArgs>;\n\nexport function useHumanInTheLoop<const T extends Parameter[] | [] = []>(\n tool: UseHumanInTheLoopArgs<T>,\n dependencies?: any[],\n) {\n const { render, ...toolRest } = tool;\n const { name, description, parameters, followUp } = toolRest;\n const zodParameters = getZodParameters(parameters);\n const renderRef = useRef<HitlRenderer | null>(null);\n\n useEffect(() => {\n renderRef.current = (args: HitlRendererArgs): React.ReactElement | null => {\n if (typeof render === \"string\") {\n return React.createElement(React.Fragment, null, render);\n }\n\n if (!render) {\n return null;\n }\n\n const renderProps: ActionRenderPropsWait<T> = (() => {\n const mappedArgs = args.args as unknown as MappedParameterTypes<T>;\n\n switch (args.status) {\n case ToolCallStatus.InProgress:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: undefined,\n };\n case ToolCallStatus.Executing:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: () => {},\n };\n case ToolCallStatus.Complete:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n handler: undefined,\n };\n default:\n throw new CopilotKitError({\n code: CopilotKitErrorCode.UNKNOWN,\n message: `Invalid tool call status: ${(args as unknown as { status: string }).status}`,\n });\n }\n })();\n\n const rendered = render(renderProps);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n };\n }, [render, ...(dependencies ?? [])]);\n\n useHumanInTheLoopVNext({\n name,\n description,\n followUp,\n parameters: zodParameters,\n render: ((args: HumanInTheLoopRenderArgs) =>\n renderRef.current?.(args as HitlRendererArgs) ??\n null) as HumanInTheLoopOptions[\"render\"],\n });\n}\n","/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { useEffect, useRef, useState } from \"react\";\nimport { Parameter } from \"@copilotkit/shared\";\nimport {\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport { useFrontendTool, UseFrontendToolArgs } from \"./use-frontend-tool\";\nimport {\n useRenderToolCall,\n UseRenderToolCallArgs,\n} from \"./use-render-tool-call\";\nimport {\n useHumanInTheLoop,\n UseHumanInTheLoopArgs,\n} from \"./use-human-in-the-loop\";\nimport { useCopilotContext } from \"../context\";\n\n// Helper to determine which component and action config to use\nfunction getActionConfig<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n) {\n if (action.name === \"*\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n\n if (\"renderAndWaitForResponse\" in action || \"renderAndWait\" in action) {\n let render = action.render;\n if (!render && \"renderAndWaitForResponse\" in action) {\n // @ts-expect-error -- renderAndWaitForResponse is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWaitForResponse;\n }\n if (!render && \"renderAndWait\" in action) {\n // @ts-expect-error -- renderAndWait is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWait;\n }\n\n return {\n type: \"hitl\" as const,\n action: { ...action, render } as UseHumanInTheLoopArgs<T>,\n };\n }\n\n if (\"available\" in action) {\n if (action.available === \"enabled\" || action.available === \"remote\") {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n if (action.available === \"frontend\" || action.available === \"disabled\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n }\n\n if (\"handler\" in action) {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n\n throw new Error(\"Invalid action configuration\");\n}\n\n/**\n * useCopilotAction is a legacy hook maintained for backwards compatibility.\n *\n * To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),\n * we use a registration pattern:\n * 1. This hook registers the action configuration with the CopilotContext\n * 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper\n * 3. React properly manages hook state since components are rendered, not conditionally called\n *\n * This allows action types to change between renders without corrupting React's hook state.\n */\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const [initialActionConfig] = useState(getActionConfig(action));\n const currentActionConfig = getActionConfig(action);\n\n /**\n * Calling hooks conditionally violates React's Rules of Hooks. This rule exists because\n * React maintains the call stack for hooks like useEffect or useState, and conditionally\n * calling a hook would result in inconsistent call stacks between renders.\n *\n * Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the\n * supplied parameters. In order to avoid breaking React's call stack tracking, while\n * breaking the Rule of Hooks, we use a ref to store the initial action configuration\n * and throw an error if the _configuration_ changes such that we would call a different hook.\n */\n if (initialActionConfig.type !== currentActionConfig.type) {\n throw new Error(\"Action configuration changed between renders\");\n }\n\n switch (currentActionConfig.type) {\n case \"render\":\n return useRenderToolCall(currentActionConfig.action, dependencies);\n case \"hitl\":\n return useHumanInTheLoop(currentActionConfig.action, dependencies);\n case \"frontend\":\n return useFrontendTool(currentActionConfig.action, dependencies);\n default:\n throw new Error(\"Invalid action configuration\");\n }\n}\n","/**\n * The useCoAgentStateRender hook allows you to render UI or text based components on a Agentic Copilot's state in the chat.\n * This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgentStateRender } from \"@copilotkit/react-core\";\n *\n * type YourAgentState = {\n * agent_state_property: string;\n * }\n *\n * useCoAgentStateRender<YourAgentState>({\n * name: \"basic_agent\",\n * nodeName: \"optionally_specify_a_specific_node\",\n * render: ({ status, state, nodeName }) => {\n * return (\n * <YourComponent\n * agentStateProperty={state.agent_state_property}\n * status={status}\n * nodeName={nodeName}\n * />\n * );\n * },\n * });\n * ```\n *\n * This allows for you to render UI components or text based on what is happening within the agent.\n *\n * ### Example\n * A great example of this is in our Perplexity Clone where we render the progress of an agent's internet search as it is happening.\n * You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).\n *\n * <Callout type=\"info\">\n * This example is hosted on Vercel and may take a few seconds to load.\n * </Callout>\n *\n * <iframe src=\"https://examples-coagents-ai-researcher-ui.vercel.app/\" className=\"w-full rounded-lg border h-[700px] my-4\" />\n */\n\nimport { useRef, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { randomId, CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCoAgentStateRenders } from \"../context/coagent-state-renders-context\";\n\n/**\n * This hook is used to render agent state with custom UI components or text. This is particularly\n * useful for showing intermediate state or progress during Agentic Copilot operations.\n * To get started using rendering intermediate state through this hook, checkout the documentation.\n *\n * https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates\n */\n\n// We implement useCoAgentStateRender dependency handling so that\n// the developer has the option to not provide any dependencies.\n// see useCopilotAction for more details about this approach.\nexport function useCoAgentStateRender<T = any>(\n action: CoAgentStateRender<T>,\n dependencies?: any[],\n): void {\n const { chatComponentsCache, availableAgents } = useContext(CopilotContext);\n const {\n setCoAgentStateRender,\n removeCoAgentStateRender,\n coAgentStateRenders,\n } = useCoAgentStateRenders();\n const idRef = useRef<string>(randomId());\n const { setBannerError, addToast } = useToast();\n\n useEffect(() => {\n if (\n availableAgents?.length &&\n !availableAgents.some((a) => a.name === action.name)\n ) {\n const message = `(useCoAgentStateRender): Agent \"${action.name}\" not found. Make sure the agent exists and is properly configured.`;\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: action.name,\n availableAgents: availableAgents.map((a) => ({\n name: a.name,\n id: a.id,\n })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coAgentStateRenders[idRef.current]) {\n coAgentStateRenders[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n // Check for duplicates by comparing against all other actions\n const currentId = idRef.current;\n const hasDuplicate = Object.entries(coAgentStateRenders).some(\n ([id, otherAction]) => {\n // Skip comparing with self\n if (id === currentId) return false;\n\n // Different agent names are never duplicates\n if (otherAction.name !== action.name) return false;\n\n // Same agent names:\n const hasNodeName = !!action.nodeName;\n const hasOtherNodeName = !!otherAction.nodeName;\n\n // If neither has nodeName, they're duplicates\n if (!hasNodeName && !hasOtherNodeName) return true;\n\n // If one has nodeName and other doesn't, they're not duplicates\n if (hasNodeName !== hasOtherNodeName) return false;\n\n // If both have nodeName, they're duplicates only if the names match\n return action.nodeName === otherAction.nodeName;\n },\n );\n\n if (hasDuplicate) {\n const message = action.nodeName\n ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden`\n : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;\n\n addToast({\n type: \"warning\",\n message,\n id: `dup-action-${action.name}`,\n });\n }\n }, [coAgentStateRenders]);\n\n useEffect(() => {\n setCoAgentStateRender(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n return () => {\n removeCoAgentStateRender(idRef.current);\n };\n }, [\n setCoAgentStateRender,\n removeCoAgentStateRender,\n action.name,\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n","import { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useCopilotContext();\n const idRef = useRef<string>(undefined!);\n\n useEffect(() => {\n const id = addDocumentContext(document, categories);\n idRef.current = id;\n\n return () => {\n removeDocumentContext(id);\n };\n }, [addDocumentContext, removeDocumentContext, ...dependencies]);\n\n return idRef.current;\n}\n","/**\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotReadable accepts a single string argument\n * representing any piece of app state, making it available for the Copilot to use\n * as context when responding to user input.\n *\n * ```tsx\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotReadable({\n * description: \"The list of employees\",\n * value: employees,\n * });\n * }\n * ```\n *\n * ### Nested Components\n *\n * Optionally, you can maintain the hierarchical structure of information by passing\n * `parentId`. This allows you to use `useCopilotReadable` in nested components:\n *\n * ```tsx /employeeContextId/1 {17,23}\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * function Employee(props: EmployeeProps) {\n * const { employeeName, workProfile, metadata } = props;\n *\n * // propagate any information to copilot\n * const employeeContextId = useCopilotReadable({\n * description: \"Employee name\",\n * value: employeeName\n * });\n *\n * // Pass a parentID to maintain a hierarchical structure.\n * // Especially useful with child React components, list elements, etc.\n * useCopilotReadable({\n * description: \"Work profile\",\n * value: workProfile.description(),\n * parentId: employeeContextId\n * });\n *\n * useCopilotReadable({\n * description: \"Employee metadata\",\n * value: metadata.description(),\n * parentId: employeeContextId\n * });\n *\n * return (\n * // Render as usual...\n * );\n * }\n * ```\n */\nimport { useCopilotKit } from \"../v2\";\nimport { useEffect, useRef } from \"react\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context. Object values are automatically stringified.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * Whether the context is available to the Copilot.\n */\n available?: \"enabled\" | \"disabled\";\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n { description, value, convert, available }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { copilotkit } = useCopilotKit();\n const ctxIdRef = useRef<string | undefined>(undefined);\n useEffect(() => {\n if (!copilotkit) return;\n\n const found = Object.entries(copilotkit.context).find(([id, ctxItem]) => {\n return JSON.stringify({ description, value }) == JSON.stringify(ctxItem);\n });\n if (found) {\n ctxIdRef.current = found[0];\n if (available === \"disabled\") copilotkit.removeContext(ctxIdRef.current);\n return;\n }\n if (!found && available === \"disabled\") return;\n\n ctxIdRef.current = copilotkit.addContext({\n description,\n value: (convert ?? JSON.stringify)(value),\n });\n\n return () => {\n if (!ctxIdRef.current) return;\n copilotkit.removeContext(ctxIdRef.current);\n };\n }, [description, value, convert]);\n\n return ctxIdRef.current;\n}\n","import { useEffect, useRef } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgent } from \"../v2\";\n\nexport function useAgentNodeName(agentName?: string) {\n const { agent } = useAgent({ agentId: agentName });\n const nodeNameRef = useRef<string>(\"start\");\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStepStartedEvent: ({ event }) => {\n nodeNameRef.current = event.stepName;\n },\n onRunStartedEvent: () => {\n nodeNameRef.current = \"start\";\n },\n onRunFinishedEvent: () => {\n nodeNameRef.current = \"end\";\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent]);\n\n return nodeNameRef.current;\n}\n","/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Message } from \"@copilotkit/shared\";\nimport { useAgent, useCopilotKit } from \"../v2\";\nimport { type AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<\n T,\n> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (...args: any[]) => Promise<any>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(\n options: UseCoagentOptions<T>,\n): UseCoagentReturnType<T> {\n const { agent } = useAgent({ agentId: options.name });\n const { copilotkit } = useCopilotKit();\n const nodeName = useAgentNodeName(options.name);\n\n const handleStateUpdate = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n if (!agent) return;\n\n if (typeof newState === \"function\") {\n const updater = newState as (prevState: T | undefined) => T;\n agent.setState(updater(agent.state));\n } else {\n agent.setState({ ...agent.state, ...newState });\n }\n },\n [agent?.state, agent?.setState],\n );\n\n useEffect(() => {\n if (!options.config && !options.configurable) return;\n\n let config = options.config ?? {};\n if (options.configurable) {\n config = {\n ...config,\n configurable: {\n ...options.configurable,\n ...config.configurable,\n },\n };\n }\n copilotkit.setProperties(config);\n }, [options.config, options.configurable]);\n\n const externalStateStr = useMemo(\n () =>\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : undefined,\n [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : undefined,\n ],\n );\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (\n agent?.state &&\n isExternalStateManagement(options) &&\n JSON.stringify(options.state) !== JSON.stringify(agent.state)\n ) {\n handleStateUpdate(options.state);\n }\n }, [agent, externalStateStr, handleStateUpdate]);\n\n const hasStateValues = useCallback((value?: Record<string, any>) => {\n return Boolean(value && Object.keys(value).length);\n }, []);\n\n const initialStateRef = useRef<any>(\n isExternalStateManagement(options)\n ? options.state\n : \"initialState\" in options\n ? options.initialState\n : undefined,\n );\n\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n initialStateRef.current = options.state;\n } else if (\"initialState\" in options) {\n initialStateRef.current = options.initialState;\n }\n }, [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : \"initialState\" in options\n ? JSON.stringify(options.initialState)\n : undefined,\n ]);\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStateChanged: (args: any) => {\n if (isExternalStateManagement(options)) {\n options.setState(args.state);\n }\n },\n onRunInitialized: (args: any) => {\n const runHasState = hasStateValues(args.state);\n if (runHasState) {\n handleStateUpdate(args.state);\n return;\n }\n\n if (hasStateValues(agent.state)) {\n return;\n }\n\n if (initialStateRef.current !== undefined) {\n handleStateUpdate(initialStateRef.current);\n }\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent, handleStateUpdate, hasStateValues]);\n\n // Return a consistent shape whether or not the agent is available\n return useMemo<UseCoagentReturnType<T>>(() => {\n if (!agent) {\n const noop = () => {};\n const noopAsync = async () => {};\n const initialState =\n // prefer externally provided state if available\n (\"state\" in options && (options as any).state) ??\n // then initialState if provided\n (\"initialState\" in options && (options as any).initialState) ??\n ({} as T);\n return {\n name: options.name,\n nodeName,\n threadId: undefined,\n running: false,\n state: initialState as T,\n setState: noop,\n start: noop,\n stop: noop,\n run: noopAsync,\n };\n }\n\n return {\n name: agent?.agentId ?? options.name,\n nodeName,\n threadId: agent.threadId,\n running: agent.isRunning,\n state: agent.state,\n setState: handleStateUpdate,\n // TODO: start and run both have same thing. need to figure out\n start: agent.runAgent,\n stop: agent.abortRun,\n run: agent.runAgent,\n };\n }, [\n agent?.state,\n agent?.runAgent,\n agent?.abortRun,\n agent?.runAgent,\n agent?.threadId,\n agent?.isRunning,\n agent?.agentId,\n handleStateUpdate,\n options.name,\n ]);\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n","import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo, useRef } from \"react\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n CopilotErrorHandler,\n CopilotErrorEvent,\n} from \"@copilotkit/shared\";\nimport { shouldShowDevConsole } from \"../utils/dev-console\";\n\nexport interface CopilotRuntimeClientHookOptions extends CopilotRuntimeClientOptions {\n showDevConsole?: boolean;\n onError: CopilotErrorHandler;\n}\n\nexport const useCopilotRuntimeClient = (\n options: CopilotRuntimeClientHookOptions,\n) => {\n const { setBannerError } = useToast();\n const { showDevConsole, onError, ...runtimeOptions } = options;\n\n // Deduplication state for structured errors\n const lastStructuredErrorRef = useRef<{\n message: string;\n timestamp: number;\n } | null>(null);\n\n // Helper function to trace UI errors\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\n try {\n const errorEvent: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"ui\",\n request: {\n operation: \"runtimeClient\",\n url: runtimeOptions.url,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent:\n typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : undefined,\n stackTrace:\n originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onError(errorEvent);\n } catch (error) {\n console.error(\"Error in onError handler:\", error);\n }\n };\n\n const runtimeClient = useMemo(() => {\n return new CopilotRuntimeClient({\n ...runtimeOptions,\n handleGQLErrors: (error) => {\n if ((error as any).graphQLErrors?.length) {\n const graphQLErrors = (error as any).graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // All errors (including DEV_ONLY) show as banners for consistency\n // Deduplicate to prevent spam\n const now = Date.now();\n const errorMessage = gqlError.message;\n if (\n lastStructuredErrorRef.current &&\n lastStructuredErrorRef.current.message === errorMessage &&\n now - lastStructuredErrorRef.current.timestamp < 150\n ) {\n return; // Skip duplicate\n }\n lastStructuredErrorRef.current = {\n message: errorMessage,\n timestamp: now,\n };\n\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the error\n traceUIError(ckError, gqlError);\n // TODO: if onError & renderError should work without key, insert here\n } else {\n // Fallback for unstructured errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n // TODO: if onError & renderError should work without key, insert here\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n // TODO: if onError & renderError should work without key, insert here\n }\n },\n handleGQLWarning: (message: string) => {\n console.warn(message);\n // Show warnings as banners too for consistency\n const warningError = new CopilotKitError({\n message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(warningError);\n },\n });\n }, [runtimeOptions, setBannerError, onError]);\n\n return runtimeClient;\n};\n\n// Create appropriate structured error from GraphQL error\nfunction createStructuredError(gqlError: GraphQLError): CopilotKitError | null {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n // Legacy error detection by stack trace\n if (originalError?.stack?.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message });\n }\n if (\n originalError?.stack?.includes(\"CopilotKitRemoteEndpointDiscoveryError\")\n ) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n\n return null;\n}\n","import { Parameter } from \"@copilotkit/shared\";\nimport { Fragment, useCallback, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { FrontendAction, ActionRenderProps } from \"../types/frontend-action\";\nimport { useCopilotAction } from \"./use-copilot-action\";\nimport React from \"react\";\n\n/**\n * Hook to create an authenticated action that requires user sign-in before execution.\n *\n * @remarks\n * This feature is only available when using CopilotKit's hosted cloud service.\n * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.\n *\n * @param action - The frontend action to be wrapped with authentication\n * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed\n */\nexport function useCopilotAuthenticatedAction_c<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();\n const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);\n\n const executeAction = useCallback(\n (props: ActionRenderProps<Parameter[]>) => {\n if (typeof action.render === \"function\") {\n return action.render(props);\n }\n return action.render || React.createElement(Fragment);\n },\n [action],\n );\n\n const wrappedRender = useCallback(\n (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {\n const isAuthenticated = Object.values(authStates_c || {}).some(\n (state) => state.status === \"authenticated\",\n );\n\n if (!isAuthenticated) {\n // Store action details for later execution\n pendingActionRef.current = props;\n\n return authConfig_c?.SignInComponent\n ? React.createElement(authConfig_c.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates_c?.((prev) => ({\n ...prev,\n [action.name]: authState,\n }));\n if (pendingActionRef.current) {\n executeAction(pendingActionRef.current);\n pendingActionRef.current = null;\n }\n },\n })\n : React.createElement(Fragment);\n }\n\n return executeAction(props);\n },\n [action, authStates_c, setAuthStates_c],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\n}\n","import React, { useCallback, useRef } from \"react\";\nimport { LangGraphInterruptRender } from \"../types/interrupt-action\";\nimport { useInterrupt, useCopilotChatConfiguration } from \"../v2\";\nimport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n} from \"../v2\";\nimport { MetaEventName } from \"@copilotkit/runtime-client-gql\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\nimport type { AgentSession } from \"../context/copilot-context\";\n\n/**\n * Transforms a v2 InterruptEvent into the v1 LangGraphInterruptEvent shape\n * expected by existing useLangGraphInterrupt callbacks.\n */\nfunction toV1Event<TEventValue>(event: InterruptEvent<TEventValue>) {\n const value =\n typeof event.value === \"string\"\n ? parseJson(event.value, event.value)\n : event.value;\n return {\n name: MetaEventName.LangGraphInterruptEvent,\n type: \"MetaEvent\" as const,\n value,\n };\n}\n\nexport function useLangGraphInterrupt<TEventValue = any>(\n action: Omit<LangGraphInterruptRender<TEventValue>, \"id\">,\n _dependencies?: any[],\n) {\n const actionRef = useRef(action);\n // Update ref synchronously during render so it's always current\n // when callbacks read from it (useEffect would be one tick late).\n actionRef.current = action;\n\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId =\n action.agentId ?? existingConfig?.agentId ?? \"default\";\n const threadId = existingConfig?.threadId;\n const nodeName = useAgentNodeName(resolvedAgentId);\n\n // Keep agentMetadata in a ref so stable callbacks always see current values.\n const metadataRef = useRef<AgentSession>({\n agentName: resolvedAgentId,\n threadId,\n nodeName,\n });\n metadataRef.current = {\n agentName: resolvedAgentId,\n threadId,\n nodeName,\n };\n\n // Stable callback references that always read the latest action from the ref.\n // This prevents useInterrupt's internal useMemo/useEffect from seeing new\n // function identities on every render, which would cause an infinite loop.\n const render = useCallback(\n ({ event, result, resolve }: InterruptRenderProps<TEventValue>) => {\n const renderFn = actionRef.current.render;\n if (!renderFn) return React.createElement(React.Fragment);\n const rendered = renderFn({\n event: toV1Event(event) as any,\n result,\n resolve: (r) => resolve(r),\n });\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n return rendered;\n },\n [],\n );\n\n // Handler always delegates to the ref — if no handler is set at call time,\n // the optional chaining returns undefined which useInterrupt treats as null.\n const handler = useCallback(\n ({ event, resolve }: InterruptHandlerProps<TEventValue>) => {\n return actionRef.current.handler?.({\n event: toV1Event(event) as any,\n resolve: (r) => resolve(r),\n });\n },\n [],\n );\n\n const enabled = useCallback((event: InterruptEvent<TEventValue>) => {\n if (!actionRef.current.enabled) return true;\n return actionRef.current.enabled({\n eventValue: toV1Event(event).value,\n agentMetadata: metadataRef.current,\n });\n }, []);\n\n useInterrupt({\n render,\n handler,\n enabled,\n agentId: resolvedAgentId,\n });\n}\n","/**\n * `useCopilotAdditionalInstructions` is a React hook that provides additional instructions\n * to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotAdditionalInstructions accepts a single string argument\n * representing the instructions to be added to the Copilot.\n *\n * ```tsx\n * import { useCopilotAdditionalInstructions } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * useCopilotAdditionalInstructions({\n * instructions: \"Do not answer questions about the weather.\",\n * });\n * }\n * ```\n *\n * ### Conditional Usage\n *\n * You can also conditionally add instructions based on the state of your app.\n *\n * ```tsx\n * import { useCopilotAdditionalInstructions } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [showInstructions, setShowInstructions] = useState(false);\n *\n * useCopilotAdditionalInstructions({\n * available: showInstructions ? \"enabled\" : \"disabled\",\n * instructions: \"Do not answer questions about the weather.\",\n * });\n * }\n * ```\n */\nimport { useEffect } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\n\n/**\n * Options for the useCopilotAdditionalInstructions hook.\n */\nexport interface UseCopilotAdditionalInstructionsOptions {\n /**\n * The instructions to be added to the Copilot. Will be added to the instructions like so:\n *\n * ```txt\n * You are a helpful assistant.\n * Additionally, follow these instructions:\n * - Do not answer questions about the weather.\n * - Do not answer questions about the stock market.\n * ```\n */\n instructions: string;\n\n /**\n * Whether the instructions are available to the Copilot.\n */\n available?: \"enabled\" | \"disabled\";\n}\n\n/**\n * Adds the given instructions to the Copilot context.\n */\nexport function useCopilotAdditionalInstructions(\n {\n instructions,\n available = \"enabled\",\n }: UseCopilotAdditionalInstructionsOptions,\n dependencies?: any[],\n) {\n const { setAdditionalInstructions } = useCopilotContext();\n\n useEffect(() => {\n if (available === \"disabled\") return;\n\n setAdditionalInstructions((prevInstructions) => [\n ...(prevInstructions || []),\n instructions,\n ]);\n\n return () => {\n setAdditionalInstructions(\n (prevInstructions) =>\n prevInstructions?.filter(\n (instruction) => instruction !== instructions,\n ) || [],\n );\n };\n }, [\n available,\n instructions,\n setAdditionalInstructions,\n ...(dependencies || []),\n ]);\n}\n","import { useCopilotAction } from \"./use-copilot-action\";\nimport { CatchAllFrontendAction } from \"../types/frontend-action\";\n\nexport function useDefaultTool(\n tool: Omit<CatchAllFrontendAction, \"name\">,\n dependencies?: any[],\n) {\n // Use the existing useCopilotAction hook\n useCopilotAction(\n { ...tool, name: \"*\" } satisfies CatchAllFrontendAction,\n dependencies,\n );\n}\n","/**\n * <Callout type=\"warning\">\n * useCopilotChatSuggestions is experimental. The interface is not final and\n * can change without notice.\n * </Callout>\n *\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * <br/>\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-chat-suggestions/use-copilot-chat-suggestions.gif\" width=\"500\" />\n *\n * ## Usage\n *\n * ### Install Dependencies\n *\n * This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.\n *\n * ```shell npm2yarn \\\"@copilotkit/react-ui\"\\\n * npm install @copilotkit/react-core @copilotkit/react-ui\n * ```\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChatSuggestions } from \"@copilotkit/react-ui\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotChatSuggestions({\n * instructions: `The following employees are on duty: ${JSON.stringify(employees)}`,\n * });\n * }\n * ```\n *\n * ### Dependency Management\n *\n * ```tsx\n * import { useCopilotChatSuggestions } from \"@copilotkit/react-ui\";\n *\n * export function MyComponent() {\n * useCopilotChatSuggestions(\n * {\n * instructions: \"Suggest the most relevant next actions.\",\n * },\n * [appState],\n * );\n * }\n * ```\n *\n * In the example above, the suggestions are generated based on the given instructions.\n * The hook monitors `appState`, and updates suggestions accordingly whenever it changes.\n *\n * ### Behavior and Lifecycle\n *\n * The hook registers the configuration with the chat context upon component mount and\n * removes it on unmount, ensuring a clean and efficient lifecycle management.\n */\nimport {\n useConfigureSuggestions,\n useCopilotChatConfiguration,\n useCopilotKit,\n useSuggestions,\n} from \"../v2\";\nimport { useEffect } from \"react\";\nimport { StaticSuggestionsConfig, Suggestion } from \"@copilotkit/core\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> &\n Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<\n StaticSuggestionsConfig,\n \"suggestions\"\n> & {\n suggestions: StaticSuggestionInput[];\n};\n\ntype DynamicSuggestionsConfigInput = {\n /**\n * A prompt or instructions for the GPT to generate suggestions.\n */\n instructions: string;\n /**\n * The minimum number of suggestions to generate. Defaults to `1`.\n * @default 1\n */\n minSuggestions?: number;\n /**\n * The maximum number of suggestions to generate. Defaults to `3`.\n * @default 1\n */\n maxSuggestions?: number;\n\n /**\n * Whether the suggestions are available. Defaults to `enabled`.\n * @default enabled\n */\n available?:\n | \"enabled\"\n | \"disabled\"\n | \"always\"\n | \"before-first-message\"\n | \"after-first-message\";\n\n /**\n * An optional class name to apply to the suggestions.\n */\n className?: string;\n};\n\nexport type UseCopilotChatSuggestionsConfiguration =\n | DynamicSuggestionsConfigInput\n | StaticSuggestionsConfigInput;\n\nexport function useCopilotChatSuggestions(\n config: UseCopilotChatSuggestionsConfiguration,\n dependencies: any[] = [],\n) {\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n\n const available =\n (config.available === \"enabled\" ? \"always\" : config.available) ??\n \"before-first-message\";\n\n const finalSuggestionConfig = {\n ...config,\n available,\n consumerAgentId: resolvedAgentId, // Use chatConfig.agentId here\n };\n useConfigureSuggestions(finalSuggestionConfig, dependencies);\n}\n","import { ActionInputAvailability } from \"@copilotkit/runtime-client-gql\";\nimport {\n Action,\n Parameter,\n MappedParameterTypes,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingState<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: any;\n}\n\ninterface InProgressStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n}\n\nexport type ActionRenderProps<T extends Parameter[] | [] = []> =\n | CompleteState<T>\n | ExecutingState<T>\n | InProgressState<T>;\n\nexport type ActionRenderPropsNoArgs<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgs<T>\n | ExecutingStateNoArgs<T>\n | InProgressStateNoArgs<T>;\n\nexport type ActionRenderPropsWait<T extends Parameter[] | [] = []> =\n | CompleteStateWait<T>\n | ExecutingStateWait<T>\n | InProgressStateWait<T>;\n\nexport type ActionRenderPropsNoArgsWait<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgsWait<T>\n | ExecutingStateNoArgsWait<T>\n | InProgressStateNoArgsWait<T>;\n\nexport type CatchAllActionRenderProps<T extends Parameter[] | [] = []> =\n | (CompleteState<T> & {\n name: string;\n })\n | (ExecutingState<T> & {\n name: string;\n })\n | (InProgressState<T> & {\n name: string;\n });\n\nexport type FrontendActionAvailability =\n | \"disabled\"\n | \"enabled\"\n | \"remote\"\n | \"frontend\";\n\nexport type FrontendAction<\n T extends Parameter[] | [] = [],\n N extends string = string,\n> = Action<T> & {\n name: Exclude<N, \"*\">;\n /**\n * @deprecated Use `available` instead.\n */\n disabled?: boolean;\n available?: FrontendActionAvailability;\n pairedAction?: string;\n followUp?: boolean;\n} & (\n | {\n render?:\n | string\n | (T extends []\n ? (\n props: ActionRenderPropsNoArgs<T>,\n ) => string | React.ReactElement\n : (props: ActionRenderProps<T>) => string | React.ReactElement);\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: never;\n renderAndWaitForResponse?: never;\n }\n | {\n render?: never;\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n renderAndWaitForResponse?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n handler?: never;\n }\n );\n\nexport type CatchAllFrontendAction = {\n name: \"*\";\n render: (props: CatchAllActionRenderProps<any>) => React.ReactElement;\n};\n\nexport type RenderFunctionStatus = ActionRenderProps<any>[\"status\"];\n\nexport function processActionsForRuntimeRequest(\n actions: FrontendAction<any>[],\n) {\n const filteredActions = actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled &&\n action.disabled !== true &&\n action.name !== \"*\" &&\n action.available != \"frontend\" &&\n !action.pairedAction,\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined =\n ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(\n actionParametersToJsonSchema(action.parameters || []),\n ),\n available,\n };\n });\n return filteredActions;\n}\n","/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/v1/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/v1/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/examples/v1/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport {\n FrontendAction,\n processActionsForRuntimeRequest,\n} from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n private forwardedParameters?: ForwardedParametersInput;\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n this.forwardedParameters = config.forwardedParameters;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions\n ? Object.assign({}, context.actions)\n : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString =\n (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString(\n [],\n defaultCopilotContextCategories,\n );\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(\n filterAgentStateMessages(messages),\n ),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n toolChoice: \"required\",\n ...(this.forwardedParameters ?? {}),\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(\n contextString: string,\n instructions: string,\n): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n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DAA0C;AAC9C,gBACE,mFACG,MAAM,KAAK,wBAAwB,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,YAAY;IACpE,MAAM,YAAY,OAAO;AACzB,WAAO,2CAAC,aAAoB,QAAQ,OAAO,UAApB,IAA8B;KACrD,GACD;KAEJ,CAAC,wBAAwB,CAAC;EAE7B,MAAM,gDACG;GACL;GACA;GACA;GACA;GACA;GACA,sBAAsB;GACtB,wBAAwB;GACxB;GACA;GACA;GACA;GACA;GACA;GACA;GACkB;GAClB;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,cAAc,MAAM;GACpB,cAAc;GACd,iBAAiB;GACjB;GACA,eAAe;GACf;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,SAAS;GACT;GACA;GACA;GACD,GACD;GACE;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,MAAM;GACN;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CACF;AAED,SACE,2CAAC;GAGC,0BAAS,MAAM,8DAAS;GACd;aAEV,4CAAC,eAAe;IAAS,OAAO;;KAC9B,2CAAC,qBAAmB;KACpB,2CAAC,0BAAwB;KACzB,4CAAC,0CACC,2CAAC,iCACC,4CAAC,8BACC,2CAACC,cAAM,sBAAyB,oBAAZ,WAA8C,EAClE,2CAAC,+BAA8B,UAAY,IAC3B,GACE,EACrB,eAAe,kBACd,2CAAC;MACC,UAAU,YAAY;MACtB,SAAS,YAAY;MACrB,eAAe,eAAe,KAAK;MACnC,SAAS,gBAAgB,YAAY;OACrC,IAEwB;;KACN;IACO;;CAIvC,MAAa,kCAAkC,CAAC,SAAS;CA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