@copilotkit/react-core 1.5.12-next.6 → 1.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/{chunk-5SXKKYAY.mjs → chunk-6BQUI465.mjs} +26 -5
  3. package/dist/chunk-6BQUI465.mjs.map +1 -0
  4. package/dist/{chunk-SDMANO6S.mjs → chunk-CBWNO2FP.mjs} +2 -2
  5. package/dist/{chunk-KHZO2WMR.mjs → chunk-EXX267DG.mjs} +2 -2
  6. package/dist/chunk-IFBUUIU7.mjs +53 -0
  7. package/dist/chunk-IFBUUIU7.mjs.map +1 -0
  8. package/dist/{chunk-HIUT2NLX.mjs → chunk-J6UBNKIR.mjs} +2 -2
  9. package/dist/{chunk-27ONDUGD.mjs → chunk-KGCYVAIN.mjs} +14 -8
  10. package/dist/chunk-KGCYVAIN.mjs.map +1 -0
  11. package/dist/{chunk-ANHSORJR.mjs → chunk-MF4F77OY.mjs} +3 -3
  12. package/dist/{chunk-5TSAQCRY.mjs → chunk-MYCYEMIM.mjs} +25 -7
  13. package/dist/chunk-MYCYEMIM.mjs.map +1 -0
  14. package/dist/{chunk-FQ53HQYZ.mjs → chunk-N37EFAUX.mjs} +2 -2
  15. package/dist/{chunk-NO6F42WV.mjs → chunk-VEGDEDID.mjs} +2 -2
  16. package/dist/{chunk-EUSQWVOS.mjs → chunk-X62FIPVR.mjs} +10 -7
  17. package/dist/chunk-X62FIPVR.mjs.map +1 -0
  18. package/dist/{chunk-WXREY7UP.mjs → chunk-YVQNSJ4Z.mjs} +6 -3
  19. package/dist/chunk-YVQNSJ4Z.mjs.map +1 -0
  20. package/dist/components/copilot-provider/copilot-messages.js +125 -2
  21. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  22. package/dist/components/copilot-provider/copilot-messages.mjs +2 -1
  23. package/dist/components/copilot-provider/copilotkit-props.d.ts +4 -0
  24. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  25. package/dist/components/copilot-provider/copilotkit.js +54 -7
  26. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  27. package/dist/components/copilot-provider/copilotkit.mjs +3 -3
  28. package/dist/components/copilot-provider/index.js +54 -7
  29. package/dist/components/copilot-provider/index.js.map +1 -1
  30. package/dist/components/copilot-provider/index.mjs +3 -3
  31. package/dist/components/index.js +54 -7
  32. package/dist/components/index.js.map +1 -1
  33. package/dist/components/index.mjs +3 -3
  34. package/dist/context/copilot-context.d.ts +5 -3
  35. package/dist/context/copilot-context.js +5 -2
  36. package/dist/context/copilot-context.js.map +1 -1
  37. package/dist/context/copilot-context.mjs +1 -1
  38. package/dist/context/index.js +5 -2
  39. package/dist/context/index.js.map +1 -1
  40. package/dist/context/index.mjs +1 -1
  41. package/dist/hooks/index.js +42 -13
  42. package/dist/hooks/index.js.map +1 -1
  43. package/dist/hooks/index.mjs +11 -11
  44. package/dist/hooks/use-chat.d.ts +11 -3
  45. package/dist/hooks/use-chat.js +11 -6
  46. package/dist/hooks/use-chat.js.map +1 -1
  47. package/dist/hooks/use-chat.mjs +1 -1
  48. package/dist/hooks/use-coagent-state-render.js +5 -2
  49. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  50. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  51. package/dist/hooks/use-coagent.js +42 -13
  52. package/dist/hooks/use-coagent.js.map +1 -1
  53. package/dist/hooks/use-coagent.mjs +6 -6
  54. package/dist/hooks/use-copilot-action.js +5 -2
  55. package/dist/hooks/use-copilot-action.js.map +1 -1
  56. package/dist/hooks/use-copilot-action.mjs +2 -2
  57. package/dist/hooks/use-copilot-authenticated-action.js +5 -2
  58. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  59. package/dist/hooks/use-copilot-authenticated-action.mjs +3 -3
  60. package/dist/hooks/use-copilot-chat.js +22 -11
  61. package/dist/hooks/use-copilot-chat.js.map +1 -1
  62. package/dist/hooks/use-copilot-chat.mjs +5 -5
  63. package/dist/hooks/use-copilot-readable.js +5 -2
  64. package/dist/hooks/use-copilot-readable.js.map +1 -1
  65. package/dist/hooks/use-copilot-readable.mjs +2 -2
  66. package/dist/hooks/use-make-copilot-document-readable.js +5 -2
  67. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  68. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  69. package/dist/index.js +122 -56
  70. package/dist/index.js.map +1 -1
  71. package/dist/index.mjs +12 -12
  72. package/dist/lib/copilot-task.js.map +1 -1
  73. package/dist/lib/copilot-task.mjs +4 -4
  74. package/dist/lib/index.js.map +1 -1
  75. package/dist/lib/index.mjs +4 -4
  76. package/dist/utils/extract.js.map +1 -1
  77. package/dist/utils/extract.mjs +3 -3
  78. package/dist/utils/index.js.map +1 -1
  79. package/dist/utils/index.mjs +3 -3
  80. package/package.json +3 -3
  81. package/src/components/copilot-provider/copilot-messages.tsx +24 -2
  82. package/src/components/copilot-provider/copilotkit-props.tsx +5 -0
  83. package/src/components/copilot-provider/copilotkit.tsx +30 -4
  84. package/src/context/copilot-context.tsx +13 -4
  85. package/src/hooks/use-chat.ts +27 -7
  86. package/src/hooks/use-coagent.ts +30 -4
  87. package/src/hooks/use-copilot-chat.ts +5 -2
  88. package/dist/chunk-27ONDUGD.mjs.map +0 -1
  89. package/dist/chunk-5SXKKYAY.mjs.map +0 -1
  90. package/dist/chunk-5TSAQCRY.mjs.map +0 -1
  91. package/dist/chunk-EUSQWVOS.mjs.map +0 -1
  92. package/dist/chunk-WXREY7UP.mjs.map +0 -1
  93. package/dist/chunk-XXR4QFAQ.mjs +0 -29
  94. package/dist/chunk-XXR4QFAQ.mjs.map +0 -1
  95. /package/dist/{chunk-SDMANO6S.mjs.map → chunk-CBWNO2FP.mjs.map} +0 -0
  96. /package/dist/{chunk-KHZO2WMR.mjs.map → chunk-EXX267DG.mjs.map} +0 -0
  97. /package/dist/{chunk-HIUT2NLX.mjs.map → chunk-J6UBNKIR.mjs.map} +0 -0
  98. /package/dist/{chunk-ANHSORJR.mjs.map → chunk-MF4F77OY.mjs.map} +0 -0
  99. /package/dist/{chunk-FQ53HQYZ.mjs.map → chunk-N37EFAUX.mjs.map} +0 -0
  100. /package/dist/{chunk-NO6F42WV.mjs.map → chunk-VEGDEDID.mjs.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"sourcesContent":["/**\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n *\n * // optionally, you can append a message without running chat completion\n * appendMessage(yourMessage, { followUp: false });\n * }\n * ```\n *\n * `useCopilotChat` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * visibleMessages, // An array of messages that are currently visible in the chat.\n * appendMessage, // A function to append a message to the chat.\n * setMessages, // A function to set the messages in the chat.\n * deleteMessage, // A function to delete a message from the chat.\n * reloadMessages, // A function to reload the messages from the API.\n * stopGeneration, // A function to stop the generation of the next message.\n * isLoading, // A boolean indicating if the chat is loading.\n * } = useCopilotChat();\n * ```\n */\nimport { useRef, useEffect, useCallback } from \"react\";\nimport { AgentSession, useCopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat, AppendMessageOptions } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CoAgentStateRenderHandlerArguments, randomId } from \"@copilotkit/shared\";\nimport { useCopilotMessagesContext } from \"../context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n reset: () => void;\n isLoading: boolean;\n runChatCompletion: () => Promise<Message[]>;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n coagentStatesRef,\n setCoagentStatesWithRef,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n extensions,\n setExtensions,\n } = useCopilotContext();\n const { messages, setMessages } = useCopilotMessagesContext();\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: Role.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const onCoAgentStateRender = useAsyncCallback(\n async (args: CoAgentStateRenderHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coAgentStateRenders],\n );\n\n const { append, reload, stop, runChatCompletion } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n onCoAgentStateRender,\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n });\n\n // this is a workaround born out of a bug that Athena incessantly ran into.\n // We could not find the origin of the bug, however, it was clear that an outdated version of the append function was being used somehow --\n // it referenced the old state of the messages array, and not the latest one.\n //\n // We want to make copilotkit as abuse-proof as possible, so we are adding this workaround to ensure that the latest version of the append function is always used.\n //\n // How does this work?\n // we store the relevant function in a ref that is always up-to-date, and then we use that ref in the callback.\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n return await latestAppend.current(message, options);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(async () => {\n return await latestReload.current();\n }, [latestReload]);\n\n const latestStop = useUpdatedRef(stop);\n const latestStopFunc = useCallback(() => {\n return latestStop.current();\n }, [latestStop]);\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const latestSetMessages = useUpdatedRef(setMessages);\n const latestSetMessagesFunc = useCallback(\n (messages: Message[]) => {\n return latestSetMessages.current(messages);\n },\n [latestSetMessages],\n );\n\n const latestRunChatCompletion = useUpdatedRef(runChatCompletion);\n const latestRunChatCompletionFunc = useAsyncCallback(async () => {\n return await latestRunChatCompletion.current!();\n }, [latestRunChatCompletion]);\n\n const reset = useCallback(() => {\n latestStopFunc();\n setMessages([]);\n setRunId(null);\n setCoagentStatesWithRef({});\n let initialAgentSession: AgentSession | null = null;\n if (agentLock) {\n initialAgentSession = {\n agentName: agentLock,\n };\n }\n setAgentSession(initialAgentSession);\n }, [\n latestStopFunc,\n setMessages,\n setThreadId,\n setCoagentStatesWithRef,\n setAgentSession,\n agentLock,\n ]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n return {\n visibleMessages: messages,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n runChatCompletion: latestRunChatCompletionFunc,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n"],"mappings":"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","names":["_a","action","options","messages"]}
