@copilotkit/react-core 1.4.1-pre.5 → 1.4.1

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 (130) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/dist/chunk-2KCEHGSI.mjs +192 -0
  3. package/dist/chunk-2KCEHGSI.mjs.map +1 -0
  4. package/dist/{chunk-IIGBMHZI.mjs → chunk-DT52QX4H.mjs} +4 -4
  5. package/dist/{chunk-TRXKPXDE.mjs → chunk-H4VZMKR6.mjs} +2 -2
  6. package/dist/{chunk-OQ326E7V.mjs → chunk-JDQCJCAQ.mjs} +18 -5
  7. package/dist/chunk-JDQCJCAQ.mjs.map +1 -0
  8. package/dist/chunk-L34MHAXR.mjs +1 -0
  9. package/dist/{chunk-HVWV4SDG.mjs → chunk-LMFSB5D5.mjs} +2 -2
  10. package/dist/{chunk-2MPUQRAY.mjs → chunk-LODRWFMB.mjs} +2 -1
  11. package/dist/chunk-LODRWFMB.mjs.map +1 -0
  12. package/dist/chunk-MLAS4QUR.mjs +18 -0
  13. package/dist/chunk-MLAS4QUR.mjs.map +1 -0
  14. package/dist/{chunk-K76NL2VN.mjs → chunk-MWZO6TUR.mjs} +2 -2
  15. package/dist/chunk-O7ARI5CV.mjs +31 -0
  16. package/dist/chunk-O7ARI5CV.mjs.map +1 -0
  17. package/dist/chunk-ODN4H66E.mjs +31 -0
  18. package/dist/chunk-ODN4H66E.mjs.map +1 -0
  19. package/dist/{chunk-6YEMNWKE.mjs → chunk-P6VS7ST4.mjs} +177 -5
  20. package/dist/chunk-P6VS7ST4.mjs.map +1 -0
  21. package/dist/{chunk-ANOG3W5S.mjs → chunk-QDGDXRRJ.mjs} +2 -2
  22. package/dist/{chunk-VE63DJCR.mjs → chunk-V22C3DOQ.mjs} +3 -3
  23. package/dist/{chunk-MTVKTUZD.mjs → chunk-XINZBP3J.mjs} +2 -2
  24. package/dist/components/copilot-provider/copilotkit.d.ts +2 -1
  25. package/dist/components/copilot-provider/copilotkit.js +283 -26
  26. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  27. package/dist/components/copilot-provider/copilotkit.mjs +8 -2
  28. package/dist/components/copilot-provider/index.js +281 -26
  29. package/dist/components/copilot-provider/index.js.map +1 -1
  30. package/dist/components/copilot-provider/index.mjs +6 -3
  31. package/dist/components/index.js +281 -26
  32. package/dist/components/index.js.map +1 -1
  33. package/dist/components/index.mjs +6 -4
  34. package/dist/components/toast/exclamation-mark-icon.d.ts +9 -0
  35. package/dist/components/toast/exclamation-mark-icon.js +55 -0
  36. package/dist/components/toast/exclamation-mark-icon.js.map +1 -0
  37. package/dist/components/toast/exclamation-mark-icon.mjs +8 -0
  38. package/dist/components/toast/toast-provider.d.ts +29 -0
  39. package/dist/components/toast/toast-provider.js +255 -0
  40. package/dist/components/toast/toast-provider.js.map +1 -0
  41. package/dist/components/toast/toast-provider.mjs +11 -0
  42. package/dist/context/copilot-context.d.ts +2 -0
  43. package/dist/context/copilot-context.js +1 -0
  44. package/dist/context/copilot-context.js.map +1 -1
  45. package/dist/context/copilot-context.mjs +1 -1
  46. package/dist/context/index.js +1 -0
  47. package/dist/context/index.js.map +1 -1
  48. package/dist/context/index.mjs +1 -1
  49. package/dist/hooks/index.d.ts +1 -0
  50. package/dist/hooks/index.js +104 -62
  51. package/dist/hooks/index.js.map +1 -1
  52. package/dist/hooks/index.mjs +17 -12
  53. package/dist/hooks/use-chat.js +65 -26
  54. package/dist/hooks/use-chat.js.map +1 -1
  55. package/dist/hooks/use-chat.mjs +4 -1
  56. package/dist/hooks/use-coagent-state-render.js +1 -0
  57. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  58. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  59. package/dist/hooks/use-coagent.js +83 -43
  60. package/dist/hooks/use-coagent.js.map +1 -1
  61. package/dist/hooks/use-coagent.mjs +9 -7
  62. package/dist/hooks/use-copilot-action.js +1 -0
  63. package/dist/hooks/use-copilot-action.js.map +1 -1
  64. package/dist/hooks/use-copilot-action.mjs +2 -2
  65. package/dist/hooks/use-copilot-chat.js +85 -45
  66. package/dist/hooks/use-copilot-chat.js.map +1 -1
  67. package/dist/hooks/use-copilot-chat.mjs +8 -6
  68. package/dist/hooks/use-copilot-readable.js +1 -0
  69. package/dist/hooks/use-copilot-readable.js.map +1 -1
  70. package/dist/hooks/use-copilot-readable.mjs +2 -2
  71. package/dist/hooks/use-copilot-runtime-client.d.ts +5 -0
  72. package/dist/hooks/use-copilot-runtime-client.js +76 -0
  73. package/dist/hooks/use-copilot-runtime-client.js.map +1 -0
  74. package/dist/hooks/use-copilot-runtime-client.mjs +10 -0
  75. package/dist/hooks/use-make-copilot-document-readable.js +1 -0
  76. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  77. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  78. package/dist/index.d.ts +2 -0
  79. package/dist/index.js +500 -241
  80. package/dist/index.js.map +1 -1
  81. package/dist/index.mjs +24 -19
  82. package/dist/lib/copilot-task.d.ts +1 -0
  83. package/dist/lib/copilot-task.js.map +1 -1
  84. package/dist/lib/copilot-task.mjs +7 -5
  85. package/dist/lib/index.d.ts +1 -0
  86. package/dist/lib/index.js.map +1 -1
  87. package/dist/lib/index.mjs +7 -5
  88. package/dist/utils/dev-console.d.ts +3 -0
  89. package/dist/utils/dev-console.js +42 -0
  90. package/dist/utils/dev-console.js.map +1 -0
  91. package/dist/utils/dev-console.mjs +8 -0
  92. package/dist/utils/dev-console.mjs.map +1 -0
  93. package/dist/utils/extract.js +4 -26
  94. package/dist/utils/extract.js.map +1 -1
  95. package/dist/utils/extract.mjs +6 -5
  96. package/dist/utils/index.d.ts +1 -0
  97. package/dist/utils/index.js +22 -28
  98. package/dist/utils/index.js.map +1 -1
  99. package/dist/utils/index.mjs +10 -7
  100. package/package.json +5 -5
  101. package/src/components/copilot-provider/copilotkit.tsx +32 -1
  102. package/src/components/toast/exclamation-mark-icon.tsx +27 -0
  103. package/src/components/toast/toast-provider.tsx +209 -0
  104. package/src/context/copilot-context.tsx +5 -0
  105. package/src/hooks/index.ts +1 -0
  106. package/src/hooks/use-chat.ts +14 -6
  107. package/src/hooks/use-copilot-runtime-client.ts +24 -0
  108. package/src/utils/dev-console.ts +18 -0
  109. package/src/utils/extract.ts +2 -16
  110. package/src/utils/index.ts +1 -0
  111. package/dist/chunk-2MPUQRAY.mjs.map +0 -1
  112. package/dist/chunk-6YEMNWKE.mjs.map +0 -1
  113. package/dist/chunk-BWYAGPEF.mjs +0 -1
  114. package/dist/chunk-JD7BAH7U.mjs +0 -1
  115. package/dist/chunk-OQ326E7V.mjs.map +0 -1
  116. package/dist/chunk-SPCZTZCY.mjs +0 -1
  117. package/dist/chunk-YJLRG5U3.mjs +0 -1
  118. package/dist/chunk-ZM6HV22S.mjs +0 -164
  119. package/dist/chunk-ZM6HV22S.mjs.map +0 -1
  120. /package/dist/{chunk-IIGBMHZI.mjs.map → chunk-DT52QX4H.mjs.map} +0 -0
  121. /package/dist/{chunk-TRXKPXDE.mjs.map → chunk-H4VZMKR6.mjs.map} +0 -0
  122. /package/dist/{chunk-BWYAGPEF.mjs.map → chunk-L34MHAXR.mjs.map} +0 -0
  123. /package/dist/{chunk-HVWV4SDG.mjs.map → chunk-LMFSB5D5.mjs.map} +0 -0
  124. /package/dist/{chunk-K76NL2VN.mjs.map → chunk-MWZO6TUR.mjs.map} +0 -0
  125. /package/dist/{chunk-ANOG3W5S.mjs.map → chunk-QDGDXRRJ.mjs.map} +0 -0
  126. /package/dist/{chunk-VE63DJCR.mjs.map → chunk-V22C3DOQ.mjs.map} +0 -0
  127. /package/dist/{chunk-MTVKTUZD.mjs.map → chunk-XINZBP3J.mjs.map} +0 -0
  128. /package/dist/{chunk-JD7BAH7U.mjs.map → components/toast/exclamation-mark-icon.mjs.map} +0 -0
  129. /package/dist/{chunk-SPCZTZCY.mjs.map → components/toast/toast-provider.mjs.map} +0 -0
  130. /package/dist/{chunk-YJLRG5U3.mjs.map → hooks/use-copilot-runtime-client.mjs.map} +0 -0
