@copilotkit/react-core 1.3.6 → 1.3.7

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 (118) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/{chunk-4AF3YGMC.mjs → chunk-2MPUQRAY.mjs} +1 -3
  3. package/dist/chunk-2MPUQRAY.mjs.map +1 -0
  4. package/dist/{chunk-KK42A2OC.mjs → chunk-3MDMBUBP.mjs} +10 -6
  5. package/dist/chunk-3MDMBUBP.mjs.map +1 -0
  6. package/dist/{chunk-VZ66ENV7.mjs → chunk-6YEMNWKE.mjs} +41 -31
  7. package/dist/chunk-6YEMNWKE.mjs.map +1 -0
  8. package/dist/{chunk-3CU2I4W2.mjs → chunk-7DFHFZJT.mjs} +3 -4
  9. package/dist/{chunk-3CU2I4W2.mjs.map → chunk-7DFHFZJT.mjs.map} +1 -1
  10. package/dist/{chunk-6VNO5DEJ.mjs → chunk-AKQVU52J.mjs} +7 -9
  11. package/dist/chunk-AKQVU52J.mjs.map +1 -0
  12. package/dist/{chunk-NTNOUYBQ.mjs → chunk-ANOG3W5S.mjs} +2 -2
  13. package/dist/{chunk-ACK2DHWA.mjs → chunk-CQ23Q555.mjs} +2 -2
  14. package/dist/chunk-DCTJZ742.mjs +22 -0
  15. package/dist/chunk-DCTJZ742.mjs.map +1 -0
  16. package/dist/{chunk-2Y3VMFJN.mjs → chunk-OFG2PW2E.mjs} +8 -6
  17. package/dist/chunk-OFG2PW2E.mjs.map +1 -0
  18. package/dist/{chunk-UJWNB2I6.mjs → chunk-RYDEG77L.mjs} +2 -2
  19. package/dist/{chunk-QUCTZQ6X.mjs → chunk-TRXKPXDE.mjs} +2 -2
  20. package/dist/chunk-XXR4QFAQ.mjs +29 -0
  21. package/dist/chunk-XXR4QFAQ.mjs.map +1 -0
  22. package/dist/chunk-YPSGKPDA.mjs +1 -0
  23. package/dist/{chunk-IAS5FL4D.mjs → chunk-ZM6HV22S.mjs} +20 -13
  24. package/dist/chunk-ZM6HV22S.mjs.map +1 -0
  25. package/dist/components/copilot-provider/copilot-messages.d.ts +7 -0
  26. package/dist/components/copilot-provider/copilot-messages.js +80 -0
  27. package/dist/components/copilot-provider/copilot-messages.js.map +1 -0
  28. package/dist/components/copilot-provider/copilot-messages.mjs +9 -0
  29. package/dist/components/copilot-provider/copilot-messages.mjs.map +1 -0
  30. package/dist/components/copilot-provider/copilotkit.js +85 -52
  31. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  32. package/dist/components/copilot-provider/copilotkit.mjs +4 -2
  33. package/dist/components/copilot-provider/index.js +85 -52
  34. package/dist/components/copilot-provider/index.js.map +1 -1
  35. package/dist/components/copilot-provider/index.mjs +4 -2
  36. package/dist/components/index.js +85 -52
  37. package/dist/components/index.js.map +1 -1
  38. package/dist/components/index.mjs +4 -2
  39. package/dist/context/copilot-context.d.ts +0 -3
  40. package/dist/context/copilot-context.js +0 -2
  41. package/dist/context/copilot-context.js.map +1 -1
  42. package/dist/context/copilot-context.mjs +1 -1
  43. package/dist/context/copilot-messages-context.d.ts +15 -0
  44. package/dist/context/copilot-messages-context.js +57 -0
  45. package/dist/context/copilot-messages-context.js.map +1 -0
  46. package/dist/context/copilot-messages-context.mjs +10 -0
  47. package/dist/context/copilot-messages-context.mjs.map +1 -0
  48. package/dist/context/index.d.ts +2 -1
  49. package/dist/context/index.js +23 -4
  50. package/dist/context/index.js.map +1 -1
  51. package/dist/context/index.mjs +9 -3
  52. package/dist/hooks/index.js +57 -40
  53. package/dist/hooks/index.js.map +1 -1
  54. package/dist/hooks/index.mjs +18 -16
  55. package/dist/hooks/use-chat.js +5 -5
  56. package/dist/hooks/use-chat.js.map +1 -1
  57. package/dist/hooks/use-chat.mjs +1 -1
  58. package/dist/hooks/use-coagent-state-render.js +0 -2
  59. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  60. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  61. package/dist/hooks/use-coagent.js +48 -33
  62. package/dist/hooks/use-coagent.js.map +1 -1
  63. package/dist/hooks/use-coagent.mjs +8 -6
  64. package/dist/hooks/use-copilot-action.js +0 -2
  65. package/dist/hooks/use-copilot-action.js.map +1 -1
  66. package/dist/hooks/use-copilot-action.mjs +2 -2
  67. package/dist/hooks/use-copilot-chat.js +37 -21
  68. package/dist/hooks/use-copilot-chat.js.map +1 -1
  69. package/dist/hooks/use-copilot-chat.mjs +7 -4
  70. package/dist/hooks/use-copilot-readable.js +0 -2
  71. package/dist/hooks/use-copilot-readable.js.map +1 -1
  72. package/dist/hooks/use-copilot-readable.mjs +2 -2
  73. package/dist/hooks/use-make-copilot-document-readable.js +0 -2
  74. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  75. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  76. package/dist/index.d.ts +2 -1
  77. package/dist/index.js +176 -122
  78. package/dist/index.js.map +1 -1
  79. package/dist/index.mjs +26 -19
  80. package/dist/lib/copilot-task.d.ts +0 -1
  81. package/dist/lib/copilot-task.js +1 -1
  82. package/dist/lib/copilot-task.js.map +1 -1
  83. package/dist/lib/copilot-task.mjs +5 -3
  84. package/dist/lib/index.d.ts +0 -1
  85. package/dist/lib/index.js +1 -1
  86. package/dist/lib/index.js.map +1 -1
  87. package/dist/lib/index.mjs +5 -3
  88. package/dist/utils/extract.d.ts +2 -1
  89. package/dist/utils/extract.js +18 -10
  90. package/dist/utils/extract.js.map +1 -1
  91. package/dist/utils/extract.mjs +5 -3
  92. package/dist/utils/index.d.ts +1 -0
  93. package/dist/utils/index.js +18 -10
  94. package/dist/utils/index.js.map +1 -1
  95. package/dist/utils/index.mjs +5 -3
  96. package/package.json +7 -7
  97. package/src/components/copilot-provider/copilot-messages.tsx +23 -0
  98. package/src/components/copilot-provider/copilotkit.tsx +36 -30
  99. package/src/context/copilot-context.tsx +0 -8
  100. package/src/context/copilot-messages-context.tsx +29 -0
  101. package/src/context/index.ts +2 -0
  102. package/src/hooks/use-chat.ts +5 -5
  103. package/src/hooks/use-coagent.ts +11 -4
  104. package/src/hooks/use-copilot-chat.ts +2 -2
  105. package/src/lib/copilot-task.ts +1 -1
  106. package/src/utils/extract.ts +25 -13
  107. package/dist/chunk-2Y3VMFJN.mjs.map +0 -1
  108. package/dist/chunk-4AF3YGMC.mjs.map +0 -1
  109. package/dist/chunk-6VNO5DEJ.mjs.map +0 -1
  110. package/dist/chunk-IAS5FL4D.mjs.map +0 -1
  111. package/dist/chunk-KK42A2OC.mjs.map +0 -1
  112. package/dist/chunk-VNRDQJXW.mjs +0 -1
  113. package/dist/chunk-VZ66ENV7.mjs.map +0 -1
  114. /package/dist/{chunk-NTNOUYBQ.mjs.map → chunk-ANOG3W5S.mjs.map} +0 -0
  115. /package/dist/{chunk-ACK2DHWA.mjs.map → chunk-CQ23Q555.mjs.map} +0 -0
  116. /package/dist/{chunk-UJWNB2I6.mjs.map → chunk-RYDEG77L.mjs.map} +0 -0
  117. /package/dist/{chunk-QUCTZQ6X.mjs.map → chunk-TRXKPXDE.mjs.map} +0 -0
  118. /package/dist/{chunk-VNRDQJXW.mjs.map → chunk-YPSGKPDA.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/index.ts","../../src/utils/extract.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["export { extract } from \"./extract\";\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 } 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;\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 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 headers = {\n ...(context.copilotApiConfig.headers || {}),\n ...(context.copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: context.copilotApiConfig.publicApiKey }\n : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = CopilotRuntimeClient.asStream(\n 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, ...filterAgentStateMessages(messages)]\n : [systemMessage],\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 instanceof ActionExecutionMessage) 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\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\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","/**\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, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\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} from \"@copilotkit/shared\";\nimport { AgentStateMessage, Message } from \"@copilotkit/runtime-client-gql\";\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\";\n\nexport function CopilotKit({ 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 [messages, setMessages] = useState<Message[]>([]);\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 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 // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = {\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 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 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 messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n showDevConsole: props.showDevConsole === undefined ? \"auto\" : props.showDevConsole,\n coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\n }}\n >\n {children}\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAMO;AACP,gCAOO;;;ACEP,mBAA8C;AAU9C,uBAA0B;AAC1B,oBAIO;AAuMH;AAsCG,IAAM,kCAAkC,CAAC,QAAQ;;;AD3PxD,IAAAC,6BAAqC;AACrC,IAAAA,6BAGO;AAsCP,SAAsB,QAAqC,IASH;AAAA,6CATG;AAAA,IACzD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,6CAAmB;AAA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,CAAC,IACrD,CAAC,aAAa;AAAA,UACpB;AAAA,UACA,UAAU;AAAA,YACR;AAAA,UACF;AAAA,UACA,qBAAqB;AAAA,YACnB,YAAY;AAAA,YACZ,wBAAwB,OAAO;AAAA,UACjC;AAAA,QACF;AAAA,QACA,YAAY,QAAQ,iBAAiB;AAAA,QACrC,QAAQ;AAAA,MACV,CAAC;AAAA,IACH;AAEA,UAAM,SAAS,SAAS,UAAU;AAElC,QAAI,YAAY;AAEhB,QAAI,yBAA6D;AAEjE,WAAO,MAAM;AACX,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,UAAI,MAAM;AACR;AAAA,MACF;AAEA,UAAI,2CAAa,SAAS;AACxB,cAAM,IAAI,MAAM,SAAS;AAAA,MAC3B;AAEA,mCAAyB;AAAA,QACvB,MAAM,wBAAwB;AAAA,MAChC,EAAE,KAAK,CAAC,QAAQ,eAAe,gDAAsB;AAErD,UAAI,CAAC,wBAAwB;AAC3B;AAAA,MACF;AAEA,uCAAS;AAAA,QACP,QAAQ,YAAY,YAAY;AAAA,QAChC,MAAM,uBAAuB;AAAA,MAC/B;AAEA,kBAAY;AAAA,IACd;AAEA,QAAI,CAAC,wBAAwB;AAC3B,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AAEA,qCAAS;AAAA,MACP,QAAQ;AAAA,MACR,MAAM,uBAAuB;AAAA,IAC/B;AAEA,WAAO,uBAAuB;AAAA,EAChC;AAAA;AAEA,SAAS,kBAAkB,eAAuB,cAA8B;AAC9E,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA;AAAA;AAAA;AAAA;AAAA;AAKF;","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"],"sourcesContent":["export { extract } from \"./extract\";\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 headers = {\n ...(context.copilotApiConfig.headers || {}),\n ...(context.copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: context.copilotApiConfig.publicApiKey }\n : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = CopilotRuntimeClient.asStream(\n 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} 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\";\n\nexport function CopilotKit({ 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 [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 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: props.showDevConsole === undefined ? \"auto\" : props.showDevConsole,\n coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAMO;AACP,gCAOO;;;ACEP,mBAAuD;AASvD,uBAA0B;AAC1B,oBAIO;AA+OD;AAKC,IAAM,kCAAkC,CAAC,QAAQ;;;ADjQxD,IAAAC,6BAAqC;AACrC,IAAAA,6BAGO;AAsCP,SAAsB,QAAqC,IASH;AAAA,6CATG;AAAA,IACzD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,6CAAmB;AAAA,EACnC,GAAwD;AApExD;AAqEE,UAAM,EAAE,SAAS,IAAI;AAErB,UAAM,SAAsB;AAAA,MAC1B,MAAM;AAAA,MACN,aAAa;AAAA,MACb;AAAA,MACA,SAAS,CAAC,SAAc;AAAA,MAAC;AAAA,IAC3B;AAEA,UAAM,mBAAkB,wCAAS,aAAT,YAAqB;AAC7C,UAAM,mBAAkB,wCAAS,aAAT,YAAqB;AAE7C,QAAI,gBAAgB;AAEpB,QAAI,MAAM;AACR,uBAAiB,OAAO,SAAS,WAAW,OAAO,KAAK,UAAU,IAAI,KAAK;AAAA,IAC7E;AAEA,QAAI,iBAAiB;AACnB,uBAAiB,QAAQ,iBAAiB,CAAC,GAAG,+BAA+B;AAAA,IAC/E;AAEA,UAAM,gBAAyB,IAAI,sCAAY;AAAA,MAC7C,SAAS,kBAAkB,eAAe,YAAY;AAAA,MAC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I,MAAM;AACR;AAAA,MACF;AAEA,UAAI,2CAAa,SAAS;AACxB,cAAM,IAAI,MAAM,SAAS;AAAA,MAC3B;AAEA,mCAAyB;AAAA,QACvB,MAAM,wBAAwB;AAAA,MAChC,EAAE,KAAK,CAAC,QAAQ,IAAI,yBAAyB,CAAC;AAE9C,UAAI,CAAC,wBAAwB;AAC3B;AAAA,MACF;AAEA,uCAAS;AAAA,QACP,QAAQ,YAAY,YAAY;AAAA,QAChC,MAAM,uBAAuB;AAAA,MAC/B;AAEA,kBAAY;AAAA,IACd;AAEA,QAAI,CAAC,wBAAwB;AAC3B,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AAEA,qCAAS;AAAA,MACP,QAAQ;AAAA,MACR,MAAM,uBAAuB;AAAA,IAC/B;AAEA,WAAO,uBAAuB;AAAA,EAChC;AAAA;AAIA,SAAS,wBAAwB,cAA8B;AAC7D,SAAO;AAAA;AAAA;AAAA;AAAA,EAIP;AAAA;AAAA;AAAA;AAAA;AAKF;AAEA,SAAS,kBAAkB,eAAuB,cAA8B;AAC9E,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASF;","names":["import_shared","import_runtime_client_gql"]}
@@ -1,13 +1,15 @@
1
1
  import "../chunk-YJLRG5U3.mjs";
2
2
  import {
3
3
  extract
4
- } from "../chunk-IAS5FL4D.mjs";
4
+ } from "../chunk-ZM6HV22S.mjs";
5
5
  import "../chunk-JD7BAH7U.mjs";
