@copilotkit/react-core 1.50.1-next.0 → 1.50.1-next.2
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 +16 -0
- package/dist/{chunk-BTZ3TJVX.mjs → chunk-4RRMC7L2.mjs} +4 -4
- package/dist/{chunk-JZN7YOPM.mjs → chunk-4YZA2BZC.mjs} +13 -13
- package/dist/{chunk-ZE4JVTEP.mjs → chunk-53K6WNJG.mjs} +2 -2
- 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-5J7RRLRO.mjs → chunk-FQFXYAV7.mjs} +2 -2
- package/dist/{chunk-EG56H77V.mjs → chunk-GPEJNVE5.mjs} +2 -2
- package/dist/{chunk-7HI6VLJJ.mjs → chunk-HE22TZMF.mjs} +4 -4
- package/dist/{chunk-FESRCHUE.mjs → chunk-LCZZ7YGZ.mjs} +2 -2
- package/dist/{chunk-SNON4QA6.mjs → chunk-LHERIF3L.mjs} +4 -4
- package/dist/{chunk-LDEWO5XH.mjs → chunk-LSHFN2Y5.mjs} +28 -7
- package/dist/chunk-LSHFN2Y5.mjs.map +1 -0
- package/dist/{chunk-IUNU4CUG.mjs → chunk-YTQHRJUA.mjs} +4 -4
- package/dist/components/copilot-provider/copilot-messages.mjs +2 -2
- package/dist/components/copilot-provider/copilotkit.mjs +7 -7
- package/dist/components/copilot-provider/index.mjs +7 -7
- package/dist/components/error-boundary/error-boundary.mjs +2 -2
- package/dist/components/index.mjs +7 -7
- package/dist/context/index.mjs +5 -5
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.js +36 -7
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +14 -14
- package/dist/hooks/use-coagent-state-render-bridge.mjs +1 -1
- package/dist/hooks/use-coagent-state-render.mjs +2 -2
- 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-copilot-chat-headless_c.js +27 -6
- package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
- package/dist/hooks/use-copilot-chat-headless_c.mjs +5 -5
- package/dist/hooks/use-copilot-chat.js +27 -6
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +5 -5
- package/dist/hooks/use-copilot-chat_internal.d.ts +24 -2
- package/dist/hooks/use-copilot-chat_internal.js +27 -6
- package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
- package/dist/hooks/use-copilot-chat_internal.mjs +4 -4
- 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/hooks/use-langgraph-interrupt-render.mjs +1 -1
- package/dist/hooks/use-langgraph-interrupt.mjs +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +36 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +39 -39
- package/dist/lib/copilot-task.mjs +8 -8
- package/dist/lib/index.mjs +8 -8
- package/package.json +3 -3
- package/src/hooks/index.ts +6 -1
- package/src/hooks/use-copilot-chat_internal.ts +59 -3
- package/src/hooks/use-frontend-tool.ts +13 -2
- package/dist/chunk-LDEWO5XH.mjs.map +0 -1
- package/dist/chunk-T2VBHAAP.mjs.map +0 -1
- /package/dist/{chunk-BTZ3TJVX.mjs.map → chunk-4RRMC7L2.mjs.map} +0 -0
- /package/dist/{chunk-JZN7YOPM.mjs.map → chunk-4YZA2BZC.mjs.map} +0 -0
- /package/dist/{chunk-ZE4JVTEP.mjs.map → chunk-53K6WNJG.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-5J7RRLRO.mjs.map → chunk-FQFXYAV7.mjs.map} +0 -0
- /package/dist/{chunk-EG56H77V.mjs.map → chunk-GPEJNVE5.mjs.map} +0 -0
- /package/dist/{chunk-7HI6VLJJ.mjs.map → chunk-HE22TZMF.mjs.map} +0 -0
- /package/dist/{chunk-FESRCHUE.mjs.map → chunk-LCZZ7YGZ.mjs.map} +0 -0
- /package/dist/{chunk-SNON4QA6.mjs.map → chunk-LHERIF3L.mjs.map} +0 -0
- /package/dist/{chunk-IUNU4CUG.mjs.map → chunk-YTQHRJUA.mjs.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/use-copilot-chat.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"],"sourcesContent":["/**\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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAAiF;;;ACWjF,mBAAkB;AAuOlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,sBAAsB,MAAM;AAAA,EAC5B,wBAAwB,MAAM;AAAA,EAAC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AASA,SAAS,yBAAyB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAKmB;AACjB,aAAO,wBAAQ,MAAM;AACnB,QAAI,CAAC,cAAc,CAAC,OAAO;AACzB,aAAO;AAAA,IACT;AAEA,WAAO,CAAC,EAAE,SAAS,SAAS,MAA0B;AA1kB1D;AA2kBM,YAAM,qBAAoB,mCAAY,MAAM,aAAlB,YAA8B;AACxD,YAAM,gBAAgB,WAAW,mBAAmB,SAAS,mBAAmB,QAAQ,EAAE;AAC1F,YAAM,QAAQ,iBAAiB,WAAW,QAAQ;AAClD,YAAM,eAAe,KAAK;AAAA,QACxB,MAAM,SAAS,UAAU,CAAC,QAAQ,IAAI,OAAO,QAAQ,EAAE;AAAA,QACvD;AAAA,MACF;AAEA,YAAM,cAA6C;AAAA,QACjD;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,mBAAmB;AAAA,QACnB,uBAAuB;AAAA,QACvB;AAAA,QACA,eAAgB,QAAgB;AAAA,MAClC;AAEA,iBAAO,8BAAc,0BAA0B,WAAW;AAAA,IAC5D;AAAA,EACF,GAAG,CAAC,OAAO,SAAS,YAAY,QAAQ,CAAC;AAC3C;;;AD1fO,SAAS,eAAe,UAAiC,CAAC,GAAyB;AACxF,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,uBAAuB,OAAO;AAElC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/use-copilot-chat.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"],"sourcesContent":["/**\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","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 OnStopGenerationArguments {\n /**\n * The name of the currently executing agent.\n */\n currentAgentName: string | undefined;\n\n /**\n * The messages in the chat.\n */\n messages: Message[];\n}\n\nexport type OnReloadMessagesArguments = OnStopGenerationArguments & {\n /**\n * The message on which \"regenerate\" was pressed\n */\n messageId: string;\n};\n\nexport type OnStopGeneration = (args: OnStopGenerationArguments) => void;\n\nexport type OnReloadMessages = (args: OnReloadMessagesArguments) => void;\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Initial messages to populate the chat with.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n\n /**\n * Disables inclusion of CopilotKit’s default system message. When true, no system message is sent (this also suppresses any custom message from <code>makeSystemMessage</code>).\n */\n disableSystemMessage?: boolean;\n /**\n * Controls the behavior of suggestions in the chat interface.\n *\n * `auto` (default) - Suggestions are generated automatically:\n * - When the chat is first opened (empty state)\n * - After each message exchange completes\n * - Uses configuration from `useCopilotChatSuggestions` hooks\n *\n * `manual` - Suggestions are controlled programmatically:\n * - Use `setSuggestions()` to set custom suggestions\n * - Use `generateSuggestions()` to trigger AI generation\n * - Access via `useCopilotChat` hook\n *\n * `SuggestionItem[]` - Static suggestions array:\n * - Always shows the same suggestions\n * - No AI generation involved\n */\n suggestions?: ChatSuggestions;\n\n onInProgress?: (isLoading: boolean) => void;\n onSubmitMessage?: (messageContent: string) => Promise<void> | void;\n onStopGeneration?: OnStopGeneration;\n onReloadMessages?: OnReloadMessages;\n}\n\nexport interface MCPServerConfig {\n endpoint: string;\n apiKey?: string;\n}\n\n// Old suggestion item interface, for returning from useCopilotChatInternal\ninterface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport interface UseCopilotChatReturn {\n /**\n * @deprecated use `messages` instead, this is an old non ag-ui version of the messages\n * Array of messages currently visible in the chat interface\n *\n * This is the visible messages, not the raw messages from the runtime client.\n */\n visibleMessages: DeprecatedGqlMessage[];\n\n /**\n * The messages that are currently in the chat in AG-UI format.\n */\n messages: Message[];\n\n /** @deprecated use `sendMessage` in `useCopilotChatHeadless_c` instead. This will be removed in a future major version. */\n appendMessage: (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 onInProgress,\n onSubmitMessage,\n onStopGeneration,\n onReloadMessages,\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const { copilotkit } = useCopilotKit();\n const { threadId, agentSession } = useCopilotContext();\n const existingConfig = useCopilotChatConfiguration();\n const [agentAvailable, setAgentAvailable] = useState(false);\n\n // Apply priority: props > existing config > defaults\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const { agent } = useAgent({ 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 useEffect(() => {\n onInProgress?.(Boolean(agent?.isRunning));\n }, [agent?.isRunning, onInProgress]);\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 if (onSubmitMessage) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : message.content && \"text\" in message.content\n ? message.content.text\n : message.content && \"filename\" in message.content\n ? message.content.filename\n : \"\";\n onSubmitMessage(content);\n }\n },\n [agent, copilotkit, resolvedAgentId, onSubmitMessage],\n );\n\n const latestAppendFunc = useAsyncCallback(\n async (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => {\n return latestSendMessageFunc(gqlToAGUI([message])[0], options);\n },\n [latestSendMessageFunc],\n );\n\n const latestSetMessagesFunc = useCallback(\n (messages: Message[] | DeprecatedGqlMessage[]) => {\n if (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 onReloadMessages?.({\n messageId,\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return await latestReload.current(messageId);\n },\n [latestReload, agent, onReloadMessages],\n );\n\n const latestStopFunc = useCallback(() => {\n onStopGeneration?.({\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return agent?.abortRun?.();\n }, [onStopGeneration, agent]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n const lazyToolRendered = useLazyToolRenderer();\n const renderCustomMessage = useRenderCustomMessages();\n const legacyCustomMessageRenderer = useLegacyCoagentRenderer({\n copilotkit,\n agent,\n agentId: resolvedAgentId,\n threadId: existingConfig?.threadId ?? threadId,\n });\n const allMessages = agent?.messages ?? [];\n const resolvedMessages = useMemo(() => {\n let processedMessages = allMessages.map((message) => {\n if (message.role !== \"assistant\") {\n return message;\n }\n\n const lazyRendered = lazyToolRendered(message, allMessages);\n if (lazyRendered) {\n const renderedGenUi = lazyRendered();\n if (renderedGenUi) {\n return { ...message, generativeUI: () => renderedGenUi };\n }\n }\n\n const bridgeRenderer =\n legacyCustomMessageRenderer || renderCustomMessage\n ? () => {\n 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAAiF;;;ACWjF,mBAAkB;AAuOlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,E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,cAA6C;AAAA,QACjD;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,mBAAmB;AAAA,QACnB,uBAAuB;AAAA,QACvB;AAAA,QACA,eAAgB,QAAgB;AAAA,MAClC;AAEA,iBAAO,8BAAc,0BAA0B,WAAW;AAAA,IAC5D;AAAA,EACF,GAAG,CAAC,OAAO,SAAS,YAAY,QAAQ,CAAC;AAC3C;;;ADljBO,SAAS,eAAe,UAAiC,CAAC,GAAyB;AACxF,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,uBAAuB,OAAO;AAElC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["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"]}
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useCopilotChat
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
3
|
+
} from "../chunk-53K6WNJG.mjs";
|
|
4
|
+
import "../chunk-LSHFN2Y5.mjs";
|
|
5
5
|
import "../chunk-VV56AVPB.mjs";
|
|
6
6
|
import "../chunk-ZVF5Q6IH.mjs";
|
|
7
|
+
import "../chunk-I76HKHPJ.mjs";
|
|
7
8
|
import "../chunk-6PUNP7CD.mjs";
|
|
8
9
|
import "../chunk-O7ARI5CV.mjs";
|
|
9
10
|
import "../chunk-QNUAXSDP.mjs";
|
|
10
|
-
import "../chunk-I76HKHPJ.mjs";
|
|
11
11
|
import "../chunk-NB2FKV2V.mjs";
|
|
12
|
+
import "../chunk-F555TVE4.mjs";
|
|
13
|
+
import "../chunk-EFL5OBKN.mjs";
|
|
12
14
|
import "../chunk-FDOMAPJY.mjs";
|
|
13
15
|
import "../chunk-AFNWX62Q.mjs";
|
|
14
16
|
import "../chunk-DMLQZG75.mjs";
|
|
15
|
-
import "../chunk-F555TVE4.mjs";
|
|
16
|
-
import "../chunk-EFL5OBKN.mjs";
|
|
17
17
|
import "../chunk-SKC7AJIV.mjs";
|
|
18
18
|
export {
|
|
19
19
|
useCopilotChat
|
|
@@ -22,6 +22,24 @@ interface AppendMessageOptions {
|
|
|
22
22
|
*/
|
|
23
23
|
clearSuggestions?: boolean;
|
|
24
24
|
}
|
|
25
|
+
interface OnStopGenerationArguments {
|
|
26
|
+
/**
|
|
27
|
+
* The name of the currently executing agent.
|
|
28
|
+
*/
|
|
29
|
+
currentAgentName: string | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* The messages in the chat.
|
|
32
|
+
*/
|
|
33
|
+
messages: Message[];
|
|
34
|
+
}
|
|
35
|
+
type OnReloadMessagesArguments = OnStopGenerationArguments & {
|
|
36
|
+
/**
|
|
37
|
+
* The message on which "regenerate" was pressed
|
|
38
|
+
*/
|
|
39
|
+
messageId: string;
|
|
40
|
+
};
|
|
41
|
+
type OnStopGeneration = (args: OnStopGenerationArguments) => void;
|
|
42
|
+
type OnReloadMessages = (args: OnReloadMessagesArguments) => void;
|
|
25
43
|
interface UseCopilotChatOptions {
|
|
26
44
|
/**
|
|
27
45
|
* A unique identifier for the chat. If not provided, a random one will be
|
|
@@ -63,6 +81,10 @@ interface UseCopilotChatOptions {
|
|
|
63
81
|
* - No AI generation involved
|
|
64
82
|
*/
|
|
65
83
|
suggestions?: ChatSuggestions;
|
|
84
|
+
onInProgress?: (isLoading: boolean) => void;
|
|
85
|
+
onSubmitMessage?: (messageContent: string) => Promise<void> | void;
|
|
86
|
+
onStopGeneration?: OnStopGeneration;
|
|
87
|
+
onReloadMessages?: OnReloadMessages;
|
|
66
88
|
}
|
|
67
89
|
interface MCPServerConfig {
|
|
68
90
|
endpoint: string;
|
|
@@ -216,7 +238,7 @@ interface UseCopilotChatReturn {
|
|
|
216
238
|
agent?: ReturnType<typeof useAgent>["agent"];
|
|
217
239
|
threadId?: string;
|
|
218
240
|
}
|
|
219
|
-
declare function useCopilotChatInternal({ suggestions, }?: UseCopilotChatOptions): UseCopilotChatReturn;
|
|
241
|
+
declare function useCopilotChatInternal({ suggestions, onInProgress, onSubmitMessage, onStopGeneration, onReloadMessages, }?: UseCopilotChatOptions): UseCopilotChatReturn;
|
|
220
242
|
declare function defaultSystemMessage(contextString: string, additionalInstructions?: string): string;
|
|
221
243
|
|
|
222
|
-
export { AppendMessageOptions, ChatSuggestions, MCPServerConfig, UseCopilotChatOptions, UseCopilotChatReturn, defaultSystemMessage, useCopilotChatInternal };
|
|
244
|
+
export { AppendMessageOptions, ChatSuggestions, MCPServerConfig, OnReloadMessages, OnReloadMessagesArguments, OnStopGeneration, OnStopGenerationArguments, UseCopilotChatOptions, UseCopilotChatReturn, defaultSystemMessage, useCopilotChatInternal };
|
|
@@ -658,7 +658,11 @@ function CoAgentStateRenderBridge(props) {
|
|
|
658
658
|
|
|
659
659
|
// src/hooks/use-copilot-chat_internal.ts
|
|
660
660
|
function useCopilotChatInternal({
|
|
661
|
-
suggestions
|
|
661
|
+
suggestions,
|
|
662
|
+
onInProgress,
|
|
663
|
+
onSubmitMessage,
|
|
664
|
+
onStopGeneration,
|
|
665
|
+
onReloadMessages
|
|
662
666
|
} = {}) {
|
|
663
667
|
var _a, _b, _c;
|
|
664
668
|
const { copilotkit } = (0, import_react14.useCopilotKit)();
|
|
@@ -687,6 +691,9 @@ function useCopilotChatInternal({
|
|
|
687
691
|
return () => {
|
|
688
692
|
};
|
|
689
693
|
}, [existingConfig == null ? void 0 : existingConfig.threadId, agent, copilotkit, resolvedAgentId]);
|
|
694
|
+
(0, import_react13.useEffect)(() => {
|
|
695
|
+
onInProgress == null ? void 0 : onInProgress(Boolean(agent == null ? void 0 : agent.isRunning));
|
|
696
|
+
}, [agent == null ? void 0 : agent.isRunning, onInProgress]);
|
|
690
697
|
const interrupt = useLangGraphInterruptRender(agent);
|
|
691
698
|
const reset = () => {
|
|
692
699
|
agent == null ? void 0 : agent.setMessages([]);
|
|
@@ -767,8 +774,12 @@ function useCopilotChatInternal({
|
|
|
767
774
|
console.error("CopilotChat: runAgent failed", error);
|
|
768
775
|
}
|
|
769
776
|
}
|
|
777
|
+
if (onSubmitMessage) {
|
|
778
|
+
const content = typeof message.content === "string" ? message.content : message.content && "text" in message.content ? message.content.text : message.content && "filename" in message.content ? message.content.filename : "";
|
|
779
|
+
onSubmitMessage(content);
|
|
780
|
+
}
|
|
770
781
|
}),
|
|
771
|
-
[agent, copilotkit, resolvedAgentId]
|
|
782
|
+
[agent, copilotkit, resolvedAgentId, onSubmitMessage]
|
|
772
783
|
);
|
|
773
784
|
const latestAppendFunc = useAsyncCallback(
|
|
774
785
|
(message, options) => __async(this, null, function* () {
|
|
@@ -789,14 +800,24 @@ function useCopilotChatInternal({
|
|
|
789
800
|
const latestReload = useUpdatedRef(reload);
|
|
790
801
|
const latestReloadFunc = useAsyncCallback(
|
|
791
802
|
(messageId) => __async(this, null, function* () {
|
|
803
|
+
var _a2;
|
|
804
|
+
onReloadMessages == null ? void 0 : onReloadMessages({
|
|
805
|
+
messageId,
|
|
806
|
+
currentAgentName: agent == null ? void 0 : agent.agentId,
|
|
807
|
+
messages: (_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : []
|
|
808
|
+
});
|
|
792
809
|
return yield latestReload.current(messageId);
|
|
793
810
|
}),
|
|
794
|
-
[latestReload]
|
|
811
|
+
[latestReload, agent, onReloadMessages]
|
|
795
812
|
);
|
|
796
813
|
const latestStopFunc = (0, import_react13.useCallback)(() => {
|
|
797
|
-
var _a2;
|
|
798
|
-
|
|
799
|
-
|
|
814
|
+
var _a2, _b2;
|
|
815
|
+
onStopGeneration == null ? void 0 : onStopGeneration({
|
|
816
|
+
currentAgentName: agent == null ? void 0 : agent.agentId,
|
|
817
|
+
messages: (_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : []
|
|
818
|
+
});
|
|
819
|
+
return (_b2 = agent == null ? void 0 : agent.abortRun) == null ? void 0 : _b2.call(agent);
|
|
820
|
+
}, [onStopGeneration, agent]);
|
|
800
821
|
const latestReset = useUpdatedRef(reset);
|
|
801
822
|
const latestResetFunc = (0, import_react13.useCallback)(() => {
|
|
802
823
|
return latestReset.current();
|