@@ -59,14 +59,17 @@ var emptyCopilotContext = {
59
59
  },
60
60
  forwardedParameters: {},
61
61
  agentLock: null,
62
- threadId: null,
62
+ threadId: "",
63
63
  setThreadId: () => {
64
64
  },
65
65
  runId: null,
66
66
  setRunId: () => {
67
67
  },
68
68
  chatAbortControllerRef: { current: null },
69
- availableAgents: []
69
+ availableAgents: [],
70
+ extensions: {},
71
+ setExtensions: () => {
72
+ }
70
73
  };
71
74
  var CopilotContext = React.createContext(emptyCopilotContext);
72
75
  function useCopilotContext() {
@@ -84,4 +87,4 @@ export {
84
87
  CopilotContext,
85
88
  useCopilotContext
86
89
  };
87
- //# sourceMappingURL=chunk-WXREY7UP.mjs.map
90
+ //# sourceMappingURL=chunk-YVQNSJ4Z.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context/copilot-context.tsx"],"sourcesContent":["import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } 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\";\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\nexport type InChatRenderFunction = (\n props: ActionRenderProps<any> | CatchAllActionRenderProps<any>,\n) => 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;\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 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 // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\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?: Pick<ForwardedParametersInput, \"temperature\">;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates?: Record<ActionName, AuthState>;\n setAuthStates?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\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\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => 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: \"auto\",\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};\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"],"mappings":";;;;;AAMA,OAAO,WAAW;AAsMlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,CAAC;AAAA,EACtB,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,0BAA0B,MAAM;AAAA,EAAC;AAAA,EAEjC,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,EAAE;AAAA,EACzE,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC;AAAA,EACvE,oBAAoB,MAAM,sBAAsB,EAAE;AAAA,EAClD,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,eAAe,CAAC;AAAA,EAEhB,kBAAkB,IAAK,MAAkC;AAAA,IACvD,IAAI,kBAA0B;AAC5B,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAAA,IAEA,IAAI,UAAkC;AACpC,aAAO,CAAC;AAAA,IACV;AAAA,IACA,IAAI,OAA4B;AAC9B,aAAO,CAAC;AAAA,IACV;AAAA,EACF,EAAG;AAAA,EAEH,6BAA6B,CAAC;AAAA,EAC9B,gCAAgC,MAAM;AAAA,EAAC;AAAA,EACvC,mCAAmC,MAAM;AAAA,EAAC;AAAA,EAC1C,gBAAgB;AAAA,EAChB,eAAe,CAAC;AAAA,EAChB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EACzB,kBAAkB,EAAE,SAAS,CAAC,EAAE;AAAA,EAChC,yBAAyB,MAAM;AAAA,EAAC;AAAA,EAChC,cAAc;AAAA,EACd,iBAAiB,MAAM;AAAA,EAAC;AAAA,EACxB,qBAAqB,CAAC;AAAA,EACtB,WAAW;AAAA,EACX,UAAU;AAAA,EACV,aAAa,MAAM;AAAA,EAAC;AAAA,EACpB,OAAO;AAAA,EACP,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,wBAAwB,EAAE,SAAS,KAAK;AAAA,EACxC,iBAAiB,CAAC;AAAA,EAClB,YAAY,CAAC;AAAA,EACb,eAAe,MAAM;AAAA,EAAC;AACxB;AAEO,IAAM,iBAAiB,MAAM,cAAoC,mBAAmB;AAEpF,SAAS,oBAA0C;AACxD,QAAM,UAAU,MAAM,WAAW,cAAc;AAC/C,MAAI,YAAY,qBAAqB;AACnC,UAAM,IAAI,MAAM,uEAAuE;AAAA,EACzF;AACA,SAAO;AACT;AAEA,SAAS,sBAAyB,QAAc;AAC9C,QAAM,IAAI,MAAM,uEAAuE;AACzF;","names":[]}
@@ -40,6 +40,26 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
40
40
  mod
41
41
  ));
