@copilotkit/react-core 1.54.1-next.3 → 1.54.1-next.4
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 +11 -0
- package/dist/index.cjs +10 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +11 -3
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +10 -2
- package/dist/index.umd.js.map +1 -1
- package/package.json +5 -5
- package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +1 -0
- package/src/hooks/__tests__/use-copilot-chat-internal-connect.test.tsx +1 -0
- package/src/hooks/use-copilot-chat_internal.ts +30 -3
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["useRenderToolCall","DeprecatedGqlMessage"],"sources":["../src/utils/suggestions-constants.ts","../src/hooks/use-lazy-tool-renderer.tsx","../src/hooks/use-copilot-chat_internal.ts","../src/hooks/use-copilot-chat.ts","../src/hooks/use-copilot-chat-headless_c.ts","../src/hooks/use-frontend-tool.ts","../src/hooks/use-render-tool-call.ts","../src/hooks/use-human-in-the-loop.ts","../src/hooks/use-copilot-action.ts","../src/hooks/use-coagent-state-render.ts","../src/hooks/use-make-copilot-document-readable.ts","../src/hooks/use-copilot-readable.ts","../src/hooks/use-agent-nodename.ts","../src/hooks/use-coagent.ts","../src/hooks/use-copilot-runtime-client.ts","../src/hooks/use-copilot-authenticated-action.ts","../src/hooks/use-langgraph-interrupt.ts","../src/hooks/use-copilot-additional-instructions.ts","../src/hooks/use-default-tool.ts","../src/hooks/use-copilot-chat-suggestions.tsx","../src/types/frontend-action.ts","../src/lib/copilot-task.ts"],"sourcesContent":["/**\n * Constants for suggestions retry logic\n */\n\nexport const SUGGESTION_RETRY_CONFIG = {\n MAX_RETRIES: 3,\n COOLDOWN_MS: 5000, // 5 seconds\n} as const;\n","import { 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 React, {\n useRef,\n useEffect,\n useCallback,\n useMemo,\n useState,\n createElement,\n} from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { Message } from \"@copilotkit/shared\";\nimport {\n gqlToAGUI,\n Message as DeprecatedGqlMessage,\n} from \"@copilotkit/runtime-client-gql\";\nimport {\n useAgent,\n useCopilotChatConfiguration,\n useCopilotKit,\n useRenderCustomMessages,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport {\n Suggestion,\n CopilotKitCoreRuntimeConnectionStatus,\n} 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 =\n | \"auto\"\n | \"manual\"\n | Omit<Suggestion, \"isLoading\">[];\n\nexport interface AppendMessageOptions {\n /**\n * Whether to run the chat completion after appending the message. Defaults to `true`.\n */\n followUp?: boolean;\n /**\n * Whether to clear the suggestions after appending the message. Defaults to `true`.\n */\n clearSuggestions?: boolean;\n}\n\nexport interface OnStopGenerationArguments {\n /**\n * The name of the currently executing agent.\n */\n currentAgentName: string | undefined;\n\n /**\n * The messages in the chat.\n */\n messages: Message[];\n}\n\nexport type OnReloadMessagesArguments = OnStopGenerationArguments & {\n /**\n * The message on which \"regenerate\" was pressed\n */\n messageId: string;\n};\n\nexport type OnStopGeneration = (args: OnStopGenerationArguments) => void;\n\nexport type OnReloadMessages = (args: OnReloadMessagesArguments) => void;\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Initial messages to populate the chat with.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n\n /**\n * Disables inclusion of CopilotKit’s default system message. When true, no system message is sent (this also suppresses any custom message from <code>makeSystemMessage</code>).\n */\n disableSystemMessage?: boolean;\n /**\n * Controls the behavior of suggestions in the chat interface.\n *\n * `auto` (default) - Suggestions are generated automatically:\n * - When the chat is first opened (empty state)\n * - After each message exchange completes\n * - Uses configuration from `useCopilotChatSuggestions` hooks\n *\n * `manual` - Suggestions are controlled programmatically:\n * - Use `setSuggestions()` to set custom suggestions\n * - Use `generateSuggestions()` to trigger AI generation\n * - Access via `useCopilotChat` hook\n *\n * `SuggestionItem[]` - Static suggestions array:\n * - Always shows the same suggestions\n * - No AI generation involved\n */\n suggestions?: ChatSuggestions;\n\n onInProgress?: (isLoading: boolean) => void;\n onSubmitMessage?: (messageContent: string) => Promise<void> | void;\n onStopGeneration?: OnStopGeneration;\n onReloadMessages?: OnReloadMessages;\n}\n\nexport interface MCPServerConfig {\n endpoint: string;\n apiKey?: string;\n}\n\n// Old suggestion item interface, for returning from useCopilotChatInternal\ninterface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport interface UseCopilotChatReturn {\n /**\n * @deprecated use `messages` instead, this is an old non ag-ui version of the messages\n * Array of messages currently visible in the chat interface\n *\n * This is the visible messages, not the raw messages from the runtime client.\n */\n visibleMessages: DeprecatedGqlMessage[];\n\n /**\n * The messages that are currently in the chat in AG-UI format.\n */\n messages: Message[];\n\n /** @deprecated use `sendMessage` in `useCopilotChatHeadless_c` instead. This will be removed in a future major version. */\n appendMessage: (\n message: DeprecatedGqlMessage,\n options?: AppendMessageOptions,\n ) => Promise<void>;\n\n /**\n * Send a new message to the chat\n *\n * ```tsx\n * await sendMessage({\n * id: \"123\",\n * role: \"user\",\n * content: \"Hello, process this request\",\n * });\n * ```\n */\n sendMessage: (\n message: Message,\n options?: AppendMessageOptions,\n ) => Promise<void>;\n\n /**\n * Replace all messages in the chat\n *\n * ```tsx\n * setMessages([\n * { id: \"123\", role: \"user\", content: \"Hello, process this request\" },\n * { id: \"456\", role: \"assistant\", content: \"Hello, I'm the assistant\" },\n * ]);\n * ```\n *\n * **Deprecated** non-ag-ui version:\n *\n * ```tsx\n * setMessages([\n * new TextMessage({\n * content: \"Hello, process this request\",\n * role: gqlRole.User,\n * }),\n * new TextMessage({\n * content: \"Hello, I'm the assistant\",\n * role: gqlRole.Assistant,\n * ]);\n * ```\n *\n */\n setMessages: (messages: Message[] | DeprecatedGqlMessage[]) => void;\n\n /**\n * Remove a specific message by ID\n *\n * ```tsx\n * deleteMessage(\"123\");\n * ```\n */\n deleteMessage: (messageId: string) => void;\n\n /**\n * Regenerate the response for a specific message\n *\n * ```tsx\n * reloadMessages(\"123\");\n * ```\n */\n reloadMessages: (messageId: string) => Promise<void>;\n\n /**\n * Stop the current message generation\n *\n * ```tsx\n * if (isLoading) {\n * stopGeneration();\n * }\n * ```\n */\n stopGeneration: () => void;\n\n /**\n * Clear all messages and reset chat state\n *\n * ```tsx\n * reset();\n * console.log(messages); // []\n * ```\n */\n reset: () => void;\n\n /**\n * Whether the chat is currently generating a response\n *\n * ```tsx\n * if (isLoading) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isLoading: boolean;\n\n /**\n * Whether the chat agent is available to generate responses\n *\n * ```tsx\n * if (isAvailable) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isAvailable: boolean;\n\n /** Manually trigger chat completion (advanced usage) */\n runChatCompletion: () => Promise<Message[]>;\n\n /** MCP (Model Context Protocol) server configurations */\n mcpServers: MCPServerConfig[];\n\n /** Update MCP server configurations */\n setMcpServers: (mcpServers: MCPServerConfig[]) => void;\n\n /**\n * Current suggestions array\n * Use this to read the current suggestions or in conjunction with setSuggestions for manual control\n */\n suggestions: Suggestion[];\n\n /**\n * Manually set suggestions\n * Useful for manual mode or custom suggestion workflows\n */\n setSuggestions: (suggestions: Omit<Suggestion, \"isLoading\">[]) => void;\n\n /**\n * Trigger AI-powered suggestion generation\n * Uses configurations from useCopilotChatSuggestions hooks\n * Respects global debouncing - only one generation can run at a time\n *\n * ```tsx\n * generateSuggestions();\n * console.log(suggestions); // [suggestion1, suggestion2, suggestion3]\n * ```\n */\n generateSuggestions: () => Promise<void>;\n\n /**\n * Clear all current suggestions\n * Also resets suggestion generation state\n */\n resetSuggestions: () => void;\n\n /** Whether suggestions are currently being generated */\n isLoadingSuggestions: boolean;\n\n /** Interrupt content for human-in-the-loop workflows */\n interrupt: string | React.ReactElement | null;\n\n agent?: ReturnType<typeof useAgent>[\"agent\"];\n\n threadId?: string;\n}\n\nexport function useCopilotChatInternal({\n suggestions,\n onInProgress,\n onSubmitMessage,\n onStopGeneration,\n onReloadMessages,\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const { copilotkit } = useCopilotKit();\n const { threadId, agentSession } = useCopilotContext();\n const existingConfig = useCopilotChatConfiguration();\n const [agentAvailable, setAgentAvailable] = useState(false);\n\n // Apply priority: props > existing config > defaults\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const { agent } = useAgent({ 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 console.error(\"CopilotChat: connectAgent failed\", error);\n // Error will be reported through subscription\n }\n }\n };\n if (\n agent &&\n existingConfig?.threadId &&\n agent.threadId !== existingConfig.threadId &&\n copilotkit.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ) {\n agent.threadId = existingConfig.threadId;\n connect(agent);\n }\n return () => {};\n }, [\n existingConfig?.threadId,\n agent,\n copilotkit,\n copilotkit.runtimeConnectionStatus,\n resolvedAgentId,\n ]);\n\n useEffect(() => {\n onInProgress?.(Boolean(agent?.isRunning));\n }, [agent?.isRunning, onInProgress]);\n\n // Subscribe to copilotkit.interruptElement so the v1 return type stays\n // reactive. The element is published by useInterrupt (v2) when user code\n // calls useLangGraphInterrupt({ render, ... }).\n const [interrupt, setInterrupt] = useState<React.ReactElement | null>(null);\n useEffect(() => {\n setInterrupt(copilotkit.interruptElement);\n const subscription = copilotkit.subscribe({\n onInterruptElementChanged: ({ interruptElement }) => {\n setInterrupt(interruptElement);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const reset = () => {\n agent?.setMessages([]);\n agent?.setState(null);\n };\n\n const deleteMessage = useCallback(\n (messageId: string) => {\n const filteredMessages = (agent?.messages ?? []).filter(\n (message) => message.id !== messageId,\n );\n agent?.setMessages(filteredMessages);\n },\n [agent?.setMessages, agent?.messages],\n );\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const currentSuggestions = useSuggestions({ agentId: resolvedAgentId });\n\n const reload = useAsyncCallback(\n async (reloadMessageId: string): Promise<void> => {\n if (!agent) return;\n const messages = agent?.messages ?? [];\n const isLoading = agent.isRunning;\n if (isLoading || messages.length === 0) {\n return;\n }\n\n const reloadMessageIndex = messages.findIndex(\n (msg) => msg.id === reloadMessageId,\n );\n if (reloadMessageIndex === -1) {\n console.warn(`Message with id ${reloadMessageId} not found`);\n return;\n }\n\n const reloadMessageRole = messages[reloadMessageIndex].role;\n if (reloadMessageRole !== \"assistant\") {\n console.warn(\n `Regenerate cannot be performed on ${reloadMessageRole} role`,\n );\n return;\n }\n let historyCutoff: Message[] = [messages[0]];\n\n if (messages.length > 2 && reloadMessageIndex !== 0) {\n // message to regenerate from is now first.\n // Work backwards to find the first the closest user message\n const lastUserMessageBeforeRegenerate = messages\n .slice(0, reloadMessageIndex)\n .reverse()\n .find((msg) => msg.role === \"user\");\n\n if (!lastUserMessageBeforeRegenerate) {\n historyCutoff = [messages[0]];\n } else {\n const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(\n (msg) => msg.id === lastUserMessageBeforeRegenerate.id,\n );\n // Include the user message, remove everything after it\n historyCutoff = messages.slice(\n 0,\n indexOfLastUserMessageBeforeRegenerate + 1,\n );\n }\n } else if (messages.length > 2 && reloadMessageIndex === 0) {\n historyCutoff = [messages[0], messages[1]];\n }\n\n agent?.setMessages(historyCutoff);\n\n if (agent) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed during reload\", error);\n // Error will be reported through subscription\n }\n }\n return;\n },\n [\n agent?.messages.length,\n agent?.isRunning,\n agent?.setMessages,\n copilotkit?.runAgent,\n ],\n );\n\n const latestSendMessageFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n if (!agent) return;\n const followUp = options?.followUp ?? true;\n if (options?.clearSuggestions) {\n copilotkit.clearSuggestions(resolvedAgentId);\n }\n\n // Call onSubmitMessage BEFORE adding message and running agent\n // This allows users to perform actions (e.g., open chat window) before agent starts processing\n if (onSubmitMessage) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : message.content && \"text\" in message.content\n ? message.content.text\n : message.content && \"filename\" in message.content\n ? message.content.filename\n : \"\";\n try {\n await onSubmitMessage(content);\n } catch (error) {\n console.error(\"Error in onSubmitMessage:\", error);\n }\n }\n\n agent?.addMessage(message);\n if (followUp) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\n // Error will be reported through subscription\n }\n }\n },\n [agent, copilotkit, resolvedAgentId, onSubmitMessage],\n );\n\n const latestAppendFunc = useAsyncCallback(\n async (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => {\n return latestSendMessageFunc(gqlToAGUI([message])[0], options);\n },\n [latestSendMessageFunc],\n );\n\n const latestSetMessagesFunc = useCallback(\n (messages: Message[] | DeprecatedGqlMessage[]) => {\n if (\n messages.every((message) => message instanceof DeprecatedGqlMessage)\n ) {\n return agent?.setMessages?.(gqlToAGUI(messages));\n }\n return agent?.setMessages?.(messages);\n },\n [agent?.setMessages, agent],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(\n async (messageId: string) => {\n onReloadMessages?.({\n messageId,\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return await latestReload.current(messageId);\n },\n [latestReload, agent, onReloadMessages],\n );\n\n const latestStopFunc = useCallback(() => {\n onStopGeneration?.({\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return agent?.abortRun?.();\n }, [onStopGeneration, agent]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n const lazyToolRendered = useLazyToolRenderer();\n const renderCustomMessage = useRenderCustomMessages();\n const legacyCustomMessageRenderer = useLegacyCoagentRenderer({\n copilotkit,\n agent,\n agentId: resolvedAgentId,\n threadId: existingConfig?.threadId ?? threadId,\n });\n const allMessages = agent?.messages ?? [];\n const resolvedMessages = useMemo(() => {\n let processedMessages = allMessages.map((message) => {\n if (message.role !== \"assistant\") {\n return message;\n }\n\n const lazyRendered = lazyToolRendered(message, allMessages);\n if (lazyRendered) {\n const renderedGenUi = lazyRendered();\n if (renderedGenUi) {\n return { ...message, generativeUI: () => renderedGenUi };\n }\n }\n\n const bridgeRenderer =\n legacyCustomMessageRenderer || renderCustomMessage\n ? () => {\n if (legacyCustomMessageRenderer) {\n return legacyCustomMessageRenderer({\n message,\n position: \"before\",\n });\n }\n try {\n return (\n renderCustomMessage?.({ message, position: \"before\" }) ?? null\n );\n } catch (error) {\n console.warn(\n \"[CopilotKit] renderCustomMessages failed, falling back to legacy renderer\",\n error,\n );\n return null;\n }\n }\n : null;\n\n if (bridgeRenderer) {\n // Attach a position so react-ui can render the custom UI above the assistant content.\n return {\n ...message,\n generativeUI: bridgeRenderer,\n generativeUIPosition: \"before\" as const,\n };\n }\n return message;\n });\n\n const hasAssistantMessages = processedMessages.some(\n (msg) => msg.role === \"assistant\",\n );\n const canUseCustomRenderer = Boolean(\n renderCustomMessage && copilotkit?.getAgent?.(resolvedAgentId),\n );\n const placeholderRenderer = legacyCustomMessageRenderer\n ? legacyCustomMessageRenderer\n : canUseCustomRenderer\n ? renderCustomMessage\n : null;\n\n const shouldRenderPlaceholder =\n Boolean(agent?.isRunning) ||\n Boolean(agent?.state && Object.keys(agent.state).length);\n\n const effectiveThreadId = threadId ?? agent?.threadId ?? \"default\";\n let latestUserIndex = -1;\n for (let i = processedMessages.length - 1; i >= 0; i -= 1) {\n if (processedMessages[i].role === \"user\") {\n latestUserIndex = i;\n break;\n }\n }\n const latestUserMessageId =\n latestUserIndex >= 0 ? processedMessages[latestUserIndex].id : undefined;\n const currentRunId = latestUserMessageId\n ? copilotkit.getRunIdForMessage(\n resolvedAgentId,\n effectiveThreadId,\n latestUserMessageId,\n ) || `pending:${latestUserMessageId}`\n : undefined;\n const hasAssistantForCurrentRun =\n latestUserIndex >= 0\n ? processedMessages\n .slice(latestUserIndex + 1)\n .some((msg) => msg.role === \"assistant\")\n : hasAssistantMessages;\n\n // Insert a placeholder assistant message so state snapshots can render before any\n // assistant text exists for the current run.\n if (\n placeholderRenderer &&\n shouldRenderPlaceholder &&\n !hasAssistantForCurrentRun\n ) {\n const placeholderId = currentRunId\n ? `coagent-state-render-${resolvedAgentId}-${currentRunId}`\n : `coagent-state-render-${resolvedAgentId}`;\n const placeholderMessage: Message = {\n id: placeholderId,\n role: \"assistant\",\n content: \"\",\n name: \"coagent-state-render\",\n runId: currentRunId,\n };\n processedMessages = [\n ...processedMessages,\n {\n ...placeholderMessage,\n generativeUIPosition: \"before\" as const,\n generativeUI: () =>\n placeholderRenderer({\n message: placeholderMessage,\n position: \"before\",\n }),\n } as Message,\n ];\n }\n\n return processedMessages;\n }, [\n agent?.messages,\n lazyToolRendered,\n allMessages,\n renderCustomMessage,\n legacyCustomMessageRenderer,\n resolvedAgentId,\n copilotkit,\n agent?.isRunning,\n agent?.state,\n ]);\n\n const renderedSuggestions = useMemo(() => {\n if (Array.isArray(suggestions)) {\n return {\n suggestions: suggestions.map((s) => ({ ...s, isLoading: false })),\n isLoading: false,\n };\n }\n return currentSuggestions;\n }, [suggestions, currentSuggestions]);\n\n // @ts-ignore\n return {\n messages: resolvedMessages,\n sendMessage: latestSendMessageFunc,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n isAvailable: agentAvailable,\n isLoading: Boolean(agent?.isRunning),\n // mcpServers,\n // setMcpServers,\n suggestions: renderedSuggestions.suggestions,\n setSuggestions: (suggestions: Omit<Suggestion, \"isLoading\">[]) =>\n copilotkit.addSuggestionsConfig({ suggestions }),\n generateSuggestions: async () =>\n copilotkit.reloadSuggestions(resolvedAgentId),\n resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),\n isLoadingSuggestions: renderedSuggestions.isLoading,\n interrupt,\n agent,\n threadId,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\ntype LegacyRenderParams = {\n message: Message;\n position: \"before\" | \"after\";\n};\n\ntype LegacyRenderer = ((args: LegacyRenderParams) => any) | null;\n\nfunction useLegacyCoagentRenderer({\n copilotkit,\n agent,\n agentId,\n threadId,\n}: {\n copilotkit: ReturnType<typeof useCopilotKit>[\"copilotkit\"];\n agent?: AbstractAgent;\n agentId: string;\n threadId?: string;\n}): LegacyRenderer {\n return useMemo(() => {\n if (!copilotkit || !agent) {\n return null;\n }\n\n return ({ message, position }: LegacyRenderParams) => {\n const effectiveThreadId = threadId ?? agent.threadId ?? \"default\";\n const providedRunId = (message as any).runId as string | undefined;\n const existingRunId = providedRunId\n ? providedRunId\n : copilotkit.getRunIdForMessage(agentId, effectiveThreadId, message.id);\n const runId = existingRunId || `pending:${message.id}`;\n const messageIndex = Math.max(\n agent.messages.findIndex((msg) => msg.id === message.id),\n 0,\n );\n\n const bridgeProps: CoAgentStateRenderBridgeProps = {\n message: message as any,\n position,\n runId,\n messageIndex,\n messageIndexInRun: 0,\n numberOfMessagesInRun: 1,\n agentId,\n stateSnapshot: (message as any).state,\n };\n\n return createElement(CoAgentStateRenderBridge, bridgeProps) as any;\n };\n }, [agent, agentId, copilotkit, threadId]);\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n","/**\n * `useCopilotChat` is a lightweight React hook for headless chat interactions.\n * Perfect for controlling the prebuilt chat components programmatically.\n *\n * **Open Source Friendly** - Works without requiring a free public license key.\n *\n * <Callout title=\"Looking for fully headless UI?\">\n * Get started with [useCopilotChatHeadless_c](https://docs.copilotkit.ai/reference/v1/hooks/useCopilotChatHeadless_c).\n * </Callout>\n *\n * ## Use Cases\n *\n * - **Programmatic Messaging**: Send messages without displaying chat UI\n * - **Programmatic control**: Control prebuilt component programmatically\n * - **Background Operations**: Trigger AI interactions in the background\n * - **Fire-and-Forget**: Send messages without needing to read responses\n *\n * ## Usage\n *\n * ```tsx\n * import { TextMessage, MessageRole } from \"@copilotkit/runtime-client-gql\";\n *\n * const { appendMessage } = useCopilotChat();\n *\n * // Example usage without naming conflicts\n * const handleSendMessage = async (content: string) => {\n * await appendMessage(\n * new TextMessage({\n * role: MessageRole.User,\n * content,\n * })\n * );\n * };\n * ```\n *\n * ## Return Values\n * The following properties are returned from the hook:\n *\n * <PropertyReference name=\"visibleMessages\" type=\"DeprecatedGqlMessage[]\" deprecated>\n * Array of messages in old non-AG-UI format, use for compatibility only\n * </PropertyReference>\n *\n * <PropertyReference name=\"appendMessage\" type=\"(message: DeprecatedGqlMessage, options?) => Promise<void>\" deprecated>\n * Append message using old format, use `sendMessage` instead\n * </PropertyReference>\n *\n * <PropertyReference name=\"reloadMessages\" type=\"(messageId: string) => Promise<void>\">\n * Regenerate the response for a specific message by ID\n * </PropertyReference>\n *\n * <PropertyReference name=\"stopGeneration\" type=\"() => void\">\n * Stop the current message generation process\n * </PropertyReference>\n *\n * <PropertyReference name=\"reset\" type=\"() => void\">\n * Clear all messages and reset chat state completely\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoading\" type=\"boolean\">\n * Whether the chat is currently generating a response\n * </PropertyReference>\n *\n * <PropertyReference name=\"runChatCompletion\" type=\"() => Promise<Message[]>\">\n * Manually trigger chat completion for advanced usage\n * </PropertyReference>\n *\n * <PropertyReference name=\"mcpServers\" type=\"MCPServerConfig[]\">\n * Array of Model Context Protocol server configurations\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMcpServers\" type=\"(servers: MCPServerConfig[]) => void\">\n * Update MCP server configurations for enhanced context\n * </PropertyReference>\n */\n\nimport {\n UseCopilotChatOptions,\n useCopilotChatInternal,\n UseCopilotChatReturn as UseCopilotChatReturnInternal,\n} from \"./use-copilot-chat_internal\";\n\n// Create a type that excludes message-related properties from the internal type\nexport type UseCopilotChatReturn = Omit<\n UseCopilotChatReturnInternal,\n | \"messages\"\n | \"sendMessage\"\n | \"suggestions\"\n | \"setSuggestions\"\n | \"generateSuggestions\"\n | \"isLoadingSuggestions\"\n | \"resetSuggestions\"\n | \"interrupt\"\n | \"setMessages\"\n | \"deleteMessage\"\n>;\n\n/**\n * A lightweight React hook for headless chat interactions.\n * Perfect for programmatic messaging, background operations, and custom UI implementations.\n *\n * **Open Source Friendly** - Works without requiring a `publicApiKey`.\n */\n// TODO: Do we need this? If so, does it work properly? test.\nexport function useCopilotChat(\n options: UseCopilotChatOptions = {},\n): UseCopilotChatReturn {\n const {\n visibleMessages,\n appendMessage,\n reloadMessages,\n stopGeneration,\n reset,\n isLoading,\n isAvailable,\n runChatCompletion,\n mcpServers,\n setMcpServers,\n } = useCopilotChatInternal(options);\n\n return {\n visibleMessages,\n appendMessage,\n reloadMessages,\n stopGeneration,\n reset,\n isLoading,\n isAvailable,\n runChatCompletion,\n mcpServers,\n setMcpServers,\n };\n}\n","/**\n * `useCopilotChatHeadless_c` is for building fully custom UI (headless UI) implementations.\n *\n * <Callout title=\"This is a premium-only feature\">\n * Sign up for free on [Copilot Cloud](https://cloud.copilotkit.ai) to get your public license key or read more about <a href=\"/premium/overview\">premium features</a>.\n *\n * Usage is generous, **free** to get started, and works with **either self-hosted or Copilot Cloud** environments.\n * </Callout>\n *\n * ## Key Features\n *\n * - **Fully headless**: Build your own fully custom UI's for your agentic applications.\n * - **Advanced Suggestions**: Direct access to suggestions array with full control\n * - **Interrupt Handling**: Support for advanced interrupt functionality\n * - **MCP Server Support**: Model Context Protocol server configurations\n * - **Chat Controls**: Complete set of chat management functions\n * - **Loading States**: Comprehensive loading state management\n *\n *\n * ## Usage\n *\n * ### Basic Setup\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n * import { useCopilotChatHeadless_c } from \"@copilotkit/react-core\";\n *\n * export function App() {\n * return (\n * <CopilotKit publicApiKey=\"your-free-public-license-key\">\n * <YourComponent />\n * </CopilotKit>\n * );\n * }\n *\n * export function YourComponent() {\n * const { messages, sendMessage, isLoading } = useCopilotChatHeadless_c();\n *\n * const handleSendMessage = async () => {\n * await sendMessage({\n * id: \"123\",\n * role: \"user\",\n * content: \"Hello World\",\n * });\n * };\n *\n * return (\n * <div>\n * {messages.map(msg => <div key={msg.id}>{msg.content}</div>)}\n * <button onClick={handleSendMessage} disabled={isLoading}>\n * Send Message\n * </button>\n * </div>\n * );\n * }\n * ```\n *\n * ### Working with Suggestions\n *\n * ```tsx\n * import { useCopilotChatHeadless_c, useCopilotChatSuggestions } from \"@copilotkit/react-core\";\n *\n * export function SuggestionExample() {\n * const {\n * suggestions,\n * setSuggestions,\n * generateSuggestions,\n * isLoadingSuggestions\n * } = useCopilotChatHeadless_c();\n *\n * // Configure AI suggestion generation\n * useCopilotChatSuggestions({\n * instructions: \"Suggest helpful actions based on the current context\",\n * maxSuggestions: 3\n * });\n *\n * return (\n * <div>\n * {suggestions.map(suggestion => (\n * <button key={suggestion.title}>{suggestion.title}</button>\n * ))}\n * <button onClick={generateSuggestions} disabled={isLoadingSuggestions}>\n * Generate Suggestions\n * </button>\n * </div>\n * );\n * }\n * ```\n *\n * ## Return Values\n * The following properties are returned from the hook:\n *\n * <PropertyReference name=\"messages\" type=\"Message[]\">\n * The messages currently in the chat in AG-UI format\n * </PropertyReference>\n *\n * <PropertyReference name=\"sendMessage\" type=\"(message: Message, options?) => Promise<void>\">\n * Send a new message to the chat and trigger AI response\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMessages\" type=\"(messages: Message[] | DeprecatedGqlMessage[]) => void\">\n * Replace all messages in the chat with new array\n * </PropertyReference>\n *\n * <PropertyReference name=\"deleteMessage\" type=\"(messageId: string) => void\">\n * Remove a specific message by ID from the chat\n * </PropertyReference>\n *\n * <PropertyReference name=\"reloadMessages\" type=\"(messageId: string) => Promise<void>\">\n * Regenerate the response for a specific message by ID\n * </PropertyReference>\n *\n * <PropertyReference name=\"stopGeneration\" type=\"() => void\">\n * Stop the current message generation process\n * </PropertyReference>\n *\n * <PropertyReference name=\"reset\" type=\"() => void\">\n * Clear all messages and reset chat state completely\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoading\" type=\"boolean\">\n * Whether the chat is currently generating a response\n * </PropertyReference>\n *\n * <PropertyReference name=\"runChatCompletion\" type=\"() => Promise<Message[]>\">\n * Manually trigger chat completion for advanced usage\n * </PropertyReference>\n *\n * <PropertyReference name=\"mcpServers\" type=\"MCPServerConfig[]\">\n * Array of Model Context Protocol server configurations\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMcpServers\" type=\"(servers: MCPServerConfig[]) => void\">\n * Update MCP server configurations for enhanced context\n * </PropertyReference>\n *\n * <PropertyReference name=\"suggestions\" type=\"SuggestionItem[]\">\n * Current suggestions array for reading or manual control\n * </PropertyReference>\n *\n * <PropertyReference name=\"setSuggestions\" type=\"(suggestions: SuggestionItem[]) => void\">\n * Manually set suggestions for custom workflows\n * </PropertyReference>\n *\n * <PropertyReference name=\"generateSuggestions\" type=\"() => Promise<void>\">\n * Trigger AI-powered suggestion generation using configured settings\n * </PropertyReference>\n *\n * <PropertyReference name=\"resetSuggestions\" type=\"() => void\">\n * Clear all current suggestions and reset generation state\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoadingSuggestions\" type=\"boolean\">\n * Whether suggestions are currently being generated\n * </PropertyReference>\n *\n * <PropertyReference name=\"interrupt\" type=\"string | React.ReactElement | null\">\n * Interrupt content for human-in-the-loop workflows\n * </PropertyReference>\n */\nimport { useEffect } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport {\n useCopilotChatInternal,\n defaultSystemMessage,\n UseCopilotChatOptions as UseCopilotChatOptions_c,\n UseCopilotChatReturn as UseCopilotChatReturn_c,\n MCPServerConfig,\n} from \"./use-copilot-chat_internal\";\n\nimport {\n ErrorVisibility,\n Severity,\n CopilotKitError,\n CopilotKitErrorCode,\n styledConsole,\n} from \"@copilotkit/shared\";\n\n// Non-functional fallback implementation\nconst createNonFunctionalReturn = (): UseCopilotChatReturn_c => ({\n visibleMessages: [],\n messages: [],\n sendMessage: async () => {},\n appendMessage: async () => {},\n setMessages: () => {},\n deleteMessage: () => {},\n reloadMessages: async () => {},\n stopGeneration: () => {},\n reset: () => {},\n isLoading: false,\n isAvailable: false,\n runChatCompletion: async () => [],\n mcpServers: [],\n setMcpServers: () => {},\n suggestions: [],\n setSuggestions: () => {},\n generateSuggestions: async () => {},\n resetSuggestions: () => {},\n isLoadingSuggestions: false,\n interrupt: null,\n});\n/**\n * Enterprise React hook that provides complete chat functionality for fully custom UI implementations.\n * Includes all advanced features like direct message access, suggestions array, interrupt handling, and MCP support.\n *\n * **Requires a publicApiKey** - Sign up for free at https://cloud.copilotkit.ai/\n *\n * @param options - Configuration options for the chat\n * @returns Complete chat interface with all enterprise features\n *\n * @example\n * ```tsx\n * const { messages, sendMessage, suggestions, interrupt } = useCopilotChatHeadless_c();\n * ```\n */\nfunction useCopilotChatHeadless_c(\n options: UseCopilotChatOptions_c = {},\n): UseCopilotChatReturn_c {\n const { copilotApiConfig, setBannerError } = useCopilotContext();\n\n // Check if publicApiKey is available\n const hasPublicApiKey = Boolean(copilotApiConfig.publicApiKey);\n\n // Always call the internal hook (follows rules of hooks)\n const internalResult = useCopilotChatInternal(options);\n\n // Set banner error when no public API key is provided\n useEffect(() => {\n if (!hasPublicApiKey) {\n setBannerError(\n new CopilotKitError({\n message:\n // add link to documentation here\n \"You're using useCopilotChatHeadless_c, a premium-only feature, which offers extensive headless chat capabilities. To continue, you'll need to provide a free public license key.\",\n code: CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,\n severity: Severity.WARNING,\n visibility: ErrorVisibility.BANNER,\n }),\n );\n styledConsole.logCopilotKitPlatformMessage();\n } else {\n setBannerError(null); // Clear banner when API key is provided\n }\n }, [hasPublicApiKey]); // Removed setBannerError dependency\n\n // Return internal result if publicApiKey is available, otherwise return fallback\n if (hasPublicApiKey) {\n return internalResult;\n }\n\n // Return non-functional fallback when no publicApiKey\n return createNonFunctionalReturn();\n}\n\nexport { defaultSystemMessage, useCopilotChatHeadless_c };\nexport type {\n UseCopilotChatOptions_c,\n UseCopilotChatReturn_c,\n MCPServerConfig,\n};\n\nconst noKeyWarning = () => {\n styledConsole.logCopilotKitPlatformMessage();\n};\n","import React, { useEffect, useMemo, useRef } from \"react\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport {\n Parameter,\n getZodParameters,\n MappedParameterTypes,\n} from \"@copilotkit/shared\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport {\n type ReactFrontendTool,\n useFrontendTool as useFrontendToolVNext,\n} from \"@copilotkitnext/react\";\n\ntype FrontendToolOptions<T extends Parameter[] | []> = ReactFrontendTool<\n MappedParameterTypes<T>\n>;\ntype FrontendToolRenderArgs<T extends Parameter[] | []> =\n | {\n name: string;\n args: Partial<MappedParameterTypes<T>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n }\n | {\n name: string;\n args: MappedParameterTypes<T>;\n status: ToolCallStatus.Executing;\n result: undefined;\n }\n | {\n name: string;\n args: MappedParameterTypes<T>;\n status: ToolCallStatus.Complete;\n result: string;\n };\n\nexport type UseFrontendToolArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n} & Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\" | \"handler\" | \"followUp\" | \"render\"\n>;\n\nexport function useFrontendTool<const T extends Parameter[] = []>(\n tool: UseFrontendToolArgs<T>,\n dependencies?: any[],\n) {\n const { name, description, parameters, render, followUp, available } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderRef = useRef<typeof render>(render);\n\n useEffect(() => {\n renderRef.current = render;\n }, [render, ...(dependencies ?? [])]);\n\n const normalizedRender: FrontendToolOptions<T>[\"render\"] | undefined =\n useMemo(() => {\n if (typeof render === \"undefined\") {\n return undefined;\n }\n\n return ((args: FrontendToolRenderArgs<T>) => {\n const currentRender = renderRef.current;\n\n if (typeof currentRender === \"undefined\") {\n return null;\n }\n\n if (typeof currentRender === \"string\") {\n return React.createElement(React.Fragment, null, currentRender);\n }\n\n const renderArgs = {\n ...args,\n result:\n typeof args.result === \"string\"\n ? parseJson(args.result, args.result)\n : args.result,\n } as ActionRenderProps<T>;\n\n const rendered = currentRender(renderArgs);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n }) as FrontendToolOptions<T>[\"render\"];\n }, []);\n\n // Handler ref to avoid stale closures\n const handlerRef = useRef<typeof tool.handler>(tool.handler);\n\n useEffect(() => {\n handlerRef.current = tool.handler;\n }, [tool.handler, ...(dependencies ?? [])]);\n\n const normalizedHandler = tool.handler\n ? (args: MappedParameterTypes<T>) => handlerRef.current?.(args)\n : undefined;\n\n useFrontendToolVNext<MappedParameterTypes<T>>({\n name,\n description,\n parameters: zodParameters,\n handler: normalizedHandler,\n followUp,\n render: normalizedRender,\n available: available === undefined ? undefined : available !== \"disabled\",\n });\n}\n","import { type Parameter, getZodParameters } from \"@copilotkit/shared\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { defineToolCallRenderer, useCopilotKit } from \"@copilotkitnext/react\";\nimport type React from \"react\";\nimport { useEffect, useRef } from \"react\";\nimport {\n type ActionRenderProps,\n type ActionRenderPropsNoArgs,\n ActionRenderPropsWait,\n type FrontendAction,\n} from \"../types\";\n\ntype ToolCallRendererDefinition = Parameters<typeof defineToolCallRenderer>[0];\n\nexport type UseRenderToolCallArgs<T extends Parameter[] | [] = []> = Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\"\n> & {\n available?: \"disabled\" | \"enabled\";\n render: T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => React.ReactElement\n : (props: ActionRenderProps<T>) => React.ReactElement;\n};\n\nexport function useRenderToolCall<const T extends Parameter[] | [] = []>(\n tool: UseRenderToolCallArgs<T>,\n dependencies?: any[],\n) {\n const { copilotkit } = useCopilotKit();\n\n // Track whether we've already added this renderer to avoid duplicates\n const hasAddedRef = useRef(false);\n\n useEffect(() => {\n const { name, parameters, render } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderToolCall =\n name === \"*\"\n ? defineToolCallRenderer({\n name: \"*\",\n render: ((args) => {\n return render({\n ...args,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n })\n : defineToolCallRenderer({\n name,\n args: zodParameters,\n render: ((args) => {\n return render({\n ...args,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n });\n\n // Remove any existing renderer with the same name\n const existingIndex = copilotkit.renderToolCalls.findIndex(\n (r) => r.name === name,\n );\n if (existingIndex !== -1) {\n copilotkit.renderToolCalls.splice(existingIndex, 1);\n }\n\n // Add the new renderer\n copilotkit.renderToolCalls.push(renderToolCall);\n hasAddedRef.current = true;\n\n // Cleanup: remove this renderer when the component unmounts or tool changes\n return () => {\n if (hasAddedRef.current) {\n const index = copilotkit.renderToolCalls.findIndex(\n (r) => r.name === name,\n );\n if (index !== -1) {\n copilotkit.renderToolCalls.splice(index, 1);\n }\n hasAddedRef.current = false;\n }\n };\n }, [tool, ...(dependencies ?? [])]);\n}\n","import {\n ActionRenderProps,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types\";\nimport {\n CopilotKitError,\n CopilotKitErrorCode,\n MappedParameterTypes,\n Parameter,\n getZodParameters,\n parseJson,\n} from \"@copilotkit/shared\";\nimport { useHumanInTheLoop as useHumanInTheLoopVNext } from \"@copilotkitnext/react\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport React, {\n ComponentType,\n FunctionComponent,\n useEffect,\n useRef,\n} from \"react\";\n\ntype HumanInTheLoopOptions = Parameters<typeof useHumanInTheLoopVNext>[0];\ntype HumanInTheLoopRender = HumanInTheLoopOptions[\"render\"];\ntype HumanInTheLoopRenderArgs = HumanInTheLoopRender extends (\n props: infer P,\n) => any\n ? P\n : never;\n\nexport type UseHumanInTheLoopArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n render: FrontendAction<T>[\"renderAndWaitForResponse\"];\n followUp?: FrontendAction<T>[\"followUp\"];\n} & Pick<FrontendAction<T>, \"name\" | \"description\" | \"parameters\">;\n\ntype HitlRendererArgs =\n | {\n name: string;\n description: string;\n args: Partial<Record<string, unknown>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n respond: undefined;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Executing;\n result: undefined;\n respond: (result: unknown) => Promise<void>;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Complete;\n result: string;\n respond: undefined;\n };\ntype HitlRenderer = FunctionComponent<HitlRendererArgs>;\n\nexport function useHumanInTheLoop<const T extends Parameter[] | [] = []>(\n tool: UseHumanInTheLoopArgs<T>,\n dependencies?: any[],\n) {\n const { render, ...toolRest } = tool;\n const { name, description, parameters, followUp } = toolRest;\n const zodParameters = getZodParameters(parameters);\n const renderRef = useRef<HitlRenderer | null>(null);\n\n useEffect(() => {\n renderRef.current = (args: HitlRendererArgs): React.ReactElement | null => {\n if (typeof render === \"string\") {\n return React.createElement(React.Fragment, null, render);\n }\n\n if (!render) {\n return null;\n }\n\n const renderProps: ActionRenderPropsWait<T> = (() => {\n const mappedArgs = args.args as unknown as MappedParameterTypes<T>;\n\n switch (args.status) {\n case ToolCallStatus.InProgress:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: undefined,\n };\n case ToolCallStatus.Executing:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: () => {},\n };\n case ToolCallStatus.Complete:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n handler: undefined,\n };\n default:\n throw new CopilotKitError({\n code: CopilotKitErrorCode.UNKNOWN,\n message: `Invalid tool call status: ${(args as unknown as { status: string }).status}`,\n });\n }\n })();\n\n const rendered = render(renderProps);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n };\n }, [render, ...(dependencies ?? [])]);\n\n useHumanInTheLoopVNext({\n name,\n description,\n followUp,\n parameters: zodParameters,\n render: ((args: HumanInTheLoopRenderArgs) =>\n renderRef.current?.(args as HitlRendererArgs) ??\n null) as HumanInTheLoopOptions[\"render\"],\n });\n}\n","/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { useEffect, useRef, useState } from \"react\";\nimport { Parameter } from \"@copilotkit/shared\";\nimport {\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport { useFrontendTool, UseFrontendToolArgs } from \"./use-frontend-tool\";\nimport {\n useRenderToolCall,\n UseRenderToolCallArgs,\n} from \"./use-render-tool-call\";\nimport {\n useHumanInTheLoop,\n UseHumanInTheLoopArgs,\n} from \"./use-human-in-the-loop\";\nimport { useCopilotContext } from \"../context\";\n\n// Helper to determine which component and action config to use\nfunction getActionConfig<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n) {\n if (action.name === \"*\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n\n if (\"renderAndWaitForResponse\" in action || \"renderAndWait\" in action) {\n let render = action.render;\n if (!render && \"renderAndWaitForResponse\" in action) {\n // @ts-expect-error -- renderAndWaitForResponse is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWaitForResponse;\n }\n if (!render && \"renderAndWait\" in action) {\n // @ts-expect-error -- renderAndWait is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWait;\n }\n\n return {\n type: \"hitl\" as const,\n action: { ...action, render } as UseHumanInTheLoopArgs<T>,\n };\n }\n\n if (\"available\" in action) {\n if (action.available === \"enabled\" || action.available === \"remote\") {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n if (action.available === \"frontend\" || action.available === \"disabled\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n }\n\n if (\"handler\" in action) {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n\n throw new Error(\"Invalid action configuration\");\n}\n\n/**\n * useCopilotAction is a legacy hook maintained for backwards compatibility.\n *\n * To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),\n * we use a registration pattern:\n * 1. This hook registers the action configuration with the CopilotContext\n * 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper\n * 3. React properly manages hook state since components are rendered, not conditionally called\n *\n * This allows action types to change between renders without corrupting React's hook state.\n */\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const [initialActionConfig] = useState(getActionConfig(action));\n const currentActionConfig = getActionConfig(action);\n\n /**\n * Calling hooks conditionally violates React's Rules of Hooks. This rule exists because\n * React maintains the call stack for hooks like useEffect or useState, and conditionally\n * calling a hook would result in inconsistent call stacks between renders.\n *\n * Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the\n * supplied parameters. In order to avoid breaking React's call stack tracking, while\n * breaking the Rule of Hooks, we use a ref to store the initial action configuration\n * and throw an error if the _configuration_ changes such that we would call a different hook.\n */\n if (initialActionConfig.type !== currentActionConfig.type) {\n throw new Error(\"Action configuration changed between renders\");\n }\n\n switch (currentActionConfig.type) {\n case \"render\":\n return useRenderToolCall(currentActionConfig.action, dependencies);\n case \"hitl\":\n return useHumanInTheLoop(currentActionConfig.action, dependencies);\n case \"frontend\":\n return useFrontendTool(currentActionConfig.action, dependencies);\n default:\n throw new Error(\"Invalid action configuration\");\n }\n}\n","/**\n * The useCoAgentStateRender hook allows you to render UI or text based components on a Agentic Copilot's state in the chat.\n * This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgentStateRender } from \"@copilotkit/react-core\";\n *\n * type YourAgentState = {\n * agent_state_property: string;\n * }\n *\n * useCoAgentStateRender<YourAgentState>({\n * name: \"basic_agent\",\n * nodeName: \"optionally_specify_a_specific_node\",\n * render: ({ status, state, nodeName }) => {\n * return (\n * <YourComponent\n * agentStateProperty={state.agent_state_property}\n * status={status}\n * nodeName={nodeName}\n * />\n * );\n * },\n * });\n * ```\n *\n * This allows for you to render UI components or text based on what is happening within the agent.\n *\n * ### Example\n * A great example of this is in our Perplexity Clone where we render the progress of an agent's internet search as it is happening.\n * You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).\n *\n * <Callout type=\"info\">\n * This example is hosted on Vercel and may take a few seconds to load.\n * </Callout>\n *\n * <iframe src=\"https://examples-coagents-ai-researcher-ui.vercel.app/\" className=\"w-full rounded-lg border h-[700px] my-4\" />\n */\n\nimport { useRef, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { randomId, CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCoAgentStateRenders } from \"../context/coagent-state-renders-context\";\n\n/**\n * This hook is used to render agent state with custom UI components or text. This is particularly\n * useful for showing intermediate state or progress during Agentic Copilot operations.\n * To get started using rendering intermediate state through this hook, checkout the documentation.\n *\n * https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates\n */\n\n// We implement useCoAgentStateRender dependency handling so that\n// the developer has the option to not provide any dependencies.\n// see useCopilotAction for more details about this approach.\nexport function useCoAgentStateRender<T = any>(\n action: CoAgentStateRender<T>,\n dependencies?: any[],\n): void {\n const { chatComponentsCache, availableAgents } = useContext(CopilotContext);\n const {\n setCoAgentStateRender,\n removeCoAgentStateRender,\n coAgentStateRenders,\n } = useCoAgentStateRenders();\n const idRef = useRef<string>(randomId());\n const { setBannerError, addToast } = useToast();\n\n useEffect(() => {\n if (\n availableAgents?.length &&\n !availableAgents.some((a) => a.name === action.name)\n ) {\n const message = `(useCoAgentStateRender): Agent \"${action.name}\" not found. Make sure the agent exists and is properly configured.`;\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: action.name,\n availableAgents: availableAgents.map((a) => ({\n name: a.name,\n id: a.id,\n })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coAgentStateRenders[idRef.current]) {\n coAgentStateRenders[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n // Check for duplicates by comparing against all other actions\n const currentId = idRef.current;\n const hasDuplicate = Object.entries(coAgentStateRenders).some(\n ([id, otherAction]) => {\n // Skip comparing with self\n if (id === currentId) return false;\n\n // Different agent names are never duplicates\n if (otherAction.name !== action.name) return false;\n\n // Same agent names:\n const hasNodeName = !!action.nodeName;\n const hasOtherNodeName = !!otherAction.nodeName;\n\n // If neither has nodeName, they're duplicates\n if (!hasNodeName && !hasOtherNodeName) return true;\n\n // If one has nodeName and other doesn't, they're not duplicates\n if (hasNodeName !== hasOtherNodeName) return false;\n\n // If both have nodeName, they're duplicates only if the names match\n return action.nodeName === otherAction.nodeName;\n },\n );\n\n if (hasDuplicate) {\n const message = action.nodeName\n ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden`\n : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;\n\n addToast({\n type: \"warning\",\n message,\n id: `dup-action-${action.name}`,\n });\n }\n }, [coAgentStateRenders]);\n\n useEffect(() => {\n setCoAgentStateRender(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n return () => {\n removeCoAgentStateRender(idRef.current);\n };\n }, [\n setCoAgentStateRender,\n removeCoAgentStateRender,\n action.name,\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n","import { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useCopilotContext();\n const idRef = useRef<string>(undefined!);\n\n useEffect(() => {\n const id = addDocumentContext(document, categories);\n idRef.current = id;\n\n return () => {\n removeDocumentContext(id);\n };\n }, [addDocumentContext, removeDocumentContext, ...dependencies]);\n\n return idRef.current;\n}\n","/**\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotReadable accepts a single string argument\n * representing any piece of app state, making it available for the Copilot to use\n * as context when responding to user input.\n *\n * ```tsx\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotReadable({\n * description: \"The list of employees\",\n * value: employees,\n * });\n * }\n * ```\n *\n * ### Nested Components\n *\n * Optionally, you can maintain the hierarchical structure of information by passing\n * `parentId`. This allows you to use `useCopilotReadable` in nested components:\n *\n * ```tsx /employeeContextId/1 {17,23}\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * function Employee(props: EmployeeProps) {\n * const { employeeName, workProfile, metadata } = props;\n *\n * // propagate any information to copilot\n * const employeeContextId = useCopilotReadable({\n * description: \"Employee name\",\n * value: employeeName\n * });\n *\n * // Pass a parentID to maintain a hierarchical structure.\n * // Especially useful with child React components, list elements, etc.\n * useCopilotReadable({\n * description: \"Work profile\",\n * value: workProfile.description(),\n * parentId: employeeContextId\n * });\n *\n * useCopilotReadable({\n * description: \"Employee metadata\",\n * value: metadata.description(),\n * parentId: employeeContextId\n * });\n *\n * return (\n * // Render as usual...\n * );\n * }\n * ```\n */\nimport { useCopilotKit } from \"@copilotkitnext/react\";\nimport { useEffect, useRef } from \"react\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context. Object values are automatically stringified.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * Whether the context is available to the Copilot.\n */\n available?: \"enabled\" | \"disabled\";\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n { description, value, convert, available }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { copilotkit } = useCopilotKit();\n const ctxIdRef = useRef<string | undefined>(undefined);\n useEffect(() => {\n if (!copilotkit) return;\n\n const found = Object.entries(copilotkit.context).find(([id, ctxItem]) => {\n return JSON.stringify({ description, value }) == JSON.stringify(ctxItem);\n });\n if (found) {\n ctxIdRef.current = found[0];\n if (available === \"disabled\") copilotkit.removeContext(ctxIdRef.current);\n return;\n }\n if (!found && available === \"disabled\") return;\n\n ctxIdRef.current = copilotkit.addContext({\n description,\n value: (convert ?? JSON.stringify)(value),\n });\n\n return () => {\n if (!ctxIdRef.current) return;\n copilotkit.removeContext(ctxIdRef.current);\n };\n }, [description, value, convert]);\n\n return ctxIdRef.current;\n}\n","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","/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Message } from \"@copilotkit/shared\";\nimport { useAgent, useCopilotKit } from \"@copilotkitnext/react\";\nimport { type AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<\n T,\n> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (...args: any[]) => Promise<any>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(\n options: UseCoagentOptions<T>,\n): UseCoagentReturnType<T> {\n const { agent } = useAgent({ agentId: options.name });\n const { copilotkit } = useCopilotKit();\n const nodeName = useAgentNodeName(options.name);\n\n const handleStateUpdate = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n if (!agent) return;\n\n if (typeof newState === \"function\") {\n const updater = newState as (prevState: T | undefined) => T;\n agent.setState(updater(agent.state));\n } else {\n agent.setState({ ...agent.state, ...newState });\n }\n },\n [agent?.state, agent?.setState],\n );\n\n useEffect(() => {\n if (!options.config && !options.configurable) return;\n\n let config = options.config ?? {};\n if (options.configurable) {\n config = {\n ...config,\n configurable: {\n ...options.configurable,\n ...config.configurable,\n },\n };\n }\n copilotkit.setProperties(config);\n }, [options.config, options.configurable]);\n\n const externalStateStr = useMemo(\n () =>\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : undefined,\n [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : undefined,\n ],\n );\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (\n agent?.state &&\n isExternalStateManagement(options) &&\n JSON.stringify(options.state) !== JSON.stringify(agent.state)\n ) {\n handleStateUpdate(options.state);\n }\n }, [agent, externalStateStr, handleStateUpdate]);\n\n const hasStateValues = useCallback((value?: Record<string, any>) => {\n return Boolean(value && Object.keys(value).length);\n }, []);\n\n const initialStateRef = useRef<any>(\n isExternalStateManagement(options)\n ? options.state\n : \"initialState\" in options\n ? options.initialState\n : undefined,\n );\n\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n initialStateRef.current = options.state;\n } else if (\"initialState\" in options) {\n initialStateRef.current = options.initialState;\n }\n }, [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : \"initialState\" in options\n ? JSON.stringify(options.initialState)\n : undefined,\n ]);\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStateChanged: (args: any) => {\n if (isExternalStateManagement(options)) {\n options.setState(args.state);\n }\n },\n onRunInitialized: (args: any) => {\n const runHasState = hasStateValues(args.state);\n if (runHasState) {\n handleStateUpdate(args.state);\n return;\n }\n\n if (hasStateValues(agent.state)) {\n return;\n }\n\n if (initialStateRef.current !== undefined) {\n handleStateUpdate(initialStateRef.current);\n }\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent, handleStateUpdate, hasStateValues]);\n\n // Return a consistent shape whether or not the agent is available\n return useMemo<UseCoagentReturnType<T>>(() => {\n if (!agent) {\n const noop = () => {};\n const noopAsync = async () => {};\n const initialState =\n // prefer externally provided state if available\n (\"state\" in options && (options as any).state) ??\n // then initialState if provided\n (\"initialState\" in options && (options as any).initialState) ??\n ({} as T);\n return {\n name: options.name,\n nodeName,\n threadId: undefined,\n running: false,\n state: initialState as T,\n setState: noop,\n start: noop,\n stop: noop,\n run: noopAsync,\n };\n }\n\n return {\n name: agent?.agentId ?? options.name,\n nodeName,\n threadId: agent.threadId,\n running: agent.isRunning,\n state: agent.state,\n setState: handleStateUpdate,\n // TODO: start and run both have same thing. need to figure out\n start: agent.runAgent,\n stop: agent.abortRun,\n run: agent.runAgent,\n };\n }, [\n agent?.state,\n agent?.runAgent,\n agent?.abortRun,\n agent?.runAgent,\n agent?.threadId,\n agent?.isRunning,\n agent?.agentId,\n handleStateUpdate,\n options.name,\n ]);\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n","import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo, useRef } from \"react\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n CopilotErrorHandler,\n CopilotErrorEvent,\n} from \"@copilotkit/shared\";\nimport { shouldShowDevConsole } from \"../utils/dev-console\";\n\nexport interface CopilotRuntimeClientHookOptions extends CopilotRuntimeClientOptions {\n showDevConsole?: boolean;\n onError: CopilotErrorHandler;\n}\n\nexport const useCopilotRuntimeClient = (\n options: CopilotRuntimeClientHookOptions,\n) => {\n const { setBannerError } = useToast();\n const { showDevConsole, onError, ...runtimeOptions } = options;\n\n // Deduplication state for structured errors\n const lastStructuredErrorRef = useRef<{\n message: string;\n timestamp: number;\n } | null>(null);\n\n // Helper function to trace UI errors\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\n try {\n const errorEvent: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"ui\",\n request: {\n operation: \"runtimeClient\",\n url: runtimeOptions.url,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent:\n typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : undefined,\n stackTrace:\n originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onError(errorEvent);\n } catch (error) {\n console.error(\"Error in onError handler:\", error);\n }\n };\n\n const runtimeClient = useMemo(() => {\n return new CopilotRuntimeClient({\n ...runtimeOptions,\n handleGQLErrors: (error) => {\n if ((error as any).graphQLErrors?.length) {\n const graphQLErrors = (error as any).graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // All errors (including DEV_ONLY) show as banners for consistency\n // Deduplicate to prevent spam\n const now = Date.now();\n const errorMessage = gqlError.message;\n if (\n lastStructuredErrorRef.current &&\n lastStructuredErrorRef.current.message === errorMessage &&\n now - lastStructuredErrorRef.current.timestamp < 150\n ) {\n return; // Skip duplicate\n }\n lastStructuredErrorRef.current = {\n message: errorMessage,\n timestamp: now,\n };\n\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the error\n traceUIError(ckError, gqlError);\n // TODO: if onError & renderError should work without key, insert here\n } else {\n // Fallback for unstructured errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n // TODO: if onError & renderError should work without key, insert here\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n // TODO: if onError & renderError should work without key, insert here\n }\n },\n handleGQLWarning: (message: string) => {\n console.warn(message);\n // Show warnings as banners too for consistency\n const warningError = new CopilotKitError({\n message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(warningError);\n },\n });\n }, [runtimeOptions, setBannerError, onError]);\n\n return runtimeClient;\n};\n\n// Create appropriate structured error from GraphQL error\nfunction createStructuredError(gqlError: GraphQLError): CopilotKitError | null {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n // Legacy error detection by stack trace\n if (originalError?.stack?.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message });\n }\n if (\n originalError?.stack?.includes(\"CopilotKitRemoteEndpointDiscoveryError\")\n ) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n\n return null;\n}\n","import { Parameter } from \"@copilotkit/shared\";\nimport { Fragment, useCallback, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { FrontendAction, ActionRenderProps } from \"../types/frontend-action\";\nimport { useCopilotAction } from \"./use-copilot-action\";\nimport React from \"react\";\n\n/**\n * Hook to create an authenticated action that requires user sign-in before execution.\n *\n * @remarks\n * This feature is only available when using CopilotKit's hosted cloud service.\n * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.\n *\n * @param action - The frontend action to be wrapped with authentication\n * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed\n */\nexport function useCopilotAuthenticatedAction_c<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();\n const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);\n\n const executeAction = useCallback(\n (props: ActionRenderProps<Parameter[]>) => {\n if (typeof action.render === \"function\") {\n return action.render(props);\n }\n return action.render || React.createElement(Fragment);\n },\n [action],\n );\n\n const wrappedRender = useCallback(\n (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {\n const isAuthenticated = Object.values(authStates_c || {}).some(\n (state) => state.status === \"authenticated\",\n );\n\n if (!isAuthenticated) {\n // Store action details for later execution\n pendingActionRef.current = props;\n\n return authConfig_c?.SignInComponent\n ? React.createElement(authConfig_c.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates_c?.((prev) => ({\n ...prev,\n [action.name]: authState,\n }));\n if (pendingActionRef.current) {\n executeAction(pendingActionRef.current);\n pendingActionRef.current = null;\n }\n },\n })\n : React.createElement(Fragment);\n }\n\n return executeAction(props);\n },\n [action, authStates_c, setAuthStates_c],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\n}\n","import React, { useCallback, useRef } from \"react\";\nimport { LangGraphInterruptRender } from \"../types/interrupt-action\";\nimport {\n useInterrupt,\n useCopilotChatConfiguration,\n} from \"@copilotkitnext/react\";\nimport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n} from \"@copilotkitnext/react\";\nimport { MetaEventName } from \"@copilotkit/runtime-client-gql\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\nimport type { AgentSession } from \"../context/copilot-context\";\n\n/**\n * Transforms a v2 InterruptEvent into the v1 LangGraphInterruptEvent shape\n * expected by existing useLangGraphInterrupt callbacks.\n */\nfunction toV1Event<TEventValue>(event: InterruptEvent<TEventValue>) {\n const value =\n typeof event.value === \"string\"\n ? parseJson(event.value, event.value)\n : event.value;\n return {\n name: MetaEventName.LangGraphInterruptEvent,\n type: \"MetaEvent\" as const,\n value,\n };\n}\n\nexport function useLangGraphInterrupt<TEventValue = any>(\n action: Omit<LangGraphInterruptRender<TEventValue>, \"id\">,\n _dependencies?: any[],\n) {\n const actionRef = useRef(action);\n // Update ref synchronously during render so it's always current\n // when callbacks read from it (useEffect would be one tick late).\n actionRef.current = action;\n\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId =\n action.agentId ?? existingConfig?.agentId ?? \"default\";\n const threadId = existingConfig?.threadId;\n const nodeName = useAgentNodeName(resolvedAgentId);\n\n // Keep agentMetadata in a ref so stable callbacks always see current values.\n const metadataRef = useRef<AgentSession>({\n agentName: resolvedAgentId,\n threadId,\n nodeName,\n });\n metadataRef.current = {\n agentName: resolvedAgentId,\n threadId,\n nodeName,\n };\n\n // Stable callback references that always read the latest action from the ref.\n // This prevents useInterrupt's internal useMemo/useEffect from seeing new\n // function identities on every render, which would cause an infinite loop.\n const render = useCallback(\n ({ event, result, resolve }: InterruptRenderProps<TEventValue>) => {\n const renderFn = actionRef.current.render;\n if (!renderFn) return React.createElement(React.Fragment);\n const rendered = renderFn({\n event: toV1Event(event) as any,\n result,\n resolve: (r) => resolve(r),\n });\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n return rendered;\n },\n [],\n );\n\n // Handler always delegates to the ref — if no handler is set at call time,\n // the optional chaining returns undefined which useInterrupt treats as null.\n const handler = useCallback(\n ({ event, resolve }: InterruptHandlerProps<TEventValue>) => {\n return actionRef.current.handler?.({\n event: toV1Event(event) as any,\n resolve: (r) => resolve(r),\n });\n },\n [],\n );\n\n const enabled = useCallback((event: InterruptEvent<TEventValue>) => {\n if (!actionRef.current.enabled) return true;\n return actionRef.current.enabled({\n eventValue: toV1Event(event).value,\n agentMetadata: metadataRef.current,\n });\n }, []);\n\n useInterrupt({\n render,\n handler,\n enabled,\n agentId: resolvedAgentId,\n });\n}\n","/**\n * `useCopilotAdditionalInstructions` is a React hook that provides additional instructions\n * to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotAdditionalInstructions accepts a single string argument\n * representing the instructions to be added to the Copilot.\n *\n * ```tsx\n * import { useCopilotAdditionalInstructions } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * useCopilotAdditionalInstructions({\n * instructions: \"Do not answer questions about the weather.\",\n * });\n * }\n * ```\n *\n * ### Conditional Usage\n *\n * You can also conditionally add instructions based on the state of your app.\n *\n * ```tsx\n * import { useCopilotAdditionalInstructions } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [showInstructions, setShowInstructions] = useState(false);\n *\n * useCopilotAdditionalInstructions({\n * available: showInstructions ? \"enabled\" : \"disabled\",\n * instructions: \"Do not answer questions about the weather.\",\n * });\n * }\n * ```\n */\nimport { useEffect } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\n\n/**\n * Options for the useCopilotAdditionalInstructions hook.\n */\nexport interface UseCopilotAdditionalInstructionsOptions {\n /**\n * The instructions to be added to the Copilot. Will be added to the instructions like so:\n *\n * ```txt\n * You are a helpful assistant.\n * Additionally, follow these instructions:\n * - Do not answer questions about the weather.\n * - Do not answer questions about the stock market.\n * ```\n */\n instructions: string;\n\n /**\n * Whether the instructions are available to the Copilot.\n */\n available?: \"enabled\" | \"disabled\";\n}\n\n/**\n * Adds the given instructions to the Copilot context.\n */\nexport function useCopilotAdditionalInstructions(\n {\n instructions,\n available = \"enabled\",\n }: UseCopilotAdditionalInstructionsOptions,\n dependencies?: any[],\n) {\n const { setAdditionalInstructions } = useCopilotContext();\n\n useEffect(() => {\n if (available === \"disabled\") return;\n\n setAdditionalInstructions((prevInstructions) => [\n ...(prevInstructions || []),\n instructions,\n ]);\n\n return () => {\n setAdditionalInstructions(\n (prevInstructions) =>\n prevInstructions?.filter(\n (instruction) => instruction !== instructions,\n ) || [],\n );\n };\n }, [\n available,\n instructions,\n setAdditionalInstructions,\n ...(dependencies || []),\n ]);\n}\n","import { useCopilotAction } from \"./use-copilot-action\";\nimport { CatchAllFrontendAction } from \"../types/frontend-action\";\n\nexport function useDefaultTool(\n tool: Omit<CatchAllFrontendAction, \"name\">,\n dependencies?: any[],\n) {\n // Use the existing useCopilotAction hook\n useCopilotAction(\n { ...tool, name: \"*\" } satisfies CatchAllFrontendAction,\n dependencies,\n );\n}\n","/**\n * <Callout type=\"warning\">\n * useCopilotChatSuggestions is experimental. The interface is not final and\n * can change without notice.\n * </Callout>\n *\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * <br/>\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-chat-suggestions/use-copilot-chat-suggestions.gif\" width=\"500\" />\n *\n * ## Usage\n *\n * ### Install Dependencies\n *\n * This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.\n *\n * ```shell npm2yarn \\\"@copilotkit/react-ui\"\\\n * npm install @copilotkit/react-core @copilotkit/react-ui\n * ```\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChatSuggestions } from \"@copilotkit/react-ui\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotChatSuggestions({\n * instructions: `The following employees are on duty: ${JSON.stringify(employees)}`,\n * });\n * }\n * ```\n *\n * ### Dependency Management\n *\n * ```tsx\n * import { useCopilotChatSuggestions } from \"@copilotkit/react-ui\";\n *\n * export function MyComponent() {\n * useCopilotChatSuggestions(\n * {\n * instructions: \"Suggest the most relevant next actions.\",\n * },\n * [appState],\n * );\n * }\n * ```\n *\n * In the example above, the suggestions are generated based on the given instructions.\n * The hook monitors `appState`, and updates suggestions accordingly whenever it changes.\n *\n * ### Behavior and Lifecycle\n *\n * The hook registers the configuration with the chat context upon component mount and\n * removes it on unmount, ensuring a clean and efficient lifecycle management.\n */\nimport {\n useConfigureSuggestions,\n useCopilotChatConfiguration,\n useCopilotKit,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport { useEffect } from \"react\";\nimport { StaticSuggestionsConfig, Suggestion } from \"@copilotkitnext/core\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> &\n Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<\n StaticSuggestionsConfig,\n \"suggestions\"\n> & {\n suggestions: StaticSuggestionInput[];\n};\n\ntype DynamicSuggestionsConfigInput = {\n /**\n * A prompt or instructions for the GPT to generate suggestions.\n */\n instructions: string;\n /**\n * The minimum number of suggestions to generate. Defaults to `1`.\n * @default 1\n */\n minSuggestions?: number;\n /**\n * The maximum number of suggestions to generate. Defaults to `3`.\n * @default 1\n */\n maxSuggestions?: number;\n\n /**\n * Whether the suggestions are available. Defaults to `enabled`.\n * @default enabled\n */\n available?:\n | \"enabled\"\n | \"disabled\"\n | \"always\"\n | \"before-first-message\"\n | \"after-first-message\";\n\n /**\n * An optional class name to apply to the suggestions.\n */\n className?: string;\n};\n\nexport type UseCopilotChatSuggestionsConfiguration =\n | DynamicSuggestionsConfigInput\n | StaticSuggestionsConfigInput;\n\nexport function useCopilotChatSuggestions(\n config: UseCopilotChatSuggestionsConfiguration,\n dependencies: any[] = [],\n) {\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n\n const available =\n (config.available === \"enabled\" ? \"always\" : config.available) ??\n \"before-first-message\";\n\n const finalSuggestionConfig = {\n ...config,\n available,\n consumerAgentId: resolvedAgentId, // Use chatConfig.agentId here\n };\n useConfigureSuggestions(finalSuggestionConfig, dependencies);\n}\n","import { ActionInputAvailability } from \"@copilotkit/runtime-client-gql\";\nimport {\n Action,\n Parameter,\n MappedParameterTypes,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingState<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: any;\n}\n\ninterface InProgressStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n}\n\nexport type ActionRenderProps<T extends Parameter[] | [] = []> =\n | CompleteState<T>\n | ExecutingState<T>\n | InProgressState<T>;\n\nexport type ActionRenderPropsNoArgs<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgs<T>\n | ExecutingStateNoArgs<T>\n | InProgressStateNoArgs<T>;\n\nexport type ActionRenderPropsWait<T extends Parameter[] | [] = []> =\n | CompleteStateWait<T>\n | ExecutingStateWait<T>\n | InProgressStateWait<T>;\n\nexport type ActionRenderPropsNoArgsWait<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgsWait<T>\n | ExecutingStateNoArgsWait<T>\n | InProgressStateNoArgsWait<T>;\n\nexport type CatchAllActionRenderProps<T extends Parameter[] | [] = []> =\n | (CompleteState<T> & {\n name: string;\n })\n | (ExecutingState<T> & {\n name: string;\n })\n | (InProgressState<T> & {\n name: string;\n });\n\nexport type FrontendActionAvailability =\n | \"disabled\"\n | \"enabled\"\n | \"remote\"\n | \"frontend\";\n\nexport type FrontendAction<\n T extends Parameter[] | [] = [],\n N extends string = string,\n> = Action<T> & {\n name: Exclude<N, \"*\">;\n /**\n * @deprecated Use `available` instead.\n */\n disabled?: boolean;\n available?: FrontendActionAvailability;\n pairedAction?: string;\n followUp?: boolean;\n} & (\n | {\n render?:\n | string\n | (T extends []\n ? (\n props: ActionRenderPropsNoArgs<T>,\n ) => string | React.ReactElement\n : (props: ActionRenderProps<T>) => string | React.ReactElement);\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: never;\n renderAndWaitForResponse?: never;\n }\n | {\n render?: never;\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n renderAndWaitForResponse?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n handler?: never;\n }\n );\n\nexport type CatchAllFrontendAction = {\n name: \"*\";\n render: (props: CatchAllActionRenderProps<any>) => React.ReactElement;\n};\n\nexport type RenderFunctionStatus = ActionRenderProps<any>[\"status\"];\n\nexport function processActionsForRuntimeRequest(\n actions: FrontendAction<any>[],\n) {\n const filteredActions = actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled &&\n action.disabled !== true &&\n action.name !== \"*\" &&\n action.available != \"frontend\" &&\n !action.pairedAction,\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined =\n ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(\n actionParametersToJsonSchema(action.parameters || []),\n ),\n available,\n };\n });\n return filteredActions;\n}\n","/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/v1/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/v1/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/src/v1.x/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport {\n FrontendAction,\n processActionsForRuntimeRequest,\n} from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n private forwardedParameters?: ForwardedParametersInput;\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n this.forwardedParameters = config.forwardedParameters;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions\n ? Object.assign({}, context.actions)\n : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString =\n (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString(\n [],\n defaultCopilotContextCategories,\n );\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(\n filterAgentStateMessages(messages),\n ),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n toolChoice: \"required\",\n ...(this.forwardedParameters ?? {}),\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(\n contextString: string,\n instructions: string,\n): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;AAIA,MAAa,0BAA0B;CACrC,aAAa;CACb,aAAa;CACd;;;;ACHD,SAAgB,sBAG4D;CAC1E,MAAM,iBAAiBA,qBAAmB;AAE1C,QAAO,aACJ,SAAqB,aAAyB;AAC7C,MAAI,CAAC,SAAS,WAAW,OAAQ,QAAO;EAExC,MAAM,WAAW,QAAQ,UAAU;AACnC,MAAI,CAAC,SAAU,QAAO;EAEtB,MAAM,cAAc,UAAU,MAC3B,MAAM,EAAE,SAAS,UAAU,EAAE,eAAe,SAAS,GACvD;AAED,eACE,eAAe;GACb;GACA;GACD,CAAC;IAEN,CAAC,eAAe,CACjB;;;;;ACqSH,SAAgB,uBAAuB,EACrC,aACA,cACA,iBACA,kBACA,qBACyB,EAAE,EAAwB;CACnD,MAAM,EAAE,eAAe,eAAe;CACtC,MAAM,EAAE,UAAU,iBAAiB,mBAAmB;CACtD,MAAM,iBAAiB,6BAA6B;CACpD,MAAM,CAAC,gBAAgB,qBAAqB,SAAS,MAAM;CAG3D,MAAM,kBAAkB,gBAAgB,WAAW;CACnD,MAAM,EAAE,UAAU,SAAS,EAAE,SAAS,iBAAiB,CAAC;AAExD,iBAAgB;EACd,MAAM,UAAU,OAAO,UAAyB;AAC9C,qBAAkB,MAAM;AACxB,OAAI;AACF,UAAM,WAAW,aAAa,EAAE,OAAO,CAAC;AACxC,sBAAkB,KAAK;YAChB,OAAO;AACd,QAAI,iBAAiB,gCAAgC,OAGnD,SAAQ,MAAM,oCAAoC,MAAM;;;AAK9D,MACE,SACA,gBAAgB,YAChB,MAAM,aAAa,eAAe,YAClC,WAAW,4BACT,sCAAsC,WACxC;AACA,SAAM,WAAW,eAAe;AAChC,WAAQ,MAAM;;AAEhB,eAAa;IACZ;EACD,gBAAgB;EAChB;EACA;EACA,WAAW;EACX;EACD,CAAC;AAEF,iBAAgB;AACd,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7C,KAAK,QAAQ,iBAAiB;GAC9B,cAAc,QAAQ,iBAAiB;GACvC,SAAS,QAAQ,iBAAiB;GAClC,aAAa,QAAQ,iBAAiB;GACvC,CAAC,CAGC,wBAAwB;GACvB,MAAM;IACJ,UAAU;KACR,SAAS,gCAAgC,OAAO,OAAO,QAAQ,CAAC;KAChE,KAAK,OAAO,SAAS;KACtB;IACD,UAAU,0BACR,yBAAyB,SAAS,CACnC;IACD,UAAU,EACR,aAAa,mBAAmB,MACjC;IACD,qBAAqB;KAEnB,YAAY;KACZ,GAAI,KAAK,uBAAuB,EAAE;KACnC;IACF;GACD,YAAY,QAAQ,iBAAiB;GACtC,CAAC,CACD,WAAW;EAEd,MAAM,sBAAsB,QAAQ,uBAAuB,QAAQ;EACnE,MAAM,gBAAgB,2BACpB,SAAS,MAAM,yBAAyB,YAAY,EAAE,CACvD,CAAC,QAAQ,MAAmC,EAAE,0BAA0B,CAAC;AAE1E,OAAK,MAAM,gBAAgB,cACzB,OAAM,oBAAoB;GACxB;GACA,MAAM,aAAa;GACnB,MAAM,aAAa;GACpB,CAAC;;;AAKR,SAAS,kBACP,eACA,cACQ;AACR,QAAO;;;;;;;;EAQP,cAAc;;;;;;;;;;;;EAYd,aAAa"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["useRenderToolCall","DeprecatedGqlMessage"],"sources":["../src/utils/suggestions-constants.ts","../src/hooks/use-lazy-tool-renderer.tsx","../src/hooks/use-copilot-chat_internal.ts","../src/hooks/use-copilot-chat.ts","../src/hooks/use-copilot-chat-headless_c.ts","../src/hooks/use-frontend-tool.ts","../src/hooks/use-render-tool-call.ts","../src/hooks/use-human-in-the-loop.ts","../src/hooks/use-copilot-action.ts","../src/hooks/use-coagent-state-render.ts","../src/hooks/use-make-copilot-document-readable.ts","../src/hooks/use-copilot-readable.ts","../src/hooks/use-agent-nodename.ts","../src/hooks/use-coagent.ts","../src/hooks/use-copilot-runtime-client.ts","../src/hooks/use-copilot-authenticated-action.ts","../src/hooks/use-langgraph-interrupt.ts","../src/hooks/use-copilot-additional-instructions.ts","../src/hooks/use-default-tool.ts","../src/hooks/use-copilot-chat-suggestions.tsx","../src/types/frontend-action.ts","../src/lib/copilot-task.ts"],"sourcesContent":["/**\n * Constants for suggestions retry logic\n */\n\nexport const SUGGESTION_RETRY_CONFIG = {\n MAX_RETRIES: 3,\n COOLDOWN_MS: 5000, // 5 seconds\n} as const;\n","import { 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 React, {\n useRef,\n useEffect,\n useCallback,\n useMemo,\n useState,\n createElement,\n} from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { Message } from \"@copilotkit/shared\";\nimport {\n gqlToAGUI,\n Message as DeprecatedGqlMessage,\n} from \"@copilotkit/runtime-client-gql\";\nimport {\n useAgent,\n useCopilotChatConfiguration,\n useCopilotKit,\n useRenderCustomMessages,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport {\n Suggestion,\n CopilotKitCoreRuntimeConnectionStatus,\n} from \"@copilotkitnext/core\";\nimport { useLazyToolRenderer } from \"./use-lazy-tool-renderer\";\nimport {\n AbstractAgent,\n AGUIConnectNotImplementedError,\n HttpAgent,\n} from \"@ag-ui/client\";\nimport {\n CoAgentStateRenderBridge,\n type CoAgentStateRenderBridgeProps,\n} from \"./use-coagent-state-render-bridge\";\n\n/**\n * The type of suggestions to use in the chat.\n *\n * `auto` - Suggestions are generated automatically.\n * `manual` - Suggestions are controlled programmatically.\n * `SuggestionItem[]` - Static suggestions array.\n */\nexport type ChatSuggestions =\n | \"auto\"\n | \"manual\"\n | Omit<Suggestion, \"isLoading\">[];\n\nexport interface AppendMessageOptions {\n /**\n * Whether to run the chat completion after appending the message. Defaults to `true`.\n */\n followUp?: boolean;\n /**\n * Whether to clear the suggestions after appending the message. Defaults to `true`.\n */\n clearSuggestions?: boolean;\n}\n\nexport interface OnStopGenerationArguments {\n /**\n * The name of the currently executing agent.\n */\n currentAgentName: string | undefined;\n\n /**\n * The messages in the chat.\n */\n messages: Message[];\n}\n\nexport type OnReloadMessagesArguments = OnStopGenerationArguments & {\n /**\n * The message on which \"regenerate\" was pressed\n */\n messageId: string;\n};\n\nexport type OnStopGeneration = (args: OnStopGenerationArguments) => void;\n\nexport type OnReloadMessages = (args: OnReloadMessagesArguments) => void;\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Initial messages to populate the chat with.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n\n /**\n * Disables inclusion of CopilotKit’s default system message. When true, no system message is sent (this also suppresses any custom message from <code>makeSystemMessage</code>).\n */\n disableSystemMessage?: boolean;\n /**\n * Controls the behavior of suggestions in the chat interface.\n *\n * `auto` (default) - Suggestions are generated automatically:\n * - When the chat is first opened (empty state)\n * - After each message exchange completes\n * - Uses configuration from `useCopilotChatSuggestions` hooks\n *\n * `manual` - Suggestions are controlled programmatically:\n * - Use `setSuggestions()` to set custom suggestions\n * - Use `generateSuggestions()` to trigger AI generation\n * - Access via `useCopilotChat` hook\n *\n * `SuggestionItem[]` - Static suggestions array:\n * - Always shows the same suggestions\n * - No AI generation involved\n */\n suggestions?: ChatSuggestions;\n\n onInProgress?: (isLoading: boolean) => void;\n onSubmitMessage?: (messageContent: string) => Promise<void> | void;\n onStopGeneration?: OnStopGeneration;\n onReloadMessages?: OnReloadMessages;\n}\n\nexport interface MCPServerConfig {\n endpoint: string;\n apiKey?: string;\n}\n\n// Old suggestion item interface, for returning from useCopilotChatInternal\ninterface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport interface UseCopilotChatReturn {\n /**\n * @deprecated use `messages` instead, this is an old non ag-ui version of the messages\n * Array of messages currently visible in the chat interface\n *\n * This is the visible messages, not the raw messages from the runtime client.\n */\n visibleMessages: DeprecatedGqlMessage[];\n\n /**\n * The messages that are currently in the chat in AG-UI format.\n */\n messages: Message[];\n\n /** @deprecated use `sendMessage` in `useCopilotChatHeadless_c` instead. This will be removed in a future major version. */\n appendMessage: (\n message: DeprecatedGqlMessage,\n options?: AppendMessageOptions,\n ) => Promise<void>;\n\n /**\n * Send a new message to the chat\n *\n * ```tsx\n * await sendMessage({\n * id: \"123\",\n * role: \"user\",\n * content: \"Hello, process this request\",\n * });\n * ```\n */\n sendMessage: (\n message: Message,\n options?: AppendMessageOptions,\n ) => Promise<void>;\n\n /**\n * Replace all messages in the chat\n *\n * ```tsx\n * setMessages([\n * { id: \"123\", role: \"user\", content: \"Hello, process this request\" },\n * { id: \"456\", role: \"assistant\", content: \"Hello, I'm the assistant\" },\n * ]);\n * ```\n *\n * **Deprecated** non-ag-ui version:\n *\n * ```tsx\n * setMessages([\n * new TextMessage({\n * content: \"Hello, process this request\",\n * role: gqlRole.User,\n * }),\n * new TextMessage({\n * content: \"Hello, I'm the assistant\",\n * role: gqlRole.Assistant,\n * ]);\n * ```\n *\n */\n setMessages: (messages: Message[] | DeprecatedGqlMessage[]) => void;\n\n /**\n * Remove a specific message by ID\n *\n * ```tsx\n * deleteMessage(\"123\");\n * ```\n */\n deleteMessage: (messageId: string) => void;\n\n /**\n * Regenerate the response for a specific message\n *\n * ```tsx\n * reloadMessages(\"123\");\n * ```\n */\n reloadMessages: (messageId: string) => Promise<void>;\n\n /**\n * Stop the current message generation\n *\n * ```tsx\n * if (isLoading) {\n * stopGeneration();\n * }\n * ```\n */\n stopGeneration: () => void;\n\n /**\n * Clear all messages and reset chat state\n *\n * ```tsx\n * reset();\n * console.log(messages); // []\n * ```\n */\n reset: () => void;\n\n /**\n * Whether the chat is currently generating a response\n *\n * ```tsx\n * if (isLoading) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isLoading: boolean;\n\n /**\n * Whether the chat agent is available to generate responses\n *\n * ```tsx\n * if (isAvailable) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isAvailable: boolean;\n\n /** Manually trigger chat completion (advanced usage) */\n runChatCompletion: () => Promise<Message[]>;\n\n /** MCP (Model Context Protocol) server configurations */\n mcpServers: MCPServerConfig[];\n\n /** Update MCP server configurations */\n setMcpServers: (mcpServers: MCPServerConfig[]) => void;\n\n /**\n * Current suggestions array\n * Use this to read the current suggestions or in conjunction with setSuggestions for manual control\n */\n suggestions: Suggestion[];\n\n /**\n * Manually set suggestions\n * Useful for manual mode or custom suggestion workflows\n */\n setSuggestions: (suggestions: Omit<Suggestion, \"isLoading\">[]) => void;\n\n /**\n * Trigger AI-powered suggestion generation\n * Uses configurations from useCopilotChatSuggestions hooks\n * Respects global debouncing - only one generation can run at a time\n *\n * ```tsx\n * generateSuggestions();\n * console.log(suggestions); // [suggestion1, suggestion2, suggestion3]\n * ```\n */\n generateSuggestions: () => Promise<void>;\n\n /**\n * Clear all current suggestions\n * Also resets suggestion generation state\n */\n resetSuggestions: () => void;\n\n /** Whether suggestions are currently being generated */\n isLoadingSuggestions: boolean;\n\n /** Interrupt content for human-in-the-loop workflows */\n interrupt: string | React.ReactElement | null;\n\n agent?: ReturnType<typeof useAgent>[\"agent\"];\n\n threadId?: string;\n}\n\nexport function useCopilotChatInternal({\n suggestions,\n onInProgress,\n onSubmitMessage,\n onStopGeneration,\n onReloadMessages,\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const { copilotkit } = useCopilotKit();\n const { threadId, agentSession } = useCopilotContext();\n const existingConfig = useCopilotChatConfiguration();\n const [agentAvailable, setAgentAvailable] = useState(false);\n\n // Apply priority: props > existing config > defaults\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const { agent } = useAgent({ agentId: resolvedAgentId });\n\n useEffect(() => {\n let detached = false;\n\n // Create a fresh AbortController so we can cancel the HTTP request on cleanup.\n // Mirrors the V2 CopilotChat pattern: HttpAgent uses abortController.signal in\n // its fetch config. connectAgent() does NOT create a new AbortController\n // automatically, so we must set one before connecting.\n const connectAbortController = new AbortController();\n if (agent instanceof HttpAgent) {\n agent.abortController = connectAbortController;\n }\n\n const connect = async (agent: AbstractAgent) => {\n setAgentAvailable(false);\n try {\n await copilotkit.connectAgent({ agent });\n // Guard against setting state after cleanup (e.g. React StrictMode unmount)\n if (!detached) {\n setAgentAvailable(true);\n }\n } catch (error) {\n // Ignore errors from aborted connections (e.g. React StrictMode cleanup)\n if (detached) return;\n if (error instanceof AGUIConnectNotImplementedError) {\n // connect not implemented, ignore\n } else {\n console.error(\"CopilotChat: connectAgent failed\", error);\n // Error will be reported through subscription\n }\n }\n };\n if (\n agent &&\n existingConfig?.threadId &&\n agent.threadId !== existingConfig.threadId &&\n copilotkit.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ) {\n agent.threadId = existingConfig.threadId;\n connect(agent);\n }\n return () => {\n // Abort the HTTP request and detach the active run.\n // This is critical for React StrictMode which unmounts+remounts in dev,\n // preventing duplicate /connect requests from reaching the server.\n detached = true;\n connectAbortController.abort();\n agent?.detachActiveRun();\n };\n }, [\n existingConfig?.threadId,\n agent,\n copilotkit,\n copilotkit.runtimeConnectionStatus,\n resolvedAgentId,\n ]);\n\n useEffect(() => {\n onInProgress?.(Boolean(agent?.isRunning));\n }, [agent?.isRunning, onInProgress]);\n\n // Subscribe to copilotkit.interruptElement so the v1 return type stays\n // reactive. The element is published by useInterrupt (v2) when user code\n // calls useLangGraphInterrupt({ render, ... }).\n const [interrupt, setInterrupt] = useState<React.ReactElement | null>(null);\n useEffect(() => {\n setInterrupt(copilotkit.interruptElement);\n const subscription = copilotkit.subscribe({\n onInterruptElementChanged: ({ interruptElement }) => {\n setInterrupt(interruptElement);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const reset = () => {\n agent?.setMessages([]);\n agent?.setState(null);\n };\n\n const deleteMessage = useCallback(\n (messageId: string) => {\n const filteredMessages = (agent?.messages ?? []).filter(\n (message) => message.id !== messageId,\n );\n agent?.setMessages(filteredMessages);\n },\n [agent?.setMessages, agent?.messages],\n );\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const currentSuggestions = useSuggestions({ agentId: resolvedAgentId });\n\n const reload = useAsyncCallback(\n async (reloadMessageId: string): Promise<void> => {\n if (!agent) return;\n const messages = agent?.messages ?? [];\n const isLoading = agent.isRunning;\n if (isLoading || messages.length === 0) {\n return;\n }\n\n const reloadMessageIndex = messages.findIndex(\n (msg) => msg.id === reloadMessageId,\n );\n if (reloadMessageIndex === -1) {\n console.warn(`Message with id ${reloadMessageId} not found`);\n return;\n }\n\n const reloadMessageRole = messages[reloadMessageIndex].role;\n if (reloadMessageRole !== \"assistant\") {\n console.warn(\n `Regenerate cannot be performed on ${reloadMessageRole} role`,\n );\n return;\n }\n let historyCutoff: Message[] = [messages[0]];\n\n if (messages.length > 2 && reloadMessageIndex !== 0) {\n // message to regenerate from is now first.\n // Work backwards to find the first the closest user message\n const lastUserMessageBeforeRegenerate = messages\n .slice(0, reloadMessageIndex)\n .reverse()\n .find((msg) => msg.role === \"user\");\n\n if (!lastUserMessageBeforeRegenerate) {\n historyCutoff = [messages[0]];\n } else {\n const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(\n (msg) => msg.id === lastUserMessageBeforeRegenerate.id,\n );\n // Include the user message, remove everything after it\n historyCutoff = messages.slice(\n 0,\n indexOfLastUserMessageBeforeRegenerate + 1,\n );\n }\n } else if (messages.length > 2 && reloadMessageIndex === 0) {\n historyCutoff = [messages[0], messages[1]];\n }\n\n agent?.setMessages(historyCutoff);\n\n if (agent) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed during reload\", error);\n // Error will be reported through subscription\n }\n }\n return;\n },\n [\n agent?.messages.length,\n agent?.isRunning,\n agent?.setMessages,\n copilotkit?.runAgent,\n ],\n );\n\n const latestSendMessageFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n if (!agent) return;\n const followUp = options?.followUp ?? true;\n if (options?.clearSuggestions) {\n copilotkit.clearSuggestions(resolvedAgentId);\n }\n\n // Call onSubmitMessage BEFORE adding message and running agent\n // This allows users to perform actions (e.g., open chat window) before agent starts processing\n if (onSubmitMessage) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : message.content && \"text\" in message.content\n ? message.content.text\n : message.content && \"filename\" in message.content\n ? message.content.filename\n : \"\";\n try {\n await onSubmitMessage(content);\n } catch (error) {\n console.error(\"Error in onSubmitMessage:\", error);\n }\n }\n\n agent?.addMessage(message);\n if (followUp) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\n // Error will be reported through subscription\n }\n }\n },\n [agent, copilotkit, resolvedAgentId, onSubmitMessage],\n );\n\n const latestAppendFunc = useAsyncCallback(\n async (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => {\n return latestSendMessageFunc(gqlToAGUI([message])[0], options);\n },\n [latestSendMessageFunc],\n );\n\n const latestSetMessagesFunc = useCallback(\n (messages: Message[] | DeprecatedGqlMessage[]) => {\n if (\n messages.every((message) => message instanceof DeprecatedGqlMessage)\n ) {\n return agent?.setMessages?.(gqlToAGUI(messages));\n }\n return agent?.setMessages?.(messages);\n },\n [agent?.setMessages, agent],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(\n async (messageId: string) => {\n onReloadMessages?.({\n messageId,\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return await latestReload.current(messageId);\n },\n [latestReload, agent, onReloadMessages],\n );\n\n const latestStopFunc = useCallback(() => {\n onStopGeneration?.({\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return agent?.abortRun?.();\n }, [onStopGeneration, agent]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n const lazyToolRendered = useLazyToolRenderer();\n const renderCustomMessage = useRenderCustomMessages();\n const legacyCustomMessageRenderer = useLegacyCoagentRenderer({\n copilotkit,\n agent,\n agentId: resolvedAgentId,\n threadId: existingConfig?.threadId ?? threadId,\n });\n const allMessages = agent?.messages ?? [];\n const resolvedMessages = useMemo(() => {\n let processedMessages = allMessages.map((message) => {\n if (message.role !== \"assistant\") {\n return message;\n }\n\n const lazyRendered = lazyToolRendered(message, allMessages);\n if (lazyRendered) {\n const renderedGenUi = lazyRendered();\n if (renderedGenUi) {\n return { ...message, generativeUI: () => renderedGenUi };\n }\n }\n\n const bridgeRenderer =\n legacyCustomMessageRenderer || renderCustomMessage\n ? () => {\n if (legacyCustomMessageRenderer) {\n return legacyCustomMessageRenderer({\n message,\n position: \"before\",\n });\n }\n try {\n return (\n renderCustomMessage?.({ message, position: \"before\" }) ?? null\n );\n } catch (error) {\n console.warn(\n \"[CopilotKit] renderCustomMessages failed, falling back to legacy renderer\",\n error,\n );\n return null;\n }\n }\n : null;\n\n if (bridgeRenderer) {\n // Attach a position so react-ui can render the custom UI above the assistant content.\n return {\n ...message,\n generativeUI: bridgeRenderer,\n generativeUIPosition: \"before\" as const,\n };\n }\n return message;\n });\n\n const hasAssistantMessages = processedMessages.some(\n (msg) => msg.role === \"assistant\",\n );\n const canUseCustomRenderer = Boolean(\n renderCustomMessage && copilotkit?.getAgent?.(resolvedAgentId),\n );\n const placeholderRenderer = legacyCustomMessageRenderer\n ? legacyCustomMessageRenderer\n : canUseCustomRenderer\n ? renderCustomMessage\n : null;\n\n const shouldRenderPlaceholder =\n Boolean(agent?.isRunning) ||\n Boolean(agent?.state && Object.keys(agent.state).length);\n\n const effectiveThreadId = threadId ?? agent?.threadId ?? \"default\";\n let latestUserIndex = -1;\n for (let i = processedMessages.length - 1; i >= 0; i -= 1) {\n if (processedMessages[i].role === \"user\") {\n latestUserIndex = i;\n break;\n }\n }\n const latestUserMessageId =\n latestUserIndex >= 0 ? processedMessages[latestUserIndex].id : undefined;\n const currentRunId = latestUserMessageId\n ? copilotkit.getRunIdForMessage(\n resolvedAgentId,\n effectiveThreadId,\n latestUserMessageId,\n ) || `pending:${latestUserMessageId}`\n : undefined;\n const hasAssistantForCurrentRun =\n latestUserIndex >= 0\n ? processedMessages\n .slice(latestUserIndex + 1)\n .some((msg) => msg.role === \"assistant\")\n : hasAssistantMessages;\n\n // Insert a placeholder assistant message so state snapshots can render before any\n // assistant text exists for the current run.\n if (\n placeholderRenderer &&\n shouldRenderPlaceholder &&\n !hasAssistantForCurrentRun\n ) {\n const placeholderId = currentRunId\n ? `coagent-state-render-${resolvedAgentId}-${currentRunId}`\n : `coagent-state-render-${resolvedAgentId}`;\n const placeholderMessage: Message = {\n id: placeholderId,\n role: \"assistant\",\n content: \"\",\n name: \"coagent-state-render\",\n runId: currentRunId,\n };\n processedMessages = [\n ...processedMessages,\n {\n ...placeholderMessage,\n generativeUIPosition: \"before\" as const,\n generativeUI: () =>\n placeholderRenderer({\n message: placeholderMessage,\n position: \"before\",\n }),\n } as Message,\n ];\n }\n\n return processedMessages;\n }, [\n agent?.messages,\n lazyToolRendered,\n allMessages,\n renderCustomMessage,\n legacyCustomMessageRenderer,\n resolvedAgentId,\n copilotkit,\n agent?.isRunning,\n agent?.state,\n ]);\n\n const renderedSuggestions = useMemo(() => {\n if (Array.isArray(suggestions)) {\n return {\n suggestions: suggestions.map((s) => ({ ...s, isLoading: false })),\n isLoading: false,\n };\n }\n return currentSuggestions;\n }, [suggestions, currentSuggestions]);\n\n // @ts-ignore\n return {\n messages: resolvedMessages,\n sendMessage: latestSendMessageFunc,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n isAvailable: agentAvailable,\n isLoading: Boolean(agent?.isRunning),\n // mcpServers,\n // setMcpServers,\n suggestions: renderedSuggestions.suggestions,\n setSuggestions: (suggestions: Omit<Suggestion, \"isLoading\">[]) =>\n copilotkit.addSuggestionsConfig({ suggestions }),\n generateSuggestions: async () =>\n copilotkit.reloadSuggestions(resolvedAgentId),\n resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),\n isLoadingSuggestions: renderedSuggestions.isLoading,\n interrupt,\n agent,\n threadId,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\ntype LegacyRenderParams = {\n message: Message;\n position: \"before\" | \"after\";\n};\n\ntype LegacyRenderer = ((args: LegacyRenderParams) => any) | null;\n\nfunction useLegacyCoagentRenderer({\n copilotkit,\n agent,\n agentId,\n threadId,\n}: {\n copilotkit: ReturnType<typeof useCopilotKit>[\"copilotkit\"];\n agent?: AbstractAgent;\n agentId: string;\n threadId?: string;\n}): LegacyRenderer {\n return useMemo(() => {\n if (!copilotkit || !agent) {\n return null;\n }\n\n return ({ message, position }: LegacyRenderParams) => {\n const effectiveThreadId = threadId ?? agent.threadId ?? \"default\";\n const providedRunId = (message as any).runId as string | undefined;\n const existingRunId = providedRunId\n ? providedRunId\n : copilotkit.getRunIdForMessage(agentId, effectiveThreadId, message.id);\n const runId = existingRunId || `pending:${message.id}`;\n const messageIndex = Math.max(\n agent.messages.findIndex((msg) => msg.id === message.id),\n 0,\n );\n\n const bridgeProps: CoAgentStateRenderBridgeProps = {\n message: message as any,\n position,\n runId,\n messageIndex,\n messageIndexInRun: 0,\n numberOfMessagesInRun: 1,\n agentId,\n stateSnapshot: (message as any).state,\n };\n\n return createElement(CoAgentStateRenderBridge, bridgeProps) as any;\n };\n }, [agent, agentId, copilotkit, threadId]);\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n","/**\n * `useCopilotChat` is a lightweight React hook for headless chat interactions.\n * Perfect for controlling the prebuilt chat components programmatically.\n *\n * **Open Source Friendly** - Works without requiring a free public license key.\n *\n * <Callout title=\"Looking for fully headless UI?\">\n * Get started with [useCopilotChatHeadless_c](https://docs.copilotkit.ai/reference/v1/hooks/useCopilotChatHeadless_c).\n * </Callout>\n *\n * ## Use Cases\n *\n * - **Programmatic Messaging**: Send messages without displaying chat UI\n * - **Programmatic control**: Control prebuilt component programmatically\n * - **Background Operations**: Trigger AI interactions in the background\n * - **Fire-and-Forget**: Send messages without needing to read responses\n *\n * ## Usage\n *\n * ```tsx\n * import { TextMessage, MessageRole } from \"@copilotkit/runtime-client-gql\";\n *\n * const { appendMessage } = useCopilotChat();\n *\n * // Example usage without naming conflicts\n * const handleSendMessage = async (content: string) => {\n * await appendMessage(\n * new TextMessage({\n * role: MessageRole.User,\n * content,\n * })\n * );\n * };\n * ```\n *\n * ## Return Values\n * The following properties are returned from the hook:\n *\n * <PropertyReference name=\"visibleMessages\" type=\"DeprecatedGqlMessage[]\" deprecated>\n * Array of messages in old non-AG-UI format, use for compatibility only\n * </PropertyReference>\n *\n * <PropertyReference name=\"appendMessage\" type=\"(message: DeprecatedGqlMessage, options?) => Promise<void>\" deprecated>\n * Append message using old format, use `sendMessage` instead\n * </PropertyReference>\n *\n * <PropertyReference name=\"reloadMessages\" type=\"(messageId: string) => Promise<void>\">\n * Regenerate the response for a specific message by ID\n * </PropertyReference>\n *\n * <PropertyReference name=\"stopGeneration\" type=\"() => void\">\n * Stop the current message generation process\n * </PropertyReference>\n *\n * <PropertyReference name=\"reset\" type=\"() => void\">\n * Clear all messages and reset chat state completely\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoading\" type=\"boolean\">\n * Whether the chat is currently generating a response\n * </PropertyReference>\n *\n * <PropertyReference name=\"runChatCompletion\" type=\"() => Promise<Message[]>\">\n * Manually trigger chat completion for advanced usage\n * </PropertyReference>\n *\n * <PropertyReference name=\"mcpServers\" type=\"MCPServerConfig[]\">\n * Array of Model Context Protocol server configurations\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMcpServers\" type=\"(servers: MCPServerConfig[]) => void\">\n * Update MCP server configurations for enhanced context\n * </PropertyReference>\n */\n\nimport {\n UseCopilotChatOptions,\n useCopilotChatInternal,\n UseCopilotChatReturn as UseCopilotChatReturnInternal,\n} from \"./use-copilot-chat_internal\";\n\n// Create a type that excludes message-related properties from the internal type\nexport type UseCopilotChatReturn = Omit<\n UseCopilotChatReturnInternal,\n | \"messages\"\n | \"sendMessage\"\n | \"suggestions\"\n | \"setSuggestions\"\n | \"generateSuggestions\"\n | \"isLoadingSuggestions\"\n | \"resetSuggestions\"\n | \"interrupt\"\n | \"setMessages\"\n | \"deleteMessage\"\n>;\n\n/**\n * A lightweight React hook for headless chat interactions.\n * Perfect for programmatic messaging, background operations, and custom UI implementations.\n *\n * **Open Source Friendly** - Works without requiring a `publicApiKey`.\n */\n// TODO: Do we need this? If so, does it work properly? test.\nexport function useCopilotChat(\n options: UseCopilotChatOptions = {},\n): UseCopilotChatReturn {\n const {\n visibleMessages,\n appendMessage,\n reloadMessages,\n stopGeneration,\n reset,\n isLoading,\n isAvailable,\n runChatCompletion,\n mcpServers,\n setMcpServers,\n } = useCopilotChatInternal(options);\n\n return {\n visibleMessages,\n appendMessage,\n reloadMessages,\n stopGeneration,\n reset,\n isLoading,\n isAvailable,\n runChatCompletion,\n mcpServers,\n setMcpServers,\n };\n}\n","/**\n * `useCopilotChatHeadless_c` is for building fully custom UI (headless UI) implementations.\n *\n * <Callout title=\"This is a premium-only feature\">\n * Sign up for free on [Copilot Cloud](https://cloud.copilotkit.ai) to get your public license key or read more about <a href=\"/premium/overview\">premium features</a>.\n *\n * Usage is generous, **free** to get started, and works with **either self-hosted or Copilot Cloud** environments.\n * </Callout>\n *\n * ## Key Features\n *\n * - **Fully headless**: Build your own fully custom UI's for your agentic applications.\n * - **Advanced Suggestions**: Direct access to suggestions array with full control\n * - **Interrupt Handling**: Support for advanced interrupt functionality\n * - **MCP Server Support**: Model Context Protocol server configurations\n * - **Chat Controls**: Complete set of chat management functions\n * - **Loading States**: Comprehensive loading state management\n *\n *\n * ## Usage\n *\n * ### Basic Setup\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n * import { useCopilotChatHeadless_c } from \"@copilotkit/react-core\";\n *\n * export function App() {\n * return (\n * <CopilotKit publicApiKey=\"your-free-public-license-key\">\n * <YourComponent />\n * </CopilotKit>\n * );\n * }\n *\n * export function YourComponent() {\n * const { messages, sendMessage, isLoading } = useCopilotChatHeadless_c();\n *\n * const handleSendMessage = async () => {\n * await sendMessage({\n * id: \"123\",\n * role: \"user\",\n * content: \"Hello World\",\n * });\n * };\n *\n * return (\n * <div>\n * {messages.map(msg => <div key={msg.id}>{msg.content}</div>)}\n * <button onClick={handleSendMessage} disabled={isLoading}>\n * Send Message\n * </button>\n * </div>\n * );\n * }\n * ```\n *\n * ### Working with Suggestions\n *\n * ```tsx\n * import { useCopilotChatHeadless_c, useCopilotChatSuggestions } from \"@copilotkit/react-core\";\n *\n * export function SuggestionExample() {\n * const {\n * suggestions,\n * setSuggestions,\n * generateSuggestions,\n * isLoadingSuggestions\n * } = useCopilotChatHeadless_c();\n *\n * // Configure AI suggestion generation\n * useCopilotChatSuggestions({\n * instructions: \"Suggest helpful actions based on the current context\",\n * maxSuggestions: 3\n * });\n *\n * return (\n * <div>\n * {suggestions.map(suggestion => (\n * <button key={suggestion.title}>{suggestion.title}</button>\n * ))}\n * <button onClick={generateSuggestions} disabled={isLoadingSuggestions}>\n * Generate Suggestions\n * </button>\n * </div>\n * );\n * }\n * ```\n *\n * ## Return Values\n * The following properties are returned from the hook:\n *\n * <PropertyReference name=\"messages\" type=\"Message[]\">\n * The messages currently in the chat in AG-UI format\n * </PropertyReference>\n *\n * <PropertyReference name=\"sendMessage\" type=\"(message: Message, options?) => Promise<void>\">\n * Send a new message to the chat and trigger AI response\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMessages\" type=\"(messages: Message[] | DeprecatedGqlMessage[]) => void\">\n * Replace all messages in the chat with new array\n * </PropertyReference>\n *\n * <PropertyReference name=\"deleteMessage\" type=\"(messageId: string) => void\">\n * Remove a specific message by ID from the chat\n * </PropertyReference>\n *\n * <PropertyReference name=\"reloadMessages\" type=\"(messageId: string) => Promise<void>\">\n * Regenerate the response for a specific message by ID\n * </PropertyReference>\n *\n * <PropertyReference name=\"stopGeneration\" type=\"() => void\">\n * Stop the current message generation process\n * </PropertyReference>\n *\n * <PropertyReference name=\"reset\" type=\"() => void\">\n * Clear all messages and reset chat state completely\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoading\" type=\"boolean\">\n * Whether the chat is currently generating a response\n * </PropertyReference>\n *\n * <PropertyReference name=\"runChatCompletion\" type=\"() => Promise<Message[]>\">\n * Manually trigger chat completion for advanced usage\n * </PropertyReference>\n *\n * <PropertyReference name=\"mcpServers\" type=\"MCPServerConfig[]\">\n * Array of Model Context Protocol server configurations\n * </PropertyReference>\n *\n * <PropertyReference name=\"setMcpServers\" type=\"(servers: MCPServerConfig[]) => void\">\n * Update MCP server configurations for enhanced context\n * </PropertyReference>\n *\n * <PropertyReference name=\"suggestions\" type=\"SuggestionItem[]\">\n * Current suggestions array for reading or manual control\n * </PropertyReference>\n *\n * <PropertyReference name=\"setSuggestions\" type=\"(suggestions: SuggestionItem[]) => void\">\n * Manually set suggestions for custom workflows\n * </PropertyReference>\n *\n * <PropertyReference name=\"generateSuggestions\" type=\"() => Promise<void>\">\n * Trigger AI-powered suggestion generation using configured settings\n * </PropertyReference>\n *\n * <PropertyReference name=\"resetSuggestions\" type=\"() => void\">\n * Clear all current suggestions and reset generation state\n * </PropertyReference>\n *\n * <PropertyReference name=\"isLoadingSuggestions\" type=\"boolean\">\n * Whether suggestions are currently being generated\n * </PropertyReference>\n *\n * <PropertyReference name=\"interrupt\" type=\"string | React.ReactElement | null\">\n * Interrupt content for human-in-the-loop workflows\n * </PropertyReference>\n */\nimport { useEffect } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport {\n useCopilotChatInternal,\n defaultSystemMessage,\n UseCopilotChatOptions as UseCopilotChatOptions_c,\n UseCopilotChatReturn as UseCopilotChatReturn_c,\n MCPServerConfig,\n} from \"./use-copilot-chat_internal\";\n\nimport {\n ErrorVisibility,\n Severity,\n CopilotKitError,\n CopilotKitErrorCode,\n styledConsole,\n} from \"@copilotkit/shared\";\n\n// Non-functional fallback implementation\nconst createNonFunctionalReturn = (): UseCopilotChatReturn_c => ({\n visibleMessages: [],\n messages: [],\n sendMessage: async () => {},\n appendMessage: async () => {},\n setMessages: () => {},\n deleteMessage: () => {},\n reloadMessages: async () => {},\n stopGeneration: () => {},\n reset: () => {},\n isLoading: false,\n isAvailable: false,\n runChatCompletion: async () => [],\n mcpServers: [],\n setMcpServers: () => {},\n suggestions: [],\n setSuggestions: () => {},\n generateSuggestions: async () => {},\n resetSuggestions: () => {},\n isLoadingSuggestions: false,\n interrupt: null,\n});\n/**\n * Enterprise React hook that provides complete chat functionality for fully custom UI implementations.\n * Includes all advanced features like direct message access, suggestions array, interrupt handling, and MCP support.\n *\n * **Requires a publicApiKey** - Sign up for free at https://cloud.copilotkit.ai/\n *\n * @param options - Configuration options for the chat\n * @returns Complete chat interface with all enterprise features\n *\n * @example\n * ```tsx\n * const { messages, sendMessage, suggestions, interrupt } = useCopilotChatHeadless_c();\n * ```\n */\nfunction useCopilotChatHeadless_c(\n options: UseCopilotChatOptions_c = {},\n): UseCopilotChatReturn_c {\n const { copilotApiConfig, setBannerError } = useCopilotContext();\n\n // Check if publicApiKey is available\n const hasPublicApiKey = Boolean(copilotApiConfig.publicApiKey);\n\n // Always call the internal hook (follows rules of hooks)\n const internalResult = useCopilotChatInternal(options);\n\n // Set banner error when no public API key is provided\n useEffect(() => {\n if (!hasPublicApiKey) {\n setBannerError(\n new CopilotKitError({\n message:\n // add link to documentation here\n \"You're using useCopilotChatHeadless_c, a premium-only feature, which offers extensive headless chat capabilities. To continue, you'll need to provide a free public license key.\",\n code: CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,\n severity: Severity.WARNING,\n visibility: ErrorVisibility.BANNER,\n }),\n );\n styledConsole.logCopilotKitPlatformMessage();\n } else {\n setBannerError(null); // Clear banner when API key is provided\n }\n }, [hasPublicApiKey]); // Removed setBannerError dependency\n\n // Return internal result if publicApiKey is available, otherwise return fallback\n if (hasPublicApiKey) {\n return internalResult;\n }\n\n // Return non-functional fallback when no publicApiKey\n return createNonFunctionalReturn();\n}\n\nexport { defaultSystemMessage, useCopilotChatHeadless_c };\nexport type {\n UseCopilotChatOptions_c,\n UseCopilotChatReturn_c,\n MCPServerConfig,\n};\n\nconst noKeyWarning = () => {\n styledConsole.logCopilotKitPlatformMessage();\n};\n","import React, { useEffect, useMemo, useRef } from \"react\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport {\n Parameter,\n getZodParameters,\n MappedParameterTypes,\n} from \"@copilotkit/shared\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport {\n type ReactFrontendTool,\n useFrontendTool as useFrontendToolVNext,\n} from \"@copilotkitnext/react\";\n\ntype FrontendToolOptions<T extends Parameter[] | []> = ReactFrontendTool<\n MappedParameterTypes<T>\n>;\ntype FrontendToolRenderArgs<T extends Parameter[] | []> =\n | {\n name: string;\n args: Partial<MappedParameterTypes<T>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n }\n | {\n name: string;\n args: MappedParameterTypes<T>;\n status: ToolCallStatus.Executing;\n result: undefined;\n }\n | {\n name: string;\n args: MappedParameterTypes<T>;\n status: ToolCallStatus.Complete;\n result: string;\n };\n\nexport type UseFrontendToolArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n} & Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\" | \"handler\" | \"followUp\" | \"render\"\n>;\n\nexport function useFrontendTool<const T extends Parameter[] = []>(\n tool: UseFrontendToolArgs<T>,\n dependencies?: any[],\n) {\n const { name, description, parameters, render, followUp, available } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderRef = useRef<typeof render>(render);\n\n useEffect(() => {\n renderRef.current = render;\n }, [render, ...(dependencies ?? [])]);\n\n const normalizedRender: FrontendToolOptions<T>[\"render\"] | undefined =\n useMemo(() => {\n if (typeof render === \"undefined\") {\n return undefined;\n }\n\n return ((args: FrontendToolRenderArgs<T>) => {\n const currentRender = renderRef.current;\n\n if (typeof currentRender === \"undefined\") {\n return null;\n }\n\n if (typeof currentRender === \"string\") {\n return React.createElement(React.Fragment, null, currentRender);\n }\n\n const renderArgs = {\n ...args,\n result:\n typeof args.result === \"string\"\n ? parseJson(args.result, args.result)\n : args.result,\n } as ActionRenderProps<T>;\n\n const rendered = currentRender(renderArgs);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n }) as FrontendToolOptions<T>[\"render\"];\n }, []);\n\n // Handler ref to avoid stale closures\n const handlerRef = useRef<typeof tool.handler>(tool.handler);\n\n useEffect(() => {\n handlerRef.current = tool.handler;\n }, [tool.handler, ...(dependencies ?? [])]);\n\n const normalizedHandler = tool.handler\n ? (args: MappedParameterTypes<T>) => handlerRef.current?.(args)\n : undefined;\n\n useFrontendToolVNext<MappedParameterTypes<T>>({\n name,\n description,\n parameters: zodParameters,\n handler: normalizedHandler,\n followUp,\n render: normalizedRender,\n available: available === undefined ? undefined : available !== \"disabled\",\n });\n}\n","import { type Parameter, getZodParameters } from \"@copilotkit/shared\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { defineToolCallRenderer, useCopilotKit } from \"@copilotkitnext/react\";\nimport type React from \"react\";\nimport { useEffect, useRef } from \"react\";\nimport {\n type ActionRenderProps,\n type ActionRenderPropsNoArgs,\n ActionRenderPropsWait,\n type FrontendAction,\n} from \"../types\";\n\ntype ToolCallRendererDefinition = Parameters<typeof defineToolCallRenderer>[0];\n\nexport type UseRenderToolCallArgs<T extends Parameter[] | [] = []> = Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\"\n> & {\n available?: \"disabled\" | \"enabled\";\n render: T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => React.ReactElement\n : (props: ActionRenderProps<T>) => React.ReactElement;\n};\n\nexport function useRenderToolCall<const T extends Parameter[] | [] = []>(\n tool: UseRenderToolCallArgs<T>,\n dependencies?: any[],\n) {\n const { copilotkit } = useCopilotKit();\n\n // Track whether we've already added this renderer to avoid duplicates\n const hasAddedRef = useRef(false);\n\n useEffect(() => {\n const { name, parameters, render } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderToolCall =\n name === \"*\"\n ? defineToolCallRenderer({\n name: \"*\",\n render: ((args) => {\n return render({\n ...args,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n })\n : defineToolCallRenderer({\n name,\n args: zodParameters,\n render: ((args) => {\n return render({\n ...args,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n });\n\n // Remove any existing renderer with the same name\n const existingIndex = copilotkit.renderToolCalls.findIndex(\n (r) => r.name === name,\n );\n if (existingIndex !== -1) {\n copilotkit.renderToolCalls.splice(existingIndex, 1);\n }\n\n // Add the new renderer\n copilotkit.renderToolCalls.push(renderToolCall);\n hasAddedRef.current = true;\n\n // Cleanup: remove this renderer when the component unmounts or tool changes\n return () => {\n if (hasAddedRef.current) {\n const index = copilotkit.renderToolCalls.findIndex(\n (r) => r.name === name,\n );\n if (index !== -1) {\n copilotkit.renderToolCalls.splice(index, 1);\n }\n hasAddedRef.current = false;\n }\n };\n }, [tool, ...(dependencies ?? [])]);\n}\n","import {\n ActionRenderProps,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types\";\nimport {\n CopilotKitError,\n CopilotKitErrorCode,\n MappedParameterTypes,\n Parameter,\n getZodParameters,\n parseJson,\n} from \"@copilotkit/shared\";\nimport { useHumanInTheLoop as useHumanInTheLoopVNext } from \"@copilotkitnext/react\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport React, {\n ComponentType,\n FunctionComponent,\n useEffect,\n useRef,\n} from \"react\";\n\ntype HumanInTheLoopOptions = Parameters<typeof useHumanInTheLoopVNext>[0];\ntype HumanInTheLoopRender = HumanInTheLoopOptions[\"render\"];\ntype HumanInTheLoopRenderArgs = HumanInTheLoopRender extends (\n props: infer P,\n) => any\n ? P\n : never;\n\nexport type UseHumanInTheLoopArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n render: FrontendAction<T>[\"renderAndWaitForResponse\"];\n followUp?: FrontendAction<T>[\"followUp\"];\n} & Pick<FrontendAction<T>, \"name\" | \"description\" | \"parameters\">;\n\ntype HitlRendererArgs =\n | {\n name: string;\n description: string;\n args: Partial<Record<string, unknown>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n respond: undefined;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Executing;\n result: undefined;\n respond: (result: unknown) => Promise<void>;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Complete;\n result: string;\n respond: undefined;\n };\ntype HitlRenderer = FunctionComponent<HitlRendererArgs>;\n\nexport function useHumanInTheLoop<const T extends Parameter[] | [] = []>(\n tool: UseHumanInTheLoopArgs<T>,\n dependencies?: any[],\n) {\n const { render, ...toolRest } = tool;\n const { name, description, parameters, followUp } = toolRest;\n const zodParameters = getZodParameters(parameters);\n const renderRef = useRef<HitlRenderer | null>(null);\n\n useEffect(() => {\n renderRef.current = (args: HitlRendererArgs): React.ReactElement | null => {\n if (typeof render === \"string\") {\n return React.createElement(React.Fragment, null, render);\n }\n\n if (!render) {\n return null;\n }\n\n const renderProps: ActionRenderPropsWait<T> = (() => {\n const mappedArgs = args.args as unknown as MappedParameterTypes<T>;\n\n switch (args.status) {\n case ToolCallStatus.InProgress:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: undefined,\n };\n case ToolCallStatus.Executing:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: () => {},\n };\n case ToolCallStatus.Complete:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n result: args.result\n ? parseJson(args.result, args.result)\n : args.result,\n handler: undefined,\n };\n default:\n throw new CopilotKitError({\n code: CopilotKitErrorCode.UNKNOWN,\n message: `Invalid tool call status: ${(args as unknown as { status: string }).status}`,\n });\n }\n })();\n\n const rendered = render(renderProps);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n };\n }, [render, ...(dependencies ?? [])]);\n\n useHumanInTheLoopVNext({\n name,\n description,\n followUp,\n parameters: zodParameters,\n render: ((args: HumanInTheLoopRenderArgs) =>\n renderRef.current?.(args as HitlRendererArgs) ??\n null) as HumanInTheLoopOptions[\"render\"],\n });\n}\n","/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { useEffect, useRef, useState } from \"react\";\nimport { Parameter } from \"@copilotkit/shared\";\nimport {\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport { useFrontendTool, UseFrontendToolArgs } from \"./use-frontend-tool\";\nimport {\n useRenderToolCall,\n UseRenderToolCallArgs,\n} from \"./use-render-tool-call\";\nimport {\n useHumanInTheLoop,\n UseHumanInTheLoopArgs,\n} from \"./use-human-in-the-loop\";\nimport { useCopilotContext } from \"../context\";\n\n// Helper to determine which component and action config to use\nfunction getActionConfig<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n) {\n if (action.name === \"*\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n\n if (\"renderAndWaitForResponse\" in action || \"renderAndWait\" in action) {\n let render = action.render;\n if (!render && \"renderAndWaitForResponse\" in action) {\n // @ts-expect-error -- renderAndWaitForResponse is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWaitForResponse;\n }\n if (!render && \"renderAndWait\" in action) {\n // @ts-expect-error -- renderAndWait is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWait;\n }\n\n return {\n type: \"hitl\" as const,\n action: { ...action, render } as UseHumanInTheLoopArgs<T>,\n };\n }\n\n if (\"available\" in action) {\n if (action.available === \"enabled\" || action.available === \"remote\") {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n if (action.available === \"frontend\" || action.available === \"disabled\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n }\n\n if (\"handler\" in action) {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n\n throw new Error(\"Invalid action configuration\");\n}\n\n/**\n * useCopilotAction is a legacy hook maintained for backwards compatibility.\n *\n * To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),\n * we use a registration pattern:\n * 1. This hook registers the action configuration with the CopilotContext\n * 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper\n * 3. React properly manages hook state since components are rendered, not conditionally called\n *\n * This allows action types to change between renders without corrupting React's hook state.\n */\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const [initialActionConfig] = useState(getActionConfig(action));\n const currentActionConfig = getActionConfig(action);\n\n /**\n * Calling hooks conditionally violates React's Rules of Hooks. This rule exists because\n * React maintains the call stack for hooks like useEffect or useState, and conditionally\n * calling a hook would result in inconsistent call stacks between renders.\n *\n * Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the\n * supplied parameters. In order to avoid breaking React's call stack tracking, while\n * breaking the Rule of Hooks, we use a ref to store the initial action configuration\n * and throw an error if the _configuration_ changes such that we would call a different hook.\n */\n if (initialActionConfig.type !== currentActionConfig.type) {\n throw new Error(\"Action configuration changed between renders\");\n }\n\n switch (currentActionConfig.type) {\n case \"render\":\n return useRenderToolCall(currentActionConfig.action, dependencies);\n case \"hitl\":\n return useHumanInTheLoop(currentActionConfig.action, dependencies);\n case \"frontend\":\n return useFrontendTool(currentActionConfig.action, dependencies);\n default:\n throw new Error(\"Invalid action configuration\");\n }\n}\n","/**\n * The useCoAgentStateRender hook allows you to render UI or text based components on a Agentic Copilot's state in the chat.\n * This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgentStateRender } from \"@copilotkit/react-core\";\n *\n * type YourAgentState = {\n * agent_state_property: string;\n * }\n *\n * useCoAgentStateRender<YourAgentState>({\n * name: \"basic_agent\",\n * nodeName: \"optionally_specify_a_specific_node\",\n * render: ({ status, state, nodeName }) => {\n * return (\n * <YourComponent\n * agentStateProperty={state.agent_state_property}\n * status={status}\n * nodeName={nodeName}\n * />\n * );\n * },\n * });\n * ```\n *\n * This allows for you to render UI components or text based on what is happening within the agent.\n *\n * ### Example\n * A great example of this is in our Perplexity Clone where we render the progress of an agent's internet search as it is happening.\n * You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).\n *\n * <Callout type=\"info\">\n * This example is hosted on Vercel and may take a few seconds to load.\n * </Callout>\n *\n * <iframe src=\"https://examples-coagents-ai-researcher-ui.vercel.app/\" className=\"w-full rounded-lg border h-[700px] my-4\" />\n */\n\nimport { useRef, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { randomId, CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCoAgentStateRenders } from \"../context/coagent-state-renders-context\";\n\n/**\n * This hook is used to render agent state with custom UI components or text. This is particularly\n * useful for showing intermediate state or progress during Agentic Copilot operations.\n * To get started using rendering intermediate state through this hook, checkout the documentation.\n *\n * https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates\n */\n\n// We implement useCoAgentStateRender dependency handling so that\n// the developer has the option to not provide any dependencies.\n// see useCopilotAction for more details about this approach.\nexport function useCoAgentStateRender<T = any>(\n action: CoAgentStateRender<T>,\n dependencies?: any[],\n): void {\n const { chatComponentsCache, availableAgents } = useContext(CopilotContext);\n const {\n setCoAgentStateRender,\n removeCoAgentStateRender,\n coAgentStateRenders,\n } = useCoAgentStateRenders();\n const idRef = useRef<string>(randomId());\n const { setBannerError, addToast } = useToast();\n\n useEffect(() => {\n if (\n availableAgents?.length &&\n !availableAgents.some((a) => a.name === action.name)\n ) {\n const message = `(useCoAgentStateRender): Agent \"${action.name}\" not found. Make sure the agent exists and is properly configured.`;\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: action.name,\n availableAgents: availableAgents.map((a) => ({\n name: a.name,\n id: a.id,\n })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coAgentStateRenders[idRef.current]) {\n coAgentStateRenders[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n // Check for duplicates by comparing against all other actions\n const currentId = idRef.current;\n const hasDuplicate = Object.entries(coAgentStateRenders).some(\n ([id, otherAction]) => {\n // Skip comparing with self\n if (id === currentId) return false;\n\n // Different agent names are never duplicates\n if (otherAction.name !== action.name) return false;\n\n // Same agent names:\n const hasNodeName = !!action.nodeName;\n const hasOtherNodeName = !!otherAction.nodeName;\n\n // If neither has nodeName, they're duplicates\n if (!hasNodeName && !hasOtherNodeName) return true;\n\n // If one has nodeName and other doesn't, they're not duplicates\n if (hasNodeName !== hasOtherNodeName) return false;\n\n // If both have nodeName, they're duplicates only if the names match\n return action.nodeName === otherAction.nodeName;\n },\n );\n\n if (hasDuplicate) {\n const message = action.nodeName\n ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden`\n : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;\n\n addToast({\n type: \"warning\",\n message,\n id: `dup-action-${action.name}`,\n });\n }\n }, [coAgentStateRenders]);\n\n useEffect(() => {\n setCoAgentStateRender(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n return () => {\n removeCoAgentStateRender(idRef.current);\n };\n }, [\n setCoAgentStateRender,\n removeCoAgentStateRender,\n action.name,\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n","import { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useCopilotContext();\n const idRef = useRef<string>(undefined!);\n\n useEffect(() => {\n const id = addDocumentContext(document, categories);\n idRef.current = id;\n\n return () => {\n removeDocumentContext(id);\n };\n }, [addDocumentContext, removeDocumentContext, ...dependencies]);\n\n return idRef.current;\n}\n","/**\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotReadable accepts a single string argument\n * representing any piece of app state, making it available for the Copilot to use\n * as context when responding to user input.\n *\n * ```tsx\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotReadable({\n * description: \"The list of employees\",\n * value: employees,\n * });\n * }\n * ```\n *\n * ### Nested Components\n *\n * Optionally, you can maintain the hierarchical structure of information by passing\n * `parentId`. This allows you to use `useCopilotReadable` in nested components:\n *\n * ```tsx /employeeContextId/1 {17,23}\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * function Employee(props: EmployeeProps) {\n * const { employeeName, workProfile, metadata } = props;\n *\n * // propagate any information to copilot\n * const employeeContextId = useCopilotReadable({\n * description: \"Employee name\",\n * value: employeeName\n * });\n *\n * // Pass a parentID to maintain a hierarchical structure.\n * // Especially useful with child React components, list elements, etc.\n * useCopilotReadable({\n * description: \"Work profile\",\n * value: workProfile.description(),\n * parentId: employeeContextId\n * });\n *\n * useCopilotReadable({\n * description: \"Employee metadata\",\n * value: metadata.description(),\n * parentId: employeeContextId\n * });\n *\n * return (\n * // Render as usual...\n * );\n * }\n * ```\n */\nimport { useCopilotKit } from \"@copilotkitnext/react\";\nimport { useEffect, useRef } from \"react\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context. Object values are automatically stringified.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * Whether the context is available to the Copilot.\n */\n available?: \"enabled\" | \"disabled\";\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n { description, value, convert, available }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { copilotkit } = useCopilotKit();\n const ctxIdRef = useRef<string | undefined>(undefined);\n useEffect(() => {\n if (!copilotkit) return;\n\n const found = Object.entries(copilotkit.context).find(([id, ctxItem]) => {\n return JSON.stringify({ description, value }) == JSON.stringify(ctxItem);\n });\n if (found) {\n ctxIdRef.current = found[0];\n if (available === \"disabled\") copilotkit.removeContext(ctxIdRef.current);\n return;\n }\n if (!found && available === \"disabled\") return;\n\n ctxIdRef.current = copilotkit.addContext({\n description,\n value: (convert ?? JSON.stringify)(value),\n });\n\n return () => {\n if (!ctxIdRef.current) return;\n copilotkit.removeContext(ctxIdRef.current);\n };\n }, [description, value, convert]);\n\n return ctxIdRef.current;\n}\n","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","/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Message } from \"@copilotkit/shared\";\nimport { useAgent, useCopilotKit } from \"@copilotkitnext/react\";\nimport { type AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<\n T,\n> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (...args: any[]) => Promise<any>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(\n options: UseCoagentOptions<T>,\n): UseCoagentReturnType<T> {\n const { agent } = useAgent({ agentId: options.name });\n const { copilotkit } = useCopilotKit();\n const nodeName = useAgentNodeName(options.name);\n\n const handleStateUpdate = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n if (!agent) return;\n\n if (typeof newState === \"function\") {\n const updater = newState as (prevState: T | undefined) => T;\n agent.setState(updater(agent.state));\n } else {\n agent.setState({ ...agent.state, ...newState });\n }\n },\n [agent?.state, agent?.setState],\n );\n\n useEffect(() => {\n if (!options.config && !options.configurable) return;\n\n let config = options.config ?? {};\n if (options.configurable) {\n config = {\n ...config,\n configurable: {\n ...options.configurable,\n ...config.configurable,\n },\n };\n }\n copilotkit.setProperties(config);\n }, [options.config, options.configurable]);\n\n const externalStateStr = useMemo(\n () =>\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : undefined,\n [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : undefined,\n ],\n );\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (\n agent?.state &&\n isExternalStateManagement(options) &&\n JSON.stringify(options.state) !== JSON.stringify(agent.state)\n ) {\n handleStateUpdate(options.state);\n }\n }, [agent, externalStateStr, handleStateUpdate]);\n\n const hasStateValues = useCallback((value?: Record<string, any>) => {\n return Boolean(value && Object.keys(value).length);\n }, []);\n\n const initialStateRef = useRef<any>(\n isExternalStateManagement(options)\n ? options.state\n : \"initialState\" in options\n ? options.initialState\n : undefined,\n );\n\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n initialStateRef.current = options.state;\n } else if (\"initialState\" in options) {\n initialStateRef.current = options.initialState;\n }\n }, [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : \"initialState\" in options\n ? JSON.stringify(options.initialState)\n : undefined,\n ]);\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStateChanged: (args: any) => {\n if (isExternalStateManagement(options)) {\n options.setState(args.state);\n }\n },\n onRunInitialized: (args: any) => {\n const runHasState = hasStateValues(args.state);\n if (runHasState) {\n handleStateUpdate(args.state);\n return;\n }\n\n if (hasStateValues(agent.state)) {\n return;\n }\n\n if (initialStateRef.current !== undefined) {\n handleStateUpdate(initialStateRef.current);\n }\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent, handleStateUpdate, hasStateValues]);\n\n // Return a consistent shape whether or not the agent is available\n return useMemo<UseCoagentReturnType<T>>(() => {\n if (!agent) {\n const noop = () => {};\n const noopAsync = async () => {};\n const initialState =\n // prefer externally provided state if available\n (\"state\" in options && (options as any).state) ??\n // then initialState if provided\n (\"initialState\" in options && (options as any).initialState) ??\n ({} as T);\n return {\n name: options.name,\n nodeName,\n threadId: undefined,\n running: false,\n state: initialState as T,\n setState: noop,\n start: noop,\n stop: noop,\n run: noopAsync,\n };\n }\n\n return {\n name: agent?.agentId ?? options.name,\n nodeName,\n threadId: agent.threadId,\n running: agent.isRunning,\n state: agent.state,\n setState: handleStateUpdate,\n // TODO: start and run both have same thing. need to figure out\n start: agent.runAgent,\n stop: agent.abortRun,\n run: agent.runAgent,\n };\n }, [\n agent?.state,\n agent?.runAgent,\n agent?.abortRun,\n agent?.runAgent,\n agent?.threadId,\n agent?.isRunning,\n agent?.agentId,\n handleStateUpdate,\n options.name,\n ]);\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n","import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo, useRef } from \"react\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n CopilotErrorHandler,\n CopilotErrorEvent,\n} from \"@copilotkit/shared\";\nimport { shouldShowDevConsole } from \"../utils/dev-console\";\n\nexport interface CopilotRuntimeClientHookOptions extends CopilotRuntimeClientOptions {\n showDevConsole?: boolean;\n onError: CopilotErrorHandler;\n}\n\nexport const useCopilotRuntimeClient = (\n options: CopilotRuntimeClientHookOptions,\n) => {\n const { setBannerError } = useToast();\n const { showDevConsole, onError, ...runtimeOptions } = options;\n\n // Deduplication state for structured errors\n const lastStructuredErrorRef = useRef<{\n message: string;\n timestamp: number;\n } | null>(null);\n\n // Helper function to trace UI errors\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\n try {\n const errorEvent: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"ui\",\n request: {\n operation: \"runtimeClient\",\n url: runtimeOptions.url,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent:\n typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : undefined,\n stackTrace:\n originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onError(errorEvent);\n } catch (error) {\n console.error(\"Error in onError handler:\", error);\n }\n };\n\n const runtimeClient = useMemo(() => {\n return new CopilotRuntimeClient({\n ...runtimeOptions,\n handleGQLErrors: (error) => {\n if ((error as any).graphQLErrors?.length) {\n const graphQLErrors = (error as any).graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // All errors (including DEV_ONLY) show as banners for consistency\n // Deduplicate to prevent spam\n const now = Date.now();\n const errorMessage = gqlError.message;\n if (\n lastStructuredErrorRef.current &&\n lastStructuredErrorRef.current.message === errorMessage &&\n now - lastStructuredErrorRef.current.timestamp < 150\n ) {\n return; // Skip duplicate\n }\n lastStructuredErrorRef.current = {\n message: errorMessage,\n timestamp: now,\n };\n\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the error\n traceUIError(ckError, gqlError);\n // TODO: if onError & renderError should work without key, insert here\n } else {\n // Fallback for unstructured errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n // TODO: if onError & renderError should work without key, insert here\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n // TODO: if onError & renderError should work without key, insert here\n }\n },\n handleGQLWarning: (message: string) => {\n console.warn(message);\n // Show warnings as banners too for consistency\n const warningError = new CopilotKitError({\n message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(warningError);\n },\n });\n }, [runtimeOptions, setBannerError, onError]);\n\n return runtimeClient;\n};\n\n// Create appropriate structured error from GraphQL error\nfunction createStructuredError(gqlError: GraphQLError): CopilotKitError | null {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n // Legacy error detection by stack trace\n if (originalError?.stack?.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message });\n }\n if (\n originalError?.stack?.includes(\"CopilotKitRemoteEndpointDiscoveryError\")\n ) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n\n return null;\n}\n","import { Parameter } from \"@copilotkit/shared\";\nimport { Fragment, useCallback, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { FrontendAction, ActionRenderProps } from \"../types/frontend-action\";\nimport { useCopilotAction } from \"./use-copilot-action\";\nimport React from \"react\";\n\n/**\n * Hook to create an authenticated action that requires user sign-in before execution.\n *\n * @remarks\n * This feature is only available when using CopilotKit's hosted cloud service.\n * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.\n *\n * @param action - The frontend action to be wrapped with authentication\n * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed\n */\nexport function useCopilotAuthenticatedAction_c<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();\n const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);\n\n const executeAction = useCallback(\n (props: ActionRenderProps<Parameter[]>) => {\n if (typeof action.render === \"function\") {\n return action.render(props);\n }\n return action.render || React.createElement(Fragment);\n },\n [action],\n );\n\n const wrappedRender = useCallback(\n (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {\n const isAuthenticated = Object.values(authStates_c || {}).some(\n (state) => state.status === \"authenticated\",\n );\n\n if (!isAuthenticated) {\n // Store action details for later execution\n pendingActionRef.current = props;\n\n return authConfig_c?.SignInComponent\n ? React.createElement(authConfig_c.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates_c?.((prev) => ({\n ...prev,\n [action.name]: authState,\n }));\n if (pendingActionRef.current) {\n executeAction(pendingActionRef.current);\n pendingActionRef.current = null;\n }\n },\n })\n : React.createElement(Fragment);\n }\n\n return executeAction(props);\n },\n [action, authStates_c, setAuthStates_c],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\n}\n","import React, { useCallback, useRef } from \"react\";\nimport { LangGraphInterruptRender } from \"../types/interrupt-action\";\nimport {\n useInterrupt,\n useCopilotChatConfiguration,\n} from \"@copilotkitnext/react\";\nimport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n} from \"@copilotkitnext/react\";\nimport { MetaEventName } from \"@copilotkit/runtime-client-gql\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\nimport type { AgentSession } from \"../context/copilot-context\";\n\n/**\n * Transforms a v2 InterruptEvent into the v1 LangGraphInterruptEvent shape\n * expected by existing useLangGraphInterrupt callbacks.\n */\nfunction toV1Event<TEventValue>(event: InterruptEvent<TEventValue>) {\n const value =\n typeof event.value === \"string\"\n ? parseJson(event.value, event.value)\n : event.value;\n return {\n name: MetaEventName.LangGraphInterruptEvent,\n type: \"MetaEvent\" as const,\n value,\n };\n}\n\nexport function useLangGraphInterrupt<TEventValue = any>(\n action: Omit<LangGraphInterruptRender<TEventValue>, \"id\">,\n _dependencies?: any[],\n) {\n const actionRef = useRef(action);\n // Update ref synchronously during render so it's always current\n // when callbacks read from it (useEffect would be one tick late).\n actionRef.current = action;\n\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId =\n action.agentId ?? existingConfig?.agentId ?? \"default\";\n const threadId = existingConfig?.threadId;\n const nodeName = useAgentNodeName(resolvedAgentId);\n\n // Keep agentMetadata in a ref so stable callbacks always see current values.\n const metadataRef = useRef<AgentSession>({\n agentName: resolvedAgentId,\n threadId,\n nodeName,\n });\n metadataRef.current = {\n agentName: resolvedAgentId,\n threadId,\n nodeName,\n };\n\n // Stable callback references that always read the latest action from the ref.\n // This prevents useInterrupt's internal useMemo/useEffect from seeing new\n // function identities on every render, which would cause an infinite loop.\n const render = useCallback(\n ({ event, result, resolve }: InterruptRenderProps<TEventValue>) => {\n const renderFn = actionRef.current.render;\n if (!renderFn) return React.createElement(React.Fragment);\n const rendered = renderFn({\n event: toV1Event(event) as any,\n result,\n resolve: (r) => resolve(r),\n });\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n return rendered;\n },\n [],\n );\n\n // Handler always delegates to the ref — if no handler is set at call time,\n // the optional chaining returns undefined which useInterrupt treats as null.\n const handler = useCallback(\n ({ event, resolve }: InterruptHandlerProps<TEventValue>) => {\n return actionRef.current.handler?.({\n event: toV1Event(event) as any,\n resolve: (r) => resolve(r),\n });\n },\n [],\n );\n\n const enabled = useCallback((event: InterruptEvent<TEventValue>) => {\n if (!actionRef.current.enabled) return true;\n return actionRef.current.enabled({\n eventValue: toV1Event(event).value,\n agentMetadata: metadataRef.current,\n });\n }, []);\n\n useInterrupt({\n render,\n handler,\n enabled,\n agentId: resolvedAgentId,\n });\n}\n","/**\n * `useCopilotAdditionalInstructions` is a React hook that provides additional instructions\n * to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotAdditionalInstructions accepts a single string argument\n * representing the instructions to be added to the Copilot.\n *\n * ```tsx\n * import { useCopilotAdditionalInstructions } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * useCopilotAdditionalInstructions({\n * instructions: \"Do not answer questions about the weather.\",\n * });\n * }\n * ```\n *\n * ### Conditional Usage\n *\n * You can also conditionally add instructions based on the state of your app.\n *\n * ```tsx\n * import { useCopilotAdditionalInstructions } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [showInstructions, setShowInstructions] = useState(false);\n *\n * useCopilotAdditionalInstructions({\n * available: showInstructions ? \"enabled\" : \"disabled\",\n * instructions: \"Do not answer questions about the weather.\",\n * });\n * }\n * ```\n */\nimport { useEffect } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\n\n/**\n * Options for the useCopilotAdditionalInstructions hook.\n */\nexport interface UseCopilotAdditionalInstructionsOptions {\n /**\n * The instructions to be added to the Copilot. Will be added to the instructions like so:\n *\n * ```txt\n * You are a helpful assistant.\n * Additionally, follow these instructions:\n * - Do not answer questions about the weather.\n * - Do not answer questions about the stock market.\n * ```\n */\n instructions: string;\n\n /**\n * Whether the instructions are available to the Copilot.\n */\n available?: \"enabled\" | \"disabled\";\n}\n\n/**\n * Adds the given instructions to the Copilot context.\n */\nexport function useCopilotAdditionalInstructions(\n {\n instructions,\n available = \"enabled\",\n }: UseCopilotAdditionalInstructionsOptions,\n dependencies?: any[],\n) {\n const { setAdditionalInstructions } = useCopilotContext();\n\n useEffect(() => {\n if (available === \"disabled\") return;\n\n setAdditionalInstructions((prevInstructions) => [\n ...(prevInstructions || []),\n instructions,\n ]);\n\n return () => {\n setAdditionalInstructions(\n (prevInstructions) =>\n prevInstructions?.filter(\n (instruction) => instruction !== instructions,\n ) || [],\n );\n };\n }, [\n available,\n instructions,\n setAdditionalInstructions,\n ...(dependencies || []),\n ]);\n}\n","import { useCopilotAction } from \"./use-copilot-action\";\nimport { CatchAllFrontendAction } from \"../types/frontend-action\";\n\nexport function useDefaultTool(\n tool: Omit<CatchAllFrontendAction, \"name\">,\n dependencies?: any[],\n) {\n // Use the existing useCopilotAction hook\n useCopilotAction(\n { ...tool, name: \"*\" } satisfies CatchAllFrontendAction,\n dependencies,\n );\n}\n","/**\n * <Callout type=\"warning\">\n * useCopilotChatSuggestions is experimental. The interface is not final and\n * can change without notice.\n * </Callout>\n *\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * <br/>\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-chat-suggestions/use-copilot-chat-suggestions.gif\" width=\"500\" />\n *\n * ## Usage\n *\n * ### Install Dependencies\n *\n * This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.\n *\n * ```shell npm2yarn \\\"@copilotkit/react-ui\"\\\n * npm install @copilotkit/react-core @copilotkit/react-ui\n * ```\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChatSuggestions } from \"@copilotkit/react-ui\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotChatSuggestions({\n * instructions: `The following employees are on duty: ${JSON.stringify(employees)}`,\n * });\n * }\n * ```\n *\n * ### Dependency Management\n *\n * ```tsx\n * import { useCopilotChatSuggestions } from \"@copilotkit/react-ui\";\n *\n * export function MyComponent() {\n * useCopilotChatSuggestions(\n * {\n * instructions: \"Suggest the most relevant next actions.\",\n * },\n * [appState],\n * );\n * }\n * ```\n *\n * In the example above, the suggestions are generated based on the given instructions.\n * The hook monitors `appState`, and updates suggestions accordingly whenever it changes.\n *\n * ### Behavior and Lifecycle\n *\n * The hook registers the configuration with the chat context upon component mount and\n * removes it on unmount, ensuring a clean and efficient lifecycle management.\n */\nimport {\n useConfigureSuggestions,\n useCopilotChatConfiguration,\n useCopilotKit,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport { useEffect } from \"react\";\nimport { StaticSuggestionsConfig, Suggestion } from \"@copilotkitnext/core\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> &\n Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<\n StaticSuggestionsConfig,\n \"suggestions\"\n> & {\n suggestions: StaticSuggestionInput[];\n};\n\ntype DynamicSuggestionsConfigInput = {\n /**\n * A prompt or instructions for the GPT to generate suggestions.\n */\n instructions: string;\n /**\n * The minimum number of suggestions to generate. Defaults to `1`.\n * @default 1\n */\n minSuggestions?: number;\n /**\n * The maximum number of suggestions to generate. Defaults to `3`.\n * @default 1\n */\n maxSuggestions?: number;\n\n /**\n * Whether the suggestions are available. Defaults to `enabled`.\n * @default enabled\n */\n available?:\n | \"enabled\"\n | \"disabled\"\n | \"always\"\n | \"before-first-message\"\n | \"after-first-message\";\n\n /**\n * An optional class name to apply to the suggestions.\n */\n className?: string;\n};\n\nexport type UseCopilotChatSuggestionsConfiguration =\n | DynamicSuggestionsConfigInput\n | StaticSuggestionsConfigInput;\n\nexport function useCopilotChatSuggestions(\n config: UseCopilotChatSuggestionsConfiguration,\n dependencies: any[] = [],\n) {\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n\n const available =\n (config.available === \"enabled\" ? \"always\" : config.available) ??\n \"before-first-message\";\n\n const finalSuggestionConfig = {\n ...config,\n available,\n consumerAgentId: resolvedAgentId, // Use chatConfig.agentId here\n };\n useConfigureSuggestions(finalSuggestionConfig, dependencies);\n}\n","import { ActionInputAvailability } from \"@copilotkit/runtime-client-gql\";\nimport {\n Action,\n Parameter,\n MappedParameterTypes,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingState<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: any;\n}\n\ninterface InProgressStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n}\n\nexport type ActionRenderProps<T extends Parameter[] | [] = []> =\n | CompleteState<T>\n | ExecutingState<T>\n | InProgressState<T>;\n\nexport type ActionRenderPropsNoArgs<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgs<T>\n | ExecutingStateNoArgs<T>\n | InProgressStateNoArgs<T>;\n\nexport type ActionRenderPropsWait<T extends Parameter[] | [] = []> =\n | CompleteStateWait<T>\n | ExecutingStateWait<T>\n | InProgressStateWait<T>;\n\nexport type ActionRenderPropsNoArgsWait<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgsWait<T>\n | ExecutingStateNoArgsWait<T>\n | InProgressStateNoArgsWait<T>;\n\nexport type CatchAllActionRenderProps<T extends Parameter[] | [] = []> =\n | (CompleteState<T> & {\n name: string;\n })\n | (ExecutingState<T> & {\n name: string;\n })\n | (InProgressState<T> & {\n name: string;\n });\n\nexport type FrontendActionAvailability =\n | \"disabled\"\n | \"enabled\"\n | \"remote\"\n | \"frontend\";\n\nexport type FrontendAction<\n T extends Parameter[] | [] = [],\n N extends string = string,\n> = Action<T> & {\n name: Exclude<N, \"*\">;\n /**\n * @deprecated Use `available` instead.\n */\n disabled?: boolean;\n available?: FrontendActionAvailability;\n pairedAction?: string;\n followUp?: boolean;\n} & (\n | {\n render?:\n | string\n | (T extends []\n ? (\n props: ActionRenderPropsNoArgs<T>,\n ) => string | React.ReactElement\n : (props: ActionRenderProps<T>) => string | React.ReactElement);\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: never;\n renderAndWaitForResponse?: never;\n }\n | {\n render?: never;\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n renderAndWaitForResponse?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n handler?: never;\n }\n );\n\nexport type CatchAllFrontendAction = {\n name: \"*\";\n render: (props: CatchAllActionRenderProps<any>) => React.ReactElement;\n};\n\nexport type RenderFunctionStatus = ActionRenderProps<any>[\"status\"];\n\nexport function processActionsForRuntimeRequest(\n actions: FrontendAction<any>[],\n) {\n const filteredActions = actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled &&\n action.disabled !== true &&\n action.name !== \"*\" &&\n action.available != \"frontend\" &&\n !action.pairedAction,\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined =\n ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(\n actionParametersToJsonSchema(action.parameters || []),\n ),\n available,\n };\n });\n return filteredActions;\n}\n","/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/v1/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/v1/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/src/v1.x/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport {\n FrontendAction,\n processActionsForRuntimeRequest,\n} from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n private forwardedParameters?: ForwardedParametersInput;\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n this.forwardedParameters = config.forwardedParameters;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions\n ? Object.assign({}, context.actions)\n : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString =\n (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString(\n [],\n defaultCopilotContextCategories,\n );\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(\n filterAgentStateMessages(messages),\n ),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n toolChoice: \"required\",\n ...(this.forwardedParameters ?? {}),\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(\n contextString: string,\n instructions: string,\n): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;AAIA,MAAa,0BAA0B;CACrC,aAAa;CACb,aAAa;CACd;;;;ACHD,SAAgB,sBAG4D;CAC1E,MAAM,iBAAiBA,qBAAmB;AAE1C,QAAO,aACJ,SAAqB,aAAyB;AAC7C,MAAI,CAAC,SAAS,WAAW,OAAQ,QAAO;EAExC,MAAM,WAAW,QAAQ,UAAU;AACnC,MAAI,CAAC,SAAU,QAAO;EAEtB,MAAM,cAAc,UAAU,MAC3B,MAAM,EAAE,SAAS,UAAU,EAAE,eAAe,SAAS,GACvD;AAED,eACE,eAAe;GACb;GACA;GACD,CAAC;IAEN,CAAC,eAAe,CACjB;;;;;ACySH,SAAgB,uBAAuB,EACrC,aAC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