6
6
  import "../chunk-SPCZTZCY.mjs";
7
- import "../chunk-VZ66ENV7.mjs";
7
+ import "../chunk-6YEMNWKE.mjs";
8
+ import "../chunk-XXR4QFAQ.mjs";
8
9
  import "../chunk-5FHSUKQL.mjs";
9
10
  import "../chunk-6U3UH3KO.mjs";
10
- import "../chunk-4AF3YGMC.mjs";
11
+ import "../chunk-DCTJZ742.mjs";
12
+ import "../chunk-2MPUQRAY.mjs";
11
13
  import "../chunk-SKC7AJIV.mjs";
12
14
  export {
13
15
  extract
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "publishConfig": {
10
10
  "access": "public"
11
11
  },
12
- "version": "1.3.6",
12
+ "version": "1.3.7",
13
13
  "sideEffects": false,
14
14
  "main": "./dist/index.js",
15
15
  "module": "./dist/index.mjs",
@@ -23,8 +23,8 @@
23
23
  "types": "./dist/index.d.ts",
24
24
  "license": "MIT",
25
25
  "peerDependencies": {
26
- "react": "^18.2.0",
27
- "react-dom": "^18.2.0"
26
+ "react": "^18 || ^19 || ^19.0.0-rc",
27
+ "react-dom": "^18 || ^19 || ^19.0.0-rc"
28
28
  },
29
29
  "devDependencies": {
30
30
  "@types/jest": "^29.5.4",
@@ -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.3.6",
40
- "tsconfig": "1.3.6"
39
+ "eslint-config-custom": "1.3.7",
40
+ "tsconfig": "1.3.7"
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.3.6",
46
- "@copilotkit/shared": "1.3.6"
45
+ "@copilotkit/runtime-client-gql": "1.3.7",
46
+ "@copilotkit/shared": "1.3.7"
47
47
  },
48
48
  "keywords": [
49
49
  "copilotkit",
@@ -0,0 +1,23 @@
1
+ /**
2
+ * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context
3
+ */
4
+
5
+ import { useState } from "react";
6
+ import { CopilotMessagesContext } from "../../context/copilot-messages-context";
7
+ import { Message } from "@copilotkit/runtime-client-gql";
8
+ import { CopilotKitProps } from "./copilotkit-props";
9
+
10
+ export function CopilotMessages({ children, ...props }: CopilotKitProps) {
11
+ const [messages, setMessages] = useState<Message[]>([]);
12
+
13
+ return (
14
+ <CopilotMessagesContext.Provider
15
+ value={{
16
+ messages,
17
+ setMessages,
18
+ }}
19
+ >
20
+ {children}
21
+ </CopilotMessagesContext.Provider>
22
+ );
23
+ }
@@ -14,11 +14,10 @@
14
14
  * ```
15
15
  */
16
16
 
17
- import { useCallback, useRef, useState } from "react";
17
+ import { useCallback, useMemo, useRef, useState } from "react";
18
18
  import {
19
19
  CopilotContext,
20
20
  CopilotApiConfig,
21
- InChatRenderFunction,
22
21
  ChatComponentsCache,
23
22
  AgentSession,
24
23
  } from "../../context/copilot-context";
@@ -30,13 +29,13 @@ import {
30
29
  CopilotCloudConfig,
31
30
  FunctionCallHandler,
32
31
  } from "@copilotkit/shared";
33
- import { AgentStateMessage, Message } from "@copilotkit/runtime-client-gql";
34
32
 
35
33
  import { FrontendAction } from "../../types/frontend-action";
36
34
  import useFlatCategoryStore from "../../hooks/use-flat-category-store";
37
35
  import { CopilotKitProps } from "./copilotkit-props";
38
36
  import { CoAgentStateRender } from "../../types/coagent-action";
39
37
  import { CoagentState } from "../../types/coagent-state";
38
+ import { CopilotMessages } from "./copilot-messages";
40
39
 
41
40
  export function CopilotKit({ children, ...props }: CopilotKitProps) {
42
41
  // Compute all the functions and properties that we need to pass
@@ -59,7 +58,6 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
59
58
  coAgentStateRenders: {},
60
59
  });
61
60
  const { addElement, removeElement, printTree } = useTree();
62
- const [messages, setMessages] = useState<Message[]>([]);
63
61
  const [isLoading, setIsLoading] = useState(false);
64
62
  const [chatInstructions, setChatInstructions] = useState("");
65
63
 
@@ -172,32 +170,42 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
172
170
  }
173
171
  }
174
172
 
175
- let cloud: CopilotCloudConfig | undefined = undefined;
176
- if (props.publicApiKey) {
177
- cloud = {
178
- guardrails: {
179
- input: {
180
- restrictToTopic: {
181
- enabled: props.cloudRestrictToTopic ? true : false,
182
- validTopics: props.cloudRestrictToTopic?.validTopics || [],
183
- invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],
173
+ // get the appropriate CopilotApiConfig from the props
174
+ const copilotApiConfig: CopilotApiConfig = useMemo(() => {
175
+ let cloud: CopilotCloudConfig | undefined = undefined;
176
+ if (props.publicApiKey) {
177
+ cloud = {
178
+ guardrails: {
179
+ input: {
180
+ restrictToTopic: {
181
+ enabled: props.cloudRestrictToTopic ? true : false,
182
+ validTopics: props.cloudRestrictToTopic?.validTopics || [],
183
+ invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],
184
+ },
184
185
  },
185
186
  },
186
- },
187
- };
188
- }
187
+ };
188
+ }
189
189
 
190
- // get the appropriate CopilotApiConfig from the props
191
- const copilotApiConfig: CopilotApiConfig = {
192
- publicApiKey: props.publicApiKey,
193
- ...(cloud ? { cloud } : {}),
194
- chatApiEndpoint: chatApiEndpoint,
195
- headers: props.headers || {},
196
- properties: props.properties || {},
197
- transcribeAudioUrl: props.transcribeAudioUrl,
198
- textToSpeechUrl: props.textToSpeechUrl,
199
- credentials: props.credentials,
200
- };
190
+ return {
191
+ publicApiKey: props.publicApiKey,
192
+ ...(cloud ? { cloud } : {}),
193
+ chatApiEndpoint: chatApiEndpoint,
194
+ headers: props.headers || {},
195
+ properties: props.properties || {},
196
+ transcribeAudioUrl: props.transcribeAudioUrl,
197
+ textToSpeechUrl: props.textToSpeechUrl,
198
+ credentials: props.credentials,
199
+ };
200
+ }, [
201
+ props.publicApiKey,
202
+ props.headers,
203
+ props.properties,
204
+ props.transcribeAudioUrl,
205
+ props.textToSpeechUrl,
206
+ props.credentials,
207
+ props.cloudRestrictToTopic,
208
+ ]);
201
209
 
202
210
  const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{
203
211
  [key: string]: CopilotChatSuggestionConfiguration;
@@ -245,8 +253,6 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
245
253
  addDocumentContext,
246
254
  removeDocumentContext,
247
255
  copilotApiConfig: copilotApiConfig,
248
- messages,
249
- setMessages,
250
256
  isLoading,
251
257
  setIsLoading,
252
258
  chatSuggestionConfiguration,
@@ -261,7 +267,7 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
261
267
  setAgentSession,
262
268
  }}
263
269
  >
264
- {children}
270
+ <CopilotMessages>{children}</CopilotMessages>
265
271
  </CopilotContext.Provider>
266
272
  );
267
273
  }
@@ -1,5 +1,4 @@
1
1
  import { CopilotCloudConfig, FunctionCallHandler } from "@copilotkit/shared";
2
- import { Message } from "@copilotkit/runtime-client-gql";
3
2
  import { ActionRenderProps, FrontendAction } from "../types/frontend-action";
4
3
  import React from "react";
5
4
  import { TreeNodeId } from "../hooks/use-tree";
@@ -111,10 +110,6 @@ export interface CopilotContextParams {
111
110
  removeDocumentContext: (documentId: string) => void;
112
111
  getDocumentsContext: (categories: string[]) => DocumentPointer[];
113
112
 
114
- // chat
115
- messages: Message[];
116
- setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
117
-
118
113
  isLoading: boolean;
119
114
  setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;
120
115
 
@@ -157,9 +152,6 @@ const emptyCopilotContext: CopilotContextParams = {
157
152
 
158
153
  getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),
159
154
 
160
- messages: [],
161
- setMessages: () => returnAndThrowInDebug([]),
162
-
163
155
  isLoading: false,
164
156
  setIsLoading: () => returnAndThrowInDebug(false),
165
157
 
@@ -0,0 +1,29 @@
1
+ /**
2
+ * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context
3
+ */
4
+
5
+ import { Message } from "@copilotkit/runtime-client-gql";
6
+ import React from "react";
7
+
8
+ export interface CopilotMessagesContextParams {
9
+ messages: Message[];
10
+ setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
11
+ }
12
+
13
+ const emptyCopilotContext: CopilotMessagesContextParams = {
14
+ messages: [],
15
+ setMessages: () => [],
16
+ };
17
+
18
+ export const CopilotMessagesContext =
19
+ React.createContext<CopilotMessagesContextParams>(emptyCopilotContext);
20
+
21
+ export function useCopilotMessagesContext(): CopilotMessagesContextParams {
22
+ const context = React.useContext(CopilotMessagesContext);
23
+ if (context === emptyCopilotContext) {
24
+ throw new Error(
25
+ "A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`",
26
+ );
27
+ }
28
+ return context;
29
+ }
@@ -1,6 +1,8 @@
1
1
  export { CopilotContext, useCopilotContext } from "./copilot-context";