42
42
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
43
+ var __async = (__this, __arguments, generator) => {
44
+ return new Promise((resolve, reject) => {
45
+ var fulfilled = (value) => {
46
+ try {
47
+ step(generator.next(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ };
52
+ var rejected = (value) => {
53
+ try {
54
+ step(generator.throw(value));
55
+ } catch (e) {
56
+ reject(e);
57
+ }
58
+ };
59
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
60
+ step((generator = generator.apply(__this, __arguments)).next());
61
+ });
62
+ };
43
63
 
44
64
  // src/components/copilot-provider/copilot-messages.tsx
45
65
  var copilot_messages_exports = {};
@@ -47,7 +67,7 @@ __export(copilot_messages_exports, {
47
67
  CopilotMessages: () => CopilotMessages
48
68
  });
49
69
  module.exports = __toCommonJS(copilot_messages_exports);
50
- var import_react2 = require("react");
70
+ var import_react3 = require("react");
51
71
 
52
72
  // src/context/copilot-messages-context.tsx
53
73
  var import_react = __toESM(require("react"));
@@ -57,11 +77,114 @@ var emptyCopilotContext = {
57
77
  };
58
78
  var CopilotMessagesContext = import_react.default.createContext(emptyCopilotContext);
59
79
 
80
+ // src/components/copilot-provider/copilot-messages.tsx
81
+ var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
82
+
83
+ // src/context/copilot-context.tsx
84
+ var import_react2 = __toESM(require("react"));
85
+ var emptyCopilotContext2 = {
86
+ actions: {},
87
+ setAction: () => {
88
+ },
89
+ removeAction: () => {
90
+ },
91
+ coAgentStateRenders: {},
92
+ setCoAgentStateRender: () => {
93
+ },
94
+ removeCoAgentStateRender: () => {
95
+ },
96
+ chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
97
+ getContextString: (documents, categories) => returnAndThrowInDebug(""),
98
+ addContext: () => "",
99
+ removeContext: () => {
100
+ },
101
+ getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
102
+ })),
103
+ isLoading: false,
104
+ setIsLoading: () => returnAndThrowInDebug(false),
105
+ chatInstructions: "",
106
+ setChatInstructions: () => returnAndThrowInDebug(""),
107
+ getDocumentsContext: (categories) => returnAndThrowInDebug([]),
108
+ addDocumentContext: () => returnAndThrowInDebug(""),
109
+ removeDocumentContext: () => {
110
+ },
111
+ runtimeClient: {},
112
+ copilotApiConfig: new class {
113
+ get chatApiEndpoint() {
114
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
115
+ }
116
+ get headers() {
117
+ return {};
118
+ }
119
+ get body() {
120
+ return {};
121
+ }
122
+ }(),
123
+ chatSuggestionConfiguration: {},
124
+ addChatSuggestionConfiguration: () => {
125
+ },
126
+ removeChatSuggestionConfiguration: () => {
127
+ },
128
+ showDevConsole: "auto",
129
+ coagentStates: {},
130
+ setCoagentStates: () => {
131
+ },
132
+ coagentStatesRef: { current: {} },
133
+ setCoagentStatesWithRef: () => {
134
+ },
135
+ agentSession: null,
136
+ setAgentSession: () => {
137
+ },
138
+ forwardedParameters: {},
139
+ agentLock: null,
140
+ threadId: "",
141
+ setThreadId: () => {
142
+ },
143
+ runId: null,
144
+ setRunId: () => {
145
+ },
146
+ chatAbortControllerRef: { current: null },
147
+ availableAgents: [],
148
+ extensions: {},
149
+ setExtensions: () => {
150
+ }
151
+ };
152
+ var CopilotContext = import_react2.default.createContext(emptyCopilotContext2);
153
+ function useCopilotContext() {
154
+ const context = import_react2.default.useContext(CopilotContext);
155
+ if (context === emptyCopilotContext2) {
156
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
157
+ }
158
+ return context;
159
+ }
160
+ function returnAndThrowInDebug(_value) {
161
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
162
+ }
163
+
60
164
  // src/components/copilot-provider/copilot-messages.tsx
