@copilotkit/react-core 1.5.1-next.3 → 1.5.1-next.4
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 +11 -2
- package/package.json +5 -5
- package/dist/chunk-2KCEHGSI.mjs +0 -192
- package/dist/chunk-2KCEHGSI.mjs.map +0 -1
- package/dist/chunk-5FHSUKQL.mjs +0 -70
- package/dist/chunk-5FHSUKQL.mjs.map +0 -1
- package/dist/chunk-6OR25P32.mjs +0 -426
- package/dist/chunk-6OR25P32.mjs.map +0 -1
- package/dist/chunk-6U3UH3KO.mjs +0 -140
- package/dist/chunk-6U3UH3KO.mjs.map +0 -1
- package/dist/chunk-DCTJZ742.mjs +0 -22
- package/dist/chunk-DCTJZ742.mjs.map +0 -1
- package/dist/chunk-DDVXFNYA.mjs +0 -126
- package/dist/chunk-DDVXFNYA.mjs.map +0 -1
- package/dist/chunk-EFZPSZWO.mjs +0 -1
- package/dist/chunk-EFZPSZWO.mjs.map +0 -1
- package/dist/chunk-FXHKK52V.mjs +0 -119
- package/dist/chunk-FXHKK52V.mjs.map +0 -1
- package/dist/chunk-H4VZMKR6.mjs +0 -23
- package/dist/chunk-H4VZMKR6.mjs.map +0 -1
- package/dist/chunk-H7LSKIDK.mjs +0 -167
- package/dist/chunk-H7LSKIDK.mjs.map +0 -1
- package/dist/chunk-JDQCJCAQ.mjs +0 -295
- package/dist/chunk-JDQCJCAQ.mjs.map +0 -1
- package/dist/chunk-L34MHAXR.mjs +0 -1
- package/dist/chunk-L34MHAXR.mjs.map +0 -1
- package/dist/chunk-LODRWFMB.mjs +0 -75
- package/dist/chunk-LODRWFMB.mjs.map +0 -1
- package/dist/chunk-LUGEI4YQ.mjs +0 -1
- package/dist/chunk-LUGEI4YQ.mjs.map +0 -1
- package/dist/chunk-MLAS4QUR.mjs +0 -18
- package/dist/chunk-MLAS4QUR.mjs.map +0 -1
- package/dist/chunk-MWZO6TUR.mjs +0 -91
- package/dist/chunk-MWZO6TUR.mjs.map +0 -1
- package/dist/chunk-O7ARI5CV.mjs +0 -31
- package/dist/chunk-O7ARI5CV.mjs.map +0 -1
- package/dist/chunk-ODN4H66E.mjs +0 -31
- package/dist/chunk-ODN4H66E.mjs.map +0 -1
- package/dist/chunk-QDGDXRRJ.mjs +0 -28
- package/dist/chunk-QDGDXRRJ.mjs.map +0 -1
- package/dist/chunk-SKC7AJIV.mjs +0 -61
- package/dist/chunk-SKC7AJIV.mjs.map +0 -1
- package/dist/chunk-XINZBP3J.mjs +0 -49
- package/dist/chunk-XINZBP3J.mjs.map +0 -1
- package/dist/chunk-XXR4QFAQ.mjs +0 -29
- package/dist/chunk-XXR4QFAQ.mjs.map +0 -1
- package/dist/chunk-YPSGKPDA.mjs +0 -1
- package/dist/chunk-YPSGKPDA.mjs.map +0 -1
- package/dist/components/copilot-provider/copilot-messages.d.ts +0 -7
- package/dist/components/copilot-provider/copilot-messages.js +0 -80
- package/dist/components/copilot-provider/copilot-messages.js.map +0 -1
- package/dist/components/copilot-provider/copilot-messages.mjs +0 -9
- package/dist/components/copilot-provider/copilot-messages.mjs.map +0 -1
- package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -72
- package/dist/components/copilot-provider/copilotkit-props.js +0 -19
- package/dist/components/copilot-provider/copilotkit-props.js.map +0 -1
- package/dist/components/copilot-provider/copilotkit-props.mjs +0 -1
- package/dist/components/copilot-provider/copilotkit-props.mjs.map +0 -1
- package/dist/components/copilot-provider/copilotkit.d.ts +0 -9
- package/dist/components/copilot-provider/copilotkit.js +0 -861
- package/dist/components/copilot-provider/copilotkit.js.map +0 -1
- package/dist/components/copilot-provider/copilotkit.mjs +0 -21
- package/dist/components/copilot-provider/copilotkit.mjs.map +0 -1
- package/dist/components/copilot-provider/index.d.ts +0 -4
- package/dist/components/copilot-provider/index.js +0 -861
- package/dist/components/copilot-provider/index.js.map +0 -1
- package/dist/components/copilot-provider/index.mjs +0 -19
- package/dist/components/copilot-provider/index.mjs.map +0 -1
- package/dist/components/index.d.ts +0 -4
- package/dist/components/index.js +0 -861
- package/dist/components/index.js.map +0 -1
- package/dist/components/index.mjs +0 -19
- package/dist/components/index.mjs.map +0 -1
- package/dist/components/toast/exclamation-mark-icon.d.ts +0 -9
- package/dist/components/toast/exclamation-mark-icon.js +0 -55
- package/dist/components/toast/exclamation-mark-icon.js.map +0 -1
- package/dist/components/toast/exclamation-mark-icon.mjs +0 -8
- package/dist/components/toast/exclamation-mark-icon.mjs.map +0 -1
- package/dist/components/toast/toast-provider.d.ts +0 -29
- package/dist/components/toast/toast-provider.js +0 -255
- package/dist/components/toast/toast-provider.js.map +0 -1
- package/dist/components/toast/toast-provider.mjs +0 -11
- package/dist/components/toast/toast-provider.mjs.map +0 -1
- package/dist/context/copilot-context.d.ts +0 -109
- package/dist/context/copilot-context.js +0 -126
- package/dist/context/copilot-context.js.map +0 -1
- package/dist/context/copilot-context.mjs +0 -10
- package/dist/context/copilot-context.mjs.map +0 -1
- package/dist/context/copilot-messages-context.d.ts +0 -15
- package/dist/context/copilot-messages-context.js +0 -57
- package/dist/context/copilot-messages-context.js.map +0 -1
- package/dist/context/copilot-messages-context.mjs +0 -10
- package/dist/context/copilot-messages-context.mjs.map +0 -1
- package/dist/context/index.d.ts +0 -11
- package/dist/context/index.js +0 -149
- package/dist/context/index.js.map +0 -1
- package/dist/context/index.mjs +0 -17
- package/dist/context/index.mjs.map +0 -1
- package/dist/hooks/index.d.ts +0 -19
- package/dist/hooks/index.js +0 -897
- package/dist/hooks/index.js.map +0 -1
- package/dist/hooks/index.mjs +0 -44
- package/dist/hooks/index.mjs.map +0 -1
- package/dist/hooks/use-chat.d.ts +0 -92
- package/dist/hooks/use-chat.js +0 -360
- package/dist/hooks/use-chat.js.map +0 -1
- package/dist/hooks/use-chat.mjs +0 -11
- package/dist/hooks/use-chat.mjs.map +0 -1
- package/dist/hooks/use-coagent-state-render.d.ts +0 -60
- package/dist/hooks/use-coagent-state-render.js +0 -160
- package/dist/hooks/use-coagent-state-render.js.map +0 -1
- package/dist/hooks/use-coagent-state-render.mjs +0 -9
- package/dist/hooks/use-coagent-state-render.mjs.map +0 -1
- package/dist/hooks/use-coagent.d.ts +0 -186
- package/dist/hooks/use-coagent.js +0 -726
- package/dist/hooks/use-coagent.js.map +0 -1
- package/dist/hooks/use-coagent.mjs +0 -21
- package/dist/hooks/use-coagent.mjs.map +0 -1
- package/dist/hooks/use-copilot-action.d.ts +0 -130
- package/dist/hooks/use-copilot-action.js +0 -219
- package/dist/hooks/use-copilot-action.js.map +0 -1
- package/dist/hooks/use-copilot-action.mjs +0 -9
- package/dist/hooks/use-copilot-action.mjs.map +0 -1
- package/dist/hooks/use-copilot-chat.d.ts +0 -36
- package/dist/hooks/use-copilot-chat.js +0 -623
- package/dist/hooks/use-copilot-chat.js.map +0 -1
- package/dist/hooks/use-copilot-chat.mjs +0 -22
- package/dist/hooks/use-copilot-chat.mjs.map +0 -1
- package/dist/hooks/use-copilot-readable.d.ts +0 -33
- package/dist/hooks/use-copilot-readable.js +0 -146
- package/dist/hooks/use-copilot-readable.js.map +0 -1
- package/dist/hooks/use-copilot-readable.mjs +0 -9
- package/dist/hooks/use-copilot-readable.mjs.map +0 -1
- package/dist/hooks/use-copilot-runtime-client.d.ts +0 -5
- package/dist/hooks/use-copilot-runtime-client.js +0 -76
- package/dist/hooks/use-copilot-runtime-client.js.map +0 -1
- package/dist/hooks/use-copilot-runtime-client.mjs +0 -10
- package/dist/hooks/use-copilot-runtime-client.mjs.map +0 -1
- package/dist/hooks/use-flat-category-store.d.ts +0 -9
- package/dist/hooks/use-flat-category-store.js +0 -90
- package/dist/hooks/use-flat-category-store.js.map +0 -1
- package/dist/hooks/use-flat-category-store.mjs +0 -8
- package/dist/hooks/use-flat-category-store.mjs.map +0 -1
- package/dist/hooks/use-make-copilot-document-readable.d.ts +0 -12
- package/dist/hooks/use-make-copilot-document-readable.js +0 -141
- package/dist/hooks/use-make-copilot-document-readable.js.map +0 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +0 -9
- package/dist/hooks/use-make-copilot-document-readable.mjs.map +0 -1
- package/dist/hooks/use-tree.d.ts +0 -18
- package/dist/hooks/use-tree.js +0 -172
- package/dist/hooks/use-tree.js.map +0 -1
- package/dist/hooks/use-tree.mjs +0 -8
- package/dist/hooks/use-tree.mjs.map +0 -1
- package/dist/index.d.ts +0 -26
- package/dist/index.js +0 -1810
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -71
- package/dist/index.mjs.map +0 -1
- package/dist/lib/copilot-task.d.ts +0 -92
- package/dist/lib/copilot-task.js +0 -157
- package/dist/lib/copilot-task.js.map +0 -1
- package/dist/lib/copilot-task.mjs +0 -18
- package/dist/lib/copilot-task.mjs.map +0 -1
- package/dist/lib/index.d.ts +0 -11
- package/dist/lib/index.js +0 -159
- package/dist/lib/index.js.map +0 -1
- package/dist/lib/index.mjs +0 -19
- package/dist/lib/index.mjs.map +0 -1
- package/dist/types/chat-suggestion-configuration.d.ts +0 -22
- package/dist/types/chat-suggestion-configuration.js +0 -19
- package/dist/types/chat-suggestion-configuration.js.map +0 -1
- package/dist/types/chat-suggestion-configuration.mjs +0 -1
- package/dist/types/chat-suggestion-configuration.mjs.map +0 -1
- package/dist/types/coagent-action.d.ts +0 -29
- package/dist/types/coagent-action.js +0 -19
- package/dist/types/coagent-action.js.map +0 -1
- package/dist/types/coagent-action.mjs +0 -1
- package/dist/types/coagent-action.mjs.map +0 -1
- package/dist/types/coagent-state.d.ts +0 -11
- package/dist/types/coagent-state.js +0 -19
- package/dist/types/coagent-state.js.map +0 -1
- package/dist/types/coagent-state.mjs +0 -1
- package/dist/types/coagent-state.mjs.map +0 -1
- package/dist/types/document-pointer.d.ts +0 -9
- package/dist/types/document-pointer.js +0 -19
- package/dist/types/document-pointer.js.map +0 -1
- package/dist/types/document-pointer.mjs +0 -1
- package/dist/types/document-pointer.mjs.map +0 -1
- package/dist/types/frontend-action.d.ts +0 -107
- package/dist/types/frontend-action.js +0 -19
- package/dist/types/frontend-action.js.map +0 -1
- package/dist/types/frontend-action.mjs +0 -1
- package/dist/types/frontend-action.mjs.map +0 -1
- package/dist/types/index.d.ts +0 -6
- package/dist/types/index.js +0 -19
- package/dist/types/index.js.map +0 -1
- package/dist/types/index.mjs +0 -2
- package/dist/types/index.mjs.map +0 -1
- package/dist/types/system-message.d.ts +0 -3
- package/dist/types/system-message.js +0 -19
- package/dist/types/system-message.js.map +0 -1
- package/dist/types/system-message.mjs +0 -1
- package/dist/types/system-message.mjs.map +0 -1
- package/dist/utils/dev-console.d.ts +0 -3
- package/dist/utils/dev-console.js +0 -42
- package/dist/utils/dev-console.js.map +0 -1
- package/dist/utils/dev-console.mjs +0 -8
- package/dist/utils/dev-console.mjs.map +0 -1
- package/dist/utils/extract.d.ts +0 -42
- package/dist/utils/extract.js +0 -190
- package/dist/utils/extract.js.map +0 -1
- package/dist/utils/extract.mjs +0 -17
- package/dist/utils/extract.mjs.map +0 -1
- package/dist/utils/index.d.ts +0 -13
- package/dist/utils/index.js +0 -208
- package/dist/utils/index.js.map +0 -1
- package/dist/utils/index.mjs +0 -20
- package/dist/utils/index.mjs.map +0 -1
- package/dist/utils/utils.d.ts +0 -2
- package/dist/utils/utils.js +0 -19
- package/dist/utils/utils.js.map +0 -1
- package/dist/utils/utils.mjs +0 -1
- package/dist/utils/utils.mjs.map +0 -1
- package/dist/utils/utils.test.d.ts +0 -2
- package/dist/utils/utils.test.js +0 -9
- package/dist/utils/utils.test.js.map +0 -1
- package/dist/utils/utils.test.mjs +0 -7
- package/dist/utils/utils.test.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/use-copilot-chat.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-chat.ts","../../src/components/toast/toast-provider.tsx","../../src/hooks/use-copilot-runtime-client.ts","../../src/components/copilot-provider/copilotkit.tsx","../../src/context/copilot-messages-context.tsx"],"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 * ```\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 { useCopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\nimport { CoAgentStateRenderHandlerArguments } from \"@copilotkit/shared\";\nimport { useCopilotMessagesContext } from \"../context\";\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) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n isLoading: boolean;\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\n coagentStates,\n setCoagentStates,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\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 = useCallback(\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 } = 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 coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\n });\n\n // this is a workaround born out of a bug that Athena insessently 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 referecned 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 = useCallback(\n (message: Message) => {\n return latestAppend.current(message);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useCallback(() => {\n return 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 return {\n visibleMessages: messages,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n deleteMessage: latestDeleteFunc,\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.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } 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 { CopilotRuntimeClient } 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 = (props: ActionRenderProps<any>) => 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 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 agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n // runtime\n runtimeClient: CopilotRuntimeClient;\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\n agentSession: null,\n setAgentSession: () => {},\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 return value;\n}\n","import { useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n actionParametersToJsonSchema,\n CoAgentStateRenderHandler,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ResultMessage,\n convertMessagesToGqlInput,\n filterAdjacentAgentStateMessages,\n filterAgentStateMessages,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n ActionInputAvailability,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession } from \"../context/copilot-context\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n\n /**\n * Callback function to be called when a coagent action is received.\n */\n onCoAgentStateRender?: CoAgentStateRenderHandler;\n\n /**\n * Function definitions to be sent to the API.\n */\n actions: FrontendAction<any>[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * The current list of coagent states.\n */\n coagentStates: Record<string, CoagentState>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n\n /**\n * The current agent session.\n */\n agentSession: AgentSession | null;\n\n /**\n * setState-powered method to update the agent session\n */\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStates,\n coagentStates,\n agentSession,\n setAgentSession,\n } = options;\n\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const { addGraphQLErrorsToast } = useToast();\n\n const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();\n // We need to keep a ref of coagent states because of renderAndWait - making sure\n // the latest state is sent to the API\n // This is a workaround and needs to be addressed in the future\n const coagentStatesRef = useRef<Record<string, CoagentState>>(coagentStates);\n coagentStatesRef.current = coagentStates;\n const agentSessionRef = useRef<AgentSession | null>(agentSession);\n agentSessionRef.current = agentSession;\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = runtimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled || !action.disabled,\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined =\n ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n available,\n };\n }),\n url: window.location.href,\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: agentSessionRef.current,\n }\n : {}),\n agentStates: Object.values(coagentStatesRef.current).map((state) => ({\n agentName: state.name,\n state: JSON.stringify(state.state),\n })),\n },\n properties: copilotConfig.properties,\n signal: abortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let actionResults: { [id: string]: string } = {};\n let executedCoAgentStateRenders: string[] = [];\n let followUp: FrontendAction[\"followUp\"] = undefined;\n\n try {\n while (true) {\n let done, value;\n\n try {\n const readResult = await reader.read();\n done = readResult.done;\n value = readResult.value;\n } catch (readError) {\n break;\n }\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(\n filterAdjacentAgentStateMessages(value.generateCopilotResponse.messages),\n );\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n // execute regular action executions\n if (\n message.isActionExecutionMessage() &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in actionResults)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n try {\n // We update the message state before calling the handler so that the render\n // function can be called with `executing` state\n setMessages([...previousMessages, ...newMessages]);\n\n const action = actions.find((action) => action.name === message.name);\n\n if (action) {\n followUp = action.followUp;\n }\n\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n actionResults[message.id] = result;\n } catch (e) {\n actionResults[message.id] = `Failed to execute action ${message.name}`;\n console.error(`Failed to execute action ${message.name}: ${e}`);\n }\n }\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(actionResults[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n // execute coagent actions\n if (\n message.isAgentStateMessage() &&\n !message.active &&\n !executedCoAgentStateRenders.includes(message.id) &&\n onCoAgentStateRender\n ) {\n // Do not execute a coagent action if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute coagent action\n await onCoAgentStateRender({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoAgentStateRenders.push(message.id);\n }\n }\n\n const lastAgentStateMessage = [...messages]\n .reverse()\n .find((message) => message.isAgentStateMessage());\n\n if (lastAgentStateMessage) {\n setCoagentStates((prevAgentStates) => ({\n ...prevAgentStates,\n [lastAgentStateMessage.agentName]: {\n name: lastAgentStateMessage.agentName,\n state: lastAgentStateMessage.state,\n running: lastAgentStateMessage.running,\n active: lastAgentStateMessage.active,\n threadId: lastAgentStateMessage.threadId,\n nodeName: lastAgentStateMessage.nodeName,\n runId: lastAgentStateMessage.runId,\n },\n }));\n if (lastAgentStateMessage.running) {\n setAgentSession({\n threadId: lastAgentStateMessage.threadId,\n agentName: lastAgentStateMessage.agentName,\n nodeName: lastAgentStateMessage.nodeName,\n });\n } else {\n setAgentSession(null);\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Update message state\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n\n if (\n // if followUp is not explicitly false\n followUp !== false &&\n // if we have client side results\n (Object.values(actionResults).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1].isResultMessage()))\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletionRef.current!([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n runChatCompletionRef.current = runChatCompletion;\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletionRef.current!(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage.isTextMessage() && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n","import { useCopilotContext } from \"../../context\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { ExclamationMarkIcon } from \"./exclamation-mark-icon\";\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: Omit<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\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 addToast = useCallback((toast: Omit<Toast, \"id\">) => {\n const id = Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => [...currentToasts, { ...toast, id }]);\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n }, []);\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // We do not display these errors unless we are in dev mode.\n // if (!showDevConsole) {\n // return;\n // }\n\n const errorsToRender = errors.map((error, idx) => {\n const message = error.message;\n const code = error.extensions?.code as string;\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 Cloud Error:{\" \"}\n <span style={{ fontFamily: \"monospace\", fontWeight: \"normal\" }}>{code}</span>\n </div>\n )}\n <div>{message}</div>\n </div>\n );\n });\n\n addToast({\n type: \"error\",\n message: (\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 is a Copilot Cloud error, and it only displays during local development.\n </div>\n </div>\n ),\n });\n }, []);\n\n const removeToast = useCallback((id: string) => {\n setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n };\n\n return (\n <ToastContext.Provider value={value}>\n <div\n style={{\n position: \"fixed\",\n bottom: \"1rem\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 50,\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.5rem\",\n }}\n >\n {toasts.length > 1 && (\n <div style={{ textAlign: \"right\" }}>\n <button\n onClick={() => setToasts([])}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n cursor: \"pointer\",\n background: \"white\",\n border: \"1px solid rgba(0,0,0,0.2)\",\n borderRadius: \"4px\",\n }}\n >\n Close All\n </button>\n </div>\n )}\n {toasts.map((toast) => (\n <Toast\n key={toast.id}\n message={toast.message}\n type={toast.type}\n onClose={() => removeToast(toast.id)}\n />\n ))}\n </div>\n {children}\n </ToastContext.Provider>\n );\n}\n\nfunction Toast({\n message,\n type = \"info\",\n onClose,\n}: {\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n onClose: () => void;\n}) {\n const bgColors = {\n info: \"#3b82f6\",\n success: \"#22c55e\",\n warning: \"#eab308\",\n error: \"#ef4444\",\n };\n\n return (\n <div\n style={{\n backgroundColor: bgColors[type],\n color: \"white\",\n padding: \"0.5rem 1rem\",\n borderRadius: \"0.25rem\",\n boxShadow: \"0 2px 4px rgba(0,0,0,0.1)\",\n position: \"relative\",\n minWidth: \"200px\",\n }}\n >\n <div>{message}</div>\n <button\n onClick={onClose}\n style={{\n position: \"absolute\",\n top: \"0\",\n right: \"0\",\n background: \"none\",\n border: \"none\",\n color: \"white\",\n cursor: \"pointer\",\n padding: \"0.5rem\",\n fontSize: \"1rem\",\n }}\n >\n ✕\n </button>\n </div>\n );\n}\n","import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo } from \"react\";\n\nexport const useCopilotRuntimeClient = (options: CopilotRuntimeClientOptions) => {\n const { addGraphQLErrorsToast } = useToast();\n\n const runtimeClient = useMemo(() => {\n return new CopilotRuntimeClient({\n ...options,\n handleGQLErrors: (error) => {\n if ((error as any).graphQLErrors.length) {\n addGraphQLErrorsToast((error as any).graphQLErrors as GraphQLError[]);\n }\n },\n });\n }, [options, addGraphQLErrorsToast]);\n\n return runtimeClient;\n};\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n} from \"@copilotkit/shared\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"../../hooks/use-copilot-runtime-client\";\nimport { shouldShowDevConsole } from \"../../utils\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n const enabled = shouldShowDevConsole(showDevConsole);\n return (\n <ToastProvider enabled={enabled}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.publicApiKey) {\n throw new Error(\n \"Please provide either a runtimeUrl or a publicApiKey to the CopilotKit component.\",\n );\n }\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n const { addElement, removeElement, printTree } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => {\n return {\n ...prevPoints,\n [id]: stateRender,\n };\n });\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n props.publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n ]);\n\n const headers = {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n });\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n };\n\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\n runtimeClient,\n }}\n >\n <CopilotMessages>{children}</CopilotMessages>\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ messages, name, args }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n","/**\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;AAAA;AAwCA,IAAAA,gBAA+C;;;ACtC/C,mBAAkB;AA2IlB,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,IACz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CAAC;AAEV,SAAO;AACT;AAEO,SAAS,qBACd,eACA,wBACQ;AACR,SACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAUG,yBAAyB;AAAA;AAAA,EAAO,2BAA2B;AAEhE;","names":["import_react","React","import_runtime_client_gql","import_react","import_runtime_client_gql","import_react","import_react","messages","action","import_react","import_shared","import_react","emptyCopilotContext","React","import_jsx_runtime","_a","action","messages"]}
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
defaultSystemMessage,
|
|
3
|
-
useCopilotChat
|
|
4
|
-
} from "../chunk-H7LSKIDK.mjs";
|
|
5
|
-
import "../chunk-JDQCJCAQ.mjs";
|
|
6
|
-
import "../chunk-YPSGKPDA.mjs";
|
|
7
|
-
import "../chunk-6OR25P32.mjs";
|
|
8
|
-
import "../chunk-5FHSUKQL.mjs";
|
|
9
|
-
import "../chunk-6U3UH3KO.mjs";
|
|
10
|
-
import "../chunk-XXR4QFAQ.mjs";
|
|
11
|
-
import "../chunk-ODN4H66E.mjs";
|
|
12
|
-
import "../chunk-2KCEHGSI.mjs";
|
|
13
|
-
import "../chunk-O7ARI5CV.mjs";
|
|
14
|
-
import "../chunk-LODRWFMB.mjs";
|
|
15
|
-
import "../chunk-DCTJZ742.mjs";
|
|
16
|
-
import "../chunk-MLAS4QUR.mjs";
|
|
17
|
-
import "../chunk-SKC7AJIV.mjs";
|
|
18
|
-
export {
|
|
19
|
-
defaultSystemMessage,
|
|
20
|
-
useCopilotChat
|
|
21
|
-
};
|
|
22
|
-
//# sourceMappingURL=use-copilot-chat.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Options for the useCopilotReadable hook.
|
|
3
|
-
*/
|
|
4
|
-
interface UseCopilotReadableOptions {
|
|
5
|
-
/**
|
|
6
|
-
* The description of the information to be added to the Copilot context.
|
|
7
|
-
*/
|
|
8
|
-
description: string;
|
|
9
|
-
/**
|
|
10
|
-
* The value to be added to the Copilot context. Object values are automatically stringified.
|
|
11
|
-
*/
|
|
12
|
-
value: any;
|
|
13
|
-
/**
|
|
14
|
-
* The ID of the parent context, if any.
|
|
15
|
-
*/
|
|
16
|
-
parentId?: string;
|
|
17
|
-
/**
|
|
18
|
-
* An array of categories to control which context are visible where. Particularly useful
|
|
19
|
-
* with CopilotTextarea (see `useMakeAutosuggestionFunction`)
|
|
20
|
-
*/
|
|
21
|
-
categories?: string[];
|
|
22
|
-
/**
|
|
23
|
-
* A custom conversion function to use to serialize the value to a string. If not provided, the value
|
|
24
|
-
* will be serialized using `JSON.stringify`.
|
|
25
|
-
*/
|
|
26
|
-
convert?: (description: string, value: any) => string;
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* Adds the given information to the Copilot context to make it readable by Copilot.
|
|
30
|
-
*/
|
|
31
|
-
declare function useCopilotReadable({ description, value, parentId, categories, convert }: UseCopilotReadableOptions, dependencies?: any[]): string | undefined;
|
|
32
|
-
|
|
33
|
-
export { UseCopilotReadableOptions, useCopilotReadable };
|
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
-
};
|
|
12
|
-
var __copyProps = (to, from, except, desc) => {
|
|
13
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
-
for (let key of __getOwnPropNames(from))
|
|
15
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
-
}
|
|
18
|
-
return to;
|
|
19
|
-
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
28
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
var __async = (__this, __arguments, generator) => {
|
|
30
|
-
return new Promise((resolve, reject) => {
|
|
31
|
-
var fulfilled = (value) => {
|
|
32
|
-
try {
|
|
33
|
-
step(generator.next(value));
|
|
34
|
-
} catch (e) {
|
|
35
|
-
reject(e);
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
var rejected = (value) => {
|
|
39
|
-
try {
|
|
40
|
-
step(generator.throw(value));
|
|
41
|
-
} catch (e) {
|
|
42
|
-
reject(e);
|
|
43
|
-
}
|
|
44
|
-
};
|
|
45
|
-
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
46
|
-
step((generator = generator.apply(__this, __arguments)).next());
|
|
47
|
-
});
|
|
48
|
-
};
|
|
49
|
-
|
|
50
|
-
// src/hooks/use-copilot-readable.ts
|
|
51
|
-
var use_copilot_readable_exports = {};
|
|
52
|
-
__export(use_copilot_readable_exports, {
|
|
53
|
-
useCopilotReadable: () => useCopilotReadable
|
|
54
|
-
});
|
|
55
|
-
module.exports = __toCommonJS(use_copilot_readable_exports);
|
|
56
|
-
var import_react2 = require("react");
|
|
57
|
-
|
|
58
|
-
// src/context/copilot-context.tsx
|
|
59
|
-
var import_react = __toESM(require("react"));
|
|
60
|
-
var emptyCopilotContext = {
|
|
61
|
-
actions: {},
|
|
62
|
-
setAction: () => {
|
|
63
|
-
},
|
|
64
|
-
removeAction: () => {
|
|
65
|
-
},
|
|
66
|
-
coAgentStateRenders: {},
|
|
67
|
-
setCoAgentStateRender: () => {
|
|
68
|
-
},
|
|
69
|
-
removeCoAgentStateRender: () => {
|
|
70
|
-
},
|
|
71
|
-
chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
|
|
72
|
-
getContextString: (documents, categories) => returnAndThrowInDebug(""),
|
|
73
|
-
addContext: () => "",
|
|
74
|
-
removeContext: () => {
|
|
75
|
-
},
|
|
76
|
-
getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
|
|
77
|
-
})),
|
|
78
|
-
isLoading: false,
|
|
79
|
-
setIsLoading: () => returnAndThrowInDebug(false),
|
|
80
|
-
chatInstructions: "",
|
|
81
|
-
setChatInstructions: () => returnAndThrowInDebug(""),
|
|
82
|
-
getDocumentsContext: (categories) => returnAndThrowInDebug([]),
|
|
83
|
-
addDocumentContext: () => returnAndThrowInDebug(""),
|
|
84
|
-
removeDocumentContext: () => {
|
|
85
|
-
},
|
|
86
|
-
runtimeClient: {},
|
|
87
|
-
copilotApiConfig: new class {
|
|
88
|
-
get chatApiEndpoint() {
|
|
89
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
90
|
-
}
|
|
91
|
-
get headers() {
|
|
92
|
-
return {};
|
|
93
|
-
}
|
|
94
|
-
get body() {
|
|
95
|
-
return {};
|
|
96
|
-
}
|
|
97
|
-
}(),
|
|
98
|
-
chatSuggestionConfiguration: {},
|
|
99
|
-
addChatSuggestionConfiguration: () => {
|
|
100
|
-
},
|
|
101
|
-
removeChatSuggestionConfiguration: () => {
|
|
102
|
-
},
|
|
103
|
-
showDevConsole: "auto",
|
|
104
|
-
coagentStates: {},
|
|
105
|
-
setCoagentStates: () => {
|
|
106
|
-
},
|
|
107
|
-
agentSession: null,
|
|
108
|
-
setAgentSession: () => {
|
|
109
|
-
}
|
|
110
|
-
};
|
|
111
|
-
var CopilotContext = import_react.default.createContext(emptyCopilotContext);
|
|
112
|
-
function useCopilotContext() {
|
|
113
|
-
const context = import_react.default.useContext(CopilotContext);
|
|
114
|
-
if (context === emptyCopilotContext) {
|
|
115
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
116
|
-
}
|
|
117
|
-
return context;
|
|
118
|
-
}
|
|
119
|
-
function returnAndThrowInDebug(value) {
|
|
120
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
121
|
-
return value;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
// src/hooks/use-copilot-readable.ts
|
|
125
|
-
function convertToJSON(description, value) {
|
|
126
|
-
return `${description}: ${typeof value === "string" ? value : JSON.stringify(value)}`;
|
|
127
|
-
}
|
|
128
|
-
function useCopilotReadable({ description, value, parentId, categories, convert }, dependencies) {
|
|
129
|
-
const { addContext, removeContext } = useCopilotContext();
|
|
130
|
-
const idRef = (0, import_react2.useRef)();
|
|
131
|
-
convert = convert || convertToJSON;
|
|
132
|
-
const information = convert(description, value);
|
|
133
|
-
(0, import_react2.useEffect)(() => {
|
|
134
|
-
const id = addContext(information, parentId, categories);
|
|
135
|
-
idRef.current = id;
|
|
136
|
-
return () => {
|
|
137
|
-
removeContext(id);
|
|
138
|
-
};
|
|
139
|
-
}, [information, parentId, addContext, removeContext, ...dependencies || []]);
|
|
140
|
-
return idRef.current;
|
|
141
|
-
}
|
|
142
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
143
|
-
0 && (module.exports = {
|
|
144
|
-
useCopilotReadable
|
|
145
|
-
});
|
|
146
|
-
//# sourceMappingURL=use-copilot-readable.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/use-copilot-readable.ts","../../src/context/copilot-context.tsx"],"sourcesContent":["/**\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotReadable accepts a single string argument\n * representing any piece of app state, making it available for the Copilot to use\n * as context when responding to user input.\n *\n * ```tsx\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotReadable({\n * description: \"The list of employees\",\n * value: employees,\n * });\n * }\n * ```\n *\n * ### Nested Components\n *\n * Optionally, you can maintain the hierarchical structure of information by passing\n * `parentId`. This allows you to use `useCopilotReadable` in nested components:\n *\n * ```tsx /employeeContextId/1 {17,23}\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * function Employee(props: EmployeeProps) {\n * const { employeeName, workProfile, metadata } = props;\n *\n * // propagate any information to copilot\n * const employeeContextId = useCopilotReadable({\n * description: \"Employee name\",\n * value: employeeName\n * });\n *\n * // Pass a parentID to maintain a hierarchical structure.\n * // Especially useful with child React components, list elements, etc.\n * useCopilotReadable({\n * description: \"Work profile\",\n * value: workProfile.description(),\n * parentId: employeeContextId\n * });\n *\n * useCopilotReadable({\n * description: \"Employee metadata\",\n * value: metadata.description(),\n * parentId: employeeContextId\n * });\n *\n * return (\n * // Render as usual...\n * );\n * }\n * ```\n */\nimport { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context. Object values are automatically stringified.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\nfunction convertToJSON(description: string, value: any): string {\n return `${description}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n { description, value, parentId, categories, convert }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { addContext, removeContext } = useCopilotContext();\n const idRef = useRef<string>();\n convert = convert || convertToJSON;\n\n const information = convert(description, value);\n\n useEffect(() => {\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [information, parentId, addContext, removeContext, ...(dependencies || [])]);\n\n return idRef.current;\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } 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 { CopilotRuntimeClient } 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 = (props: ActionRenderProps<any>) => 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 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 agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n // runtime\n runtimeClient: CopilotRuntimeClient;\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\n agentSession: null,\n setAgentSession: () => {},\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 return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA+DA,IAAAA,gBAAkC;;;AC7DlC,mBAAkB;AA2IlB,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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AAY,eAAe,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAE9E,SAAO,MAAM;AACf;","names":["import_react","React"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __defProps = Object.defineProperties;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
6
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
8
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
-
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
10
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
11
|
-
var __spreadValues = (a, b) => {
|
|
12
|
-
for (var prop in b || (b = {}))
|
|
13
|
-
if (__hasOwnProp.call(b, prop))
|
|
14
|
-
__defNormalProp(a, prop, b[prop]);
|
|
15
|
-
if (__getOwnPropSymbols)
|
|
16
|
-
for (var prop of __getOwnPropSymbols(b)) {
|
|
17
|
-
if (__propIsEnum.call(b, prop))
|
|
18
|
-
__defNormalProp(a, prop, b[prop]);
|
|
19
|
-
}
|
|
20
|
-
return a;
|
|
21
|
-
};
|
|
22
|
-
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
23
|
-
var __export = (target, all) => {
|
|
24
|
-
for (var name in all)
|
|
25
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
26
|
-
};
|
|
27
|
-
var __copyProps = (to, from, except, desc) => {
|
|
28
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
29
|
-
for (let key of __getOwnPropNames(from))
|
|
30
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
31
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
32
|
-
}
|
|
33
|
-
return to;
|
|
34
|
-
};
|
|
35
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
36
|
-
|
|
37
|
-
// src/hooks/use-copilot-runtime-client.ts
|
|
38
|
-
var use_copilot_runtime_client_exports = {};
|
|
39
|
-
__export(use_copilot_runtime_client_exports, {
|
|
40
|
-
useCopilotRuntimeClient: () => useCopilotRuntimeClient
|
|
41
|
-
});
|
|
42
|
-
module.exports = __toCommonJS(use_copilot_runtime_client_exports);
|
|
43
|
-
var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
|
|
44
|
-
|
|
45
|
-
// src/components/toast/toast-provider.tsx
|
|
46
|
-
var import_react = require("react");
|
|
47
|
-
var import_jsx_runtime = require("react/jsx-runtime");
|
|
48
|
-
var ToastContext = (0, import_react.createContext)(void 0);
|
|
49
|
-
function useToast() {
|
|
50
|
-
const context = (0, import_react.useContext)(ToastContext);
|
|
51
|
-
if (!context) {
|
|
52
|
-
throw new Error("useToast must be used within a ToastProvider");
|
|
53
|
-
}
|
|
54
|
-
return context;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// src/hooks/use-copilot-runtime-client.ts
|
|
58
|
-
var import_react2 = require("react");
|
|
59
|
-
var useCopilotRuntimeClient = (options) => {
|
|
60
|
-
const { addGraphQLErrorsToast } = useToast();
|
|
61
|
-
const runtimeClient = (0, import_react2.useMemo)(() => {
|
|
62
|
-
return new import_runtime_client_gql.CopilotRuntimeClient(__spreadProps(__spreadValues({}, options), {
|
|
63
|
-
handleGQLErrors: (error) => {
|
|
64
|
-
if (error.graphQLErrors.length) {
|
|
65
|
-
addGraphQLErrorsToast(error.graphQLErrors);
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
}));
|
|
69
|
-
}, [options, addGraphQLErrorsToast]);
|
|
70
|
-
return runtimeClient;
|
|
71
|
-
};
|
|
72
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
73
|
-
0 && (module.exports = {
|
|
74
|
-
useCopilotRuntimeClient
|
|
75
|
-
});
|
|
76
|
-
//# sourceMappingURL=use-copilot-runtime-client.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/use-copilot-runtime-client.ts","../../src/components/toast/toast-provider.tsx"],"sourcesContent":["import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo } from \"react\";\n\nexport const useCopilotRuntimeClient = (options: CopilotRuntimeClientOptions) => {\n const { addGraphQLErrorsToast } = useToast();\n\n const runtimeClient = useMemo(() => {\n return new CopilotRuntimeClient({\n ...options,\n handleGQLErrors: (error) => {\n if ((error as any).graphQLErrors.length) {\n addGraphQLErrorsToast((error as any).graphQLErrors as GraphQLError[]);\n }\n },\n });\n }, [options, addGraphQLErrorsToast]);\n\n return runtimeClient;\n};\n","import { useCopilotContext } from \"../../context\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { ExclamationMarkIcon } from \"./exclamation-mark-icon\";\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: Omit<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\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 addToast = useCallback((toast: Omit<Toast, \"id\">) => {\n const id = Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => [...currentToasts, { ...toast, id }]);\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n }, []);\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // We do not display these errors unless we are in dev mode.\n // if (!showDevConsole) {\n // return;\n // }\n\n const errorsToRender = errors.map((error, idx) => {\n const message = error.message;\n const code = error.extensions?.code as string;\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 Cloud Error:{\" \"}\n <span style={{ fontFamily: \"monospace\", fontWeight: \"normal\" }}>{code}</span>\n </div>\n )}\n <div>{message}</div>\n </div>\n );\n });\n\n addToast({\n type: \"error\",\n message: (\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 is a Copilot Cloud error, and it only displays during local development.\n </div>\n </div>\n ),\n });\n }, []);\n\n const removeToast = useCallback((id: string) => {\n setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n };\n\n return (\n <ToastContext.Provider value={value}>\n <div\n style={{\n position: \"fixed\",\n bottom: \"1rem\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 50,\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.5rem\",\n }}\n >\n {toasts.length > 1 && (\n <div style={{ textAlign: \"right\" }}>\n <button\n onClick={() => setToasts([])}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n cursor: \"pointer\",\n background: \"white\",\n border: \"1px solid rgba(0,0,0,0.2)\",\n borderRadius: \"4px\",\n }}\n >\n Close All\n </button>\n </div>\n )}\n {toasts.map((toast) => (\n <Toast\n key={toast.id}\n message={toast.message}\n type={toast.type}\n onClose={() => removeToast(toast.id)}\n />\n ))}\n </div>\n {children}\n </ToastContext.Provider>\n );\n}\n\nfunction Toast({\n message,\n type = \"info\",\n onClose,\n}: {\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n onClose: () => void;\n}) {\n const bgColors = {\n info: \"#3b82f6\",\n success: \"#22c55e\",\n warning: \"#eab308\",\n error: \"#ef4444\",\n };\n\n return (\n <div\n style={{\n backgroundColor: bgColors[type],\n color: \"white\",\n padding: \"0.5rem 1rem\",\n borderRadius: \"0.25rem\",\n boxShadow: \"0 2px 4px rgba(0,0,0,0.1)\",\n position: \"relative\",\n minWidth: \"200px\",\n }}\n >\n <div>{message}</div>\n <button\n onClick={onClose}\n style={{\n position: \"absolute\",\n top: \"0\",\n right: \"0\",\n background: \"none\",\n border: \"none\",\n color: \"white\",\n cursor: \"pointer\",\n padding: \"0.5rem\",\n fontSize: \"1rem\",\n }}\n >\n ✕\n </button>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAIO;;;ACFP,mBAAwE;AAkE9D;AAhDV,IAAM,mBAAe,4BAA6C,MAAS;AAEpE,SAAS,WAAW;AACzB,QAAM,cAAU,yBAAW,YAAY;AACvC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AACA,SAAO;AACT;;;ADtBA,IAAAA,gBAAwB;AAEjB,IAAM,0BAA0B,CAAC,YAAyC;AAC/E,QAAM,EAAE,sBAAsB,IAAI,SAAS;AAE3C,QAAM,oBAAgB,uBAAQ,MAAM;AAClC,WAAO,IAAI,+CAAqB,iCAC3B,UAD2B;AAAA,MAE9B,iBAAiB,CAAC,UAAU;AAC1B,YAAK,MAAc,cAAc,QAAQ;AACvC,gCAAuB,MAAc,aAA+B;AAAA,QACtE;AAAA,MACF;AAAA,IACF,EAAC;AAAA,EACH,GAAG,CAAC,SAAS,qBAAqB,CAAC;AAEnC,SAAO;AACT;","names":["import_react"]}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
useCopilotRuntimeClient
|
|
3
|
-
} from "../chunk-ODN4H66E.mjs";
|
|
4
|
-
import "../chunk-2KCEHGSI.mjs";
|
|
5
|
-
import "../chunk-O7ARI5CV.mjs";
|
|
6
|
-
import "../chunk-SKC7AJIV.mjs";
|
|
7
|
-
export {
|
|
8
|
-
useCopilotRuntimeClient
|
|
9
|
-
};
|
|
10
|
-
//# sourceMappingURL=use-copilot-runtime-client.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
type FlatCategoryStoreId = string;
|
|
2
|
-
interface UseFlatCategoryStoreReturn<T> {
|
|
3
|
-
addElement: (value: T, categories: string[]) => FlatCategoryStoreId;
|
|
4
|
-
removeElement: (id: FlatCategoryStoreId) => void;
|
|
5
|
-
allElements: (categories: string[]) => T[];
|
|
6
|
-
}
|
|
7
|
-
declare const useFlatCategoryStore: <T>() => UseFlatCategoryStoreReturn<T>;
|
|
8
|
-
|
|
9
|
-
export { FlatCategoryStoreId, UseFlatCategoryStoreReturn, useFlatCategoryStore as default };
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
|
-
var __copyProps = (to, from, except, desc) => {
|
|
11
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
-
for (let key of __getOwnPropNames(from))
|
|
13
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
-
|
|
20
|
-
// src/hooks/use-flat-category-store.ts
|
|
21
|
-
var use_flat_category_store_exports = {};
|
|
22
|
-
__export(use_flat_category_store_exports, {
|
|
23
|
-
default: () => use_flat_category_store_default
|
|
24
|
-
});
|
|
25
|
-
module.exports = __toCommonJS(use_flat_category_store_exports);
|
|
26
|
-
var import_react = require("react");
|
|
27
|
-
var import_shared = require("@copilotkit/shared");
|
|
28
|
-
var useFlatCategoryStore = () => {
|
|
29
|
-
const [elements, dispatch] = (0, import_react.useReducer)(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
|
|
30
|
-
const addElement = (0, import_react.useCallback)((value, categories) => {
|
|
31
|
-
const newId = (0, import_shared.randomId)();
|
|
32
|
-
dispatch({
|
|
33
|
-
type: "ADD_ELEMENT",
|
|
34
|
-
value,
|
|
35
|
-
id: newId,
|
|
36
|
-
categories
|
|
37
|
-
});
|
|
38
|
-
return newId;
|
|
39
|
-
}, []);
|
|
40
|
-
const removeElement = (0, import_react.useCallback)((id) => {
|
|
41
|
-
dispatch({ type: "REMOVE_ELEMENT", id });
|
|
42
|
-
}, []);
|
|
43
|
-
const allElements = (0, import_react.useCallback)(
|
|
44
|
-
(categories) => {
|
|
45
|
-
const categoriesSet = new Set(categories);
|
|
46
|
-
const result = [];
|
|
47
|
-
elements.forEach((element) => {
|
|
48
|
-
if (setsHaveIntersection(categoriesSet, element.categories)) {
|
|
49
|
-
result.push(element.value);
|
|
50
|
-
}
|
|
51
|
-
});
|
|
52
|
-
return result;
|
|
53
|
-
},
|
|
54
|
-
[elements]
|
|
55
|
-
);
|
|
56
|
-
return { addElement, removeElement, allElements };
|
|
57
|
-
};
|
|
58
|
-
var use_flat_category_store_default = useFlatCategoryStore;
|
|
59
|
-
function flatCategoryStoreReducer(state, action) {
|
|
60
|
-
switch (action.type) {
|
|
61
|
-
case "ADD_ELEMENT": {
|
|
62
|
-
const { value, id, categories } = action;
|
|
63
|
-
const newElement = {
|
|
64
|
-
id,
|
|
65
|
-
value,
|
|
66
|
-
categories: new Set(categories)
|
|
67
|
-
};
|
|
68
|
-
const newState = new Map(state);
|
|
69
|
-
newState.set(id, newElement);
|
|
70
|
-
return newState;
|
|
71
|
-
}
|
|
72
|
-
case "REMOVE_ELEMENT": {
|
|
73
|
-
const newState = new Map(state);
|
|
74
|
-
newState.delete(action.id);
|
|
75
|
-
return newState;
|
|
76
|
-
}
|
|
77
|
-
default:
|
|
78
|
-
return state;
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
function setsHaveIntersection(setA, setB) {
|
|
82
|
-
const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
|
|
83
|
-
for (let item of smallerSet) {
|
|
84
|
-
if (largerSet.has(item)) {
|
|
85
|
-
return true;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
return false;
|
|
89
|
-
}
|
|
90
|
-
//# sourceMappingURL=use-flat-category-store.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/use-flat-category-store.ts"],"sourcesContent":["import { useCallback, useReducer } from \"react\";\nimport { randomId } from \"@copilotkit/shared\";\n\nexport type FlatCategoryStoreId = string;\n\nexport interface UseFlatCategoryStoreReturn<T> {\n addElement: (value: T, categories: string[]) => FlatCategoryStoreId;\n removeElement: (id: FlatCategoryStoreId) => void;\n allElements: (categories: string[]) => T[];\n}\n\ninterface FlatCategoryStoreElement<T> {\n id: FlatCategoryStoreId;\n value: T;\n categories: Set<string>;\n}\n\nconst useFlatCategoryStore = <T>(): UseFlatCategoryStoreReturn<T> => {\n const [elements, dispatch] = useReducer<\n React.Reducer<Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>, Action<T>>\n >(flatCategoryStoreReducer, new Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>());\n\n const addElement = useCallback((value: T, categories: string[]): FlatCategoryStoreId => {\n const newId = randomId();\n dispatch({\n type: \"ADD_ELEMENT\",\n value,\n id: newId,\n categories,\n });\n return newId;\n }, []);\n\n const removeElement = useCallback((id: FlatCategoryStoreId): void => {\n dispatch({ type: \"REMOVE_ELEMENT\", id });\n }, []);\n\n const allElements = useCallback(\n (categories: string[]): T[] => {\n const categoriesSet = new Set(categories);\n const result: T[] = [];\n elements.forEach((element) => {\n if (setsHaveIntersection(categoriesSet, element.categories)) {\n result.push(element.value);\n }\n });\n return result;\n },\n [elements],\n );\n\n return { addElement, removeElement, allElements };\n};\n\nexport default useFlatCategoryStore;\n\n// Action types\ntype Action<T> =\n | {\n type: \"ADD_ELEMENT\";\n value: T;\n id: FlatCategoryStoreId;\n categories: string[];\n }\n | { type: \"REMOVE_ELEMENT\"; id: FlatCategoryStoreId };\n\n// Reducer\nfunction flatCategoryStoreReducer<T>(\n state: Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>,\n action: Action<T>,\n): Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>> {\n switch (action.type) {\n case \"ADD_ELEMENT\": {\n const { value, id, categories } = action;\n const newElement: FlatCategoryStoreElement<T> = {\n id,\n value,\n categories: new Set(categories),\n };\n const newState = new Map(state);\n newState.set(id, newElement);\n return newState;\n }\n case \"REMOVE_ELEMENT\": {\n const newState = new Map(state);\n newState.delete(action.id);\n return newState;\n }\n default:\n return state;\n }\n}\n\nfunction setsHaveIntersection<T>(setA: Set<T>, setB: Set<T>): boolean {\n const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];\n\n for (let item of smallerSet) {\n if (largerSet.has(item)) {\n return true;\n }\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAwC;AACxC,oBAAyB;AAgBzB,IAAM,uBAAuB,MAAwC;AACnE,QAAM,CAAC,UAAU,QAAQ,QAAI,yBAE3B,0BAA0B,oBAAI,IAAsD,CAAC;AAEvF,QAAM,iBAAa,0BAAY,CAAC,OAAU,eAA8C;AACtF,UAAM,YAAQ,wBAAS;AACvB,aAAS;AAAA,MACP,MAAM;AAAA,MACN;AAAA,MACA,IAAI;AAAA,MACJ;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,QAAM,oBAAgB,0BAAY,CAAC,OAAkC;AACnE,aAAS,EAAE,MAAM,kBAAkB,GAAG,CAAC;AAAA,EACzC,GAAG,CAAC,CAAC;AAEL,QAAM,kBAAc;AAAA,IAClB,CAAC,eAA8B;AAC7B,YAAM,gBAAgB,IAAI,IAAI,UAAU;AACxC,YAAM,SAAc,CAAC;AACrB,eAAS,QAAQ,CAAC,YAAY;AAC5B,YAAI,qBAAqB,eAAe,QAAQ,UAAU,GAAG;AAC3D,iBAAO,KAAK,QAAQ,KAAK;AAAA,QAC3B;AAAA,MACF,CAAC;AACD,aAAO;AAAA,IACT;AAAA,IACA,CAAC,QAAQ;AAAA,EACX;AAEA,SAAO,EAAE,YAAY,eAAe,YAAY;AAClD;AAEA,IAAO,kCAAQ;AAaf,SAAS,yBACP,OACA,QACuD;AACvD,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK,eAAe;AAClB,YAAM,EAAE,OAAO,IAAI,WAAW,IAAI;AAClC,YAAM,aAA0C;AAAA,QAC9C;AAAA,QACA;AAAA,QACA,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