@copilotkit/react-core 1.5.1-next.1 → 1.5.1-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/{chunk-SFPANIOY.mjs → chunk-2KCEHGSI.mjs} +49 -99
  3. package/dist/chunk-2KCEHGSI.mjs.map +1 -0
  4. package/dist/{chunk-YL6V3QTN.mjs → chunk-6OR25P32.mjs} +15 -42
  5. package/dist/chunk-6OR25P32.mjs.map +1 -0
  6. package/dist/{chunk-VQDGBYWQ.mjs → chunk-DDVXFNYA.mjs} +31 -55
  7. package/dist/chunk-DDVXFNYA.mjs.map +1 -0
  8. package/dist/{chunk-NYBGR2NK.mjs → chunk-FXHKK52V.mjs} +13 -14
  9. package/dist/chunk-FXHKK52V.mjs.map +1 -0
  10. package/dist/{chunk-VPTC36RZ.mjs → chunk-H4VZMKR6.mjs} +2 -2
  11. package/dist/{chunk-OAF4ASJH.mjs → chunk-H7LSKIDK.mjs} +23 -70
  12. package/dist/chunk-H7LSKIDK.mjs.map +1 -0
  13. package/dist/chunk-JDQCJCAQ.mjs +295 -0
  14. package/dist/chunk-JDQCJCAQ.mjs.map +1 -0
  15. package/dist/{chunk-STZUYPHJ.mjs → chunk-LODRWFMB.mjs} +2 -14
  16. package/dist/chunk-LODRWFMB.mjs.map +1 -0
  17. package/dist/{chunk-MKEQ2MJG.mjs → chunk-MWZO6TUR.mjs} +13 -29
  18. package/dist/chunk-MWZO6TUR.mjs.map +1 -0
  19. package/dist/{chunk-7LRDVJH5.mjs → chunk-ODN4H66E.mjs} +2 -6
  20. package/dist/chunk-ODN4H66E.mjs.map +1 -0
  21. package/dist/{chunk-6KHA5W5R.mjs → chunk-QDGDXRRJ.mjs} +2 -2
  22. package/dist/{chunk-ODAH4HNG.mjs → chunk-XINZBP3J.mjs} +2 -2
  23. package/dist/{chunk-ODAH4HNG.mjs.map → chunk-XINZBP3J.mjs.map} +1 -1
  24. package/dist/components/copilot-provider/copilot-messages.d.ts +0 -1
  25. package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -5
  26. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  27. package/dist/components/copilot-provider/copilotkit.d.ts +0 -1
  28. package/dist/components/copilot-provider/copilotkit.js +91 -191
  29. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  30. package/dist/components/copilot-provider/copilotkit.mjs +7 -8
  31. package/dist/components/copilot-provider/index.d.ts +0 -1
  32. package/dist/components/copilot-provider/index.js +91 -191
  33. package/dist/components/copilot-provider/index.js.map +1 -1
  34. package/dist/components/copilot-provider/index.mjs +7 -8
  35. package/dist/components/index.d.ts +0 -1
  36. package/dist/components/index.js +91 -191
  37. package/dist/components/index.js.map +1 -1
  38. package/dist/components/index.mjs +7 -8
  39. package/dist/components/toast/toast-provider.d.ts +1 -2
  40. package/dist/components/toast/toast-provider.js +62 -76
  41. package/dist/components/toast/toast-provider.js.map +1 -1
  42. package/dist/components/toast/toast-provider.mjs +1 -1
  43. package/dist/context/copilot-context.d.ts +3 -15
  44. package/dist/context/copilot-context.js +1 -13
  45. package/dist/context/copilot-context.js.map +1 -1
  46. package/dist/context/copilot-context.mjs +1 -1
  47. package/dist/context/index.d.ts +1 -1
  48. package/dist/context/index.js +1 -13
  49. package/dist/context/index.js.map +1 -1
  50. package/dist/context/index.mjs +4 -4
  51. package/dist/hooks/index.d.ts +1 -2
  52. package/dist/hooks/index.js +293 -624
  53. package/dist/hooks/index.js.map +1 -1
  54. package/dist/hooks/index.mjs +22 -30
  55. package/dist/hooks/use-chat.d.ts +3 -31
  56. package/dist/hooks/use-chat.js +205 -443
  57. package/dist/hooks/use-chat.js.map +1 -1
  58. package/dist/hooks/use-chat.mjs +3 -4
  59. package/dist/hooks/use-coagent-state-render.d.ts +2 -2
  60. package/dist/hooks/use-coagent-state-render.js +1 -13
  61. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  62. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  63. package/dist/hooks/use-coagent.d.ts +1 -14
  64. package/dist/hooks/use-coagent.js +262 -580
  65. package/dist/hooks/use-coagent.js.map +1 -1
  66. package/dist/hooks/use-coagent.mjs +11 -19
  67. package/dist/hooks/use-copilot-action.d.ts +2 -12
  68. package/dist/hooks/use-copilot-action.js +17 -167
  69. package/dist/hooks/use-copilot-action.js.map +1 -1
  70. package/dist/hooks/use-copilot-action.mjs +2 -4
  71. package/dist/hooks/use-copilot-chat.d.ts +0 -2
  72. package/dist/hooks/use-copilot-chat.js +238 -532
  73. package/dist/hooks/use-copilot-chat.js.map +1 -1
  74. package/dist/hooks/use-copilot-chat.mjs +10 -12
  75. package/dist/hooks/use-copilot-readable.js +1 -13
  76. package/dist/hooks/use-copilot-readable.js.map +1 -1
  77. package/dist/hooks/use-copilot-readable.mjs +2 -2
  78. package/dist/hooks/use-copilot-runtime-client.js +4 -110
  79. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  80. package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
  81. package/dist/hooks/use-make-copilot-document-readable.js +1 -13
  82. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  83. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  84. package/dist/index.d.ts +3 -3
  85. package/dist/index.js +391 -703
  86. package/dist/index.js.map +1 -1
  87. package/dist/index.mjs +30 -38
  88. package/dist/lib/copilot-task.d.ts +1 -6
  89. package/dist/lib/copilot-task.js +17 -55
  90. package/dist/lib/copilot-task.js.map +1 -1
  91. package/dist/lib/copilot-task.mjs +8 -10
  92. package/dist/lib/index.d.ts +1 -1
  93. package/dist/lib/index.js +17 -55
  94. package/dist/lib/index.js.map +1 -1
  95. package/dist/lib/index.mjs +8 -10
  96. package/dist/types/frontend-action.d.ts +2 -21
  97. package/dist/types/frontend-action.js +0 -34
  98. package/dist/types/frontend-action.js.map +1 -1
  99. package/dist/types/frontend-action.mjs +0 -7
  100. package/dist/types/index.d.ts +1 -2
  101. package/dist/types/index.js.map +1 -1
  102. package/dist/utils/extract.d.ts +2 -3
  103. package/dist/utils/extract.js +3 -21
  104. package/dist/utils/extract.js.map +1 -1
  105. package/dist/utils/extract.mjs +7 -8
  106. package/dist/utils/index.js +3 -21
  107. package/dist/utils/index.js.map +1 -1
  108. package/dist/utils/index.mjs +9 -10
  109. package/package.json +5 -5
  110. package/src/components/copilot-provider/copilotkit-props.tsx +10 -0
  111. package/src/components/copilot-provider/copilotkit.tsx +44 -7
  112. package/src/components/toast/toast-provider.tsx +1 -1
  113. package/src/context/copilot-context.tsx +28 -2
  114. package/src/hooks/index.ts +1 -0
  115. package/src/hooks/use-chat.ts +15 -5
  116. package/src/hooks/use-coagent-state-render.ts +11 -0
  117. package/src/hooks/use-coagent.ts +11 -1
  118. package/src/hooks/use-copilot-authenticated-action.ts +60 -0
  119. package/src/hooks/use-copilot-chat.ts +1 -0
  120. package/dist/chunk-7LRDVJH5.mjs.map +0 -1
  121. package/dist/chunk-M3SYKJ3W.mjs +0 -393
  122. package/dist/chunk-M3SYKJ3W.mjs.map +0 -1
  123. package/dist/chunk-MKEQ2MJG.mjs.map +0 -1
  124. package/dist/chunk-NYBGR2NK.mjs.map +0 -1
  125. package/dist/chunk-OAF4ASJH.mjs.map +0 -1
  126. package/dist/chunk-QCUP6HLK.mjs +0 -37
  127. package/dist/chunk-QCUP6HLK.mjs.map +0 -1
  128. package/dist/chunk-SFPANIOY.mjs.map +0 -1
  129. package/dist/chunk-STZUYPHJ.mjs.map +0 -1
  130. package/dist/chunk-VQDGBYWQ.mjs.map +0 -1
  131. package/dist/chunk-XERJQUHA.mjs +0 -31
  132. package/dist/chunk-XERJQUHA.mjs.map +0 -1
  133. package/dist/chunk-YL6V3QTN.mjs.map +0 -1
  134. package/dist/components/error-boundary/error-boundary.d.ts +0 -22
  135. package/dist/components/error-boundary/error-boundary.js +0 -183
  136. package/dist/components/error-boundary/error-boundary.js.map +0 -1
  137. package/dist/components/error-boundary/error-boundary.mjs +0 -12
  138. package/dist/components/error-boundary/error-boundary.mjs.map +0 -1
  139. package/dist/components/error-boundary/error-utils.d.ts +0 -11
  140. package/dist/components/error-boundary/error-utils.js +0 -177
  141. package/dist/components/error-boundary/error-utils.js.map +0 -1
  142. package/dist/components/error-boundary/error-utils.mjs +0 -13
  143. package/dist/components/error-boundary/error-utils.mjs.map +0 -1
  144. /package/dist/{chunk-VPTC36RZ.mjs.map → chunk-H4VZMKR6.mjs.map} +0 -0
  145. /package/dist/{chunk-6KHA5W5R.mjs.map → chunk-QDGDXRRJ.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/index.ts","../../src/utils/extract.ts","../../src/components/copilot-provider/copilotkit.tsx","../../src/utils/dev-console.ts"],"sourcesContent":["export { extract } from \"./extract\";\nexport * from \"./dev-console\";\n","import {\n Action,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n MappedParameterTypes,\n Parameter,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n ActionExecutionMessage,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\nimport {\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n} from \"@copilotkit/runtime-client-gql\";\n\ninterface InitialState<T extends Parameter[] | [] = []> {\n status: \"initial\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n}\n\ntype StreamHandlerArgs<T extends Parameter[] | [] = []> =\n | InitialState<T>\n | InProgressState<T>\n | CompleteState<T>;\n\ninterface ExtractOptions<T extends Parameter[]> {\n context: CopilotContextParams & CopilotMessagesContextParams;\n instructions: string;\n parameters: T;\n include?: IncludeOptions;\n data?: any;\n abortSignal?: AbortSignal;\n stream?: (args: StreamHandlerArgs<T>) => void;\n requestType?: CopilotRequestType;\n forwardedParameters?: ForwardedParametersInput;\n}\n\ninterface IncludeOptions {\n readable?: boolean;\n messages?: boolean;\n}\n\nexport async function extract<const T extends Parameter[]>({\n context,\n instructions,\n parameters,\n include,\n data,\n abortSignal,\n stream,\n requestType = CopilotRequestType.Task,\n forwardedParameters,\n}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {\n const { messages } = context;\n\n const action: Action<any> = {\n name: \"extract\",\n description: instructions,\n parameters,\n handler: (args: any) => {},\n };\n\n const includeReadable = include?.readable ?? false;\n const includeMessages = include?.messages ?? false;\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (includeReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = new TextMessage({\n content: makeSystemMessage(contextString, instructions),\n role: Role.System,\n });\n\n const instructionsMessage: Message = new TextMessage({\n content: makeInstructionsMessage(instructions),\n role: Role.User,\n });\n\n const response = context.runtimeClient.asStream(\n context.runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [\n {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n },\n ],\n url: window.location.href,\n },\n\n messages: convertMessagesToGqlInput(\n includeMessages\n ? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)]\n : [systemMessage, instructionsMessage],\n ),\n metadata: {\n requestType: requestType,\n },\n forwardedParameters: {\n ...(forwardedParameters ?? {}),\n toolChoice: \"function\",\n toolChoiceFunctionName: action.name,\n },\n },\n properties: context.copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n\n const reader = response.getReader();\n\n let isInitial = true;\n\n let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (abortSignal?.aborted) {\n throw new Error(\"Aborted\");\n }\n\n actionExecutionMessage = convertGqlOutputToMessages(\n value.generateCopilotResponse.messages,\n ).find((msg) => msg.isActionExecutionMessage()) as ActionExecutionMessage | undefined;\n\n if (!actionExecutionMessage) {\n continue;\n }\n\n stream?.({\n status: isInitial ? \"initial\" : \"inProgress\",\n args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,\n });\n\n isInitial = false;\n }\n\n if (!actionExecutionMessage) {\n throw new Error(\"extract() failed: No function call occurred\");\n }\n\n stream?.({\n status: \"complete\",\n args: actionExecutionMessage.arguments as MappedParameterTypes<T>,\n });\n\n return actionExecutionMessage.arguments as MappedParameterTypes<T>;\n}\n\n// We need to put this in a user message since some LLMs need\n// at least one user message to function\nfunction makeInstructionsMessage(instructions: string): string {\n return `\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n\nAny additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.\n`;\n}\n\nfunction makeSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with a function called extract you MUST call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call the function without saying anything else.\n`;\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, 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\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\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 <CopilotErrorBoundary>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotErrorBoundary>\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 const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n\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 const [threadId, setThreadId] = useState<string | null>(null);\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\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 coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n runtimeClient,\n forwardedParameters: props.forwardedParameters || {},\n agentLock: props.agent || null,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\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","export function shouldShowDevConsole(showDevConsole: boolean | \"auto\"): boolean {\n if (typeof showDevConsole === \"boolean\") {\n return showDevConsole;\n }\n return (\n getHostname() === \"localhost\" ||\n getHostname() === \"127.0.0.1\" ||\n getHostname() === \"0.0.0.0\" ||\n getHostname() === \"::1\"\n );\n}\n\nfunction getHostname(): string {\n if (typeof window !== \"undefined\" && window.location) {\n return window.location.hostname;\n }\n return \"\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAMO;AACP,gCAQO;;;ACCP,mBAAuD;AASvD,uBAA0B;AAC1B,oBAKO;AAmBC;AA+RD,IAAM,kCAAkC,CAAC,QAAQ;;;AD9TxD,IAAAC,6BAGO;AAuCP,SAAsB,QAAqC,IAUH;AAAA,6CAVG;AAAA,IACzD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,6CAAmB;AAAA,IACjC;AAAA,EACF,GAAwD;AAvExD;AAwEE,UAAM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AW,eAAe,OAAO,UAAU;AACpD,WAAO,OAAO,SAAS;AAAA,EACzB;AACA,SAAO;AACT;","names":["import_shared","import_runtime_client_gql"]}