61
165
  var import_jsx_runtime = require("react/jsx-runtime");
62
166
  function CopilotMessages(_a) {
63
167
  var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
64
- const [messages, setMessages] = (0, import_react2.useState)([]);
168
+ const [messages, setMessages] = (0, import_react3.useState)([]);
169
+ const { threadId, agentSession, runtimeClient } = useCopilotContext();
170
+ (0, import_react3.useEffect)(() => {
171
+ if (agentSession == null ? void 0 : agentSession.agentName) {
172
+ const fetchAgentState = () => __async(this, null, function* () {
173
+ var _a2, _b2, _c, _d;
174
+ const result = yield runtimeClient.loadAgentState({
175
+ threadId,
176
+ agentName: agentSession.agentName
177
+ });
178
+ if ((_b2 = (_a2 = result.data) == null ? void 0 : _a2.loadAgentState) == null ? void 0 : _b2.threadExists) {
179
+ const messages2 = (0, import_runtime_client_gql.loadMessagesFromJsonRepresentation)(
180
+ JSON.parse(((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.messages) || "[]")
181
+ );
182
+ setMessages(messages2);
183
+ }
184
+ });
185
+ void fetchAgentState();
186
+ }
187
+ }, [threadId, (agentSession == null ? void 0 : agentSession.agentName) !== void 0]);
65
188
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
66
189
  CopilotMessagesContext.Provider,
67
190
  {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/components/copilot-provider/copilot-messages.tsx","../../../src/context/copilot-messages-context.tsx"],"sourcesContent":["/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { useState } from \"react\";\nimport { CopilotMessagesContext } from \"../../context/copilot-messages-context\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\n\nexport function CopilotMessages({ children, ...props }: CopilotKitProps) {\n const [messages, setMessages] = useState<Message[]>([]);\n\n return (\n <CopilotMessagesContext.Provider\n value={{\n messages,\n setMessages,\n }}\n >\n {children}\n </CopilotMessagesContext.Provider>\n );\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport React from \"react\";\n\nexport interface CopilotMessagesContextParams {\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n}\n\nconst emptyCopilotContext: CopilotMessagesContextParams = {\n messages: [],\n setMessages: () => [],\n};\n\nexport const CopilotMessagesContext =\n React.createContext<CopilotMessagesContextParams>(emptyCopilotContext);\n\nexport function useCopilotMessagesContext(): CopilotMessagesContextParams {\n const context = React.useContext(CopilotMessagesContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`\",\n );\n }\n return context;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,IAAAA,gBAAyB;;;ACCzB,mBAAkB;AAOlB,IAAM,sBAAoD;AAAA,EACxD,UAAU,CAAC;AAAA,EACX,aAAa,MAAM,CAAC;AACtB;AAEO,IAAM,yBACX,aAAAC,QAAM,cAA4C,mBAAmB;;;ADLnE;AAJG,SAAS,gBAAgB,IAAyC;AAAzC,eAAE,WATlC,IASgC,IAAe,kBAAf,IAAe,CAAb;AAChC,QAAM,CAAC,UAAU,WAAW,QAAI,wBAAoB,CAAC,CAAC;AAEtD,SACE;AAAA,IAAC,uBAAuB;AAAA,IAAvB;AAAA,MACC,OAAO;AAAA,QACL;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;","names":["import_react","React"]}
1
+ {"version":3,"sources":["../../../src/components/copilot-provider/copilot-messages.tsx","../../../src/context/copilot-messages-context.tsx","../../../src/context/copilot-context.tsx"],"sourcesContent":["/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { useEffect, useState } from \"react\";\nimport { CopilotMessagesContext } from \"../../context/copilot-messages-context\";\nimport { loadMessagesFromJsonRepresentation, Message } from \"@copilotkit/runtime-client-gql\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { useCopilotContext } from \"../../context/copilot-context\";\n\nexport function CopilotMessages({ children, ...props }: CopilotKitProps) {\n const [messages, setMessages] = useState<Message[]>([]);\n\n const { threadId, agentSession, runtimeClient } = useCopilotContext();\n\n useEffect(() => {\n if (agentSession?.agentName) {\n // reload messages\n const fetchAgentState = async () => {\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: agentSession.agentName,\n });\n if (result.data?.loadAgentState?.threadExists) {\n const messages = loadMessagesFromJsonRepresentation(\n JSON.parse(result.data?.loadAgentState?.messages || \"[]\"),\n );\n setMessages(messages);\n }\n };\n void fetchAgentState();\n }\n }, [threadId, agentSession?.agentName !== undefined]);\n\n return (\n <CopilotMessagesContext.Provider\n value={{\n messages,\n setMessages,\n }}\n >\n {children}\n </CopilotMessagesContext.Provider>\n );\n}\n","/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport React from \"react\";\n\nexport interface CopilotMessagesContextParams {\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n}\n\nconst emptyCopilotContext: CopilotMessagesContextParams = {\n messages: [],\n setMessages: () => [],\n};\n\nexport const CopilotMessagesContext =\n React.createContext<CopilotMessagesContextParams>(emptyCopilotContext);\n\nexport function useCopilotMessagesContext(): CopilotMessagesContextParams {\n const context = React.useContext(CopilotMessagesContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`\",\n );\n }\n return context;\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } 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\";\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\nexport type InChatRenderFunction = (\n props: ActionRenderProps<any> | CatchAllActionRenderProps<any>,\n) => 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;\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 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 // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\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?: Pick<ForwardedParametersInput, \"temperature\">;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates?: Record<ActionName, AuthState>;\n setAuthStates?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\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\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => 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: \"auto\",\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};\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"],"mappings":"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","names":["import_react","React","import_react","emptyCopilotContext","React","_a","_b","messages"]}
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  CopilotMessages
3
- } from "../../chunk-XXR4QFAQ.mjs";
3
+ } from "../../chunk-IFBUUIU7.mjs";
4
4
  import "../../chunk-DCTJZ742.mjs";
