@copilotkit/react-core 1.10.5-next.0 → 1.10.5-next.10
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 +74 -0
- package/dist/{chunk-6INCKUL6.mjs → chunk-3N4MVKFZ.mjs} +32 -18
- package/dist/chunk-3N4MVKFZ.mjs.map +1 -0
- package/dist/{chunk-CLQLVMW4.mjs → chunk-3WUDRJTT.mjs} +2 -2
- package/dist/{chunk-AGP7SAEE.mjs → chunk-7LTRT3IV.mjs} +4 -4
- package/dist/{chunk-CXDK6XA5.mjs → chunk-BBUQMG45.mjs} +2 -2
- package/dist/{chunk-G2GQX4FI.mjs → chunk-CUWOXXM5.mjs} +3 -3
- package/dist/{chunk-YHT6CWIY.mjs → chunk-EUX2P2E7.mjs} +5 -3
- package/dist/{chunk-YHT6CWIY.mjs.map → chunk-EUX2P2E7.mjs.map} +1 -1
- package/dist/{chunk-4JBVPOHK.mjs → chunk-GIGUZ2OK.mjs} +3 -3
- package/dist/{chunk-36FJAVOF.mjs → chunk-HDOG2RTM.mjs} +2 -2
- package/dist/{chunk-AR7HJPGU.mjs → chunk-HI6SPUOX.mjs} +2 -2
- package/dist/{chunk-FCRODLLL.mjs → chunk-HYJUBYMU.mjs} +5 -5
- package/dist/{chunk-7D4OASUM.mjs → chunk-IHV5PTID.mjs} +2 -2
- package/dist/{chunk-7LZXD5RJ.mjs → chunk-ITDKIB5E.mjs} +30 -23
- package/dist/chunk-ITDKIB5E.mjs.map +1 -0
- package/dist/{chunk-KA3NCZEJ.mjs → chunk-JBACWIFW.mjs} +2 -2
- package/dist/{chunk-HHLBUGRA.mjs → chunk-JCHRWCYH.mjs} +3 -3
- package/dist/{chunk-NALRM7KT.mjs → chunk-L5MS4UDD.mjs} +11 -5
- package/dist/chunk-L5MS4UDD.mjs.map +1 -0
- package/dist/{chunk-MY2BUA6F.mjs → chunk-M37URBJS.mjs} +2 -2
- package/dist/{chunk-MZ37BAAE.mjs → chunk-MGWRDFBE.mjs} +2 -2
- package/dist/{chunk-23SOG4FI.mjs → chunk-TUTNHDM3.mjs} +2 -2
- package/dist/{chunk-QF3Q5LUN.mjs → chunk-ZVOLWJCY.mjs} +5 -5
- package/dist/chunk-ZVOLWJCY.mjs.map +1 -0
- package/dist/components/copilot-provider/copilot-messages.js +4 -2
- package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
- package/dist/components/copilot-provider/copilot-messages.mjs +2 -2
- 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 +30 -21
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +5 -5
- package/dist/components/copilot-provider/index.d.ts +1 -1
- package/dist/components/copilot-provider/index.js +30 -21
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +5 -5
- package/dist/components/dev-console/console-trigger.js +4 -2
- 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 +4 -2
- 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/index.d.ts +1 -1
- package/dist/components/index.js +30 -21
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +5 -5
- package/dist/context/copilot-context.d.ts +1 -1
- package/dist/context/copilot-context.js +4 -2
- 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 +4 -2
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +1 -1
- package/dist/{copilot-context-59740e82.d.ts → copilot-context-cf9de848.d.ts} +2 -2
- package/dist/hooks/index.d.ts +2 -2
- package/dist/hooks/index.js +44 -22
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +18 -18
- package/dist/hooks/use-chat.d.ts +1 -1
- package/dist/hooks/use-chat.js +33 -17
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +2 -2
- package/dist/hooks/use-coagent-state-render.js +4 -2
- 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 +36 -20
- package/dist/hooks/use-coagent.js.map +1 -1
- package/dist/hooks/use-coagent.mjs +9 -9
- package/dist/hooks/use-copilot-action.js +4 -2
- 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 +4 -2
- 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 +4 -2
- 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 +36 -20
- package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
- package/dist/hooks/use-copilot-chat-headless_c.mjs +9 -9
- package/dist/hooks/use-copilot-chat.d.ts +2 -2
- package/dist/hooks/use-copilot-chat.js +36 -20
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +9 -9
- package/dist/hooks/use-copilot-chat_internal.d.ts +2 -2
- package/dist/hooks/use-copilot-chat_internal.js +36 -20
- package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
- package/dist/hooks/use-copilot-chat_internal.mjs +8 -8
- package/dist/hooks/use-copilot-readable.js +4 -2
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-langgraph-interrupt-render.js +7 -5
- 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 +44 -22
- package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
- package/dist/hooks/use-langgraph-interrupt.mjs +9 -9
- package/dist/hooks/use-make-copilot-document-readable.js +4 -2
- 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-d1743abe.d.ts → index-1f5b66ac.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +70 -41
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +19 -19
- package/dist/lib/copilot-task.d.ts +1 -1
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +6 -6
- package/dist/lib/index.d.ts +1 -1
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +6 -6
- package/dist/types/interrupt-action.d.ts +1 -1
- package/dist/types/interrupt-action.js.map +1 -1
- package/dist/utils/extract.d.ts +2 -2
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +5 -5
- package/dist/utils/index.d.ts +2 -2
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +5 -5
- package/dist/utils/suggestions.d.ts +2 -2
- package/dist/utils/suggestions.js.map +1 -1
- package/dist/utils/suggestions.mjs +5 -5
- package/package.json +3 -3
- package/src/components/copilot-provider/copilotkit.tsx +27 -17
- package/src/context/copilot-context.tsx +3 -3
- package/src/hooks/use-chat.ts +27 -11
- package/src/hooks/use-langgraph-interrupt-render.ts +4 -3
- package/src/hooks/use-langgraph-interrupt.ts +8 -3
- package/src/types/interrupt-action.ts +4 -1
- package/dist/chunk-6INCKUL6.mjs.map +0 -1
- package/dist/chunk-7LZXD5RJ.mjs.map +0 -1
- package/dist/chunk-NALRM7KT.mjs.map +0 -1
- package/dist/chunk-QF3Q5LUN.mjs.map +0 -1
- /package/dist/{chunk-CLQLVMW4.mjs.map → chunk-3WUDRJTT.mjs.map} +0 -0
- /package/dist/{chunk-AGP7SAEE.mjs.map → chunk-7LTRT3IV.mjs.map} +0 -0
- /package/dist/{chunk-CXDK6XA5.mjs.map → chunk-BBUQMG45.mjs.map} +0 -0
- /package/dist/{chunk-G2GQX4FI.mjs.map → chunk-CUWOXXM5.mjs.map} +0 -0
- /package/dist/{chunk-4JBVPOHK.mjs.map → chunk-GIGUZ2OK.mjs.map} +0 -0
- /package/dist/{chunk-36FJAVOF.mjs.map → chunk-HDOG2RTM.mjs.map} +0 -0
- /package/dist/{chunk-AR7HJPGU.mjs.map → chunk-HI6SPUOX.mjs.map} +0 -0
- /package/dist/{chunk-FCRODLLL.mjs.map → chunk-HYJUBYMU.mjs.map} +0 -0
- /package/dist/{chunk-7D4OASUM.mjs.map → chunk-IHV5PTID.mjs.map} +0 -0
- /package/dist/{chunk-KA3NCZEJ.mjs.map → chunk-JBACWIFW.mjs.map} +0 -0
- /package/dist/{chunk-HHLBUGRA.mjs.map → chunk-JCHRWCYH.mjs.map} +0 -0
- /package/dist/{chunk-MY2BUA6F.mjs.map → chunk-M37URBJS.mjs.map} +0 -0
- /package/dist/{chunk-MZ37BAAE.mjs.map → chunk-MGWRDFBE.mjs.map} +0 -0
- /package/dist/{chunk-23SOG4FI.mjs.map → chunk-TUTNHDM3.mjs.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/use-copilot-authenticated-action.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-copilot-action.ts","../../src/components/error-boundary/error-utils.tsx","../../src/components/toast/toast-provider.tsx","../../src/components/toast/exclamation-mark-icon.tsx"],"sourcesContent":["import { Parameter } from \"@copilotkit/shared\";\nimport { Fragment, useCallback, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { FrontendAction, ActionRenderProps } from \"../types/frontend-action\";\nimport { useCopilotAction } from \"./use-copilot-action\";\nimport React from \"react\";\n\n/**\n * Hook to create an authenticated action that requires user sign-in before execution.\n *\n * @remarks\n * This feature is only available when using CopilotKit's hosted cloud service.\n * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.\n *\n * @param action - The frontend action to be wrapped with authentication\n * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed\n */\nexport function useCopilotAuthenticatedAction_c<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();\n const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);\n\n const executeAction = useCallback(\n (props: ActionRenderProps<Parameter[]>) => {\n if (typeof action.render === \"function\") {\n return action.render(props);\n }\n return action.render || React.createElement(Fragment);\n },\n [action],\n );\n\n const wrappedRender = useCallback(\n (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {\n const isAuthenticated = Object.values(authStates_c || {}).some(\n (state) => state.status === \"authenticated\",\n );\n\n if (!isAuthenticated) {\n // Store action details for later execution\n pendingActionRef.current = props;\n\n return authConfig_c?.SignInComponent\n ? React.createElement(authConfig_c.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates_c?.((prev) => ({ ...prev, [action.name]: authState }));\n if (pendingActionRef.current) {\n executeAction(pendingActionRef.current);\n pendingActionRef.current = null;\n }\n },\n })\n : React.createElement(Fragment);\n }\n\n return executeAction(props);\n },\n [action, authStates_c, setAuthStates_c],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\n}\n","import {\n CopilotCloudConfig,\n FunctionCallHandler,\n CopilotErrorHandler,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\nimport { SuggestionItem } from \"../utils/suggestions\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Optional configuration for connecting to Model Context Protocol (MCP) servers.\n * This is typically derived from the CopilotKitProps and used internally.\n * @experimental\n */\n mcpServers?: Array<{ endpoint: string; apiKey?: string }>;\n}\n\nexport type InChatRenderFunction<TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>> =\n (props: TProps) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\nexport type ContextTree = Tree;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // coagent actions\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n additionalInstructions?: string[];\n setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean;\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n // runtime\n runtimeClient: CopilotRuntimeClient;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Partial<Pick<ForwardedParametersInput, \"temperature\">>;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n langGraphInterruptAction: LangGraphInterruptAction | null;\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n removeLangGraphInterruptAction: () => void;\n\n /**\n * Optional trace handler for comprehensive debugging and observability.\n */\n onError: CopilotErrorHandler;\n\n // banner error state\n bannerError: CopilotKitError | null;\n setBannerError: React.Dispatch<React.SetStateAction<CopilotKitError | null>>;\n // Internal error handlers\n // These are used to handle errors that occur during the execution of the chat.\n // They are not intended for use by the developer. A component can register itself an error listener to be activated somewhere else as needed\n internalErrorHandlers: Record<string, CopilotErrorHandler>;\n setInternalErrorHandler: (handler: Record<string, CopilotErrorHandler>) => void;\n removeInternalErrorHandler: (id: string) => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coAgentStateRenders: {},\n setCoAgentStateRender: () => {},\n removeCoAgentStateRender: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n getAllContext: () => [],\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n additionalInstructions: [],\n setAdditionalInstructions: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n runtimeClient: {} as any,\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: false,\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n langGraphInterruptAction: null,\n setLangGraphInterruptAction: () => null,\n removeLangGraphInterruptAction: () => null,\n onError: () => {},\n bannerError: null,\n setBannerError: () => {},\n internalErrorHandlers: {},\n setInternalErrorHandler: () => {},\n removeInternalErrorHandler: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n","/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { Parameter, randomId } from \"@copilotkit/shared\";\nimport { createElement, Fragment, useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport {\n ActionRenderProps,\n ActionRenderPropsNoArgsWait,\n ActionRenderPropsWait,\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n const renderAndWaitRef = useRef<RenderAndWaitForResponse | null>(null);\n const activatingMessageIdRef = useRef<string | null>(null);\n const { addToast } = useToast();\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // const { currentlyActivatingHitlActionMessageIdRef } = useCopilotContext() as any; // <-- REMOVE THIS FOR NOW\n\n // If the developer provides a renderAndWaitForResponse function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (\n // renderAndWaitForResponse is not available for catch all actions\n isFrontendAction(action) &&\n // check if renderAndWaitForResponse is set\n (action.renderAndWait || action.renderAndWaitForResponse)\n ) {\n (action as any)._isRenderAndWait = true; // Internal flag to identify this action type later\n const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n action.renderAndWaitForResponse = undefined;\n\n // Add a method for use-chat.ts to set the activating message ID.\n // This helps correlate the action instance with the message being processed by use-chat.\n (action as any)._setActivatingMessageId = (id: string | null) => {\n activatingMessageIdRef.current = id;\n };\n\n // add a handler that will be called when the action is executed\n action.handler = useAsyncCallback(async () => {\n const currentActivatingId = activatingMessageIdRef.current;\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = {\n promise,\n resolve: resolve!,\n reject: reject!,\n messageId: currentActivatingId,\n };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n const result = await promise;\n return result;\n }, []) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<T> & { messageId?: string }): React.ReactElement => {\n const currentRenderMessageId = props.messageId;\n // For renderAndWaitForResponse, the 'executing' state might be set by use-chat before\n // this specific action instance's handler (and thus its promise) is ready.\n // This logic adjusts the status to 'inProgress' if the current render\n // isn't for the actively processing HITL action, preventing premature interaction.\n let status = props.status;\n if (props.status === \"executing\") {\n if (!renderAndWaitRef.current || !renderAndWaitRef.current.promise) {\n status = \"inProgress\";\n } else if (\n renderAndWaitRef.current.messageId !== currentRenderMessageId &&\n activatingMessageIdRef.current !== currentRenderMessageId\n ) {\n status = \"inProgress\";\n }\n // If conditions met, status remains 'executing'\n }\n // Create type safe waitProps based on whether T extends empty array or not\n const waitProps = {\n status,\n args: props.args,\n result: props.result,\n // handler and respond should only be provided if this is the truly active instance\n // and its promise infrastructure is ready.\n handler:\n status === \"executing\" &&\n renderAndWaitRef.current &&\n renderAndWaitRef.current.messageId === currentRenderMessageId\n ? renderAndWaitRef.current!.resolve\n : undefined,\n respond:\n status === \"executing\" &&\n renderAndWaitRef.current &&\n renderAndWaitRef.current.messageId === currentRenderMessageId\n ? renderAndWaitRef.current!.resolve\n : undefined,\n } as T extends [] ? ActionRenderPropsNoArgsWait<T> : ActionRenderPropsWait<T>;\n\n // Type guard to check if renderAndWait is for no args case\n const isNoArgsRenderWait = (\n _fn:\n | ((props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement)\n | ((props: ActionRenderPropsWait<T>) => React.ReactElement),\n ): _fn is (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement => {\n return action.parameters?.length === 0;\n };\n\n // Safely call renderAndWait with correct props type\n if (renderAndWait) {\n if (isNoArgsRenderWait(renderAndWait)) {\n return renderAndWait(waitProps as ActionRenderPropsNoArgsWait<T>);\n } else {\n return renderAndWait(waitProps as ActionRenderPropsWait<T>);\n }\n }\n\n // Return empty Fragment instead of null\n return createElement(Fragment);\n }) as any;\n }\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n // catch all actions don't have a handler\n if (isFrontendAction(action)) {\n actions[idRef.current].handler = action.handler as any;\n }\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n // TODO: using as any here because the type definitions are getting to tricky\n // not wasting time on this now - we know the types are compatible\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n }\n }\n }\n\n useEffect(() => {\n const hasDuplicate = Object.values(actions).some(\n (otherAction) => otherAction.name === action.name && otherAction !== actions[idRef.current],\n );\n\n if (hasDuplicate) {\n addToast({\n type: \"warning\",\n message: `Found an already registered action with name ${action.name}.`,\n id: `dup-action-${action.name}`,\n });\n }\n }, [actions]);\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n // see comment about type safety above\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n // UPDATE: We now have access, we should remove the entry if not referenced by any message.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n isFrontendAction(action) ? action.description : undefined,\n action.name,\n isFrontendAction(action) ? action.disabled : undefined,\n isFrontendAction(action) ? action.available : undefined,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(isFrontendAction(action) ? action.parameters : []),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\nfunction isFrontendAction<T extends Parameter[]>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n): action is FrontendAction<T> {\n return action.name !== \"*\";\n}\n\ninterface RenderAndWaitForResponse {\n promise: Promise<any>;\n resolve: (result: any) => void;\n reject: (error: any) => void;\n messageId: string | null;\n}\n","import React, { useCallback } from \"react\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { ExclamationMarkIcon } from \"../toast/exclamation-mark-icon\";\nimport ReactMarkdown from \"react-markdown\";\n\ninterface OriginalError {\n message?: string;\n stack?: string;\n}\n\nexport function ErrorToast({ errors }: { errors: (Error | GraphQLError)[] }) {\n const errorsToRender = errors.map((error, idx) => {\n const originalError =\n \"extensions\" in error ? (error.extensions?.originalError as undefined | OriginalError) : {};\n const message = originalError?.message ?? error.message;\n const code = \"extensions\" in error ? (error.extensions?.code as string) : null;\n\n return (\n <div\n key={idx}\n style={{\n marginTop: idx === 0 ? 0 : 10,\n marginBottom: 14,\n }}\n >\n <ExclamationMarkIcon style={{ marginBottom: 4 }} />\n\n {code && (\n <div\n style={{\n fontWeight: \"600\",\n marginBottom: 4,\n }}\n >\n Copilot Runtime Error:{\" \"}\n <span style={{ fontFamily: \"monospace\", fontWeight: \"normal\" }}>{code}</span>\n </div>\n )}\n <ReactMarkdown>{message}</ReactMarkdown>\n </div>\n );\n });\n return (\n <div\n style={{\n fontSize: \"13px\",\n maxWidth: \"600px\",\n }}\n >\n {errorsToRender}\n <div style={{ fontSize: \"11px\", opacity: 0.75 }}>\n NOTE: This error only displays during local development.\n </div>\n </div>\n );\n}\n\nexport function useErrorToast() {\n const { addToast } = useToast();\n\n return useCallback(\n (error: (Error | GraphQLError)[]) => {\n const errorId = error\n .map((err) => {\n const message =\n \"extensions\" in err\n ? (err.extensions?.originalError as any)?.message || err.message\n : err.message;\n const stack = err.stack || \"\";\n return btoa(message + stack).slice(0, 32); // Create hash from message + stack\n })\n .join(\"|\");\n\n addToast({\n type: \"error\",\n id: errorId, // Toast libraries typically dedupe by id\n message: <ErrorToast errors={error} />,\n });\n },\n [addToast],\n );\n}\n\nexport function useAsyncCallback<T extends (...args: any[]) => Promise<any>>(\n callback: T,\n deps: Parameters<typeof useCallback>[1],\n) {\n const addErrorToast = useErrorToast();\n return useCallback(async (...args: Parameters<T>) => {\n try {\n return await callback(...args);\n } catch (error) {\n console.error(\"Error in async callback:\", error);\n // @ts-ignore\n addErrorToast([error]);\n throw error;\n }\n }, deps);\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { PartialBy, CopilotKitError, Severity } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(null);\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(/'message':\\s*'([^']+)'/);\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n","import React from \"react\";\n\nexport const ExclamationMarkIcon = ({\n className,\n style,\n}: {\n className?: string;\n style?: React.CSSProperties;\n}) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={`lucide lucide-circle-alert ${className ? className : \"\"}`}\n style={style}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"12\" x2=\"12\" y1=\"8\" y2=\"12\" />\n <line x1=\"12\" x2=\"12.01\" y1=\"16\" y2=\"16\" />\n </svg>\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,IAAAA,gBAA8C;;;ACU9C,mBAAkB;AAwOlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,CAAC;AAAA,EACtB,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,0BAA0B,MAAM;AAAA,EAAC;AAAA,EAEjC,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,EAAE;AAA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;AAAA,EACxC;AAEA;AAAA,IACE,iCACK,SADL;AAAA,MAEE,QAAQ;AAAA,IACV;AAAA,IACA;AAAA,EACF;AACF;","names":["import_react","React","import_shared","import_react","import_react","import_react","import_jsx_runtime","import_jsx_runtime","ReactMarkdown","import_react","React"]}
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/use-copilot-authenticated-action.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-copilot-action.ts","../../src/components/error-boundary/error-utils.tsx","../../src/components/toast/toast-provider.tsx","../../src/components/toast/exclamation-mark-icon.tsx"],"sourcesContent":["import { Parameter } from \"@copilotkit/shared\";\nimport { Fragment, useCallback, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { FrontendAction, ActionRenderProps } from \"../types/frontend-action\";\nimport { useCopilotAction } from \"./use-copilot-action\";\nimport React from \"react\";\n\n/**\n * Hook to create an authenticated action that requires user sign-in before execution.\n *\n * @remarks\n * This feature is only available when using CopilotKit's hosted cloud service.\n * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.\n *\n * @param action - The frontend action to be wrapped with authentication\n * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed\n */\nexport function useCopilotAuthenticatedAction_c<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();\n const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);\n\n const executeAction = useCallback(\n (props: ActionRenderProps<Parameter[]>) => {\n if (typeof action.render === \"function\") {\n return action.render(props);\n }\n return action.render || React.createElement(Fragment);\n },\n [action],\n );\n\n const wrappedRender = useCallback(\n (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {\n const isAuthenticated = Object.values(authStates_c || {}).some(\n (state) => state.status === \"authenticated\",\n );\n\n if (!isAuthenticated) {\n // Store action details for later execution\n pendingActionRef.current = props;\n\n return authConfig_c?.SignInComponent\n ? React.createElement(authConfig_c.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates_c?.((prev) => ({ ...prev, [action.name]: authState }));\n if (pendingActionRef.current) {\n executeAction(pendingActionRef.current);\n pendingActionRef.current = null;\n }\n },\n })\n : React.createElement(Fragment);\n }\n\n return executeAction(props);\n },\n [action, authStates_c, setAuthStates_c],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\n}\n","import {\n CopilotCloudConfig,\n FunctionCallHandler,\n CopilotErrorHandler,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\nimport { SuggestionItem } from \"../utils/suggestions\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Optional configuration for connecting to Model Context Protocol (MCP) servers.\n * This is typically derived from the CopilotKitProps and used internally.\n * @experimental\n */\n mcpServers?: Array<{ endpoint: string; apiKey?: string }>;\n}\n\nexport type InChatRenderFunction<TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>> =\n (props: TProps) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\nexport type ContextTree = Tree;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // coagent actions\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n additionalInstructions?: string[];\n setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean;\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n // runtime\n runtimeClient: CopilotRuntimeClient;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Partial<Pick<ForwardedParametersInput, \"temperature\">>;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n langGraphInterruptAction: LangGraphInterruptAction | null;\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n removeLangGraphInterruptAction: (threadId: string) => void;\n\n /**\n * Optional trace handler for comprehensive debugging and observability.\n */\n onError: CopilotErrorHandler;\n\n // banner error state\n bannerError: CopilotKitError | null;\n setBannerError: React.Dispatch<React.SetStateAction<CopilotKitError | null>>;\n // Internal error handlers\n // These are used to handle errors that occur during the execution of the chat.\n // They are not intended for use by the developer. A component can register itself an error listener to be activated somewhere else as needed\n internalErrorHandlers: Record<string, CopilotErrorHandler>;\n setInternalErrorHandler: (handler: Record<string, CopilotErrorHandler>) => void;\n removeInternalErrorHandler: (id: string) => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coAgentStateRenders: {},\n setCoAgentStateRender: () => {},\n removeCoAgentStateRender: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n getAllContext: () => [],\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n additionalInstructions: [],\n setAdditionalInstructions: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n runtimeClient: {} as any,\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: false,\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n langGraphInterruptAction: null,\n setLangGraphInterruptAction: () => {},\n removeLangGraphInterruptAction: () => {},\n onError: () => {},\n bannerError: null,\n setBannerError: () => {},\n internalErrorHandlers: {},\n setInternalErrorHandler: () => {},\n removeInternalErrorHandler: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n","/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { Parameter, randomId } from \"@copilotkit/shared\";\nimport { createElement, Fragment, useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport {\n ActionRenderProps,\n ActionRenderPropsNoArgsWait,\n ActionRenderPropsWait,\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n const renderAndWaitRef = useRef<RenderAndWaitForResponse | null>(null);\n const activatingMessageIdRef = useRef<string | null>(null);\n const { addToast } = useToast();\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // const { currentlyActivatingHitlActionMessageIdRef } = useCopilotContext() as any; // <-- REMOVE THIS FOR NOW\n\n // If the developer provides a renderAndWaitForResponse function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (\n // renderAndWaitForResponse is not available for catch all actions\n isFrontendAction(action) &&\n // check if renderAndWaitForResponse is set\n (action.renderAndWait || action.renderAndWaitForResponse)\n ) {\n (action as any)._isRenderAndWait = true; // Internal flag to identify this action type later\n const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n action.renderAndWaitForResponse = undefined;\n\n // Add a method for use-chat.ts to set the activating message ID.\n // This helps correlate the action instance with the message being processed by use-chat.\n (action as any)._setActivatingMessageId = (id: string | null) => {\n activatingMessageIdRef.current = id;\n };\n\n // add a handler that will be called when the action is executed\n action.handler = useAsyncCallback(async () => {\n const currentActivatingId = activatingMessageIdRef.current;\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = {\n promise,\n resolve: resolve!,\n reject: reject!,\n messageId: currentActivatingId,\n };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n const result = await promise;\n return result;\n }, []) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<T> & { messageId?: string }): React.ReactElement => {\n const currentRenderMessageId = props.messageId;\n // For renderAndWaitForResponse, the 'executing' state might be set by use-chat before\n // this specific action instance's handler (and thus its promise) is ready.\n // This logic adjusts the status to 'inProgress' if the current render\n // isn't for the actively processing HITL action, preventing premature interaction.\n let status = props.status;\n if (props.status === \"executing\") {\n if (!renderAndWaitRef.current || !renderAndWaitRef.current.promise) {\n status = \"inProgress\";\n } else if (\n renderAndWaitRef.current.messageId !== currentRenderMessageId &&\n activatingMessageIdRef.current !== currentRenderMessageId\n ) {\n status = \"inProgress\";\n }\n // If conditions met, status remains 'executing'\n }\n // Create type safe waitProps based on whether T extends empty array or not\n const waitProps = {\n status,\n args: props.args,\n result: props.result,\n // handler and respond should only be provided if this is the truly active instance\n // and its promise infrastructure is ready.\n handler:\n status === \"executing\" &&\n renderAndWaitRef.current &&\n renderAndWaitRef.current.messageId === currentRenderMessageId\n ? renderAndWaitRef.current!.resolve\n : undefined,\n respond:\n status === \"executing\" &&\n renderAndWaitRef.current &&\n renderAndWaitRef.current.messageId === currentRenderMessageId\n ? renderAndWaitRef.current!.resolve\n : undefined,\n } as T extends [] ? ActionRenderPropsNoArgsWait<T> : ActionRenderPropsWait<T>;\n\n // Type guard to check if renderAndWait is for no args case\n const isNoArgsRenderWait = (\n _fn:\n | ((props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement)\n | ((props: ActionRenderPropsWait<T>) => React.ReactElement),\n ): _fn is (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement => {\n return action.parameters?.length === 0;\n };\n\n // Safely call renderAndWait with correct props type\n if (renderAndWait) {\n if (isNoArgsRenderWait(renderAndWait)) {\n return renderAndWait(waitProps as ActionRenderPropsNoArgsWait<T>);\n } else {\n return renderAndWait(waitProps as ActionRenderPropsWait<T>);\n }\n }\n\n // Return empty Fragment instead of null\n return createElement(Fragment);\n }) as any;\n }\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n // catch all actions don't have a handler\n if (isFrontendAction(action)) {\n actions[idRef.current].handler = action.handler as any;\n }\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n // TODO: using as any here because the type definitions are getting to tricky\n // not wasting time on this now - we know the types are compatible\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n }\n }\n }\n\n useEffect(() => {\n const hasDuplicate = Object.values(actions).some(\n (otherAction) => otherAction.name === action.name && otherAction !== actions[idRef.current],\n );\n\n if (hasDuplicate) {\n addToast({\n type: \"warning\",\n message: `Found an already registered action with name ${action.name}.`,\n id: `dup-action-${action.name}`,\n });\n }\n }, [actions]);\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n // see comment about type safety above\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n // UPDATE: We now have access, we should remove the entry if not referenced by any message.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n isFrontendAction(action) ? action.description : undefined,\n action.name,\n isFrontendAction(action) ? action.disabled : undefined,\n isFrontendAction(action) ? action.available : undefined,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(isFrontendAction(action) ? action.parameters : []),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\nfunction isFrontendAction<T extends Parameter[]>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n): action is FrontendAction<T> {\n return action.name !== \"*\";\n}\n\ninterface RenderAndWaitForResponse {\n promise: Promise<any>;\n resolve: (result: any) => void;\n reject: (error: any) => void;\n messageId: string | null;\n}\n","import React, { useCallback } from \"react\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { ExclamationMarkIcon } from \"../toast/exclamation-mark-icon\";\nimport ReactMarkdown from \"react-markdown\";\n\ninterface OriginalError {\n message?: string;\n stack?: string;\n}\n\nexport function ErrorToast({ errors }: { errors: (Error | GraphQLError)[] }) {\n const errorsToRender = errors.map((error, idx) => {\n const originalError =\n \"extensions\" in error ? (error.extensions?.originalError as undefined | OriginalError) : {};\n const message = originalError?.message ?? error.message;\n const code = \"extensions\" in error ? (error.extensions?.code as string) : null;\n\n return (\n <div\n key={idx}\n style={{\n marginTop: idx === 0 ? 0 : 10,\n marginBottom: 14,\n }}\n >\n <ExclamationMarkIcon style={{ marginBottom: 4 }} />\n\n {code && (\n <div\n style={{\n fontWeight: \"600\",\n marginBottom: 4,\n }}\n >\n Copilot Runtime Error:{\" \"}\n <span style={{ fontFamily: \"monospace\", fontWeight: \"normal\" }}>{code}</span>\n </div>\n )}\n <ReactMarkdown>{message}</ReactMarkdown>\n </div>\n );\n });\n return (\n <div\n style={{\n fontSize: \"13px\",\n maxWidth: \"600px\",\n }}\n >\n {errorsToRender}\n <div style={{ fontSize: \"11px\", opacity: 0.75 }}>\n NOTE: This error only displays during local development.\n </div>\n </div>\n );\n}\n\nexport function useErrorToast() {\n const { addToast } = useToast();\n\n return useCallback(\n (error: (Error | GraphQLError)[]) => {\n const errorId = error\n .map((err) => {\n const message =\n \"extensions\" in err\n ? (err.extensions?.originalError as any)?.message || err.message\n : err.message;\n const stack = err.stack || \"\";\n return btoa(message + stack).slice(0, 32); // Create hash from message + stack\n })\n .join(\"|\");\n\n addToast({\n type: \"error\",\n id: errorId, // Toast libraries typically dedupe by id\n message: <ErrorToast errors={error} />,\n });\n },\n [addToast],\n );\n}\n\nexport function useAsyncCallback<T extends (...args: any[]) => Promise<any>>(\n callback: T,\n deps: Parameters<typeof useCallback>[1],\n) {\n const addErrorToast = useErrorToast();\n return useCallback(async (...args: Parameters<T>) => {\n try {\n return await callback(...args);\n } catch (error) {\n console.error(\"Error in async callback:\", error);\n // @ts-ignore\n addErrorToast([error]);\n throw error;\n }\n }, deps);\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { PartialBy, CopilotKitError, Severity } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(null);\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(/'message':\\s*'([^']+)'/);\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n","import React from \"react\";\n\nexport const ExclamationMarkIcon = ({\n className,\n style,\n}: {\n className?: string;\n style?: React.CSSProperties;\n}) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={`lucide lucide-circle-alert ${className ? className : \"\"}`}\n style={style}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"12\" x2=\"12\" y1=\"8\" y2=\"12\" />\n <line x1=\"12\" x2=\"12.01\" y1=\"16\" y2=\"16\" />\n </svg>\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;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9B;AAEA,UAAI,CAAC,iBAAiB;AAEpB,yBAAiB,UAAU;AAE3B,gBAAO,6CAAc,mBACjB,cAAAA,QAAM,cAAc,aAAa,iBAAiB;AAAA,UAChD,kBAAkB,CAAC,cAAc;AAC/B,+DAAkB,CAAC,SAAU,iCAAK,OAAL,EAAW,CAAC,OAAO,IAAI,GAAG,UAAU;AACjE,gBAAI,iBAAiB,SAAS;AAC5B,4BAAc,iBAAiB,OAAO;AACtC,+BAAiB,UAAU;AAAA,YAC7B;AAAA,UACF;AAAA,QACF,CAAC,IACD,cAAAA,QAAM,cAAc,sBAAQ;AAAA,MAClC;AAEA,aAAO,cAAc,KAAK;AAAA,IAC5B;AAAA,IACA,CAAC,QAAQ,cAAc,eAAe;AAAA,EACxC;AAEA;AAAA,IACE,iCACK,SADL;AAAA,MAEE,QAAQ;AAAA,IACV;AAAA,IACA;AAAA,EACF;AACF;","names":["import_react","React","import_shared","import_react","import_react","import_react","import_jsx_runtime","import_jsx_runtime","ReactMarkdown","import_react","React"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useCopilotAuthenticatedAction_c
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
3
|
+
} from "../chunk-GIGUZ2OK.mjs";
|
|
4
|
+
import "../chunk-HI6SPUOX.mjs";
|
|
5
5
|
import "../chunk-N4WEHORG.mjs";
|
|
6
6
|
import "../chunk-O7ARI5CV.mjs";
|
|
7
|
-
import "../chunk-
|
|
7
|
+
import "../chunk-EUX2P2E7.mjs";
|
|
8
8
|
import "../chunk-EFL5OBKN.mjs";
|
|
9
9
|
import "../chunk-SKC7AJIV.mjs";
|
|
10
10
|
export {
|
|
@@ -5,14 +5,14 @@ import '@copilotkit/runtime-client-gql';
|
|
|
5
5
|
import '@copilotkit/shared';
|
|
6
6
|
import './use-chat.js';
|
|
7
7
|
import 'react';
|
|
8
|
-
import '../copilot-context-
|
|
8
|
+
import '../copilot-context-cf9de848.js';
|
|
9
9
|
import '../types/frontend-action.js';
|
|
10
10
|
import './use-tree.js';
|
|
11
11
|
import '../types/document-pointer.js';
|
|
12
12
|
import '../types/chat-suggestion-configuration.js';
|
|
13
13
|
import '../types/coagent-action.js';
|
|
14
14
|
import '../types/coagent-state.js';
|
|
15
|
-
import '../index-
|
|
15
|
+
import '../index-1f5b66ac.js';
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* Enterprise React hook that provides complete chat functionality for fully custom UI implementations.
|
|
@@ -157,8 +157,10 @@ var emptyCopilotContext = {
|
|
|
157
157
|
setExtensions: () => {
|
|
158
158
|
},
|
|
159
159
|
langGraphInterruptAction: null,
|
|
160
|
-
setLangGraphInterruptAction: () =>
|
|
161
|
-
|
|
160
|
+
setLangGraphInterruptAction: () => {
|
|
161
|
+
},
|
|
162
|
+
removeLangGraphInterruptAction: () => {
|
|
163
|
+
},
|
|
162
164
|
onError: () => {
|
|
163
165
|
},
|
|
164
166
|
bannerError: null,
|
|
@@ -534,7 +536,18 @@ function useChat(options) {
|
|
|
534
536
|
const runChatCompletionRef = (0, import_react6.useRef)();
|
|
535
537
|
const addErrorToast = useErrorToast();
|
|
536
538
|
const { setBannerError } = useToast();
|
|
537
|
-
const { onError } = useCopilotContext();
|
|
539
|
+
const { onError, showDevConsole, getAllContext } = useCopilotContext();
|
|
540
|
+
const copilotReadableContext = getAllContext();
|
|
541
|
+
const context = (0, import_react6.useMemo)(
|
|
542
|
+
() => copilotReadableContext.map((contextItem) => {
|
|
543
|
+
const [description, ...valueParts] = contextItem.value.split(":");
|
|
544
|
+
return {
|
|
545
|
+
description: description.trim(),
|
|
546
|
+
value: valueParts.join(":").trim()
|
|
547
|
+
};
|
|
548
|
+
}),
|
|
549
|
+
[copilotReadableContext]
|
|
550
|
+
);
|
|
538
551
|
const traceUIError = (error, originalError) => __async(this, null, function* () {
|
|
539
552
|
try {
|
|
540
553
|
const traceEvent = {
|
|
@@ -568,7 +581,6 @@ function useChat(options) {
|
|
|
568
581
|
extensionsRef.current = extensions;
|
|
569
582
|
const publicApiKey = copilotConfig.publicApiKey;
|
|
570
583
|
const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared4.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
|
|
571
|
-
const { showDevConsole } = useCopilotContext();
|
|
572
584
|
const runtimeClient = useCopilotRuntimeClient({
|
|
573
585
|
url: copilotConfig.chatApiEndpoint,
|
|
574
586
|
publicApiKey: copilotConfig.publicApiKey,
|
|
@@ -649,7 +661,8 @@ function useChat(options) {
|
|
|
649
661
|
}
|
|
650
662
|
return stateObject;
|
|
651
663
|
}),
|
|
652
|
-
forwardedParameters: options.forwardedParameters || {}
|
|
664
|
+
forwardedParameters: options.forwardedParameters || {},
|
|
665
|
+
context
|
|
653
666
|
}),
|
|
654
667
|
properties: finalProperties,
|
|
655
668
|
signal: (_e = chatAbortControllerRef.current) == null ? void 0 : _e.signal
|
|
@@ -693,7 +706,7 @@ function useChat(options) {
|
|
|
693
706
|
if (ev.name === import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent) {
|
|
694
707
|
let eventValue = (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev).value;
|
|
695
708
|
eventValue = (0, import_shared4.parseJson)(eventValue, eventValue);
|
|
696
|
-
setLangGraphInterruptAction({
|
|
709
|
+
setLangGraphInterruptAction(threadId, {
|
|
697
710
|
event: __spreadProps(__spreadValues({}, (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev)), {
|
|
698
711
|
value: eventValue
|
|
699
712
|
})
|
|
@@ -756,7 +769,7 @@ function useChat(options) {
|
|
|
756
769
|
preservedStructure: !!originalCode
|
|
757
770
|
});
|
|
758
771
|
setIsLoading(false);
|
|
759
|
-
|
|
772
|
+
throw new Error(structuredError.message);
|
|
760
773
|
} else if (messages2.length > 0) {
|
|
761
774
|
newMessages = [...messages2];
|
|
762
775
|
for (const message of messages2) {
|
|
@@ -877,8 +890,8 @@ function useChat(options) {
|
|
|
877
890
|
}
|
|
878
891
|
const currentResultMessagePairedFeAction = message.isResultMessage() ? getPairedFeAction(actions, message) : null;
|
|
879
892
|
if (action && message.isActionExecutionMessage()) {
|
|
880
|
-
const
|
|
881
|
-
const alreadyProcessed =
|
|
893
|
+
const pairedFeAction = getPairedFeAction(actions, message);
|
|
894
|
+
const alreadyProcessed = !pairedFeAction && finalMessages.some(
|
|
882
895
|
(fm) => fm.isResultMessage() && fm.actionExecutionId === message.id
|
|
883
896
|
);
|
|
884
897
|
if (alreadyProcessed) {
|
|
@@ -887,16 +900,16 @@ function useChat(options) {
|
|
|
887
900
|
action,
|
|
888
901
|
message
|
|
889
902
|
);
|
|
890
|
-
const
|
|
891
|
-
if (
|
|
903
|
+
const pairedFeAction2 = getPairedFeAction(actions, resultMessage);
|
|
904
|
+
if (pairedFeAction2) {
|
|
892
905
|
const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
|
|
893
|
-
name:
|
|
906
|
+
name: pairedFeAction2.name,
|
|
894
907
|
arguments: (0, import_shared4.parseJson)(resultMessage.result, resultMessage.result),
|
|
895
908
|
status: message.status,
|
|
896
909
|
createdAt: message.createdAt,
|
|
897
910
|
parentMessageId: message.parentMessageId
|
|
898
911
|
});
|
|
899
|
-
yield executeActionFromMessage(
|
|
912
|
+
yield executeActionFromMessage(pairedFeAction2, newExecutionMessage);
|
|
900
913
|
}
|
|
901
914
|
}
|
|
902
915
|
} else if (message.isResultMessage() && currentResultMessagePairedFeAction) {
|
|
@@ -961,7 +974,8 @@ function useChat(options) {
|
|
|
961
974
|
coagentStatesRef,
|
|
962
975
|
agentSession,
|
|
963
976
|
setAgentSession,
|
|
964
|
-
disableSystemMessage
|
|
977
|
+
disableSystemMessage,
|
|
978
|
+
context
|
|
965
979
|
]
|
|
966
980
|
);
|
|
967
981
|
runChatCompletionRef.current = runChatCompletion;
|
|
@@ -990,7 +1004,7 @@ function useChat(options) {
|
|
|
990
1004
|
switch (event.name) {
|
|
991
1005
|
case import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent:
|
|
992
1006
|
if (event.response) {
|
|
993
|
-
setLangGraphInterruptAction(null);
|
|
1007
|
+
setLangGraphInterruptAction(threadId, null);
|
|
994
1008
|
const value = event.value;
|
|
995
1009
|
return [
|
|
996
1010
|
...acc,
|
|
@@ -1040,8 +1054,8 @@ function useChat(options) {
|
|
|
1040
1054
|
console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
|
|
1041
1055
|
return;
|
|
1042
1056
|
}
|
|
1043
|
-
let historyCutoff = [];
|
|
1044
|
-
if (messages.length > 2) {
|
|
1057
|
+
let historyCutoff = [messages[0]];
|
|
1058
|
+
if (messages.length > 2 && reloadMessageIndex !== 0) {
|
|
1045
1059
|
const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find(
|
|
1046
1060
|
(msg) => (
|
|
1047
1061
|
// @ts-expect-error -- message has role
|
|
@@ -1052,6 +1066,8 @@ function useChat(options) {
|
|
|
1052
1066
|
(msg) => msg.id === lastUserMessageBeforeRegenerate.id
|
|
1053
1067
|
);
|
|
1054
1068
|
historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
|
|
1069
|
+
} else if (messages.length > 2 && reloadMessageIndex === 0) {
|
|
1070
|
+
historyCutoff = [messages[0], messages[1]];
|
|
1055
1071
|
}
|
|
1056
1072
|
setMessages(historyCutoff);
|
|
1057
1073
|
return runChatCompletionAndHandleFunctionCall(historyCutoff);
|
|
@@ -1444,16 +1460,16 @@ var InterruptRenderer = ({ event, result, render, resolve }) => {
|
|
|
1444
1460
|
return render({ event, result, resolve });
|
|
1445
1461
|
};
|
|
1446
1462
|
function useLangGraphInterruptRender() {
|
|
1447
|
-
const { langGraphInterruptAction, setLangGraphInterruptAction, agentSession } = useCopilotContext();
|
|
1463
|
+
const { langGraphInterruptAction, setLangGraphInterruptAction, agentSession, threadId } = useCopilotContext();
|
|
1448
1464
|
const responseRef = import_react8.default.useRef();
|
|
1449
1465
|
const resolveInterrupt = (0, import_react8.useCallback)(
|
|
1450
1466
|
(response) => {
|
|
1451
1467
|
responseRef.current = response;
|
|
1452
1468
|
setTimeout(() => {
|
|
1453
|
-
setLangGraphInterruptAction({ event: { response } });
|
|
1469
|
+
setLangGraphInterruptAction(threadId, { event: { response } });
|
|
1454
1470
|
}, 0);
|
|
1455
1471
|
},
|
|
1456
|
-
[setLangGraphInterruptAction]
|
|
1472
|
+
[setLangGraphInterruptAction, threadId]
|
|
1457
1473
|
);
|
|
1458
1474
|
if (!langGraphInterruptAction || !langGraphInterruptAction.event || !langGraphInterruptAction.render)
|
|
1459
1475
|
return null;
|