1
+ {"version":3,"sources":["../../src/utils/index.ts","../../src/utils/extract.ts","../../src/components/copilot-provider/copilotkit.tsx","../../src/utils/dev-console.ts"],"sourcesContent":["export { extract } from \"./extract\";\nexport * from \"./dev-console\";\n","import {\n Action,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n MappedParameterTypes,\n Parameter,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n ActionExecutionMessage,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\nimport {\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n} from \"@copilotkit/runtime-client-gql\";\n\ninterface InitialState<T extends Parameter[] | [] = []> {\n status: \"initial\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n}\n\ntype StreamHandlerArgs<T extends Parameter[] | [] = []> =\n | InitialState<T>\n | InProgressState<T>\n | CompleteState<T>;\n\ninterface ExtractOptions<T extends Parameter[]> {\n context: CopilotContextParams & CopilotMessagesContextParams;\n instructions: string;\n parameters: T;\n include?: IncludeOptions;\n data?: any;\n abortSignal?: AbortSignal;\n stream?: (args: StreamHandlerArgs<T>) => void;\n requestType?: CopilotRequestType;\n}\n\ninterface IncludeOptions {\n readable?: boolean;\n messages?: boolean;\n}\n\nexport async function extract<const T extends Parameter[]>({\n context,\n instructions,\n parameters,\n include,\n data,\n abortSignal,\n stream,\n requestType = CopilotRequestType.Task,\n}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {\n const { messages } = context;\n\n const action: Action<any> = {\n name: \"extract\",\n description: instructions,\n parameters,\n handler: (args: any) => {},\n };\n\n const includeReadable = include?.readable ?? false;\n const includeMessages = include?.messages ?? false;\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (includeReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = new TextMessage({\n content: makeSystemMessage(contextString, instructions),\n role: Role.System,\n });\n\n const instructionsMessage: Message = new TextMessage({\n content: makeInstructionsMessage(instructions),\n role: Role.User,\n });\n\n const response = context.runtimeClient.asStream(\n context.runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [\n {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n },\n ],\n url: window.location.href,\n },\n\n messages: convertMessagesToGqlInput(\n includeMessages\n ? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)]\n : [systemMessage, instructionsMessage],\n ),\n metadata: {\n requestType: requestType,\n },\n forwardedParameters: {\n toolChoice: \"function\",\n toolChoiceFunctionName: action.name,\n },\n },\n properties: context.copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n\n const reader = response.getReader();\n\n let isInitial = true;\n\n let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (abortSignal?.aborted) {\n throw new Error(\"Aborted\");\n }\n\n actionExecutionMessage = convertGqlOutputToMessages(\n value.generateCopilotResponse.messages,\n ).find((msg) => msg.isActionExecutionMessage()) as ActionExecutionMessage | undefined;\n\n if (!actionExecutionMessage) {\n continue;\n }\n\n stream?.({\n status: isInitial ? \"initial\" : \"inProgress\",\n args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,\n });\n\n isInitial = false;\n }\n\n if (!actionExecutionMessage) {\n throw new Error(\"extract() failed: No function call occurred\");\n }\n\n stream?.({\n status: \"complete\",\n args: actionExecutionMessage.arguments as MappedParameterTypes<T>,\n });\n\n return actionExecutionMessage.arguments as MappedParameterTypes<T>;\n}\n\n// We need to put this in a user message since some LLMs need\n// at least one user message to function\nfunction makeInstructionsMessage(instructions: string): string {\n return `\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n\nAny additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.\n`;\n}\n\nfunction makeSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with a function called extract you MUST call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call the function without saying anything else.\n`;\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, 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","export function shouldShowDevConsole(showDevConsole: boolean | \"auto\"): boolean {\n if (typeof showDevConsole === \"boolean\") {\n return showDevConsole;\n }\n return (\n getHostname() === \"localhost\" ||\n getHostname() === \"127.0.0.1\" ||\n getHostname() === \"0.0.0.0\" ||\n getHostname() === \"::1\"\n );\n}\n\nfunction getHostname(): string {\n if (typeof window !== \"undefined\" && window.location) {\n return window.location.hostname;\n }\n return \"\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAM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;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASF;;;AElNO,SAAS,qBAAqB,gBAA2C;AAC9E,MAAI,OAAO,mBAAmB,WAAW;AACvC,WAAO;AAAA,EACT;AACA,SACE,YAAY,MAAM,eAClB,YAAY,MAAM,eAClB,YAAY,MAAM,aAClB,YAAY,MAAM;AAEtB;AAEA,SAAS,cAAsB;AAC7B,MAAI,OAAO,WAAW,eAAe,OAAO,UAAU;AACpD,WAAO,OAAO,SAAS;AAAA,EACzB;AACA,SAAO;AACT;","names":["import_shared","import_runtime_client_gql"]}
@@ -1,18 +1,17 @@
1
1
  import {
2
2
  extract
3
- } from "../chunk-YL6V3QTN.mjs";
4
- import "../chunk-QCUP6HLK.mjs";
5
- import {
6
- shouldShowDevConsole
7
- } from "../chunk-MLAS4QUR.mjs";
8
- import "../chunk-XXR4QFAQ.mjs";
3
+ } from "../chunk-6OR25P32.mjs";
9
4
  import "../chunk-5FHSUKQL.mjs";
