@copilotkit/react-core 0.38.0-mme-pre.0 → 0.38.0-mme-alpha.0

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 (165) hide show
  1. package/.turbo/turbo-build.log +187 -234
  2. package/CHANGELOG.md +4 -3
  3. package/dist/{chunk-NKIUZSGZ.mjs → chunk-5Q7DU3XW.mjs} +40 -40
  4. package/dist/chunk-5Q7DU3XW.mjs.map +1 -0
  5. package/dist/{chunk-B244LK6F.mjs → chunk-ATWK243A.mjs} +2 -2
  6. package/dist/{chunk-AJSY6LS5.mjs → chunk-FY3TQ7Q6.mjs} +17 -32
  7. package/dist/chunk-FY3TQ7Q6.mjs.map +1 -0
  8. package/dist/{chunk-SR4RW4CU.mjs → chunk-GFQBAEJL.mjs} +6 -6
  9. package/dist/chunk-GFQBAEJL.mjs.map +1 -0
  10. package/dist/{chunk-DY63PD22.mjs → chunk-GLPZSBNA.mjs} +4 -5
  11. package/dist/chunk-GLPZSBNA.mjs.map +1 -0
  12. package/dist/{chunk-S5LWO5V3.mjs → chunk-IBOL6LE5.mjs} +2 -2
  13. package/dist/{chunk-NSUYO6TP.mjs → chunk-MI7BERU7.mjs} +9 -9
  14. package/dist/chunk-MI7BERU7.mjs.map +1 -0
  15. package/dist/chunk-MW2IVCDP.mjs +188 -0
  16. package/dist/chunk-MW2IVCDP.mjs.map +1 -0
  17. package/dist/{chunk-ZHYCHXIO.mjs → chunk-PSZAPRNZ.mjs} +56 -42
  18. package/dist/chunk-PSZAPRNZ.mjs.map +1 -0
  19. package/dist/{chunk-DY4YVUO3.mjs → chunk-WJIS7HTH.mjs} +14 -25
  20. package/dist/chunk-WJIS7HTH.mjs.map +1 -0
  21. package/dist/{chunk-MNZXQ6UH.mjs → chunk-WTGFKR3D.mjs} +2 -2
  22. package/dist/chunk-YJLRG5U3.mjs +1 -0
  23. package/dist/components/copilot-provider/copilotkit.js +17 -32
  24. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  25. package/dist/components/copilot-provider/copilotkit.mjs +2 -2
  26. package/dist/components/copilot-provider/index.js +17 -32
  27. package/dist/components/copilot-provider/index.js.map +1 -1
  28. package/dist/components/copilot-provider/index.mjs +2 -2
  29. package/dist/components/index.js +17 -32
  30. package/dist/components/index.js.map +1 -1
  31. package/dist/components/index.mjs +2 -2
  32. package/dist/context/copilot-context.d.ts +5 -5
  33. package/dist/context/copilot-context.js +3 -4
  34. package/dist/context/copilot-context.js.map +1 -1
  35. package/dist/context/copilot-context.mjs +1 -1
  36. package/dist/context/index.d.ts +1 -0
  37. package/dist/context/index.js +3 -4
  38. package/dist/context/index.js.map +1 -1
  39. package/dist/context/index.mjs +1 -1
  40. package/dist/hooks/index.d.ts +2 -1
  41. package/dist/hooks/index.js +136 -232
  42. package/dist/hooks/index.js.map +1 -1
  43. package/dist/hooks/index.mjs +9 -10
  44. package/dist/hooks/use-chat.d.ts +26 -52
  45. package/dist/hooks/use-chat.js +104 -203
  46. package/dist/hooks/use-chat.js.map +1 -1
  47. package/dist/hooks/use-chat.mjs +1 -2
  48. package/dist/hooks/use-copilot-action.js +10 -11
  49. package/dist/hooks/use-copilot-action.js.map +1 -1
  50. package/dist/hooks/use-copilot-action.mjs +2 -2
  51. package/dist/hooks/use-copilot-chat.d.ts +1 -1
  52. package/dist/hooks/use-copilot-chat.js +119 -215
  53. package/dist/hooks/use-copilot-chat.js.map +1 -1
  54. package/dist/hooks/use-copilot-chat.mjs +4 -5
  55. package/dist/hooks/use-copilot-readable.js +3 -4
  56. package/dist/hooks/use-copilot-readable.js.map +1 -1
  57. package/dist/hooks/use-copilot-readable.mjs +2 -2
  58. package/dist/hooks/use-make-copilot-actionable.js +7 -8
  59. package/dist/hooks/use-make-copilot-actionable.js.map +1 -1
  60. package/dist/hooks/use-make-copilot-actionable.mjs +2 -2
  61. package/dist/hooks/use-make-copilot-document-readable.js +3 -4
  62. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  63. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  64. package/dist/hooks/use-make-copilot-readable.js +3 -4
  65. package/dist/hooks/use-make-copilot-readable.js.map +1 -1
  66. package/dist/hooks/use-make-copilot-readable.mjs +2 -2
  67. package/dist/index.d.ts +1 -3
  68. package/dist/index.js +227 -499
  69. package/dist/index.js.map +1 -1
  70. package/dist/index.mjs +12 -31
  71. package/dist/lib/copilot-task.d.ts +1 -0
  72. package/dist/lib/copilot-task.js +31 -110
  73. package/dist/lib/copilot-task.js.map +1 -1
  74. package/dist/lib/copilot-task.mjs +3 -4
  75. package/dist/lib/index.d.ts +1 -0
  76. package/dist/lib/index.js +33 -110
  77. package/dist/lib/index.js.map +1 -1
  78. package/dist/lib/index.mjs +3 -4
  79. package/dist/utils/extract.d.ts +1 -0
  80. package/dist/utils/extract.js +49 -109
  81. package/dist/utils/extract.js.map +1 -1
  82. package/dist/utils/extract.mjs +3 -4
  83. package/dist/utils/index.d.ts +1 -1
  84. package/dist/utils/index.js +52 -132
  85. package/dist/utils/index.js.map +1 -1
  86. package/dist/utils/index.mjs +5 -13
  87. package/package.json +6 -5
  88. package/src/components/copilot-provider/copilotkit.tsx +16 -33
  89. package/src/context/copilot-context.tsx +9 -16
  90. package/src/hooks/use-chat.ts +204 -212
  91. package/src/hooks/use-copilot-action.ts +7 -8
  92. package/src/hooks/use-copilot-chat.ts +12 -36
  93. package/src/hooks/use-make-copilot-actionable.ts +4 -4
  94. package/src/index.tsx +0 -1
  95. package/src/lib/copilot-task.ts +42 -42
  96. package/src/utils/extract.ts +61 -36
  97. package/src/utils/index.ts +0 -7
  98. package/dist/chunk-36FKUOWM.mjs +0 -137
  99. package/dist/chunk-36FKUOWM.mjs.map +0 -1
  100. package/dist/chunk-3XVO5UEG.mjs +0 -205
  101. package/dist/chunk-3XVO5UEG.mjs.map +0 -1
  102. package/dist/chunk-7GFKOIO7.mjs +0 -1
  103. package/dist/chunk-AJSY6LS5.mjs.map +0 -1
  104. package/dist/chunk-BABVSMJR.mjs +0 -1
  105. package/dist/chunk-BABVSMJR.mjs.map +0 -1
  106. package/dist/chunk-CYDWEPFL.mjs +0 -1
  107. package/dist/chunk-CYDWEPFL.mjs.map +0 -1
  108. package/dist/chunk-DY4YVUO3.mjs.map +0 -1
  109. package/dist/chunk-DY63PD22.mjs.map +0 -1
  110. package/dist/chunk-FRAKUJWH.mjs +0 -1
  111. package/dist/chunk-FRAKUJWH.mjs.map +0 -1
  112. package/dist/chunk-MJKBCG4U.mjs +0 -91
  113. package/dist/chunk-MJKBCG4U.mjs.map +0 -1
  114. package/dist/chunk-NKIUZSGZ.mjs.map +0 -1
  115. package/dist/chunk-NSUYO6TP.mjs.map +0 -1
  116. package/dist/chunk-SR4RW4CU.mjs.map +0 -1
  117. package/dist/chunk-ZFS5SQUT.mjs +0 -31
  118. package/dist/chunk-ZFS5SQUT.mjs.map +0 -1
  119. package/dist/chunk-ZHYCHXIO.mjs.map +0 -1
  120. package/dist/openai-assistants/hooks/index.d.ts +0 -2
  121. package/dist/openai-assistants/hooks/index.js +0 -277
  122. package/dist/openai-assistants/hooks/index.js.map +0 -1
  123. package/dist/openai-assistants/hooks/index.mjs +0 -18
  124. package/dist/openai-assistants/hooks/index.mjs.map +0 -1
  125. package/dist/openai-assistants/hooks/use-assistants.d.ts +0 -17
  126. package/dist/openai-assistants/hooks/use-assistants.js +0 -154
  127. package/dist/openai-assistants/hooks/use-assistants.js.map +0 -1
  128. package/dist/openai-assistants/hooks/use-assistants.mjs +0 -92
  129. package/dist/openai-assistants/hooks/use-assistants.mjs.map +0 -1
  130. package/dist/openai-assistants/hooks/use-copilot-chat-v2.d.ts +0 -44
  131. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js +0 -277
  132. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +0 -1
  133. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +0 -19
  134. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +0 -1
  135. package/dist/openai-assistants/index.d.ts +0 -3
  136. package/dist/openai-assistants/index.js +0 -279
  137. package/dist/openai-assistants/index.js.map +0 -1
  138. package/dist/openai-assistants/index.mjs +0 -22
  139. package/dist/openai-assistants/index.mjs.map +0 -1
  140. package/dist/openai-assistants/utils/index.d.ts +0 -1
  141. package/dist/openai-assistants/utils/index.js +0 -73
  142. package/dist/openai-assistants/utils/index.js.map +0 -1
  143. package/dist/openai-assistants/utils/index.mjs +0 -9
  144. package/dist/openai-assistants/utils/index.mjs.map +0 -1
  145. package/dist/openai-assistants/utils/process-message-stream.d.ts +0 -3
  146. package/dist/openai-assistants/utils/process-message-stream.js +0 -71
  147. package/dist/openai-assistants/utils/process-message-stream.js.map +0 -1
  148. package/dist/openai-assistants/utils/process-message-stream.mjs +0 -8
  149. package/dist/openai-assistants/utils/process-message-stream.mjs.map +0 -1
  150. package/dist/utils/fetch-chat-completion.d.ts +0 -36
  151. package/dist/utils/fetch-chat-completion.js +0 -141
  152. package/dist/utils/fetch-chat-completion.js.map +0 -1
  153. package/dist/utils/fetch-chat-completion.mjs +0 -12
  154. package/dist/utils/fetch-chat-completion.mjs.map +0 -1
  155. package/src/openai-assistants/hooks/index.ts +0 -9
  156. package/src/openai-assistants/hooks/use-assistants.ts +0 -112
  157. package/src/openai-assistants/hooks/use-copilot-chat-v2.ts +0 -189
  158. package/src/openai-assistants/index.ts +0 -2
  159. package/src/openai-assistants/utils/index.ts +0 -1
  160. package/src/openai-assistants/utils/process-message-stream.ts +0 -25
  161. package/src/utils/fetch-chat-completion.ts +0 -120
  162. /package/dist/{chunk-B244LK6F.mjs.map → chunk-ATWK243A.mjs.map} +0 -0
  163. /package/dist/{chunk-S5LWO5V3.mjs.map → chunk-IBOL6LE5.mjs.map} +0 -0
  164. /package/dist/{chunk-MNZXQ6UH.mjs.map → chunk-WTGFKR3D.mjs.map} +0 -0
  165. /package/dist/{chunk-7GFKOIO7.mjs.map → chunk-YJLRG5U3.mjs.map} +0 -0
