@copilotkit/react-core 1.9.3-next.3 → 1.9.3-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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/index.ts","../../src/hooks/use-copilot-chat.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-chat.ts","../../src/types/frontend-action.ts","../../src/hooks/use-copilot-runtime-client.ts","../../src/components/toast/toast-provider.tsx","../../src/utils/dev-console.ts","../../src/components/error-boundary/error-utils.tsx","../../src/components/toast/exclamation-mark-icon.tsx","../../src/components/copilot-provider/copilotkit.tsx","../../src/context/copilot-messages-context.tsx","../../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-coagent.ts","../../src/hooks/use-copilot-authenticated-action.ts","../../src/hooks/use-langgraph-interrupt.ts","../../src/hooks/use-langgraph-interrupt-render.ts","../../src/hooks/use-copilot-additional-instructions.ts"],"sourcesContent":["export { useCopilotChat } from \"./use-copilot-chat\";\nexport type { UseCopilotChatOptions } from \"./use-copilot-chat\";\nexport type { UseCopilotChatReturn } from \"./use-copilot-chat\";\n\nexport { useCopilotAction } from \"./use-copilot-action\";\nexport { useCoAgentStateRender } from \"./use-coagent-state-render\";\nexport { useMakeCopilotDocumentReadable } from \"./use-make-copilot-document-readable\";\nexport { type UseChatHelpers } from \"./use-chat\";\nexport { useCopilotReadable } from \"./use-copilot-readable\";\nexport { useCoAgent, type HintFunction, runAgent, startAgent, stopAgent } from \"./use-coagent\";\nexport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nexport { useCopilotAuthenticatedAction_c } from \"./use-copilot-authenticated-action\";\nexport { useLangGraphInterrupt } from \"./use-langgraph-interrupt\";\nexport { useLangGraphInterruptRender } from \"./use-langgraph-interrupt-render\";\nexport { useCopilotAdditionalInstructions } from \"./use-copilot-additional-instructions\";\nexport type { Tree, TreeNode } from \"./use-tree\";\n","/**\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n *\n * // optionally, you can append a message without running chat completion\n * appendMessage(yourMessage, { followUp: false });\n * }\n * ```\n *\n * `useCopilotChat` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * visibleMessages, // An array of messages that are currently visible in the chat.\n * appendMessage, // A function to append a message to the chat.\n * setMessages, // A function to set the messages in the chat.\n * deleteMessage, // A function to delete a message from the chat.\n * reloadMessages, // A function to reload the messages from the API.\n * stopGeneration, // A function to stop the generation of the next message.\n * reset, // A function to reset the chat.\n * isLoading, // A boolean indicating if the chat is loading.\n * } = useCopilotChat();\n * ```\n */\nimport { useRef, useEffect, useCallback, useState } from \"react\";\nimport { AgentSession, useCopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat, AppendMessageOptions } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CoAgentStateRenderHandlerArguments } from \"@copilotkit/shared\";\nimport { useCopilotMessagesContext } from \"../context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\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 * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface MCPServerConfig {\n endpoint: string;\n apiKey?: string;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: (messageId: string) => Promise<void>;\n stopGeneration: () => void;\n reset: () => void;\n isLoading: boolean;\n runChatCompletion: () => Promise<Message[]>;\n mcpServers: MCPServerConfig[];\n setMcpServers: (mcpServers: MCPServerConfig[]) => void;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n coagentStatesRef,\n setCoagentStatesWithRef,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n } = useCopilotContext();\n const { messages, setMessages } = useCopilotMessagesContext();\n\n // Simple state for MCP servers (keep for interface compatibility)\n const [mcpServers, setLocalMcpServers] = useState<MCPServerConfig[]>([]);\n\n // This effect directly updates the context when mcpServers state changes\n useEffect(() => {\n if (mcpServers.length > 0) {\n // Copy to avoid issues\n const serversCopy = [...mcpServers];\n\n // Update in all locations\n copilotApiConfig.mcpServers = serversCopy;\n\n // Also ensure it's in properties\n if (!copilotApiConfig.properties) {\n copilotApiConfig.properties = {};\n }\n copilotApiConfig.properties.mcpServers = serversCopy;\n }\n }, [mcpServers, copilotApiConfig]);\n\n // Provide the same interface\n const setMcpServers = useCallback((servers: MCPServerConfig[]) => {\n setLocalMcpServers(servers);\n }, []);\n\n // Move these function declarations above the useChat call\n const onCoAgentStateRender = useAsyncCallback(\n async (args: CoAgentStateRenderHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coAgentStateRenders],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: Role.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n // Get chat helpers with updated config\n const { append, reload, stop, runChatCompletion } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n onCoAgentStateRender,\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n });\n\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n return await latestAppend.current(message, options);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(\n async (messageId: string) => {\n return await latestReload.current(messageId);\n },\n [latestReload],\n );\n\n const latestStop = useUpdatedRef(stop);\n const latestStopFunc = useCallback(() => {\n return latestStop.current();\n }, [latestStop]);\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 latestSetMessages = useUpdatedRef(setMessages);\n const latestSetMessagesFunc = useCallback(\n (messages: Message[]) => {\n return latestSetMessages.current(messages);\n },\n [latestSetMessages],\n );\n\n const latestRunChatCompletion = useUpdatedRef(runChatCompletion);\n const latestRunChatCompletionFunc = useAsyncCallback(async () => {\n return await latestRunChatCompletion.current!();\n }, [latestRunChatCompletion]);\n\n const reset = useCallback(() => {\n latestStopFunc();\n setMessages([]);\n setRunId(null);\n setCoagentStatesWithRef({});\n let initialAgentSession: AgentSession | null = null;\n if (agentLock) {\n initialAgentSession = {\n agentName: agentLock,\n };\n }\n setAgentSession(initialAgentSession);\n }, [\n latestStopFunc,\n setMessages,\n setThreadId,\n setCoagentStatesWithRef,\n setAgentSession,\n agentLock,\n ]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n return {\n visibleMessages: messages,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n runChatCompletion: latestRunChatCompletionFunc,\n isLoading,\n mcpServers,\n setMcpServers,\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\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n","import { CopilotCloudConfig, FunctionCallHandler, CopilotErrorHandler } from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Optional configuration for connecting to Model Context Protocol (MCP) servers.\n * This is typically derived from the CopilotKitProps and used internally.\n * @experimental\n */\n mcpServers?: Array<{ endpoint: string; apiKey?: string }>;\n}\n\nexport type InChatRenderFunction<TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>> =\n (props: TProps) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\nexport type ContextTree = Tree;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // coagent actions\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n additionalInstructions?: string[];\n setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean;\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n // runtime\n runtimeClient: CopilotRuntimeClient;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Partial<Pick<ForwardedParametersInput, \"temperature\">>;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n langGraphInterruptAction: LangGraphInterruptAction | null;\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n removeLangGraphInterruptAction: () => void;\n\n /**\n * Optional trace handler for comprehensive debugging and observability.\n */\n onError?: CopilotErrorHandler;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coAgentStateRenders: {},\n setCoAgentStateRender: () => {},\n removeCoAgentStateRender: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n getAllContext: () => [],\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n additionalInstructions: [],\n setAdditionalInstructions: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n runtimeClient: {} as any,\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: false,\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n langGraphInterruptAction: null,\n setLangGraphInterruptAction: () => null,\n removeLangGraphInterruptAction: () => null,\n onError: undefined,\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n","import React, { useCallback, useEffect, useRef } from \"react\";\nimport { flushSync } from \"react-dom\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n CoAgentStateRenderHandler,\n randomId,\n parseJson,\n CopilotKitError,\n CopilotKitErrorCode,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ResultMessage,\n convertMessagesToGqlInput,\n filterAdjacentAgentStateMessages,\n filterAgentStateMessages,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n ForwardedParametersInput,\n loadMessagesFromJsonRepresentation,\n ExtensionsInput,\n CopilotRuntimeClient,\n langGraphInterruptEvent,\n MetaEvent,\n MetaEventName,\n ActionExecutionMessage,\n CopilotKitLangGraphInterruptEvent,\n LangGraphInterruptEvent,\n MetaEventInput,\n AgentStateInput,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession, useCopilotContext } from \"../context/copilot-context\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { useAsyncCallback, useErrorToast } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n\n /**\n * Callback function to be called when a coagent action is received.\n */\n onCoAgentStateRender?: CoAgentStateRenderHandler;\n\n /**\n * Function definitions to be sent to the API.\n */\n actions: FrontendAction<any>[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * The current list of coagent states.\n */\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStatesWithRef: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n\n /**\n * The current agent session.\n */\n agentSession: AgentSession | null;\n\n /**\n * setState-powered method to update the agent session\n */\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n /**\n * The forwarded parameters.\n */\n forwardedParameters?: Pick<ForwardedParametersInput, \"temperature\">;\n\n /**\n * The current thread ID.\n */\n threadId: string;\n /**\n * set the current thread ID\n */\n setThreadId: (threadId: string) => void;\n /**\n * The current run ID.\n */\n runId: string | null;\n /**\n * set the current run ID\n */\n setRunId: (runId: string | null) => void;\n /**\n * The global chat abort controller.\n */\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n /**\n * The agent lock.\n */\n agentLock: string | null;\n /**\n * The extensions.\n */\n extensions: ExtensionsInput;\n /**\n * The setState-powered method to update the extensions.\n */\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n\n langGraphInterruptAction: LangGraphInterruptAction | null;\n\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (messageId: string) => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Run the chat completion.\n */\n runChatCompletion: () => Promise<Message[]>;\n};\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\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStatesWithRef,\n coagentStatesRef,\n agentSession,\n setAgentSession,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n } = options;\n const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();\n const addErrorToast = useErrorToast();\n const { setBannerError } = useToast();\n\n // Get onError from context since it's not part of copilotConfig\n const { onError } = useCopilotContext();\n\n // Add tracing functionality to use-chat\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\n // Just check if onError and publicApiKey are defined\n if (!onError || !copilotConfig?.publicApiKey) return;\n\n try {\n const traceEvent = {\n type: \"error\" as const,\n timestamp: Date.now(),\n context: {\n source: \"ui\" as const,\n request: {\n operation: \"useChatCompletion\",\n url: copilotConfig.chatApiEndpoint,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n\n await onError(traceEvent);\n } catch (traceError) {\n console.error(\"Error in use-chat onError handler:\", traceError);\n }\n };\n // We need to keep a ref of coagent states and session because of renderAndWait - making sure\n // the latest state is sent to the API\n // This is a workaround and needs to be addressed in the future\n const agentSessionRef = useRef<AgentSession | null>(agentSession);\n agentSessionRef.current = agentSession;\n\n const runIdRef = useRef<string | null>(runId);\n runIdRef.current = runId;\n const extensionsRef = useRef<ExtensionsInput>(extensions);\n extensionsRef.current = extensions;\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const { showDevConsole } = useCopilotContext();\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n showDevConsole,\n });\n\n const pendingAppendsRef = useRef<{ message: Message; followUp: boolean }[]>([]);\n\n const runChatCompletion = useAsyncCallback(\n async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n const interruptEvent = langGraphInterruptAction?.event;\n // In case an interrupt event exist and valid but has no response yet, we cannot process further messages to an agent\n if (\n interruptEvent?.name === MetaEventName.LangGraphInterruptEvent &&\n interruptEvent?.value &&\n !interruptEvent?.response &&\n agentSessionRef.current\n ) {\n addErrorToast([\n new Error(\n \"A message was sent while interrupt is active. This will cause failure on the agent side\",\n ),\n ]);\n }\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n\n chatAbortControllerRef.current = new AbortController();\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n // ----- Set mcpServers in properties -----\n // Create a copy of properties to avoid modifying the original object\n const finalProperties = { ...(copilotConfig.properties || {}) };\n\n // Look for mcpServers in either direct property or properties\n let mcpServersToUse = null;\n\n // First check direct mcpServers property\n if (\n copilotConfig.mcpServers &&\n Array.isArray(copilotConfig.mcpServers) &&\n copilotConfig.mcpServers.length > 0\n ) {\n mcpServersToUse = copilotConfig.mcpServers;\n }\n // Then check mcpServers in properties\n else if (\n copilotConfig.properties?.mcpServers &&\n Array.isArray(copilotConfig.properties.mcpServers) &&\n copilotConfig.properties.mcpServers.length > 0\n ) {\n mcpServersToUse = copilotConfig.properties.mcpServers;\n }\n\n // Apply the mcpServers to properties if found\n if (mcpServersToUse) {\n // Set in finalProperties\n finalProperties.mcpServers = mcpServersToUse;\n\n // Also set in copilotConfig directly for future use\n copilotConfig.mcpServers = mcpServersToUse;\n }\n // -------------------------------------------------------------\n\n const isAgentRun = agentSessionRef.current !== null;\n\n const stream = runtimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(actions),\n url: window.location.href,\n },\n threadId: threadId,\n runId: runIdRef.current,\n extensions: extensionsRef.current,\n metaEvents: composeAndFlushMetaEventsInput([langGraphInterruptAction?.event]),\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: agentSessionRef.current,\n }\n : {}),\n agentStates: Object.values(coagentStatesRef.current!).map((state) => {\n const stateObject: AgentStateInput = {\n agentName: state.name,\n state: JSON.stringify(state.state),\n };\n\n if (state.config !== undefined) {\n stateObject.config = JSON.stringify(state.config);\n }\n\n return stateObject;\n }),\n forwardedParameters: options.forwardedParameters || {},\n },\n properties: finalProperties,\n signal: chatAbortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let executedCoAgentStateRenders: string[] = [];\n let followUp: FrontendAction[\"followUp\"] = undefined;\n\n let messages: Message[] = [];\n let syncedMessages: Message[] = [];\n let interruptMessages: Message[] = [];\n\n try {\n while (true) {\n let done, value;\n\n try {\n const readResult = await reader.read();\n done = readResult.done;\n value = readResult.value;\n } catch (readError) {\n break;\n }\n\n if (done) {\n if (chatAbortControllerRef.current.signal.aborted) {\n return [];\n }\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n // in the output, graphql inserts __typename, which leads to an error when sending it along\n // as input to the next request.\n extensionsRef.current = CopilotRuntimeClient.removeGraphQLTypename(\n value.generateCopilotResponse.extensions || {},\n );\n\n // setThreadId(threadIdRef.current);\n setRunId(runIdRef.current);\n setExtensions(extensionsRef.current);\n let rawMessagesResponse = value.generateCopilotResponse.messages;\n\n const metaEvents: MetaEvent[] | undefined =\n value.generateCopilotResponse?.metaEvents ?? [];\n (metaEvents ?? []).forEach((ev) => {\n if (ev.name === MetaEventName.LangGraphInterruptEvent) {\n let eventValue = langGraphInterruptEvent(ev as LangGraphInterruptEvent).value;\n eventValue = parseJson(eventValue, eventValue);\n setLangGraphInterruptAction({\n event: {\n ...langGraphInterruptEvent(ev as LangGraphInterruptEvent),\n value: eventValue,\n },\n });\n }\n if (ev.name === MetaEventName.CopilotKitLangGraphInterruptEvent) {\n const data = (ev as CopilotKitLangGraphInterruptEvent).data;\n\n // @ts-expect-error -- same type of messages\n rawMessagesResponse = [...rawMessagesResponse, ...data.messages];\n interruptMessages = convertGqlOutputToMessages(\n // @ts-ignore\n filterAdjacentAgentStateMessages(data.messages),\n );\n }\n });\n\n messages = convertGqlOutputToMessages(\n filterAdjacentAgentStateMessages(rawMessagesResponse),\n );\n\n newMessages = [];\n\n // Handle error statuses BEFORE checking if there are messages\n // (errors can come in chunks with no messages)\n\n // request failed, display error message and quit\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n const guardrailsReason =\n value.generateCopilotResponse.status.details?.guardrailsReason || \"\";\n\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: guardrailsReason,\n }),\n ];\n\n // Trace guardrails validation failure\n const guardrailsError = new CopilotKitError({\n message: `Guardrails validation failed: ${guardrailsReason}`,\n code: CopilotKitErrorCode.MISUSE,\n });\n await traceUIError(guardrailsError, {\n statusReason: value.generateCopilotResponse.status.reason,\n statusDetails: value.generateCopilotResponse.status.details,\n });\n\n setMessages([...previousMessages, ...newMessages]);\n break;\n }\n\n // Handle UNKNOWN_ERROR failures (like authentication errors) by routing to banner error system\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"UNKNOWN_ERROR\"\n ) {\n const errorMessage =\n value.generateCopilotResponse.status.details?.description ||\n \"An unknown error occurred\";\n\n // Try to extract original error information from the response details\n const statusDetails = value.generateCopilotResponse.status.details;\n const originalError = statusDetails?.originalError || statusDetails?.error;\n\n // Extract structured error information if available (prioritize top-level over extensions)\n const originalCode = originalError?.code || originalError?.extensions?.code;\n const originalSeverity = originalError?.severity || originalError?.extensions?.severity;\n const originalVisibility =\n originalError?.visibility || originalError?.extensions?.visibility;\n\n // Use the original error code if available, otherwise default to NETWORK_ERROR\n let errorCode = CopilotKitErrorCode.NETWORK_ERROR;\n if (originalCode && Object.values(CopilotKitErrorCode).includes(originalCode)) {\n errorCode = originalCode;\n }\n\n // Create a structured CopilotKitError preserving original error information\n const structuredError = new CopilotKitError({\n message: errorMessage,\n code: errorCode,\n severity: originalSeverity,\n visibility: originalVisibility,\n });\n\n // Display the error in the banner\n setBannerError(structuredError);\n\n // Trace the error for debugging/observability\n await traceUIError(structuredError, {\n statusReason: value.generateCopilotResponse.status.reason,\n statusDetails: value.generateCopilotResponse.status.details,\n originalErrorCode: originalCode,\n preservedStructure: !!originalCode,\n });\n\n // Stop processing and break from the loop\n setIsLoading(false);\n break;\n }\n\n // add messages to the chat\n else if (messages.length > 0) {\n newMessages = [...messages];\n\n for (const message of messages) {\n // execute onCoAgentStateRender handler\n if (\n message.isAgentStateMessage() &&\n !message.active &&\n !executedCoAgentStateRenders.includes(message.id) &&\n onCoAgentStateRender\n ) {\n // Do not execute a coagent action if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute coagent action\n await onCoAgentStateRender({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoAgentStateRenders.push(message.id);\n }\n }\n\n const lastAgentStateMessage = [...messages]\n .reverse()\n .find((message) => message.isAgentStateMessage());\n\n if (lastAgentStateMessage) {\n if (\n lastAgentStateMessage.state.messages &&\n lastAgentStateMessage.state.messages.length > 0\n ) {\n syncedMessages = loadMessagesFromJsonRepresentation(\n lastAgentStateMessage.state.messages,\n );\n }\n setCoagentStatesWithRef((prevAgentStates) => ({\n ...prevAgentStates,\n [lastAgentStateMessage.agentName]: {\n name: lastAgentStateMessage.agentName,\n state: lastAgentStateMessage.state,\n running: lastAgentStateMessage.running,\n active: lastAgentStateMessage.active,\n threadId: lastAgentStateMessage.threadId,\n nodeName: lastAgentStateMessage.nodeName,\n runId: lastAgentStateMessage.runId,\n // Preserve existing config from previous state\n config: prevAgentStates[lastAgentStateMessage.agentName]?.config,\n },\n }));\n if (lastAgentStateMessage.running) {\n setAgentSession({\n threadId: lastAgentStateMessage.threadId,\n agentName: lastAgentStateMessage.agentName,\n nodeName: lastAgentStateMessage.nodeName,\n });\n } else {\n if (agentLock) {\n setAgentSession({\n threadId: randomId(),\n agentName: agentLock,\n nodeName: undefined,\n });\n } else {\n setAgentSession(null);\n }\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Update message state\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n let finalMessages = constructFinalMessages(\n [...syncedMessages, ...interruptMessages],\n previousMessages,\n newMessages,\n );\n\n let didExecuteAction = false;\n\n // ----- Helper function to execute an action and manage its lifecycle -----\n const executeActionFromMessage = async (\n currentAction: FrontendAction<any>,\n actionMessage: ActionExecutionMessage,\n ) => {\n const isInterruptAction = interruptMessages.find((m) => m.id === actionMessage.id);\n // Determine follow-up behavior: use action's specific setting if defined, otherwise default based on interrupt status.\n followUp = currentAction?.followUp ?? !isInterruptAction;\n\n // Call _setActivatingMessageId before executing the action for HITL correlation\n if ((currentAction as any)?._setActivatingMessageId) {\n (currentAction as any)._setActivatingMessageId(actionMessage.id);\n }\n\n const resultMessage = await executeAction({\n onFunctionCall: onFunctionCall!,\n message: actionMessage,\n chatAbortControllerRef,\n onError: (error: Error) => {\n addErrorToast([error]);\n // console.error is kept here as it's a genuine error in action execution\n console.error(`Failed to execute action ${actionMessage.name}: ${error}`);\n },\n setMessages,\n getFinalMessages: () => finalMessages,\n isRenderAndWait: (currentAction as any)?._isRenderAndWait || false,\n });\n didExecuteAction = true;\n const messageIndex = finalMessages.findIndex((msg) => msg.id === actionMessage.id);\n finalMessages.splice(messageIndex + 1, 0, resultMessage);\n\n // If the executed action was a renderAndWaitForResponse type, update messages immediately\n // to reflect its completion in the UI, making it interactive promptly.\n if ((currentAction as any)?._isRenderAndWait) {\n const messagesForImmediateUpdate = [...finalMessages];\n flushSync(() => {\n setMessages(messagesForImmediateUpdate);\n });\n }\n\n // Clear _setActivatingMessageId after the action is done\n if ((currentAction as any)?._setActivatingMessageId) {\n (currentAction as any)._setActivatingMessageId(null);\n }\n\n return resultMessage;\n };\n // ----------------------------------------------------------------------\n\n // execute regular action executions that are specific to the frontend (last actions)\n if (onFunctionCall) {\n // Find consecutive action execution messages at the end\n const lastMessages = [];\n\n for (let i = finalMessages.length - 1; i >= 0; i--) {\n const message = finalMessages[i];\n if (\n (message.isActionExecutionMessage() || message.isResultMessage()) &&\n message.status.code !== MessageStatusCode.Pending\n ) {\n lastMessages.unshift(message);\n } else if (!message.isAgentStateMessage()) {\n break;\n }\n }\n\n for (const message of lastMessages) {\n // We update the message state before calling the handler so that the render\n // function can be called with `executing` state\n setMessages(finalMessages);\n\n const action = actions.find(\n (action) => action.name === (message as ActionExecutionMessage).name,\n );\n const currentResultMessagePairedFeAction = message.isResultMessage()\n ? getPairedFeAction(actions, message)\n : null;\n\n // execution message which has an action registered with the hook (remote availability):\n // execute that action first, and then the \"paired FE action\"\n if (action && message.isActionExecutionMessage()) {\n // For HITL actions, check if they've already been processed to avoid redundant handler calls.\n const isRenderAndWaitAction = (action as any)?._isRenderAndWait || false;\n const alreadyProcessed =\n isRenderAndWaitAction &&\n finalMessages.some(\n (fm) => fm.isResultMessage() && fm.actionExecutionId === message.id,\n );\n\n if (alreadyProcessed) {\n // Skip re-execution if already processed\n } else {\n // Call the single, externally defined executeActionFromMessage\n const resultMessage = await executeActionFromMessage(\n action,\n message as ActionExecutionMessage,\n );\n const pairedFeAction = getPairedFeAction(actions, resultMessage);\n\n if (pairedFeAction) {\n const newExecutionMessage = new ActionExecutionMessage({\n name: pairedFeAction.name,\n arguments: parseJson(resultMessage.result, resultMessage.result),\n status: message.status,\n createdAt: message.createdAt,\n parentMessageId: message.parentMessageId,\n });\n // Call the single, externally defined executeActionFromMessage\n await executeActionFromMessage(pairedFeAction, newExecutionMessage);\n }\n }\n } else if (message.isResultMessage() && currentResultMessagePairedFeAction) {\n // Actions which are set up in runtime actions array: Grab the result, executed paired FE action with it as args.\n const newExecutionMessage = new ActionExecutionMessage({\n name: currentResultMessagePairedFeAction.name,\n arguments: parseJson(message.result, message.result),\n status: message.status,\n createdAt: message.createdAt,\n });\n finalMessages.push(newExecutionMessage);\n // Call the single, externally defined executeActionFromMessage\n await executeActionFromMessage(\n currentResultMessagePairedFeAction,\n newExecutionMessage,\n );\n }\n }\n\n setMessages(finalMessages);\n }\n\n // Conditionally run chat completion again if followUp is not explicitly false\n // and an action was executed or the last message is a server-side result (for non-agent runs).\n if (\n followUp !== false &&\n (didExecuteAction ||\n // the last message is a server side result\n (!isAgentRun &&\n finalMessages.length &&\n finalMessages[finalMessages.length - 1].isResultMessage())) &&\n // the user did not stop generation\n !chatAbortControllerRef.current?.signal.aborted\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletionRef.current!(finalMessages);\n } else if (chatAbortControllerRef.current?.signal.aborted) {\n // filter out all the action execution messages that do not have a consecutive matching result message\n const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {\n if (message.isActionExecutionMessage()) {\n return finalMessages.find(\n (msg, resultIndex) =>\n msg.isResultMessage() &&\n msg.actionExecutionId === message.id &&\n resultIndex === actionExecutionIndex + 1,\n );\n }\n return true;\n });\n const repairedMessageIds = repairedMessages.map((message) => message.id);\n setMessages(repairedMessages);\n\n // LangGraph needs two pieces of information to continue execution:\n // 1. The threadId\n // 2. The nodeName it came from\n // When stopping the agent, we don't know the nodeName the agent would have ended with\n // Therefore, we set the nodeName to the most reasonable thing we can guess, which\n // is \"__end__\"\n if (agentSessionRef.current?.nodeName) {\n setAgentSession({\n threadId: agentSessionRef.current.threadId,\n agentName: agentSessionRef.current.agentName,\n nodeName: \"__end__\",\n });\n }\n // only return new messages that were not filtered out\n return newMessages.filter((message) => repairedMessageIds.includes(message.id));\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n },\n [\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStatesWithRef,\n coagentStatesRef,\n agentSession,\n setAgentSession,\n ],\n );\n\n runChatCompletionRef.current = runChatCompletion;\n\n const runChatCompletionAndHandleFunctionCall = useAsyncCallback(\n async (messages: Message[]): Promise<void> => {\n await runChatCompletionRef.current!(messages);\n },\n [messages],\n );\n\n useEffect(() => {\n if (!isLoading && pendingAppendsRef.current.length > 0) {\n const pending = pendingAppendsRef.current.splice(0);\n const followUp = pending.some((p) => p.followUp);\n const newMessages = [...messages, ...pending.map((p) => p.message)];\n setMessages(newMessages);\n if (followUp) {\n runChatCompletionAndHandleFunctionCall(newMessages);\n }\n }\n }, [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);\n\n // Go over all events and see that they include data that should be returned to the agent\n const composeAndFlushMetaEventsInput = useCallback(\n (metaEvents: (MetaEvent | undefined | null)[]) => {\n return metaEvents.reduce((acc: MetaEventInput[], event) => {\n if (!event) return acc;\n\n switch (event.name) {\n case MetaEventName.LangGraphInterruptEvent:\n if (event.response) {\n // Flush interrupt event from state\n setLangGraphInterruptAction(null);\n const value = (event as LangGraphInterruptEvent).value;\n return [\n ...acc,\n {\n name: event.name,\n value: typeof value === \"string\" ? value : JSON.stringify(value),\n response:\n typeof event.response === \"string\"\n ? event.response\n : JSON.stringify(event.response),\n },\n ];\n }\n return acc;\n default:\n return acc;\n }\n }, []);\n },\n [setLangGraphInterruptAction],\n );\n\n const append = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions): Promise<void> => {\n const followUp = options?.followUp ?? true;\n if (isLoading) {\n pendingAppendsRef.current.push({ message, followUp });\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n if (followUp) {\n return runChatCompletionAndHandleFunctionCall(newMessages);\n }\n },\n [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall],\n );\n\n const reload = useAsyncCallback(\n async (reloadMessageId: string): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n\n const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);\n if (reloadMessageIndex === -1) {\n console.warn(`Message with id ${reloadMessageId} not found`);\n return;\n }\n\n // @ts-expect-error -- message has role\n const reloadMessageRole = messages[reloadMessageIndex].role;\n if (reloadMessageRole !== MessageRole.Assistant) {\n console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);\n return;\n }\n\n let historyCutoff: Message[] = [];\n if (messages.length > 2) {\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(\n (msg) =>\n // @ts-expect-error -- message has role\n msg.role === MessageRole.User,\n );\n const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(\n (msg) => msg.id === lastUserMessageBeforeRegenerate!.id,\n );\n\n // Include the user message, remove everything after it\n historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);\n }\n\n setMessages(historyCutoff);\n\n return runChatCompletionAndHandleFunctionCall(historyCutoff);\n },\n [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall],\n );\n\n const stop = (): void => {\n chatAbortControllerRef.current?.abort(\"Stop was called\");\n };\n\n return {\n append,\n reload,\n stop,\n runChatCompletion: () => runChatCompletionRef.current!(messages),\n };\n}\n\nfunction constructFinalMessages(\n syncedMessages: Message[],\n previousMessages: Message[],\n newMessages: Message[],\n): Message[] {\n const finalMessages =\n syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];\n\n if (syncedMessages.length > 0) {\n const messagesWithAgentState = [...previousMessages, ...newMessages];\n\n let previousMessageId: string | undefined = undefined;\n\n for (const message of messagesWithAgentState) {\n if (message.isAgentStateMessage()) {\n // insert this message into finalMessages after the position of previousMessageId\n const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);\n if (index !== -1) {\n finalMessages.splice(index + 1, 0, message);\n }\n }\n\n previousMessageId = message.id;\n }\n }\n\n return finalMessages;\n}\n\nasync function executeAction({\n onFunctionCall,\n message,\n chatAbortControllerRef,\n onError,\n setMessages,\n getFinalMessages,\n isRenderAndWait,\n}: {\n onFunctionCall: FunctionCallHandler;\n message: ActionExecutionMessage;\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n onError: (error: Error) => void;\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n getFinalMessages: () => Message[];\n isRenderAndWait: boolean;\n}) {\n let result: any;\n let error: Error | null = null;\n\n const currentMessagesForHandler = getFinalMessages();\n\n // The handler (onFunctionCall) runs its synchronous part here, potentially setting up\n // renderAndWaitRef.current for HITL actions via useCopilotAction's transformed handler.\n const handlerReturnedPromise = onFunctionCall({\n messages: currentMessagesForHandler,\n name: message.name,\n args: message.arguments,\n });\n\n // For HITL actions, call flushSync immediately after their handler has set up the promise\n // and before awaiting the promise. This ensures the UI updates to an interactive state.\n if (isRenderAndWait) {\n const currentMessagesForRender = getFinalMessages();\n flushSync(() => {\n setMessages([...currentMessagesForRender]);\n });\n }\n\n try {\n result = await Promise.race([\n handlerReturnedPromise, // Await the promise returned by the handler\n new Promise((resolve) =>\n chatAbortControllerRef.current?.signal.addEventListener(\"abort\", () =>\n resolve(\"Operation was aborted by the user\"),\n ),\n ),\n // if the user stopped generation, we also abort consecutive actions\n new Promise((resolve) => {\n if (chatAbortControllerRef.current?.signal.aborted) {\n resolve(\"Operation was aborted by the user\");\n }\n }),\n ]);\n } catch (e) {\n onError(e as Error);\n }\n return new ResultMessage({\n id: \"result-\" + message.id,\n result: ResultMessage.encodeResult(\n error\n ? {\n content: result,\n error: JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error))),\n }\n : result,\n ),\n actionExecutionId: message.id,\n actionName: message.name,\n });\n}\n\nfunction getPairedFeAction(\n actions: FrontendAction<any>[],\n message: ActionExecutionMessage | ResultMessage,\n) {\n let actionName = null;\n if (message.isActionExecutionMessage()) {\n actionName = message.name;\n } else if (message.isResultMessage()) {\n actionName = message.actionName;\n }\n return actions.find(\n (action) =>\n (action.name === actionName && action.available === \"frontend\") ||\n action.pairedAction === actionName,\n );\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 = \"disabled\" | \"enabled\" | \"remote\" | \"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 ? (props: ActionRenderPropsNoArgs<T>) => 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(actions: FrontendAction<any>[]) {\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 = 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(actionParametersToJsonSchema(action.parameters || [])),\n available,\n };\n });\n return filteredActions;\n}\n","import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo, useRef } from \"react\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n CopilotErrorHandler,\n CopilotErrorEvent,\n} from \"@copilotkit/shared\";\nimport { shouldShowDevConsole } from \"../utils/dev-console\";\n\nexport interface CopilotRuntimeClientHookOptions extends CopilotRuntimeClientOptions {\n showDevConsole?: boolean;\n onError?: CopilotErrorHandler;\n}\n\nexport const useCopilotRuntimeClient = (options: CopilotRuntimeClientHookOptions) => {\n const { setBannerError } = useToast();\n const { showDevConsole, onError, ...runtimeOptions } = options;\n\n // Deduplication state for structured errors\n const lastStructuredErrorRef = useRef<{ message: string; timestamp: number } | null>(null);\n\n // Helper function to trace UI errors\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\n // Just check if onError and publicApiKey are defined\n if (!onError || !runtimeOptions.publicApiKey) return;\n\n try {\n const errorEvent: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"ui\",\n request: {\n operation: \"runtimeClient\",\n url: runtimeOptions.url,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onError(errorEvent);\n } catch (error) {\n console.error(\"Error in onError handler:\", error);\n }\n };\n\n const runtimeClient = useMemo(() => {\n return new CopilotRuntimeClient({\n ...runtimeOptions,\n handleGQLErrors: (error) => {\n if ((error as any).graphQLErrors?.length) {\n const graphQLErrors = (error as any).graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole ?? false);\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", gqlError.message);\n return;\n }\n\n // All errors (including DEV_ONLY) show as banners for consistency\n // Deduplicate to prevent spam\n const now = Date.now();\n const errorMessage = gqlError.message;\n if (\n lastStructuredErrorRef.current &&\n lastStructuredErrorRef.current.message === errorMessage &&\n now - lastStructuredErrorRef.current.timestamp < 150\n ) {\n return; // Skip duplicate\n }\n lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };\n\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the error\n traceUIError(ckError, gqlError);\n } 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 }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole ?? false);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n }\n }\n },\n 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, showDevConsole, onError]);\n\n return runtimeClient;\n};\n\n// Create appropriate structured error from GraphQL error\nfunction createStructuredError(gqlError: GraphQLError): CopilotKitError | null {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n // Legacy error detection by stack trace\n if (originalError?.stack?.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n\n return null;\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { ErrorToast } from \"../error-boundary/error-utils\";\nimport { PartialBy, CopilotKitError, CopilotKitErrorCode, Severity } from \"@copilotkit/shared\";\nimport { renderCopilotKitUsage } from \"../usage-banner\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(null);\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(/'message':\\s*'([^']+)'/);\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n","export function shouldShowDevConsole(showDevConsole: boolean): boolean {\n return showDevConsole;\n}\n","import React, { useCallback } from \"react\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { ExclamationMarkIcon } from \"../toast/exclamation-mark-icon\";\nimport ReactMarkdown from \"react-markdown\";\n\ninterface OriginalError {\n message?: string;\n stack?: string;\n}\n\nexport function ErrorToast({ errors }: { errors: (Error | GraphQLError)[] }) {\n const errorsToRender = errors.map((error, idx) => {\n const originalError =\n \"extensions\" in error ? (error.extensions?.originalError as undefined | OriginalError) : {};\n const message = originalError?.message ?? error.message;\n const code = \"extensions\" in error ? (error.extensions?.code as string) : null;\n\n return (\n <div\n key={idx}\n style={{\n marginTop: idx === 0 ? 0 : 10,\n marginBottom: 14,\n }}\n >\n <ExclamationMarkIcon style={{ marginBottom: 4 }} />\n\n {code && (\n <div\n style={{\n fontWeight: \"600\",\n marginBottom: 4,\n }}\n >\n Copilot Runtime Error:{\" \"}\n <span style={{ fontFamily: \"monospace\", fontWeight: \"normal\" }}>{code}</span>\n </div>\n )}\n <ReactMarkdown>{message}</ReactMarkdown>\n </div>\n );\n });\n return (\n <div\n style={{\n fontSize: \"13px\",\n maxWidth: \"600px\",\n }}\n >\n {errorsToRender}\n <div style={{ fontSize: \"11px\", opacity: 0.75 }}>\n NOTE: This error only displays during local development.\n </div>\n </div>\n );\n}\n\nexport function useErrorToast() {\n const { addToast } = useToast();\n\n return useCallback(\n (error: (Error | GraphQLError)[]) => {\n const errorId = error\n .map((err) => {\n const message =\n \"extensions\" in err\n ? (err.extensions?.originalError as any)?.message || err.message\n : err.message;\n const stack = err.stack || \"\";\n return btoa(message + stack).slice(0, 32); // Create hash from message + stack\n })\n .join(\"|\");\n\n addToast({\n type: \"error\",\n id: errorId, // Toast libraries typically dedupe by id\n message: <ErrorToast errors={error} />,\n });\n },\n [addToast],\n );\n}\n\nexport function useAsyncCallback<T extends (...args: any[]) => Promise<any>>(\n callback: T,\n deps: Parameters<typeof useCallback>[1],\n) {\n const addErrorToast = useErrorToast();\n return useCallback(async (...args: Parameters<T>) => {\n try {\n return await callback(...args);\n } catch (error) {\n console.error(\"Error in async callback:\", error);\n // @ts-ignore\n addErrorToast([error]);\n throw error;\n }\n }, deps);\n}\n","import React from \"react\";\n\nexport const ExclamationMarkIcon = ({\n className,\n style,\n}: {\n className?: string;\n style?: React.CSSProperties;\n}) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={`lucide lucide-circle-alert ${className ? className : \"\"}`}\n style={style}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"12\" x2=\"12\" y1=\"8\" y2=\"12\" />\n <line x1=\"12\" x2=\"12.01\" y1=\"16\" y2=\"16\" />\n </svg>\n);\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, SetStateAction } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"../../hooks/use-copilot-runtime-client\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetterArgs,\n} from \"../../types/interrupt-action\";\nimport { StatusChecker } from \"../../lib/status-checker\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const showDevConsole = props.showDevConsole ?? false;\n const enabled = shouldShowDevConsole(showDevConsole);\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={props.publicApiKey} showUsageBanner={enabled}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<string[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const statusChecker = useMemo(() => new StatusChecker(), []);\n\n const [usageBannerStatus, setUsageBannerStatus] = useState<any>(null);\n\n // Compute all the functions and properties that we need to pass\n\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => {\n return {\n ...prevPoints,\n [id]: stateRender,\n };\n });\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n props.publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: props.showDevConsole ?? false,\n onError: props.onError,\n });\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n const hasLoadedAgents = useRef(false);\n\n useEffect(() => {\n if (hasLoadedAgents.current) return;\n\n const fetchData = async () => {\n const result = await runtimeClient.availableAgents();\n if (result.data?.availableAgents) {\n setAvailableAgents(result.data.availableAgents.agents);\n }\n hasLoadedAgents.current = true;\n };\n void fetchData();\n }, []);\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const [internalThreadId, setInternalThreadId] = useState<string>(props.threadId || randomUUID());\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\"Cannot call setThreadId() when threadId is provided via props.\");\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n // update the internal threadId if the props.threadId changes\n useEffect(() => {\n if (props.threadId !== undefined) {\n setInternalThreadId(props.threadId);\n }\n }, [props.threadId]);\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = props.showDevConsole ?? false;\n\n const [langGraphInterruptAction, _setLangGraphInterruptAction] =\n useState<LangGraphInterruptAction | null>(null);\n const setLangGraphInterruptAction = useCallback((action: LangGraphInterruptActionSetterArgs) => {\n _setLangGraphInterruptAction((prev) => {\n if (prev == null) return action as LangGraphInterruptAction;\n if (action == null) return null;\n let event = prev.event;\n if (action.event) {\n // @ts-ignore\n event = { ...prev.event, ...action.event };\n }\n return { ...prev, ...action, event };\n });\n }, []);\n const removeLangGraphInterruptAction = useCallback((): void => {\n setLangGraphInterruptAction(null);\n }, []);\n\n const memoizedChildren = useMemo(() => children, [children]);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = typeof newExtensions === \"function\" ? newExtensions(prev) : newExtensions;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved = typeof newAuthStates === \"function\" ? newAuthStates(prev) : newAuthStates;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n runtimeClient,\n forwardedParameters,\n agentLock,\n threadId: internalThreadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n removeLangGraphInterruptAction,\n onError: props.onError,\n }}\n >\n <CopilotMessages>{memoizedChildren}</CopilotMessages>\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ name, args }: { name: string; args: Record<string, any> }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n if (!props.runtimeUrl && !props.publicApiKey) {\n throw new ConfigurationError(\"Missing required prop: 'runtimeUrl' or 'publicApiKey'\");\n }\n\n if (cloudFeatures.length > 0 && !props.publicApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport React from \"react\";\n\nexport interface CopilotMessagesContextParams {\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n}\n\nconst emptyCopilotContext: CopilotMessagesContextParams = {\n messages: [],\n setMessages: () => [],\n};\n\nexport const CopilotMessagesContext =\n React.createContext<CopilotMessagesContextParams>(emptyCopilotContext);\n\nexport function useCopilotMessagesContext(): CopilotMessagesContextParams {\n const context = React.useContext(CopilotMessagesContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`\",\n );\n }\n return context;\n}\n","/**\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=\"/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 { Parameter, randomId } from \"@copilotkit/shared\";\nimport { createElement, Fragment, useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport {\n ActionRenderProps,\n ActionRenderPropsNoArgsWait,\n ActionRenderPropsWait,\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n const renderAndWaitRef = useRef<RenderAndWaitForResponse | null>(null);\n const activatingMessageIdRef = useRef<string | null>(null);\n const { addToast } = useToast();\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // const { currentlyActivatingHitlActionMessageIdRef } = useCopilotContext() as any; // <-- REMOVE THIS FOR NOW\n\n // If the developer provides a renderAndWaitForResponse function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (\n // renderAndWaitForResponse is not available for catch all actions\n isFrontendAction(action) &&\n // check if renderAndWaitForResponse is set\n (action.renderAndWait || action.renderAndWaitForResponse)\n ) {\n (action as any)._isRenderAndWait = true; // Internal flag to identify this action type later\n const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n action.renderAndWaitForResponse = undefined;\n\n // Add a method for use-chat.ts to set the activating message ID.\n // This helps correlate the action instance with the message being processed by use-chat.\n (action as any)._setActivatingMessageId = (id: string | null) => {\n activatingMessageIdRef.current = id;\n };\n\n // add a handler that will be called when the action is executed\n action.handler = useAsyncCallback(async () => {\n const currentActivatingId = activatingMessageIdRef.current;\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = {\n promise,\n resolve: resolve!,\n reject: reject!,\n messageId: currentActivatingId,\n };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n const result = await promise;\n return result;\n }, []) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<T> & { messageId?: string }): React.ReactElement => {\n const currentRenderMessageId = props.messageId;\n // For renderAndWaitForResponse, the 'executing' state might be set by use-chat before\n // this specific action instance's handler (and thus its promise) is ready.\n // This logic adjusts the status to 'inProgress' if the current render\n // isn't for the actively processing HITL action, preventing premature interaction.\n let status = props.status;\n if (props.status === \"executing\") {\n if (!renderAndWaitRef.current || !renderAndWaitRef.current.promise) {\n status = \"inProgress\";\n } else if (\n renderAndWaitRef.current.messageId !== currentRenderMessageId &&\n activatingMessageIdRef.current !== currentRenderMessageId\n ) {\n status = \"inProgress\";\n }\n // If conditions met, status remains 'executing'\n }\n // Create type safe waitProps based on whether T extends empty array or not\n const waitProps = {\n status,\n args: props.args,\n result: props.result,\n // handler and respond should only be provided if this is the truly active instance\n // and its promise infrastructure is ready.\n handler:\n status === \"executing\" &&\n renderAndWaitRef.current &&\n renderAndWaitRef.current.messageId === currentRenderMessageId\n ? renderAndWaitRef.current!.resolve\n : undefined,\n respond:\n status === \"executing\" &&\n renderAndWaitRef.current &&\n renderAndWaitRef.current.messageId === currentRenderMessageId\n ? renderAndWaitRef.current!.resolve\n : undefined,\n } as T extends [] ? ActionRenderPropsNoArgsWait<T> : ActionRenderPropsWait<T>;\n\n // Type guard to check if renderAndWait is for no args case\n const isNoArgsRenderWait = (\n _fn:\n | ((props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement)\n | ((props: ActionRenderPropsWait<T>) => React.ReactElement),\n ): _fn is (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement => {\n return action.parameters?.length === 0;\n };\n\n // Safely call renderAndWait with correct props type\n if (renderAndWait) {\n if (isNoArgsRenderWait(renderAndWait)) {\n return renderAndWait(waitProps as ActionRenderPropsNoArgsWait<T>);\n } else {\n return renderAndWait(waitProps as ActionRenderPropsWait<T>);\n }\n }\n\n // Return empty Fragment instead of null\n return createElement(Fragment);\n }) as any;\n }\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n // catch all actions don't have a handler\n if (isFrontendAction(action)) {\n actions[idRef.current].handler = action.handler as any;\n }\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n // TODO: using as any here because the type definitions are getting to tricky\n // not wasting time on this now - we know the types are compatible\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n }\n }\n }\n\n useEffect(() => {\n const hasDuplicate = Object.values(actions).some(\n (otherAction) => otherAction.name === action.name && otherAction !== actions[idRef.current],\n );\n\n if (hasDuplicate) {\n addToast({\n type: \"warning\",\n message: `Found an already registered action with name ${action.name}.`,\n id: `dup-action-${action.name}`,\n });\n }\n }, [actions]);\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n // see comment about type safety above\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n // UPDATE: We now have access, we should remove the entry if not referenced by any message.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n isFrontendAction(action) ? action.description : undefined,\n action.name,\n isFrontendAction(action) ? action.disabled : undefined,\n isFrontendAction(action) ? action.available : undefined,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(isFrontendAction(action) ? action.parameters : []),\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\nfunction isFrontendAction<T extends Parameter[]>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n): action is FrontendAction<T> {\n return action.name !== \"*\";\n}\n\ninterface RenderAndWaitForResponse {\n promise: Promise<any>;\n resolve: (result: any) => void;\n reject: (error: any) => void;\n messageId: string | null;\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\";\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 {\n setCoAgentStateRender,\n removeCoAgentStateRender,\n coAgentStateRenders,\n chatComponentsCache,\n availableAgents,\n } = useContext(CopilotContext);\n const idRef = useRef<string>(randomId());\n const { setBannerError, addToast } = useToast();\n\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === action.name)) {\n const message = `(useCoAgentStateRender): Agent \"${action.name}\" not found. Make sure the agent exists and is properly configured.`;\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: action.name,\n availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coAgentStateRenders[idRef.current]) {\n coAgentStateRenders[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n // Check for duplicates by comparing against all other actions\n const currentId = idRef.current;\n const hasDuplicate = Object.entries(coAgentStateRenders).some(([id, otherAction]) => {\n // Skip comparing with self\n if (id === currentId) return false;\n\n // Different agent names are never duplicates\n if (otherAction.name !== action.name) return false;\n\n // Same agent names:\n const hasNodeName = !!action.nodeName;\n const hasOtherNodeName = !!otherAction.nodeName;\n\n // If neither has nodeName, they're duplicates\n if (!hasNodeName && !hasOtherNodeName) return true;\n\n // If one has nodeName and other doesn't, they're not duplicates\n if (hasNodeName !== hasOtherNodeName) return false;\n\n // If both have nodeName, they're duplicates only if the names match\n return action.nodeName === otherAction.nodeName;\n });\n\n if (hasDuplicate) {\n const message = action.nodeName\n ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden`\n : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;\n\n addToast({\n type: \"warning\",\n message,\n id: `dup-action-${action.name}`,\n });\n }\n }, [coAgentStateRenders]);\n\n useEffect(() => {\n setCoAgentStateRender(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n return () => {\n removeCoAgentStateRender(idRef.current);\n };\n }, [\n setCoAgentStateRender,\n removeCoAgentStateRender,\n action.name,\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n","import { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useCopilotContext();\n const idRef = useRef<string>();\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 { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\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\nfunction convertToJSON(description: string, value: any): string {\n return `${description}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n {\n description,\n value,\n parentId,\n categories,\n convert,\n available = \"enabled\",\n }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { addContext, removeContext } = useCopilotContext();\n const idRef = useRef<string>();\n convert = convert || convertToJSON;\n\n const information = convert(description, value);\n\n useEffect(() => {\n if (available === \"disabled\") return;\n\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [available, information, parentId, addContext, removeContext, ...(dependencies || [])]);\n\n return idRef.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=\"/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 } from \"react\";\nimport {\n CopilotContextParams,\n CopilotMessagesContextParams,\n useCopilotContext,\n useCopilotMessagesContext,\n} from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { useCopilotChat } from \"./use-copilot-chat\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { parseJson, CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<T> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (hint?: HintFunction) => Promise<void>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n const generalContext = useCopilotContext();\n const { availableAgents } = generalContext;\n const { setBannerError } = useToast();\n const lastLoadedThreadId = useRef<string>();\n const lastLoadedState = useRef<any>();\n\n const { name } = options;\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === name)) {\n const message = `(useCoAgent): Agent \"${name}\" not found. Make sure the agent exists and is properly configured.`;\n console.warn(message);\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: name,\n availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const messagesContext = useCopilotMessagesContext();\n const context = { ...generalContext, ...messagesContext };\n const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } =\n context;\n const { appendMessage, runChatCompletion } = useCopilotChat();\n const headers = {\n ...(copilotApiConfig.headers || {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: context.showDevConsole,\n });\n\n // if we manage state internally, we need to provide a function to set the state\n const setState = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n // coagentStatesRef.current || {}\n let coagentState: CoagentState = getCoagentState({ coagentStates, name, options });\n const updatedState =\n typeof newState === \"function\" ? (newState as Function)(coagentState.state) : newState;\n\n setCoagentStatesWithRef({\n ...coagentStatesRef.current,\n [name]: {\n ...coagentState,\n state: updatedState,\n },\n });\n },\n [coagentStates, name],\n );\n\n useEffect(() => {\n const fetchAgentState = async () => {\n if (!threadId || threadId === lastLoadedThreadId.current) return;\n\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: name,\n });\n\n // Runtime client handles errors automatically via handleGQLErrors\n if (result.error) {\n return; // Don't process data on error\n }\n\n const newState = result.data?.loadAgentState?.state;\n if (newState === lastLoadedState.current) return;\n\n if (result.data?.loadAgentState?.threadExists && newState && newState != \"{}\") {\n lastLoadedState.current = newState;\n lastLoadedThreadId.current = threadId;\n const fetchedState = parseJson(newState, {});\n isExternalStateManagement(options)\n ? options.setState(fetchedState)\n : setState(fetchedState);\n }\n };\n void fetchAgentState();\n }, [threadId]);\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n setState(options.state);\n } else if (coagentStates[name] === undefined) {\n setState(options.initialState === undefined ? {} : options.initialState);\n }\n }, [\n isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined,\n // reset initialstate on reset\n coagentStates[name] === undefined,\n ]);\n\n // Sync config when runtime configuration changes\n useEffect(() => {\n const newConfig = options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : undefined;\n\n if (newConfig === undefined) return;\n\n setCoagentStatesWithRef((prev) => {\n const existing = prev[name] ?? {\n name,\n state: isInternalStateManagementWithInitial(options) ? options.initialState : {},\n config: {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n\n if (JSON.stringify(existing.config) === JSON.stringify(newConfig)) {\n return prev;\n }\n\n return {\n ...prev,\n [name]: {\n ...existing,\n config: newConfig,\n },\n };\n });\n }, [JSON.stringify(options.config), JSON.stringify(options.configurable)]);\n\n const runAgentCallback = useAsyncCallback(\n async (hint?: HintFunction) => {\n await runAgent(name, context, appendMessage, runChatCompletion, hint);\n },\n [name, context, appendMessage, runChatCompletion],\n );\n\n // Return the state and setState function\n return useMemo(() => {\n const coagentState = getCoagentState({ coagentStates, name, options });\n return {\n name,\n nodeName: coagentState.nodeName,\n threadId: coagentState.threadId,\n running: coagentState.running,\n state: coagentState.state,\n setState: isExternalStateManagement(options) ? options.setState : setState,\n start: () => startAgent(name, context),\n stop: () => stopAgent(name, context),\n run: runAgentCallback,\n };\n }, [name, coagentStates, options, setState, runAgentCallback]);\n}\n\nexport function startAgent(name: string, context: CopilotContextParams) {\n const { setAgentSession } = context;\n setAgentSession({\n agentName: name,\n });\n}\n\nexport function stopAgent(name: string, context: CopilotContextParams) {\n const { agentSession, setAgentSession } = context;\n if (agentSession && agentSession.agentName === name) {\n setAgentSession(null);\n context.setCoagentStates((prevAgentStates) => {\n return {\n ...prevAgentStates,\n [name]: {\n ...prevAgentStates[name],\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n },\n };\n });\n } else {\n console.warn(`No agent session found for ${name}`);\n }\n}\n\nexport async function runAgent(\n name: string,\n context: CopilotContextParams & CopilotMessagesContextParams,\n appendMessage: (message: Message) => Promise<void>,\n runChatCompletion: () => Promise<Message[]>,\n hint?: HintFunction,\n) {\n const { agentSession, setAgentSession } = context;\n if (!agentSession || agentSession.agentName !== name) {\n setAgentSession({\n agentName: name,\n });\n }\n\n let previousState: any = null;\n for (let i = context.messages.length - 1; i >= 0; i--) {\n const message = context.messages[i];\n if (message.isAgentStateMessage() && message.agentName === name) {\n previousState = message.state;\n }\n }\n\n let state = context.coagentStatesRef.current?.[name]?.state || {};\n\n if (hint) {\n const hintMessage = hint({ previousState, currentState: state });\n if (hintMessage) {\n await appendMessage(hintMessage);\n } else {\n await runChatCompletion();\n }\n } else {\n await runChatCompletion();\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\nconst isInternalStateManagementWithInitial = <T>(\n options: UseCoagentOptions<T>,\n): options is WithInternalStateManagementAndInitial<T> => {\n return \"initialState\" in options;\n};\n\nconst getCoagentState = <T>({\n coagentStates,\n name,\n options,\n}: {\n coagentStates: Record<string, CoagentState>;\n name: string;\n options: UseCoagentOptions<T>;\n}) => {\n if (coagentStates[name]) {\n return coagentStates[name];\n } else {\n return {\n name,\n state: isInternalStateManagementWithInitial<T>(options) ? options.initialState : {},\n config: options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n }\n};\n","import { Parameter } from \"@copilotkit/shared\";\nimport { Fragment, useCallback, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { FrontendAction, ActionRenderProps } from \"../types/frontend-action\";\nimport { useCopilotAction } from \"./use-copilot-action\";\nimport React from \"react\";\n\n/**\n * Hook to create an authenticated action that requires user sign-in before execution.\n *\n * @remarks\n * This feature is only available when using CopilotKit's hosted cloud service.\n * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.\n *\n * @param action - The frontend action to be wrapped with authentication\n * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed\n */\nexport function useCopilotAuthenticatedAction_c<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();\n const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);\n\n const executeAction = useCallback(\n (props: ActionRenderProps<Parameter[]>) => {\n if (typeof action.render === \"function\") {\n return action.render(props);\n }\n return action.render || React.createElement(Fragment);\n },\n [action],\n );\n\n const wrappedRender = useCallback(\n (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {\n const isAuthenticated = Object.values(authStates_c || {}).some(\n (state) => state.status === \"authenticated\",\n );\n\n if (!isAuthenticated) {\n // Store action details for later execution\n pendingActionRef.current = props;\n\n return authConfig_c?.SignInComponent\n ? React.createElement(authConfig_c.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates_c?.((prev) => ({ ...prev, [action.name]: authState }));\n if (pendingActionRef.current) {\n executeAction(pendingActionRef.current);\n pendingActionRef.current = null;\n }\n },\n })\n : React.createElement(Fragment);\n }\n\n return executeAction(props);\n },\n [action, authStates_c, setAuthStates_c],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\n}\n","import { useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { LangGraphInterruptRender } from \"../types/interrupt-action\";\nimport { useCopilotChat } from \"./use-copilot-chat\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { dataToUUID } from \"@copilotkit/shared\";\n\nexport function useLangGraphInterrupt<TEventValue = any>(\n action: Omit<LangGraphInterruptRender<TEventValue>, \"id\">,\n dependencies?: any[],\n) {\n const { setLangGraphInterruptAction, removeLangGraphInterruptAction, langGraphInterruptAction } =\n useContext(CopilotContext);\n const { runChatCompletion } = useCopilotChat();\n const { addToast } = useToast();\n\n const actionId = dataToUUID(JSON.stringify(action), \"lgAction\");\n // We only consider action to be defined once the ID is there\n const hasAction = useMemo(\n () => Boolean(langGraphInterruptAction?.id),\n [langGraphInterruptAction],\n );\n\n const isCurrentAction = useMemo(\n () => langGraphInterruptAction?.id && langGraphInterruptAction?.id === actionId,\n [langGraphInterruptAction],\n );\n\n // Run chat completion to submit a response event. Only if it's the current action\n useEffect(() => {\n if (hasAction && isCurrentAction && langGraphInterruptAction?.event?.response) {\n runChatCompletion();\n }\n }, [langGraphInterruptAction?.event?.response, runChatCompletion, hasAction, isCurrentAction]);\n\n useEffect(() => {\n if (!action) return;\n // An action was already set, with no conditions and it's not the action we're using right now.\n // Show a warning, as this action will not be executed\n if (hasAction && !isCurrentAction && !action.enabled) {\n addToast({\n type: \"warning\",\n message: \"An action is already registered for the interrupt event\",\n });\n return;\n }\n\n if (hasAction && isCurrentAction) {\n return;\n }\n\n setLangGraphInterruptAction({ ...action, id: actionId });\n }, [\n action,\n hasAction,\n isCurrentAction,\n setLangGraphInterruptAction,\n removeLangGraphInterruptAction,\n ...(dependencies || []),\n ]);\n}\n","import { useCopilotContext } from \"../context\";\nimport React, { useCallback } from \"react\";\nimport { executeConditions } from \"@copilotkit/shared\";\n\ntype InterruptProps = {\n event: any;\n result: any;\n render: (props: {\n event: any;\n result: any;\n resolve: (response: string) => void;\n }) => string | React.ReactElement;\n resolve: (response: string) => void;\n};\n\nconst InterruptRenderer: React.FC<InterruptProps> = ({ event, result, render, resolve }) => {\n return render({ event, result, resolve });\n};\n\nexport function useLangGraphInterruptRender(): string | React.ReactElement | null {\n const { langGraphInterruptAction, setLangGraphInterruptAction, agentSession } =\n useCopilotContext();\n\n const responseRef = React.useRef<string>();\n const resolveInterrupt = useCallback(\n (response: string) => {\n responseRef.current = response;\n // Use setTimeout to defer the state update to next tick\n setTimeout(() => {\n setLangGraphInterruptAction({ event: { response } });\n }, 0);\n },\n [setLangGraphInterruptAction],\n );\n\n if (\n !langGraphInterruptAction ||\n !langGraphInterruptAction.event ||\n !langGraphInterruptAction.render\n )\n return null;\n\n const { render, handler, event, enabled } = langGraphInterruptAction;\n\n const conditionsMet =\n !agentSession || !enabled\n ? true\n : enabled({ eventValue: event.value, agentMetadata: agentSession });\n if (!conditionsMet) {\n return null;\n }\n\n let result = null;\n if (handler) {\n result = handler({\n event,\n resolve: resolveInterrupt,\n });\n }\n\n return React.createElement(InterruptRenderer, {\n event,\n result,\n render,\n resolve: resolveInterrupt,\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 { instructions, available = \"enabled\" }: UseCopilotAdditionalInstructionsOptions,\n dependencies?: any[],\n) {\n const { setAdditionalInstructions } = useCopilotContext();\n\n useEffect(() => {\n if (available === \"disabled\") return;\n\n setAdditionalInstructions((prevInstructions) => [...(prevInstructions || []), instructions]);\n\n return () => {\n setAdditionalInstructions(\n (prevInstructions) =>\n prevInstructions?.filter((instruction) => instruction !== instructions) || [],\n );\n };\n }, [available, instructions, setAdditionalInstructions, ...(dependencies || [])]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC4CA,IAAAA,gBAAyD;;;ACtCzD,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;AAAA,EACT;AAEA,MAAI,SAAS;AACb,MAAI,SAAS;AACX,aAAS,QAAQ;AAAA,MACf;AAAA,MACA,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,SAAO,eAAAA,QAAM,cAAc,mBAAmB;AAAA,IAC5C;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,EACX,CAAC;AACH;;;AC5BA,IAAAC,iBAA0B;AA4BnB,SAAS,iCACd,EAAE,cAAc,YAAY,UAAU,GACtC,cACA;AACA,QAAM,EAAE,0BAA0B,IAAI,kBAAkB;AAExD,gCAAU,MAAM;AACd,QAAI,cAAc;AAAY;AAE9B,8BAA0B,CAAC,qBAAqB,CAAC,GAAI,oBAAoB,CAAC,GAAI,YAAY,CAAC;AAE3F,WAAO,MAAM;AACX;AAAA,QACE,CAAC,sBACC,qDAAkB,OAAO,CAAC,gBAAgB,gBAAgB,kBAAiB,CAAC;AAAA,MAChF;AAAA,IACF;AAAA,EACF,GAAG,CAAC,WAAW,cAAc,2BAA2B,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAClF;","names":["import_react","React","import_runtime_client_gql","import_react","import_shared","import_runtime_client_gql","import_runtime_client_gql","import_react","import_shared","import_react","import_shared","error","_a","import_react","import_jsx_runtime","import_jsx_runtime","ReactMarkdown","messages","_a","action","options","import_react","import_react_dom","import_shared","import_react","emptyCopilotContext","React","import_jsx_runtime","_a","action","options","messages","import_shared","import_react","import_react","import_shared","import_react","import_react","import_react","import_shared","import_react","import_react","executeAction","React","import_react","import_shared","_a","import_react","React","import_react"]}
1
+ {"version":3,"sources":["../../src/hooks/index.ts","../../src/hooks/use-copilot-chat.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-chat.ts","../../src/types/frontend-action.ts","../../src/hooks/use-copilot-runtime-client.ts","../../src/components/toast/toast-provider.tsx","../../src/utils/dev-console.ts","../../src/components/error-boundary/error-utils.tsx","../../src/components/toast/exclamation-mark-icon.tsx","../../src/components/copilot-provider/copilotkit.tsx","../../src/context/copilot-messages-context.tsx","../../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-coagent.ts","../../src/hooks/use-copilot-authenticated-action.ts","../../src/hooks/use-langgraph-interrupt.ts","../../src/hooks/use-langgraph-interrupt-render.ts","../../src/hooks/use-copilot-additional-instructions.ts"],"sourcesContent":["export { useCopilotChat } from \"./use-copilot-chat\";\nexport type { UseCopilotChatOptions } from \"./use-copilot-chat\";\nexport type { UseCopilotChatReturn } from \"./use-copilot-chat\";\n\nexport { useCopilotAction } from \"./use-copilot-action\";\nexport { useCoAgentStateRender } from \"./use-coagent-state-render\";\nexport { useMakeCopilotDocumentReadable } from \"./use-make-copilot-document-readable\";\nexport { type UseChatHelpers } from \"./use-chat\";\nexport { useCopilotReadable } from \"./use-copilot-readable\";\nexport { useCoAgent, type HintFunction, runAgent, startAgent, stopAgent } from \"./use-coagent\";\nexport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nexport { useCopilotAuthenticatedAction_c } from \"./use-copilot-authenticated-action\";\nexport { useLangGraphInterrupt } from \"./use-langgraph-interrupt\";\nexport { useLangGraphInterruptRender } from \"./use-langgraph-interrupt-render\";\nexport { useCopilotAdditionalInstructions } from \"./use-copilot-additional-instructions\";\nexport type { Tree, TreeNode } from \"./use-tree\";\n","/**\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n *\n * // optionally, you can append a message without running chat completion\n * appendMessage(yourMessage, { followUp: false });\n * }\n * ```\n *\n * `useCopilotChat` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * visibleMessages, // An array of messages that are currently visible in the chat.\n * appendMessage, // A function to append a message to the chat.\n * setMessages, // A function to set the messages in the chat.\n * deleteMessage, // A function to delete a message from the chat.\n * reloadMessages, // A function to reload the messages from the API.\n * stopGeneration, // A function to stop the generation of the next message.\n * reset, // A function to reset the chat.\n * isLoading, // A boolean indicating if the chat is loading.\n * } = useCopilotChat();\n * ```\n */\nimport { useRef, useEffect, useCallback, useState } from \"react\";\nimport { AgentSession, useCopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat, AppendMessageOptions } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CoAgentStateRenderHandlerArguments } from \"@copilotkit/shared\";\nimport { useCopilotMessagesContext } from \"../context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\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 * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface MCPServerConfig {\n endpoint: string;\n apiKey?: string;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: (messageId: string) => Promise<void>;\n stopGeneration: () => void;\n reset: () => void;\n isLoading: boolean;\n runChatCompletion: () => Promise<Message[]>;\n mcpServers: MCPServerConfig[];\n setMcpServers: (mcpServers: MCPServerConfig[]) => void;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n coagentStatesRef,\n setCoagentStatesWithRef,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n } = useCopilotContext();\n const { messages, setMessages } = useCopilotMessagesContext();\n\n // Simple state for MCP servers (keep for interface compatibility)\n const [mcpServers, setLocalMcpServers] = useState<MCPServerConfig[]>([]);\n\n // This effect directly updates the context when mcpServers state changes\n useEffect(() => {\n if (mcpServers.length > 0) {\n // Copy to avoid issues\n const serversCopy = [...mcpServers];\n\n // Update in all locations\n copilotApiConfig.mcpServers = serversCopy;\n\n // Also ensure it's in properties\n if (!copilotApiConfig.properties) {\n copilotApiConfig.properties = {};\n }\n copilotApiConfig.properties.mcpServers = serversCopy;\n }\n }, [mcpServers, copilotApiConfig]);\n\n // Provide the same interface\n const setMcpServers = useCallback((servers: MCPServerConfig[]) => {\n setLocalMcpServers(servers);\n }, []);\n\n // Move these function declarations above the useChat call\n const onCoAgentStateRender = useAsyncCallback(\n async (args: CoAgentStateRenderHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coAgentStateRenders],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: Role.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n // Get chat helpers with updated config\n const { append, reload, stop, runChatCompletion } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n onCoAgentStateRender,\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n });\n\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n return await latestAppend.current(message, options);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(\n async (messageId: string) => {\n return await latestReload.current(messageId);\n },\n [latestReload],\n );\n\n const latestStop = useUpdatedRef(stop);\n const latestStopFunc = useCallback(() => {\n return latestStop.current();\n }, [latestStop]);\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 latestSetMessages = useUpdatedRef(setMessages);\n const latestSetMessagesFunc = useCallback(\n (messages: Message[]) => {\n return latestSetMessages.current(messages);\n },\n [latestSetMessages],\n );\n\n const latestRunChatCompletion = useUpdatedRef(runChatCompletion);\n const latestRunChatCompletionFunc = useAsyncCallback(async () => {\n return await latestRunChatCompletion.current!();\n }, [latestRunChatCompletion]);\n\n const reset = useCallback(() => {\n latestStopFunc();\n setMessages([]);\n setRunId(null);\n setCoagentStatesWithRef({});\n let initialAgentSession: AgentSession | null = null;\n if (agentLock) {\n initialAgentSession = {\n agentName: agentLock,\n };\n }\n setAgentSession(initialAgentSession);\n }, [\n latestStopFunc,\n setMessages,\n setThreadId,\n setCoagentStatesWithRef,\n setAgentSession,\n agentLock,\n ]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n return {\n visibleMessages: messages,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n runChatCompletion: latestRunChatCompletionFunc,\n isLoading,\n mcpServers,\n setMcpServers,\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\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n","import { CopilotCloudConfig, FunctionCallHandler, CopilotErrorHandler } from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Optional configuration for connecting to Model Context Protocol (MCP) servers.\n * This is typically derived from the CopilotKitProps and used internally.\n * @experimental\n */\n mcpServers?: Array<{ endpoint: string; apiKey?: string }>;\n}\n\nexport type InChatRenderFunction<TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>> =\n (props: TProps) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\nexport type ContextTree = Tree;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // coagent actions\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n additionalInstructions?: string[];\n setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean;\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n // runtime\n runtimeClient: CopilotRuntimeClient;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Partial<Pick<ForwardedParametersInput, \"temperature\">>;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n langGraphInterruptAction: LangGraphInterruptAction | null;\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n removeLangGraphInterruptAction: () => void;\n\n /**\n * Optional trace handler for comprehensive debugging and observability.\n */\n onError?: CopilotErrorHandler;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coAgentStateRenders: {},\n setCoAgentStateRender: () => {},\n removeCoAgentStateRender: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n getAllContext: () => [],\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n additionalInstructions: [],\n setAdditionalInstructions: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n runtimeClient: {} as any,\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: false,\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n langGraphInterruptAction: null,\n setLangGraphInterruptAction: () => null,\n removeLangGraphInterruptAction: () => null,\n onError: undefined,\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n","import React, { useCallback, useEffect, useRef } from \"react\";\nimport { flushSync } from \"react-dom\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n CoAgentStateRenderHandler,\n randomId,\n parseJson,\n CopilotKitError,\n CopilotKitErrorCode,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ResultMessage,\n convertMessagesToGqlInput,\n filterAdjacentAgentStateMessages,\n filterAgentStateMessages,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n ForwardedParametersInput,\n loadMessagesFromJsonRepresentation,\n ExtensionsInput,\n CopilotRuntimeClient,\n langGraphInterruptEvent,\n MetaEvent,\n MetaEventName,\n ActionExecutionMessage,\n CopilotKitLangGraphInterruptEvent,\n LangGraphInterruptEvent,\n MetaEventInput,\n AgentStateInput,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession, useCopilotContext } from \"../context/copilot-context\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { useAsyncCallback, useErrorToast } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n\n /**\n * Callback function to be called when a coagent action is received.\n */\n onCoAgentStateRender?: CoAgentStateRenderHandler;\n\n /**\n * Function definitions to be sent to the API.\n */\n actions: FrontendAction<any>[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * The current list of coagent states.\n */\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStatesWithRef: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n\n /**\n * The current agent session.\n */\n agentSession: AgentSession | null;\n\n /**\n * setState-powered method to update the agent session\n */\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n /**\n * The forwarded parameters.\n */\n forwardedParameters?: Pick<ForwardedParametersInput, \"temperature\">;\n\n /**\n * The current thread ID.\n */\n threadId: string;\n /**\n * set the current thread ID\n */\n setThreadId: (threadId: string) => void;\n /**\n * The current run ID.\n */\n runId: string | null;\n /**\n * set the current run ID\n */\n setRunId: (runId: string | null) => void;\n /**\n * The global chat abort controller.\n */\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n /**\n * The agent lock.\n */\n agentLock: string | null;\n /**\n * The extensions.\n */\n extensions: ExtensionsInput;\n /**\n * The setState-powered method to update the extensions.\n */\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n\n langGraphInterruptAction: LangGraphInterruptAction | null;\n\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (messageId: string) => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Run the chat completion.\n */\n runChatCompletion: () => Promise<Message[]>;\n};\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\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStatesWithRef,\n coagentStatesRef,\n agentSession,\n setAgentSession,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n } = options;\n const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();\n const addErrorToast = useErrorToast();\n const { setBannerError } = useToast();\n\n // Get onError from context since it's not part of copilotConfig\n const { onError } = useCopilotContext();\n\n // Add tracing functionality to use-chat\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\n // Just check if onError and publicApiKey are defined\n if (!onError || !copilotConfig?.publicApiKey) return;\n\n try {\n const traceEvent = {\n type: \"error\" as const,\n timestamp: Date.now(),\n context: {\n source: \"ui\" as const,\n request: {\n operation: \"useChatCompletion\",\n url: copilotConfig.chatApiEndpoint,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n\n await onError(traceEvent);\n } catch (traceError) {\n console.error(\"Error in use-chat onError handler:\", traceError);\n }\n };\n // We need to keep a ref of coagent states and session because of renderAndWait - making sure\n // the latest state is sent to the API\n // This is a workaround and needs to be addressed in the future\n const agentSessionRef = useRef<AgentSession | null>(agentSession);\n agentSessionRef.current = agentSession;\n\n const runIdRef = useRef<string | null>(runId);\n runIdRef.current = runId;\n const extensionsRef = useRef<ExtensionsInput>(extensions);\n extensionsRef.current = extensions;\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const { showDevConsole } = useCopilotContext();\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n showDevConsole,\n });\n\n const pendingAppendsRef = useRef<{ message: Message; followUp: boolean }[]>([]);\n\n const runChatCompletion = useAsyncCallback(\n async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n const interruptEvent = langGraphInterruptAction?.event;\n // In case an interrupt event exist and valid but has no response yet, we cannot process further messages to an agent\n if (\n interruptEvent?.name === MetaEventName.LangGraphInterruptEvent &&\n interruptEvent?.value &&\n !interruptEvent?.response &&\n agentSessionRef.current\n ) {\n addErrorToast([\n new Error(\n \"A message was sent while interrupt is active. This will cause failure on the agent side\",\n ),\n ]);\n }\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n\n chatAbortControllerRef.current = new AbortController();\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n // ----- Set mcpServers in properties -----\n // Create a copy of properties to avoid modifying the original object\n const finalProperties = { ...(copilotConfig.properties || {}) };\n\n // Look for mcpServers in either direct property or properties\n let mcpServersToUse = null;\n\n // First check direct mcpServers property\n if (\n copilotConfig.mcpServers &&\n Array.isArray(copilotConfig.mcpServers) &&\n copilotConfig.mcpServers.length > 0\n ) {\n mcpServersToUse = copilotConfig.mcpServers;\n }\n // Then check mcpServers in properties\n else if (\n copilotConfig.properties?.mcpServers &&\n Array.isArray(copilotConfig.properties.mcpServers) &&\n copilotConfig.properties.mcpServers.length > 0\n ) {\n mcpServersToUse = copilotConfig.properties.mcpServers;\n }\n\n // Apply the mcpServers to properties if found\n if (mcpServersToUse) {\n // Set in finalProperties\n finalProperties.mcpServers = mcpServersToUse;\n\n // Also set in copilotConfig directly for future use\n copilotConfig.mcpServers = mcpServersToUse;\n }\n // -------------------------------------------------------------\n\n const isAgentRun = agentSessionRef.current !== null;\n\n const stream = runtimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(actions),\n url: window.location.href,\n },\n threadId: threadId,\n runId: runIdRef.current,\n extensions: extensionsRef.current,\n metaEvents: composeAndFlushMetaEventsInput([langGraphInterruptAction?.event]),\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: agentSessionRef.current,\n }\n : {}),\n agentStates: Object.values(coagentStatesRef.current!).map((state) => {\n const stateObject: AgentStateInput = {\n agentName: state.name,\n state: JSON.stringify(state.state),\n };\n\n if (state.config !== undefined) {\n stateObject.config = JSON.stringify(state.config);\n }\n\n return stateObject;\n }),\n forwardedParameters: options.forwardedParameters || {},\n },\n properties: finalProperties,\n signal: chatAbortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let executedCoAgentStateRenders: string[] = [];\n let followUp: FrontendAction[\"followUp\"] = undefined;\n\n let messages: Message[] = [];\n let syncedMessages: Message[] = [];\n let interruptMessages: Message[] = [];\n\n try {\n while (true) {\n let done, value;\n\n try {\n const readResult = await reader.read();\n done = readResult.done;\n value = readResult.value;\n } catch (readError) {\n break;\n }\n\n if (done) {\n if (chatAbortControllerRef.current.signal.aborted) {\n return [];\n }\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n // in the output, graphql inserts __typename, which leads to an error when sending it along\n // as input to the next request.\n extensionsRef.current = CopilotRuntimeClient.removeGraphQLTypename(\n value.generateCopilotResponse.extensions || {},\n );\n\n // setThreadId(threadIdRef.current);\n setRunId(runIdRef.current);\n setExtensions(extensionsRef.current);\n let rawMessagesResponse = value.generateCopilotResponse.messages;\n\n const metaEvents: MetaEvent[] | undefined =\n value.generateCopilotResponse?.metaEvents ?? [];\n (metaEvents ?? []).forEach((ev) => {\n if (ev.name === MetaEventName.LangGraphInterruptEvent) {\n let eventValue = langGraphInterruptEvent(ev as LangGraphInterruptEvent).value;\n eventValue = parseJson(eventValue, eventValue);\n setLangGraphInterruptAction({\n event: {\n ...langGraphInterruptEvent(ev as LangGraphInterruptEvent),\n value: eventValue,\n },\n });\n }\n if (ev.name === MetaEventName.CopilotKitLangGraphInterruptEvent) {\n const data = (ev as CopilotKitLangGraphInterruptEvent).data;\n\n // @ts-expect-error -- same type of messages\n rawMessagesResponse = [...rawMessagesResponse, ...data.messages];\n interruptMessages = convertGqlOutputToMessages(\n // @ts-ignore\n filterAdjacentAgentStateMessages(data.messages),\n );\n }\n });\n\n messages = convertGqlOutputToMessages(\n filterAdjacentAgentStateMessages(rawMessagesResponse),\n );\n\n newMessages = [];\n\n // Handle error statuses BEFORE checking if there are messages\n // (errors can come in chunks with no messages)\n\n // request failed, display error message and quit\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n const guardrailsReason =\n value.generateCopilotResponse.status.details?.guardrailsReason || \"\";\n\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: guardrailsReason,\n }),\n ];\n\n // Trace guardrails validation failure\n const guardrailsError = new CopilotKitError({\n message: `Guardrails validation failed: ${guardrailsReason}`,\n code: CopilotKitErrorCode.MISUSE,\n });\n await traceUIError(guardrailsError, {\n statusReason: value.generateCopilotResponse.status.reason,\n statusDetails: value.generateCopilotResponse.status.details,\n });\n\n setMessages([...previousMessages, ...newMessages]);\n break;\n }\n\n // Handle UNKNOWN_ERROR failures (like authentication errors) by routing to banner error system\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"UNKNOWN_ERROR\"\n ) {\n const errorMessage =\n value.generateCopilotResponse.status.details?.description ||\n \"An unknown error occurred\";\n\n // Try to extract original error information from the response details\n const statusDetails = value.generateCopilotResponse.status.details;\n const originalError = statusDetails?.originalError || statusDetails?.error;\n\n // Extract structured error information if available (prioritize top-level over extensions)\n const originalCode = originalError?.code || originalError?.extensions?.code;\n const originalSeverity = originalError?.severity || originalError?.extensions?.severity;\n const originalVisibility =\n originalError?.visibility || originalError?.extensions?.visibility;\n\n // Use the original error code if available, otherwise default to NETWORK_ERROR\n let errorCode = CopilotKitErrorCode.NETWORK_ERROR;\n if (originalCode && Object.values(CopilotKitErrorCode).includes(originalCode)) {\n errorCode = originalCode;\n }\n\n // Create a structured CopilotKitError preserving original error information\n const structuredError = new CopilotKitError({\n message: errorMessage,\n code: errorCode,\n severity: originalSeverity,\n visibility: originalVisibility,\n });\n\n // Display the error in the banner\n setBannerError(structuredError);\n\n // Trace the error for debugging/observability\n await traceUIError(structuredError, {\n statusReason: value.generateCopilotResponse.status.reason,\n statusDetails: value.generateCopilotResponse.status.details,\n originalErrorCode: originalCode,\n preservedStructure: !!originalCode,\n });\n\n // Stop processing and break from the loop\n setIsLoading(false);\n break;\n }\n\n // add messages to the chat\n else if (messages.length > 0) {\n newMessages = [...messages];\n\n for (const message of messages) {\n // execute onCoAgentStateRender handler\n if (\n message.isAgentStateMessage() &&\n !message.active &&\n !executedCoAgentStateRenders.includes(message.id) &&\n onCoAgentStateRender\n ) {\n // Do not execute a coagent action if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute coagent action\n await onCoAgentStateRender({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoAgentStateRenders.push(message.id);\n }\n }\n\n const lastAgentStateMessage = [...messages]\n .reverse()\n .find((message) => message.isAgentStateMessage());\n\n if (lastAgentStateMessage) {\n if (\n lastAgentStateMessage.state.messages &&\n lastAgentStateMessage.state.messages.length > 0\n ) {\n syncedMessages = loadMessagesFromJsonRepresentation(\n lastAgentStateMessage.state.messages,\n );\n }\n setCoagentStatesWithRef((prevAgentStates) => ({\n ...prevAgentStates,\n [lastAgentStateMessage.agentName]: {\n name: lastAgentStateMessage.agentName,\n state: lastAgentStateMessage.state,\n running: lastAgentStateMessage.running,\n active: lastAgentStateMessage.active,\n threadId: lastAgentStateMessage.threadId,\n nodeName: lastAgentStateMessage.nodeName,\n runId: lastAgentStateMessage.runId,\n // Preserve existing config from previous state\n config: prevAgentStates[lastAgentStateMessage.agentName]?.config,\n },\n }));\n if (lastAgentStateMessage.running) {\n setAgentSession({\n threadId: lastAgentStateMessage.threadId,\n agentName: lastAgentStateMessage.agentName,\n nodeName: lastAgentStateMessage.nodeName,\n });\n } else {\n if (agentLock) {\n setAgentSession({\n threadId: randomId(),\n agentName: agentLock,\n nodeName: undefined,\n });\n } else {\n setAgentSession(null);\n }\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Update message state\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n let finalMessages = constructFinalMessages(\n [...syncedMessages, ...interruptMessages],\n previousMessages,\n newMessages,\n );\n\n let didExecuteAction = false;\n\n // ----- Helper function to execute an action and manage its lifecycle -----\n const executeActionFromMessage = async (\n currentAction: FrontendAction<any>,\n actionMessage: ActionExecutionMessage,\n ) => {\n const isInterruptAction = interruptMessages.find((m) => m.id === actionMessage.id);\n // Determine follow-up behavior: use action's specific setting if defined, otherwise default based on interrupt status.\n followUp = currentAction?.followUp ?? !isInterruptAction;\n\n // Call _setActivatingMessageId before executing the action for HITL correlation\n if ((currentAction as any)?._setActivatingMessageId) {\n (currentAction as any)._setActivatingMessageId(actionMessage.id);\n }\n\n const resultMessage = await executeAction({\n onFunctionCall: onFunctionCall!,\n message: actionMessage,\n chatAbortControllerRef,\n onError: (error: Error) => {\n addErrorToast([error]);\n // console.error is kept here as it's a genuine error in action execution\n console.error(`Failed to execute action ${actionMessage.name}: ${error}`);\n },\n setMessages,\n getFinalMessages: () => finalMessages,\n isRenderAndWait: (currentAction as any)?._isRenderAndWait || false,\n });\n didExecuteAction = true;\n const messageIndex = finalMessages.findIndex((msg) => msg.id === actionMessage.id);\n finalMessages.splice(messageIndex + 1, 0, resultMessage);\n\n // If the executed action was a renderAndWaitForResponse type, update messages immediately\n // to reflect its completion in the UI, making it interactive promptly.\n if ((currentAction as any)?._isRenderAndWait) {\n const messagesForImmediateUpdate = [...finalMessages];\n flushSync(() => {\n setMessages(messagesForImmediateUpdate);\n });\n }\n\n // Clear _setActivatingMessageId after the action is done\n if ((currentAction as any)?._setActivatingMessageId) {\n (currentAction as any)._setActivatingMessageId(null);\n }\n\n return resultMessage;\n };\n // ----------------------------------------------------------------------\n\n // execute regular action executions that are specific to the frontend (last actions)\n if (onFunctionCall) {\n // Find consecutive action execution messages at the end\n const lastMessages = [];\n\n for (let i = finalMessages.length - 1; i >= 0; i--) {\n const message = finalMessages[i];\n if (\n (message.isActionExecutionMessage() || message.isResultMessage()) &&\n message.status.code !== MessageStatusCode.Pending\n ) {\n lastMessages.unshift(message);\n } else if (!message.isAgentStateMessage()) {\n break;\n }\n }\n\n for (const message of lastMessages) {\n // We update the message state before calling the handler so that the render\n // function can be called with `executing` state\n setMessages(finalMessages);\n\n const action = actions.find(\n (action) => action.name === (message as ActionExecutionMessage).name,\n );\n if (action && action.available === \"remote\") {\n // never execute remote actions\n continue;\n }\n const currentResultMessagePairedFeAction = message.isResultMessage()\n ? getPairedFeAction(actions, message)\n : null;\n\n // execution message which has an action registered with the hook (remote availability):\n // execute that action first, and then the \"paired FE action\"\n if (action && message.isActionExecutionMessage()) {\n // For HITL actions, check if they've already been processed to avoid redundant handler calls.\n const isRenderAndWaitAction = (action as any)?._isRenderAndWait || false;\n const alreadyProcessed =\n isRenderAndWaitAction &&\n finalMessages.some(\n (fm) => fm.isResultMessage() && fm.actionExecutionId === message.id,\n );\n\n if (alreadyProcessed) {\n // Skip re-execution if already processed\n } else {\n // Call the single, externally defined executeActionFromMessage\n const resultMessage = await executeActionFromMessage(\n action,\n message as ActionExecutionMessage,\n );\n const pairedFeAction = getPairedFeAction(actions, resultMessage);\n\n if (pairedFeAction) {\n const newExecutionMessage = new ActionExecutionMessage({\n name: pairedFeAction.name,\n arguments: parseJson(resultMessage.result, resultMessage.result),\n status: message.status,\n createdAt: message.createdAt,\n parentMessageId: message.parentMessageId,\n });\n // Call the single, externally defined executeActionFromMessage\n await executeActionFromMessage(pairedFeAction, newExecutionMessage);\n }\n }\n } else if (message.isResultMessage() && currentResultMessagePairedFeAction) {\n // Actions which are set up in runtime actions array: Grab the result, executed paired FE action with it as args.\n const newExecutionMessage = new ActionExecutionMessage({\n name: currentResultMessagePairedFeAction.name,\n arguments: parseJson(message.result, message.result),\n status: message.status,\n createdAt: message.createdAt,\n });\n finalMessages.push(newExecutionMessage);\n // Call the single, externally defined executeActionFromMessage\n await executeActionFromMessage(\n currentResultMessagePairedFeAction,\n newExecutionMessage,\n );\n }\n }\n\n setMessages(finalMessages);\n }\n\n // Conditionally run chat completion again if followUp is not explicitly false\n // and an action was executed or the last message is a server-side result (for non-agent runs).\n if (\n followUp !== false &&\n (didExecuteAction ||\n // the last message is a server side result\n (!isAgentRun &&\n finalMessages.length &&\n finalMessages[finalMessages.length - 1].isResultMessage())) &&\n // the user did not stop generation\n !chatAbortControllerRef.current?.signal.aborted\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletionRef.current!(finalMessages);\n } else if (chatAbortControllerRef.current?.signal.aborted) {\n // filter out all the action execution messages that do not have a consecutive matching result message\n const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {\n if (message.isActionExecutionMessage()) {\n return finalMessages.find(\n (msg, resultIndex) =>\n msg.isResultMessage() &&\n msg.actionExecutionId === message.id &&\n resultIndex === actionExecutionIndex + 1,\n );\n }\n return true;\n });\n const repairedMessageIds = repairedMessages.map((message) => message.id);\n setMessages(repairedMessages);\n\n // LangGraph needs two pieces of information to continue execution:\n // 1. The threadId\n // 2. The nodeName it came from\n // When stopping the agent, we don't know the nodeName the agent would have ended with\n // Therefore, we set the nodeName to the most reasonable thing we can guess, which\n // is \"__end__\"\n if (agentSessionRef.current?.nodeName) {\n setAgentSession({\n threadId: agentSessionRef.current.threadId,\n agentName: agentSessionRef.current.agentName,\n nodeName: \"__end__\",\n });\n }\n // only return new messages that were not filtered out\n return newMessages.filter((message) => repairedMessageIds.includes(message.id));\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n },\n [\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStatesWithRef,\n coagentStatesRef,\n agentSession,\n setAgentSession,\n ],\n );\n\n runChatCompletionRef.current = runChatCompletion;\n\n const runChatCompletionAndHandleFunctionCall = useAsyncCallback(\n async (messages: Message[]): Promise<void> => {\n await runChatCompletionRef.current!(messages);\n },\n [messages],\n );\n\n useEffect(() => {\n if (!isLoading && pendingAppendsRef.current.length > 0) {\n const pending = pendingAppendsRef.current.splice(0);\n const followUp = pending.some((p) => p.followUp);\n const newMessages = [...messages, ...pending.map((p) => p.message)];\n setMessages(newMessages);\n if (followUp) {\n runChatCompletionAndHandleFunctionCall(newMessages);\n }\n }\n }, [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);\n\n // Go over all events and see that they include data that should be returned to the agent\n const composeAndFlushMetaEventsInput = useCallback(\n (metaEvents: (MetaEvent | undefined | null)[]) => {\n return metaEvents.reduce((acc: MetaEventInput[], event) => {\n if (!event) return acc;\n\n switch (event.name) {\n case MetaEventName.LangGraphInterruptEvent:\n if (event.response) {\n // Flush interrupt event from state\n setLangGraphInterruptAction(null);\n const value = (event as LangGraphInterruptEvent).value;\n return [\n ...acc,\n {\n name: event.name,\n value: typeof value === \"string\" ? value : JSON.stringify(value),\n response:\n typeof event.response === \"string\"\n ? event.response\n : JSON.stringify(event.response),\n },\n ];\n }\n return acc;\n default:\n return acc;\n }\n }, []);\n },\n [setLangGraphInterruptAction],\n );\n\n const append = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions): Promise<void> => {\n const followUp = options?.followUp ?? true;\n if (isLoading) {\n pendingAppendsRef.current.push({ message, followUp });\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n if (followUp) {\n return runChatCompletionAndHandleFunctionCall(newMessages);\n }\n },\n [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall],\n );\n\n const reload = useAsyncCallback(\n async (reloadMessageId: string): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n\n const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);\n if (reloadMessageIndex === -1) {\n console.warn(`Message with id ${reloadMessageId} not found`);\n return;\n }\n\n // @ts-expect-error -- message has role\n const reloadMessageRole = messages[reloadMessageIndex].role;\n if (reloadMessageRole !== MessageRole.Assistant) {\n console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);\n return;\n }\n\n let historyCutoff: Message[] = [];\n if (messages.length > 2) {\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(\n (msg) =>\n // @ts-expect-error -- message has role\n msg.role === MessageRole.User,\n );\n const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(\n (msg) => msg.id === lastUserMessageBeforeRegenerate!.id,\n );\n\n // Include the user message, remove everything after it\n historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);\n }\n\n setMessages(historyCutoff);\n\n return runChatCompletionAndHandleFunctionCall(historyCutoff);\n },\n [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall],\n );\n\n const stop = (): void => {\n chatAbortControllerRef.current?.abort(\"Stop was called\");\n };\n\n return {\n append,\n reload,\n stop,\n runChatCompletion: () => runChatCompletionRef.current!(messages),\n };\n}\n\nfunction constructFinalMessages(\n syncedMessages: Message[],\n previousMessages: Message[],\n newMessages: Message[],\n): Message[] {\n const finalMessages =\n syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];\n\n if (syncedMessages.length > 0) {\n const messagesWithAgentState = [...previousMessages, ...newMessages];\n\n let previousMessageId: string | undefined = undefined;\n\n for (const message of messagesWithAgentState) {\n if (message.isAgentStateMessage()) {\n // insert this message into finalMessages after the position of previousMessageId\n const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);\n if (index !== -1) {\n finalMessages.splice(index + 1, 0, message);\n }\n }\n\n previousMessageId = message.id;\n }\n }\n\n return finalMessages;\n}\n\nasync function executeAction({\n onFunctionCall,\n message,\n chatAbortControllerRef,\n onError,\n setMessages,\n getFinalMessages,\n isRenderAndWait,\n}: {\n onFunctionCall: FunctionCallHandler;\n message: ActionExecutionMessage;\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n onError: (error: Error) => void;\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n getFinalMessages: () => Message[];\n isRenderAndWait: boolean;\n}) {\n let result: any;\n let error: Error | null = null;\n\n const currentMessagesForHandler = getFinalMessages();\n\n // The handler (onFunctionCall) runs its synchronous part here, potentially setting up\n // renderAndWaitRef.current for HITL actions via useCopilotAction's transformed handler.\n const handlerReturnedPromise = onFunctionCall({\n messages: currentMessagesForHandler,\n name: message.name,\n args: message.arguments,\n });\n\n // For HITL actions, call flushSync immediately after their handler has set up the promise\n // and before awaiting the promise. This ensures the UI updates to an interactive state.\n if (isRenderAndWait) {\n const currentMessagesForRender = getFinalMessages();\n flushSync(() => {\n setMessages([...currentMessagesForRender]);\n });\n }\n\n try {\n result = await Promise.race([\n handlerReturnedPromise, // Await the promise returned by the handler\n new Promise((resolve) =>\n chatAbortControllerRef.current?.signal.addEventListener(\"abort\", () =>\n resolve(\"Operation was aborted by the user\"),\n ),\n ),\n // if the user stopped generation, we also abort consecutive actions\n new Promise((resolve) => {\n if (chatAbortControllerRef.current?.signal.aborted) {\n resolve(\"Operation was aborted by the user\");\n }\n }),\n ]);\n } catch (e) {\n onError(e as Error);\n }\n return new ResultMessage({\n id: \"result-\" + message.id,\n result: ResultMessage.encodeResult(\n error\n ? {\n content: result,\n error: JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error))),\n }\n : result,\n ),\n actionExecutionId: message.id,\n actionName: message.name,\n });\n}\n\nfunction getPairedFeAction(\n actions: FrontendAction<any>[],\n message: ActionExecutionMessage | ResultMessage,\n) {\n let actionName = null;\n if (message.isActionExecutionMessage()) {\n actionName = message.name;\n } else if (message.isResultMessage()) {\n actionName = message.actionName;\n }\n return actions.find(\n (action) =>\n (action.name === actionName && action.available === \"frontend\") ||\n action.pairedAction === actionName,\n );\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 = \"disabled\" | \"enabled\" | \"remote\" | \"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 ? (props: ActionRenderPropsNoArgs<T>) => 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(actions: FrontendAction<any>[]) {\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 = 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(actionParametersToJsonSchema(action.parameters || [])),\n available,\n };\n });\n return filteredActions;\n}\n","import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo, useRef } from \"react\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n CopilotErrorHandler,\n CopilotErrorEvent,\n} from \"@copilotkit/shared\";\nimport { shouldShowDevConsole } from \"../utils/dev-console\";\n\nexport interface CopilotRuntimeClientHookOptions extends CopilotRuntimeClientOptions {\n showDevConsole?: boolean;\n onError?: CopilotErrorHandler;\n}\n\nexport const useCopilotRuntimeClient = (options: CopilotRuntimeClientHookOptions) => {\n const { setBannerError } = useToast();\n const { showDevConsole, onError, ...runtimeOptions } = options;\n\n // Deduplication state for structured errors\n const lastStructuredErrorRef = useRef<{ message: string; timestamp: number } | null>(null);\n\n // Helper function to trace UI errors\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\n // Just check if onError and publicApiKey are defined\n if (!onError || !runtimeOptions.publicApiKey) return;\n\n try {\n const errorEvent: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"ui\",\n request: {\n operation: \"runtimeClient\",\n url: runtimeOptions.url,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onError(errorEvent);\n } catch (error) {\n console.error(\"Error in onError handler:\", error);\n }\n };\n\n const runtimeClient = useMemo(() => {\n return new CopilotRuntimeClient({\n ...runtimeOptions,\n handleGQLErrors: (error) => {\n if ((error as any).graphQLErrors?.length) {\n const graphQLErrors = (error as any).graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole ?? false);\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", gqlError.message);\n return;\n }\n\n // All errors (including DEV_ONLY) show as banners for consistency\n // Deduplicate to prevent spam\n const now = Date.now();\n const errorMessage = gqlError.message;\n if (\n lastStructuredErrorRef.current &&\n lastStructuredErrorRef.current.message === errorMessage &&\n now - lastStructuredErrorRef.current.timestamp < 150\n ) {\n return; // Skip duplicate\n }\n lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };\n\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the error\n traceUIError(ckError, gqlError);\n } 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 }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole ?? false);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n }\n }\n },\n 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, showDevConsole, onError]);\n\n return runtimeClient;\n};\n\n// Create appropriate structured error from GraphQL error\nfunction createStructuredError(gqlError: GraphQLError): CopilotKitError | null {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n // Legacy error detection by stack trace\n if (originalError?.stack?.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n\n return null;\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { ErrorToast } from \"../error-boundary/error-utils\";\nimport { PartialBy, CopilotKitError, CopilotKitErrorCode, Severity } from \"@copilotkit/shared\";\nimport { renderCopilotKitUsage } from \"../usage-banner\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(null);\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(/'message':\\s*'([^']+)'/);\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n","export function shouldShowDevConsole(showDevConsole: boolean): boolean {\n return showDevConsole;\n}\n","import React, { useCallback } from \"react\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { ExclamationMarkIcon } from \"../toast/exclamation-mark-icon\";\nimport ReactMarkdown from \"react-markdown\";\n\ninterface OriginalError {\n message?: string;\n stack?: string;\n}\n\nexport function ErrorToast({ errors }: { errors: (Error | GraphQLError)[] }) {\n const errorsToRender = errors.map((error, idx) => {\n const originalError =\n \"extensions\" in error ? (error.extensions?.originalError as undefined | OriginalError) : {};\n const message = originalError?.message ?? error.message;\n const code = \"extensions\" in error ? (error.extensions?.code as string) : null;\n\n return (\n <div\n key={idx}\n style={{\n marginTop: idx === 0 ? 0 : 10,\n marginBottom: 14,\n }}\n >\n <ExclamationMarkIcon style={{ marginBottom: 4 }} />\n\n {code && (\n <div\n style={{\n fontWeight: \"600\",\n marginBottom: 4,\n }}\n >\n Copilot Runtime Error:{\" \"}\n <span style={{ fontFamily: \"monospace\", fontWeight: \"normal\" }}>{code}</span>\n </div>\n )}\n <ReactMarkdown>{message}</ReactMarkdown>\n </div>\n );\n });\n return (\n <div\n style={{\n fontSize: \"13px\",\n maxWidth: \"600px\",\n }}\n >\n {errorsToRender}\n <div style={{ fontSize: \"11px\", opacity: 0.75 }}>\n NOTE: This error only displays during local development.\n </div>\n </div>\n );\n}\n\nexport function useErrorToast() {\n const { addToast } = useToast();\n\n return useCallback(\n (error: (Error | GraphQLError)[]) => {\n const errorId = error\n .map((err) => {\n const message =\n \"extensions\" in err\n ? (err.extensions?.originalError as any)?.message || err.message\n : err.message;\n const stack = err.stack || \"\";\n return btoa(message + stack).slice(0, 32); // Create hash from message + stack\n })\n .join(\"|\");\n\n addToast({\n type: \"error\",\n id: errorId, // Toast libraries typically dedupe by id\n message: <ErrorToast errors={error} />,\n });\n },\n [addToast],\n );\n}\n\nexport function useAsyncCallback<T extends (...args: any[]) => Promise<any>>(\n callback: T,\n deps: Parameters<typeof useCallback>[1],\n) {\n const addErrorToast = useErrorToast();\n return useCallback(async (...args: Parameters<T>) => {\n try {\n return await callback(...args);\n } catch (error) {\n console.error(\"Error in async callback:\", error);\n // @ts-ignore\n addErrorToast([error]);\n throw error;\n }\n }, deps);\n}\n","import React from \"react\";\n\nexport const ExclamationMarkIcon = ({\n className,\n style,\n}: {\n className?: string;\n style?: React.CSSProperties;\n}) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={`lucide lucide-circle-alert ${className ? className : \"\"}`}\n style={style}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"12\" x2=\"12\" y1=\"8\" y2=\"12\" />\n <line x1=\"12\" x2=\"12.01\" y1=\"16\" y2=\"16\" />\n </svg>\n);\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, SetStateAction } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"../../hooks/use-copilot-runtime-client\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetterArgs,\n} from \"../../types/interrupt-action\";\nimport { StatusChecker } from \"../../lib/status-checker\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const showDevConsole = props.showDevConsole ?? false;\n const enabled = shouldShowDevConsole(showDevConsole);\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={props.publicApiKey} showUsageBanner={enabled}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<string[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const statusChecker = useMemo(() => new StatusChecker(), []);\n\n const [usageBannerStatus, setUsageBannerStatus] = useState<any>(null);\n\n // Compute all the functions and properties that we need to pass\n\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => {\n return {\n ...prevPoints,\n [id]: stateRender,\n };\n });\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n props.publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: props.showDevConsole ?? false,\n onError: props.onError,\n });\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n const hasLoadedAgents = useRef(false);\n\n useEffect(() => {\n if (hasLoadedAgents.current) return;\n\n const fetchData = async () => {\n const result = await runtimeClient.availableAgents();\n if (result.data?.availableAgents) {\n setAvailableAgents(result.data.availableAgents.agents);\n }\n hasLoadedAgents.current = true;\n };\n void fetchData();\n }, []);\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const [internalThreadId, setInternalThreadId] = useState<string>(props.threadId || randomUUID());\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\"Cannot call setThreadId() when threadId is provided via props.\");\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n // update the internal threadId if the props.threadId changes\n useEffect(() => {\n if (props.threadId !== undefined) {\n setInternalThreadId(props.threadId);\n }\n }, [props.threadId]);\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = props.showDevConsole ?? false;\n\n const [langGraphInterruptAction, _setLangGraphInterruptAction] =\n useState<LangGraphInterruptAction | null>(null);\n const setLangGraphInterruptAction = useCallback((action: LangGraphInterruptActionSetterArgs) => {\n _setLangGraphInterruptAction((prev) => {\n if (prev == null) return action as LangGraphInterruptAction;\n if (action == null) return null;\n let event = prev.event;\n if (action.event) {\n // @ts-ignore\n event = { ...prev.event, ...action.event };\n }\n return { ...prev, ...action, event };\n });\n }, []);\n const removeLangGraphInterruptAction = useCallback((): void => {\n setLangGraphInterruptAction(null);\n }, []);\n\n const memoizedChildren = useMemo(() => children, [children]);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = typeof newExtensions === \"function\" ? newExtensions(prev) : newExtensions;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved = typeof newAuthStates === \"function\" ? newAuthStates(prev) : newAuthStates;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n runtimeClient,\n forwardedParameters,\n agentLock,\n threadId: internalThreadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n removeLangGraphInterruptAction,\n onError: props.onError,\n }}\n >\n <CopilotMessages>{memoizedChildren}</CopilotMessages>\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ name, args }: { name: string; args: Record<string, any> }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n if (!props.runtimeUrl && !props.publicApiKey) {\n throw new ConfigurationError(\"Missing required prop: 'runtimeUrl' or 'publicApiKey'\");\n }\n\n if (cloudFeatures.length > 0 && !props.publicApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport React from \"react\";\n\nexport interface CopilotMessagesContextParams {\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n}\n\nconst emptyCopilotContext: CopilotMessagesContextParams = {\n messages: [],\n setMessages: () => [],\n};\n\nexport const CopilotMessagesContext =\n React.createContext<CopilotMessagesContextParams>(emptyCopilotContext);\n\nexport function useCopilotMessagesContext(): CopilotMessagesContextParams {\n const context = React.useContext(CopilotMessagesContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`\",\n );\n }\n return context;\n}\n","/**\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=\"/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 { Parameter, randomId } from \"@copilotkit/shared\";\nimport { createElement, Fragment, useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport {\n ActionRenderProps,\n ActionRenderPropsNoArgsWait,\n ActionRenderPropsWait,\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n const renderAndWaitRef = useRef<RenderAndWaitForResponse | null>(null);\n const activatingMessageIdRef = useRef<string | null>(null);\n const { addToast } = useToast();\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // const { currentlyActivatingHitlActionMessageIdRef } = useCopilotContext() as any; // <-- REMOVE THIS FOR NOW\n\n // If the developer provides a renderAndWaitForResponse function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (\n // renderAndWaitForResponse is not available for catch all actions\n isFrontendAction(action) &&\n // check if renderAndWaitForResponse is set\n (action.renderAndWait || action.renderAndWaitForResponse)\n ) {\n (action as any)._isRenderAndWait = true; // Internal flag to identify this action type later\n const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n action.renderAndWaitForResponse = undefined;\n\n // Add a method for use-chat.ts to set the activating message ID.\n // This helps correlate the action instance with the message being processed by use-chat.\n (action as any)._setActivatingMessageId = (id: string | null) => {\n activatingMessageIdRef.current = id;\n };\n\n // add a handler that will be called when the action is executed\n action.handler = useAsyncCallback(async () => {\n const currentActivatingId = activatingMessageIdRef.current;\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = {\n promise,\n resolve: resolve!,\n reject: reject!,\n messageId: currentActivatingId,\n };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n const result = await promise;\n return result;\n }, []) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<T> & { messageId?: string }): React.ReactElement => {\n const currentRenderMessageId = props.messageId;\n // For renderAndWaitForResponse, the 'executing' state might be set by use-chat before\n // this specific action instance's handler (and thus its promise) is ready.\n // This logic adjusts the status to 'inProgress' if the current render\n // isn't for the actively processing HITL action, preventing premature interaction.\n let status = props.status;\n if (props.status === \"executing\") {\n if (!renderAndWaitRef.current || !renderAndWaitRef.current.promise) {\n status = \"inProgress\";\n } else if (\n renderAndWaitRef.current.messageId !== currentRenderMessageId &&\n activatingMessageIdRef.current !== currentRenderMessageId\n ) {\n status = \"inProgress\";\n }\n // If conditions met, status remains 'executing'\n }\n // Create type safe waitProps based on whether T extends empty array or not\n const waitProps = {\n status,\n args: props.args,\n result: props.result,\n // handler and respond should only be provided if this is the truly active instance\n // and its promise infrastructure is ready.\n handler:\n status === \"executing\" &&\n renderAndWaitRef.current &&\n renderAndWaitRef.current.messageId === currentRenderMessageId\n ? renderAndWaitRef.current!.resolve\n : undefined,\n respond:\n status === \"executing\" &&\n renderAndWaitRef.current &&\n renderAndWaitRef.current.messageId === currentRenderMessageId\n ? renderAndWaitRef.current!.resolve\n : undefined,\n } as T extends [] ? ActionRenderPropsNoArgsWait<T> : ActionRenderPropsWait<T>;\n\n // Type guard to check if renderAndWait is for no args case\n const isNoArgsRenderWait = (\n _fn:\n | ((props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement)\n | ((props: ActionRenderPropsWait<T>) => React.ReactElement),\n ): _fn is (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement => {\n return action.parameters?.length === 0;\n };\n\n // Safely call renderAndWait with correct props type\n if (renderAndWait) {\n if (isNoArgsRenderWait(renderAndWait)) {\n return renderAndWait(waitProps as ActionRenderPropsNoArgsWait<T>);\n } else {\n return renderAndWait(waitProps as ActionRenderPropsWait<T>);\n }\n }\n\n // Return empty Fragment instead of null\n return createElement(Fragment);\n }) as any;\n }\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n // catch all actions don't have a handler\n if (isFrontendAction(action)) {\n actions[idRef.current].handler = action.handler as any;\n }\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n // TODO: using as any here because the type definitions are getting to tricky\n // not wasting time on this now - we know the types are compatible\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n }\n }\n }\n\n useEffect(() => {\n const hasDuplicate = Object.values(actions).some(\n (otherAction) => otherAction.name === action.name && otherAction !== actions[idRef.current],\n );\n\n if (hasDuplicate) {\n addToast({\n type: \"warning\",\n message: `Found an already registered action with name ${action.name}.`,\n id: `dup-action-${action.name}`,\n });\n }\n }, [actions]);\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n // see comment about type safety above\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n // UPDATE: We now have access, we should remove the entry if not referenced by any message.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n isFrontendAction(action) ? action.description : undefined,\n action.name,\n isFrontendAction(action) ? action.disabled : undefined,\n isFrontendAction(action) ? action.available : undefined,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(isFrontendAction(action) ? action.parameters : []),\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\nfunction isFrontendAction<T extends Parameter[]>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n): action is FrontendAction<T> {\n return action.name !== \"*\";\n}\n\ninterface RenderAndWaitForResponse {\n promise: Promise<any>;\n resolve: (result: any) => void;\n reject: (error: any) => void;\n messageId: string | null;\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\";\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 {\n setCoAgentStateRender,\n removeCoAgentStateRender,\n coAgentStateRenders,\n chatComponentsCache,\n availableAgents,\n } = useContext(CopilotContext);\n const idRef = useRef<string>(randomId());\n const { setBannerError, addToast } = useToast();\n\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === action.name)) {\n const message = `(useCoAgentStateRender): Agent \"${action.name}\" not found. Make sure the agent exists and is properly configured.`;\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: action.name,\n availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coAgentStateRenders[idRef.current]) {\n coAgentStateRenders[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n // Check for duplicates by comparing against all other actions\n const currentId = idRef.current;\n const hasDuplicate = Object.entries(coAgentStateRenders).some(([id, otherAction]) => {\n // Skip comparing with self\n if (id === currentId) return false;\n\n // Different agent names are never duplicates\n if (otherAction.name !== action.name) return false;\n\n // Same agent names:\n const hasNodeName = !!action.nodeName;\n const hasOtherNodeName = !!otherAction.nodeName;\n\n // If neither has nodeName, they're duplicates\n if (!hasNodeName && !hasOtherNodeName) return true;\n\n // If one has nodeName and other doesn't, they're not duplicates\n if (hasNodeName !== hasOtherNodeName) return false;\n\n // If both have nodeName, they're duplicates only if the names match\n return action.nodeName === otherAction.nodeName;\n });\n\n if (hasDuplicate) {\n const message = action.nodeName\n ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden`\n : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;\n\n addToast({\n type: \"warning\",\n message,\n id: `dup-action-${action.name}`,\n });\n }\n }, [coAgentStateRenders]);\n\n useEffect(() => {\n setCoAgentStateRender(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n return () => {\n removeCoAgentStateRender(idRef.current);\n };\n }, [\n setCoAgentStateRender,\n removeCoAgentStateRender,\n action.name,\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n","import { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useCopilotContext();\n const idRef = useRef<string>();\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 { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\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\nfunction convertToJSON(description: string, value: any): string {\n return `${description}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n {\n description,\n value,\n parentId,\n categories,\n convert,\n available = \"enabled\",\n }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { addContext, removeContext } = useCopilotContext();\n const idRef = useRef<string>();\n convert = convert || convertToJSON;\n\n const information = convert(description, value);\n\n useEffect(() => {\n if (available === \"disabled\") return;\n\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [available, information, parentId, addContext, removeContext, ...(dependencies || [])]);\n\n return idRef.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=\"/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 } from \"react\";\nimport {\n CopilotContextParams,\n CopilotMessagesContextParams,\n useCopilotContext,\n useCopilotMessagesContext,\n} from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { useCopilotChat } from \"./use-copilot-chat\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { parseJson, CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<T> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (hint?: HintFunction) => Promise<void>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n const generalContext = useCopilotContext();\n const { availableAgents } = generalContext;\n const { setBannerError } = useToast();\n const lastLoadedThreadId = useRef<string>();\n const lastLoadedState = useRef<any>();\n\n const { name } = options;\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === name)) {\n const message = `(useCoAgent): Agent \"${name}\" not found. Make sure the agent exists and is properly configured.`;\n console.warn(message);\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: name,\n availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const messagesContext = useCopilotMessagesContext();\n const context = { ...generalContext, ...messagesContext };\n const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } =\n context;\n const { appendMessage, runChatCompletion } = useCopilotChat();\n const headers = {\n ...(copilotApiConfig.headers || {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: context.showDevConsole,\n });\n\n // if we manage state internally, we need to provide a function to set the state\n const setState = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n // coagentStatesRef.current || {}\n let coagentState: CoagentState = getCoagentState({ coagentStates, name, options });\n const updatedState =\n typeof newState === \"function\" ? (newState as Function)(coagentState.state) : newState;\n\n setCoagentStatesWithRef({\n ...coagentStatesRef.current,\n [name]: {\n ...coagentState,\n state: updatedState,\n },\n });\n },\n [coagentStates, name],\n );\n\n useEffect(() => {\n const fetchAgentState = async () => {\n if (!threadId || threadId === lastLoadedThreadId.current) return;\n\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: name,\n });\n\n // Runtime client handles errors automatically via handleGQLErrors\n if (result.error) {\n return; // Don't process data on error\n }\n\n const newState = result.data?.loadAgentState?.state;\n if (newState === lastLoadedState.current) return;\n\n if (result.data?.loadAgentState?.threadExists && newState && newState != \"{}\") {\n lastLoadedState.current = newState;\n lastLoadedThreadId.current = threadId;\n const fetchedState = parseJson(newState, {});\n isExternalStateManagement(options)\n ? options.setState(fetchedState)\n : setState(fetchedState);\n }\n };\n void fetchAgentState();\n }, [threadId]);\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n setState(options.state);\n } else if (coagentStates[name] === undefined) {\n setState(options.initialState === undefined ? {} : options.initialState);\n }\n }, [\n isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined,\n // reset initialstate on reset\n coagentStates[name] === undefined,\n ]);\n\n // Sync config when runtime configuration changes\n useEffect(() => {\n const newConfig = options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : undefined;\n\n if (newConfig === undefined) return;\n\n setCoagentStatesWithRef((prev) => {\n const existing = prev[name] ?? {\n name,\n state: isInternalStateManagementWithInitial(options) ? options.initialState : {},\n config: {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n\n if (JSON.stringify(existing.config) === JSON.stringify(newConfig)) {\n return prev;\n }\n\n return {\n ...prev,\n [name]: {\n ...existing,\n config: newConfig,\n },\n };\n });\n }, [JSON.stringify(options.config), JSON.stringify(options.configurable)]);\n\n const runAgentCallback = useAsyncCallback(\n async (hint?: HintFunction) => {\n await runAgent(name, context, appendMessage, runChatCompletion, hint);\n },\n [name, context, appendMessage, runChatCompletion],\n );\n\n // Return the state and setState function\n return useMemo(() => {\n const coagentState = getCoagentState({ coagentStates, name, options });\n return {\n name,\n nodeName: coagentState.nodeName,\n threadId: coagentState.threadId,\n running: coagentState.running,\n state: coagentState.state,\n setState: isExternalStateManagement(options) ? options.setState : setState,\n start: () => startAgent(name, context),\n stop: () => stopAgent(name, context),\n run: runAgentCallback,\n };\n }, [name, coagentStates, options, setState, runAgentCallback]);\n}\n\nexport function startAgent(name: string, context: CopilotContextParams) {\n const { setAgentSession } = context;\n setAgentSession({\n agentName: name,\n });\n}\n\nexport function stopAgent(name: string, context: CopilotContextParams) {\n const { agentSession, setAgentSession } = context;\n if (agentSession && agentSession.agentName === name) {\n setAgentSession(null);\n context.setCoagentStates((prevAgentStates) => {\n return {\n ...prevAgentStates,\n [name]: {\n ...prevAgentStates[name],\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n },\n };\n });\n } else {\n console.warn(`No agent session found for ${name}`);\n }\n}\n\nexport async function runAgent(\n name: string,\n context: CopilotContextParams & CopilotMessagesContextParams,\n appendMessage: (message: Message) => Promise<void>,\n runChatCompletion: () => Promise<Message[]>,\n hint?: HintFunction,\n) {\n const { agentSession, setAgentSession } = context;\n if (!agentSession || agentSession.agentName !== name) {\n setAgentSession({\n agentName: name,\n });\n }\n\n let previousState: any = null;\n for (let i = context.messages.length - 1; i >= 0; i--) {\n const message = context.messages[i];\n if (message.isAgentStateMessage() && message.agentName === name) {\n previousState = message.state;\n }\n }\n\n let state = context.coagentStatesRef.current?.[name]?.state || {};\n\n if (hint) {\n const hintMessage = hint({ previousState, currentState: state });\n if (hintMessage) {\n await appendMessage(hintMessage);\n } else {\n await runChatCompletion();\n }\n } else {\n await runChatCompletion();\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\nconst isInternalStateManagementWithInitial = <T>(\n options: UseCoagentOptions<T>,\n): options is WithInternalStateManagementAndInitial<T> => {\n return \"initialState\" in options;\n};\n\nconst getCoagentState = <T>({\n coagentStates,\n name,\n options,\n}: {\n coagentStates: Record<string, CoagentState>;\n name: string;\n options: UseCoagentOptions<T>;\n}) => {\n if (coagentStates[name]) {\n return coagentStates[name];\n } else {\n return {\n name,\n state: isInternalStateManagementWithInitial<T>(options) ? options.initialState : {},\n config: options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n }\n};\n","import { Parameter } from \"@copilotkit/shared\";\nimport { Fragment, useCallback, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { FrontendAction, ActionRenderProps } from \"../types/frontend-action\";\nimport { useCopilotAction } from \"./use-copilot-action\";\nimport React from \"react\";\n\n/**\n * Hook to create an authenticated action that requires user sign-in before execution.\n *\n * @remarks\n * This feature is only available when using CopilotKit's hosted cloud service.\n * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.\n *\n * @param action - The frontend action to be wrapped with authentication\n * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed\n */\nexport function useCopilotAuthenticatedAction_c<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();\n const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);\n\n const executeAction = useCallback(\n (props: ActionRenderProps<Parameter[]>) => {\n if (typeof action.render === \"function\") {\n return action.render(props);\n }\n return action.render || React.createElement(Fragment);\n },\n [action],\n );\n\n const wrappedRender = useCallback(\n (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {\n const isAuthenticated = Object.values(authStates_c || {}).some(\n (state) => state.status === \"authenticated\",\n );\n\n if (!isAuthenticated) {\n // Store action details for later execution\n pendingActionRef.current = props;\n\n return authConfig_c?.SignInComponent\n ? React.createElement(authConfig_c.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates_c?.((prev) => ({ ...prev, [action.name]: authState }));\n if (pendingActionRef.current) {\n executeAction(pendingActionRef.current);\n pendingActionRef.current = null;\n }\n },\n })\n : React.createElement(Fragment);\n }\n\n return executeAction(props);\n },\n [action, authStates_c, setAuthStates_c],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\n}\n","import { useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { LangGraphInterruptRender } from \"../types/interrupt-action\";\nimport { useCopilotChat } from \"./use-copilot-chat\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { dataToUUID } from \"@copilotkit/shared\";\n\nexport function useLangGraphInterrupt<TEventValue = any>(\n action: Omit<LangGraphInterruptRender<TEventValue>, \"id\">,\n dependencies?: any[],\n) {\n const { setLangGraphInterruptAction, removeLangGraphInterruptAction, langGraphInterruptAction } =\n useContext(CopilotContext);\n const { runChatCompletion } = useCopilotChat();\n const { addToast } = useToast();\n\n const actionId = dataToUUID(JSON.stringify(action), \"lgAction\");\n // We only consider action to be defined once the ID is there\n const hasAction = useMemo(\n () => Boolean(langGraphInterruptAction?.id),\n [langGraphInterruptAction],\n );\n\n const isCurrentAction = useMemo(\n () => langGraphInterruptAction?.id && langGraphInterruptAction?.id === actionId,\n [langGraphInterruptAction],\n );\n\n // Run chat completion to submit a response event. Only if it's the current action\n useEffect(() => {\n if (hasAction && isCurrentAction && langGraphInterruptAction?.event?.response) {\n runChatCompletion();\n }\n }, [langGraphInterruptAction?.event?.response, runChatCompletion, hasAction, isCurrentAction]);\n\n useEffect(() => {\n if (!action) return;\n // An action was already set, with no conditions and it's not the action we're using right now.\n // Show a warning, as this action will not be executed\n if (hasAction && !isCurrentAction && !action.enabled) {\n addToast({\n type: \"warning\",\n message: \"An action is already registered for the interrupt event\",\n });\n return;\n }\n\n if (hasAction && isCurrentAction) {\n return;\n }\n\n setLangGraphInterruptAction({ ...action, id: actionId });\n }, [\n action,\n hasAction,\n isCurrentAction,\n setLangGraphInterruptAction,\n removeLangGraphInterruptAction,\n ...(dependencies || []),\n ]);\n}\n","import { useCopilotContext } from \"../context\";\nimport React, { useCallback } from \"react\";\nimport { executeConditions } from \"@copilotkit/shared\";\n\ntype InterruptProps = {\n event: any;\n result: any;\n render: (props: {\n event: any;\n result: any;\n resolve: (response: string) => void;\n }) => string | React.ReactElement;\n resolve: (response: string) => void;\n};\n\nconst InterruptRenderer: React.FC<InterruptProps> = ({ event, result, render, resolve }) => {\n return render({ event, result, resolve });\n};\n\nexport function useLangGraphInterruptRender(): string | React.ReactElement | null {\n const { langGraphInterruptAction, setLangGraphInterruptAction, agentSession } =\n useCopilotContext();\n\n const responseRef = React.useRef<string>();\n const resolveInterrupt = useCallback(\n (response: string) => {\n responseRef.current = response;\n // Use setTimeout to defer the state update to next tick\n setTimeout(() => {\n setLangGraphInterruptAction({ event: { response } });\n }, 0);\n },\n [setLangGraphInterruptAction],\n );\n\n if (\n !langGraphInterruptAction ||\n !langGraphInterruptAction.event ||\n !langGraphInterruptAction.render\n )\n return null;\n\n const { render, handler, event, enabled } = langGraphInterruptAction;\n\n const conditionsMet =\n !agentSession || !enabled\n ? true\n : enabled({ eventValue: event.value, agentMetadata: agentSession });\n if (!conditionsMet) {\n return null;\n }\n\n let result = null;\n if (handler) {\n result = handler({\n event,\n resolve: resolveInterrupt,\n });\n }\n\n return React.createElement(InterruptRenderer, {\n event,\n result,\n render,\n resolve: resolveInterrupt,\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 { instructions, available = \"enabled\" }: UseCopilotAdditionalInstructionsOptions,\n dependencies?: any[],\n) {\n const { setAdditionalInstructions } = useCopilotContext();\n\n useEffect(() => {\n if (available === \"disabled\") return;\n\n setAdditionalInstructions((prevInstructions) => [...(prevInstructions || []), instructions]);\n\n return () => {\n setAdditionalInstructions(\n (prevInstructions) =>\n prevInstructions?.filter((instruction) => instruction !== instructions) || [],\n );\n };\n }, [available, instructions, setAdditionalInstructions, ...(dependencies || [])]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC4CA,IAAAA,gBAAyD;;;ACtCzD,mBAAkB;AA6NlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,CAAC;AAAA,EACtB,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,0BAA0B,MAAM;AAAA,EAAC;AAAA,EAEjC,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,EAAE;AAAA,EACzE,kBAAkB,CAAC,WAA8B,eAC/C,s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GACtC,cACA;AACA,QAAM,EAAE,0BAA0B,IAAI,kBAAkB;AAExD,gCAAU,MAAM;AACd,QAAI,cAAc;AAAY;AAE9B,8BAA0B,CAAC,qBAAqB,CAAC,GAAI,oBAAoB,CAAC,GAAI,YAAY,CAAC;AAE3F,WAAO,MAAM;AACX;AAAA,QACE,CAAC,sBACC,qDAAkB,OAAO,CAAC,gBAAgB,gBAAgB,kBAAiB,CAAC;AAAA,MAChF;AAAA,IACF;AAAA,EACF,GAAG,CAAC,WAAW,cAAc,2BAA2B,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAClF;","names":["import_react","React","import_runtime_client_gql","import_react","import_shared","import_runtime_client_gql","import_runtime_client_gql","import_react","import_shared","import_react","import_shared","error","_a","import_react","import_jsx_runtime","import_jsx_runtime","ReactMarkdown","messages","_a","action","options","import_react","import_react_dom","import_shared","import_react","emptyCopilotContext","React","import_jsx_runtime","_a","action","options","messages","import_shared","import_react","import_react","import_shared","import_react","import_react","import_react","import_shared","import_react","import_react","executeAction","React","import_react","import_shared","_a","import_react","React","import_react"]}