5
+ import "../../chunk-YVQNSJ4Z.mjs";
5
6
  import "../../chunk-SKC7AJIV.mjs";
6
7
  export {
7
8
  CopilotMessages
@@ -88,6 +88,10 @@ interface CopilotKitProps {
88
88
  onSignInComplete: (authState: AuthState) => void;
89
89
  }>;
90
90
  };
91
+ /**
92
+ * The thread id to use for the CopilotKit.
93
+ */
94
+ threadId?: string;
91
95
  }
92
96
 
93
97
  export { CopilotKitProps };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/components/copilot-provider/copilotkit-props.tsx"],"sourcesContent":["import { ForwardedParametersInput } from \"@copilotkit/runtime-client-gql\";\nimport { ReactNode } from \"react\";\nimport { AuthState } from \"../../context/copilot-context\";\n\n/**\n * Props for CopilotKit.\n */\n\nexport interface CopilotKitProps {\n /**\n * Your Copilot Cloud API key. Don't have it yet? Go to https://cloud.copilotkit.ai and get one for free.\n */\n publicApiKey?: string;\n\n /**\n * Restrict input to a specific topic.\n */\n cloudRestrictToTopic?: {\n validTopics?: string[];\n invalidTopics?: string[];\n };\n\n /**\n * The endpoint for the Copilot Runtime instance. [Click here for more information](/concepts/copilot-runtime).\n */\n runtimeUrl?: 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 *\n * For example:\n * ```json\n * {\n * \"Authorization\": \"Bearer X\"\n * }\n * ```\n */\n headers?: Record<string, string>;\n\n /**\n * The children to be rendered within the CopilotKit.\n */\n children: ReactNode;\n\n /**\n * Custom properties to be sent with the request\n * For example:\n * ```js\n * {\n * 'user_id': 'users_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 * Whether to show the dev console.\n *\n * If set to \"auto\", the dev console will be show on localhost only.\n */\n showDevConsole?: boolean | \"auto\";\n\n /**\n * The name of the agent to use.\n */\n agent?: string;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Pick<ForwardedParametersInput, \"temperature\">;\n\n /**\n * The auth config to use for the CopilotKit.\n */\n authConfig?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