10
5
  import "../chunk-6U3UH3KO.mjs";
11
- import "../chunk-DCTJZ742.mjs";
12
- import "../chunk-7LRDVJH5.mjs";
13
- import "../chunk-SFPANIOY.mjs";
6
+ import "../chunk-XXR4QFAQ.mjs";
7
+ import "../chunk-ODN4H66E.mjs";
8
+ import "../chunk-2KCEHGSI.mjs";
14
9
  import "../chunk-O7ARI5CV.mjs";
15
- import "../chunk-STZUYPHJ.mjs";
10
+ import "../chunk-LODRWFMB.mjs";
11
+ import "../chunk-DCTJZ742.mjs";
12
+ import {
13
+ shouldShowDevConsole
14
+ } from "../chunk-MLAS4QUR.mjs";
16
15
  import "../chunk-SKC7AJIV.mjs";
17
16
  export {
18
17
  extract,
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "publishConfig": {
10
10
  "access": "public"
11
11
  },
12
- "version": "1.5.1-next.1",
12
+ "version": "1.5.1-next.3",
13
13
  "sideEffects": false,
14
14
  "main": "./dist/index.js",
15
15
  "module": "./dist/index.mjs",
@@ -36,14 +36,14 @@
36
36
  "tsup": "^6.7.0",
37
37
  "typescript": "^5.2.3",
38
38
  "@types/react-dom": "^18.2.4",
39
- "eslint-config-custom": "1.4.6",
40
- "tsconfig": "1.4.6"
39
+ "tsconfig": "1.4.6",
40
+ "eslint-config-custom": "1.4.6"
41
41
  },
