@copilotkit/react-core 1.10.5-next.5 → 1.10.5-next.7

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 (74) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/{chunk-MY2BUA6F.mjs → chunk-2MGJO3FY.mjs} +6 -6
  3. package/dist/{chunk-CLQLVMW4.mjs → chunk-2QZSAQTX.mjs} +4 -4
  4. package/dist/{chunk-VQVTXQFI.mjs → chunk-AGBNJCIM.mjs} +2 -2
  5. package/dist/{chunk-DHGLYDRF.mjs → chunk-BKI4I4S2.mjs} +8 -8
  6. package/dist/{chunk-23SOG4FI.mjs → chunk-DSDAZA3B.mjs} +4 -4
  7. package/dist/{chunk-WZSSCA5T.mjs → chunk-FCRPPUZA.mjs} +2 -2
  8. package/dist/{chunk-G2GQX4FI.mjs → chunk-FRXYSJGZ.mjs} +2 -2
  9. package/dist/{chunk-5SPC4UVI.mjs → chunk-IF4OYMFZ.mjs} +7 -7
  10. package/dist/{chunk-5SPC4UVI.mjs.map → chunk-IF4OYMFZ.mjs.map} +1 -1
  11. package/dist/{chunk-AR7HJPGU.mjs → chunk-JEMBA7PE.mjs} +4 -4
  12. package/dist/{chunk-4JBVPOHK.mjs → chunk-KWS75AOU.mjs} +2 -2
  13. package/dist/{chunk-L3I57GMV.mjs → chunk-N4VN2B5S.mjs} +4 -4
  14. package/dist/{chunk-AOQEZ7AY.mjs → chunk-TM5MFTHG.mjs} +5 -5
  15. package/dist/{chunk-7D4OASUM.mjs → chunk-UPQPBCUW.mjs} +4 -4
  16. package/dist/{chunk-6R5PM7YT.mjs → chunk-Y5ZF7AZ3.mjs} +8 -8
  17. package/dist/{chunk-7LZXD5RJ.mjs → chunk-ZRDV3MVW.mjs} +11 -11
  18. package/dist/components/copilot-provider/copilot-messages.mjs +3 -3
  19. package/dist/components/copilot-provider/copilotkit.mjs +10 -10
  20. package/dist/components/copilot-provider/index.mjs +10 -10
  21. package/dist/components/dev-console/console-trigger.mjs +3 -3
  22. package/dist/components/dev-console/developer-console-modal.mjs +2 -2
  23. package/dist/components/error-boundary/error-boundary.mjs +2 -2
  24. package/dist/components/index.mjs +10 -10
  25. package/dist/context/index.mjs +4 -4
  26. package/dist/hooks/index.js +1 -1
  27. package/dist/hooks/index.js.map +1 -1
  28. package/dist/hooks/index.mjs +31 -31
  29. package/dist/hooks/use-chat.js +1 -1
  30. package/dist/hooks/use-chat.js.map +1 -1
  31. package/dist/hooks/use-chat.mjs +4 -4
  32. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  33. package/dist/hooks/use-coagent.js +1 -1
  34. package/dist/hooks/use-coagent.js.map +1 -1
  35. package/dist/hooks/use-coagent.mjs +15 -15
  36. package/dist/hooks/use-copilot-action.mjs +2 -2
  37. package/dist/hooks/use-copilot-authenticated-action.mjs +3 -3
  38. package/dist/hooks/use-copilot-chat-headless_c.js +1 -1
  39. package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
  40. package/dist/hooks/use-copilot-chat-headless_c.mjs +15 -15
  41. package/dist/hooks/use-copilot-chat.js +1 -1
  42. package/dist/hooks/use-copilot-chat.js.map +1 -1
  43. package/dist/hooks/use-copilot-chat.mjs +15 -15
  44. package/dist/hooks/use-copilot-chat_internal.js +1 -1
  45. package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
  46. package/dist/hooks/use-copilot-chat_internal.mjs +14 -14
  47. package/dist/hooks/use-langgraph-interrupt-render.mjs +1 -1
  48. package/dist/hooks/use-langgraph-interrupt.js +1 -1
  49. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  50. package/dist/hooks/use-langgraph-interrupt.mjs +15 -15
  51. package/dist/index.js +1 -1
  52. package/dist/index.js.map +1 -1
  53. package/dist/index.mjs +35 -35
  54. package/dist/lib/copilot-task.mjs +12 -12
  55. package/dist/lib/index.mjs +12 -12
  56. package/dist/utils/extract.mjs +10 -10
  57. package/dist/utils/index.mjs +10 -10
  58. package/dist/utils/suggestions.mjs +10 -10
  59. package/package.json +3 -3
  60. package/src/hooks/use-chat.ts +1 -1
  61. /package/dist/{chunk-MY2BUA6F.mjs.map → chunk-2MGJO3FY.mjs.map} +0 -0
  62. /package/dist/{chunk-CLQLVMW4.mjs.map → chunk-2QZSAQTX.mjs.map} +0 -0
  63. /package/dist/{chunk-VQVTXQFI.mjs.map → chunk-AGBNJCIM.mjs.map} +0 -0
  64. /package/dist/{chunk-DHGLYDRF.mjs.map → chunk-BKI4I4S2.mjs.map} +0 -0
  65. /package/dist/{chunk-23SOG4FI.mjs.map → chunk-DSDAZA3B.mjs.map} +0 -0
  66. /package/dist/{chunk-WZSSCA5T.mjs.map → chunk-FCRPPUZA.mjs.map} +0 -0
  67. /package/dist/{chunk-G2GQX4FI.mjs.map → chunk-FRXYSJGZ.mjs.map} +0 -0
  68. /package/dist/{chunk-AR7HJPGU.mjs.map → chunk-JEMBA7PE.mjs.map} +0 -0
  69. /package/dist/{chunk-4JBVPOHK.mjs.map → chunk-KWS75AOU.mjs.map} +0 -0
  70. /package/dist/{chunk-L3I57GMV.mjs.map → chunk-N4VN2B5S.mjs.map} +0 -0
  71. /package/dist/{chunk-AOQEZ7AY.mjs.map → chunk-TM5MFTHG.mjs.map} +0 -0
  72. /package/dist/{chunk-7D4OASUM.mjs.map → chunk-UPQPBCUW.mjs.map} +0 -0
  73. /package/dist/{chunk-6R5PM7YT.mjs.map → chunk-Y5ZF7AZ3.mjs.map} +0 -0
  74. /package/dist/{chunk-7LZXD5RJ.mjs.map → chunk-ZRDV3MVW.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-chat.ts","../../src/types/frontend-action.ts","../../src/context/copilot-context.tsx","../../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"],"sourcesContent":["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 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 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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBAA+D;AAC/D,uBAA0B;AAC1B,IAAAC,iBAQO;AACP,IAAAC,6BAwBO;;;ACnCP,gCAAwC;AACxC,oBAKO;AAwKA,SAAS,gCAAgC,SAAgC;AAC9E,QAAM,kBAAkB,QACrB;AAAA,IACC,CAAC,WACC,OAAO,cAAc,kDAAwB,YAC7C,OAAO,aAAa,QACpB,OAAO,SAAS,OAChB,OAAO,aAAa,cACpB,CAAC,OAAO;AAAA,EACZ,EACC,IAAI,CAAC,WAAW;AACf,QAAI,YAAiD,kDAAwB;AAC7E,QAAI,OAAO,UAAU;AACnB,kBAAY,kDAAwB;AAAA,IACtC,WAAW,OAAO,cAAc,YAAY;AAC1C,kBAAY,kDAAwB;AAAA,IACtC,WAAW,OAAO,cAAc,UAAU;AACxC,kBAAY,kDAAwB;AAAA,IACtC;AACA,WAAO;AAAA,MACL,MAAM,OAAO;AAAA,MACb,aAAa,OAAO,eAAe;AAAA,MACnC,YAAY,KAAK,cAAU,4CAA6B,OAAO,cAAc,CAAC,CAAC,CAAC;AAAA,MAChF;AAAA,IACF;AAAA,EACF,CAAC;AACH,SAAO;AACT;;;AC9LA,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;AA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Q,yCAAc;AAAA,QACpB,QACI;AAAA,UACE,SAAS;AAAA,UACT,OAAO,KAAK,MAAM,KAAK,UAAU,OAAO,OAAO,oBAAoB,KAAK,CAAC,CAAC;AAAA,QAC5E,IACA;AAAA,MACN;AAAA,MACA,mBAAmB,QAAQ;AAAA,MAC3B,YAAY,QAAQ;AAAA,IACtB,CAAC;AAAA,EACH;AAAA;AAEA,SAAS,kBACP,SACA,SACA;AACA,MAAI,aAAa;AACjB,MAAI,QAAQ,yBAAyB,GAAG;AACtC,iBAAa,QAAQ;AAAA,EACvB,WAAW,QAAQ,gBAAgB,GAAG;AACpC,iBAAa,QAAQ;AAAA,EACvB;AACA,SAAO,QAAQ;AAAA,IACb,CAAC,WACE,OAAO,SAAS,cAAc,OAAO,cAAc,cACpD,OAAO,iBAAiB;AAAA,EAC5B;AACF;","names":["import_react","import_shared","import_runtime_client_gql","React","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"]}
1
+ {"version":3,"sources":["../../src/hooks/use-chat.ts","../../src/types/frontend-action.ts","../../src/context/copilot-context.tsx","../../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"],"sourcesContent":["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 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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,I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I,QAAQ,yBAAyB,GAAG;AACtC,iBAAa,QAAQ;AAAA,EACvB,WAAW,QAAQ,gBAAgB,GAAG;AACpC,iBAAa,QAAQ;AAAA,EACvB;AACA,SAAO,QAAQ;AAAA,IACb,CAAC,WACE,OAAO,SAAS,cAAc,OAAO,cAAc,cACpD,OAAO,iBAAiB;AAAA,EAC5B;AACF;","names":["import_react","import_shared","import_runtime_client_gql","React","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"]}
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  useChat
3
- } from "../chunk-5SPC4UVI.mjs";
3
+ } from "../chunk-IF4OYMFZ.mjs";
4
4
  import "../chunk-4CEQJ2X6.mjs";