1
+ {"version":3,"sources":["../../../src/components/copilot-provider/copilotkit-props.tsx"],"sourcesContent":["import { ForwardedParametersInput } from \"@copilotkit/runtime-client-gql\";\nimport { ReactNode } from \"react\";\nimport { AuthState } from \"../../context/copilot-context\";\n\n/**\n * Props for CopilotKit.\n */\n\nexport interface CopilotKitProps {\n /**\n * Your Copilot Cloud API key. Don't have it yet? Go to https://cloud.copilotkit.ai and get one for free.\n */\n publicApiKey?: string;\n\n /**\n * Restrict input to a specific topic.\n */\n cloudRestrictToTopic?: {\n validTopics?: string[];\n invalidTopics?: string[];\n };\n\n /**\n * The endpoint for the Copilot Runtime instance. [Click here for more information](/concepts/copilot-runtime).\n */\n runtimeUrl?: 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 *\n * For example:\n * ```json\n * {\n * \"Authorization\": \"Bearer X\"\n * }\n * ```\n */\n headers?: Record<string, string>;\n\n /**\n * The children to be rendered within the CopilotKit.\n */\n children: ReactNode;\n\n /**\n * Custom properties to be sent with the request\n * For example:\n * ```js\n * {\n * 'user_id': 'users_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 * Whether to show the dev console.\n *\n * If set to \"auto\", the dev console will be show on localhost only.\n */\n showDevConsole?: boolean | \"auto\";\n\n /**\n * The name of the agent to use.\n */\n agent?: string;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Pick<ForwardedParametersInput, \"temperature\">;\n\n /**\n * The auth config to use for the CopilotKit.\n */\n authConfig?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n /**\n * The thread id to use for the CopilotKit.\n */\n threadId?: string;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -144,16 +144,26 @@ var emptyCopilotContext = {
144
144
  },
145
145
  forwardedParameters: {},
146
146
  agentLock: null,
147
- threadId: null,
147
+ threadId: "",
148
148
  setThreadId: () => {
149
149
  },
150
150
  runId: null,
151
151
  setRunId: () => {
152
152
  },
153
153
  chatAbortControllerRef: { current: null },
154
- availableAgents: []
154
+ availableAgents: [],
155
+ extensions: {},
156
+ setExtensions: () => {
157
+ }
155
158
  };
