@copilotkit/react-core 1.10.5-next.4 → 1.10.5-next.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/{chunk-XFJNMZ6X.mjs → chunk-AGBNJCIM.mjs} +2 -2
  3. package/dist/{chunk-OLXYK6PP.mjs → chunk-BKI4I4S2.mjs} +2 -2
  4. package/dist/{chunk-RLT4KZR4.mjs → chunk-FCRPPUZA.mjs} +2 -2
  5. package/dist/{chunk-WBBJMOZI.mjs → chunk-IF4OYMFZ.mjs} +6 -4
  6. package/dist/chunk-IF4OYMFZ.mjs.map +1 -0
  7. package/dist/{chunk-WRPXFDFL.mjs → chunk-TM5MFTHG.mjs} +2 -2
  8. package/dist/{chunk-O73FZGSU.mjs → chunk-Y5ZF7AZ3.mjs} +2 -2
  9. package/dist/hooks/index.js +5 -3
  10. package/dist/hooks/index.js.map +1 -1
  11. package/dist/hooks/index.mjs +6 -6
  12. package/dist/hooks/use-chat.js +5 -3
  13. package/dist/hooks/use-chat.js.map +1 -1
  14. package/dist/hooks/use-chat.mjs +1 -1
  15. package/dist/hooks/use-coagent.js +5 -3
  16. package/dist/hooks/use-coagent.js.map +1 -1
  17. package/dist/hooks/use-coagent.mjs +3 -3
  18. package/dist/hooks/use-copilot-chat-headless_c.js +5 -3
  19. package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
  20. package/dist/hooks/use-copilot-chat-headless_c.mjs +3 -3
  21. package/dist/hooks/use-copilot-chat.js +5 -3
  22. package/dist/hooks/use-copilot-chat.js.map +1 -1
  23. package/dist/hooks/use-copilot-chat.mjs +3 -3
  24. package/dist/hooks/use-copilot-chat_internal.js +5 -3
  25. package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
  26. package/dist/hooks/use-copilot-chat_internal.mjs +2 -2
  27. package/dist/hooks/use-langgraph-interrupt.js +5 -3
  28. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  29. package/dist/hooks/use-langgraph-interrupt.mjs +3 -3
  30. package/dist/index.js +5 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/index.mjs +6 -6
  33. package/package.json +3 -3
  34. package/src/hooks/use-chat.ts +5 -3
  35. package/dist/chunk-WBBJMOZI.mjs.map +0 -1
  36. /package/dist/{chunk-XFJNMZ6X.mjs.map → chunk-AGBNJCIM.mjs.map} +0 -0
  37. /package/dist/{chunk-OLXYK6PP.mjs.map → chunk-BKI4I4S2.mjs.map} +0 -0
  38. /package/dist/{chunk-RLT4KZR4.mjs.map → chunk-FCRPPUZA.mjs.map} +0 -0
  39. /package/dist/{chunk-WRPXFDFL.mjs.map → chunk-TM5MFTHG.mjs.map} +0 -0
  40. /package/dist/{chunk-O73FZGSU.mjs.map → chunk-Y5ZF7AZ3.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-coagent.ts","../../src/context/copilot-context.tsx","../../src/context/copilot-messages-context.tsx","../../src/hooks/use-copilot-chat_internal.ts","../../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/components/copilot-provider/copilot-messages.tsx","../../src/utils/extract.ts","../../src/utils/suggestions.ts","../../src/hooks/use-langgraph-interrupt-render.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { CopilotContextParams, useCopilotContext } from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { useCopilotChat } from \"./use-copilot-chat_internal\";\nimport { Message } from \"@copilotkit/shared\";\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\";\nimport { useMessagesTap } from \"../components/copilot-provider/copilot-messages\";\nimport { Message as GqlMessage } from \"@copilotkit/runtime-client-gql\";\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 context = useCopilotContext();\n const { availableAgents, onError } = context;\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 { getMessagesFromTap } = useMessagesTap();\n\n const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } =\n context;\n const { sendMessage, 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 onError,\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, getMessagesFromTap(), sendMessage, runChatCompletion, hint);\n },\n [name, context, sendMessage, 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,\n messages: GqlMessage[],\n sendMessage: (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 = messages.length - 1; i >= 0; i--) {\n const message = 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 sendMessage(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 {\n CopilotCloudConfig,\n FunctionCallHandler,\n CopilotErrorHandler,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\nimport { SuggestionItem } from \"../utils/suggestions\";\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 // banner error state\n bannerError: CopilotKitError | null;\n setBannerError: React.Dispatch<React.SetStateAction<CopilotKitError | null>>;\n // Internal error handlers\n // These are used to handle errors that occur during the execution of the chat.\n // They are not intended for use by the developer. A component can register itself an error listener to be activated somewhere else as needed\n internalErrorHandlers: Record<string, CopilotErrorHandler>;\n setInternalErrorHandler: (handler: Record<string, CopilotErrorHandler>) => void;\n removeInternalErrorHandler: (id: string) => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n 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: () => {},\n bannerError: null,\n setBannerError: () => {},\n internalErrorHandlers: {},\n setInternalErrorHandler: () => {},\n removeInternalErrorHandler: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport React from \"react\";\nimport { SuggestionItem } from \"../utils/suggestions\";\n\nexport interface CopilotMessagesContextParams {\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>; // suggestions state\n suggestions: SuggestionItem[];\n setSuggestions: React.Dispatch<React.SetStateAction<SuggestionItem[]>>;\n}\n\nconst emptyCopilotContext: CopilotMessagesContextParams = {\n messages: [],\n setMessages: () => [],\n // suggestions state\n suggestions: [],\n setSuggestions: () => [],\n};\n\nexport const CopilotMessagesContext =\n React.createContext<CopilotMessagesContextParams>(emptyCopilotContext);\n\nexport function useCopilotMessagesContext(): CopilotMessagesContextParams {\n const context = React.useContext(CopilotMessagesContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`\",\n );\n }\n return context;\n}\n","import { useRef, useEffect, useCallback, useState, useMemo } from \"react\";\nimport { AgentSession, useCopilotContext, CopilotContextParams } from \"../context/copilot-context\";\nimport { useCopilotMessagesContext, CopilotMessagesContextParams } from \"../context\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat, AppendMessageOptions } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CoAgentStateRenderHandlerArguments } from \"@copilotkit/shared\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { reloadSuggestions as generateSuggestions } from \"../utils\";\nimport type { SuggestionItem } from \"../utils\";\n\nimport { Message } from \"@copilotkit/shared\";\nimport {\n Role as gqlRole,\n TextMessage,\n aguiToGQL,\n gqlToAGUI,\n Message as DeprecatedGqlMessage,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useLangGraphInterruptRender } from \"./use-langgraph-interrupt-render\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Initial messages to populate the chat with.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n\n /**\n * Disables inclusion of CopilotKit’s default system message. When true, no system message is sent (this also suppresses any custom message from <code>makeSystemMessage</code>).\n */\n disableSystemMessage?: boolean;\n}\n\nexport interface MCPServerConfig {\n endpoint: string;\n apiKey?: string;\n}\n\nexport interface UseCopilotChatReturn {\n /**\n * @deprecated use `messages` instead, this is an old non ag-ui version of the messages\n * Array of messages currently visible in the chat interface\n *\n * This is the visible messages, not the raw messages from the runtime client.\n */\n visibleMessages: DeprecatedGqlMessage[];\n\n /**\n * The messages that are currently in the chat in AG-UI format.\n */\n messages: Message[];\n\n /** @deprecated use `sendMessage` instead */\n appendMessage: (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => Promise<void>;\n\n /**\n * Send a new message to the chat\n *\n * ```tsx\n * await sendMessage({\n * id: \"123\",\n * role: \"user\",\n * content: \"Hello, process this request\",\n * });\n * ```\n */\n sendMessage: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n\n /**\n * Replace all messages in the chat\n *\n * ```tsx\n * setMessages([\n * { id: \"123\", role: \"user\", content: \"Hello, process this request\" },\n * { id: \"456\", role: \"assistant\", content: \"Hello, I'm the assistant\" },\n * ]);\n * ```\n *\n * **Deprecated** non-ag-ui version:\n *\n * ```tsx\n * setMessages([\n * new TextMessage({\n * content: \"Hello, process this request\",\n * role: gqlRole.User,\n * }),\n * new TextMessage({\n * content: \"Hello, I'm the assistant\",\n * role: gqlRole.Assistant,\n * ]);\n * ```\n *\n */\n setMessages: (messages: Message[] | DeprecatedGqlMessage[]) => void;\n\n /**\n * Remove a specific message by ID\n *\n * ```tsx\n * deleteMessage(\"123\");\n * ```\n */\n deleteMessage: (messageId: string) => void;\n\n /**\n * Regenerate the response for a specific message\n *\n * ```tsx\n * reloadMessages(\"123\");\n * ```\n */\n reloadMessages: (messageId: string) => Promise<void>;\n\n /**\n * Stop the current message generation\n *\n * ```tsx\n * if (isLoading) {\n * stopGeneration();\n * }\n * ```\n */\n stopGeneration: () => void;\n\n /**\n * Clear all messages and reset chat state\n *\n * ```tsx\n * reset();\n * console.log(messages); // []\n * ```\n */\n reset: () => void;\n\n /**\n * Whether the chat is currently generating a response\n *\n * ```tsx\n * if (isLoading) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isLoading: boolean;\n\n /** Manually trigger chat completion (advanced usage) */\n runChatCompletion: () => Promise<Message[]>;\n\n /** MCP (Model Context Protocol) server configurations */\n mcpServers: MCPServerConfig[];\n\n /** Update MCP server configurations */\n setMcpServers: (mcpServers: MCPServerConfig[]) => void;\n\n /**\n * Current suggestions array\n * Use this to read the current suggestions or in conjunction with setSuggestions for manual control\n */\n suggestions: SuggestionItem[];\n\n /**\n * Manually set suggestions\n * Useful for manual mode or custom suggestion workflows\n */\n setSuggestions: (suggestions: SuggestionItem[]) => void;\n\n /**\n * Trigger AI-powered suggestion generation\n * Uses configurations from useCopilotChatSuggestions hooks\n * Respects global debouncing - only one generation can run at a time\n *\n * ```tsx\n * generateSuggestions();\n * console.log(suggestions); // [suggestion1, suggestion2, suggestion3]\n * ```\n */\n generateSuggestions: () => Promise<void>;\n\n /**\n * Clear all current suggestions\n * Also resets suggestion generation state\n */\n resetSuggestions: () => void;\n\n /** Whether suggestions are currently being generated */\n isLoadingSuggestions: boolean;\n\n /** Interrupt content for human-in-the-loop workflows */\n interrupt: string | React.ReactElement | null;\n}\n\nlet globalSuggestionPromise: Promise<void> | null = null;\n\nexport function useCopilotChat(options: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const makeSystemMessage = options.makeSystemMessage ?? defaultSystemMessage;\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 chatSuggestionConfiguration,\n\n runtimeClient,\n } = useCopilotContext();\n const { messages, setMessages, suggestions, setSuggestions } = useCopilotMessagesContext();\n\n // Simple state for MCP servers (keep for interface compatibility)\n const [mcpServers, setLocalMcpServers] = useState<MCPServerConfig[]>([]);\n\n // Basic suggestion state for programmatic control\n const suggestionsAbortControllerRef = useRef<AbortController | null>(null);\n const isLoadingSuggestionsRef = useRef<boolean>(false);\n\n const abortSuggestions = useCallback(\n (clear: boolean = true) => {\n suggestionsAbortControllerRef.current?.abort(\"suggestions aborted by user\");\n suggestionsAbortControllerRef.current = null;\n if (clear) {\n setSuggestions([]);\n }\n },\n [setSuggestions],\n );\n\n // Memoize context with stable dependencies only\n const stableContext = useMemo(() => {\n return {\n actions,\n copilotApiConfig,\n chatSuggestionConfiguration,\n messages,\n setMessages,\n getContextString,\n runtimeClient,\n };\n }, [\n JSON.stringify(Object.keys(actions)),\n copilotApiConfig.chatApiEndpoint,\n messages.length,\n Object.keys(chatSuggestionConfiguration).length,\n ]);\n\n // Programmatic suggestion generation function\n const generateSuggestionsFunc = useCallback(async () => {\n // If a global suggestion is running, ignore this call\n if (globalSuggestionPromise) {\n return globalSuggestionPromise;\n }\n\n globalSuggestionPromise = (async () => {\n try {\n abortSuggestions();\n isLoadingSuggestionsRef.current = true;\n suggestionsAbortControllerRef.current = new AbortController();\n\n setSuggestions([]);\n\n await generateSuggestions(\n stableContext as CopilotContextParams & CopilotMessagesContextParams,\n chatSuggestionConfiguration,\n setSuggestions,\n suggestionsAbortControllerRef,\n );\n } catch (error) {\n // Re-throw to allow caller to handle the error\n throw error;\n } finally {\n isLoadingSuggestionsRef.current = false;\n globalSuggestionPromise = null;\n }\n })();\n\n return globalSuggestionPromise;\n }, [stableContext, chatSuggestionConfiguration, setSuggestions, abortSuggestions]);\n\n const resetSuggestions = useCallback(() => {\n setSuggestions([]);\n }, [setSuggestions]);\n\n // MCP servers logic\n useEffect(() => {\n if (mcpServers.length > 0) {\n const serversCopy = [...mcpServers];\n copilotApiConfig.mcpServers = serversCopy;\n if (!copilotApiConfig.properties) {\n copilotApiConfig.properties = {};\n }\n copilotApiConfig.properties.mcpServers = serversCopy;\n }\n }, [mcpServers, copilotApiConfig]);\n\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: gqlRole.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: aguiToGQL(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 disableSystemMessage: options.disableSystemMessage,\n });\n\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useAsyncCallback(\n async (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => {\n abortSuggestions(options?.clearSuggestions);\n return await latestAppend.current(message, options);\n },\n [latestAppend],\n );\n\n const latestSendMessageFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n abortSuggestions(options?.clearSuggestions);\n return await latestAppend.current(aguiToGQL([message])[0] as DeprecatedGqlMessage, 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[] | DeprecatedGqlMessage[]) => {\n if (messages.every((message) => message instanceof DeprecatedGqlMessage)) {\n return latestSetMessages.current(messages as DeprecatedGqlMessage[]);\n }\n return latestSetMessages.current(aguiToGQL(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 // Reset suggestions when chat is reset\n resetSuggestions();\n }, [\n latestStopFunc,\n setMessages,\n setThreadId,\n setCoagentStatesWithRef,\n setAgentSession,\n agentLock,\n resetSuggestions,\n ]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n const interrupt = useLangGraphInterruptRender();\n\n return {\n visibleMessages: messages,\n messages: gqlToAGUI(messages, actions, coAgentStateRenders),\n sendMessage: latestSendMessageFunc,\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 suggestions,\n setSuggestions,\n generateSuggestions: generateSuggestionsFunc,\n resetSuggestions,\n isLoadingSuggestions: isLoadingSuggestionsRef.current,\n interrupt,\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 React, { useCallback, useEffect, useMemo, 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 disableSystemMessage?: boolean;\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 * Whether to clear the suggestions after appending the message. Defaults to `true`.\n */\n clearSuggestions?: 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 disableSystemMessage = false,\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, showDevConsole, getAllContext } = useCopilotContext();\n\n const copilotReadableContext = getAllContext();\n\n const context = useMemo(\n () =>\n copilotReadableContext.map((contextItem) => {\n const [description, ...valueParts] = contextItem.value.split(\":\");\n return {\n description: description.trim(),\n value: valueParts.join(\":\").trim(),\n };\n }),\n [copilotReadableContext],\n );\n\n // Add tracing functionality to use-chat\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\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 runtimeClient = useCopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n showDevConsole,\n onError,\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 messagesWithContext = disableSystemMessage\n ? [...(initialMessages || []), ...previousMessages]\n : [makeSystemMessageCallback(), ...(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 context,\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 // TODO: if onError & renderError should work without key, insert here\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 // TODO: if onError & renderError should work without key, insert here\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 === \"frontend\") {\n // never execute frontend 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 disableSystemMessage,\n context,\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 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 // TODO: if onError & renderError should work without key, insert here\n } else {\n // Fallback for unstructured errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n // TODO: if onError & renderError should work without key, insert here\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n 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 // TODO: if onError & renderError should work without key, insert here\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 { PartialBy, CopilotKitError, Severity } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(null);\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(/'message':\\s*'([^']+)'/);\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n","function isLocalhost(): boolean {\n if (typeof window === \"undefined\") return false;\n\n return (\n window.location.hostname === \"localhost\" ||\n window.location.hostname === \"127.0.0.1\" ||\n window.location.hostname === \"0.0.0.0\"\n );\n}\n\nexport function shouldShowDevConsole(showDevConsole?: boolean): boolean {\n // If explicitly set, use that value\n if (showDevConsole !== undefined) {\n return showDevConsole;\n }\n\n // If not set, default to true on localhost\n return isLocalhost();\n}\n","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 CopilotKitError,\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages, MessagesTapProvider } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { 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 { ConsoleTrigger } from \"../dev-console/console-trigger\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n\n // Use API key if provided, otherwise use the license key\n const publicApiKey = props.publicApiKey || props.publicLicenseKey;\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={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 // Use license key as API key if provided, otherwise use the API key\n const publicApiKey = props.publicLicenseKey || props.publicApiKey;\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n 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 // Compute all the functions and properties that we need to pass\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const 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 (publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const [internalErrorHandlers, _setInternalErrorHandler] = useState<\n Record<string, CopilotErrorHandler>\n >({});\n const setInternalErrorHandler = useCallback((handler: Record<string, CopilotErrorHandler>) => {\n _setInternalErrorHandler((prev: Record<string, CopilotErrorHandler>) => ({\n ...prev,\n ...handler,\n }));\n }, []);\n const removeInternalErrorHandler = useCallback((key: string) => {\n _setInternalErrorHandler((prev) => {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n });\n }, []);\n\n // Keep latest values in refs\n const onErrorRef = useRef<CopilotErrorHandler | undefined>(props.onError);\n useEffect(() => {\n onErrorRef.current = props.onError;\n }, [props.onError]);\n\n const internalHandlersRef = useRef<Record<string, CopilotErrorHandler>>({});\n useEffect(() => {\n internalHandlersRef.current = internalErrorHandlers;\n }, [internalErrorHandlers]);\n\n const handleErrors = useCallback(\n async (error: CopilotErrorEvent) => {\n if (copilotApiConfig.publicApiKey && onErrorRef.current) {\n try {\n await onErrorRef.current(error);\n } catch (e) {\n console.error(\"Error in public onError handler:\", e);\n }\n }\n const handlers = Object.values(internalHandlersRef.current);\n await Promise.all(\n handlers.map((h) =>\n Promise.resolve(h(error)).catch((e) =>\n console.error(\"Error in internal error handler:\", e),\n ),\n ),\n );\n },\n [copilotApiConfig.publicApiKey],\n );\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: shouldShowDevConsole(props.showDevConsole),\n onError: handleErrors,\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 = shouldShowDevConsole(props.showDevConsole);\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 const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = 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 bannerError,\n setBannerError,\n onError: handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n }}\n >\n <MessagesTapProvider>\n <CopilotMessages>\n {memoizedChildren}\n {showDevConsole && <ConsoleTrigger />}\n </CopilotMessages>\n </MessagesTapProvider>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </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 // Check if we have either a runtimeUrl or one of the API keys\n const hasApiKey = props.publicApiKey || props.publicLicenseKey;\n\n if (!props.runtimeUrl && !hasApiKey) {\n throw new ConfigurationError(\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\",\n );\n }\n\n if (cloudFeatures.length > 0 && !hasApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport {\n ReactNode,\n useEffect,\n useState,\n useRef,\n useCallback,\n useMemo,\n createContext,\n useContext,\n} from \"react\";\nimport { CopilotMessagesContext } from \"../../context/copilot-messages-context\";\nimport {\n loadMessagesFromJsonRepresentation,\n Message,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useCopilotContext } from \"../../context/copilot-context\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { shouldShowDevConsole } from \"../../utils/dev-console\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n} from \"@copilotkit/shared\";\nimport { SuggestionItem } from \"../../utils/suggestions\";\n\n// Helper to determine if error should show as banner based on visibility and legacy patterns\nfunction shouldShowAsBanner(gqlError: GraphQLError): boolean {\n const extensions = gqlError.extensions;\n if (!extensions) return false;\n\n // Priority 1: Check error code for discovery errors (these should always be banners)\n const code = extensions.code as CopilotKitErrorCode;\n if (\n code === CopilotKitErrorCode.AGENT_NOT_FOUND ||\n code === CopilotKitErrorCode.API_NOT_FOUND ||\n code === CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND ||\n code === CopilotKitErrorCode.CONFIGURATION_ERROR ||\n code === CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR ||\n code === CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR\n ) {\n return true;\n }\n\n // Priority 2: Check banner visibility\n if (extensions.visibility === ErrorVisibility.BANNER) {\n return true;\n }\n\n // Priority 3: Check for critical errors that should be banners regardless of formal classification\n const errorMessage = gqlError.message.toLowerCase();\n if (\n errorMessage.includes(\"api key\") ||\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"unauthorized\") ||\n errorMessage.includes(\"authentication\") ||\n errorMessage.includes(\"incorrect api key\")\n ) {\n return true;\n }\n\n // Priority 4: Legacy stack trace detection for discovery errors\n const originalError = extensions.originalError as any;\n if (originalError?.stack) {\n return (\n originalError.stack.includes(\"CopilotApiDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")\n );\n }\n\n return false;\n}\n\n/**\n * MessagesTap is used to mitigate performance issues when we only need\n * a snapshot of the messages, not a continuously updating stream of messages.\n */\n\nexport type MessagesTap = {\n getMessagesFromTap: () => Message[];\n updateTapMessages: (messages: Message[]) => void;\n};\n\nconst MessagesTapContext = createContext<MessagesTap | null>(null);\n\nexport function useMessagesTap() {\n const tap = useContext(MessagesTapContext);\n if (!tap) throw new Error(\"useMessagesTap must be used inside <MessagesTapProvider>\");\n return tap;\n}\n\nexport function MessagesTapProvider({ children }: { children: React.ReactNode }) {\n const messagesRef = useRef<Message[]>([]);\n\n const tapRef = useRef<MessagesTap>({\n getMessagesFromTap: () => messagesRef.current,\n updateTapMessages: (messages: Message[]) => {\n messagesRef.current = messages;\n },\n });\n\n return (\n <MessagesTapContext.Provider value={tapRef.current}>{children}</MessagesTapContext.Provider>\n );\n}\n\n/**\n * CopilotKit messages context.\n */\n\nexport function CopilotMessages({ children }: { children: ReactNode }) {\n const [messages, setMessages] = useState<Message[]>([]);\n const lastLoadedThreadId = useRef<string>();\n const lastLoadedAgentName = useRef<string>();\n const lastLoadedMessages = useRef<string>();\n\n const { updateTapMessages } = useMessagesTap();\n\n const { threadId, agentSession, runtimeClient, showDevConsole, onError, copilotApiConfig } =\n useCopilotContext();\n const { setBannerError } = useToast();\n\n // Helper function to trace UI errors (similar to useCopilotRuntimeClient)\n const traceUIError = useCallback(\n async (error: CopilotKitError, originalError?: any) => {\n // Just check if onError and publicApiKey are defined\n if (!onError || !copilotApiConfig.publicApiKey) return;\n\n try {\n const traceEvent = {\n type: \"error\" as const,\n timestamp: Date.now(),\n context: {\n source: \"ui\" as const,\n request: {\n operation: \"loadAgentState\",\n url: copilotApiConfig.chatApiEndpoint,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onError(traceEvent);\n } catch (traceError) {\n console.error(\"Error in CopilotMessages onError handler:\", traceError);\n }\n },\n [onError, copilotApiConfig.publicApiKey, copilotApiConfig.chatApiEndpoint],\n );\n\n const createStructuredError = (gqlError: GraphQLError): CopilotKitError | null => {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n\n // Priority: Check stack trace for discovery errors first\n if (originalError?.stack) {\n if (originalError.stack.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message: originalError.message });\n }\n if (originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message: originalError.message });\n }\n if (originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n }\n\n // Fallback: Use the formal error code if available\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n return null;\n };\n\n const handleGraphQLErrors = useCallback(\n (error: any) => {\n if (error.graphQLErrors?.length) {\n const graphQLErrors = error.graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole);\n\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", gqlError.message);\n return;\n }\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // All other errors (including DEV_ONLY) show as banners for consistency\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the structured error\n traceUIError(ckError, gqlError);\n } else {\n // Fallback: create a generic error for unstructured GraphQL errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n }\n }\n },\n [setBannerError, showDevConsole, traceUIError],\n );\n\n useEffect(() => {\n if (!threadId || threadId === lastLoadedThreadId.current) return;\n if (\n threadId === lastLoadedThreadId.current &&\n agentSession?.agentName === lastLoadedAgentName.current\n ) {\n return;\n }\n\n const fetchMessages = async () => {\n if (!agentSession?.agentName) return;\n\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: agentSession?.agentName,\n });\n\n // Check for GraphQL errors and manually trigger error handling\n if (result.error) {\n // Update refs to prevent infinite retries of the same failed request\n lastLoadedThreadId.current = threadId;\n lastLoadedAgentName.current = agentSession?.agentName;\n handleGraphQLErrors(result.error);\n return; // Don't try to process the data if there's an error\n }\n\n const newMessages = result.data?.loadAgentState?.messages;\n if (newMessages === lastLoadedMessages.current) return;\n\n if (result.data?.loadAgentState) {\n lastLoadedMessages.current = newMessages;\n lastLoadedThreadId.current = threadId;\n lastLoadedAgentName.current = agentSession?.agentName;\n\n const messages = loadMessagesFromJsonRepresentation(JSON.parse(newMessages || \"[]\"));\n setMessages(messages);\n }\n };\n void fetchMessages();\n }, [threadId, agentSession?.agentName]);\n\n useEffect(() => {\n updateTapMessages(messages);\n }, [messages, updateTapMessages]);\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [suggestions, setSuggestions] = useState<SuggestionItem[]>([]);\n\n return (\n <CopilotMessagesContext.Provider\n value={{\n messages,\n setMessages,\n suggestions,\n setSuggestions,\n }}\n >\n {memoizedChildren}\n </CopilotMessagesContext.Provider>\n );\n}\n","import {\n Action,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n MappedParameterTypes,\n Parameter,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n ActionExecutionMessage,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\nimport {\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n} from \"@copilotkit/runtime-client-gql\";\n\ninterface InitialState<T extends Parameter[] | [] = []> {\n status: \"initial\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n}\n\ntype StreamHandlerArgs<T extends Parameter[] | [] = []> =\n | InitialState<T>\n | InProgressState<T>\n | CompleteState<T>;\n\ninterface ExtractOptions<T extends Parameter[]> {\n context: CopilotContextParams & CopilotMessagesContextParams;\n instructions: string;\n parameters: T;\n include?: IncludeOptions;\n data?: any;\n abortSignal?: AbortSignal;\n stream?: (args: StreamHandlerArgs<T>) => void;\n requestType?: CopilotRequestType;\n forwardedParameters?: ForwardedParametersInput;\n}\n\ninterface IncludeOptions {\n readable?: boolean;\n messages?: boolean;\n}\n\nexport async function extract<const T extends Parameter[]>({\n context,\n instructions,\n parameters,\n include,\n data,\n abortSignal,\n stream,\n requestType = CopilotRequestType.Task,\n forwardedParameters,\n}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {\n const { messages } = context;\n\n const action: Action<any> = {\n name: \"extract\",\n description: instructions,\n parameters,\n handler: (args: any) => {},\n };\n\n const includeReadable = include?.readable ?? false;\n const includeMessages = include?.messages ?? false;\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (includeReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = new TextMessage({\n content: makeSystemMessage(contextString, instructions),\n role: Role.System,\n });\n\n const instructionsMessage: Message = new TextMessage({\n content: makeInstructionsMessage(instructions),\n role: Role.User,\n });\n\n const response = context.runtimeClient.asStream(\n context.runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [\n {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n },\n ],\n url: window.location.href,\n },\n\n messages: convertMessagesToGqlInput(\n includeMessages\n ? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)]\n : [systemMessage, instructionsMessage],\n ),\n metadata: {\n requestType: requestType,\n },\n forwardedParameters: {\n ...(forwardedParameters ?? {}),\n toolChoice: \"function\",\n toolChoiceFunctionName: action.name,\n },\n },\n properties: context.copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n\n const reader = response.getReader();\n\n let isInitial = true;\n\n let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (abortSignal?.aborted) {\n throw new Error(\"Aborted\");\n }\n\n actionExecutionMessage = convertGqlOutputToMessages(\n value.generateCopilotResponse.messages,\n ).find((msg) => msg.isActionExecutionMessage()) as ActionExecutionMessage | undefined;\n\n if (!actionExecutionMessage) {\n continue;\n }\n\n stream?.({\n status: isInitial ? \"initial\" : \"inProgress\",\n args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,\n });\n\n isInitial = false;\n }\n\n if (!actionExecutionMessage) {\n throw new Error(\"extract() failed: No function call occurred\");\n }\n\n stream?.({\n status: \"complete\",\n args: actionExecutionMessage.arguments as MappedParameterTypes<T>,\n });\n\n return actionExecutionMessage.arguments as MappedParameterTypes<T>;\n}\n\n// We need to put this in a user message since some LLMs need\n// at least one user message to function\nfunction makeInstructionsMessage(instructions: string): string {\n return `\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n\nAny additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.\n`;\n}\n\nfunction makeSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with a function called extract you MUST call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call the function without saying anything else.\n`;\n}\n","/**\n * Suggestions utility functions for CopilotKit\n *\n * This module handles the generation of chat suggestions with optimized error handling\n * and streaming validation to prevent infinite retry loops and console spam.\n */\n\nimport { extract } from \"./extract\";\nimport { actionParametersToJsonSchema } from \"@copilotkit/shared\";\nimport { CopilotRequestType } from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { CopilotChatSuggestionConfiguration } from \"../types\";\n\nexport interface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport const reloadSuggestions = async (\n context: CopilotContextParams & CopilotMessagesContextParams,\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration },\n setCurrentSuggestions: (suggestions: SuggestionItem[]) => void,\n abortControllerRef: React.MutableRefObject<AbortController | null>,\n): Promise<void> => {\n const abortController = abortControllerRef.current;\n\n // Early abort check\n if (abortController?.signal.aborted) {\n return;\n }\n\n // Abort-aware suggestion setter with safety checks to prevent race conditions\n const setSuggestionsIfNotAborted = (suggestions: SuggestionItem[]) => {\n if (!abortController?.signal.aborted && abortControllerRef.current === abortController) {\n setCurrentSuggestions(suggestions);\n }\n };\n\n try {\n const tools = JSON.stringify(\n Object.values(context.actions).map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n })),\n );\n\n const allSuggestions: SuggestionItem[] = [];\n let hasSuccessfulSuggestions = false;\n let hasErrors = false; // Track if any errors occurred\n let lastError: Error | null = null; // Track the last error for better error reporting\n\n // Get enabled configurations\n const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(\n (config) => config.instructions && config.instructions.trim().length > 0,\n );\n\n if (enabledConfigs.length === 0) {\n return;\n }\n\n // Clear existing suggestions\n setSuggestionsIfNotAborted([]);\n\n // Generate suggestions for each configuration\n for (const config of enabledConfigs) {\n // Check if aborted before each configuration\n if (abortController?.signal.aborted) {\n setSuggestionsIfNotAborted([]);\n return;\n }\n\n try {\n const result = await extract({\n context,\n instructions:\n \"Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. \",\n data: `${config.instructions}\\n\\nAvailable tools: ${tools}\\n\\n`,\n requestType: CopilotRequestType.Task,\n parameters: [\n {\n name: \"suggestions\",\n type: \"object[]\",\n attributes: [\n {\n name: \"title\",\n description:\n \"The title of the suggestion. This is shown as a button and should be short.\",\n type: \"string\",\n },\n {\n name: \"message\",\n description:\n \"The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI.\",\n type: \"string\",\n },\n ],\n },\n ],\n include: {\n messages: true,\n readable: true,\n },\n abortSignal: abortController?.signal,\n stream: ({ status, args }: { status: string; args: any }) => {\n // Check abort status in stream callback\n if (abortController?.signal.aborted) {\n return;\n }\n\n const suggestions = args.suggestions || [];\n const newSuggestions: SuggestionItem[] = [];\n\n for (let i = 0; i < suggestions.length; i++) {\n // Respect max suggestions limit\n if (config.maxSuggestions !== undefined && i >= config.maxSuggestions) {\n break;\n }\n\n const suggestion = suggestions[i];\n\n // Skip completely empty or invalid objects during streaming\n if (!suggestion || typeof suggestion !== \"object\") {\n continue;\n }\n\n const { title, message } = suggestion;\n\n // During streaming, be permissive but require at least a meaningful title\n const hasValidTitle = title && typeof title === \"string\" && title.trim().length > 0;\n const hasValidMessage =\n message && typeof message === \"string\" && message.trim().length > 0;\n\n // During streaming, we need at least a title to show something useful\n if (!hasValidTitle) {\n continue;\n }\n\n // Mark as partial if this is the last suggestion and streaming isn't complete\n const partial = i === suggestions.length - 1 && status !== \"complete\";\n\n newSuggestions.push({\n title: title.trim(),\n message: hasValidMessage ? message.trim() : \"\", // Use title as fallback\n partial,\n className: config.className,\n });\n }\n\n // Update suggestions with current batch\n setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);\n },\n });\n\n // Process final results with strict validation\n if (result?.suggestions && Array.isArray(result.suggestions)) {\n const validSuggestions = result.suggestions\n .filter(\n (suggestion: any) =>\n suggestion &&\n typeof suggestion.title === \"string\" &&\n suggestion.title.trim().length > 0,\n )\n .map((suggestion: any) => ({\n title: suggestion.title.trim(),\n message:\n suggestion.message &&\n typeof suggestion.message === \"string\" &&\n suggestion.message.trim()\n ? suggestion.message.trim()\n : suggestion.title.trim(),\n }));\n\n if (validSuggestions.length > 0) {\n allSuggestions.push(...validSuggestions);\n hasSuccessfulSuggestions = true;\n }\n }\n } catch (error) {\n // Simple error handling - just continue with next config, don't log here\n hasErrors = true;\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n }\n\n // Display any successful suggestions we got\n if (hasSuccessfulSuggestions && allSuggestions.length > 0) {\n // Remove duplicates based on message content\n const uniqueSuggestions = allSuggestions.filter(\n (suggestion, index, self) =>\n index === self.findIndex((s) => s.message === suggestion.message),\n );\n\n setSuggestionsIfNotAborted(uniqueSuggestions);\n } else if (hasErrors) {\n // If we had errors but no successful suggestions, throw an error with details\n const errorMessage = lastError\n ? lastError.message\n : \"Failed to generate suggestions due to API errors\";\n throw new Error(errorMessage);\n }\n } catch (error) {\n // Top-level error handler - re-throw to allow caller to handle\n throw error;\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0FA,IAAAA,iBAAwD;;;AC/ExD,mBAAkB;AAwOlB,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,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,eAAe,MAAM,CAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,s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AAC;AAAA,MACP,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,UAAU;AAAA,MACV,OAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["import_react","React","import_react","emptyCopilotContext","React","import_react","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","import_runtime_client_gql","import_shared","import_jsx_runtime","import_shared","import_runtime_client_gql","import_runtime_client_gql","import_shared","import_runtime_client_gql","import_jsx_runtime","import_runtime_client_gql","import_react","React","makeSystemMessage","_a","action","gqlRole","options","messages","DeprecatedGqlMessage","import_shared"]}