@@ -2,21 +2,7 @@
2
2
  var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __spreadValues = (a, b) => {
10
- for (var prop in b || (b = {}))
11
- if (__hasOwnProp.call(b, prop))
12
- __defNormalProp(a, prop, b[prop]);
13
- if (__getOwnPropSymbols)
14
- for (var prop of __getOwnPropSymbols(b)) {
15
- if (__propIsEnum.call(b, prop))
16
- __defNormalProp(a, prop, b[prop]);
17
- }
18
- return a;
19
- };
20
6
  var __export = (target, all) => {
21
7
  for (var name in all)
22
8
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -54,7 +40,8 @@ var __async = (__this, __arguments, generator) => {
54
40
  // src/utils/index.ts
55
41
  var utils_exports = {};
56
42
  __export(utils_exports, {
57
- extract: () => extract
43
+ extract: () => extract,
44
+ shouldShowDevConsole: () => shouldShowDevConsole
58
45
  });
59
46
  module.exports = __toCommonJS(utils_exports);
60
47
 
@@ -71,7 +58,6 @@ var defaultCopilotContextCategories = ["global"];
71
58
 
72
59
  // src/utils/extract.ts
73
60
  var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
74
- var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
75
61
  function extract(_0) {
76
62
  return __async(this, arguments, function* ({
77
63
  context,
@@ -109,15 +95,8 @@ function extract(_0) {
109
95
  content: makeInstructionsMessage(instructions),
110
96
  role: import_runtime_client_gql.Role.User
111
97
  });
112
- const headers = __spreadValues(__spreadValues({}, context.copilotApiConfig.headers || {}), context.copilotApiConfig.publicApiKey ? { [import_shared2.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: context.copilotApiConfig.publicApiKey } : {});
113
- const runtimeClient = new import_runtime_client_gql2.CopilotRuntimeClient({
114
- url: context.copilotApiConfig.chatApiEndpoint,
115
- publicApiKey: context.copilotApiConfig.publicApiKey,
116
- headers,
117
- credentials: context.copilotApiConfig.credentials
118
- });
119
- const response = import_runtime_client_gql2.CopilotRuntimeClient.asStream(
120
- runtimeClient.generateCopilotResponse({
98
+ const response = context.runtimeClient.asStream(
99
+ context.runtimeClient.generateCopilotResponse({
121
100
  data: {
122
101
  frontend: {
123
102
  actions: [
@@ -129,8 +108,8 @@ function extract(_0) {
129
108
  ],
130
109
  url: window.location.href
131
110
  },
132
- messages: (0, import_runtime_client_gql3.convertMessagesToGqlInput)(
133
- includeMessages ? [systemMessage, instructionsMessage, ...(0, import_runtime_client_gql3.filterAgentStateMessages)(messages)] : [systemMessage, instructionsMessage]
111
+ messages: (0, import_runtime_client_gql2.convertMessagesToGqlInput)(
112
+ includeMessages ? [systemMessage, instructionsMessage, ...(0, import_runtime_client_gql2.filterAgentStateMessages)(messages)] : [systemMessage, instructionsMessage]
134
113
  ),
135
114
  metadata: {
136
115
  requestType
@@ -207,8 +186,23 @@ Please assist them as best you can.
207
186
  This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
208
187
  `;
209
188
  }
189
+
190
+ // src/utils/dev-console.ts
191
+ function shouldShowDevConsole(showDevConsole) {
192
+ if (typeof showDevConsole === "boolean") {
193
+ return showDevConsole;
194
+ }
195
+ return getHostname() === "localhost" || getHostname() === "127.0.0.1" || getHostname() === "0.0.0.0" || getHostname() === "::1";
196
+ }
197
+ function getHostname() {
198
+ if (typeof window !== "undefined" && window.location) {
199
+ return window.location.hostname;
200
+ }
201
+ return "";
202
+ }
210
203
  // Annotate the CommonJS export names for ESM import in node:
211
204
  0 && (module.exports = {
212
- extract
205
+ extract,
206
+ shouldShowDevConsole
213
207
  });
214
208
  //# sourceMappingURL=index.js.map
@@ -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, 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":"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","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":"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","names":["import_shared","import_runtime_client_gql"]}
@@ -1,17 +1,20 @@
1
- import "../chunk-YJLRG5U3.mjs";
2
1
  import {
3
2
  extract
4
- } from "../chunk-ZM6HV22S.mjs";
5
- import "../chunk-JD7BAH7U.mjs";
6
- import "../chunk-SPCZTZCY.mjs";
7
- import "../chunk-6YEMNWKE.mjs";
3
+ } from "../chunk-P6VS7ST4.mjs";
4
+ import {
5
+ shouldShowDevConsole
6
+ } from "../chunk-MLAS4QUR.mjs";
8
7
  import "../chunk-XXR4QFAQ.mjs";
9
8
  import "../chunk-5FHSUKQL.mjs";
10
9
  import "../chunk-6U3UH3KO.mjs";
11
10
  import "../chunk-DCTJZ742.mjs";
12
- import "../chunk-2MPUQRAY.mjs";
11
+ import "../chunk-ODN4H66E.mjs";
12
+ import "../chunk-2KCEHGSI.mjs";
13
+ import "../chunk-O7ARI5CV.mjs";
14
+ import "../chunk-LODRWFMB.mjs";
13
15
  import "../chunk-SKC7AJIV.mjs";
14
16
  export {
15
- extract
17
+ extract,
18
+ shouldShowDevConsole
16
19
  };
17
20
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "publishConfig": {
10
10
  "access": "public"
11
11
  },
12
- "version": "1.4.1-pre.5",
12
+ "version": "1.4.1",
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.1-pre.5",
40
- "tsconfig": "1.4.1-pre.5"
39
+ "eslint-config-custom": "1.4.1",
40
+ "tsconfig": "1.4.1"
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.4.1-pre.5",
46
- "@copilotkit/shared": "1.4.1-pre.5"
45
+ "@copilotkit/runtime-client-gql": "1.4.1",
46
+ "@copilotkit/shared": "1.4.1"
47
47
  },
48
48
  "keywords": [
49
49
  "copilotkit",
@@ -28,6 +28,7 @@ import {
28
28
  COPILOT_CLOUD_CHAT_URL,
29
29
  CopilotCloudConfig,
30
30
  FunctionCallHandler,
31
+ COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
31
32
  } from "@copilotkit/shared";
32
33
 
33
34
  import { FrontendAction } from "../../types/frontend-action";
@@ -36,8 +37,21 @@ import { CopilotKitProps } from "./copilotkit-props";
36
37
  import { CoAgentStateRender } from "../../types/coagent-action";
37
38
  import { CoagentState } from "../../types/coagent-state";
38
39
  import { CopilotMessages } from "./copilot-messages";
40
+ import { ToastProvider } from "../toast/toast-provider";
41
+ import { useCopilotRuntimeClient } from "../../hooks/use-copilot-runtime-client";
42
+ import { shouldShowDevConsole } from "../../utils";
39
43
 
40
44
  export function CopilotKit({ children, ...props }: CopilotKitProps) {
45
+ const showDevConsole = props.showDevConsole === undefined ? "auto" : props.showDevConsole;
46
+ const enabled = shouldShowDevConsole(showDevConsole);
47
+ return (
48
+ <ToastProvider enabled={enabled}>
49
+ <CopilotKitInternal {...props}>{children}</CopilotKitInternal>
50
+ </ToastProvider>
51
+ );
52
+ }
53
+
54
+ export function CopilotKitInternal({ children, ...props }: CopilotKitProps) {
41
55
  // Compute all the functions and properties that we need to pass
42
56
  // to the CopilotContext.
43
57
 
@@ -207,6 +221,20 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
207
221
  props.cloudRestrictToTopic,
208
222
  ]);
209
223
 
224
+ const headers = {
225
+ ...(copilotApiConfig.headers || {}),
226
+ ...(copilotApiConfig.publicApiKey
227
+ ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }
228
+ : {}),
229
+ };
230
+
231
+ const runtimeClient = useCopilotRuntimeClient({
232
+ url: copilotApiConfig.chatApiEndpoint,
233
+ publicApiKey: copilotApiConfig.publicApiKey,
234
+ headers,
235
+ credentials: copilotApiConfig.credentials,
236
+ });
237
+
210
238
  const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{
211
239
  [key: string]: CopilotChatSuggestionConfiguration;
212
240
  }>({});
@@ -235,6 +263,8 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
235
263
 
236
264
  const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);
237
265
 
266
+ const showDevConsole = props.showDevConsole === undefined ? "auto" : props.showDevConsole;
267
+
238
268
  return (
239
269
  <CopilotContext.Provider
240
270
  value={{
@@ -260,11 +290,12 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
260
290
  removeChatSuggestionConfiguration,
261
291
  chatInstructions,
262
292
  setChatInstructions,
263
- showDevConsole: props.showDevConsole === undefined ? "auto" : props.showDevConsole,
293
+ showDevConsole,
264
294
  coagentStates,
265
295
  setCoagentStates,
266
296
  agentSession,
267
297
  setAgentSession,
298
+ runtimeClient,
268
299
  }}
269
300
  >
270
301
  <CopilotMessages>{children}</CopilotMessages>
@@ -0,0 +1,27 @@
1
+ import React from "react";
2
+
3
+ export const ExclamationMarkIcon = ({
4
+ className,
5
+ style,
6
+ }: {
7
+ className?: string;
8
+ style?: React.CSSProperties;
9
+ }) => (
10
+ <svg
11
+ xmlns="http://www.w3.org/2000/svg"
12
+ width="24"
13
+ height="24"
14
+ viewBox="0 0 24 24"
15
+ fill="none"
16
+ stroke="currentColor"
17
+ strokeWidth="2"
18
+ strokeLinecap="round"
19
+ strokeLinejoin="round"
20
+ className={`lucide lucide-circle-alert ${className ? className : ""}`}
21
+ style={style}
22
+ >
23
+ <circle cx="12" cy="12" r="10" />
24
+ <line x1="12" x2="12" y1="8" y2="12" />
25
+ <line x1="12" x2="12.01" y1="16" y2="16" />
26
+ </svg>
27
+ );
@@ -0,0 +1,209 @@
1
+ import { useCopilotContext } from "../../context";
2
+ import { GraphQLError } from "@copilotkit/runtime-client-gql";
3
+ import React, { createContext, useContext, useState, useCallback } from "react";
4
+ import { ExclamationMarkIcon } from "./exclamation-mark-icon";
5
+
6
+ interface Toast {
7
+ id: string;
8
+ message: string | React.ReactNode;
9
+ type: "info" | "success" | "warning" | "error";
10
+ duration?: number;
11
+ }
12
+
13
+ interface ToastContextValue {
14
+ toasts: Toast[];
15
+ addToast: (toast: Omit<Toast, "id">) => void;
16
+ addGraphQLErrorsToast: (errors: GraphQLError[]) => void;
17
+ removeToast: (id: string) => void;
18
+ enabled: boolean;
19
+ }
20
+
21
+ const ToastContext = createContext<ToastContextValue | undefined>(undefined);
22
+
23
+ export function useToast() {
24
+ const context = useContext(ToastContext);
25
+ if (!context) {
26
+ throw new Error("useToast must be used within a ToastProvider");
27
+ }
28
+ return context;
29
+ }
30
+
31
+ export function ToastProvider({
32
+ enabled,
33
+ children,
34
+ }: {
35
+ enabled: boolean;
36
+ children: React.ReactNode;
37
+ }) {
38
+ const [toasts, setToasts] = useState<Toast[]>([]);
39
+ const addToast = useCallback((toast: Omit<Toast, "id">) => {
40
+ const id = Math.random().toString(36).substring(2, 9);
41
+
42
+ setToasts((currentToasts) => [...currentToasts, { ...toast, id }]);
43
+
44
+ if (toast.duration) {
45
+ setTimeout(() => {
46
+ removeToast(id);
47
+ }, toast.duration);
48
+ }
49
+ }, []);
50
+
51
+ const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {
52
+ // We do not display these errors unless we are in dev mode.
53
+ // if (!showDevConsole) {
54
+ // return;
55
+ // }
56
+
57
+ const errorsToRender = errors.map((error, idx) => {
58
+ const message = error.message;
59
+ const code = error.extensions?.code as string;
60
+
61
+ return (
62
+ <div
63
+ key={idx}
64
+ style={{
65
+ marginTop: idx === 0 ? 0 : 10,
66
+ marginBottom: 14,
67
+ }}
68
+ >
69
+ <ExclamationMarkIcon style={{ marginBottom: 4 }} />
70
+
71
+ {code && (
72
+ <div
73
+ style={{
74
+ fontWeight: "600",
75
+ marginBottom: 4,
76
+ }}
77
+ >
78
+ Copilot Cloud Error:{" "}
79
+ <span style={{ fontFamily: "monospace", fontWeight: "normal" }}>{code}</span>
80
+ </div>
81
+ )}
82
+ <div>{message}</div>
83
+ </div>
84
+ );
85
+ });
86
+
87
+ addToast({
88
+ type: "error",
89
+ message: (
90
+ <div
91
+ style={{
92
+ fontSize: "13px",
93
+ maxWidth: "600px",
94
+ }}
95
+ >
96
+ {errorsToRender}
97
+ <div style={{ fontSize: "11px", opacity: 0.75 }}>
98
+ NOTE: This is a Copilot Cloud error, and it only displays during local development.
99
+ </div>
100
+ </div>
101
+ ),
102
+ });
103
+ }, []);
104
+
105
+ const removeToast = useCallback((id: string) => {
106
+ setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));
107
+ }, []);
108
+
109
+ const value = {
110
+ toasts,
111
+ addToast,
112
+ addGraphQLErrorsToast,
113
+ removeToast,
114
+ enabled,
115
+ };
116
+
117
+ return (
118
+ <ToastContext.Provider value={value}>
119
+ <div
120
+ style={{
121
+ position: "fixed",
122
+ bottom: "1rem",
123
+ left: "50%",
124
+ transform: "translateX(-50%)",
125
+ zIndex: 50,
126
+ display: "flex",
127
+ flexDirection: "column",
128
+ gap: "0.5rem",
129
+ }}
130
+ >
131
+ {toasts.length > 1 && (
132
+ <div style={{ textAlign: "right" }}>
133
+ <button
134
+ onClick={() => setToasts([])}
135
+ style={{
136
+ padding: "4px 8px",
137
+ fontSize: "12px",
138
+ cursor: "pointer",
139
+ background: "white",
140
+ border: "1px solid rgba(0,0,0,0.2)",
141
+ borderRadius: "4px",
142
+ }}
143
+ >
144
+ Close All
145
+ </button>
146
+ </div>
147
+ )}
148
+ {toasts.map((toast) => (
149
+ <Toast
150
+ key={toast.id}
151
+ message={toast.message}
152
+ type={toast.type}
153
+ onClose={() => removeToast(toast.id)}
154
+ />
155
+ ))}
156
+ </div>
157
+ {children}
158
+ </ToastContext.Provider>
159
+ );
160
+ }
161
+
162
+ function Toast({
163
+ message,
164
+ type = "info",
165
+ onClose,
166
+ }: {
167
+ message: string | React.ReactNode;
168
+ type: "info" | "success" | "warning" | "error";
169
+ onClose: () => void;
170
+ }) {
171
+ const bgColors = {
172
+ info: "#3b82f6",
173
+ success: "#22c55e",
174
+ warning: "#eab308",
175
+ error: "#ef4444",
176
+ };
177
+
178
+ return (
179
+ <div
180
+ style={{
181
+ backgroundColor: bgColors[type],
182
+ color: "white",
183
+ padding: "0.5rem 1rem",
184
+ borderRadius: "0.25rem",
185
+ boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
186
+ position: "relative",
187
+ minWidth: "200px",
188
+ }}
189
+ >
190
+ <div>{message}</div>
191
+ <button
192
+ onClick={onClose}
193
+ style={{
194
+ position: "absolute",
195
+ top: "0",
196
+ right: "0",
197
+ background: "none",
198
+ border: "none",
199
+ color: "white",
200
+ cursor: "pointer",
201
+ padding: "0.5rem",
202
+ fontSize: "1rem",
203
+ }}
204
+ >
205
+
206
+ </button>
207
+ </div>
208
+ );
209
+ }
@@ -6,6 +6,7 @@ import { DocumentPointer } from "../types";
6
6
  import { CopilotChatSuggestionConfiguration } from "../types/chat-suggestion-configuration";
7
7
  import { CoAgentStateRender, CoAgentStateRenderProps } from "../types/coagent-action";
8
8
  import { CoagentState } from "../types/coagent-state";
9
+ import { CopilotRuntimeClient } from "@copilotkit/runtime-client-gql";
9
10
 
10
11
  /**
11
12
  * Interface for the configuration of the Copilot API.
@@ -133,6 +134,9 @@ export interface CopilotContextParams {
133
134
  setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;
134
135
  agentSession: AgentSession | null;
135
136
  setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;
137
+
138
+ // runtime
139
+ runtimeClient: CopilotRuntimeClient;
136
140
  }
137
141
 
138
142
  const emptyCopilotContext: CopilotContextParams = {
@@ -161,6 +165,7 @@ const emptyCopilotContext: CopilotContextParams = {
161
165
  getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),
162
166
  addDocumentContext: () => returnAndThrowInDebug(""),
163
167
  removeDocumentContext: () => {},
168
+ runtimeClient: {} as any,
164
169
 
165
170
  copilotApiConfig: new (class implements CopilotApiConfig {
166
171
  get chatApiEndpoint(): string {
@@ -8,3 +8,4 @@ export { useMakeCopilotDocumentReadable } from "./use-make-copilot-document-read
8
8
  export { type UseChatHelpers } from "./use-chat";
9
9
  export { useCopilotReadable } from "./use-copilot-readable";
10
10
  export { useCoAgent } from "./use-coagent";
11
+ export { useCopilotRuntimeClient } from "./use-copilot-runtime-client";
@@ -8,9 +8,7 @@ import {
8
8
  import {
9
9
  Message,
10
10
  TextMessage,
11
- ActionExecutionMessage,
12
11
  ResultMessage,
13
- CopilotRuntimeClient,
14
12
  convertMessagesToGqlInput,
15
13
  filterAdjacentAgentStateMessages,
16
14
  filterAgentStateMessages,
@@ -19,7 +17,6 @@ import {
19
17
  MessageRole,
20
18
  Role,
21
19
  CopilotRequestType,
22
- AgentStateMessage,
23
20
  ActionInputAvailability,
24
21
  } from "@copilotkit/runtime-client-gql";
25
22
 
@@ -27,6 +24,8 @@ import { CopilotApiConfig } from "../context";
27
24
  import { FrontendAction } from "../types/frontend-action";
28
25
  import { CoagentState } from "../types/coagent-state";
29
26
  import { AgentSession } from "../context/copilot-context";
27
+ import { useToast } from "../components/toast/toast-provider";
28
+ import { useCopilotRuntimeClient } from "./use-copilot-runtime-client";
30
29
 
31
30
  export type UseChatOptions = {
32
31
  /**
@@ -140,6 +139,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
140
139
  const abortControllerRef = useRef<AbortController>();
141
140
  const threadIdRef = useRef<string | null>(null);
142
141
  const runIdRef = useRef<string | null>(null);
142
+ const { addGraphQLErrorsToast } = useToast();
143
143
 
144
144
  const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();
145
145
  // We need to keep a ref of coagent states because of renderAndWait - making sure
@@ -157,7 +157,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
157
157
  ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),
158
158
  };
159
159
 
160
- const runtimeClient = new CopilotRuntimeClient({
160
+ const runtimeClient = useCopilotRuntimeClient({
161
161
  url: copilotConfig.chatApiEndpoint,
162
162
  publicApiKey: copilotConfig.publicApiKey,
163
163
  headers,
@@ -184,7 +184,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
184
184
 
185
185
  const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];
186
186
 
187
- const stream = CopilotRuntimeClient.asStream(
187
+ const stream = runtimeClient.asStream(
188
188
  runtimeClient.generateCopilotResponse({
189
189
  data: {
190
190
  frontend: {
@@ -262,7 +262,15 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
262
262
 
263
263
  try {
264
264
  while (true) {
265
- const { done, value } = await reader.read();
265
+ let done, value;
266
+
267
+ try {
268
+ const readResult = await reader.read();
269
+ done = readResult.done;
270
+ value = readResult.value;
271
+ } catch (readError) {
272
+ break;
273
+ }
266
274
 
267
275
  if (done) {
268
276
  break;