@@ -1,14 +1,20 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-AJSY6LS5.mjs";
4
- import {
5
- fetchAndDecodeChatCompletion
6
- } from "./chunk-MJKBCG4U.mjs";
3
+ } from "./chunk-FY3TQ7Q6.mjs";
7
4
  import {
8
5
  __async
9
6
  } from "./chunk-SKC7AJIV.mjs";
10
7
 
11
8
  // src/lib/copilot-task.ts
9
+ import {
10
+ ActionExecutionMessage,
11
+ CopilotRuntimeClient,
12
+ Role,
13
+ TextMessage,
14
+ convertGqlOutputToMessages,
15
+ convertMessagesToGqlInput
16
+ } from "@copilotkit/runtime-client-gql";
17
+ import { actionParametersToJsonSchema } from "@copilotkit/shared";
12
18
  var CopilotTask = class {
13
19
  constructor(config) {
14
20
  this.instructions = config.instructions;
@@ -23,9 +29,10 @@ var CopilotTask = class {
23
29
  */
24
30
  run(context, data) {
25
31
  return __async(this, null, function* () {
26
- const entryPoints = this.includeCopilotActions ? Object.assign({}, context.entryPoints) : {};
32
+ var _a, _b;
33
+ const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
27
34
  for (const fn of this.actions) {
28
- entryPoints[fn.name] = fn;
35
+ actions[fn.name] = fn;
29
36
  }
30
37
  let contextString = "";
31
38
  if (data) {
@@ -34,43 +41,36 @@ var CopilotTask = class {
34
41
  if (this.includeCopilotReadable) {
35
42
  contextString += context.getContextString([], defaultCopilotContextCategories);
36
43
  }
37
- const systemMessage = {
38
- id: "system",
44
+ const systemMessage = new TextMessage({
39
45
  content: taskSystemMessage(contextString, this.instructions),
40
- role: "system"
41
- };
46
+ role: Role.System
47
+ });
42
48
  const messages = [systemMessage];
43
- const response = yield fetchAndDecodeChatCompletion({
44
- copilotConfig: context.copilotApiConfig,
45
- messages,
46
- tools: context.getChatCompletionFunctionDescriptions(entryPoints),
47
- headers: context.copilotApiConfig.headers,
48
- body: context.copilotApiConfig.body
49
+ const runtimeClient = new CopilotRuntimeClient({
50
+ url: context.copilotApiConfig.chatApiEndpoint,
51
+ publicApiKey: context.copilotApiConfig.publicApiKey,
52
+ headers: context.copilotApiConfig.headers
49
53
  });
50
- if (!response.events) {
51
- throw new Error("Failed to execute task");
52
- }
53
- const reader = response.events.getReader();
54
- let functionCalls = [];
55
- while (true) {
56
- const { done, value } = yield reader.read();
57
- if (done) {
58
- break;
59
- }
60
- if (value.type === "function") {
61
- functionCalls.push({
62
- name: value.name,
63
- arguments: JSON.stringify(value.arguments)
64
- });
65
- break;
66
- }
67
- }
68
- if (!functionCalls.length) {
69
- throw new Error("No function call occurred");
70
- }
71
- const functionCallHandler = context.getFunctionCallHandler(entryPoints);
54
+ const response = yield runtimeClient.generateCopilotResponse({
55
+ frontend: {
56
+ actions: Object.values(actions).map((action) => ({
57
+ name: action.name,
58
+ description: action.description || "",
59
+ jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || []))
60
+ }))
61
+ },
62
+ messages: convertMessagesToGqlInput(messages)
63
+ }).toPromise();
64
+ const functionCallHandler = context.getFunctionCallHandler(actions);
65
+ const functionCalls = convertGqlOutputToMessages(
66
+ ((_b = (_a = response.data) == null ? void 0 : _a.generateCopilotResponse) == null ? void 0 : _b.messages) || []
67
+ ).filter((m) => m instanceof ActionExecutionMessage);
72
68
  for (const functionCall of functionCalls) {
73
- yield functionCallHandler(messages, functionCall);
69
+ yield functionCallHandler({
70
+ messages,
71
+ name: functionCall.name,
72
+ args: functionCall.arguments
73
+ });
74
74
  }
75
75
  });
76
76
  }
@@ -104,4 +104,4 @@ ${instructions}
104
104
  export {
105
105
  CopilotTask
106
106
  };
107
- //# sourceMappingURL=chunk-NKIUZSGZ.mjs.map
107
+ //# sourceMappingURL=chunk-5Q7DU3XW.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/copilot-task.ts"],"sourcesContent":["/**\n * Execute one-off tasks using Copilot intelligence.\n *\n * <img referrerPolicy=\"no-referrer-when-downgrade\" src=\"https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be\" />\n *\n * This class is used to execute one-off tasks, for example on button press. It\n * can use the context available via [useCopilotReadable](../useCopilotReadable)\n * and the actions provided by [useCopilotAction](../useCopilotAction), or\n * you can provide your own context and actions.\n *\n * <RequestExample>\n * ```jsx CopilotTask Example\n * import {\n * CopilotTask,\n * useCopilotContext\n * } from \"@copilotkit/react-core\";\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n *\n * implementation: async (message) => {\n * // ...\n * },\n * }\n * ]\n * });\n * const context = useCopilotContext();\n * await task.run(context);\n * ```\n * </RequestExample>\n *\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```jsx\n * import {\n * CopilotTask,\n * useCopilotContext\n * } from \"@copilotkit/react-core\";\n *\n * const randomSlideTask = new CopilotTask({\n * instructions: \"Make a random slide\",\n * });\n *\n * const context = useCopilotContext();\n *\n * return (\n * <button onClick={() => randomSlideTask.run(context)}>\n * Make a random slide\n * </button>\n * );\n * ```\n *\n * Have a look at the [Presentation example](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx)\n * for a more complete example.\n *\n * It's also possible to provide your own context and actions. In addition, you can specify to ignore\n * `useCopilotReadable` and `useCopilotAction`.\n *\n * ```jsx\n * import {\n * CopilotTask,\n * useCopilotContext\n * } from \"@copilotkit/react-core\";\n *\n * const standaloneTask = new CopilotTask({\n * instructions: \"Do something standalone\",\n * data: [...],\n * actions: [...],\n * includeCopilotReadable: false, // Don't use current context\n * includeCopilotActions: false, // Don't use current actions\n * });\n *\n * const context = useCopilotContext();\n *\n * standaloneTask.run(context);\n * ```\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\nimport { actionParametersToJsonSchema } from \"@copilotkit/shared\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n * @deprecated Use the `includeCopilotActions` property instead.\n */\n includeCopilotActionable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions =\n config.includeCopilotActions !== false && config.includeCopilotActionable !== false;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n frontend: {\n actions: Object.values(actions).map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n },\n messages: convertMessagesToGqlInput(messages),\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m instanceof ActionExecutionMessage);\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(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 functions you can 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 a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n"],"mappings":";;;;;;;;AA2FA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKP,SAAS,oCAAoC;AA4BtC,IAAM,cAAN,MAA2B;AAAA,EAMhC,YAAY,QAA2B;AACrC,SAAK,eAAe,OAAO;AAC3B,SAAK,UAAU,OAAO,WAAW,CAAC;AAClC,SAAK,yBAAyB,OAAO,2BAA2B;AAChE,SAAK,wBACH,OAAO,0BAA0B,SAAS,OAAO,6BAA6B;AAAA,EAClF;AAAA;AAAA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Aa,sBAAsB;AAEhF,iBAAW,gBAAgB,eAAe;AACxC,cAAM,oBAAoB;AAAA,UACxB;AAAA,UACA,MAAM,aAAa;AAAA,UACnB,MAAM,aAAa;AAAA,QACrB,CAAC;AAAA,MACH;AAAA,IACF;AAAA;AACF;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;AAGF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CopilotContext
3
- } from "./chunk-DY63PD22.mjs";
3
+ } from "./chunk-GLPZSBNA.mjs";
4
4
 
5
5
  // src/hooks/use-make-copilot-readable.ts
6
6
  import { useContext, useEffect, useRef } from "react";
@@ -20,4 +20,4 @@ function useMakeCopilotReadable(information, parentId, categories) {
20
20
  export {
21
21
  useMakeCopilotReadable
22
22
  };
23
- //# sourceMappingURL=chunk-B244LK6F.mjs.map
23
+ //# sourceMappingURL=chunk-ATWK243A.mjs.map
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-YWITCRBI.mjs";
7
7
  import {
8
8
  CopilotContext
9
- } from "./chunk-DY63PD22.mjs";
9
+ } from "./chunk-GLPZSBNA.mjs";
10
10
  import {
11
11
  __async,
12
12
  __objRest,
@@ -18,8 +18,7 @@ import {
18
18
  // src/components/copilot-provider/copilotkit.tsx
19
19
  import { useCallback, useRef, useState } from "react";
20
20
  import {
21
- COPILOT_CLOUD_CHAT_URL,
22
- actionToChatCompletionFunction
21
+ COPILOT_CLOUD_CHAT_URL
23
22
  } from "@copilotkit/shared";
24
23
  import { jsx } from "react/jsx-runtime";
25
24
  function CopilotKit(_a) {
@@ -29,7 +28,7 @@ function CopilotKit(_a) {
29
28
  throw new Error("Please provide either a url or a publicApiKey to the CopilotKit component.");
30
29
  }
31
30
  const chatApiEndpoint = props.runtimeUrl || props.url || COPILOT_CLOUD_CHAT_URL;
32
- const [entryPoints, setEntryPoints] = useState({});
31
+ const [actions, setActions] = useState({});
33
32
  const chatComponentsCache = useRef({});
34
33
  const { addElement, removeElement, printTree } = use_tree_default();
35
34
  const [messages, setMessages] = useState([]);
@@ -40,15 +39,15 @@ function CopilotKit(_a) {
40
39
  removeElement: removeDocument,
41
40
  allElements: allDocuments
42
41
  } = use_flat_category_store_default();
43
- const setEntryPoint = useCallback((id, entryPoint) => {
44
- setEntryPoints((prevPoints) => {
42
+ const setAction = useCallback((id, action) => {
43
+ setActions((prevPoints) => {
45
44
  return __spreadProps(__spreadValues({}, prevPoints), {
46
- [id]: entryPoint
45
+ [id]: action
47
46
  });
48
47
  });
49
48
  }, []);
50
- const removeEntryPoint = useCallback((id) => {
51
- setEntryPoints((prevPoints) => {
49
+ const removeAction = useCallback((id) => {
50
+ setActions((prevPoints) => {
52
51
  const newPoints = __spreadValues({}, prevPoints);
53
52
  delete newPoints[id];
54
53
  return newPoints;
@@ -79,17 +78,11 @@ ${nonDocumentStrings}`;
79
78
  },
80
79
  [removeElement]
81
80
  );
82
- const getChatCompletionFunctionDescriptions = useCallback(
83
- (customEntryPoints) => {
84
- return entryPointsToChatCompletionFunctions(Object.values(customEntryPoints || entryPoints));
85
- },
86
- [entryPoints]
87
- );
88
81
  const getFunctionCallHandler = useCallback(
89
82
  (customEntryPoints) => {
90
- return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || entryPoints));
83
+ return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
91
84
  },
92
- [entryPoints]
85
+ [actions]
93
86
  );
94
87
  const getDocumentsContext = useCallback(
95
88
  (categories) => {
@@ -155,12 +148,11 @@ ${nonDocumentStrings}`;
155
148
  CopilotContext.Provider,
156
149
  {
157
150
  value: {
158
- entryPoints,
151
+ actions,
159
152
  chatComponentsCache,
160
- getChatCompletionFunctionDescriptions,
161
153
  getFunctionCallHandler,
162
- setEntryPoint,
163
- removeEntryPoint,
154
+ setAction,
155
+ removeAction,
164
156
  getContextString,
165
157
  addContext,
166
158
  removeContext,
@@ -183,22 +175,15 @@ ${nonDocumentStrings}`;
183
175
  );
184
176
  }
185
177
  var defaultCopilotContextCategories = ["global"];
186
- function entryPointsToChatCompletionFunctions(actions) {
187
- return actions.map(actionToChatCompletionFunction);
188
- }
189
178
  function entryPointsToFunctionCallHandler(actions) {
190
- return (chatMessages, functionCall) => __async(this, null, function* () {
179
+ return (_0) => __async(this, [_0], function* ({ messages, name, args }) {
191
180
  let actionsByFunctionName = {};
192
181
  for (let action2 of actions) {
193
182
  actionsByFunctionName[action2.name] = action2;
194
183
  }
195
- const action = actionsByFunctionName[functionCall.name || ""];
184
+ const action = actionsByFunctionName[name];
196
185
  if (action) {
197
- let functionCallArguments = [];
198
- if (functionCall.arguments) {
199
- functionCallArguments = JSON.parse(functionCall.arguments);
200
- }
201
- return yield action.handler(functionCallArguments);
186
+ return yield action.handler(args);
202
187
  }
203
188
  });
204
189
  }
@@ -207,4 +192,4 @@ export {
207
192
  CopilotKit,
208
193
  defaultCopilotContextCategories
209
194
  };
210
- //# sourceMappingURL=chunk-AJSY6LS5.mjs.map
195
+ //# sourceMappingURL=chunk-FY3TQ7Q6.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * Provides the Copilot context to its children.\n * \n * <img\n * referrerPolicy=\"no-referrer-when-downgrade\"\n * src=\"https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be\"\n * />\n * \n * This component provides the Copilot context to its children.\n * It can be configured either with a chat API endpoint or a `CopilotApiConfig`.\n * \n * <Note>\n * The backend can use OpenAI, or you can bring your own LLM. For examples of the\n * backend api implementation, see `examples/next-openai` or the [runtime\n * docs](https://docs.copilotkit.ai/getting-started/quickstart-runtime).\n * </Note>\n * \n * <RequestExample>\n * ```jsx CopilotKit Example\n * import { CopilotKit } from \"@copilotkit/react-core\";\n * \n * <CopilotKit \n * runtimeUrl=\"https://your.copilotkit.api\">\n * <YourApp/>\n * </CopilotKit>\n * ```\n * </RequestExample>\n * \n * ## Example usage\n * \n * ```jsx\n * <CopilotKit publicApiKey=\"the api key or self host (see below)\">\n * <App />\n * </CopilotKit>\n```\n */\nimport { Ref, useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\n\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n} from \"@copilotkit/shared\";\nimport { 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\";\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.url && !props.publicApiKey) {\n throw new Error(\"Please provide either a url or a publicApiKey to the CopilotKit component.\");\n }\n\n const chatApiEndpoint = props.runtimeUrl || props.url || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});\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 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 chatApiEndpointV2: `${props.url}/v2`,\n headers: props.headers || {},\n body: {\n ...props.body,\n ...props.backendOnlyProps,\n },\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 return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\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 }}\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 if (action) {\n return await action.handler(args);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoCA,SAAc,aAAa,QAAQ,gBAAgB;AASnD;AAAA,EACE;AAAA,OAGK;AAsKH;AA/JG,SAAS,WAAW,IAAyC;AAAzC,eAAE,WAxD7B,IAwD2B,IAAe,kBAAf,IAAe,CAAb;AAxD7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AAIA;AAAA,IACvC;AAEA,UAAM,SAAS,sBAAsB,IAAI;AACzC,QAAI,QAAQ;AACV,aAAO,MAAM,OAAO,QAAQ,IAAI;AAAA,IAClC;AAAA,EACF;AACF;","names":["_a","_b","action"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CopilotContext
3
- } from "./chunk-DY63PD22.mjs";
3
+ } from "./chunk-GLPZSBNA.mjs";
4
4
 
5
5
  // src/hooks/use-make-copilot-actionable.ts
6
6
  import { useRef, useContext, useEffect, useMemo } from "react";
@@ -8,7 +8,7 @@ import { nanoid } from "nanoid";
8
8
  import { annotatedFunctionToAction } from "@copilotkit/shared";
9
9
  function useMakeCopilotActionable(annotatedFunction, dependencies) {
10
10
  const idRef = useRef(nanoid());
11
- const { setEntryPoint, removeEntryPoint } = useContext(CopilotContext);
11
+ const { setAction, removeAction } = useContext(CopilotContext);
12
12
  const memoizedAnnotatedFunction = useMemo(
13
13
  () => ({
14
14
  name: annotatedFunction.name,
@@ -20,14 +20,14 @@ function useMakeCopilotActionable(annotatedFunction, dependencies) {
20
20
  );
21
21
  useEffect(() => {
22
22
  const action = annotatedFunctionToAction(memoizedAnnotatedFunction);
23
- setEntryPoint(idRef.current, action);
23
+ setAction(idRef.current, action);
24
24
  return () => {
25
- removeEntryPoint(idRef.current);
25
+ removeAction(idRef.current);
26
26
  };
27
- }, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);
27
+ }, [memoizedAnnotatedFunction, setAction, removeAction]);
28
28
  }
29
29
 
30
30
  export {
31
31
  useMakeCopilotActionable
32
32
  };
33
- //# sourceMappingURL=chunk-SR4RW4CU.mjs.map
33
+ //# sourceMappingURL=chunk-GFQBAEJL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-make-copilot-actionable.ts"],"sourcesContent":["import { useRef, useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { AnnotatedFunction } from \"@copilotkit/shared\";\nimport { nanoid } from \"nanoid\";\nimport { annotatedFunctionToAction } from \"@copilotkit/shared\";\n\n/**\n * @deprecated Use the useCopilotAction function instead.\n */\nexport function useMakeCopilotActionable<ActionInput extends any[]>(\n annotatedFunction: AnnotatedFunction<ActionInput>,\n dependencies: any[],\n) {\n const idRef = useRef(nanoid()); // generate a unique id\n const { setAction, removeAction } = useContext(CopilotContext);\n\n const memoizedAnnotatedFunction: AnnotatedFunction<ActionInput> = useMemo(\n () => ({\n name: annotatedFunction.name,\n description: annotatedFunction.description,\n argumentAnnotations: annotatedFunction.argumentAnnotations,\n implementation: annotatedFunction.implementation,\n }),\n dependencies,\n );\n\n useEffect(() => {\n const action = annotatedFunctionToAction(memoizedAnnotatedFunction as AnnotatedFunction<any[]>);\n setAction(idRef.current, action);\n\n return () => {\n removeAction(idRef.current);\n };\n }, [memoizedAnnotatedFunction, setAction, removeAction]);\n}\n"],"mappings":";;;;;AAAA,SAAS,QAAQ,YAAY,WAAW,eAAe;AAGvD,SAAS,cAAc;AACvB,SAAS,iCAAiC;AAKnC,SAAS,yBACd,mBACA,cACA;AACA,QAAM,QAAQ,OAAO,OAAO,CAAC;AAC7B,QAAM,EAAE,WAAW,aAAa,IAAI,WAAW,cAAc;AAE7D,QAAM,4BAA4D;AAAA,IAChE,OAAO;AAAA,MACL,MAAM,kBAAkB;AAAA,MACxB,aAAa,kBAAkB;AAAA,MAC/B,qBAAqB,kBAAkB;AAAA,MACvC,gBAAgB,kBAAkB;AAAA,IACpC;AAAA,IACA;AAAA,EACF;AAEA,YAAU,MAAM;AACd,UAAM,SAAS,0BAA0B,yBAAqD;AAC9F,cAAU,MAAM,SAAS,MAAM;AAE/B,WAAO,MAAM;AACX,mBAAa,MAAM,OAAO;AAAA,IAC5B;AAAA,EACF,GAAG,CAAC,2BAA2B,WAAW,YAAY,CAAC;AACzD;","names":[]}
@@ -5,17 +5,16 @@ import {
5
5
  // src/context/copilot-context.tsx
6
6
  import React from "react";
7
7
  var emptyCopilotContext = {
8
- entryPoints: {},
9
- setEntryPoint: () => {
8
+ actions: {},
9
+ setAction: () => {
10
10
  },
11
- removeEntryPoint: () => {
11
+ removeAction: () => {
12
12
  },
13
13
  chatComponentsCache: { current: {} },
14
14
  getContextString: (documents, categories) => returnAndThrowInDebug(""),
15
15
  addContext: () => "",
16
16
  removeContext: () => {
17
17
  },
18
- getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),
19
18
  getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
20
19
  })),
21
20
  messages: [],
@@ -61,4 +60,4 @@ export {
61
60
  CopilotContext,
62
61
  useCopilotContext
63
62
  };
64
- //# sourceMappingURL=chunk-DY63PD22.mjs.map
63
+ //# sourceMappingURL=chunk-GLPZSBNA.mjs.map
@@ -0,0 +1 @@
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\";\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 * The endpoint for the chat API v2.\n */\n chatApiEndpointV2: 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 * Additional body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'message': 'Hello, world!'\n * }\n * ```\n */\n body: Record<string, any>;\n\n /**\n * Backend only props that will be combined to body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n backendOnlyProps?: 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;\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 chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\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\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n chatComponentsCache: { current: {} },\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 get chatApiEndpointV2(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\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};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\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;AA8HlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,EAAE,SAAS,CAAC,EAAE;AAAA,EACnC,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,UAAU,CAAC;AAAA,EACX,aAAa,MAAM,sBAAsB,CAAC,CAAC;AAAA,EAE3C,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC;AAAA,EACvE,oBAAoB,MAAM,sBAAsB,EAAE;AAAA,EAClD,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAE9B,kBAAkB,IAAK,MAAkC;AAAA,IACvD,IAAI,kBAA0B;AAC5B,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAAA,IACA,IAAI,oBAA4B;AAC9B,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAAA,IACA,IAAI,UAAkC;AACpC,aAAO,CAAC;AAAA,IACV;AAAA,IACA,IAAI,OAA4B;AAC9B,aAAO,CAAC;AAAA,IACV;AAAA,EACF,EAAG;AAAA,EAEH,6BAA6B,CAAC;AAAA,EAC9B,gCAAgC,MAAM;AAAA,EAAC;AAAA,EACvC,mCAAmC,MAAM;AAAA,EAAC;AAC5C;AAEO,IAAM,iBAAiB,MAAM,cAAoC,mBAAmB;AAEpF,SAAS,oBAA0C;AACxD,SAAO,MAAM,WAAW,cAAc;AACxC;AAEA,SAAS,sBAAyB,OAAa;AAC7C,QAAM,IAAI,MAAM,uEAAuE;AACvF,SAAO;AACT;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CopilotContext
3
- } from "./chunk-DY63PD22.mjs";
3
+ } from "./chunk-GLPZSBNA.mjs";
4
4
 
5
5
  // src/hooks/use-make-copilot-document-readable.ts
6
6
  import { useContext, useEffect, useRef } from "react";
@@ -20,4 +20,4 @@ function useMakeCopilotDocumentReadable(document, categories, dependencies = [])
20
20
  export {
21
21
  useMakeCopilotDocumentReadable
22
22
  };
23
- //# sourceMappingURL=chunk-S5LWO5V3.mjs.map
23
+ //# sourceMappingURL=chunk-IBOL6LE5.mjs.map
@@ -1,16 +1,16 @@
1
1
  import {
2
2
  CopilotContext
3
- } from "./chunk-DY63PD22.mjs";
3
+ } from "./chunk-GLPZSBNA.mjs";
4
4
 
5
5
  // src/hooks/use-copilot-action.ts
6
6
  import { useRef, useContext, useEffect } from "react";
7
7
  import { nanoid } from "nanoid";
8
8
  function useCopilotAction(action, dependencies) {
9
- const { setEntryPoint, removeEntryPoint, entryPoints, chatComponentsCache } = useContext(CopilotContext);
9
+ const { setAction, removeAction, actions, chatComponentsCache } = useContext(CopilotContext);
10
10
  const idRef = useRef(nanoid());
11
11
  if (dependencies === void 0) {
12
- if (entryPoints[idRef.current]) {
13
- entryPoints[idRef.current].handler = action.handler;
12
+ if (actions[idRef.current]) {
13
+ actions[idRef.current].handler = action.handler;
14
14
  if (typeof action.render === "function") {
15
15
  if (chatComponentsCache.current !== null) {
16
16
  chatComponentsCache.current[action.name] = action.render;
@@ -19,16 +19,16 @@ function useCopilotAction(action, dependencies) {
19
19
  }
20
20
  }
21
21
  useEffect(() => {
22
- setEntryPoint(idRef.current, action);
22
+ setAction(idRef.current, action);
23
23
  if (chatComponentsCache.current !== null && action.render !== void 0) {
24
24
  chatComponentsCache.current[action.name] = action.render;
25
25
  }
26
26
  return () => {
27
- removeEntryPoint(idRef.current);
27
+ removeAction(idRef.current);
28
28
  };
29
29
  }, [
30
- setEntryPoint,
31
- removeEntryPoint,
30
+ setAction,
31
+ removeAction,
32
32
  action.description,
33
33
  action.name,
34
34
  // This should be faster than deep equality checking
@@ -44,4 +44,4 @@ function useCopilotAction(action, dependencies) {
44
44
  export {
45
45
  useCopilotAction
46
46
  };
47
- //# sourceMappingURL=chunk-NSUYO6TP.mjs.map
47
+ //# sourceMappingURL=chunk-MI7BERU7.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-action.ts"],"sourcesContent":["import { useRef, useContext, useEffect } from \"react\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { nanoid } from \"nanoid\";\nimport { Parameter } from \"@copilotkit/shared\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useContext(CopilotContext);\n const idRef = useRef<string>(nanoid());\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n actions[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current[action.name] = action.render;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n action.description,\n action.name,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(action.parameters),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\n// Usage Example:\n// useCopilotAction({\n// name: \"myAction\",\n// parameters: [\n// { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n// { name: \"arg2\", type: \"number\" },\n// {\n// name: \"arg3\",\n// type: \"object\",\n// attributes: [\n// { name: \"nestedArg1\", type: \"boolean\" },\n// { name: \"xyz\", required: false },\n// ],\n// },\n// { name: \"arg4\", type: \"number[]\" },\n// ],\n// handler: ({ arg1, arg2, arg3, arg4 }) => {\n// const x = arg3.nestedArg1;\n// const z = arg3.xyz;\n// console.log(arg1, arg2, arg3);\n// },\n// });\n\n// useCopilotAction({\n// name: \"myAction\",\n// handler: () => {\n// console.log(\"No parameters provided.\");\n// },\n// });\n"],"mappings":";;;;;AAAA,SAAS,QAAQ,YAAY,iBAAiB;AAG9C,SAAS,cAAc;AAYhB,SAAS,iBACd,QACA,cACM;AACN,QAAM,EAAE,WAAW,cAAc,SAAS,oBAAoB,IAAI,WAAW,cAAc;AAC3F,QAAM,QAAQ,OAAe,OAAO,CAAC;AAKrC,MAAI,iBAAiB,QAAW;AAC9B,QAAI,QAAQ,MAAM,OAAO,GAAG;AAC1B,cAAQ,MAAM,OAAO,EAAE,UAAU,OAAO;AACxC,UAAI,OAAO,OAAO,WAAW,YAAY;AACvC,YAAI,oBAAoB,YAAY,MAAM;AACxC,8BAAoB,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,QACpD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,YAAU,MAAM;AACd,cAAU,MAAM,SAAS,MAAa;AACtC,QAAI,oBAAoB,YAAY,QAAQ,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,IACpD;AACA,WAAO,MAAM;AAGX,mBAAa,MAAM,OAAO;AAAA,IAC5B;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,OAAO;AAAA;AAAA;AAAA,IAGP,KAAK,UAAU,OAAO,UAAU;AAAA;AAAA,IAEhC,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":[]}
@@ -0,0 +1,188 @@
1
+ import {
2
+ __async,
3
+ __spreadValues
4
+ } from "./chunk-SKC7AJIV.mjs";
5
+
6
+ // src/hooks/use-chat.ts
7
+ import { useRef } from "react";
8
+ import {
9
+ COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
10
+ actionParametersToJsonSchema
11
+ } from "@copilotkit/shared";
12
+ import {
13
+ TextMessage,
14
+ ActionExecutionMessage,
15
+ ResultMessage,
16
+ CopilotRuntimeClient,
17
+ convertMessagesToGqlInput,
18
+ convertGqlOutputToMessages,
19
+ MessageStatusCode,
20
+ MessageRole,
21
+ Role
22
+ } from "@copilotkit/runtime-client-gql";
23
+ function useChat(options) {
24
+ const {
25
+ messages,
26
+ setMessages,
27
+ makeSystemMessageCallback,
28
+ copilotConfig,
29
+ setIsLoading,
30
+ initialMessages,
31
+ isLoading,
32
+ actions,
33
+ onFunctionCall
34
+ } = options;
35
+ const abortControllerRef = useRef();
36
+ const threadIdRef = useRef(null);
37
+ const runIdRef = useRef(null);
38
+ const publicApiKey = copilotConfig.publicApiKey;
39
+ const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
40
+ const runtimeClient = new CopilotRuntimeClient({
41
+ url: copilotConfig.chatApiEndpoint,
42
+ publicApiKey: copilotConfig.publicApiKey,
43
+ headers
44
+ });
45
+ const runChatCompletion = (previousMessages) => __async(this, null, function* () {
46
+ var _a, _b, _c, _d, _e;
47
+ setIsLoading(true);
48
+ let newMessages = [
49
+ new TextMessage({
50
+ content: "",
51
+ role: Role.Assistant
52
+ })
53
+ ];
54
+ const abortController = new AbortController();
55
+ abortControllerRef.current = abortController;
56
+ setMessages([...previousMessages, ...newMessages]);
57
+ const systemMessage = makeSystemMessageCallback();
58
+ const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
59
+ const stream = CopilotRuntimeClient.asStream(
60
+ runtimeClient.generateCopilotResponse(__spreadValues({
61
+ frontend: {
62
+ actions: actions.map((action) => ({
63
+ name: action.name,
64
+ description: action.description || "",
65
+ jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || []))
66
+ }))
67
+ },
68
+ threadId: threadIdRef.current,
69
+ runId: runIdRef.current,
70
+ messages: convertMessagesToGqlInput(messagesWithContext)
71
+ }, copilotConfig.cloud ? {
72
+ cloud: {
73
+ guardrails: {
74
+ inputValidationRules: {
75
+ allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
76
+ denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
77
+ }
78
+ }
79
+ }
80
+ } : {}))
81
+ );
82
+ const guardrailsEnabled = ((_c = (_b = (_a = copilotConfig.cloud) == null ? void 0 : _a.guardrails) == null ? void 0 : _b.input) == null ? void 0 : _c.restrictToTopic.enabled) || false;
83
+ const reader = stream.getReader();
84
+ let results = {};
85
+ try {
86
+ while (true) {
87
+ const { done, value } = yield reader.read();
88
+ if (done) {
89
+ break;
90
+ }
91
+ if (!value.generateCopilotResponse) {
92
+ continue;
93
+ }
94
+ threadIdRef.current = value.generateCopilotResponse.threadId || null;
95
+ runIdRef.current = value.generateCopilotResponse.runId || null;
96
+ const messages2 = convertGqlOutputToMessages(value.generateCopilotResponse.messages);
97
+ if (messages2.length === 0) {
98
+ continue;
99
+ }
100
+ newMessages = [];
101
+ if (((_d = value.generateCopilotResponse.status) == null ? void 0 : _d.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
102
+ newMessages = [
103
+ new TextMessage({
104
+ role: MessageRole.Assistant,
105
+ content: ((_e = value.generateCopilotResponse.status.details) == null ? void 0 : _e.guardrailsReason) || ""
106
+ })
107
+ ];
108
+ } else {
109
+ for (const message of messages2) {
110
+ newMessages.push(message);
111
+ if (message instanceof ActionExecutionMessage && message.status.code !== MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
112
+ if (!(message.id in results)) {
113
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
114
+ break;
115
+ }
116
+ const result = yield onFunctionCall({
117
+ messages: previousMessages,
118
+ name: message.name,
119
+ args: message.arguments
120
+ });
121
+ results[message.id] = result;
122
+ }
123
+ newMessages.push(
124
+ new ResultMessage({
125
+ result: ResultMessage.encodeResult(results[message.id]),
126
+ actionExecutionId: message.id,
127
+ actionName: message.name
128
+ })
129
+ );
130
+ }
131
+ }
132
+ }
133
+ if (newMessages.length > 0) {
134
+ setMessages([...previousMessages, ...newMessages]);
135
+ }
136
+ }
137
+ if (
138
+ // if we have client side results
139
+ Object.values(results).length || // or the last message we received is a result
140
+ newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage
141
+ ) {
142
+ yield new Promise((resolve) => setTimeout(resolve, 10));
143
+ return yield runChatCompletion([...previousMessages, ...newMessages]);
144
+ } else {
145
+ return newMessages.slice();
146
+ }
147
+ } finally {
148
+ setIsLoading(false);
149
+ }
150
+ });
151
+ const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
152
+ yield runChatCompletion(messages2);
153
+ });
154
+ const append = (message) => __async(this, null, function* () {
155
+ if (isLoading) {
156
+ return;
157
+ }
158
+ const newMessages = [...messages, message];
159
+ setMessages(newMessages);
160
+ return runChatCompletionAndHandleFunctionCall(newMessages);
161
+ });
162
+ const reload = () => __async(this, null, function* () {
163
+ if (isLoading || messages.length === 0) {
164
+ return;
165
+ }
166
+ let newMessages = [...messages];
167
+ const lastMessage = messages[messages.length - 1];
168
+ if (lastMessage instanceof TextMessage && lastMessage.role === "assistant") {
169
+ newMessages = newMessages.slice(0, -1);
170
+ }
171
+ setMessages(newMessages);
172
+ return runChatCompletionAndHandleFunctionCall(newMessages);
173
+ });
174
+ const stop = () => {
175
+ var _a;
176
+ (_a = abortControllerRef.current) == null ? void 0 : _a.abort();
177
+ };
178
+ return {
179
+ append,
180
+ reload,
181
+ stop
182
+ };
183
+ }
184
+
185
+ export {
186
+ useChat
187
+ };
188
+ //# sourceMappingURL=chunk-MW2IVCDP.mjs.map