1
+ {"version":3,"sources":["../../src/hooks/use-coagent.ts","../../src/context/copilot-context.tsx","../../src/context/copilot-messages-context.tsx","../../src/hooks/use-copilot-chat_internal.ts","../../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/components/copilot-provider/copilot-messages.tsx","../../src/utils/extract.ts","../../src/utils/suggestions.ts","../../src/hooks/use-langgraph-interrupt-render.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { CopilotContextParams, useCopilotContext } from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { useCopilotChat } from \"./use-copilot-chat_internal\";\nimport { Message } from \"@copilotkit/shared\";\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\";\nimport { useMessagesTap } from \"../components/copilot-provider/copilot-messages\";\nimport { Message as GqlMessage } from \"@copilotkit/runtime-client-gql\";\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 context = useCopilotContext();\n const { availableAgents, onError } = context;\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 { getMessagesFromTap } = useMessagesTap();\n\n const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } =\n context;\n const { sendMessage, 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 onError,\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, getMessagesFromTap(), sendMessage, runChatCompletion, hint);\n },\n [name, context, sendMessage, 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,\n messages: GqlMessage[],\n sendMessage: (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 = messages.length - 1; i >= 0; i--) {\n const message = 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 sendMessage(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 {\n CopilotCloudConfig,\n FunctionCallHandler,\n CopilotErrorHandler,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\nimport { SuggestionItem } from \"../utils/suggestions\";\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 // banner error state\n bannerError: CopilotKitError | null;\n setBannerError: React.Dispatch<React.SetStateAction<CopilotKitError | null>>;\n // Internal error handlers\n // These are used to handle errors that occur during the execution of the chat.\n // They are not intended for use by the developer. A component can register itself an error listener to be activated somewhere else as needed\n internalErrorHandlers: Record<string, CopilotErrorHandler>;\n setInternalErrorHandler: (handler: Record<string, CopilotErrorHandler>) => void;\n removeInternalErrorHandler: (id: string) => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n 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: () => {},\n bannerError: null,\n setBannerError: () => {},\n internalErrorHandlers: {},\n setInternalErrorHandler: () => {},\n removeInternalErrorHandler: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport React from \"react\";\nimport { SuggestionItem } from \"../utils/suggestions\";\n\nexport interface CopilotMessagesContextParams {\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>; // suggestions state\n suggestions: SuggestionItem[];\n setSuggestions: React.Dispatch<React.SetStateAction<SuggestionItem[]>>;\n}\n\nconst emptyCopilotContext: CopilotMessagesContextParams = {\n messages: [],\n setMessages: () => [],\n // suggestions state\n suggestions: [],\n setSuggestions: () => [],\n};\n\nexport const CopilotMessagesContext =\n React.createContext<CopilotMessagesContextParams>(emptyCopilotContext);\n\nexport function useCopilotMessagesContext(): CopilotMessagesContextParams {\n const context = React.useContext(CopilotMessagesContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`\",\n );\n }\n return context;\n}\n","import { useRef, useEffect, useCallback, useState, useMemo } from \"react\";\nimport { AgentSession, useCopilotContext, CopilotContextParams } from \"../context/copilot-context\";\nimport { useCopilotMessagesContext, CopilotMessagesContextParams } from \"../context\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat, AppendMessageOptions } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CoAgentStateRenderHandlerArguments } from \"@copilotkit/shared\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { reloadSuggestions as generateSuggestions } from \"../utils\";\nimport type { SuggestionItem } from \"../utils\";\n\nimport { Message } from \"@copilotkit/shared\";\nimport {\n Role as gqlRole,\n TextMessage,\n aguiToGQL,\n gqlToAGUI,\n Message as DeprecatedGqlMessage,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useLangGraphInterruptRender } from \"./use-langgraph-interrupt-render\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Initial messages to populate the chat with.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n\n /**\n * Disables inclusion of CopilotKit’s default system message. When true, no system message is sent (this also suppresses any custom message from <code>makeSystemMessage</code>).\n */\n disableSystemMessage?: boolean;\n}\n\nexport interface MCPServerConfig {\n endpoint: string;\n apiKey?: string;\n}\n\nexport interface UseCopilotChatReturn {\n /**\n * @deprecated use `messages` instead, this is an old non ag-ui version of the messages\n * Array of messages currently visible in the chat interface\n *\n * This is the visible messages, not the raw messages from the runtime client.\n */\n visibleMessages: DeprecatedGqlMessage[];\n\n /**\n * The messages that are currently in the chat in AG-UI format.\n */\n messages: Message[];\n\n /** @deprecated use `sendMessage` instead */\n appendMessage: (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => Promise<void>;\n\n /**\n * Send a new message to the chat\n *\n * ```tsx\n * await sendMessage({\n * id: \"123\",\n * role: \"user\",\n * content: \"Hello, process this request\",\n * });\n * ```\n */\n sendMessage: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n\n /**\n * Replace all messages in the chat\n *\n * ```tsx\n * setMessages([\n * { id: \"123\", role: \"user\", content: \"Hello, process this request\" },\n * { id: \"456\", role: \"assistant\", content: \"Hello, I'm the assistant\" },\n * ]);\n * ```\n *\n * **Deprecated** non-ag-ui version:\n *\n * ```tsx\n * setMessages([\n * new TextMessage({\n * content: \"Hello, process this request\",\n * role: gqlRole.User,\n * }),\n * new TextMessage({\n * content: \"Hello, I'm the assistant\",\n * role: gqlRole.Assistant,\n * ]);\n * ```\n *\n */\n setMessages: (messages: Message[] | DeprecatedGqlMessage[]) => void;\n\n /**\n * Remove a specific message by ID\n *\n * ```tsx\n * deleteMessage(\"123\");\n * ```\n */\n deleteMessage: (messageId: string) => void;\n\n /**\n * Regenerate the response for a specific message\n *\n * ```tsx\n * reloadMessages(\"123\");\n * ```\n */\n reloadMessages: (messageId: string) => Promise<void>;\n\n /**\n * Stop the current message generation\n *\n * ```tsx\n * if (isLoading) {\n * stopGeneration();\n * }\n * ```\n */\n stopGeneration: () => void;\n\n /**\n * Clear all messages and reset chat state\n *\n * ```tsx\n * reset();\n * console.log(messages); // []\n * ```\n */\n reset: () => void;\n\n /**\n * Whether the chat is currently generating a response\n *\n * ```tsx\n * if (isLoading) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isLoading: boolean;\n\n /** Manually trigger chat completion (advanced usage) */\n runChatCompletion: () => Promise<Message[]>;\n\n /** MCP (Model Context Protocol) server configurations */\n mcpServers: MCPServerConfig[];\n\n /** Update MCP server configurations */\n setMcpServers: (mcpServers: MCPServerConfig[]) => void;\n\n /**\n * Current suggestions array\n * Use this to read the current suggestions or in conjunction with setSuggestions for manual control\n */\n suggestions: SuggestionItem[];\n\n /**\n * Manually set suggestions\n * Useful for manual mode or custom suggestion workflows\n */\n setSuggestions: (suggestions: SuggestionItem[]) => void;\n\n /**\n * Trigger AI-powered suggestion generation\n * Uses configurations from useCopilotChatSuggestions hooks\n * Respects global debouncing - only one generation can run at a time\n *\n * ```tsx\n * generateSuggestions();\n * console.log(suggestions); // [suggestion1, suggestion2, suggestion3]\n * ```\n */\n generateSuggestions: () => Promise<void>;\n\n /**\n * Clear all current suggestions\n * Also resets suggestion generation state\n */\n resetSuggestions: () => void;\n\n /** Whether suggestions are currently being generated */\n isLoadingSuggestions: boolean;\n\n /** Interrupt content for human-in-the-loop workflows */\n interrupt: string | React.ReactElement | null;\n}\n\nlet globalSuggestionPromise: Promise<void> | null = null;\n\nexport function useCopilotChat(options: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const makeSystemMessage = options.makeSystemMessage ?? defaultSystemMessage;\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 chatSuggestionConfiguration,\n\n runtimeClient,\n } = useCopilotContext();\n const { messages, setMessages, suggestions, setSuggestions } = useCopilotMessagesContext();\n\n // Simple state for MCP servers (keep for interface compatibility)\n const [mcpServers, setLocalMcpServers] = useState<MCPServerConfig[]>([]);\n\n // Basic suggestion state for programmatic control\n const suggestionsAbortControllerRef = useRef<AbortController | null>(null);\n const isLoadingSuggestionsRef = useRef<boolean>(false);\n\n const abortSuggestions = useCallback(\n (clear: boolean = true) => {\n suggestionsAbortControllerRef.current?.abort(\"suggestions aborted by user\");\n suggestionsAbortControllerRef.current = null;\n if (clear) {\n setSuggestions([]);\n }\n },\n [setSuggestions],\n );\n\n // Memoize context with stable dependencies only\n const stableContext = useMemo(() => {\n return {\n actions,\n copilotApiConfig,\n chatSuggestionConfiguration,\n messages,\n setMessages,\n getContextString,\n runtimeClient,\n };\n }, [\n JSON.stringify(Object.keys(actions)),\n copilotApiConfig.chatApiEndpoint,\n messages.length,\n Object.keys(chatSuggestionConfiguration).length,\n ]);\n\n // Programmatic suggestion generation function\n const generateSuggestionsFunc = useCallback(async () => {\n // If a global suggestion is running, ignore this call\n if (globalSuggestionPromise) {\n return globalSuggestionPromise;\n }\n\n globalSuggestionPromise = (async () => {\n try {\n abortSuggestions();\n isLoadingSuggestionsRef.current = true;\n suggestionsAbortControllerRef.current = new AbortController();\n\n setSuggestions([]);\n\n await generateSuggestions(\n stableContext as CopilotContextParams & CopilotMessagesContextParams,\n chatSuggestionConfiguration,\n setSuggestions,\n suggestionsAbortControllerRef,\n );\n } catch (error) {\n // Re-throw to allow caller to handle the error\n throw error;\n } finally {\n isLoadingSuggestionsRef.current = false;\n globalSuggestionPromise = null;\n }\n })();\n\n return globalSuggestionPromise;\n }, [stableContext, chatSuggestionConfiguration, setSuggestions, abortSuggestions]);\n\n const resetSuggestions = useCallback(() => {\n setSuggestions([]);\n }, [setSuggestions]);\n\n // MCP servers logic\n useEffect(() => {\n if (mcpServers.length > 0) {\n const serversCopy = [...mcpServers];\n copilotApiConfig.mcpServers = serversCopy;\n if (!copilotApiConfig.properties) {\n copilotApiConfig.properties = {};\n }\n copilotApiConfig.properties.mcpServers = serversCopy;\n }\n }, [mcpServers, copilotApiConfig]);\n\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: gqlRole.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: aguiToGQL(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 disableSystemMessage: options.disableSystemMessage,\n });\n\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useAsyncCallback(\n async (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => {\n abortSuggestions(options?.clearSuggestions);\n return await latestAppend.current(message, options);\n },\n [latestAppend],\n );\n\n const latestSendMessageFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n abortSuggestions(options?.clearSuggestions);\n return await latestAppend.current(aguiToGQL([message])[0] as DeprecatedGqlMessage, 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[] | DeprecatedGqlMessage[]) => {\n if (messages.every((message) => message instanceof DeprecatedGqlMessage)) {\n return latestSetMessages.current(messages as DeprecatedGqlMessage[]);\n }\n return latestSetMessages.current(aguiToGQL(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 // Reset suggestions when chat is reset\n resetSuggestions();\n }, [\n latestStopFunc,\n setMessages,\n setThreadId,\n setCoagentStatesWithRef,\n setAgentSession,\n agentLock,\n resetSuggestions,\n ]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n const interrupt = useLangGraphInterruptRender();\n\n return {\n visibleMessages: messages,\n messages: gqlToAGUI(messages, actions, coAgentStateRenders),\n sendMessage: latestSendMessageFunc,\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 suggestions,\n setSuggestions,\n generateSuggestions: generateSuggestionsFunc,\n resetSuggestions,\n isLoadingSuggestions: isLoadingSuggestionsRef.current,\n interrupt,\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 React, { useCallback, useEffect, useMemo, 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 disableSystemMessage?: boolean;\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 * Whether to clear the suggestions after appending the message. Defaults to `true`.\n */\n clearSuggestions?: 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 disableSystemMessage = false,\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, showDevConsole, getAllContext } = useCopilotContext();\n\n const copilotReadableContext = getAllContext();\n\n const context = useMemo(\n () =>\n copilotReadableContext.map((contextItem) => {\n const [description, ...valueParts] = contextItem.value.split(\":\");\n return {\n description: description.trim(),\n value: valueParts.join(\":\").trim(),\n };\n }),\n [copilotReadableContext],\n );\n\n // Add tracing functionality to use-chat\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\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 runtimeClient = useCopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n showDevConsole,\n onError,\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 messagesWithContext = disableSystemMessage\n ? [...(initialMessages || []), ...previousMessages]\n : [makeSystemMessageCallback(), ...(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 context,\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 // TODO: if onError & renderError should work without key, insert here\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 // TODO: if onError & renderError should work without key, insert here\n\n // Stop processing and break from the loop\n setIsLoading(false);\n throw new Error(structuredError.message);\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 === \"frontend\") {\n // never execute frontend 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 disableSystemMessage,\n context,\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 let historyCutoff: Message[] = [messages[0]];\n\n if (messages.length > 2 && reloadMessageIndex !== 0) {\n // message to regenerate from is now first.\n // Work backwards to find the first the closest user message\n const lastUserMessageBeforeRegenerate = messages\n .slice(0, reloadMessageIndex)\n .reverse()\n .find(\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 } else if (messages.length > 2 && reloadMessageIndex === 0) {\n historyCutoff = [messages[0], messages[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 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 // TODO: if onError & renderError should work without key, insert here\n } else {\n // Fallback for unstructured errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n // TODO: if onError & renderError should work without key, insert here\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n 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 // TODO: if onError & renderError should work without key, insert here\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 { PartialBy, CopilotKitError, Severity } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(null);\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(/'message':\\s*'([^']+)'/);\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n","function isLocalhost(): boolean {\n if (typeof window === \"undefined\") return false;\n\n return (\n window.location.hostname === \"localhost\" ||\n window.location.hostname === \"127.0.0.1\" ||\n window.location.hostname === \"0.0.0.0\"\n );\n}\n\nexport function shouldShowDevConsole(showDevConsole?: boolean): boolean {\n // If explicitly set, use that value\n if (showDevConsole !== undefined) {\n return showDevConsole;\n }\n\n // If not set, default to true on localhost\n return isLocalhost();\n}\n","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 CopilotKitError,\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages, MessagesTapProvider } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { 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 { ConsoleTrigger } from \"../dev-console/console-trigger\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n\n // Use API key if provided, otherwise use the license key\n const publicApiKey = props.publicApiKey || props.publicLicenseKey;\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={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 // Use license key as API key if provided, otherwise use the API key\n const publicApiKey = props.publicLicenseKey || props.publicApiKey;\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n 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 // Compute all the functions and properties that we need to pass\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const 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 (publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const [internalErrorHandlers, _setInternalErrorHandler] = useState<\n Record<string, CopilotErrorHandler>\n >({});\n const setInternalErrorHandler = useCallback((handler: Record<string, CopilotErrorHandler>) => {\n _setInternalErrorHandler((prev: Record<string, CopilotErrorHandler>) => ({\n ...prev,\n ...handler,\n }));\n }, []);\n const removeInternalErrorHandler = useCallback((key: string) => {\n _setInternalErrorHandler((prev) => {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n });\n }, []);\n\n // Keep latest values in refs\n const onErrorRef = useRef<CopilotErrorHandler | undefined>(props.onError);\n useEffect(() => {\n onErrorRef.current = props.onError;\n }, [props.onError]);\n\n const internalHandlersRef = useRef<Record<string, CopilotErrorHandler>>({});\n useEffect(() => {\n internalHandlersRef.current = internalErrorHandlers;\n }, [internalErrorHandlers]);\n\n const handleErrors = useCallback(\n async (error: CopilotErrorEvent) => {\n if (copilotApiConfig.publicApiKey && onErrorRef.current) {\n try {\n await onErrorRef.current(error);\n } catch (e) {\n console.error(\"Error in public onError handler:\", e);\n }\n }\n const handlers = Object.values(internalHandlersRef.current);\n await Promise.all(\n handlers.map((h) =>\n Promise.resolve(h(error)).catch((e) =>\n console.error(\"Error in internal error handler:\", e),\n ),\n ),\n );\n },\n [copilotApiConfig.publicApiKey],\n );\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: shouldShowDevConsole(props.showDevConsole),\n onError: handleErrors,\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 = shouldShowDevConsole(props.showDevConsole);\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 const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = 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 bannerError,\n setBannerError,\n onError: handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n }}\n >\n <MessagesTapProvider>\n <CopilotMessages>\n {memoizedChildren}\n {showDevConsole && <ConsoleTrigger />}\n </CopilotMessages>\n </MessagesTapProvider>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </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 // Check if we have either a runtimeUrl or one of the API keys\n const hasApiKey = props.publicApiKey || props.publicLicenseKey;\n\n if (!props.runtimeUrl && !hasApiKey) {\n throw new ConfigurationError(\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\",\n );\n }\n\n if (cloudFeatures.length > 0 && !hasApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport {\n ReactNode,\n useEffect,\n useState,\n useRef,\n useCallback,\n useMemo,\n createContext,\n useContext,\n} from \"react\";\nimport { CopilotMessagesContext } from \"../../context/copilot-messages-context\";\nimport {\n loadMessagesFromJsonRepresentation,\n Message,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useCopilotContext } from \"../../context/copilot-context\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { shouldShowDevConsole } from \"../../utils/dev-console\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n} from \"@copilotkit/shared\";\nimport { SuggestionItem } from \"../../utils/suggestions\";\n\n// Helper to determine if error should show as banner based on visibility and legacy patterns\nfunction shouldShowAsBanner(gqlError: GraphQLError): boolean {\n const extensions = gqlError.extensions;\n if (!extensions) return false;\n\n // Priority 1: Check error code for discovery errors (these should always be banners)\n const code = extensions.code as CopilotKitErrorCode;\n if (\n code === CopilotKitErrorCode.AGENT_NOT_FOUND ||\n code === CopilotKitErrorCode.API_NOT_FOUND ||\n code === CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND ||\n code === CopilotKitErrorCode.CONFIGURATION_ERROR ||\n code === CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR ||\n code === CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR\n ) {\n return true;\n }\n\n // Priority 2: Check banner visibility\n if (extensions.visibility === ErrorVisibility.BANNER) {\n return true;\n }\n\n // Priority 3: Check for critical errors that should be banners regardless of formal classification\n const errorMessage = gqlError.message.toLowerCase();\n if (\n errorMessage.includes(\"api key\") ||\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"unauthorized\") ||\n errorMessage.includes(\"authentication\") ||\n errorMessage.includes(\"incorrect api key\")\n ) {\n return true;\n }\n\n // Priority 4: Legacy stack trace detection for discovery errors\n const originalError = extensions.originalError as any;\n if (originalError?.stack) {\n return (\n originalError.stack.includes(\"CopilotApiDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")\n );\n }\n\n return false;\n}\n\n/**\n * MessagesTap is used to mitigate performance issues when we only need\n * a snapshot of the messages, not a continuously updating stream of messages.\n */\n\nexport type MessagesTap = {\n getMessagesFromTap: () => Message[];\n updateTapMessages: (messages: Message[]) => void;\n};\n\nconst MessagesTapContext = createContext<MessagesTap | null>(null);\n\nexport function useMessagesTap() {\n const tap = useContext(MessagesTapContext);\n if (!tap) throw new Error(\"useMessagesTap must be used inside <MessagesTapProvider>\");\n return tap;\n}\n\nexport function MessagesTapProvider({ children }: { children: React.ReactNode }) {\n const messagesRef = useRef<Message[]>([]);\n\n const tapRef = useRef<MessagesTap>({\n getMessagesFromTap: () => messagesRef.current,\n updateTapMessages: (messages: Message[]) => {\n messagesRef.current = messages;\n },\n });\n\n return (\n <MessagesTapContext.Provider value={tapRef.current}>{children}</MessagesTapContext.Provider>\n );\n}\n\n/**\n * CopilotKit messages context.\n */\n\nexport function CopilotMessages({ children }: { children: ReactNode }) {\n const [messages, setMessages] = useState<Message[]>([]);\n const lastLoadedThreadId = useRef<string>();\n const lastLoadedAgentName = useRef<string>();\n const lastLoadedMessages = useRef<string>();\n\n const { updateTapMessages } = useMessagesTap();\n\n const { threadId, agentSession, runtimeClient, showDevConsole, onError, copilotApiConfig } =\n useCopilotContext();\n const { setBannerError } = useToast();\n\n // Helper function to trace UI errors (similar to useCopilotRuntimeClient)\n const traceUIError = useCallback(\n async (error: CopilotKitError, originalError?: any) => {\n // Just check if onError and publicApiKey are defined\n if (!onError || !copilotApiConfig.publicApiKey) return;\n\n try {\n const traceEvent = {\n type: \"error\" as const,\n timestamp: Date.now(),\n context: {\n source: \"ui\" as const,\n request: {\n operation: \"loadAgentState\",\n url: copilotApiConfig.chatApiEndpoint,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onError(traceEvent);\n } catch (traceError) {\n console.error(\"Error in CopilotMessages onError handler:\", traceError);\n }\n },\n [onError, copilotApiConfig.publicApiKey, copilotApiConfig.chatApiEndpoint],\n );\n\n const createStructuredError = (gqlError: GraphQLError): CopilotKitError | null => {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n\n // Priority: Check stack trace for discovery errors first\n if (originalError?.stack) {\n if (originalError.stack.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message: originalError.message });\n }\n if (originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message: originalError.message });\n }\n if (originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n }\n\n // Fallback: Use the formal error code if available\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n return null;\n };\n\n const handleGraphQLErrors = useCallback(\n (error: any) => {\n if (error.graphQLErrors?.length) {\n const graphQLErrors = error.graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole);\n\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", gqlError.message);\n return;\n }\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // All other errors (including DEV_ONLY) show as banners for consistency\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the structured error\n traceUIError(ckError, gqlError);\n } else {\n // Fallback: create a generic error for unstructured GraphQL errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n }\n }\n },\n [setBannerError, showDevConsole, traceUIError],\n );\n\n useEffect(() => {\n if (!threadId || threadId === lastLoadedThreadId.current) return;\n if (\n threadId === lastLoadedThreadId.current &&\n agentSession?.agentName === lastLoadedAgentName.current\n ) {\n return;\n }\n\n const fetchMessages = async () => {\n if (!agentSession?.agentName) return;\n\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: agentSession?.agentName,\n });\n\n // Check for GraphQL errors and manually trigger error handling\n if (result.error) {\n // Update refs to prevent infinite retries of the same failed request\n lastLoadedThreadId.current = threadId;\n lastLoadedAgentName.current = agentSession?.agentName;\n handleGraphQLErrors(result.error);\n return; // Don't try to process the data if there's an error\n }\n\n const newMessages = result.data?.loadAgentState?.messages;\n if (newMessages === lastLoadedMessages.current) return;\n\n if (result.data?.loadAgentState) {\n lastLoadedMessages.current = newMessages;\n lastLoadedThreadId.current = threadId;\n lastLoadedAgentName.current = agentSession?.agentName;\n\n const messages = loadMessagesFromJsonRepresentation(JSON.parse(newMessages || \"[]\"));\n setMessages(messages);\n }\n };\n void fetchMessages();\n }, [threadId, agentSession?.agentName]);\n\n useEffect(() => {\n updateTapMessages(messages);\n }, [messages, updateTapMessages]);\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [suggestions, setSuggestions] = useState<SuggestionItem[]>([]);\n\n return (\n <CopilotMessagesContext.Provider\n value={{\n messages,\n setMessages,\n suggestions,\n setSuggestions,\n }}\n >\n {memoizedChildren}\n </CopilotMessagesContext.Provider>\n );\n}\n","import {\n Action,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n MappedParameterTypes,\n Parameter,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n ActionExecutionMessage,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\nimport {\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n} from \"@copilotkit/runtime-client-gql\";\n\ninterface InitialState<T extends Parameter[] | [] = []> {\n status: \"initial\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n}\n\ntype StreamHandlerArgs<T extends Parameter[] | [] = []> =\n | InitialState<T>\n | InProgressState<T>\n | CompleteState<T>;\n\ninterface ExtractOptions<T extends Parameter[]> {\n context: CopilotContextParams & CopilotMessagesContextParams;\n instructions: string;\n parameters: T;\n include?: IncludeOptions;\n data?: any;\n abortSignal?: AbortSignal;\n stream?: (args: StreamHandlerArgs<T>) => void;\n requestType?: CopilotRequestType;\n forwardedParameters?: ForwardedParametersInput;\n}\n\ninterface IncludeOptions {\n readable?: boolean;\n messages?: boolean;\n}\n\nexport async function extract<const T extends Parameter[]>({\n context,\n instructions,\n parameters,\n include,\n data,\n abortSignal,\n stream,\n requestType = CopilotRequestType.Task,\n forwardedParameters,\n}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {\n const { messages } = context;\n\n const action: Action<any> = {\n name: \"extract\",\n description: instructions,\n parameters,\n handler: (args: any) => {},\n };\n\n const includeReadable = include?.readable ?? false;\n const includeMessages = include?.messages ?? false;\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (includeReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = new TextMessage({\n content: makeSystemMessage(contextString, instructions),\n role: Role.System,\n });\n\n const instructionsMessage: Message = new TextMessage({\n content: makeInstructionsMessage(instructions),\n role: Role.User,\n });\n\n const response = context.runtimeClient.asStream(\n context.runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [\n {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n },\n ],\n url: window.location.href,\n },\n\n messages: convertMessagesToGqlInput(\n includeMessages\n ? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)]\n : [systemMessage, instructionsMessage],\n ),\n metadata: {\n requestType: requestType,\n },\n forwardedParameters: {\n ...(forwardedParameters ?? {}),\n toolChoice: \"function\",\n toolChoiceFunctionName: action.name,\n },\n },\n properties: context.copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n\n const reader = response.getReader();\n\n let isInitial = true;\n\n let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (abortSignal?.aborted) {\n throw new Error(\"Aborted\");\n }\n\n actionExecutionMessage = convertGqlOutputToMessages(\n value.generateCopilotResponse.messages,\n ).find((msg) => msg.isActionExecutionMessage()) as ActionExecutionMessage | undefined;\n\n if (!actionExecutionMessage) {\n continue;\n }\n\n stream?.({\n status: isInitial ? \"initial\" : \"inProgress\",\n args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,\n });\n\n isInitial = false;\n }\n\n if (!actionExecutionMessage) {\n throw new Error(\"extract() failed: No function call occurred\");\n }\n\n stream?.({\n status: \"complete\",\n args: actionExecutionMessage.arguments as MappedParameterTypes<T>,\n });\n\n return actionExecutionMessage.arguments as MappedParameterTypes<T>;\n}\n\n// We need to put this in a user message since some LLMs need\n// at least one user message to function\nfunction makeInstructionsMessage(instructions: string): string {\n return `\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n\nAny additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.\n`;\n}\n\nfunction makeSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with a function called extract you MUST call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call the function without saying anything else.\n`;\n}\n","/**\n * Suggestions utility functions for CopilotKit\n *\n * This module handles the generation of chat suggestions with optimized error handling\n * and streaming validation to prevent infinite retry loops and console spam.\n */\n\nimport { extract } from \"./extract\";\nimport { actionParametersToJsonSchema } from \"@copilotkit/shared\";\nimport { CopilotRequestType } from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { CopilotChatSuggestionConfiguration } from \"../types\";\n\nexport interface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport const reloadSuggestions = async (\n context: CopilotContextParams & CopilotMessagesContextParams,\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration },\n setCurrentSuggestions: (suggestions: SuggestionItem[]) => void,\n abortControllerRef: React.MutableRefObject<AbortController | null>,\n): Promise<void> => {\n const abortController = abortControllerRef.current;\n\n // Early abort check\n if (abortController?.signal.aborted) {\n return;\n }\n\n // Abort-aware suggestion setter with safety checks to prevent race conditions\n const setSuggestionsIfNotAborted = (suggestions: SuggestionItem[]) => {\n if (!abortController?.signal.aborted && abortControllerRef.current === abortController) {\n setCurrentSuggestions(suggestions);\n }\n };\n\n try {\n const tools = JSON.stringify(\n Object.values(context.actions).map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n })),\n );\n\n const allSuggestions: SuggestionItem[] = [];\n let hasSuccessfulSuggestions = false;\n let hasErrors = false; // Track if any errors occurred\n let lastError: Error | null = null; // Track the last error for better error reporting\n\n // Get enabled configurations\n const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(\n (config) => config.instructions && config.instructions.trim().length > 0,\n );\n\n if (enabledConfigs.length === 0) {\n return;\n }\n\n // Clear existing suggestions\n setSuggestionsIfNotAborted([]);\n\n // Generate suggestions for each configuration\n for (const config of enabledConfigs) {\n // Check if aborted before each configuration\n if (abortController?.signal.aborted) {\n setSuggestionsIfNotAborted([]);\n return;\n }\n\n try {\n const result = await extract({\n context,\n instructions:\n \"Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. \",\n data: `${config.instructions}\\n\\nAvailable tools: ${tools}\\n\\n`,\n requestType: CopilotRequestType.Task,\n parameters: [\n {\n name: \"suggestions\",\n type: \"object[]\",\n attributes: [\n {\n name: \"title\",\n description:\n \"The title of the suggestion. This is shown as a button and should be short.\",\n type: \"string\",\n },\n {\n name: \"message\",\n description:\n \"The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI.\",\n type: \"string\",\n },\n ],\n },\n ],\n include: {\n messages: true,\n readable: true,\n },\n abortSignal: abortController?.signal,\n stream: ({ status, args }: { status: string; args: any }) => {\n // Check abort status in stream callback\n if (abortController?.signal.aborted) {\n return;\n }\n\n const suggestions = args.suggestions || [];\n const newSuggestions: SuggestionItem[] = [];\n\n for (let i = 0; i < suggestions.length; i++) {\n // Respect max suggestions limit\n if (config.maxSuggestions !== undefined && i >= config.maxSuggestions) {\n break;\n }\n\n const suggestion = suggestions[i];\n\n // Skip completely empty or invalid objects during streaming\n if (!suggestion || typeof suggestion !== \"object\") {\n continue;\n }\n\n const { title, message } = suggestion;\n\n // During streaming, be permissive but require at least a meaningful title\n const hasValidTitle = title && typeof title === \"string\" && title.trim().length > 0;\n const hasValidMessage =\n message && typeof message === \"string\" && message.trim().length > 0;\n\n // During streaming, we need at least a title to show something useful\n if (!hasValidTitle) {\n continue;\n }\n\n // Mark as partial if this is the last suggestion and streaming isn't complete\n const partial = i === suggestions.length - 1 && status !== \"complete\";\n\n newSuggestions.push({\n title: title.trim(),\n message: hasValidMessage ? message.trim() : \"\", // Use title as fallback\n partial,\n className: config.className,\n });\n }\n\n // Update suggestions with current batch\n setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);\n },\n });\n\n // Process final results with strict validation\n if (result?.suggestions && Array.isArray(result.suggestions)) {\n const validSuggestions = result.suggestions\n .filter(\n (suggestion: any) =>\n suggestion &&\n typeof suggestion.title === \"string\" &&\n suggestion.title.trim().length > 0,\n )\n .map((suggestion: any) => ({\n title: suggestion.title.trim(),\n message:\n suggestion.message &&\n typeof suggestion.message === \"string\" &&\n suggestion.message.trim()\n ? suggestion.message.trim()\n : suggestion.title.trim(),\n }));\n\n if (validSuggestions.length > 0) {\n allSuggestions.push(...validSuggestions);\n hasSuccessfulSuggestions = true;\n }\n }\n } catch (error) {\n // Simple error handling - just continue with next config, don't log here\n hasErrors = true;\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n }\n\n // Display any successful suggestions we got\n if (hasSuccessfulSuggestions && allSuggestions.length > 0) {\n // Remove duplicates based on message content\n const uniqueSuggestions = allSuggestions.filter(\n (suggestion, index, self) =>\n index === self.findIndex((s) => s.message === suggestion.message),\n );\n\n setSuggestionsIfNotAborted(uniqueSuggestions);\n } else if (hasErrors) {\n // If we had errors but no successful suggestions, throw an error with details\n const errorMessage = lastError\n ? lastError.message\n : \"Failed to generate suggestions due to API errors\";\n throw new Error(errorMessage);\n }\n } catch (error) {\n // Top-level error handler - re-throw to allow caller to handle\n throw error;\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0FA,IAAAA,iBAAwD;;;AC/ExD,mBAAkB;AAwOlB,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,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,eAAe,MAAM,CAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qB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AI;AAAA,EAC3B,OAAO;AACL,WAAO;AAAA,MACL;AAAA,MACA,OAAO,qCAAwC,OAAO,IAAI,QAAQ,eAAe,CAAC;AAAA,MAClF,QAAQ,QAAQ,SACZ,QAAQ,SACR,QAAQ,eACN,EAAE,cAAc,QAAQ,aAAa,IACrC,CAAC;AAAA,MACP,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,UAAU;AAAA,MACV,OAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["import_react","React","import_react","emptyCopilotContext","React","import_react","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","import_runtime_client_gql","import_shared","import_jsx_runtime","import_shared","import_runtime_client_gql","import_runtime_client_gql","import_shared","import_runtime_client_gql","import_jsx_runtime","import_runtime_client_gql","import_react","React","makeSystemMessage","_a","action","gqlRole","options","messages","DeprecatedGqlMessage","import_shared"]}