@copilotkit/react-core 1.50.0 → 1.50.1-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/{chunk-CO6V4G7P.mjs → chunk-4YZA2BZC.mjs} +4 -4
- package/dist/{chunk-U2ZRVVKT.mjs → chunk-BUSWSDYO.mjs} +2 -2
- package/dist/{chunk-T2VBHAAP.mjs → chunk-CDUIA2WM.mjs} +11 -3
- package/dist/chunk-CDUIA2WM.mjs.map +1 -0
- package/dist/{chunk-4HRUQH6U.mjs → chunk-E7SE25ZU.mjs} +2 -2
- package/dist/{chunk-EG56H77V.mjs → chunk-GPEJNVE5.mjs} +2 -2
- package/dist/{chunk-HQTDDA6V.mjs → chunk-LCZZ7YGZ.mjs} +2 -2
- package/dist/components/copilot-provider/copilotkit.mjs +3 -3
- package/dist/components/copilot-provider/index.mjs +3 -3
- package/dist/components/index.mjs +3 -3
- package/dist/hooks/index.js +9 -1
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +4 -4
- package/dist/hooks/use-copilot-action.js +9 -1
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -2
- package/dist/hooks/use-copilot-authenticated-action.js +9 -1
- package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
- package/dist/hooks/use-copilot-authenticated-action.mjs +3 -3
- package/dist/hooks/use-default-tool.js +9 -1
- package/dist/hooks/use-default-tool.js.map +1 -1
- package/dist/hooks/use-default-tool.mjs +3 -3
- package/dist/hooks/use-frontend-tool.js +9 -1
- package/dist/hooks/use-frontend-tool.js.map +1 -1
- package/dist/hooks/use-frontend-tool.mjs +1 -1
- package/dist/index.js +9 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +9 -9
- package/dist/lib/copilot-task.mjs +4 -4
- package/dist/lib/index.mjs +4 -4
- package/dist/types/index.mjs +1 -1
- package/package.json +3 -3
- package/src/hooks/use-frontend-tool.ts +13 -2
- package/dist/chunk-T2VBHAAP.mjs.map +0 -1
- /package/dist/{chunk-CO6V4G7P.mjs.map → chunk-4YZA2BZC.mjs.map} +0 -0
- /package/dist/{chunk-U2ZRVVKT.mjs.map → chunk-BUSWSDYO.mjs.map} +0 -0
- /package/dist/{chunk-4HRUQH6U.mjs.map → chunk-E7SE25ZU.mjs.map} +0 -0
- /package/dist/{chunk-EG56H77V.mjs.map → chunk-GPEJNVE5.mjs.map} +0 -0
- /package/dist/{chunk-HQTDDA6V.mjs.map → chunk-LCZZ7YGZ.mjs.map} +0 -0
package/dist/hooks/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/index.ts","../../src/hooks/use-copilot-chat_internal.ts","../../src/context/copilot-context.tsx","../../src/components/error-boundary/error-utils.tsx","../../src/components/toast/toast-provider.tsx","../../src/components/toast/exclamation-mark-icon.tsx","../../src/context/coagent-state-renders-context.tsx","../../src/hooks/use-langgraph-interrupt-render.ts","../../src/hooks/use-agent-nodename.ts","../../src/hooks/use-lazy-tool-renderer.tsx","../../src/hooks/use-coagent-state-render-bridge.tsx","../../src/hooks/use-copilot-chat.ts","../../src/hooks/use-copilot-chat-headless_c.ts","../../src/hooks/use-copilot-action.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-coagent-state-render.ts","../../src/hooks/use-make-copilot-document-readable.ts","../../src/hooks/use-copilot-readable.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"],"sourcesContent":["export { useCopilotChat } from \"./use-copilot-chat\";\nexport type { UseCopilotChatReturn } from \"./use-copilot-chat\";\nexport type { UseCopilotChatOptions } from \"./use-copilot-chat_internal\";\nexport {\n type UseCopilotChatReturn_c,\n type UseCopilotChatOptions_c,\n useCopilotChatHeadless_c,\n} from \"./use-copilot-chat-headless_c\";\nexport { useCopilotChatInternal, type ChatSuggestions } from \"./use-copilot-chat_internal\";\nexport { useCopilotAction } from \"./use-copilot-action\";\nexport { useCoAgentStateRender } from \"./use-coagent-state-render\";\nexport { useMakeCopilotDocumentReadable } from \"./use-make-copilot-document-readable\";\nexport { useCopilotReadable } from \"./use-copilot-readable\";\nexport { useCoAgent, type HintFunction } from \"./use-coagent\";\nexport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nexport { useCopilotAuthenticatedAction_c } from \"./use-copilot-authenticated-action\";\nexport { useLangGraphInterrupt } from \"./use-langgraph-interrupt\";\nexport { useLangGraphInterruptRender } from \"./use-langgraph-interrupt-render\";\nexport { useCopilotAdditionalInstructions } from \"./use-copilot-additional-instructions\";\nexport type { Tree, TreeNode } from \"./use-tree\";\nexport { useFrontendTool } from \"./use-frontend-tool\";\nexport { useHumanInTheLoop } from \"./use-human-in-the-loop\";\nexport { useRenderToolCall } from \"./use-render-tool-call\";\nexport { useDefaultTool } from \"./use-default-tool\";\nexport { useLazyToolRenderer } from \"./use-lazy-tool-renderer\";\nexport {\n useCopilotChatSuggestions,\n type UseCopilotChatSuggestionsConfiguration,\n} from \"./use-copilot-chat-suggestions\";\n","import { useRef, useEffect, useCallback, useMemo, useState, createElement } 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 { gqlToAGUI, Message as DeprecatedGqlMessage } from \"@copilotkit/runtime-client-gql\";\nimport { useLangGraphInterruptRender } from \"./use-langgraph-interrupt-render\";\nimport {\n useAgent,\n useCopilotChatConfiguration,\n useCopilotKit,\n useRenderCustomMessages,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport { Suggestion } from \"@copilotkitnext/core\";\nimport { useLazyToolRenderer } from \"./use-lazy-tool-renderer\";\nimport { AbstractAgent, AGUIConnectNotImplementedError } 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 = \"auto\" | \"manual\" | 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 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\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: (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => 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: (message: Message, options?: AppendMessageOptions) => 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}: 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({ agentId: resolvedAgentId });\n\n useEffect(() => {\n const connect = async (agent: AbstractAgent) => {\n setAgentAvailable(false);\n try {\n await copilotkit.connectAgent({ agent });\n setAgentAvailable(true);\n } catch (error) {\n if (error instanceof AGUIConnectNotImplementedError) {\n // connect not implemented, ignore\n } else {\n throw error;\n }\n }\n };\n if (agent && existingConfig?.threadId && agent.threadId !== existingConfig.threadId) {\n agent.threadId = existingConfig.threadId;\n connect(agent);\n }\n return () => {};\n }, [existingConfig?.threadId, agent, copilotkit, resolvedAgentId]);\n\n const interrupt = useLangGraphInterruptRender(agent);\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 const messages = agent?.messages ?? [];\n // TODO: get isLoading\n const isLoading = false;\n if (isLoading || messages.length === 0) {\n return;\n }\n\n const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);\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(`Regenerate cannot be performed on ${reloadMessageRole} role`);\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(0, indexOfLastUserMessageBeforeRegenerate + 1);\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 copilotkit.runAgent({ agent });\n }\n return;\n },\n [agent?.setMessages, copilotkit?.runAgent],\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 agent?.addMessage(message);\n if (followUp) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\n }\n }\n },\n [agent, copilotkit, resolvedAgentId],\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 (messages.every((message) => message instanceof DeprecatedGqlMessage)) {\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 return await latestReload.current(messageId);\n },\n [latestReload],\n );\n\n const latestStopFunc = useCallback(() => {\n return agent?.abortRun?.();\n }, [agent?.abortRun]);\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 const customRender = renderCustomMessage?.({\n message,\n position: \"before\",\n });\n if (customRender) {\n return customRender;\n }\n return legacyCustomMessageRenderer?.({ message, position: \"before\" });\n }\n : null;\n\n if (bridgeRenderer) {\n return { ...message, generativeUI: bridgeRenderer };\n }\n return message;\n });\n\n const hasAssistantMessages = processedMessages.some((msg) => msg.role === \"assistant\");\n\n // TODO: what is this?\n // if (legacyCustomMessageRenderer && !hasAssistantMessages) {\n // const placeholderId = `coagent-state-render-${resolvedAgentId}`;\n // const placeholderMessage: Message = {\n // id: placeholderId,\n // role: \"assistant\",\n // content: \"\",\n // name: \"coagent-state-render\",\n // };\n // processedMessages = [\n // ...processedMessages,\n // {\n // ...placeholderMessage,\n // generativeUI: () =>\n // legacyCustomMessageRenderer({\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 ]);\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 () => 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 existingRunId = 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","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 { CoAgentStateRender, CoAgentStateRenderProps } 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<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: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => 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: { [key: string]: CopilotChatSuggestionConfiguration };\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<React.SetStateAction<Record<string, CoagentState>>>;\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<React.SetStateAction<Record<ActionName, AuthState>>>;\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: (threadId: string, eventId: string, response: string) => 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: (handler: Record<string, CopilotErrorHandler>) => 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(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\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 = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\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 ? (error.extensions?.originalError as undefined | OriginalError) : {};\n const message = originalError?.message ?? error.message;\n const code = \"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\" }}>{code}</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 { 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>(null);\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)) 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(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\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(/'message':\\s*'([^']+)'/);\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={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\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 {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","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, {\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 locked?: boolean;\n}\n\ntype ClaimsRef = Record<string, StateRenderClaim>;\n\nexport interface CoAgentStateRendersContextValue {\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n claimsRef: RefObject<ClaimsRef>;\n}\n\nconst CoAgentStateRendersContext = createContext<CoAgentStateRendersContextValue | undefined>(\n undefined,\n);\n\nexport function CoAgentStateRendersProvider({ children }: { children: ReactNode }) {\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => ({\n ...prevPoints,\n [id]: stateRender,\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(\"useCoAgentStateRenders must be used within CoAgentStateRendersProvider\");\n }\n return context;\n}\n\nexport { CoAgentStateRendersContext };\n","import { useCopilotContext } from \"../context\";\nimport React, { useCallback, useEffect, useMemo } from \"react\";\nimport type { AbstractAgent, AgentSubscriber } from \"@ag-ui/client\";\nimport { MetaEventName } from \"@copilotkit/runtime-client-gql\";\nimport { dataToUUID, parseJson } from \"@copilotkit/shared\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\nimport { useCopilotChatConfiguration } from \"@copilotkitnext/react\";\n\ntype InterruptProps = {\n event: any;\n result: any;\n render: (props: {\n event: any;\n result: any;\n resolve: (response: string) => void;\n }) => string | React.ReactElement;\n resolve: (response: string) => void;\n};\n\nconst InterruptRenderer: React.FC<InterruptProps> = ({ event, result, render, resolve }) => {\n return render({ event, result, resolve });\n};\n\nexport function useLangGraphInterruptRender(\n agent: AbstractAgent,\n): string | React.ReactElement | null {\n const {\n interruptActions,\n agentSession,\n threadId,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n } = useCopilotContext();\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const nodeName = useAgentNodeName(resolvedAgentId);\n\n useEffect(() => {\n if (!agent) return;\n let localInterrupt: any = null;\n const subscriber: AgentSubscriber = {\n onCustomEvent: ({ event }) => {\n if (event.name === \"on_interrupt\") {\n const eventData = {\n name: MetaEventName.LangGraphInterruptEvent,\n type: event.type,\n value: parseJson(event.value, event.value),\n };\n const eventId = dataToUUID(eventData, \"interruptEvents\");\n localInterrupt = {\n eventId,\n threadId,\n event: eventData,\n };\n }\n },\n onRunStartedEvent: () => {\n localInterrupt = null;\n },\n onRunFinalized: () => {\n if (localInterrupt) {\n addInterruptEvent(localInterrupt);\n localInterrupt = null;\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 }, [agent, threadId]);\n\n const handleResolve = useCallback(\n (eventId: string, response?: string) => {\n agent?.runAgent({\n forwardedProps: {\n command: {\n resume: response,\n },\n },\n });\n resolveInterruptEvent(threadId, eventId, response ?? \"\");\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [agent, threadId],\n );\n\n return useMemo(() => {\n // Get the queue for this thread and find the first unresponded event\n const eventQueue = interruptEventQueue[threadId] || [];\n const currentQueuedEvent = eventQueue.find((qe) => !qe.event.response);\n\n if (!currentQueuedEvent || !agentSession) return null;\n\n // Find the first matching action from all registered actions\n const allActions = Object.values(interruptActions);\n const matchingAction = allActions.find((action) => {\n if (!action.enabled) return true; // No filter = match all\n return action.enabled({\n eventValue: currentQueuedEvent.event.value,\n agentMetadata: {\n ...agentSession,\n nodeName,\n },\n });\n });\n\n if (!matchingAction) return null;\n\n const { render, handler } = matchingAction;\n\n const resolveInterrupt = (response: string) => {\n handleResolve(currentQueuedEvent.eventId, response);\n };\n\n let result = null;\n if (handler) {\n result = handler({\n event: currentQueuedEvent.event,\n resolve: resolveInterrupt,\n });\n }\n\n if (!render) return null;\n\n return React.createElement(InterruptRenderer, {\n event: currentQueuedEvent.event,\n result,\n render,\n resolve: resolveInterrupt,\n });\n }, [interruptActions, interruptEventQueue, threadId, agentSession, handleResolve]);\n}\n","import { useEffect, useRef } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgent } from \"@copilotkitnext/react\";\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","import { useRenderToolCall } from \"@copilotkitnext/react\";\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 { ReactCustomMessageRendererPosition, useAgent } from \"@copilotkitnext/react\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useCoAgentStateRenders } from \"../context\";\nimport { dataToUUID, parseJson } from \"@copilotkit/shared\";\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\nfunction 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 JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);\n}\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(agentId: string, props: CoAgentStateRenderBridgeProps) {\n const { stateSnapshot, messageIndexInRun, message } = props;\n const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();\n const { agent } = useAgent({ agentId });\n const [nodeName, setNodeName] = useState<string | undefined>(undefined);\n\n const runId = props.runId ?? message.runId;\n const effectiveRunId = runId || \"pending\";\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\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(([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 ? stateRender.nodeName === nodeName : true;\n return matchingAgentName && matchesNodeContext;\n });\n },\n [coAgentStateRenders, nodeName, agentId],\n );\n\n // Message ID-based claim system - A state render can only be claimed by one message ID\n const handleRenderRequest = ({\n stateRenderId,\n messageId,\n runId,\n stateSnapshot: renderSnapshot,\n }: {\n stateRenderId: string;\n messageId: string;\n runId?: string;\n stateSnapshot?: any;\n }): boolean => {\n // Check if this message has already claimed this state render\n if (claimsRef.current[messageId]) {\n const canRender = claimsRef.current[messageId].stateRenderId === stateRenderId;\n\n // Update runId if it doesn't exist\n if (\n canRender &&\n runId &&\n (!claimsRef.current[messageId].runId || claimsRef.current[messageId].runId === \"pending\")\n ) {\n claimsRef.current[messageId].runId = runId;\n }\n\n return canRender;\n }\n\n // Do not allow render if any other message has claimed this state render\n const renderClaimedByOtherMessage = Object.values(claimsRef.current).find(\n (c) =>\n c.stateRenderId === stateRenderId &&\n dataToUUID(getStateWithoutConstantKeys(c.stateSnapshot)) ===\n dataToUUID(getStateWithoutConstantKeys(renderSnapshot)),\n );\n if (renderClaimedByOtherMessage) {\n // If:\n // - state render already claimed\n // - snapshot exists in the claiming object and is different from current,\n if (\n renderSnapshot &&\n renderClaimedByOtherMessage.stateSnapshot &&\n !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, renderSnapshot)\n ) {\n claimsRef.current[messageId] = { stateRenderId, runId };\n return true;\n }\n return false;\n }\n\n // No existing claim anywhere yet – allow this message to claim even if we already know the runId.\n if (!runId) {\n return false;\n }\n\n claimsRef.current[messageId] = { stateRenderId, runId };\n return true;\n };\n\n return useMemo(() => {\n if (messageIndexInRun !== 0) {\n return null;\n }\n\n const [stateRenderId, stateRender] = getStateRender(message.id) ?? [];\n\n if (!stateRender || !stateRenderId) {\n return null;\n }\n\n // Is there any state we can use?\n const snapshot = stateSnapshot ? parseJson(stateSnapshot, stateSnapshot) : agent?.state;\n\n // Synchronously check/claim - returns true if this message can render\n const canRender = handleRenderRequest({\n stateRenderId,\n messageId: message.id,\n runId: effectiveRunId,\n stateSnapshot: snapshot,\n });\n if (!canRender) {\n return null;\n }\n\n // If we found state, and given that now there's a claim for the current message, let's save it in the claim\n if (snapshot && !claimsRef.current[message.id].locked) {\n if (stateSnapshot) {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n claimsRef.current[message.id].locked = true;\n } else {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n }\n }\n\n if (stateRender.handler) {\n stateRender.handler({\n state: stateSnapshot ? parseJson(stateSnapshot, stateSnapshot) : (agent?.state ?? {}),\n nodeName: nodeName ?? \"\",\n });\n }\n\n if (stateRender.render) {\n const status = agent?.isRunning ? \"inProgress\" : \"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 getStateRender,\n stateSnapshot,\n agent?.state,\n agent?.isRunning,\n nodeName,\n effectiveRunId,\n message.id,\n messageIndexInRun,\n ]);\n}\n\nexport function CoAgentStateRenderBridge(props: CoAgentStateRenderBridgeProps) {\n return useCoagentStateRenderBridge(props.agentId, props);\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/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(options: UseCopilotChatOptions = {}): 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(options: UseCopilotChatOptions_c = {}): 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 { UseCopilotChatOptions_c, UseCopilotChatReturn_c, MCPServerConfig };\n\nconst noKeyWarning = () => {\n styledConsole.logCopilotKitPlatformMessage();\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 { CatchAllFrontendAction, FrontendAction } from \"../types/frontend-action\";\nimport { useFrontendTool, UseFrontendToolArgs } from \"./use-frontend-tool\";\nimport { useRenderToolCall, UseRenderToolCallArgs } from \"./use-render-tool-call\";\nimport { useHumanInTheLoop, UseHumanInTheLoopArgs } 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","import React from \"react\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport { Parameter, getZodParameters, MappedParameterTypes } from \"@copilotkit/shared\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport {\n type ReactFrontendTool,\n useFrontendTool as useFrontendToolVNext,\n} from \"@copilotkitnext/react\";\n\ntype FrontendToolOptions<T extends Parameter[] | []> = ReactFrontendTool<MappedParameterTypes<T>>;\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 } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const normalizedRender: FrontendToolOptions<T>[\"render\"] | undefined = (() => {\n if (typeof render === \"undefined\") {\n return undefined;\n }\n\n if (typeof render === \"string\") {\n const staticRender = render;\n return (() =>\n React.createElement(\n React.Fragment,\n null,\n staticRender,\n )) as FrontendToolOptions<T>[\"render\"];\n }\n\n return ((args: FrontendToolRenderArgs<T>) => {\n const renderArgs = {\n ...args,\n result: typeof args.result === \"string\" ? parseJson(args.result, args.result) : args.result,\n } as ActionRenderProps<T>;\n\n const rendered = render(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 useFrontendToolVNext<MappedParameterTypes<T>>({\n name,\n description,\n parameters: zodParameters,\n handler: tool.handler,\n followUp,\n render: normalizedRender,\n });\n}\n","import {\n ActionRenderProps,\n ActionRenderPropsNoArgs,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types\";\nimport { Parameter, getZodParameters } from \"@copilotkit/shared\";\nimport React, { useEffect, useRef } from \"react\";\nimport { defineToolCallRenderer, useCopilotKit } from \"@copilotkitnext/react\";\nimport { parseJson } from \"@copilotkit/shared\";\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 ? parseJson(args.result, args.result) : 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 ? parseJson(args.result, args.result) : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n });\n\n // Remove any existing renderer with the same name\n const existingIndex = copilotkit.renderToolCalls.findIndex((r) => r.name === name);\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((r) => r.name === name);\n if (index !== -1) {\n copilotkit.renderToolCalls.splice(index, 1);\n }\n hasAddedRef.current = false;\n }\n };\n }, [tool, ...(dependencies ?? [])]);\n}\n","import { ActionRenderProps, ActionRenderPropsWait, FrontendAction } from \"../types\";\nimport {\n CopilotKitError,\n CopilotKitErrorCode,\n MappedParameterTypes,\n Parameter,\n getZodParameters,\n parseJson,\n} from \"@copilotkit/shared\";\nimport { useHumanInTheLoop as useHumanInTheLoopVNext } from \"@copilotkitnext/react\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport React, { ComponentType, FunctionComponent, useEffect, useRef } from \"react\";\n\ntype HumanInTheLoopOptions = Parameters<typeof useHumanInTheLoopVNext>[0];\ntype HumanInTheLoopRender = HumanInTheLoopOptions[\"render\"];\ntype HumanInTheLoopRenderArgs = HumanInTheLoopRender extends (props: infer P) => any ? P : 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 ? parseJson(args.result, args.result) : 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) ?? null) as HumanInTheLoopOptions[\"render\"],\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 { setCoAgentStateRender, removeCoAgentStateRender, coAgentStateRenders } =\n useCoAgentStateRenders();\n const idRef = useRef<string>(randomId());\n const { setBannerError, addToast } = useToast();\n\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === action.name)) {\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) => ({ name: a.name, id: a.id })),\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(([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 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 \"@copilotkitnext/react\";\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","/**\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 \"@copilotkitnext/react\";\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<T> 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>(options: UseCoagentOptions<T>): 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 () => (isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined),\n [isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined],\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 = (options: CopilotRuntimeClientHookOptions) => {\n const { setBannerError } = useToast();\n const { showDevConsole, onError, ...runtimeOptions } = options;\n\n // Deduplication state for structured errors\n const lastStructuredErrorRef = useRef<{ message: string; timestamp: number } | 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: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: 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 = { message: errorMessage, timestamp: now };\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 (originalError?.stack?.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\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) => ({ ...prev, [action.name]: authState }));\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 { useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { LangGraphInterruptRender } from \"../types/interrupt-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { dataToUUID } from \"@copilotkit/shared\";\n\nexport function useLangGraphInterrupt<TEventValue = any>(\n action: Omit<LangGraphInterruptRender<TEventValue>, \"id\">,\n dependencies?: any[],\n) {\n const { setInterruptAction, removeInterruptAction, interruptActions, threadId } =\n useContext(CopilotContext);\n const { addToast } = useToast();\n\n const actionId = dataToUUID(action, \"lgAction\");\n\n useEffect(() => {\n if (!action) return;\n\n // if (!action.enabled) {\n // TODO: if there are any other actions registered, we need to warn the user that a current action without \"enabled\" might render for everything\n // addToast({\n // type: \"warning\",\n // message: \"An action is already registered for the interrupt event\",\n // });\n // return;\n // }\n\n setInterruptAction({ ...action, id: actionId });\n\n // Cleanup: remove action on unmount\n return () => {\n removeInterruptAction(actionId);\n };\n }, [setInterruptAction, removeInterruptAction, threadId, actionId, ...(dependencies || [])]);\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 { instructions, available = \"enabled\" }: UseCopilotAdditionalInstructionsOptions,\n dependencies?: any[],\n) {\n const { setAdditionalInstructions } = useCopilotContext();\n\n useEffect(() => {\n if (available === \"disabled\") return;\n\n setAdditionalInstructions((prevInstructions) => [...(prevInstructions || []), instructions]);\n\n return () => {\n setAdditionalInstructions(\n (prevInstructions) =>\n prevInstructions?.filter((instruction) => instruction !== instructions) || [],\n );\n };\n }, [available, instructions, setAdditionalInstructions, ...(dependencies || [])]);\n}\n","import { useCopilotAction } from \"./use-copilot-action\";\nimport { CatchAllFrontendAction } from \"../types/frontend-action\";\n\nexport function useDefaultTool(tool: Omit<CatchAllFrontendAction, \"name\">, dependencies?: any[]) {\n // Use the existing useCopilotAction hook\n useCopilotAction({ ...tool, name: \"*\" } satisfies CatchAllFrontendAction, dependencies);\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 \"@copilotkitnext/react\";\nimport { useEffect } from \"react\";\nimport { StaticSuggestionsConfig, Suggestion } from \"@copilotkitnext/core\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> & Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<StaticSuggestionsConfig, \"suggestions\"> & {\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?: \"enabled\" | \"disabled\" | \"always\" | \"before-first-message\" | \"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) ?? \"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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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X,4BAAsB,QAAQ;AAAA,IAChC;AAAA,EACF,GAAG,CAAC,oBAAoB,uBAAuB,UAAU,UAAU,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAC7F;;;ACGA,IAAAC,iBAA0B;AA4BnB,SAAS,iCACd,EAAE,cAAc,YAAY,UAAU,GACtC,cACA;AACA,QAAM,EAAE,0BAA0B,IAAI,kBAAkB;AAExD,gCAAU,MAAM;AACd,QAAI,cAAc;AAAY;AAE9B,8BAA0B,CAAC,qBAAqB,CAAC,GAAI,oBAAoB,CAAC,GAAI,YAAY,CAAC;AAE3F,WAAO,MAAM;AACX;AAAA,QACE,CAAC,sBACC,qDAAkB,OAAO,CAAC,gBAAgB,gBAAgB,kBAAiB,CAAC;AAAA,MAChF;AAAA,IACF;AAAA,EACF,GAAG,CAAC,WAAW,cAAc,2BAA2B,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAClF;;;ACjFO,SAAS,eAAe,MAA4C,cAAsB;AAE/F,mBAAiB,iCAAK,OAAL,EAAW,MAAM,IAAI,IAAoC,YAAY;AACxF;;;ACsDA,IAAAC,iBAKO;AA0CA,SAAS,0BACd,QACA,eAAsB,CAAC,GACvB;AA9GF;AA+GE,QAAM,qBAAiB,4CAA4B;AACnD,QAAM,mBAAkB,sDAAgB,YAAhB,YAA2B;AAEnD,QAAM,aACH,YAAO,cAAc,YAAY,WAAW,OAAO,cAAnD,YAAiE;AAEpE,QAAM,wBAAwB,iCACzB,SADyB;AAAA,IAE5B;AAAA,IACA,iBAAiB;AAAA;AAAA,EACnB;AACA,8CAAwB,uBAAuB,YAAY;AAC7D;","names":["useRenderToolCall","import_react","React","import_react","import_react","import_jsx_runtime","import_jsx_runtime","ReactMarkdown","import_runtime_client_gql","import_react","import_jsx_runtime","import_react","import_shared","import_react","import_react","React","import_react","import_react","import_react","import_shared","runId","_a","agent","_a","_b","DeprecatedGqlMessage","suggestions","import_react","import_shared","import_react","import_react","import_shared","React","useFrontendToolVNext","import_shared","import_react","useRenderToolCall","import_shared","import_react","React","useHumanInTheLoopVNext","_a","useRenderToolCall","import_react","import_shared","import_react","import_react","import_react","import_runtime_client_gql","import_react","import_shared","error","_a","import_react","import_react","React","import_react","import_shared","import_react","import_react"]}
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/index.ts","../../src/hooks/use-copilot-chat_internal.ts","../../src/context/copilot-context.tsx","../../src/components/error-boundary/error-utils.tsx","../../src/components/toast/toast-provider.tsx","../../src/components/toast/exclamation-mark-icon.tsx","../../src/context/coagent-state-renders-context.tsx","../../src/hooks/use-langgraph-interrupt-render.ts","../../src/hooks/use-agent-nodename.ts","../../src/hooks/use-lazy-tool-renderer.tsx","../../src/hooks/use-coagent-state-render-bridge.tsx","../../src/hooks/use-copilot-chat.ts","../../src/hooks/use-copilot-chat-headless_c.ts","../../src/hooks/use-copilot-action.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-coagent-state-render.ts","../../src/hooks/use-make-copilot-document-readable.ts","../../src/hooks/use-copilot-readable.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"],"sourcesContent":["export { useCopilotChat } from \"./use-copilot-chat\";\nexport type { UseCopilotChatReturn } from \"./use-copilot-chat\";\nexport type { UseCopilotChatOptions } from \"./use-copilot-chat_internal\";\nexport {\n type UseCopilotChatReturn_c,\n type UseCopilotChatOptions_c,\n useCopilotChatHeadless_c,\n} from \"./use-copilot-chat-headless_c\";\nexport { useCopilotChatInternal, type ChatSuggestions } from \"./use-copilot-chat_internal\";\nexport { useCopilotAction } from \"./use-copilot-action\";\nexport { useCoAgentStateRender } from \"./use-coagent-state-render\";\nexport { useMakeCopilotDocumentReadable } from \"./use-make-copilot-document-readable\";\nexport { useCopilotReadable } from \"./use-copilot-readable\";\nexport { useCoAgent, type HintFunction } from \"./use-coagent\";\nexport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nexport { useCopilotAuthenticatedAction_c } from \"./use-copilot-authenticated-action\";\nexport { useLangGraphInterrupt } from \"./use-langgraph-interrupt\";\nexport { useLangGraphInterruptRender } from \"./use-langgraph-interrupt-render\";\nexport { useCopilotAdditionalInstructions } from \"./use-copilot-additional-instructions\";\nexport type { Tree, TreeNode } from \"./use-tree\";\nexport { useFrontendTool } from \"./use-frontend-tool\";\nexport { useHumanInTheLoop } from \"./use-human-in-the-loop\";\nexport { useRenderToolCall } from \"./use-render-tool-call\";\nexport { useDefaultTool } from \"./use-default-tool\";\nexport { useLazyToolRenderer } from \"./use-lazy-tool-renderer\";\nexport {\n useCopilotChatSuggestions,\n type UseCopilotChatSuggestionsConfiguration,\n} from \"./use-copilot-chat-suggestions\";\n","import { useRef, useEffect, useCallback, useMemo, useState, createElement } 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 { gqlToAGUI, Message as DeprecatedGqlMessage } from \"@copilotkit/runtime-client-gql\";\nimport { useLangGraphInterruptRender } from \"./use-langgraph-interrupt-render\";\nimport {\n useAgent,\n useCopilotChatConfiguration,\n useCopilotKit,\n useRenderCustomMessages,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport { Suggestion } from \"@copilotkitnext/core\";\nimport { useLazyToolRenderer } from \"./use-lazy-tool-renderer\";\nimport { AbstractAgent, AGUIConnectNotImplementedError } 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 = \"auto\" | \"manual\" | 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 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\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: (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => 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: (message: Message, options?: AppendMessageOptions) => 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}: 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({ agentId: resolvedAgentId });\n\n useEffect(() => {\n const connect = async (agent: AbstractAgent) => {\n setAgentAvailable(false);\n try {\n await copilotkit.connectAgent({ agent });\n setAgentAvailable(true);\n } catch (error) {\n if (error instanceof AGUIConnectNotImplementedError) {\n // connect not implemented, ignore\n } else {\n throw error;\n }\n }\n };\n if (agent && existingConfig?.threadId && agent.threadId !== existingConfig.threadId) {\n agent.threadId = existingConfig.threadId;\n connect(agent);\n }\n return () => {};\n }, [existingConfig?.threadId, agent, copilotkit, resolvedAgentId]);\n\n const interrupt = useLangGraphInterruptRender(agent);\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 const messages = agent?.messages ?? [];\n // TODO: get isLoading\n const isLoading = false;\n if (isLoading || messages.length === 0) {\n return;\n }\n\n const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);\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(`Regenerate cannot be performed on ${reloadMessageRole} role`);\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(0, indexOfLastUserMessageBeforeRegenerate + 1);\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 copilotkit.runAgent({ agent });\n }\n return;\n },\n [agent?.setMessages, copilotkit?.runAgent],\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 agent?.addMessage(message);\n if (followUp) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\n }\n }\n },\n [agent, copilotkit, resolvedAgentId],\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 (messages.every((message) => message instanceof DeprecatedGqlMessage)) {\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 return await latestReload.current(messageId);\n },\n [latestReload],\n );\n\n const latestStopFunc = useCallback(() => {\n return agent?.abortRun?.();\n }, [agent?.abortRun]);\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 const customRender = renderCustomMessage?.({\n message,\n position: \"before\",\n });\n if (customRender) {\n return customRender;\n }\n return legacyCustomMessageRenderer?.({ message, position: \"before\" });\n }\n : null;\n\n if (bridgeRenderer) {\n return { ...message, generativeUI: bridgeRenderer };\n }\n return message;\n });\n\n const hasAssistantMessages = processedMessages.some((msg) => msg.role === \"assistant\");\n\n // TODO: what is this?\n // if (legacyCustomMessageRenderer && !hasAssistantMessages) {\n // const placeholderId = `coagent-state-render-${resolvedAgentId}`;\n // const placeholderMessage: Message = {\n // id: placeholderId,\n // role: \"assistant\",\n // content: \"\",\n // name: \"coagent-state-render\",\n // };\n // processedMessages = [\n // ...processedMessages,\n // {\n // ...placeholderMessage,\n // generativeUI: () =>\n // legacyCustomMessageRenderer({\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 ]);\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 () => 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 existingRunId = 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","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 { CoAgentStateRender, CoAgentStateRenderProps } 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<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: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => 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: { [key: string]: CopilotChatSuggestionConfiguration };\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<React.SetStateAction<Record<string, CoagentState>>>;\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<React.SetStateAction<Record<ActionName, AuthState>>>;\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: (threadId: string, eventId: string, response: string) => 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: (handler: Record<string, CopilotErrorHandler>) => 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(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\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 = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\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 ? (error.extensions?.originalError as undefined | OriginalError) : {};\n const message = originalError?.message ?? error.message;\n const code = \"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\" }}>{code}</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 { 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>(null);\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)) 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(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\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(/'message':\\s*'([^']+)'/);\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={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\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 {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","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, {\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 locked?: boolean;\n}\n\ntype ClaimsRef = Record<string, StateRenderClaim>;\n\nexport interface CoAgentStateRendersContextValue {\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n claimsRef: RefObject<ClaimsRef>;\n}\n\nconst CoAgentStateRendersContext = createContext<CoAgentStateRendersContextValue | undefined>(\n undefined,\n);\n\nexport function CoAgentStateRendersProvider({ children }: { children: ReactNode }) {\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => ({\n ...prevPoints,\n [id]: stateRender,\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(\"useCoAgentStateRenders must be used within CoAgentStateRendersProvider\");\n }\n return context;\n}\n\nexport { CoAgentStateRendersContext };\n","import { useCopilotContext } from \"../context\";\nimport React, { useCallback, useEffect, useMemo } from \"react\";\nimport type { AbstractAgent, AgentSubscriber } from \"@ag-ui/client\";\nimport { MetaEventName } from \"@copilotkit/runtime-client-gql\";\nimport { dataToUUID, parseJson } from \"@copilotkit/shared\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\nimport { useCopilotChatConfiguration } from \"@copilotkitnext/react\";\n\ntype InterruptProps = {\n event: any;\n result: any;\n render: (props: {\n event: any;\n result: any;\n resolve: (response: string) => void;\n }) => string | React.ReactElement;\n resolve: (response: string) => void;\n};\n\nconst InterruptRenderer: React.FC<InterruptProps> = ({ event, result, render, resolve }) => {\n return render({ event, result, resolve });\n};\n\nexport function useLangGraphInterruptRender(\n agent: AbstractAgent,\n): string | React.ReactElement | null {\n const {\n interruptActions,\n agentSession,\n threadId,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n } = useCopilotContext();\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const nodeName = useAgentNodeName(resolvedAgentId);\n\n useEffect(() => {\n if (!agent) return;\n let localInterrupt: any = null;\n const subscriber: AgentSubscriber = {\n onCustomEvent: ({ event }) => {\n if (event.name === \"on_interrupt\") {\n const eventData = {\n name: MetaEventName.LangGraphInterruptEvent,\n type: event.type,\n value: parseJson(event.value, event.value),\n };\n const eventId = dataToUUID(eventData, \"interruptEvents\");\n localInterrupt = {\n eventId,\n threadId,\n event: eventData,\n };\n }\n },\n onRunStartedEvent: () => {\n localInterrupt = null;\n },\n onRunFinalized: () => {\n if (localInterrupt) {\n addInterruptEvent(localInterrupt);\n localInterrupt = null;\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 }, [agent, threadId]);\n\n const handleResolve = useCallback(\n (eventId: string, response?: string) => {\n agent?.runAgent({\n forwardedProps: {\n command: {\n resume: response,\n },\n },\n });\n resolveInterruptEvent(threadId, eventId, response ?? \"\");\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [agent, threadId],\n );\n\n return useMemo(() => {\n // Get the queue for this thread and find the first unresponded event\n const eventQueue = interruptEventQueue[threadId] || [];\n const currentQueuedEvent = eventQueue.find((qe) => !qe.event.response);\n\n if (!currentQueuedEvent || !agentSession) return null;\n\n // Find the first matching action from all registered actions\n const allActions = Object.values(interruptActions);\n const matchingAction = allActions.find((action) => {\n if (!action.enabled) return true; // No filter = match all\n return action.enabled({\n eventValue: currentQueuedEvent.event.value,\n agentMetadata: {\n ...agentSession,\n nodeName,\n },\n });\n });\n\n if (!matchingAction) return null;\n\n const { render, handler } = matchingAction;\n\n const resolveInterrupt = (response: string) => {\n handleResolve(currentQueuedEvent.eventId, response);\n };\n\n let result = null;\n if (handler) {\n result = handler({\n event: currentQueuedEvent.event,\n resolve: resolveInterrupt,\n });\n }\n\n if (!render) return null;\n\n return React.createElement(InterruptRenderer, {\n event: currentQueuedEvent.event,\n result,\n render,\n resolve: resolveInterrupt,\n });\n }, [interruptActions, interruptEventQueue, threadId, agentSession, handleResolve]);\n}\n","import { useEffect, useRef } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgent } from \"@copilotkitnext/react\";\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","import { useRenderToolCall } from \"@copilotkitnext/react\";\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 { ReactCustomMessageRendererPosition, useAgent } from \"@copilotkitnext/react\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useCoAgentStateRenders } from \"../context\";\nimport { dataToUUID, parseJson } from \"@copilotkit/shared\";\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\nfunction 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 JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);\n}\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(agentId: string, props: CoAgentStateRenderBridgeProps) {\n const { stateSnapshot, messageIndexInRun, message } = props;\n const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();\n const { agent } = useAgent({ agentId });\n const [nodeName, setNodeName] = useState<string | undefined>(undefined);\n\n const runId = props.runId ?? message.runId;\n const effectiveRunId = runId || \"pending\";\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\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(([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 ? stateRender.nodeName === nodeName : true;\n return matchingAgentName && matchesNodeContext;\n });\n },\n [coAgentStateRenders, nodeName, agentId],\n );\n\n // Message ID-based claim system - A state render can only be claimed by one message ID\n const handleRenderRequest = ({\n stateRenderId,\n messageId,\n runId,\n stateSnapshot: renderSnapshot,\n }: {\n stateRenderId: string;\n messageId: string;\n runId?: string;\n stateSnapshot?: any;\n }): boolean => {\n // Check if this message has already claimed this state render\n if (claimsRef.current[messageId]) {\n const canRender = claimsRef.current[messageId].stateRenderId === stateRenderId;\n\n // Update runId if it doesn't exist\n if (\n canRender &&\n runId &&\n (!claimsRef.current[messageId].runId || claimsRef.current[messageId].runId === \"pending\")\n ) {\n claimsRef.current[messageId].runId = runId;\n }\n\n return canRender;\n }\n\n // Do not allow render if any other message has claimed this state render\n const renderClaimedByOtherMessage = Object.values(claimsRef.current).find(\n (c) =>\n c.stateRenderId === stateRenderId &&\n dataToUUID(getStateWithoutConstantKeys(c.stateSnapshot)) ===\n dataToUUID(getStateWithoutConstantKeys(renderSnapshot)),\n );\n if (renderClaimedByOtherMessage) {\n // If:\n // - state render already claimed\n // - snapshot exists in the claiming object and is different from current,\n if (\n renderSnapshot &&\n renderClaimedByOtherMessage.stateSnapshot &&\n !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, renderSnapshot)\n ) {\n claimsRef.current[messageId] = { stateRenderId, runId };\n return true;\n }\n return false;\n }\n\n // No existing claim anywhere yet – allow this message to claim even if we already know the runId.\n if (!runId) {\n return false;\n }\n\n claimsRef.current[messageId] = { stateRenderId, runId };\n return true;\n };\n\n return useMemo(() => {\n if (messageIndexInRun !== 0) {\n return null;\n }\n\n const [stateRenderId, stateRender] = getStateRender(message.id) ?? [];\n\n if (!stateRender || !stateRenderId) {\n return null;\n }\n\n // Is there any state we can use?\n const snapshot = stateSnapshot ? parseJson(stateSnapshot, stateSnapshot) : agent?.state;\n\n // Synchronously check/claim - returns true if this message can render\n const canRender = handleRenderRequest({\n stateRenderId,\n messageId: message.id,\n runId: effectiveRunId,\n stateSnapshot: snapshot,\n });\n if (!canRender) {\n return null;\n }\n\n // If we found state, and given that now there's a claim for the current message, let's save it in the claim\n if (snapshot && !claimsRef.current[message.id].locked) {\n if (stateSnapshot) {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n claimsRef.current[message.id].locked = true;\n } else {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n }\n }\n\n if (stateRender.handler) {\n stateRender.handler({\n state: stateSnapshot ? parseJson(stateSnapshot, stateSnapshot) : (agent?.state ?? {}),\n nodeName: nodeName ?? \"\",\n });\n }\n\n if (stateRender.render) {\n const status = agent?.isRunning ? \"inProgress\" : \"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 getStateRender,\n stateSnapshot,\n agent?.state,\n agent?.isRunning,\n nodeName,\n effectiveRunId,\n message.id,\n messageIndexInRun,\n ]);\n}\n\nexport function CoAgentStateRenderBridge(props: CoAgentStateRenderBridgeProps) {\n return useCoagentStateRenderBridge(props.agentId, props);\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/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(options: UseCopilotChatOptions = {}): 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(options: UseCopilotChatOptions_c = {}): 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 { UseCopilotChatOptions_c, UseCopilotChatReturn_c, MCPServerConfig };\n\nconst noKeyWarning = () => {\n styledConsole.logCopilotKitPlatformMessage();\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 { CatchAllFrontendAction, FrontendAction } from \"../types/frontend-action\";\nimport { useFrontendTool, UseFrontendToolArgs } from \"./use-frontend-tool\";\nimport { useRenderToolCall, UseRenderToolCallArgs } from \"./use-render-tool-call\";\nimport { useHumanInTheLoop, UseHumanInTheLoopArgs } 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","import React, { useEffect, useRef } from \"react\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport { Parameter, getZodParameters, MappedParameterTypes } from \"@copilotkit/shared\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport {\n type ReactFrontendTool,\n useFrontendTool as useFrontendToolVNext,\n} from \"@copilotkitnext/react\";\n\ntype FrontendToolOptions<T extends Parameter[] | []> = ReactFrontendTool<MappedParameterTypes<T>>;\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 } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const normalizedRender: FrontendToolOptions<T>[\"render\"] | undefined = (() => {\n if (typeof render === \"undefined\") {\n return undefined;\n }\n\n if (typeof render === \"string\") {\n const staticRender = render;\n return (() =>\n React.createElement(\n React.Fragment,\n null,\n staticRender,\n )) as FrontendToolOptions<T>[\"render\"];\n }\n\n return ((args: FrontendToolRenderArgs<T>) => {\n const renderArgs = {\n ...args,\n result: typeof args.result === \"string\" ? parseJson(args.result, args.result) : args.result,\n } as ActionRenderProps<T>;\n\n const rendered = render(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 });\n}\n","import {\n ActionRenderProps,\n ActionRenderPropsNoArgs,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types\";\nimport { Parameter, getZodParameters } from \"@copilotkit/shared\";\nimport React, { useEffect, useRef } from \"react\";\nimport { defineToolCallRenderer, useCopilotKit } from \"@copilotkitnext/react\";\nimport { parseJson } from \"@copilotkit/shared\";\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 ? parseJson(args.result, args.result) : 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 ? parseJson(args.result, args.result) : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n });\n\n // Remove any existing renderer with the same name\n const existingIndex = copilotkit.renderToolCalls.findIndex((r) => r.name === name);\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((r) => r.name === name);\n if (index !== -1) {\n copilotkit.renderToolCalls.splice(index, 1);\n }\n hasAddedRef.current = false;\n }\n };\n }, [tool, ...(dependencies ?? [])]);\n}\n","import { ActionRenderProps, ActionRenderPropsWait, FrontendAction } from \"../types\";\nimport {\n CopilotKitError,\n CopilotKitErrorCode,\n MappedParameterTypes,\n Parameter,\n getZodParameters,\n parseJson,\n} from \"@copilotkit/shared\";\nimport { useHumanInTheLoop as useHumanInTheLoopVNext } from \"@copilotkitnext/react\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport React, { ComponentType, FunctionComponent, useEffect, useRef } from \"react\";\n\ntype HumanInTheLoopOptions = Parameters<typeof useHumanInTheLoopVNext>[0];\ntype HumanInTheLoopRender = HumanInTheLoopOptions[\"render\"];\ntype HumanInTheLoopRenderArgs = HumanInTheLoopRender extends (props: infer P) => any ? P : 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 ? parseJson(args.result, args.result) : 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) ?? null) as HumanInTheLoopOptions[\"render\"],\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 { setCoAgentStateRender, removeCoAgentStateRender, coAgentStateRenders } =\n useCoAgentStateRenders();\n const idRef = useRef<string>(randomId());\n const { setBannerError, addToast } = useToast();\n\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === action.name)) {\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) => ({ name: a.name, id: a.id })),\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(([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 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 \"@copilotkitnext/react\";\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","/**\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 \"@copilotkitnext/react\";\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<T> 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>(options: UseCoagentOptions<T>): 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 () => (isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined),\n [isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined],\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 = (options: CopilotRuntimeClientHookOptions) => {\n const { setBannerError } = useToast();\n const { showDevConsole, onError, ...runtimeOptions } = options;\n\n // Deduplication state for structured errors\n const lastStructuredErrorRef = useRef<{ message: string; timestamp: number } | 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: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: 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 = { message: errorMessage, timestamp: now };\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 (originalError?.stack?.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\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) => ({ ...prev, [action.name]: authState }));\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 { useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { LangGraphInterruptRender } from \"../types/interrupt-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { dataToUUID } from \"@copilotkit/shared\";\n\nexport function useLangGraphInterrupt<TEventValue = any>(\n action: Omit<LangGraphInterruptRender<TEventValue>, \"id\">,\n dependencies?: any[],\n) {\n const { setInterruptAction, removeInterruptAction, interruptActions, threadId } =\n useContext(CopilotContext);\n const { addToast } = useToast();\n\n const actionId = dataToUUID(action, \"lgAction\");\n\n useEffect(() => {\n if (!action) return;\n\n // if (!action.enabled) {\n // TODO: if there are any other actions registered, we need to warn the user that a current action without \"enabled\" might render for everything\n // addToast({\n // type: \"warning\",\n // message: \"An action is already registered for the interrupt event\",\n // });\n // return;\n // }\n\n setInterruptAction({ ...action, id: actionId });\n\n // Cleanup: remove action on unmount\n return () => {\n removeInterruptAction(actionId);\n };\n }, [setInterruptAction, removeInterruptAction, threadId, actionId, ...(dependencies || [])]);\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 { instructions, available = \"enabled\" }: UseCopilotAdditionalInstructionsOptions,\n dependencies?: any[],\n) {\n const { setAdditionalInstructions } = useCopilotContext();\n\n useEffect(() => {\n if (available === \"disabled\") return;\n\n setAdditionalInstructions((prevInstructions) => [...(prevInstructions || []), instructions]);\n\n return () => {\n setAdditionalInstructions(\n (prevInstructions) =>\n prevInstructions?.filter((instruction) => instruction !== instructions) || [],\n );\n };\n }, [available, instructions, setAdditionalInstructions, ...(dependencies || [])]);\n}\n","import { useCopilotAction } from \"./use-copilot-action\";\nimport { CatchAllFrontendAction } from \"../types/frontend-action\";\n\nexport function useDefaultTool(tool: Omit<CatchAllFrontendAction, \"name\">, dependencies?: any[]) {\n // Use the existing useCopilotAction hook\n useCopilotAction({ ...tool, name: \"*\" } satisfies CatchAllFrontendAction, dependencies);\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 \"@copilotkitnext/react\";\nimport { useEffect } from \"react\";\nimport { StaticSuggestionsConfig, Suggestion } from \"@copilotkitnext/core\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> & Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<StaticSuggestionsConfig, \"suggestions\"> & {\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?: \"enabled\" | \"disabled\" | \"always\" | \"before-first-message\" | \"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) ?? \"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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAAAA;AAAA;AAAA;;;ACAA,IAAAC,iBAAiF;;;ACWjF,mBAA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AS,IAAI,SAAS;AAE9B,QAAM,eAAW,4BAAW,QAAQ,UAAU;AAE9C,gCAAU,MAAM;AACd,QAAI,CAAC;AAAQ;AAWb,uBAAmB,iCAAK,SAAL,EAAa,IAAI,SAAS,EAAC;AAG9C,WAAO,MAAM;AACX,4BAAsB,QAAQ;AAAA,IAChC;AAAA,EACF,GAAG,CAAC,oBAAoB,uBAAuB,UAAU,UAAU,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAC7F;;;ACGA,IAAAC,iBAA0B;AA4BnB,SAAS,iCACd,EAAE,cAAc,YAAY,UAAU,GACtC,cACA;AACA,QAAM,EAAE,0BAA0B,IAAI,kBAAkB;AAExD,gCAAU,MAAM;AACd,QAAI,cAAc;AAAY;AAE9B,8BAA0B,CAAC,qBAAqB,CAAC,GAAI,oBAAoB,CAAC,GAAI,YAAY,CAAC;AAE3F,WAAO,MAAM;AACX;AAAA,QACE,CAAC,sBACC,qDAAkB,OAAO,CAAC,gBAAgB,gBAAgB,kBAAiB,CAAC;AAAA,MAChF;AAAA,IACF;AAAA,EACF,GAAG,CAAC,WAAW,cAAc,2BAA2B,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAClF;;;ACjFO,SAAS,eAAe,MAA4C,cAAsB;AAE/F,mBAAiB,iCAAK,OAAL,EAAW,MAAM,IAAI,IAAoC,YAAY;AACxF;;;ACsDA,IAAAC,iBAKO;AA0CA,SAAS,0BACd,QACA,eAAsB,CAAC,GACvB;AA9GF;AA+GE,QAAM,qBAAiB,4CAA4B;AACnD,QAAM,mBAAkB,sDAAgB,YAAhB,YAA2B;AAEnD,QAAM,aACH,YAAO,cAAc,YAAY,WAAW,OAAO,cAAnD,YAAiE;AAEpE,QAAM,wBAAwB,iCACzB,SADyB;AAAA,IAE5B;AAAA,IACA,iBAAiB;AAAA;AAAA,EACnB;AACA,8CAAwB,uBAAuB,YAAY;AAC7D;","names":["useRenderToolCall","import_react","React","import_react","import_react","import_jsx_runtime","import_jsx_runtime","ReactMarkdown","import_runtime_client_gql","import_react","import_jsx_runtime","import_react","import_shared","import_react","import_react","React","import_react","import_react","import_react","import_shared","runId","_a","agent","_a","_b","DeprecatedGqlMessage","suggestions","import_react","import_shared","import_react","import_react","import_shared","React","useFrontendToolVNext","import_shared","import_react","useRenderToolCall","import_shared","import_react","React","useHumanInTheLoopVNext","_a","useRenderToolCall","import_react","import_shared","import_react","import_react","import_react","import_runtime_client_gql","import_react","import_shared","error","_a","import_react","import_react","React","import_react","import_shared","import_react","import_react"]}
|