42
42
  "dependencies": {
43
43
  "@scarf/scarf": "^1.3.0",
44
44
  "untruncate-json": "^0.0.1",
45
- "@copilotkit/runtime-client-gql": "1.5.1-next.1",
46
- "@copilotkit/shared": "1.5.1-next.1"
45
+ "@copilotkit/runtime-client-gql": "1.5.1-next.3",
46
+ "@copilotkit/shared": "1.5.1-next.3"
47
47
  },
48
48
  "keywords": [
49
49
  "copilotkit",
@@ -1,5 +1,6 @@
1
1
  import { ForwardedParametersInput } from "@copilotkit/runtime-client-gql";
2
2
  import { ReactNode } from "react";
3
+ import { AuthState } from "../../context/copilot-context";
3
4
 
4
5
  /**
5
6
  * Props for CopilotKit.
@@ -84,4 +85,13 @@ export interface CopilotKitProps {
84
85
  * The forwarded parameters to use for the task.
85
86
  */
86
87
  forwardedParameters?: Pick<ForwardedParametersInput, "temperature">;
88
+
89
+ /**
90
+ * The auth config to use for the CopilotKit.
91
+ */
92
+ authConfig?: {
93
+ SignInComponent: React.ComponentType<{
94
+ onSignInComplete: (authState: AuthState) => void;
95
+ }>;
96
+ };
87
97
  }