5
- import "../chunk-N4WEHORG.mjs";
6
- import "../chunk-O7ARI5CV.mjs";
7
5
  import "../chunk-Q3MCVRO3.mjs";
8
6
  import "../chunk-ICIK2BSB.mjs";
9
- import "../chunk-YHT6CWIY.mjs";
7
+ import "../chunk-N4WEHORG.mjs";
8
+ import "../chunk-O7ARI5CV.mjs";
10
9
  import "../chunk-EFL5OBKN.mjs";
10
+ import "../chunk-YHT6CWIY.mjs";
11
11
  import "../chunk-SKC7AJIV.mjs";
12
12
  export {
13
13
  useChat
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  useCoAgentStateRender
3
- } from "../chunk-CLQLVMW4.mjs";
4
- import "../chunk-YHT6CWIY.mjs";
3
+ } from "../chunk-2QZSAQTX.mjs";
5
4
  import "../chunk-EFL5OBKN.mjs";
5
+ import "../chunk-YHT6CWIY.mjs";
6
6
  import "../chunk-SKC7AJIV.mjs";
7
7
  export {
8
8
  useCoAgentStateRender
@@ -769,7 +769,7 @@ function useChat(options) {
769
769
  preservedStructure: !!originalCode
770
770
  });
771
771
  setIsLoading(false);
772
- break;
772
+ throw new Error(structuredError.message);
773
773
  } else if (messages2.length > 0) {
774
774
  newMessages = [...messages2];
775
775
  for (const message of messages2) {