2
+ export { CopilotMessagesContext, useCopilotMessagesContext } from "./copilot-messages-context";
2
3
  export type {
3
4
  CopilotContextParams,
4
5
  CoagentInChatRenderFunction,
5
6
  CopilotApiConfig,
6
7
  } from "./copilot-context";
8
+ export type { CopilotMessagesContextParams } from "./copilot-messages-context";
@@ -288,7 +288,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
288
288
  newMessages.push(message);
289
289
  // execute regular action executions
290
290
  if (
291
- message instanceof ActionExecutionMessage &&
291
+ message.isActionExecutionMessage() &&
292
292
  message.status.code !== MessageStatusCode.Pending &&
293
293
  message.scope === "client" &&
294
294
  onFunctionCall
@@ -332,7 +332,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
332
332
  }
333
333
  // execute coagent actions
334
334
  if (
335
- message instanceof AgentStateMessage &&
335
+ message.isAgentStateMessage() &&
336
336
  !message.active &&
337
337
  !executedCoAgentStateRenders.includes(message.id) &&
338
338
  onCoAgentStateRender
@@ -353,7 +353,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
353
353
 
354
354
  const lastAgentStateMessage = [...messages]
355
355
  .reverse()
356
- .find((message) => message instanceof AgentStateMessage);
356
+ .find((message) => message.isAgentStateMessage());
357
357
 
358
358
  if (lastAgentStateMessage) {
359
359
  if (lastAgentStateMessage.running) {
@@ -392,7 +392,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
392
392
  // if we have client side results
393
393
  (Object.values(actionResults).length ||
394
394
  // or the last message we received is a result
395
- (newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage))
395
+ (newMessages.length && newMessages[newMessages.length - 1].isResultMessage()))
396
396
  ) {
397
397
  // run the completion again and return the result
398
398
 
@@ -432,7 +432,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
432
432
  let newMessages = [...messages];
433
433
  const lastMessage = messages[messages.length - 1];
434
434
 
435
- if (lastMessage instanceof TextMessage && lastMessage.role === "assistant") {
435
+ if (lastMessage.isTextMessage() && lastMessage.role === "assistant") {
436
436
  newMessages = newMessages.slice(0, -1);
437
437
  }
438
438
 
@@ -1,5 +1,10 @@
1
1
  import { useEffect } from "react";
2
- import { CopilotContextParams, useCopilotContext } from "../context";
2
+ import {
3
+ CopilotContextParams,
4
+ CopilotMessagesContextParams,
5
+ useCopilotContext,
6
+ useCopilotMessagesContext,
7
+ } from "../context";
3
8
  import { CoagentState } from "../types/coagent-state";
4
9
  import { useCopilotChat } from "./use-copilot-chat";
5
10
  import { AgentStateMessage, Message, Role, TextMessage } from "@copilotkit/runtime-client-gql";
@@ -59,7 +64,9 @@ export function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentRe
59
64
  return "initialState" in options;
60
65
  };
61
66
 
62
- const context = useCopilotContext();
67
+ const generalContext = useCopilotContext();
68
+ const messagesContext = useCopilotMessagesContext();
69
+ const context = { ...generalContext, ...messagesContext };
63
70
  const { coagentStates, setCoagentStates } = context;
64
71
  const { appendMessage } = useCopilotChat();
65
72
 
@@ -147,7 +154,7 @@ function stopAgent(name: string, context: CopilotContextParams) {
147
154
 
148
155
  async function runAgent(
149
156
  name: string,
150
- context: CopilotContextParams,
157
+ context: CopilotContextParams & CopilotMessagesContextParams,
151
158
  appendMessage: (message: Message) => Promise<void>,
152
159
  hint?: HintFunction,
153
160
  ) {
@@ -161,7 +168,7 @@ async function runAgent(
161
168
  let previousState: any = null;
162
169
  for (let i = context.messages.length - 1; i >= 0; i--) {
163
170
  const message = context.messages[i];
164
- if (message instanceof AgentStateMessage && message.agentName === name) {
171
+ if (message.isAgentStateMessage() && message.agentName === name) {
165
172
  previousState = message.state;
166
173
  }
167
174
  }
@@ -46,6 +46,7 @@ import { useChat } from "./use-chat";
46
46
  import { defaultCopilotContextCategories } from "../components";
47
47
  import { MessageStatusCode } from "@copilotkit/runtime-client-gql";
48
48
  import { CoAgentStateRenderHandlerArguments } from "@copilotkit/shared";
49
+ import { useCopilotMessagesContext } from "../context";
49
50
 
50
51
  export interface UseCopilotChatOptions {
51
52
  /**
@@ -88,8 +89,6 @@ export function useCopilotChat({
88
89
  getContextString,
89
90
  getFunctionCallHandler,
90
91
  copilotApiConfig,
91
- messages,
92
- setMessages,
93
92
  isLoading,
94
93
  setIsLoading,
95
94
  chatInstructions,
@@ -101,6 +100,7 @@ export function useCopilotChat({
101
100
  agentSession,
102
101
  setAgentSession,
103
102
  } = useCopilotContext();
103
+ const { messages, setMessages } = useCopilotMessagesContext();
104
104
 
105
105
  // We need to ensure that makeSystemMessageCallback always uses the latest
106
106
  // useCopilotReadable data.
@@ -163,7 +163,7 @@ export class CopilotTask<T = any> {
163
163
  const functionCallHandler = context.getFunctionCallHandler(actions);
164
164
  const functionCalls = convertGqlOutputToMessages(
165
165
  response.data?.generateCopilotResponse?.messages || [],
166
- ).filter((m): m is ActionExecutionMessage => m instanceof ActionExecutionMessage);
166
+ ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());
167
167
 
168
168
  for (const functionCall of functionCalls) {
169
169
  await functionCallHandler({
@@ -13,7 +13,7 @@ import {
13
13
  convertGqlOutputToMessages,
14
14
  CopilotRequestType,
15
15
  } from "@copilotkit/runtime-client-gql";
16
- import { CopilotContextParams } from "../context";
16
+ import { CopilotContextParams, CopilotMessagesContextParams } from "../context";
17
17
  import { defaultCopilotContextCategories } from "../components";
18
18
  import { CopilotRuntimeClient } from "@copilotkit/runtime-client-gql";
19
19
  import {
@@ -42,7 +42,7 @@ type StreamHandlerArgs<T extends Parameter[] | [] = []> =
42
42
  | CompleteState<T>;
43
43
 
44
44
  interface ExtractOptions<T extends Parameter[]> {
45
- context: CopilotContextParams;
45
+ context: CopilotContextParams & CopilotMessagesContextParams;
46
46
  instructions: string;
47
47
  parameters: T;
48
48
  include?: IncludeOptions;
@@ -71,6 +71,7 @@ export async function extract<const T extends Parameter[]>({
71
71
 
72
72
  const action: Action<any> = {
73
73
  name: "extract",
74
+ description: instructions,
74
75
  parameters,
75
76
  handler: (args: any) => {},
76
77
  };
@@ -93,6 +94,11 @@ export async function extract<const T extends Parameter[]>({
93
94
  role: Role.System,
94
95
  });
95
96
 
97
+ const instructionsMessage: Message = new TextMessage({
98
+ content: makeInstructionsMessage(instructions),
99
+ role: Role.User,
100
+ });
101
+
96
102
  const headers = {
97
103
  ...(context.copilotApiConfig.headers || {}),
98
104
  ...(context.copilotApiConfig.publicApiKey
@@ -123,8 +129,8 @@ export async function extract<const T extends Parameter[]>({
123
129
 
124
130
  messages: convertMessagesToGqlInput(
125
131
  includeMessages
126
- ? [systemMessage, ...filterAgentStateMessages(messages)]
127
- : [systemMessage],
132
+ ? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)]
133
+ : [systemMessage, instructionsMessage],
128
134
  ),
129
135
  metadata: {
130
136
  requestType: requestType,
@@ -158,7 +164,7 @@ export async function extract<const T extends Parameter[]>({
158
164
 
159
165
  actionExecutionMessage = convertGqlOutputToMessages(
160
166
  value.generateCopilotResponse.messages,
161
- ).find((msg) => msg instanceof ActionExecutionMessage) as ActionExecutionMessage | undefined;
167
+ ).find((msg) => msg.isActionExecutionMessage()) as ActionExecutionMessage | undefined;
162
168
 
163
169
  if (!actionExecutionMessage) {
164
170
  continue;
@@ -184,6 +190,20 @@ export async function extract<const T extends Parameter[]>({
184
190
  return actionExecutionMessage.arguments as MappedParameterTypes<T>;
185
191
  }
186
192
 
193
+ // We need to put this in a user message since some LLMs need
194
+ // at least one user message to function
195
+ function makeInstructionsMessage(instructions: string): string {
196
+ return `
197
+ The user has given you the following task to complete:
198
+
199
+ \`\`\`
200
+ ${instructions}
201
+ \`\`\`
202
+
203
+ Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
204
+ `;
205
+ }
206
+
187
207
  function makeSystemMessage(contextString: string, instructions: string): string {
188
208
  return `
189
209
  Please act as an efficient, competent, conscientious, and industrious professional assistant.
@@ -201,13 +221,5 @@ They have also provided you with a function called extract you MUST call to init
201
221
  Please assist them as best you can.
202
222
 
203
223
  This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
204
-
205
- The user has given you the following task to complete:
206
-
207
- \`\`\`
208
- ${instructions}
209
- \`\`\`
210
-
211
- Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
212
224
  `;
213
225
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"sourcesContent":["/**\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n * }\n * ```\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\";\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 messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n\n coagentStates,\n setCoagentStates,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\n } = useCopilotContext();\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"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,SAAS,QAAQ,WAAW,mBAAmB;AAE/C,SAAkB,MAAM,mBAAmB;AAwCpC,SAAS,eAAe,KAGJ,CAAC,GAAyB;AAHtB,eAC7B;AAAA;AAAA,EAnFF,IAkF+B,IAE1B,oBAF0B,IAE1B;AAAA,IADH;AAAA;AAGA,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,kBAAkB;AAItB,QAAM,yBAAyB,cAAc,gBAAgB;AAC7D,QAAM,gBAAgB;AAAA,IACpB,CAAC,cAAsB;AACrB,kBAAY,CAAC,SAAS,KAAK,OAAO,CAAC,YAAY,QAAQ,OAAO,SAAS,CAAC;AAAA,IAC1E;AAAA,IACA,CAAC,WAAW;AAAA,EACd;AAEA,QAAM,4BAA4B,YAAY,MAAM;AAClD,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EA,QAAM,eAAe,cAAc,MAAM;AACzC,QAAM,mBAAmB,YAAY,MAAM;AACzC,WAAO,aAAa,QAAQ;AAAA,EAC9B,GAAG,CAAC,YAAY,CAAC;AAEjB,QAAM,aAAa,cAAc,IAAI;AACrC,QAAM,iBAAiB,YAAY,MAAM;AACvC,WAAO,WAAW,QAAQ;AAAA,EAC5B,GAAG,CAAC,UAAU,CAAC;AAEf,QAAM,eAAe,cAAc,aAAa;AAChD,QAAM,mBAAmB;AAAA,IACvB,CAAC,cAAsB;AACrB,aAAO,aAAa,QAAQ,SAAS;AAAA,IACvC;AAAA,IACA,CAAC,YAAY;AAAA,EACf;AAEA,QAAM,oBAAoB,cAAc,WAAW;AACnD,QAAM,wBAAwB;AAAA,IAC5B,CAACE,cAAwB;AACvB,aAAO,kBAAkB,QAAQA,SAAQ;AAAA,IAC3C;AAAA,IACA,CAAC,iBAAiB;AAAA,EACpB;AAEA,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf,aAAa;AAAA,IACb,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,eAAe;AAAA,IACf;AAAA,EACF;AACF;AAIA,SAAS,cAAiB,OAAU;AAClC,QAAM,MAAM,OAAO,KAAK;AAExB,YAAU,MAAM;AACd,QAAI,UAAU;AAAA,EAChB,GAAG,CAAC,KAAK,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":["_a","action","messages"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/context/copilot-context.tsx"],"sourcesContent":["import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\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\";\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 // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\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\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 messages: [],\n setMessages: () => returnAndThrowInDebug([]),\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\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":";;;;;AAGA,OAAO,WAAW;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/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