@@ -14,12 +14,13 @@
14
14
  * ```
15
15
  */
16
16
 
17
- import { useCallback, useMemo, useRef, useState } from "react";
17
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
18
18
  import {
19
19
  CopilotContext,
20
20
  CopilotApiConfig,
21
21
  ChatComponentsCache,
22
22
  AgentSession,
23
+ AuthState,
23
24
  } from "../../context/copilot-context";
24
25
  import useTree from "../../hooks/use-tree";
25
26
  import { CopilotChatSuggestionConfiguration, DocumentPointer } from "../../types";
@@ -41,6 +42,7 @@ import { ToastProvider } from "../toast/toast-provider";
41
42
  import { useCopilotRuntimeClient } from "../../hooks/use-copilot-runtime-client";
42
43
  import { shouldShowDevConsole } from "../../utils";
43
44
  import { CopilotErrorBoundary } from "../error-boundary/error-boundary";
45
+ import { Agent } from "@copilotkit/runtime-client-gql";
44
46
 
45
47
  export function CopilotKit({ children, ...props }: CopilotKitProps) {
46
48
  const showDevConsole = props.showDevConsole === undefined ? "auto" : props.showDevConsole;
@@ -77,6 +79,7 @@ export function CopilotKitInternal({ children, ...props }: CopilotKitProps) {
77
79
  const { addElement, removeElement, printTree } = useTree();
78
80
  const [isLoading, setIsLoading] = useState(false);
79
81
  const [chatInstructions, setChatInstructions] = useState("");
82
+ const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});
80
83
 
81
84
  const {
82
85
  addElement: addDocument,
@@ -224,12 +227,31 @@ export function CopilotKitInternal({ children, ...props }: CopilotKitProps) {
224
227
  props.cloudRestrictToTopic,
225
228
  ]);
226
229
 
227
- const headers = {
228
- ...(copilotApiConfig.headers || {}),
229
- ...(copilotApiConfig.publicApiKey
230
- ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }
231
- : {}),
232
- };
230
+ const headers = useMemo(() => {
231
+ const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {
232
+ if (state.status === "authenticated" && state.authHeaders) {
233
+ return {
234
+ ...acc,
235
+ ...Object.entries(state.authHeaders).reduce(
236
+ (headers, [key, value]) => ({
237
+ ...headers,
238
+ [key.startsWith("X-Custom-") ? key : `X-Custom-${key}`]: value,
239
+ }),
240
+ {},
241
+ ),
242
+ };
243
+ }
244
+ return acc;
245
+ }, {});
246
+
247
+ return {
248
+ ...(copilotApiConfig.headers || {}),
249
+ ...(copilotApiConfig.publicApiKey
250
+ ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }
251
+ : {}),
252
+ ...authHeaders,
253
+ };
254
+ }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);
233
255
 
234
256
  const runtimeClient = useCopilotRuntimeClient({
235
257
  url: copilotApiConfig.chatApiEndpoint,
@@ -256,6 +278,7 @@ export function CopilotKitInternal({ children, ...props }: CopilotKitProps) {
256
278
  });
257
279
  };
258
280
 
281
+ const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);
259
282
  const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});
260
283
  const coagentStatesRef = useRef<Record<string, CoagentState>>({});
261
284
  const setCoagentStatesWithRef = useCallback(
@@ -273,6 +296,16 @@ export function CopilotKitInternal({ children, ...props }: CopilotKitProps) {
273
296
  [],
274
297
  );
275
298
 
299
+ useEffect(() => {
300
+ const fetchData = async () => {
301
+ const result = await runtimeClient.availableAgents();
302
+ if (result.data?.availableAgents) {
303
+ setAvailableAgents(result.data.availableAgents.agents);
304
+ }
305
+ };
306
+ void fetchData();
307
+ }, []);
308
+
276
309
  let initialAgentSession: AgentSession | null = null;
277
310
  if (props.agent) {
278
311
  initialAgentSession = {
@@ -328,6 +361,10 @@ export function CopilotKitInternal({ children, ...props }: CopilotKitProps) {
328
361
  runId,
329
362
  setRunId,
330
363
  chatAbortControllerRef,
364
+ availableAgents,
365
+ authConfig: props.authConfig,
366
+ authStates,
367
+ setAuthStates,
331
368
  }}
332
369
  >
333
370
  <CopilotMessages>{children}</CopilotMessages>
@@ -141,7 +141,7 @@ function Toast({
141
141
  style={{
142
142
  backgroundColor: bgColors[type],
143
143
  color: "white",
144
- padding: "0.5rem 1rem",
144
+ padding: "0.5rem 1.5rem",
145
145
  borderRadius: "0.25rem",
146
146
  boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
147
147
  position: "relative",
@@ -11,6 +11,7 @@ import { CopilotChatSuggestionConfiguration } from "../types/chat-suggestion-con
11
11
  import { CoAgentStateRender, CoAgentStateRenderProps } from "../types/coagent-action";
12
12
  import { CoagentState } from "../types/coagent-state";
13
13
  import { CopilotRuntimeClient, ForwardedParametersInput } from "@copilotkit/runtime-client-gql";
14
+ import { Agent } from "@copilotkit/runtime-client-gql";
14
15
 
15
16
  /**
16
17
  * Interface for the configuration of the Copilot API.
@@ -90,6 +91,15 @@ export interface AgentSession {
90
91
  nodeName?: string;
91
92
  }
92
93
 
94
+ export interface AuthState {
95
+ status: "authenticated" | "unauthenticated";
96
+ authHeaders: Record<string, string>;
97
+ userId?: string;
98
+ metadata?: Record<string, any>;
99
+ }
100
+
101
+ export type ActionName = string;
102
+
93
103
  export interface CopilotContextParams {
94
104
  // function-calling
95
105
  actions: Record<string, FrontendAction<any>>;
@@ -167,6 +177,22 @@ export interface CopilotContextParams {
167
177
  * The forwarded parameters to use for the task.
168
178
  */
169
179
  forwardedParameters?: Pick<ForwardedParametersInput, "temperature">;
180
+ availableAgents: Agent[];
181
+
182
+ /**
183
+ * The auth states for the CopilotKit.
184
+ */
185
+ authStates?: Record<ActionName, AuthState>;
186
+ setAuthStates?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;
187
+
188
+ /**
189
+ * The auth config for the CopilotKit.
190
+ */
191
+ authConfig?: {
192
+ SignInComponent: React.ComponentType<{
193
+ onSignInComplete: (authState: AuthState) => void;
194
+ }>;
195
+ };
170
196
  }
171
197
 
172
198
  const emptyCopilotContext: CopilotContextParams = {
@@ -227,6 +253,7 @@ const emptyCopilotContext: CopilotContextParams = {
227
253
  runId: null,
228
254
  setRunId: () => {},
229
255
  chatAbortControllerRef: { current: null },
256
+ availableAgents: [],
230
257
  };
231
258
 
232
259
  export const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);
@@ -239,7 +266,6 @@ export function useCopilotContext(): CopilotContextParams {
239
266
  return context;
240
267
  }
241
268
 
242
- function returnAndThrowInDebug<T>(value: T): T {
269
+ function returnAndThrowInDebug<T>(_value: T): T {
243
270
  throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
244
- return value;
245
271
  }
@@ -9,3 +9,4 @@ export { type UseChatHelpers } from "./use-chat";
9
9
  export { useCopilotReadable } from "./use-copilot-readable";
10
10
  export { useCoAgent, type HintFunction, runAgent, startAgent, stopAgent } from "./use-coagent";
11
11
  export { useCopilotRuntimeClient } from "./use-copilot-runtime-client";
12
+ export { useCopilotAuthenticatedAction } from "./use-copilot-authenticated-action";
@@ -2,8 +2,8 @@ import { useRef } from "react";
2
2
  import {
3
3
  FunctionCallHandler,
4
4
  COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
5
- actionParametersToJsonSchema,
6
5
  CoAgentStateRenderHandler,
6
+ randomId,
7
7
  } from "@copilotkit/shared";
8
8
  import {
9
9
  Message,
@@ -17,7 +17,6 @@ import {
17
17
  MessageRole,
18
18
  Role,
19
19
  CopilotRequestType,
20
- ActionInputAvailability,
21
20
  ForwardedParametersInput,
22
21
  loadMessagesFromJsonRepresentation,
23
22
  } from "@copilotkit/runtime-client-gql";
@@ -26,7 +25,6 @@ import { CopilotApiConfig } from "../context";
26
25
  import { FrontendAction, processActionsForRuntimeRequest } from "../types/frontend-action";
27
26
  import { CoagentState } from "../types/coagent-state";
28
27
  import { AgentSession } from "../context/copilot-context";
29
- import { useToast } from "../components/toast/toast-provider";
30
28
  import { useCopilotRuntimeClient } from "./use-copilot-runtime-client";
31
29
  import { useAsyncCallback } from "../components/error-boundary/error-utils";
32
30
 
@@ -126,6 +124,10 @@ export type UseChatOptions = {
126
124
  * The global chat abort controller.
127
125
  */
128
126
  chatAbortControllerRef: React.MutableRefObject<AbortController | null>;
127
+ /**
128
+ * The agent lock.
129
+ */
130
+ agentLock: string | null;
129
131
  };
130
132
 
131
133
  export type UseChatHelpers = {
@@ -173,8 +175,8 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
173
175
  runId,
174
176
  setRunId,
175
177
  chatAbortControllerRef,
178
+ agentLock,
176
179
  } = options;
177
- const { addGraphQLErrorsToast } = useToast();
178
180
  const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();
179
181
  // We need to keep a ref of coagent states and session because of renderAndWait - making sure
180
182
  // the latest state is sent to the API
@@ -393,7 +395,15 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
393
395
  nodeName: lastAgentStateMessage.nodeName,
394
396
  });
395
397
  } else {
396
- setAgentSession(null);
398
+ if (agentLock) {
399
+ setAgentSession({
400
+ threadId: randomId(),
401
+ agentName: agentLock,
402
+ nodeName: undefined,
403
+ });
404
+ } else {
405
+ setAgentSession(null);
406
+ }
397
407
  }
398
408
  }
399
409
  }
@@ -50,6 +50,7 @@ import { useRef, useContext, useEffect } from "react";
50
50
  import { CopilotContext } from "../context/copilot-context";
51
51
  import { randomId } from "@copilotkit/shared";
52
52
  import { CoAgentStateRender } from "../types/coagent-action";
53
+ import { useToast } from "../components/toast/toast-provider";
53
54
 
54
55
  /**
55
56
  * This hook is used to render agent state with custom UI components or text. This is particularly
@@ -71,8 +72,18 @@ export function useCoAgentStateRender<T = any>(
71
72
  removeCoAgentStateRender,
72
73
  coAgentStateRenders,
73
74
  chatComponentsCache,
75
+ availableAgents,
74
76
  } = useContext(CopilotContext);
75
77
  const idRef = useRef<string>(randomId());
78
+ const { addToast } = useToast();
79
+
80
+ useEffect(() => {
81
+ if (availableAgents?.length && !availableAgents.some((a) => a.name === action.name)) {
82
+ const message = `(useCoAgentStateRender): Agent "${action.name}" not found. Make sure the agent exists and is properly configured.`;
83
+ console.warn(message);
84
+ addToast({ type: "warning", message });
85
+ }
86
+ }, [availableAgents]);
76
87
 
77
88
  const key = `${action.name}-${action.nodeName || "global"}`;
78
89
 
@@ -100,6 +100,7 @@ import { useCopilotChat } from "./use-copilot-chat";
100
100
  import { Message } from "@copilotkit/runtime-client-gql";
101
101
  import { flushSync } from "react-dom";
102
102
  import { useAsyncCallback } from "../components/error-boundary/error-utils";
103
+ import { useToast } from "../components/toast/toast-provider";
103
104
 
104
105
  interface WithInternalStateManagementAndInitial<T> {
105
106
  /**
@@ -203,6 +204,9 @@ export type HintFunction = (params: HintFunctionParams) => Message | undefined;
203
204
  * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart.
204
205
  */
205
206
  export function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {
207
+ const generalContext = useCopilotContext();
208
+ const { availableAgents } = generalContext;
209
+ const { addToast } = useToast();
206
210
  const isExternalStateManagement = (
207
211
  options: UseCoagentOptions<T>,
208
212
  ): options is WithExternalStateManagement<T> => {
@@ -210,6 +214,13 @@ export function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentRe
210
214
  };
211
215
 
212
216
  const { name } = options;
217
+ useEffect(() => {
218
+ if (availableAgents?.length && !availableAgents.some((a) => a.name === name)) {
219
+ const message = `(useCoAgent): Agent "${name}" not found. Make sure the agent exists and is properly configured.`;
220
+ console.warn(message);
221
+ addToast({ type: "warning", message });
222
+ }
223
+ }, [availableAgents]);
213
224
 
214
225
  const isInternalStateManagementWithInitial = (
215
226
  options: UseCoagentOptions<T>,
@@ -217,7 +228,6 @@ export function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentRe
217
228
  return "initialState" in options;
218
229
  };
219
230
 
220
- const generalContext = useCopilotContext();
221
231
  const messagesContext = useCopilotMessagesContext();
222
232
  const context = { ...generalContext, ...messagesContext };
223
233
  const { coagentStates, coagentStatesRef, setCoagentStatesWithRef } = context;
@@ -0,0 +1,60 @@
1
+ import { Parameter } from "@copilotkit/shared";
2
+ import { Fragment, useCallback, useRef } from "react";
3
+ import { useCopilotContext } from "../context/copilot-context";
4
+ import { FrontendAction, ActionRenderProps } from "../types/frontend-action";
5
+ import { useCopilotAction } from "./use-copilot-action";
6
+ import React from "react";
7
+
8
+ export function useCopilotAuthenticatedAction<T extends Parameter[]>(
9
+ action: FrontendAction<T>,
10
+ dependencies?: any[],
11
+ ): void {
12
+ const { authConfig, authStates, setAuthStates } = useCopilotContext();
13
+ const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);
14
+
15
+ const executeAction = useCallback(
16
+ (props: ActionRenderProps<Parameter[]>) => {
17
+ if (typeof action.render === "function") {
18
+ return action.render(props);
19
+ }
20
+ return action.render || React.createElement(Fragment);
21
+ },
22
+ [action],
23
+ );
24
+
25
+ const wrappedRender = useCallback(
26
+ (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {
27
+ const isAuthenticated = Object.values(authStates || {}).some(
28
+ (state) => state.status === "authenticated",
29
+ );
30
+
31
+ if (!isAuthenticated) {
32
+ // Store action details for later execution
33
+ pendingActionRef.current = props;
34
+
35
+ return authConfig?.SignInComponent
36
+ ? React.createElement(authConfig.SignInComponent, {
37
+ onSignInComplete: (authState) => {
38
+ setAuthStates?.((prev) => ({ ...prev, [action.name]: authState }));
39
+ if (pendingActionRef.current) {
40
+ executeAction(pendingActionRef.current);
41
+ pendingActionRef.current = null;
42
+ }
43
+ },
44
+ })
45
+ : React.createElement(Fragment);
46
+ }
47
+
48
+ return executeAction(props);
49
+ },
50
+ [action, authStates, setAuthStates],
51
+ );
52
+
53
+ useCopilotAction(
54
+ {
55
+ ...action,
56
+ render: wrappedRender,
57
+ } as FrontendAction<T>,
58
+ dependencies,
59
+ );
60
+ }
@@ -172,6 +172,7 @@ export function useCopilotChat({
172
172
  runId,
173
173
  setRunId,
174
174
  chatAbortControllerRef,
175
+ agentLock,
175
176
  });
176
177
 
177
178
  // this is a workaround born out of a bug that Athena incessantly ran into.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/use-copilot-runtime-client.ts"],"sourcesContent":["import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo } from \"react\";\nimport { useErrorToast } from \"../components/error-boundary/error-utils\";\n\nexport const useCopilotRuntimeClient = (options: CopilotRuntimeClientOptions) => {\n const { addGraphQLErrorsToast } = useToast();\n const addErrorToast = useErrorToast();\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 } else {\n addErrorToast([error]);\n }\n },\n });\n }, [options, addGraphQLErrorsToast]);\n\n return runtimeClient;\n};\n"],"mappings":";;;;;;;;;;AAAA;AAAA,EACE;AAAA,OAGK;AAEP,SAAS,eAAe;AAGjB,IAAM,0BAA0B,CAAC,YAAyC;AAC/E,QAAM,EAAE,sBAAsB,IAAI,SAAS;AAC3C,QAAM,gBAAgB,cAAc;AAEpC,QAAM,gBAAgB,QAAQ,MAAM;AAClC,WAAO,IAAI,qBAAqB,iCAC3B,UAD2B;AAAA,MAE9B,iBAAiB,CAAC,UAAU;AAC1B,YAAK,MAAc,cAAc,QAAQ;AACvC,gCAAuB,MAAc,aAA+B;AAAA,QACtE,OAAO;AACL,wBAAc,CAAC,KAAK,CAAC;AAAA,QACvB;AAAA,MACF;AAAA,IACF,EAAC;AAAA,EACH,GAAG,CAAC,SAAS,qBAAqB,CAAC;AAEnC,SAAO;AACT;","names":[]}