@copilotkit/react-core 1.10.4-next.0 → 1.10.4-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/{chunk-BKODPOZI.mjs → chunk-2MGJO3FY.mjs} +7 -7
- package/dist/{chunk-DLEXVOQE.mjs → chunk-2QZSAQTX.mjs} +4 -4
- package/dist/{chunk-6EKLRL7B.mjs → chunk-36FJAVOF.mjs} +2 -2
- package/dist/{chunk-TQGWN4FE.mjs → chunk-5KVEE73R.mjs} +4 -4
- package/dist/{chunk-SAWWZBE3.mjs → chunk-6WTWBXEJ.mjs} +56 -15
- package/dist/chunk-6WTWBXEJ.mjs.map +1 -0
- package/dist/{chunk-KOGKA4V5.mjs → chunk-AALETENN.mjs} +3 -3
- package/dist/{chunk-B6ZYKFIA.mjs → chunk-CLAHAV6J.mjs} +10 -10
- package/dist/{chunk-CLMDRYEN.mjs → chunk-CXDK6XA5.mjs} +2 -2
- package/dist/{chunk-QXSEHCPY.mjs → chunk-DSDAZA3B.mjs} +4 -4
- package/dist/{chunk-PI7BDJ6G.mjs → chunk-EBSAU46C.mjs} +5 -5
- package/dist/{chunk-W7W43PPC.mjs → chunk-HWM2Z3J3.mjs} +2 -2
- package/dist/{chunk-FG3FWUVW.mjs → chunk-ID5JRMGN.mjs} +3 -3
- package/dist/{chunk-X2DNXTME.mjs → chunk-JEMBA7PE.mjs} +4 -4
- package/dist/{chunk-JJDXTTEN.mjs → chunk-KWS75AOU.mjs} +3 -3
- package/dist/{chunk-V5PU37CB.mjs → chunk-LLLCUHOO.mjs} +9 -10
- package/dist/chunk-LLLCUHOO.mjs.map +1 -0
- package/dist/{chunk-3RHHNUVV.mjs → chunk-MZ37BAAE.mjs} +2 -2
- package/dist/{chunk-L3I57GMV.mjs → chunk-N4VN2B5S.mjs} +4 -4
- package/dist/{chunk-FAUNHSQU.mjs → chunk-Q3MCVRO3.mjs} +1 -3
- package/dist/chunk-Q3MCVRO3.mjs.map +1 -0
- package/dist/{chunk-IN7GE4NO.mjs → chunk-QF3Q5LUN.mjs} +2 -2
- package/dist/{chunk-2DXYQG42.mjs → chunk-QNJNOZH3.mjs} +12 -11
- package/dist/chunk-QNJNOZH3.mjs.map +1 -0
- package/dist/{chunk-TEMLWRRT.mjs → chunk-YHT6CWIY.mjs} +8 -2
- package/dist/{chunk-TEMLWRRT.mjs.map → chunk-YHT6CWIY.mjs.map} +1 -1
- package/dist/components/copilot-provider/copilot-messages.js +7 -1
- package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
- package/dist/components/copilot-provider/copilot-messages.mjs +3 -3
- package/dist/components/copilot-provider/copilotkit-props.d.ts +1 -1
- package/dist/components/copilot-provider/copilotkit.d.ts +1 -1
- package/dist/components/copilot-provider/copilotkit.js +51 -6
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +10 -10
- package/dist/components/copilot-provider/index.d.ts +1 -1
- package/dist/components/copilot-provider/index.js +51 -6
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +10 -10
- package/dist/components/dev-console/console-trigger.js +7 -1
- package/dist/components/dev-console/console-trigger.js.map +1 -1
- package/dist/components/dev-console/console-trigger.mjs +3 -3
- package/dist/components/dev-console/developer-console-modal.js +7 -1
- package/dist/components/dev-console/developer-console-modal.js.map +1 -1
- package/dist/components/dev-console/developer-console-modal.mjs +2 -2
- package/dist/components/error-boundary/error-boundary.mjs +2 -2
- package/dist/components/index.d.ts +1 -1
- package/dist/components/index.js +51 -6
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +10 -10
- package/dist/context/copilot-context.d.ts +1 -1
- package/dist/context/copilot-context.js +7 -1
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +1 -1
- package/dist/context/copilot-messages-context.d.ts +2 -2
- package/dist/context/index.d.ts +2 -2
- package/dist/context/index.js +7 -1
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +4 -4
- package/dist/{copilot-context-256f9020.d.ts → copilot-context-59740e82.d.ts} +4 -1
- package/dist/hooks/index.d.ts +2 -2
- package/dist/hooks/index.js +12 -8
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +35 -35
- package/dist/hooks/use-chat.d.ts +1 -1
- package/dist/hooks/use-chat.js +9 -6
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +4 -4
- package/dist/hooks/use-coagent-state-render.js +7 -1
- package/dist/hooks/use-coagent-state-render.js.map +1 -1
- package/dist/hooks/use-coagent-state-render.mjs +2 -2
- package/dist/hooks/use-coagent.d.ts +1 -1
- package/dist/hooks/use-coagent.js +12 -8
- package/dist/hooks/use-coagent.js.map +1 -1
- package/dist/hooks/use-coagent.mjs +16 -16
- package/dist/hooks/use-copilot-action.js +7 -1
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -2
- package/dist/hooks/use-copilot-additional-instructions.js +7 -1
- package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
- package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
- package/dist/hooks/use-copilot-authenticated-action.js +7 -1
- package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
- package/dist/hooks/use-copilot-authenticated-action.mjs +3 -3
- package/dist/hooks/use-copilot-chat-headless_c.d.ts +2 -2
- package/dist/hooks/use-copilot-chat-headless_c.js +9 -6
- package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
- package/dist/hooks/use-copilot-chat-headless_c.mjs +16 -16
- package/dist/hooks/use-copilot-chat.d.ts +2 -2
- package/dist/hooks/use-copilot-chat.js +9 -6
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +16 -16
- package/dist/hooks/use-copilot-chat_internal.d.ts +2 -2
- package/dist/hooks/use-copilot-chat_internal.js +9 -6
- package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
- package/dist/hooks/use-copilot-chat_internal.mjs +15 -15
- package/dist/hooks/use-copilot-readable.js +7 -1
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-copilot-runtime-client.d.ts +1 -1
- package/dist/hooks/use-copilot-runtime-client.js +0 -2
- package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
- package/dist/hooks/use-copilot-runtime-client.mjs +1 -1
- package/dist/hooks/use-langgraph-interrupt-render.js +7 -1
- package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
- package/dist/hooks/use-langgraph-interrupt-render.mjs +2 -2
- package/dist/hooks/use-langgraph-interrupt.d.ts +1 -1
- package/dist/hooks/use-langgraph-interrupt.js +9 -6
- package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
- package/dist/hooks/use-langgraph-interrupt.mjs +16 -16
- package/dist/hooks/use-make-copilot-document-readable.js +7 -1
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
- package/dist/{index-08c43df1.d.ts → index-d1743abe.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +56 -11
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +40 -40
- package/dist/lib/copilot-task.d.ts +1 -1
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +12 -12
- package/dist/lib/index.d.ts +1 -1
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +12 -12
- package/dist/types/interrupt-action.d.ts +1 -1
- package/dist/utils/extract.d.ts +2 -2
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +10 -10
- package/dist/utils/index.d.ts +2 -2
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +11 -11
- package/dist/utils/suggestions.d.ts +2 -2
- package/dist/utils/suggestions.js.map +1 -1
- package/dist/utils/suggestions.mjs +10 -10
- package/package.json +3 -3
- package/src/components/copilot-provider/copilotkit.tsx +55 -2
- package/src/context/copilot-context.tsx +11 -2
- package/src/hooks/use-chat.ts +3 -3
- package/src/hooks/use-coagent.ts +2 -1
- package/src/hooks/use-copilot-runtime-client.ts +4 -4
- package/dist/chunk-2DXYQG42.mjs.map +0 -1
- package/dist/chunk-FAUNHSQU.mjs.map +0 -1
- package/dist/chunk-SAWWZBE3.mjs.map +0 -1
- package/dist/chunk-V5PU37CB.mjs.map +0 -1
- /package/dist/{chunk-BKODPOZI.mjs.map → chunk-2MGJO3FY.mjs.map} +0 -0
- /package/dist/{chunk-DLEXVOQE.mjs.map → chunk-2QZSAQTX.mjs.map} +0 -0
- /package/dist/{chunk-6EKLRL7B.mjs.map → chunk-36FJAVOF.mjs.map} +0 -0
- /package/dist/{chunk-TQGWN4FE.mjs.map → chunk-5KVEE73R.mjs.map} +0 -0
- /package/dist/{chunk-KOGKA4V5.mjs.map → chunk-AALETENN.mjs.map} +0 -0
- /package/dist/{chunk-B6ZYKFIA.mjs.map → chunk-CLAHAV6J.mjs.map} +0 -0
- /package/dist/{chunk-CLMDRYEN.mjs.map → chunk-CXDK6XA5.mjs.map} +0 -0
- /package/dist/{chunk-QXSEHCPY.mjs.map → chunk-DSDAZA3B.mjs.map} +0 -0
- /package/dist/{chunk-PI7BDJ6G.mjs.map → chunk-EBSAU46C.mjs.map} +0 -0
- /package/dist/{chunk-W7W43PPC.mjs.map → chunk-HWM2Z3J3.mjs.map} +0 -0
- /package/dist/{chunk-FG3FWUVW.mjs.map → chunk-ID5JRMGN.mjs.map} +0 -0
- /package/dist/{chunk-X2DNXTME.mjs.map → chunk-JEMBA7PE.mjs.map} +0 -0
- /package/dist/{chunk-JJDXTTEN.mjs.map → chunk-KWS75AOU.mjs.map} +0 -0
- /package/dist/{chunk-3RHHNUVV.mjs.map → chunk-MZ37BAAE.mjs.map} +0 -0
- /package/dist/{chunk-L3I57GMV.mjs.map → chunk-N4VN2B5S.mjs.map} +0 -0
- /package/dist/{chunk-IN7GE4NO.mjs.map → chunk-QF3Q5LUN.mjs.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/suggestions.ts","../../src/utils/extract.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * Suggestions utility functions for CopilotKit\n *\n * This module handles the generation of chat suggestions with optimized error handling\n * and streaming validation to prevent infinite retry loops and console spam.\n */\n\nimport { extract } from \"./extract\";\nimport { actionParametersToJsonSchema } from \"@copilotkit/shared\";\nimport { CopilotRequestType } from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { CopilotChatSuggestionConfiguration } from \"../types\";\n\nexport interface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport const reloadSuggestions = async (\n context: CopilotContextParams & CopilotMessagesContextParams,\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration },\n setCurrentSuggestions: (suggestions: SuggestionItem[]) => void,\n abortControllerRef: React.MutableRefObject<AbortController | null>,\n): Promise<void> => {\n const abortController = abortControllerRef.current;\n\n // Early abort check\n if (abortController?.signal.aborted) {\n return;\n }\n\n // Abort-aware suggestion setter with safety checks to prevent race conditions\n const setSuggestionsIfNotAborted = (suggestions: SuggestionItem[]) => {\n if (!abortController?.signal.aborted && abortControllerRef.current === abortController) {\n setCurrentSuggestions(suggestions);\n }\n };\n\n try {\n const tools = JSON.stringify(\n Object.values(context.actions).map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n })),\n );\n\n const allSuggestions: SuggestionItem[] = [];\n let hasSuccessfulSuggestions = false;\n let hasErrors = false; // Track if any errors occurred\n let lastError: Error | null = null; // Track the last error for better error reporting\n\n // Get enabled configurations\n const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(\n (config) => config.instructions && config.instructions.trim().length > 0,\n );\n\n if (enabledConfigs.length === 0) {\n return;\n }\n\n // Clear existing suggestions\n setSuggestionsIfNotAborted([]);\n\n // Generate suggestions for each configuration\n for (const config of enabledConfigs) {\n // Check if aborted before each configuration\n if (abortController?.signal.aborted) {\n setSuggestionsIfNotAborted([]);\n return;\n }\n\n try {\n const result = await extract({\n context,\n instructions:\n \"Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. \",\n data: `${config.instructions}\\n\\nAvailable tools: ${tools}\\n\\n`,\n requestType: CopilotRequestType.Task,\n parameters: [\n {\n name: \"suggestions\",\n type: \"object[]\",\n attributes: [\n {\n name: \"title\",\n description:\n \"The title of the suggestion. This is shown as a button and should be short.\",\n type: \"string\",\n },\n {\n name: \"message\",\n description:\n \"The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI.\",\n type: \"string\",\n },\n ],\n },\n ],\n include: {\n messages: true,\n readable: true,\n },\n abortSignal: abortController?.signal,\n stream: ({ status, args }: { status: string; args: any }) => {\n // Check abort status in stream callback\n if (abortController?.signal.aborted) {\n return;\n }\n\n const suggestions = args.suggestions || [];\n const newSuggestions: SuggestionItem[] = [];\n\n for (let i = 0; i < suggestions.length; i++) {\n // Respect max suggestions limit\n if (config.maxSuggestions !== undefined && i >= config.maxSuggestions) {\n break;\n }\n\n const suggestion = suggestions[i];\n\n // Skip completely empty or invalid objects during streaming\n if (!suggestion || typeof suggestion !== \"object\") {\n continue;\n }\n\n const { title, message } = suggestion;\n\n // During streaming, be permissive but require at least a meaningful title\n const hasValidTitle = title && typeof title === \"string\" && title.trim().length > 0;\n const hasValidMessage =\n message && typeof message === \"string\" && message.trim().length > 0;\n\n // During streaming, we need at least a title to show something useful\n if (!hasValidTitle) {\n continue;\n }\n\n // Mark as partial if this is the last suggestion and streaming isn't complete\n const partial = i === suggestions.length - 1 && status !== \"complete\";\n\n newSuggestions.push({\n title: title.trim(),\n message: hasValidMessage ? message.trim() : \"\", // Use title as fallback\n partial,\n className: config.className,\n });\n }\n\n // Update suggestions with current batch\n setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);\n },\n });\n\n // Process final results with strict validation\n if (result?.suggestions && Array.isArray(result.suggestions)) {\n const validSuggestions = result.suggestions\n .filter(\n (suggestion: any) =>\n suggestion &&\n typeof suggestion.title === \"string\" &&\n suggestion.title.trim().length > 0,\n )\n .map((suggestion: any) => ({\n title: suggestion.title.trim(),\n message:\n suggestion.message &&\n typeof suggestion.message === \"string\" &&\n suggestion.message.trim()\n ? suggestion.message.trim()\n : suggestion.title.trim(),\n }));\n\n if (validSuggestions.length > 0) {\n allSuggestions.push(...validSuggestions);\n hasSuccessfulSuggestions = true;\n }\n }\n } catch (error) {\n // Simple error handling - just continue with next config, don't log here\n hasErrors = true;\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n }\n\n // Display any successful suggestions we got\n if (hasSuccessfulSuggestions && allSuggestions.length > 0) {\n // Remove duplicates based on message content\n const uniqueSuggestions = allSuggestions.filter(\n (suggestion, index, self) =>\n index === self.findIndex((s) => s.message === suggestion.message),\n );\n\n setSuggestionsIfNotAborted(uniqueSuggestions);\n } else if (hasErrors) {\n // If we had errors but no successful suggestions, throw an error with details\n const errorMessage = lastError\n ? lastError.message\n : \"Failed to generate suggestions due to API errors\";\n throw new Error(errorMessage);\n }\n } catch (error) {\n // Top-level error handler - re-throw to allow caller to handle\n throw error;\n }\n};\n","import {\n Action,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n MappedParameterTypes,\n Parameter,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n ActionExecutionMessage,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\nimport {\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n} from \"@copilotkit/runtime-client-gql\";\n\ninterface InitialState<T extends Parameter[] | [] = []> {\n status: \"initial\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n}\n\ntype StreamHandlerArgs<T extends Parameter[] | [] = []> =\n | InitialState<T>\n | InProgressState<T>\n | CompleteState<T>;\n\ninterface ExtractOptions<T extends Parameter[]> {\n context: CopilotContextParams & CopilotMessagesContextParams;\n instructions: string;\n parameters: T;\n include?: IncludeOptions;\n data?: any;\n abortSignal?: AbortSignal;\n stream?: (args: StreamHandlerArgs<T>) => void;\n requestType?: CopilotRequestType;\n forwardedParameters?: ForwardedParametersInput;\n}\n\ninterface IncludeOptions {\n readable?: boolean;\n messages?: boolean;\n}\n\nexport async function extract<const T extends Parameter[]>({\n context,\n instructions,\n parameters,\n include,\n data,\n abortSignal,\n stream,\n requestType = CopilotRequestType.Task,\n forwardedParameters,\n}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {\n const { messages } = context;\n\n const action: Action<any> = {\n name: \"extract\",\n description: instructions,\n parameters,\n handler: (args: any) => {},\n };\n\n const includeReadable = include?.readable ?? false;\n const includeMessages = include?.messages ?? false;\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (includeReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = new TextMessage({\n content: makeSystemMessage(contextString, instructions),\n role: Role.System,\n });\n\n const instructionsMessage: Message = new TextMessage({\n content: makeInstructionsMessage(instructions),\n role: Role.User,\n });\n\n const response = context.runtimeClient.asStream(\n context.runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [\n {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n },\n ],\n url: window.location.href,\n },\n\n messages: convertMessagesToGqlInput(\n includeMessages\n ? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)]\n : [systemMessage, instructionsMessage],\n ),\n metadata: {\n requestType: requestType,\n },\n forwardedParameters: {\n ...(forwardedParameters ?? {}),\n toolChoice: \"function\",\n toolChoiceFunctionName: action.name,\n },\n },\n properties: context.copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n\n const reader = response.getReader();\n\n let isInitial = true;\n\n let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (abortSignal?.aborted) {\n throw new Error(\"Aborted\");\n }\n\n actionExecutionMessage = convertGqlOutputToMessages(\n value.generateCopilotResponse.messages,\n ).find((msg) => msg.isActionExecutionMessage()) as ActionExecutionMessage | undefined;\n\n if (!actionExecutionMessage) {\n continue;\n }\n\n stream?.({\n status: isInitial ? \"initial\" : \"inProgress\",\n args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,\n });\n\n isInitial = false;\n }\n\n if (!actionExecutionMessage) {\n throw new Error(\"extract() failed: No function call occurred\");\n }\n\n stream?.({\n status: \"complete\",\n args: actionExecutionMessage.arguments as MappedParameterTypes<T>,\n });\n\n return actionExecutionMessage.arguments as MappedParameterTypes<T>;\n}\n\n// We need to put this in a user message since some LLMs need\n// at least one user message to function\nfunction makeInstructionsMessage(instructions: string): string {\n return `\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n\nAny additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.\n`;\n}\n\nfunction makeSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with a function called extract you MUST call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call the function without saying anything else.\n`;\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, SetStateAction } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages, MessagesTapProvider } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { useCopilotRuntimeClient } from \"../../hooks/use-copilot-runtime-client\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetterArgs,\n} from \"../../types/interrupt-action\";\nimport { ConsoleTrigger } from \"../dev-console/console-trigger\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n\n // Use API key if provided, otherwise use the license key\n const publicApiKey = props.publicApiKey || props.publicLicenseKey;\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={publicApiKey} showUsageBanner={enabled}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n // Use license key as API key if provided, otherwise use the API key\n const publicApiKey = props.publicLicenseKey || props.publicApiKey;\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<string[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n // Compute all the functions and properties that we need to pass\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => {\n return {\n ...prevPoints,\n [id]: stateRender,\n };\n });\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: shouldShowDevConsole(props.showDevConsole),\n onError: props.onError,\n });\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n const hasLoadedAgents = useRef(false);\n\n useEffect(() => {\n if (hasLoadedAgents.current) return;\n\n const fetchData = async () => {\n const result = await runtimeClient.availableAgents();\n if (result.data?.availableAgents) {\n setAvailableAgents(result.data.availableAgents.agents);\n }\n hasLoadedAgents.current = true;\n };\n void fetchData();\n }, []);\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const [internalThreadId, setInternalThreadId] = useState<string>(props.threadId || randomUUID());\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\"Cannot call setThreadId() when threadId is provided via props.\");\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n // update the internal threadId if the props.threadId changes\n useEffect(() => {\n if (props.threadId !== undefined) {\n setInternalThreadId(props.threadId);\n }\n }, [props.threadId]);\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = shouldShowDevConsole(props.showDevConsole);\n\n const [langGraphInterruptAction, _setLangGraphInterruptAction] =\n useState<LangGraphInterruptAction | null>(null);\n const setLangGraphInterruptAction = useCallback((action: LangGraphInterruptActionSetterArgs) => {\n _setLangGraphInterruptAction((prev) => {\n if (prev == null) return action as LangGraphInterruptAction;\n if (action == null) return null;\n let event = prev.event;\n if (action.event) {\n // @ts-ignore\n event = { ...prev.event, ...action.event };\n }\n return { ...prev, ...action, event };\n });\n }, []);\n const removeLangGraphInterruptAction = useCallback((): void => {\n setLangGraphInterruptAction(null);\n }, []);\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = typeof newExtensions === \"function\" ? newExtensions(prev) : newExtensions;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved = typeof newAuthStates === \"function\" ? newAuthStates(prev) : newAuthStates;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n runtimeClient,\n forwardedParameters,\n agentLock,\n threadId: internalThreadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n removeLangGraphInterruptAction,\n onError: props.onError,\n bannerError,\n setBannerError,\n }}\n >\n <MessagesTapProvider>\n <CopilotMessages>\n {memoizedChildren}\n {showDevConsole && <ConsoleTrigger />}\n </CopilotMessages>\n </MessagesTapProvider>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ name, args }: { name: string; args: Record<string, any> }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n // Check if we have either a runtimeUrl or one of the API keys\n const hasApiKey = props.publicApiKey || props.publicLicenseKey;\n\n if (!props.runtimeUrl && !hasApiKey) {\n throw new ConfigurationError(\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\",\n );\n }\n\n if (cloudFeatures.length > 0 && !hasApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAMO;AACP,gCAQO;;;ACCP,mBAAkF;AAUlF,uBAA0B;AAC1B,oBASO;AA4BC;AA+bD,IAAM,kCAAkC,CAAC,QAAQ;;;AD5exD,IAAAC,6BAGO;AAuCP,SAAsB,QAAqC,IAUH;AAAA,6CAVG;AAAA,IACzD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,6CAAmB;AAAA,IACjC;AAAA,EACF,GAAwD;AAvExD;AAwEE,UAAM,EAAE,SAAS,IAAI;AAErB,UAAM,SAAsB;AAAA,MAC1B,MAAM;AAAA,MACN,aAAa;AAAA,MACb;AAAA,MACA,SAAS,CAAC,SAAc;AAAA,MAAC;AAAA,IAC3B;AAEA,UAAM,mBAAkB,wCAAS,aAAT,YAAqB;AAC7C,UAAM,mBAAkB,wCAAS,aAAT,YAAqB;AAE7C,QAAI,gBAAgB;AAEpB,QAAI,MAAM;AACR,uBAAiB,OAAO,SAAS,WAAW,OAA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AAAA,MACtE;AAAA,IACF;AAGA,QAAI,4BAA4B,eAAe,SAAS,GAAG;AAEzD,YAAM,oBAAoB,eAAe;AAAA,QACvC,CAAC,YAAY,OAAO,SAClB,UAAU,KAAK,UAAU,CAAC,MAAM,EAAE,YAAY,WAAW,OAAO;AAAA,MACpE;AAEA,iCAA2B,iBAAiB;AAAA,IAC9C,WAAW,WAAW;AAEpB,YAAM,eAAe,YACjB,UAAU,UACV;AACJ,YAAM,IAAI,MAAM,YAAY;AAAA,IAC9B;AAAA,EACF,SAAS,OAAP;AAEA,UAAM;AAAA,EACR;AACF;","names":["import_shared","import_runtime_client_gql","import_shared","import_runtime_client_gql"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/suggestions.ts","../../src/utils/extract.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * Suggestions utility functions for CopilotKit\n *\n * This module handles the generation of chat suggestions with optimized error handling\n * and streaming validation to prevent infinite retry loops and console spam.\n */\n\nimport { extract } from \"./extract\";\nimport { actionParametersToJsonSchema } from \"@copilotkit/shared\";\nimport { CopilotRequestType } from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { CopilotChatSuggestionConfiguration } from \"../types\";\n\nexport interface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport const reloadSuggestions = async (\n context: CopilotContextParams & CopilotMessagesContextParams,\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration },\n setCurrentSuggestions: (suggestions: SuggestionItem[]) => void,\n abortControllerRef: React.MutableRefObject<AbortController | null>,\n): Promise<void> => {\n const abortController = abortControllerRef.current;\n\n // Early abort check\n if (abortController?.signal.aborted) {\n return;\n }\n\n // Abort-aware suggestion setter with safety checks to prevent race conditions\n const setSuggestionsIfNotAborted = (suggestions: SuggestionItem[]) => {\n if (!abortController?.signal.aborted && abortControllerRef.current === abortController) {\n setCurrentSuggestions(suggestions);\n }\n };\n\n try {\n const tools = JSON.stringify(\n Object.values(context.actions).map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n })),\n );\n\n const allSuggestions: SuggestionItem[] = [];\n let hasSuccessfulSuggestions = false;\n let hasErrors = false; // Track if any errors occurred\n let lastError: Error | null = null; // Track the last error for better error reporting\n\n // Get enabled configurations\n const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(\n (config) => config.instructions && config.instructions.trim().length > 0,\n );\n\n if (enabledConfigs.length === 0) {\n return;\n }\n\n // Clear existing suggestions\n setSuggestionsIfNotAborted([]);\n\n // Generate suggestions for each configuration\n for (const config of enabledConfigs) {\n // Check if aborted before each configuration\n if (abortController?.signal.aborted) {\n setSuggestionsIfNotAborted([]);\n return;\n }\n\n try {\n const result = await extract({\n context,\n instructions:\n \"Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. \",\n data: `${config.instructions}\\n\\nAvailable tools: ${tools}\\n\\n`,\n requestType: CopilotRequestType.Task,\n parameters: [\n {\n name: \"suggestions\",\n type: \"object[]\",\n attributes: [\n {\n name: \"title\",\n description:\n \"The title of the suggestion. This is shown as a button and should be short.\",\n type: \"string\",\n },\n {\n name: \"message\",\n description:\n \"The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI.\",\n type: \"string\",\n },\n ],\n },\n ],\n include: {\n messages: true,\n readable: true,\n },\n abortSignal: abortController?.signal,\n stream: ({ status, args }: { status: string; args: any }) => {\n // Check abort status in stream callback\n if (abortController?.signal.aborted) {\n return;\n }\n\n const suggestions = args.suggestions || [];\n const newSuggestions: SuggestionItem[] = [];\n\n for (let i = 0; i < suggestions.length; i++) {\n // Respect max suggestions limit\n if (config.maxSuggestions !== undefined && i >= config.maxSuggestions) {\n break;\n }\n\n const suggestion = suggestions[i];\n\n // Skip completely empty or invalid objects during streaming\n if (!suggestion || typeof suggestion !== \"object\") {\n continue;\n }\n\n const { title, message } = suggestion;\n\n // During streaming, be permissive but require at least a meaningful title\n const hasValidTitle = title && typeof title === \"string\" && title.trim().length > 0;\n const hasValidMessage =\n message && typeof message === \"string\" && message.trim().length > 0;\n\n // During streaming, we need at least a title to show something useful\n if (!hasValidTitle) {\n continue;\n }\n\n // Mark as partial if this is the last suggestion and streaming isn't complete\n const partial = i === suggestions.length - 1 && status !== \"complete\";\n\n newSuggestions.push({\n title: title.trim(),\n message: hasValidMessage ? message.trim() : \"\", // Use title as fallback\n partial,\n className: config.className,\n });\n }\n\n // Update suggestions with current batch\n setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);\n },\n });\n\n // Process final results with strict validation\n if (result?.suggestions && Array.isArray(result.suggestions)) {\n const validSuggestions = result.suggestions\n .filter(\n (suggestion: any) =>\n suggestion &&\n typeof suggestion.title === \"string\" &&\n suggestion.title.trim().length > 0,\n )\n .map((suggestion: any) => ({\n title: suggestion.title.trim(),\n message:\n suggestion.message &&\n typeof suggestion.message === \"string\" &&\n suggestion.message.trim()\n ? suggestion.message.trim()\n : suggestion.title.trim(),\n }));\n\n if (validSuggestions.length > 0) {\n allSuggestions.push(...validSuggestions);\n hasSuccessfulSuggestions = true;\n }\n }\n } catch (error) {\n // Simple error handling - just continue with next config, don't log here\n hasErrors = true;\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n }\n\n // Display any successful suggestions we got\n if (hasSuccessfulSuggestions && allSuggestions.length > 0) {\n // Remove duplicates based on message content\n const uniqueSuggestions = allSuggestions.filter(\n (suggestion, index, self) =>\n index === self.findIndex((s) => s.message === suggestion.message),\n );\n\n setSuggestionsIfNotAborted(uniqueSuggestions);\n } else if (hasErrors) {\n // If we had errors but no successful suggestions, throw an error with details\n const errorMessage = lastError\n ? lastError.message\n : \"Failed to generate suggestions due to API errors\";\n throw new Error(errorMessage);\n }\n } catch (error) {\n // Top-level error handler - re-throw to allow caller to handle\n throw error;\n }\n};\n","import {\n Action,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n MappedParameterTypes,\n Parameter,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n ActionExecutionMessage,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\nimport {\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n} from \"@copilotkit/runtime-client-gql\";\n\ninterface InitialState<T extends Parameter[] | [] = []> {\n status: \"initial\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n}\n\ntype StreamHandlerArgs<T extends Parameter[] | [] = []> =\n | InitialState<T>\n | InProgressState<T>\n | CompleteState<T>;\n\ninterface ExtractOptions<T extends Parameter[]> {\n context: CopilotContextParams & CopilotMessagesContextParams;\n instructions: string;\n parameters: T;\n include?: IncludeOptions;\n data?: any;\n abortSignal?: AbortSignal;\n stream?: (args: StreamHandlerArgs<T>) => void;\n requestType?: CopilotRequestType;\n forwardedParameters?: ForwardedParametersInput;\n}\n\ninterface IncludeOptions {\n readable?: boolean;\n messages?: boolean;\n}\n\nexport async function extract<const T extends Parameter[]>({\n context,\n instructions,\n parameters,\n include,\n data,\n abortSignal,\n stream,\n requestType = CopilotRequestType.Task,\n forwardedParameters,\n}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {\n const { messages } = context;\n\n const action: Action<any> = {\n name: \"extract\",\n description: instructions,\n parameters,\n handler: (args: any) => {},\n };\n\n const includeReadable = include?.readable ?? false;\n const includeMessages = include?.messages ?? false;\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (includeReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = new TextMessage({\n content: makeSystemMessage(contextString, instructions),\n role: Role.System,\n });\n\n const instructionsMessage: Message = new TextMessage({\n content: makeInstructionsMessage(instructions),\n role: Role.User,\n });\n\n const response = context.runtimeClient.asStream(\n context.runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [\n {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n },\n ],\n url: window.location.href,\n },\n\n messages: convertMessagesToGqlInput(\n includeMessages\n ? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)]\n : [systemMessage, instructionsMessage],\n ),\n metadata: {\n requestType: requestType,\n },\n forwardedParameters: {\n ...(forwardedParameters ?? {}),\n toolChoice: \"function\",\n toolChoiceFunctionName: action.name,\n },\n },\n properties: context.copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n\n const reader = response.getReader();\n\n let isInitial = true;\n\n let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (abortSignal?.aborted) {\n throw new Error(\"Aborted\");\n }\n\n actionExecutionMessage = convertGqlOutputToMessages(\n value.generateCopilotResponse.messages,\n ).find((msg) => msg.isActionExecutionMessage()) as ActionExecutionMessage | undefined;\n\n if (!actionExecutionMessage) {\n continue;\n }\n\n stream?.({\n status: isInitial ? \"initial\" : \"inProgress\",\n args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,\n });\n\n isInitial = false;\n }\n\n if (!actionExecutionMessage) {\n throw new Error(\"extract() failed: No function call occurred\");\n }\n\n stream?.({\n status: \"complete\",\n args: actionExecutionMessage.arguments as MappedParameterTypes<T>,\n });\n\n return actionExecutionMessage.arguments as MappedParameterTypes<T>;\n}\n\n// We need to put this in a user message since some LLMs need\n// at least one user message to function\nfunction makeInstructionsMessage(instructions: string): string {\n return `\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n\nAny additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.\n`;\n}\n\nfunction makeSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with a function called extract you MUST call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call the function without saying anything else.\n`;\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, SetStateAction } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n CopilotKitError,\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages, MessagesTapProvider } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { useCopilotRuntimeClient } from \"../../hooks/use-copilot-runtime-client\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetterArgs,\n} from \"../../types/interrupt-action\";\nimport { ConsoleTrigger } from \"../dev-console/console-trigger\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n\n // Use API key if provided, otherwise use the license key\n const publicApiKey = props.publicApiKey || props.publicLicenseKey;\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={publicApiKey} showUsageBanner={enabled}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n // Use license key as API key if provided, otherwise use the API key\n const publicApiKey = props.publicLicenseKey || props.publicApiKey;\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<string[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n // Compute all the functions and properties that we need to pass\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => {\n return {\n ...prevPoints,\n [id]: stateRender,\n };\n });\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const [internalErrorHandlers, _setInternalErrorHandler] = useState<\n Record<string, CopilotErrorHandler>\n >({});\n const setInternalErrorHandler = useCallback((handler: Record<string, CopilotErrorHandler>) => {\n _setInternalErrorHandler((prev: Record<string, CopilotErrorHandler>) => ({\n ...prev,\n ...handler,\n }));\n }, []);\n const removeInternalErrorHandler = useCallback((key: string) => {\n _setInternalErrorHandler((prev) => {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n });\n }, []);\n\n // Keep latest values in refs\n const onErrorRef = useRef<CopilotErrorHandler | undefined>(props.onError);\n useEffect(() => {\n onErrorRef.current = props.onError;\n }, [props.onError]);\n\n const internalHandlersRef = useRef<Record<string, CopilotErrorHandler>>({});\n useEffect(() => {\n internalHandlersRef.current = internalErrorHandlers;\n }, [internalErrorHandlers]);\n\n const handleErrors = useCallback(\n async (error: CopilotErrorEvent) => {\n if (copilotApiConfig.publicApiKey && onErrorRef.current) {\n try {\n await onErrorRef.current(error);\n } catch (e) {\n console.error(\"Error in public onError handler:\", e);\n }\n }\n const handlers = Object.values(internalHandlersRef.current);\n await Promise.all(\n handlers.map((h) =>\n Promise.resolve(h(error)).catch((e) =>\n console.error(\"Error in internal error handler:\", e),\n ),\n ),\n );\n },\n [copilotApiConfig.publicApiKey],\n );\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: shouldShowDevConsole(props.showDevConsole),\n onError: handleErrors,\n });\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n const hasLoadedAgents = useRef(false);\n\n useEffect(() => {\n if (hasLoadedAgents.current) return;\n\n const fetchData = async () => {\n const result = await runtimeClient.availableAgents();\n if (result.data?.availableAgents) {\n setAvailableAgents(result.data.availableAgents.agents);\n }\n hasLoadedAgents.current = true;\n };\n void fetchData();\n }, []);\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const [internalThreadId, setInternalThreadId] = useState<string>(props.threadId || randomUUID());\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\"Cannot call setThreadId() when threadId is provided via props.\");\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n // update the internal threadId if the props.threadId changes\n useEffect(() => {\n if (props.threadId !== undefined) {\n setInternalThreadId(props.threadId);\n }\n }, [props.threadId]);\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = shouldShowDevConsole(props.showDevConsole);\n\n const [langGraphInterruptAction, _setLangGraphInterruptAction] =\n useState<LangGraphInterruptAction | null>(null);\n const setLangGraphInterruptAction = useCallback((action: LangGraphInterruptActionSetterArgs) => {\n _setLangGraphInterruptAction((prev) => {\n if (prev == null) return action as LangGraphInterruptAction;\n if (action == null) return null;\n let event = prev.event;\n if (action.event) {\n // @ts-ignore\n event = { ...prev.event, ...action.event };\n }\n return { ...prev, ...action, event };\n });\n }, []);\n const removeLangGraphInterruptAction = useCallback((): void => {\n setLangGraphInterruptAction(null);\n }, []);\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = typeof newExtensions === \"function\" ? newExtensions(prev) : newExtensions;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved = typeof newAuthStates === \"function\" ? newAuthStates(prev) : newAuthStates;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n runtimeClient,\n forwardedParameters,\n agentLock,\n threadId: internalThreadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n removeLangGraphInterruptAction,\n bannerError,\n setBannerError,\n onError: handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n }}\n >\n <MessagesTapProvider>\n <CopilotMessages>\n {memoizedChildren}\n {showDevConsole && <ConsoleTrigger />}\n </CopilotMessages>\n </MessagesTapProvider>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ name, args }: { name: string; args: Record<string, any> }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n // Check if we have either a runtimeUrl or one of the API keys\n const hasApiKey = props.publicApiKey || props.publicLicenseKey;\n\n if (!props.runtimeUrl && !hasApiKey) {\n throw new ConfigurationError(\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\",\n );\n }\n\n if (cloudFeatures.length > 0 && !hasApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAMO;AACP,gCAQO;;;ACCP,mBAAkF;AAUlF,uBAA0B;AAC1B,oBAWO;AA4BC;AAkfD,IAAM,kCAAkC,CAAC,QAAQ;;;ADjiBxD,IAAAC,6BAGO;AAuCP,SAAsB,QAAqC,IAUH;AAAA,6CAVG;AAAA,IACzD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,6CAAmB;AAAA,IACjC;AAAA,EACF,GAAwD;AAvExD;AAwEE,UAAM,EAAE,SAAS,IAAI;AAErB,UAAM,SAAsB;AAAA,MAC1B,MAAM;AAAA,MACN,aAAa;AAAA,MACb;AAAA,MACA,SAAS,CAAC,SAAc;AAAA,MAAC;AAAA,IAC3B;AAEA,UAAM,mBAAkB,wCAAS,aAAT,YAAqB;AAC7C,UAAM,mBAAkB,wCAAS,aAAT,YAAqB;AAE7C,QAAI,gBAAgB;AAEpB,QAAI,MAAM;AACR,uBAAiB,OAAO,SAAS,WAAW,OAAO,KAAK,UAAU,IAAI,KAAK;AAAA,IAC7E;AAE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eAAe,SAAS,GAAG;AAEzD,YAAM,oBAAoB,eAAe;AAAA,QACvC,CAAC,YAAY,OAAO,SAClB,UAAU,KAAK,UAAU,CAAC,MAAM,EAAE,YAAY,WAAW,OAAO;AAAA,MACpE;AAEA,iCAA2B,iBAAiB;AAAA,IAC9C,WAAW,WAAW;AAEpB,YAAM,eAAe,YACjB,UAAU,UACV;AACJ,YAAM,IAAI,MAAM,YAAY;AAAA,IAC9B;AAAA,EACF,SAAS,OAAP;AAEA,UAAM;AAAA,EACR;AACF;","names":["import_shared","import_runtime_client_gql","import_shared","import_runtime_client_gql"]}
|
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
import {
|
|
2
2
|
reloadSuggestions
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
5
|
-
import "../chunk-
|
|
6
|
-
import "../chunk-
|
|
7
|
-
import "../chunk-
|
|
3
|
+
} from "../chunk-6WTWBXEJ.mjs";
|
|
4
|
+
import "../chunk-N4VN2B5S.mjs";
|
|
5
|
+
import "../chunk-2MGJO3FY.mjs";
|
|
6
|
+
import "../chunk-AALETENN.mjs";
|
|
7
|
+
import "../chunk-DSDAZA3B.mjs";
|
|
8
8
|
import "../chunk-PIF5KJYI.mjs";
|
|
9
9
|
import "../chunk-2IDV5OHF.mjs";
|
|
10
10
|
import "../chunk-PMAFHQ7P.mjs";
|
|
11
11
|
import "../chunk-5FHSUKQL.mjs";
|
|
12
12
|
import "../chunk-RKTVJRK7.mjs";
|
|
13
|
-
import "../chunk-
|
|
14
|
-
import "../chunk-
|
|
13
|
+
import "../chunk-Q3MCVRO3.mjs";
|
|
14
|
+
import "../chunk-ICIK2BSB.mjs";
|
|
15
15
|
import "../chunk-N4WEHORG.mjs";
|
|
16
16
|
import "../chunk-O7ARI5CV.mjs";
|
|
17
|
-
import "../chunk-FAUNHSQU.mjs";
|
|
18
|
-
import "../chunk-ICIK2BSB.mjs";
|
|
19
|
-
import "../chunk-TEMLWRRT.mjs";
|
|
20
17
|
import "../chunk-EFL5OBKN.mjs";
|
|
18
|
+
import "../chunk-6ZLPNY7X.mjs";
|
|
19
|
+
import "../chunk-YHT6CWIY.mjs";
|
|
20
|
+
import "../chunk-ZLQVRPDS.mjs";
|
|
21
21
|
import "../chunk-SKC7AJIV.mjs";
|
|
22
22
|
export {
|
|
23
23
|
reloadSuggestions
|
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"publishConfig": {
|
|
10
10
|
"access": "public"
|
|
11
11
|
},
|
|
12
|
-
"version": "1.10.4-next.
|
|
12
|
+
"version": "1.10.4-next.2",
|
|
13
13
|
"sideEffects": false,
|
|
14
14
|
"main": "./dist/index.js",
|
|
15
15
|
"module": "./dist/index.mjs",
|
|
@@ -47,8 +47,8 @@
|
|
|
47
47
|
"@scarf/scarf": "^1.3.0",
|
|
48
48
|
"react-markdown": "^8.0.7",
|
|
49
49
|
"untruncate-json": "^0.0.1",
|
|
50
|
-
"@copilotkit/runtime-client-gql": "1.10.4-next.
|
|
51
|
-
"@copilotkit/shared": "1.10.4-next.
|
|
50
|
+
"@copilotkit/runtime-client-gql": "1.10.4-next.2",
|
|
51
|
+
"@copilotkit/shared": "1.10.4-next.2"
|
|
52
52
|
},
|
|
53
53
|
"keywords": [
|
|
54
54
|
"copilotkit",
|
|
@@ -34,6 +34,8 @@ import {
|
|
|
34
34
|
ConfigurationError,
|
|
35
35
|
MissingPublicApiKeyError,
|
|
36
36
|
CopilotKitError,
|
|
37
|
+
CopilotErrorEvent,
|
|
38
|
+
CopilotErrorHandler,
|
|
37
39
|
} from "@copilotkit/shared";
|
|
38
40
|
import { FrontendAction } from "../../types/frontend-action";
|
|
39
41
|
import useFlatCategoryStore from "../../hooks/use-flat-category-store";
|
|
@@ -268,13 +270,61 @@ export function CopilotKitInternal(cpkProps: CopilotKitProps) {
|
|
|
268
270
|
};
|
|
269
271
|
}, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);
|
|
270
272
|
|
|
273
|
+
const [internalErrorHandlers, _setInternalErrorHandler] = useState<
|
|
274
|
+
Record<string, CopilotErrorHandler>
|
|
275
|
+
>({});
|
|
276
|
+
const setInternalErrorHandler = useCallback((handler: Record<string, CopilotErrorHandler>) => {
|
|
277
|
+
_setInternalErrorHandler((prev: Record<string, CopilotErrorHandler>) => ({
|
|
278
|
+
...prev,
|
|
279
|
+
...handler,
|
|
280
|
+
}));
|
|
281
|
+
}, []);
|
|
282
|
+
const removeInternalErrorHandler = useCallback((key: string) => {
|
|
283
|
+
_setInternalErrorHandler((prev) => {
|
|
284
|
+
const { [key]: _removed, ...rest } = prev;
|
|
285
|
+
return rest;
|
|
286
|
+
});
|
|
287
|
+
}, []);
|
|
288
|
+
|
|
289
|
+
// Keep latest values in refs
|
|
290
|
+
const onErrorRef = useRef<CopilotErrorHandler | undefined>(props.onError);
|
|
291
|
+
useEffect(() => {
|
|
292
|
+
onErrorRef.current = props.onError;
|
|
293
|
+
}, [props.onError]);
|
|
294
|
+
|
|
295
|
+
const internalHandlersRef = useRef<Record<string, CopilotErrorHandler>>({});
|
|
296
|
+
useEffect(() => {
|
|
297
|
+
internalHandlersRef.current = internalErrorHandlers;
|
|
298
|
+
}, [internalErrorHandlers]);
|
|
299
|
+
|
|
300
|
+
const handleErrors = useCallback(
|
|
301
|
+
async (error: CopilotErrorEvent) => {
|
|
302
|
+
if (copilotApiConfig.publicApiKey && onErrorRef.current) {
|
|
303
|
+
try {
|
|
304
|
+
await onErrorRef.current(error);
|
|
305
|
+
} catch (e) {
|
|
306
|
+
console.error("Error in public onError handler:", e);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
const handlers = Object.values(internalHandlersRef.current);
|
|
310
|
+
await Promise.all(
|
|
311
|
+
handlers.map((h) =>
|
|
312
|
+
Promise.resolve(h(error)).catch((e) =>
|
|
313
|
+
console.error("Error in internal error handler:", e),
|
|
314
|
+
),
|
|
315
|
+
),
|
|
316
|
+
);
|
|
317
|
+
},
|
|
318
|
+
[copilotApiConfig.publicApiKey],
|
|
319
|
+
);
|
|
320
|
+
|
|
271
321
|
const runtimeClient = useCopilotRuntimeClient({
|
|
272
322
|
url: copilotApiConfig.chatApiEndpoint,
|
|
273
323
|
publicApiKey: publicApiKey,
|
|
274
324
|
headers,
|
|
275
325
|
credentials: copilotApiConfig.credentials,
|
|
276
326
|
showDevConsole: shouldShowDevConsole(props.showDevConsole),
|
|
277
|
-
onError:
|
|
327
|
+
onError: handleErrors,
|
|
278
328
|
});
|
|
279
329
|
|
|
280
330
|
const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{
|
|
@@ -486,9 +536,12 @@ export function CopilotKitInternal(cpkProps: CopilotKitProps) {
|
|
|
486
536
|
langGraphInterruptAction,
|
|
487
537
|
setLangGraphInterruptAction,
|
|
488
538
|
removeLangGraphInterruptAction,
|
|
489
|
-
onError: props.onError,
|
|
490
539
|
bannerError,
|
|
491
540
|
setBannerError,
|
|
541
|
+
onError: handleErrors,
|
|
542
|
+
internalErrorHandlers,
|
|
543
|
+
setInternalErrorHandler,
|
|
544
|
+
removeInternalErrorHandler,
|
|
492
545
|
}}
|
|
493
546
|
>
|
|
494
547
|
<MessagesTapProvider>
|
|
@@ -228,11 +228,17 @@ export interface CopilotContextParams {
|
|
|
228
228
|
/**
|
|
229
229
|
* Optional trace handler for comprehensive debugging and observability.
|
|
230
230
|
*/
|
|
231
|
-
onError
|
|
231
|
+
onError: CopilotErrorHandler;
|
|
232
232
|
|
|
233
233
|
// banner error state
|
|
234
234
|
bannerError: CopilotKitError | null;
|
|
235
235
|
setBannerError: React.Dispatch<React.SetStateAction<CopilotKitError | null>>;
|
|
236
|
+
// Internal error handlers
|
|
237
|
+
// These are used to handle errors that occur during the execution of the chat.
|
|
238
|
+
// They are not intended for use by the developer. A component can register itself an error listener to be activated somewhere else as needed
|
|
239
|
+
internalErrorHandlers: Record<string, CopilotErrorHandler>;
|
|
240
|
+
setInternalErrorHandler: (handler: Record<string, CopilotErrorHandler>) => void;
|
|
241
|
+
removeInternalErrorHandler: (id: string) => void;
|
|
236
242
|
}
|
|
237
243
|
|
|
238
244
|
const emptyCopilotContext: CopilotContextParams = {
|
|
@@ -303,9 +309,12 @@ const emptyCopilotContext: CopilotContextParams = {
|
|
|
303
309
|
langGraphInterruptAction: null,
|
|
304
310
|
setLangGraphInterruptAction: () => null,
|
|
305
311
|
removeLangGraphInterruptAction: () => null,
|
|
306
|
-
onError:
|
|
312
|
+
onError: () => {},
|
|
307
313
|
bannerError: null,
|
|
308
314
|
setBannerError: () => {},
|
|
315
|
+
internalErrorHandlers: {},
|
|
316
|
+
setInternalErrorHandler: () => {},
|
|
317
|
+
removeInternalErrorHandler: () => {},
|
|
309
318
|
};
|
|
310
319
|
|
|
311
320
|
export const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);
|
package/src/hooks/use-chat.ts
CHANGED
|
@@ -235,9 +235,6 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
235
235
|
|
|
236
236
|
// Add tracing functionality to use-chat
|
|
237
237
|
const traceUIError = async (error: CopilotKitError, originalError?: any) => {
|
|
238
|
-
// Just check if onError and publicApiKey are defined
|
|
239
|
-
if (!onError || !copilotConfig?.publicApiKey) return;
|
|
240
|
-
|
|
241
238
|
try {
|
|
242
239
|
const traceEvent = {
|
|
243
240
|
type: "error" as const,
|
|
@@ -289,6 +286,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
289
286
|
headers,
|
|
290
287
|
credentials: copilotConfig.credentials,
|
|
291
288
|
showDevConsole,
|
|
289
|
+
onError,
|
|
292
290
|
});
|
|
293
291
|
|
|
294
292
|
const pendingAppendsRef = useRef<{ message: Message; followUp: boolean }[]>([]);
|
|
@@ -527,6 +525,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
527
525
|
statusReason: value.generateCopilotResponse.status.reason,
|
|
528
526
|
statusDetails: value.generateCopilotResponse.status.details,
|
|
529
527
|
});
|
|
528
|
+
// TODO: if onError & renderError should work without key, insert here
|
|
530
529
|
|
|
531
530
|
setMessages([...previousMessages, ...newMessages]);
|
|
532
531
|
break;
|
|
@@ -575,6 +574,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
575
574
|
originalErrorCode: originalCode,
|
|
576
575
|
preservedStructure: !!originalCode,
|
|
577
576
|
});
|
|
577
|
+
// TODO: if onError & renderError should work without key, insert here
|
|
578
578
|
|
|
579
579
|
// Stop processing and break from the loop
|
|
580
580
|
setIsLoading(false);
|
package/src/hooks/use-coagent.ts
CHANGED
|
@@ -210,7 +210,7 @@ export type HintFunction = (params: HintFunctionParams) => Message | undefined;
|
|
|
210
210
|
*/
|
|
211
211
|
export function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {
|
|
212
212
|
const context = useCopilotContext();
|
|
213
|
-
const { availableAgents } = context;
|
|
213
|
+
const { availableAgents, onError } = context;
|
|
214
214
|
const { setBannerError } = useToast();
|
|
215
215
|
const lastLoadedThreadId = useRef<string>();
|
|
216
216
|
const lastLoadedState = useRef<any>();
|
|
@@ -245,6 +245,7 @@ export function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentRe
|
|
|
245
245
|
headers,
|
|
246
246
|
credentials: copilotApiConfig.credentials,
|
|
247
247
|
showDevConsole: context.showDevConsole,
|
|
248
|
+
onError,
|
|
248
249
|
});
|
|
249
250
|
|
|
250
251
|
// if we manage state internally, we need to provide a function to set the state
|
|
@@ -19,7 +19,7 @@ import { shouldShowDevConsole } from "../utils/dev-console";
|
|
|
19
19
|
|
|
20
20
|
export interface CopilotRuntimeClientHookOptions extends CopilotRuntimeClientOptions {
|
|
21
21
|
showDevConsole?: boolean;
|
|
22
|
-
onError
|
|
22
|
+
onError: CopilotErrorHandler;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
export const useCopilotRuntimeClient = (options: CopilotRuntimeClientHookOptions) => {
|
|
@@ -31,9 +31,6 @@ export const useCopilotRuntimeClient = (options: CopilotRuntimeClientHookOptions
|
|
|
31
31
|
|
|
32
32
|
// Helper function to trace UI errors
|
|
33
33
|
const traceUIError = async (error: CopilotKitError, originalError?: any) => {
|
|
34
|
-
// Just check if onError and publicApiKey are defined
|
|
35
|
-
if (!onError || !runtimeOptions.publicApiKey) return;
|
|
36
|
-
|
|
37
34
|
try {
|
|
38
35
|
const errorEvent: CopilotErrorEvent = {
|
|
39
36
|
type: "error",
|
|
@@ -101,6 +98,7 @@ export const useCopilotRuntimeClient = (options: CopilotRuntimeClientHookOptions
|
|
|
101
98
|
setBannerError(ckError);
|
|
102
99
|
// Trace the error
|
|
103
100
|
traceUIError(ckError, gqlError);
|
|
101
|
+
// TODO: if onError & renderError should work without key, insert here
|
|
104
102
|
} else {
|
|
105
103
|
// Fallback for unstructured errors
|
|
106
104
|
const fallbackError = new CopilotKitError({
|
|
@@ -110,6 +108,7 @@ export const useCopilotRuntimeClient = (options: CopilotRuntimeClientHookOptions
|
|
|
110
108
|
setBannerError(fallbackError);
|
|
111
109
|
// Trace the fallback error
|
|
112
110
|
traceUIError(fallbackError, gqlError);
|
|
111
|
+
// TODO: if onError & renderError should work without key, insert here
|
|
113
112
|
}
|
|
114
113
|
};
|
|
115
114
|
|
|
@@ -128,6 +127,7 @@ export const useCopilotRuntimeClient = (options: CopilotRuntimeClientHookOptions
|
|
|
128
127
|
setBannerError(fallbackError);
|
|
129
128
|
// Trace the non-GraphQL error
|
|
130
129
|
traceUIError(fallbackError, error);
|
|
130
|
+
// TODO: if onError & renderError should work without key, insert here
|
|
131
131
|
}
|
|
132
132
|
}
|
|
133
133
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-coagent.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { CopilotContextParams, useCopilotContext } from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { useCopilotChat } from \"./use-copilot-chat_internal\";\nimport { Message } from \"@copilotkit/shared\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { parseJson, CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\nimport { useMessagesTap } from \"../components/copilot-provider/copilot-messages\";\nimport { Message as GqlMessage } from \"@copilotkit/runtime-client-gql\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<T> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (hint?: HintFunction) => Promise<void>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n const context = useCopilotContext();\n const { availableAgents } = context;\n const { setBannerError } = useToast();\n const lastLoadedThreadId = useRef<string>();\n const lastLoadedState = useRef<any>();\n\n const { name } = options;\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === name)) {\n const message = `(useCoAgent): Agent \"${name}\" not found. Make sure the agent exists and is properly configured.`;\n console.warn(message);\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: name,\n availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const { getMessagesFromTap } = useMessagesTap();\n\n const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } =\n context;\n const { sendMessage, runChatCompletion } = useCopilotChat();\n const headers = {\n ...(copilotApiConfig.headers || {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: context.showDevConsole,\n });\n\n // if we manage state internally, we need to provide a function to set the state\n const setState = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n // coagentStatesRef.current || {}\n let coagentState: CoagentState = getCoagentState({ coagentStates, name, options });\n const updatedState =\n typeof newState === \"function\" ? (newState as Function)(coagentState.state) : newState;\n\n setCoagentStatesWithRef({\n ...coagentStatesRef.current,\n [name]: {\n ...coagentState,\n state: updatedState,\n },\n });\n },\n [coagentStates, name],\n );\n\n useEffect(() => {\n const fetchAgentState = async () => {\n if (!threadId || threadId === lastLoadedThreadId.current) return;\n\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: name,\n });\n\n // Runtime client handles errors automatically via handleGQLErrors\n if (result.error) {\n return; // Don't process data on error\n }\n\n const newState = result.data?.loadAgentState?.state;\n if (newState === lastLoadedState.current) return;\n\n if (result.data?.loadAgentState?.threadExists && newState && newState != \"{}\") {\n lastLoadedState.current = newState;\n lastLoadedThreadId.current = threadId;\n const fetchedState = parseJson(newState, {});\n isExternalStateManagement(options)\n ? options.setState(fetchedState)\n : setState(fetchedState);\n }\n };\n void fetchAgentState();\n }, [threadId]);\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n setState(options.state);\n } else if (coagentStates[name] === undefined) {\n setState(options.initialState === undefined ? {} : options.initialState);\n }\n }, [\n isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined,\n // reset initialstate on reset\n coagentStates[name] === undefined,\n ]);\n\n // Sync config when runtime configuration changes\n useEffect(() => {\n const newConfig = options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : undefined;\n\n if (newConfig === undefined) return;\n\n setCoagentStatesWithRef((prev) => {\n const existing = prev[name] ?? {\n name,\n state: isInternalStateManagementWithInitial(options) ? options.initialState : {},\n config: {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n\n if (JSON.stringify(existing.config) === JSON.stringify(newConfig)) {\n return prev;\n }\n\n return {\n ...prev,\n [name]: {\n ...existing,\n config: newConfig,\n },\n };\n });\n }, [JSON.stringify(options.config), JSON.stringify(options.configurable)]);\n\n const runAgentCallback = useAsyncCallback(\n async (hint?: HintFunction) => {\n await runAgent(name, context, getMessagesFromTap(), sendMessage, runChatCompletion, hint);\n },\n [name, context, sendMessage, runChatCompletion],\n );\n\n // Return the state and setState function\n return useMemo(() => {\n const coagentState = getCoagentState({ coagentStates, name, options });\n return {\n name,\n nodeName: coagentState.nodeName,\n threadId: coagentState.threadId,\n running: coagentState.running,\n state: coagentState.state,\n setState: isExternalStateManagement(options) ? options.setState : setState,\n start: () => startAgent(name, context),\n stop: () => stopAgent(name, context),\n run: runAgentCallback,\n };\n }, [name, coagentStates, options, setState, runAgentCallback]);\n}\n\nexport function startAgent(name: string, context: CopilotContextParams) {\n const { setAgentSession } = context;\n setAgentSession({\n agentName: name,\n });\n}\n\nexport function stopAgent(name: string, context: CopilotContextParams) {\n const { agentSession, setAgentSession } = context;\n if (agentSession && agentSession.agentName === name) {\n setAgentSession(null);\n context.setCoagentStates((prevAgentStates) => {\n return {\n ...prevAgentStates,\n [name]: {\n ...prevAgentStates[name],\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n },\n };\n });\n } else {\n console.warn(`No agent session found for ${name}`);\n }\n}\n\nexport async function runAgent(\n name: string,\n context: CopilotContextParams,\n messages: GqlMessage[],\n sendMessage: (message: Message) => Promise<void>,\n runChatCompletion: () => Promise<Message[]>,\n hint?: HintFunction,\n) {\n const { agentSession, setAgentSession } = context;\n if (!agentSession || agentSession.agentName !== name) {\n setAgentSession({\n agentName: name,\n });\n }\n\n let previousState: any = null;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message.isAgentStateMessage() && message.agentName === name) {\n previousState = message.state;\n }\n }\n\n let state = context.coagentStatesRef.current?.[name]?.state || {};\n\n if (hint) {\n const hintMessage = hint({ previousState, currentState: state });\n if (hintMessage) {\n await sendMessage(hintMessage);\n } else {\n await runChatCompletion();\n }\n } else {\n await runChatCompletion();\n }\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n\nconst isInternalStateManagementWithInitial = <T>(\n options: UseCoagentOptions<T>,\n): options is WithInternalStateManagementAndInitial<T> => {\n return \"initialState\" in options;\n};\n\nconst getCoagentState = <T>({\n coagentStates,\n name,\n options,\n}: {\n coagentStates: Record<string, CoagentState>;\n name: string;\n options: UseCoagentOptions<T>;\n}) => {\n if (coagentStates[name]) {\n return coagentStates[name];\n } else {\n return {\n name,\n state: isInternalStateManagementWithInitial<T>(options) ? options.initialState : {},\n config: options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,SAAS,aAAa,WAAW,SAAS,cAAc;AAQxD,SAAS,WAAW,qCAAqC;AAgHlD,SAAS,WAAoB,SAAwD;AAC1F,QAAM,UAAU,kBAAkB;AAClC,QAAM,EAAE,gBAAgB,IAAI;AAC5B,QAAM,EAAE,eAAe,IAAI,SAAS;AACpC,QAAM,qBAAqB,OAAe;AAC1C,QAAM,kBAAkB,OAAY;AAEpC,QAAM,EAAE,KAAK,IAAI;AACjB,YAAU,MAAM;AACd,SAAI,mDAAiB,WAAU,CAAC,gBAAgB,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI,GAAG;AAC5E,YAAM,UAAU,wBAAwB;AACxC,cAAQ,KAAK,OAAO;AAGpB,YAAM,aAAa,IAAI,8BAA8B;AAAA,QACnD,WAAW;AAAA,QACX,iBAAiB,gBAAgB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,EAAE,GAAG,EAAE;AAAA,MAC1E,CA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3,"sources":["../src/hooks/use-copilot-runtime-client.ts"],"sourcesContent":["import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo, useRef } from \"react\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n CopilotErrorHandler,\n CopilotErrorEvent,\n} from \"@copilotkit/shared\";\nimport { shouldShowDevConsole } from \"../utils/dev-console\";\n\nexport interface CopilotRuntimeClientHookOptions extends CopilotRuntimeClientOptions {\n showDevConsole?: boolean;\n onError?: CopilotErrorHandler;\n}\n\nexport const useCopilotRuntimeClient = (options: CopilotRuntimeClientHookOptions) => {\n const { setBannerError } = useToast();\n const { showDevConsole, onError, ...runtimeOptions } = options;\n\n // Deduplication state for structured errors\n const lastStructuredErrorRef = useRef<{ message: string; timestamp: number } | null>(null);\n\n // Helper function to trace UI errors\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\n // Just check if onError and publicApiKey are defined\n if (!onError || !runtimeOptions.publicApiKey) return;\n\n try {\n const errorEvent: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"ui\",\n request: {\n operation: \"runtimeClient\",\n url: runtimeOptions.url,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onError(errorEvent);\n } catch (error) {\n console.error(\"Error in onError handler:\", error);\n }\n };\n\n const runtimeClient = useMemo(() => {\n return new CopilotRuntimeClient({\n ...runtimeOptions,\n handleGQLErrors: (error) => {\n if ((error as any).graphQLErrors?.length) {\n const graphQLErrors = (error as any).graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole ?? false);\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", gqlError.message);\n return;\n }\n\n // All errors (including DEV_ONLY) show as banners for consistency\n // Deduplicate to prevent spam\n const now = Date.now();\n const errorMessage = gqlError.message;\n if (\n lastStructuredErrorRef.current &&\n lastStructuredErrorRef.current.message === errorMessage &&\n now - lastStructuredErrorRef.current.timestamp < 150\n ) {\n return; // Skip duplicate\n }\n lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };\n\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the error\n traceUIError(ckError, gqlError);\n } else {\n // Fallback for unstructured errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole ?? false);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n }\n }\n },\n handleGQLWarning: (message: string) => {\n console.warn(message);\n // Show warnings as banners too for consistency\n const warningError = new CopilotKitError({\n message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(warningError);\n },\n });\n }, [runtimeOptions, setBannerError, showDevConsole, onError]);\n\n return runtimeClient;\n};\n\n// Create appropriate structured error from GraphQL error\nfunction createStructuredError(gqlError: GraphQLError): CopilotKitError | null {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n // Legacy error detection by stack trace\n if (originalError?.stack?.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,OAGK;AAEP,SAAS,SAAS,cAAc;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAQA,IAAM,0BAA0B,CAAC,YAA6C;AACnF,QAAM,EAAE,eAAe,IAAI,SAAS;AACpC,QAAuD,cAA/C,kBAAgB,QA1B1B,IA0ByD,IAAnB,2BAAmB,IAAnB,CAA5B,kBAAgB;AAGxB,QAAM,yBAAyB,OAAsD,IAAI;AAGzF,QAAM,eAAe,CAAO,OAAwB,kBAAwB;AAE1E,QAAI,CAAC,WAAW,CAAC,eAAe;AAAc;AAE9C,QAAI;AACF,YAAM,aAAgC;AAAA,QACpC,MAAM;AAAA,QACN,WAAW,KAAK,IAAI;AAAA,QACpB,SAAS;AAAA,UACP,QAAQ;AAAA,UACR,SAAS;AAAA,YACP,WAAW;AAAA,YACX,KAAK,eAAe;AAAA,YACpB,WAAW,KAAK,IAAI;AAAA,UACtB;AAAA,UACA,WAAW;AAAA,YACT,aAAa;AAAA,YACb,WAAW,OAAO,cAAc,cAAc,UAAU,YAAY;AAAA,YACpE,YAAY,yBAAyB,QAAQ,cAAc,QAAQ;AAAA,UACrE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