156
159
  var CopilotContext = import_react.default.createContext(emptyCopilotContext);
160
+ function useCopilotContext() {
161
+ const context = import_react.default.useContext(CopilotContext);
162
+ if (context === emptyCopilotContext) {
163
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
164
+ }
165
+ return context;
166
+ }
157
167
  function returnAndThrowInDebug(_value) {
158
168
  throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
159
169
  }
@@ -371,10 +381,30 @@ var emptyCopilotContext2 = {
371
381
  var CopilotMessagesContext = import_react4.default.createContext(emptyCopilotContext2);
372
382
 
373
383
  // src/components/copilot-provider/copilot-messages.tsx
384
+ var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
374
385
  var import_jsx_runtime = require("react/jsx-runtime");
375
386
  function CopilotMessages(_a) {
376
387
  var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
377
388
  const [messages, setMessages] = (0, import_react5.useState)([]);
389
+ const { threadId, agentSession, runtimeClient } = useCopilotContext();
390
+ (0, import_react5.useEffect)(() => {
391
+ if (agentSession == null ? void 0 : agentSession.agentName) {
392
+ const fetchAgentState = () => __async(this, null, function* () {
393
+ var _a2, _b2, _c, _d;
394
+ const result = yield runtimeClient.loadAgentState({
395
+ threadId,
396
+ agentName: agentSession.agentName
397
+ });
398
+ if ((_b2 = (_a2 = result.data) == null ? void 0 : _a2.loadAgentState) == null ? void 0 : _b2.threadExists) {
399
+ const messages2 = (0, import_runtime_client_gql.loadMessagesFromJsonRepresentation)(
400
+ JSON.parse(((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.messages) || "[]")
401
+ );
402
+ setMessages(messages2);
403
+ }
404
+ });
405
+ void fetchAgentState();
406
+ }
407
+ }, [threadId, (agentSession == null ? void 0 : agentSession.agentName) !== void 0]);
378
408
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
379
409
  CopilotMessagesContext.Provider,
380
410
  {
@@ -632,13 +662,13 @@ function Toast({
632
662
  }
633
663
 
634
664
  // src/hooks/use-copilot-runtime-client.ts
635
- var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
665
+ var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
636
666
  var import_react8 = require("react");
637
667
  var useCopilotRuntimeClient = (options) => {
638
668
  const { addGraphQLErrorsToast } = useToast();
639
669
  const addErrorToast = useErrorToast();
640
670
  const runtimeClient = (0, import_react8.useMemo)(() => {
641
- return new import_runtime_client_gql.CopilotRuntimeClient(__spreadProps(__spreadValues({}, options), {
671
+ return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, options), {
642
672
  handleGQLErrors: (error) => {
643
673
  if (error.graphQLErrors.length) {
644
674
  addGraphQLErrorsToast(error.graphQLErrors);
@@ -719,6 +749,7 @@ function CopilotKitInternal(_a) {
719
749
  const [isLoading, setIsLoading] = (0, import_react10.useState)(false);
720
750
  const [chatInstructions, setChatInstructions] = (0, import_react10.useState)("");
721
751
  const [authStates, setAuthStates] = (0, import_react10.useState)({});
752
+ const [extensions, setExtensions] = (0, import_react10.useState)({});
722
753
  const {
723
754
  addElement: addDocument,
724
755
  removeElement: removeDocument,
@@ -903,7 +934,21 @@ ${nonDocumentStrings}`;
903
934
  };
904
935
  }
905
936
  const [agentSession, setAgentSession] = (0, import_react10.useState)(initialAgentSession);
906
- const [threadId, setThreadId] = (0, import_react10.useState)(null);
937
+ const [internalThreadId, setInternalThreadId] = (0, import_react10.useState)(props.threadId || (0, import_shared3.randomUUID)());
938
+ const setThreadId = (0, import_react10.useCallback)(
939
+ (value) => {
940
+ if (props.threadId) {
941
+ throw new Error("Cannot call setThreadId() when threadId is provided via props.");
942
+ }
943
+ setInternalThreadId(value);
944
+ },
945
+ [props.threadId]
946
+ );
947
+ (0, import_react10.useEffect)(() => {
948
+ if (props.threadId !== void 0) {
949
+ setInternalThreadId(props.threadId);
950
+ }
951
+ }, [props.threadId]);
907
952
  const [runId, setRunId] = (0, import_react10.useState)(null);
908
953
  const chatAbortControllerRef = (0, import_react10.useRef)(null);
909
954
  const showDevConsole = props.showDevConsole === void 0 ? "auto" : props.showDevConsole;
@@ -943,7 +988,7 @@ ${nonDocumentStrings}`;
943
988
  runtimeClient,
944
989
  forwardedParameters: props.forwardedParameters || {},
945
990
  agentLock: props.agent || null,
946
- threadId,
991
+ threadId: internalThreadId,
947
992
  setThreadId,
948
993
  runId,
949
994
  setRunId,
@@ -951,7 +996,9 @@ ${nonDocumentStrings}`;
951
996
  availableAgents,
952
997
  authConfig: props.authConfig,
953
998
  authStates,
954
- setAuthStates
999
+ setAuthStates,
1000
+ extensions,
1001
+ setExtensions
955
1002
  },
956
1003
  children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(CopilotMessages, { children })
957
1004
  }