@copilotkit/react-core 0.0.0-mme-load-agent-state-20250117154700

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 (293) hide show
  1. package/CHANGELOG.md +2017 -0
  2. package/README.md +48 -0
  3. package/dist/chunk-4IYWTPBR.mjs +61 -0
  4. package/dist/chunk-4IYWTPBR.mjs.map +1 -0
  5. package/dist/chunk-5FHSUKQL.mjs +70 -0
  6. package/dist/chunk-5FHSUKQL.mjs.map +1 -0
  7. package/dist/chunk-6BQVZFNO.mjs +35 -0
  8. package/dist/chunk-6BQVZFNO.mjs.map +1 -0
  9. package/dist/chunk-6U3UH3KO.mjs +140 -0
  10. package/dist/chunk-6U3UH3KO.mjs.map +1 -0
  11. package/dist/chunk-BHRJWCZT.mjs +423 -0
  12. package/dist/chunk-BHRJWCZT.mjs.map +1 -0
  13. package/dist/chunk-DCTJZ742.mjs +22 -0
  14. package/dist/chunk-DCTJZ742.mjs.map +1 -0
  15. package/dist/chunk-EFZPSZWO.mjs +1 -0
  16. package/dist/chunk-EFZPSZWO.mjs.map +1 -0
  17. package/dist/chunk-IFBUUIU7.mjs +53 -0
  18. package/dist/chunk-IFBUUIU7.mjs.map +1 -0
  19. package/dist/chunk-IJJTXITZ.mjs +59 -0
  20. package/dist/chunk-IJJTXITZ.mjs.map +1 -0
  21. package/dist/chunk-IPTELVUL.mjs +221 -0
  22. package/dist/chunk-IPTELVUL.mjs.map +1 -0
  23. package/dist/chunk-J6UBNKIR.mjs +23 -0
  24. package/dist/chunk-J6UBNKIR.mjs.map +1 -0
  25. package/dist/chunk-JFMOYUAX.mjs +120 -0
  26. package/dist/chunk-JFMOYUAX.mjs.map +1 -0
  27. package/dist/chunk-LNI2Z45S.mjs +242 -0
  28. package/dist/chunk-LNI2Z45S.mjs.map +1 -0
  29. package/dist/chunk-LUGEI4YQ.mjs +1 -0
  30. package/dist/chunk-LUGEI4YQ.mjs.map +1 -0
  31. package/dist/chunk-MLAS4QUR.mjs +18 -0
  32. package/dist/chunk-MLAS4QUR.mjs.map +1 -0
  33. package/dist/chunk-N37EFAUX.mjs +28 -0
  34. package/dist/chunk-N37EFAUX.mjs.map +1 -0
  35. package/dist/chunk-NR2BTA6Z.mjs +1 -0
  36. package/dist/chunk-NR2BTA6Z.mjs.map +1 -0
  37. package/dist/chunk-O7ARI5CV.mjs +31 -0
  38. package/dist/chunk-O7ARI5CV.mjs.map +1 -0
  39. package/dist/chunk-SKC7AJIV.mjs +61 -0
  40. package/dist/chunk-SKC7AJIV.mjs.map +1 -0
  41. package/dist/chunk-U6JOA64X.mjs +107 -0
  42. package/dist/chunk-U6JOA64X.mjs.map +1 -0
  43. package/dist/chunk-VNTDIJSG.mjs +37 -0
  44. package/dist/chunk-VNTDIJSG.mjs.map +1 -0
  45. package/dist/chunk-VRQFYEQF.mjs +181 -0
  46. package/dist/chunk-VRQFYEQF.mjs.map +1 -0
  47. package/dist/chunk-WZZEEFIX.mjs +500 -0
  48. package/dist/chunk-WZZEEFIX.mjs.map +1 -0
  49. package/dist/chunk-XERJQUHA.mjs +31 -0
  50. package/dist/chunk-XERJQUHA.mjs.map +1 -0
  51. package/dist/chunk-YPSGKPDA.mjs +1 -0
  52. package/dist/chunk-YPSGKPDA.mjs.map +1 -0
  53. package/dist/chunk-YVQNSJ4Z.mjs +90 -0
  54. package/dist/chunk-YVQNSJ4Z.mjs.map +1 -0
  55. package/dist/components/copilot-provider/copilot-messages.d.ts +16 -0
  56. package/dist/components/copilot-provider/copilot-messages.js +203 -0
  57. package/dist/components/copilot-provider/copilot-messages.js.map +1 -0
  58. package/dist/components/copilot-provider/copilot-messages.mjs +10 -0
  59. package/dist/components/copilot-provider/copilot-messages.mjs.map +1 -0
  60. package/dist/components/copilot-provider/copilotkit-props.d.ts +97 -0
  61. package/dist/components/copilot-provider/copilotkit-props.js +19 -0
  62. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -0
  63. package/dist/components/copilot-provider/copilotkit-props.mjs +1 -0
  64. package/dist/components/copilot-provider/copilotkit-props.mjs.map +1 -0
  65. package/dist/components/copilot-provider/copilotkit.d.ts +18 -0
  66. package/dist/components/copilot-provider/copilotkit.js +1037 -0
  67. package/dist/components/copilot-provider/copilotkit.js.map +1 -0
  68. package/dist/components/copilot-provider/copilotkit.mjs +22 -0
  69. package/dist/components/copilot-provider/copilotkit.mjs.map +1 -0
  70. package/dist/components/copilot-provider/index.d.ts +13 -0
  71. package/dist/components/copilot-provider/index.js +1037 -0
  72. package/dist/components/copilot-provider/index.js.map +1 -0
  73. package/dist/components/copilot-provider/index.mjs +20 -0
  74. package/dist/components/copilot-provider/index.mjs.map +1 -0
  75. package/dist/components/error-boundary/error-boundary.d.ts +22 -0
  76. package/dist/components/error-boundary/error-boundary.js +183 -0
  77. package/dist/components/error-boundary/error-boundary.js.map +1 -0
  78. package/dist/components/error-boundary/error-boundary.mjs +12 -0
  79. package/dist/components/error-boundary/error-boundary.mjs.map +1 -0
  80. package/dist/components/error-boundary/error-utils.d.ts +11 -0
  81. package/dist/components/error-boundary/error-utils.js +177 -0
  82. package/dist/components/error-boundary/error-utils.js.map +1 -0
  83. package/dist/components/error-boundary/error-utils.mjs +13 -0
  84. package/dist/components/error-boundary/error-utils.mjs.map +1 -0
  85. package/dist/components/index.d.ts +13 -0
  86. package/dist/components/index.js +1037 -0
  87. package/dist/components/index.js.map +1 -0
  88. package/dist/components/index.mjs +20 -0
  89. package/dist/components/index.mjs.map +1 -0
  90. package/dist/components/toast/exclamation-mark-icon.d.ts +9 -0
  91. package/dist/components/toast/exclamation-mark-icon.js +55 -0
  92. package/dist/components/toast/exclamation-mark-icon.js.map +1 -0
  93. package/dist/components/toast/exclamation-mark-icon.mjs +8 -0
  94. package/dist/components/toast/exclamation-mark-icon.mjs.map +1 -0
  95. package/dist/components/toast/toast-provider.d.ts +30 -0
  96. package/dist/components/toast/toast-provider.js +269 -0
  97. package/dist/components/toast/toast-provider.js.map +1 -0
  98. package/dist/components/toast/toast-provider.mjs +11 -0
  99. package/dist/components/toast/toast-provider.mjs.map +1 -0
  100. package/dist/context/copilot-context.d.ts +144 -0
  101. package/dist/context/copilot-context.js +141 -0
  102. package/dist/context/copilot-context.js.map +1 -0
  103. package/dist/context/copilot-context.mjs +10 -0
  104. package/dist/context/copilot-context.mjs.map +1 -0
  105. package/dist/context/copilot-messages-context.d.ts +15 -0
  106. package/dist/context/copilot-messages-context.js +57 -0
  107. package/dist/context/copilot-messages-context.js.map +1 -0
  108. package/dist/context/copilot-messages-context.mjs +10 -0
  109. package/dist/context/copilot-messages-context.mjs.map +1 -0
  110. package/dist/context/index.d.ts +11 -0
  111. package/dist/context/index.js +164 -0
  112. package/dist/context/index.js.map +1 -0
  113. package/dist/context/index.mjs +17 -0
  114. package/dist/context/index.mjs.map +1 -0
  115. package/dist/hooks/index.d.ts +21 -0
  116. package/dist/hooks/index.js +1350 -0
  117. package/dist/hooks/index.js.map +1 -0
  118. package/dist/hooks/index.mjs +56 -0
  119. package/dist/hooks/index.mjs.map +1 -0
  120. package/dist/hooks/use-chat.d.ts +138 -0
  121. package/dist/hooks/use-chat.js +628 -0
  122. package/dist/hooks/use-chat.js.map +1 -0
  123. package/dist/hooks/use-chat.mjs +12 -0
  124. package/dist/hooks/use-chat.mjs.map +1 -0
  125. package/dist/hooks/use-coagent-state-render.d.ts +60 -0
  126. package/dist/hooks/use-coagent-state-render.js +198 -0
  127. package/dist/hooks/use-coagent-state-render.js.map +1 -0
  128. package/dist/hooks/use-coagent-state-render.mjs +11 -0
  129. package/dist/hooks/use-coagent-state-render.mjs.map +1 -0
  130. package/dist/hooks/use-coagent.d.ts +199 -0
  131. package/dist/hooks/use-coagent.js +1111 -0
  132. package/dist/hooks/use-coagent.js.map +1 -0
  133. package/dist/hooks/use-coagent.mjs +29 -0
  134. package/dist/hooks/use-coagent.mjs.map +1 -0
  135. package/dist/hooks/use-copilot-action.d.ts +140 -0
  136. package/dist/hooks/use-copilot-action.js +372 -0
  137. package/dist/hooks/use-copilot-action.js.map +1 -0
  138. package/dist/hooks/use-copilot-action.mjs +11 -0
  139. package/dist/hooks/use-copilot-action.mjs.map +1 -0
  140. package/dist/hooks/use-copilot-authenticated-action.d.ts +8 -0
  141. package/dist/hooks/use-copilot-authenticated-action.js +421 -0
  142. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -0
  143. package/dist/hooks/use-copilot-authenticated-action.mjs +12 -0
  144. package/dist/hooks/use-copilot-authenticated-action.mjs.map +1 -0
  145. package/dist/hooks/use-copilot-chat.d.ts +48 -0
  146. package/dist/hooks/use-copilot-chat.js +957 -0
  147. package/dist/hooks/use-copilot-chat.js.map +1 -0
  148. package/dist/hooks/use-copilot-chat.mjs +24 -0
  149. package/dist/hooks/use-copilot-chat.mjs.map +1 -0
  150. package/dist/hooks/use-copilot-readable.d.ts +33 -0
  151. package/dist/hooks/use-copilot-readable.js +161 -0
  152. package/dist/hooks/use-copilot-readable.js.map +1 -0
  153. package/dist/hooks/use-copilot-readable.mjs +9 -0
  154. package/dist/hooks/use-copilot-readable.mjs.map +1 -0
  155. package/dist/hooks/use-copilot-runtime-client.d.ts +5 -0
  156. package/dist/hooks/use-copilot-runtime-client.js +182 -0
  157. package/dist/hooks/use-copilot-runtime-client.js.map +1 -0
  158. package/dist/hooks/use-copilot-runtime-client.mjs +10 -0
  159. package/dist/hooks/use-copilot-runtime-client.mjs.map +1 -0
  160. package/dist/hooks/use-flat-category-store.d.ts +9 -0
  161. package/dist/hooks/use-flat-category-store.js +90 -0
  162. package/dist/hooks/use-flat-category-store.js.map +1 -0
  163. package/dist/hooks/use-flat-category-store.mjs +8 -0
  164. package/dist/hooks/use-flat-category-store.mjs.map +1 -0
  165. package/dist/hooks/use-make-copilot-document-readable.d.ts +12 -0
  166. package/dist/hooks/use-make-copilot-document-readable.js +156 -0
  167. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -0
  168. package/dist/hooks/use-make-copilot-document-readable.mjs +9 -0
  169. package/dist/hooks/use-make-copilot-document-readable.mjs.map +1 -0
  170. package/dist/hooks/use-tree.d.ts +18 -0
  171. package/dist/hooks/use-tree.js +172 -0
  172. package/dist/hooks/use-tree.js.map +1 -0
  173. package/dist/hooks/use-tree.mjs +8 -0
  174. package/dist/hooks/use-tree.mjs.map +1 -0
  175. package/dist/index.d.ts +27 -0
  176. package/dist/index.js +2308 -0
  177. package/dist/index.js.map +1 -0
  178. package/dist/index.mjs +83 -0
  179. package/dist/index.mjs.map +1 -0
  180. package/dist/lib/copilot-task.d.ts +97 -0
  181. package/dist/lib/copilot-task.js +195 -0
  182. package/dist/lib/copilot-task.js.map +1 -0
  183. package/dist/lib/copilot-task.mjs +20 -0
  184. package/dist/lib/copilot-task.mjs.map +1 -0
  185. package/dist/lib/index.d.ts +11 -0
  186. package/dist/lib/index.js +197 -0
  187. package/dist/lib/index.js.map +1 -0
  188. package/dist/lib/index.mjs +21 -0
  189. package/dist/lib/index.mjs.map +1 -0
  190. package/dist/types/chat-suggestion-configuration.d.ts +22 -0
  191. package/dist/types/chat-suggestion-configuration.js +19 -0
  192. package/dist/types/chat-suggestion-configuration.js.map +1 -0
  193. package/dist/types/chat-suggestion-configuration.mjs +1 -0
  194. package/dist/types/chat-suggestion-configuration.mjs.map +1 -0
  195. package/dist/types/coagent-action.d.ts +29 -0
  196. package/dist/types/coagent-action.js +19 -0
  197. package/dist/types/coagent-action.js.map +1 -0
  198. package/dist/types/coagent-action.mjs +1 -0
  199. package/dist/types/coagent-action.mjs.map +1 -0
  200. package/dist/types/coagent-state.d.ts +11 -0
  201. package/dist/types/coagent-state.js +19 -0
  202. package/dist/types/coagent-state.js.map +1 -0
  203. package/dist/types/coagent-state.mjs +1 -0
  204. package/dist/types/coagent-state.mjs.map +1 -0
  205. package/dist/types/document-pointer.d.ts +9 -0
  206. package/dist/types/document-pointer.js +19 -0
  207. package/dist/types/document-pointer.js.map +1 -0
  208. package/dist/types/document-pointer.mjs +1 -0
  209. package/dist/types/document-pointer.mjs.map +1 -0
  210. package/dist/types/frontend-action.d.ts +126 -0
  211. package/dist/types/frontend-action.js +53 -0
  212. package/dist/types/frontend-action.js.map +1 -0
  213. package/dist/types/frontend-action.mjs +8 -0
  214. package/dist/types/frontend-action.mjs.map +1 -0
  215. package/dist/types/index.d.ts +7 -0
  216. package/dist/types/index.js +19 -0
  217. package/dist/types/index.js.map +1 -0
  218. package/dist/types/index.mjs +2 -0
  219. package/dist/types/index.mjs.map +1 -0
  220. package/dist/types/system-message.d.ts +3 -0
  221. package/dist/types/system-message.js +19 -0
  222. package/dist/types/system-message.js.map +1 -0
  223. package/dist/types/system-message.mjs +1 -0
  224. package/dist/types/system-message.mjs.map +1 -0
  225. package/dist/utils/dev-console.d.ts +3 -0
  226. package/dist/utils/dev-console.js +42 -0
  227. package/dist/utils/dev-console.js.map +1 -0
  228. package/dist/utils/dev-console.mjs +8 -0
  229. package/dist/utils/dev-console.mjs.map +1 -0
  230. package/dist/utils/extract.d.ts +43 -0
  231. package/dist/utils/extract.js +208 -0
  232. package/dist/utils/extract.js.map +1 -0
  233. package/dist/utils/extract.mjs +18 -0
  234. package/dist/utils/extract.mjs.map +1 -0
  235. package/dist/utils/index.d.ts +13 -0
  236. package/dist/utils/index.js +226 -0
  237. package/dist/utils/index.js.map +1 -0
  238. package/dist/utils/index.mjs +21 -0
  239. package/dist/utils/index.mjs.map +1 -0
  240. package/dist/utils/utils.d.ts +2 -0
  241. package/dist/utils/utils.js +19 -0
  242. package/dist/utils/utils.js.map +1 -0
  243. package/dist/utils/utils.mjs +1 -0
  244. package/dist/utils/utils.mjs.map +1 -0
  245. package/dist/utils/utils.test.d.ts +2 -0
  246. package/dist/utils/utils.test.js +9 -0
  247. package/dist/utils/utils.test.js.map +1 -0
  248. package/dist/utils/utils.test.mjs +7 -0
  249. package/dist/utils/utils.test.mjs.map +1 -0
  250. package/jest.config.js +5 -0
  251. package/package.json +69 -0
  252. package/src/components/copilot-provider/copilot-messages.tsx +45 -0
  253. package/src/components/copilot-provider/copilotkit-props.tsx +102 -0
  254. package/src/components/copilot-provider/copilotkit.tsx +427 -0
  255. package/src/components/copilot-provider/index.ts +3 -0
  256. package/src/components/error-boundary/error-boundary.tsx +42 -0
  257. package/src/components/error-boundary/error-utils.tsx +95 -0
  258. package/src/components/index.ts +1 -0
  259. package/src/components/toast/exclamation-mark-icon.tsx +27 -0
  260. package/src/components/toast/toast-provider.tsx +170 -0
  261. package/src/context/copilot-context.tsx +280 -0
  262. package/src/context/copilot-messages-context.tsx +29 -0
  263. package/src/context/index.ts +8 -0
  264. package/src/hooks/index.ts +12 -0
  265. package/src/hooks/use-chat.ts +682 -0
  266. package/src/hooks/use-coagent-state-render.ts +118 -0
  267. package/src/hooks/use-coagent.ts +394 -0
  268. package/src/hooks/use-copilot-action.ts +289 -0
  269. package/src/hooks/use-copilot-authenticated-action.ts +60 -0
  270. package/src/hooks/use-copilot-chat.ts +310 -0
  271. package/src/hooks/use-copilot-readable.ts +123 -0
  272. package/src/hooks/use-copilot-runtime-client.ts +28 -0
  273. package/src/hooks/use-flat-category-store.ts +104 -0
  274. package/src/hooks/use-make-copilot-document-readable.ts +30 -0
  275. package/src/hooks/use-tree.ts +202 -0
  276. package/src/index.tsx +7 -0
  277. package/src/lib/copilot-task.ts +201 -0
  278. package/src/lib/index.ts +1 -0
  279. package/src/types/chat-suggestion-configuration.ts +23 -0
  280. package/src/types/coagent-action.ts +31 -0
  281. package/src/types/coagent-state.ts +9 -0
  282. package/src/types/document-pointer.ts +7 -0
  283. package/src/types/frontend-action.ts +199 -0
  284. package/src/types/index.ts +8 -0
  285. package/src/types/system-message.ts +4 -0
  286. package/src/utils/dev-console.ts +18 -0
  287. package/src/utils/extract.ts +215 -0
  288. package/src/utils/index.ts +2 -0
  289. package/src/utils/utils.test.ts +7 -0
  290. package/src/utils/utils.ts +1 -0
  291. package/tsconfig.json +12 -0
  292. package/tsup.config.ts +16 -0
  293. package/typedoc.json +4 -0
@@ -0,0 +1,221 @@
1
+ import {
2
+ defaultCopilotContextCategories
3
+ } from "./chunk-WZZEEFIX.mjs";
4
+ import {
5
+ useCopilotMessagesContext
6
+ } from "./chunk-DCTJZ742.mjs";
7
+ import {
8
+ useChat
9
+ } from "./chunk-BHRJWCZT.mjs";
10
+ import {
11
+ useCopilotContext
12
+ } from "./chunk-YVQNSJ4Z.mjs";
13
+ import {
14
+ useAsyncCallback
15
+ } from "./chunk-LNI2Z45S.mjs";
16
+ import {
17
+ __async,
18
+ __objRest,
19
+ __spreadProps,
20
+ __spreadValues
21
+ } from "./chunk-SKC7AJIV.mjs";
22
+
23
+ // src/hooks/use-copilot-chat.ts
24
+ import { useRef, useEffect, useCallback } from "react";
25
+ import { Role, TextMessage } from "@copilotkit/runtime-client-gql";
26
+ function useCopilotChat(_a = {}) {
27
+ var _b = _a, {
28
+ makeSystemMessage
29
+ } = _b, options = __objRest(_b, [
30
+ "makeSystemMessage"
31
+ ]);
32
+ const {
33
+ getContextString,
34
+ getFunctionCallHandler,
35
+ copilotApiConfig,
36
+ isLoading,
37
+ setIsLoading,
38
+ chatInstructions,
39
+ actions,
40
+ coagentStatesRef,
41
+ setCoagentStatesWithRef,
42
+ coAgentStateRenders,
43
+ agentSession,
44
+ setAgentSession,
45
+ forwardedParameters,
46
+ agentLock,
47
+ threadId,
48
+ setThreadId,
49
+ runId,
50
+ setRunId,
51
+ chatAbortControllerRef,
52
+ extensions,
53
+ setExtensions
54
+ } = useCopilotContext();
55
+ const { messages, setMessages } = useCopilotMessagesContext();
56
+ const latestGetContextString = useUpdatedRef(getContextString);
57
+ const deleteMessage = useCallback(
58
+ (messageId) => {
59
+ setMessages((prev) => prev.filter((message) => message.id !== messageId));
60
+ },
61
+ [setMessages]
62
+ );
63
+ const makeSystemMessageCallback = useCallback(() => {
64
+ const systemMessageMaker = makeSystemMessage || defaultSystemMessage;
65
+ const contextString = latestGetContextString.current([], defaultCopilotContextCategories);
66
+ return new TextMessage({
67
+ content: systemMessageMaker(contextString, chatInstructions),
68
+ role: Role.System
69
+ });
70
+ }, [getContextString, makeSystemMessage, chatInstructions]);
71
+ const onCoAgentStateRender = useAsyncCallback(
72
+ (args) => __async(this, null, function* () {
73
+ var _a2;
74
+ const { name, nodeName, state } = args;
75
+ let action = Object.values(coAgentStateRenders).find(
76
+ (action2) => action2.name === name && action2.nodeName === nodeName
77
+ );
78
+ if (!action) {
79
+ action = Object.values(coAgentStateRenders).find(
80
+ (action2) => action2.name === name && !action2.nodeName
81
+ );
82
+ }
83
+ if (action) {
84
+ yield (_a2 = action.handler) == null ? void 0 : _a2.call(action, { state, nodeName });
85
+ }
86
+ }),
87
+ [coAgentStateRenders]
88
+ );
89
+ const { append, reload, stop, runChatCompletion } = useChat(__spreadProps(__spreadValues({}, options), {
90
+ actions: Object.values(actions),
91
+ copilotConfig: copilotApiConfig,
92
+ initialMessages: options.initialMessages || [],
93
+ onFunctionCall: getFunctionCallHandler(),
94
+ onCoAgentStateRender,
95
+ messages,
96
+ setMessages,
97
+ makeSystemMessageCallback,
98
+ isLoading,
99
+ setIsLoading,
100
+ coagentStatesRef,
101
+ setCoagentStatesWithRef,
102
+ agentSession,
103
+ setAgentSession,
104
+ forwardedParameters,
105
+ threadId,
106
+ setThreadId,
107
+ runId,
108
+ setRunId,
109
+ chatAbortControllerRef,
110
+ agentLock,
111
+ extensions,
112
+ setExtensions
113
+ }));
114
+ const latestAppend = useUpdatedRef(append);
115
+ const latestAppendFunc = useAsyncCallback(
116
+ (message, options2) => __async(this, null, function* () {
117
+ return yield latestAppend.current(message, options2);
118
+ }),
119
+ [latestAppend]
120
+ );
121
+ const latestReload = useUpdatedRef(reload);
122
+ const latestReloadFunc = useAsyncCallback(() => __async(this, null, function* () {
123
+ return yield latestReload.current();
124
+ }), [latestReload]);
125
+ const latestStop = useUpdatedRef(stop);
126
+ const latestStopFunc = useCallback(() => {
127
+ return latestStop.current();
128
+ }, [latestStop]);
129
+ const latestDelete = useUpdatedRef(deleteMessage);
130
+ const latestDeleteFunc = useCallback(
131
+ (messageId) => {
132
+ return latestDelete.current(messageId);
133
+ },
134
+ [latestDelete]
135
+ );
136
+ const latestSetMessages = useUpdatedRef(setMessages);
137
+ const latestSetMessagesFunc = useCallback(
138
+ (messages2) => {
139
+ return latestSetMessages.current(messages2);
140
+ },
141
+ [latestSetMessages]
142
+ );
143
+ const latestRunChatCompletion = useUpdatedRef(runChatCompletion);
144
+ const latestRunChatCompletionFunc = useAsyncCallback(() => __async(this, null, function* () {
145
+ return yield latestRunChatCompletion.current();
146
+ }), [latestRunChatCompletion]);
147
+ const reset = useCallback(() => {
148
+ latestStopFunc();
149
+ setMessages([]);
150
+ setRunId(null);
151
+ setCoagentStatesWithRef({});
152
+ let initialAgentSession = null;
153
+ if (agentLock) {
154
+ initialAgentSession = {
155
+ agentName: agentLock
156
+ };
157
+ }
158
+ setAgentSession(initialAgentSession);
159
+ }, [
160
+ latestStopFunc,
161
+ setMessages,
162
+ setThreadId,
163
+ setCoagentStatesWithRef,
164
+ setAgentSession,
165
+ agentLock
166
+ ]);
167
+ const latestReset = useUpdatedRef(reset);
168
+ const latestResetFunc = useCallback(() => {
169
+ return latestReset.current();
170
+ }, [latestReset]);
171
+ return {
172
+ visibleMessages: messages,
173
+ appendMessage: latestAppendFunc,
174
+ setMessages: latestSetMessagesFunc,
175
+ reloadMessages: latestReloadFunc,
176
+ stopGeneration: latestStopFunc,
177
+ reset: latestResetFunc,
178
+ deleteMessage: latestDeleteFunc,
179
+ runChatCompletion: latestRunChatCompletionFunc,
180
+ isLoading
181
+ };
182
+ }
183
+ function useUpdatedRef(value) {
184
+ const ref = useRef(value);
185
+ useEffect(() => {
186
+ ref.current = value;
187
+ }, [value]);
188
+ return ref;
189
+ }
190
+ function defaultSystemMessage(contextString, additionalInstructions) {
191
+ return `
192
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
193
+
194
+ Help 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.
195
+ Always be polite and respectful, and prefer brevity over verbosity.
196
+
197
+ The user has provided you with the following context:
198
+ \`\`\`
199
+ ${contextString}
200
+ \`\`\`
201
+
202
+ They have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.
203
+
204
+ Please assist them as best you can.
205
+
206
+ You can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.
207
+
208
+ If you would like to call a function, call it without saying anything else.
209
+ In case of a function error:
210
+ - If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.
211
+ - If the error's source is unclear or seems unrelated to your input, do not attempt further retries.
212
+ ` + (additionalInstructions ? `
213
+
214
+ ${additionalInstructions}` : "");
215
+ }
216
+
217
+ export {
218
+ useCopilotChat,
219
+ defaultSystemMessage
220
+ };
221
+ //# sourceMappingURL=chunk-IPTELVUL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"sourcesContent":["/**\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n *\n * // optionally, you can append a message without running chat completion\n * appendMessage(yourMessage, { followUp: false });\n * }\n * ```\n *\n * `useCopilotChat` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * visibleMessages, // An array of messages that are currently visible in the chat.\n * appendMessage, // A function to append a message to the chat.\n * setMessages, // A function to set the messages in the chat.\n * deleteMessage, // A function to delete a message from the chat.\n * reloadMessages, // A function to reload the messages from the API.\n * stopGeneration, // A function to stop the generation of the next message.\n * isLoading, // A boolean indicating if the chat is loading.\n * } = useCopilotChat();\n * ```\n */\nimport { useRef, useEffect, useCallback } from \"react\";\nimport { AgentSession, useCopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat, AppendMessageOptions } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CoAgentStateRenderHandlerArguments, randomId } from \"@copilotkit/shared\";\nimport { useCopilotMessagesContext } from \"../context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n reset: () => void;\n isLoading: boolean;\n runChatCompletion: () => Promise<Message[]>;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n coagentStatesRef,\n setCoagentStatesWithRef,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n extensions,\n setExtensions,\n } = useCopilotContext();\n const { messages, setMessages } = useCopilotMessagesContext();\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: Role.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const onCoAgentStateRender = useAsyncCallback(\n async (args: CoAgentStateRenderHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coAgentStateRenders],\n );\n\n const { append, reload, stop, runChatCompletion } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n onCoAgentStateRender,\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n });\n\n // this is a workaround born out of a bug that Athena incessantly ran into.\n // We could not find the origin of the bug, however, it was clear that an outdated version of the append function was being used somehow --\n // it referenced the old state of the messages array, and not the latest one.\n //\n // We want to make copilotkit as abuse-proof as possible, so we are adding this workaround to ensure that the latest version of the append function is always used.\n //\n // How does this work?\n // we store the relevant function in a ref that is always up-to-date, and then we use that ref in the callback.\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n return await latestAppend.current(message, options);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(async () => {\n return await latestReload.current();\n }, [latestReload]);\n\n const latestStop = useUpdatedRef(stop);\n const latestStopFunc = useCallback(() => {\n return latestStop.current();\n }, [latestStop]);\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const latestSetMessages = useUpdatedRef(setMessages);\n const latestSetMessagesFunc = useCallback(\n (messages: Message[]) => {\n return latestSetMessages.current(messages);\n },\n [latestSetMessages],\n );\n\n const latestRunChatCompletion = useUpdatedRef(runChatCompletion);\n const latestRunChatCompletionFunc = useAsyncCallback(async () => {\n return await latestRunChatCompletion.current!();\n }, [latestRunChatCompletion]);\n\n const reset = useCallback(() => {\n latestStopFunc();\n setMessages([]);\n setRunId(null);\n setCoagentStatesWithRef({});\n let initialAgentSession: AgentSession | null = null;\n if (agentLock) {\n initialAgentSession = {\n agentName: agentLock,\n };\n }\n setAgentSession(initialAgentSession);\n }, [\n latestStopFunc,\n setMessages,\n setThreadId,\n setCoagentStatesWithRef,\n setAgentSession,\n agentLock,\n ]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n return {\n visibleMessages: messages,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n runChatCompletion: latestRunChatCompletionFunc,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAS,QAAQ,WAAW,mBAAmB;AAE/C,SAAkB,MAAM,mBAAmB;AA2CpC,SAAS,eAAe,KAGJ,CAAC,GAAyB;AAHtB,eAC7B;AAAA;AAAA,EAzFF,IAwF+B,IAE1B,oBAF0B,IAE1B;AAAA,IADH;AAAA;AAGA,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,kBAAkB;AACtB,QAAM,EAAE,UAAU,YAAY,IAAI,0BAA0B;AAI5D,QAAM,yBAAyB,cAAc,gBAAgB;AAC7D,QAAM,gBAAgB;AAAA,IACpB,CAAC,cAAsB;AACrB,kBAAY,CAAC,SAAS,KAAK,OAAO,CAAC,YAAY,QAAQ,OAAO,SAAS,CAAC;AAAA,IAC1E;AAAA,IACA,CAAC,WAAW;AAAA,EACd;AAEA,QAAM,4BAA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AM,kBAAkB,YAAY,MAAM;AACxC,WAAO,YAAY,QAAQ;AAAA,EAC7B,GAAG,CAAC,WAAW,CAAC;AAEhB,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf,aAAa;AAAA,IACb,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,OAAO;AAAA,IACP,eAAe;AAAA,IACf,mBAAmB;AAAA,IACnB;AAAA,EACF;AACF;AAIA,SAAS,cAAiB,OAAU;AAClC,QAAM,MAAM,OAAO,KAAK;AAExB,YAAU,MAAM;AACd,QAAI,UAAU;AAAA,EAChB,GAAG,CAAC,KAAK,CAAC;AAEV,SAAO;AACT;AAEO,SAAS,qBACd,eACA,wBACQ;AACR,SACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAaG,yBAAyB;AAAA;AAAA,EAAO,2BAA2B;AAEhE;","names":["_a","action","options","messages"]}
@@ -0,0 +1,23 @@
1
+ import {
2
+ useCopilotContext
3
+ } from "./chunk-YVQNSJ4Z.mjs";
4
+
5
+ // src/hooks/use-make-copilot-document-readable.ts
6
+ import { useEffect, useRef } from "react";
7
+ function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
8
+ const { addDocumentContext, removeDocumentContext } = useCopilotContext();
9
+ const idRef = useRef();
10
+ useEffect(() => {
11
+ const id = addDocumentContext(document, categories);
12
+ idRef.current = id;
13
+ return () => {
14
+ removeDocumentContext(id);
15
+ };
16
+ }, [addDocumentContext, removeDocumentContext, ...dependencies]);
17
+ return idRef.current;
18
+ }
19
+
20
+ export {
21
+ useMakeCopilotDocumentReadable
22
+ };
23
+ //# sourceMappingURL=chunk-J6UBNKIR.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-make-copilot-document-readable.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useCopilotContext();\n const idRef = useRef<string>();\n\n useEffect(() => {\n const id = addDocumentContext(document, categories);\n idRef.current = id;\n\n return () => {\n removeDocumentContext(id);\n };\n }, [addDocumentContext, removeDocumentContext, ...dependencies]);\n\n return idRef.current;\n}\n"],"mappings":";;;;;AAAA,SAAS,WAAW,cAAc;AAW3B,SAAS,+BACd,UACA,YACA,eAAsB,CAAC,GACH;AACpB,QAAM,EAAE,oBAAoB,sBAAsB,IAAI,kBAAkB;AACxE,QAAM,QAAQ,OAAe;AAE7B,YAAU,MAAM;AACd,UAAM,KAAK,mBAAmB,UAAU,UAAU;AAClD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,4BAAsB,EAAE;AAAA,IAC1B;AAAA,EACF,GAAG,CAAC,oBAAoB,uBAAuB,GAAG,YAAY,CAAC;AAE/D,SAAO,MAAM;AACf;","names":[]}
@@ -0,0 +1,120 @@
1
+ import {
2
+ defaultCopilotContextCategories
3
+ } from "./chunk-WZZEEFIX.mjs";
4
+ import {
5
+ processActionsForRuntimeRequest
6
+ } from "./chunk-XERJQUHA.mjs";
7
+ import {
8
+ __async,
9
+ __spreadProps,
10
+ __spreadValues
11
+ } from "./chunk-SKC7AJIV.mjs";
12
+
13
+ // src/lib/copilot-task.ts
14
+ import {
15
+ CopilotRuntimeClient,
16
+ Role,
17
+ TextMessage,
18
+ convertGqlOutputToMessages,
19
+ convertMessagesToGqlInput,
20
+ filterAgentStateMessages,
21
+ CopilotRequestType
22
+ } from "@copilotkit/runtime-client-gql";
23
+ var CopilotTask = class {
24
+ constructor(config) {
25
+ this.instructions = config.instructions;
26
+ this.actions = config.actions || [];
27
+ this.includeCopilotReadable = config.includeCopilotReadable !== false;
28
+ this.includeCopilotActions = config.includeCopilotActions !== false;
29
+ this.forwardedParameters = config.forwardedParameters;
30
+ }
31
+ /**
32
+ * Run the task.
33
+ * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.
34
+ * @param data The data to use for the task.
35
+ */
36
+ run(context, data) {
37
+ return __async(this, null, function* () {
38
+ var _a, _b, _c;
39
+ const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
40
+ for (const fn of this.actions) {
41
+ actions[fn.name] = fn;
42
+ }
43
+ let contextString = "";
44
+ if (data) {
45
+ contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
46
+ }
47
+ if (this.includeCopilotReadable) {
48
+ contextString += context.getContextString([], defaultCopilotContextCategories);
49
+ }
50
+ const systemMessage = new TextMessage({
51
+ content: taskSystemMessage(contextString, this.instructions),
52
+ role: Role.System
53
+ });
54
+ const messages = [systemMessage];
55
+ const runtimeClient = new CopilotRuntimeClient({
56
+ url: context.copilotApiConfig.chatApiEndpoint,
57
+ publicApiKey: context.copilotApiConfig.publicApiKey,
58
+ headers: context.copilotApiConfig.headers,
59
+ credentials: context.copilotApiConfig.credentials
60
+ });
61
+ const response = yield runtimeClient.generateCopilotResponse({
62
+ data: {
63
+ frontend: {
64
+ actions: processActionsForRuntimeRequest(Object.values(actions)),
65
+ url: window.location.href
66
+ },
67
+ messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),
68
+ metadata: {
69
+ requestType: CopilotRequestType.Task
70
+ },
71
+ forwardedParameters: __spreadProps(__spreadValues({}, (_a = this.forwardedParameters) != null ? _a : {}), {
72
+ toolChoice: "required"
73
+ })
74
+ },
75
+ properties: context.copilotApiConfig.properties
76
+ }).toPromise();
77
+ const functionCallHandler = context.getFunctionCallHandler(actions);
78
+ const functionCalls = convertGqlOutputToMessages(
79
+ ((_c = (_b = response.data) == null ? void 0 : _b.generateCopilotResponse) == null ? void 0 : _c.messages) || []
80
+ ).filter((m) => m.isActionExecutionMessage());
81
+ for (const functionCall of functionCalls) {
82
+ yield functionCallHandler({
83
+ messages,
84
+ name: functionCall.name,
85
+ args: functionCall.arguments
86
+ });
87
+ }
88
+ });
89
+ }
90
+ };
91
+ function taskSystemMessage(contextString, instructions) {
92
+ return `
93
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
94
+
95
+ Help 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.
96
+ Always be polite and respectful, and prefer brevity over verbosity.
97
+
98
+ The user has provided you with the following context:
99
+ \`\`\`
100
+ ${contextString}
101
+ \`\`\`
102
+
103
+ They have also provided you with functions you can call to initiate actions on their behalf.
104
+
105
+ Please assist them as best you can.
106
+
107
+ This is not a conversation, so please do not ask questions. Just call a function without saying anything else.
108
+
109
+ The user has given you the following task to complete:
110
+
111
+ \`\`\`
112
+ ${instructions}
113
+ \`\`\`
114
+ `;
115
+ }
116
+
117
+ export {
118
+ CopilotTask
119
+ };
120
+ //# sourceMappingURL=chunk-JFMOYUAX.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/copilot-task.ts"],"sourcesContent":["/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\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 * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\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 */\n includeCopilotActions?: boolean;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\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 private forwardedParameters?: ForwardedParametersInput;\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n this.forwardedParameters = config.forwardedParameters;\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 credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n ...(this.forwardedParameters ?? {}),\n toolChoice: \"required\",\n },\n },\n properties: context.copilotApiConfig.properties,\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.isActionExecutionMessage());\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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MAAM;AAAA,UACJ,UAAU;AAAA,YACR,SAAS,gCAAgC,OAAO,OAAO,OAAO,CAAC;AAAA,YAC/D,KAAK,OAAO,SAAS;AAAA,UACvB;AAAA,UACA,UAAU,0BAA0B,yBAAyB,QAAQ,CAAC;AAAA,UACtE,UAAU;AAAA,YACR,aAAa,mBAAmB;AAAA,UAClC;AAAA,UACA,qBAAqB,kCAEf,UAAK,wBAAL,YAA4B,CAAC,IAFd;AAAA,YAGnB,YAAY;AAAA,UACd;AAAA,QACF;AAAA,QACA,YAAY,QAAQ,iBAAiB;AAAA,MACvC,CAAC,EACA,UAAU;AAEb,YAAM,sBAAsB,QAAQ,uBAAuB,OAAO;AAClE,YAAM,gBAAgB;AAAA,UACpB,oBAAS,SAAT,mBAAe,4BAAf,mBAAwC,aAAY,CAAC;AAAA,MACvD,EAAE,OAAO,CAAC,MAAmC,EAAE,yBAAyB,CAAC;AAEzE,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":[]}
@@ -0,0 +1,242 @@
1
+ import {
2
+ ExclamationMarkIcon
3
+ } from "./chunk-O7ARI5CV.mjs";
4
+ import {
5
+ __async,
6
+ __spreadProps,
7
+ __spreadValues
8
+ } from "./chunk-SKC7AJIV.mjs";
9
+
10
+ // src/components/error-boundary/error-utils.tsx
11
+ import { useCallback as useCallback2 } from "react";
12
+
13
+ // src/components/toast/toast-provider.tsx
14
+ import { createContext, useContext, useState, useCallback } from "react";
15
+ import { jsx, jsxs } from "react/jsx-runtime";
16
+ var ToastContext = createContext(void 0);
17
+ function useToast() {
18
+ const context = useContext(ToastContext);
19
+ if (!context) {
20
+ throw new Error("useToast must be used within a ToastProvider");
21
+ }
22
+ return context;
23
+ }
24
+ function ToastProvider({
25
+ enabled,
26
+ children
27
+ }) {
28
+ const [toasts, setToasts] = useState([]);
29
+ const addToast = useCallback((toast) => {
30
+ var _a;
31
+ const id = (_a = toast.id) != null ? _a : Math.random().toString(36).substring(2, 9);
32
+ setToasts((currentToasts) => {
33
+ if (currentToasts.find((toast2) => toast2.id === id))
34
+ return currentToasts;
35
+ return [...currentToasts, __spreadProps(__spreadValues({}, toast), { id })];
36
+ });
37
+ if (toast.duration) {
38
+ setTimeout(() => {
39
+ removeToast(id);
40
+ }, toast.duration);
41
+ }
42
+ }, []);
43
+ const addGraphQLErrorsToast = useCallback((errors) => {
44
+ addToast({
45
+ type: "error",
46
+ message: /* @__PURE__ */ jsx(ErrorToast, { errors })
47
+ });
48
+ }, []);
49
+ const removeToast = useCallback((id) => {
50
+ setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));
51
+ }, []);
52
+ const value = {
53
+ toasts,
54
+ addToast,
55
+ addGraphQLErrorsToast,
56
+ removeToast,
57
+ enabled
58
+ };
59
+ return /* @__PURE__ */ jsxs(ToastContext.Provider, { value, children: [
60
+ /* @__PURE__ */ jsxs(
61
+ "div",
62
+ {
63
+ style: {
64
+ position: "fixed",
65
+ bottom: "1rem",
66
+ left: "50%",
67
+ transform: "translateX(-50%)",
68
+ zIndex: 50,
69
+ display: "flex",
70
+ flexDirection: "column",
71
+ gap: "0.5rem"
72
+ },
73
+ children: [
74
+ toasts.length > 1 && /* @__PURE__ */ jsx("div", { style: { textAlign: "right" }, children: /* @__PURE__ */ jsx(
75
+ "button",
76
+ {
77
+ onClick: () => setToasts([]),
78
+ style: {
79
+ padding: "4px 8px",
80
+ fontSize: "12px",
81
+ cursor: "pointer",
82
+ background: "white",
83
+ border: "1px solid rgba(0,0,0,0.2)",
84
+ borderRadius: "4px"
85
+ },
86
+ children: "Close All"
87
+ }
88
+ ) }),
89
+ toasts.map((toast) => /* @__PURE__ */ jsx(
90
+ Toast,
91
+ {
92
+ message: toast.message,
93
+ type: toast.type,
94
+ onClose: () => removeToast(toast.id)
95
+ },
96
+ toast.id
97
+ ))
98
+ ]
99
+ }
100
+ ),
101
+ children
102
+ ] });
103
+ }
104
+ function Toast({
105
+ message,
106
+ type = "info",
107
+ onClose
108
+ }) {
109
+ const bgColors = {
110
+ info: "#3b82f6",
111
+ success: "#22c55e",
112
+ warning: "#eab308",
113
+ error: "#ef4444"
114
+ };
115
+ return /* @__PURE__ */ jsxs(
116
+ "div",
117
+ {
118
+ style: {
119
+ backgroundColor: bgColors[type],
120
+ color: "white",
121
+ padding: "0.5rem 1.5rem",
122
+ borderRadius: "0.25rem",
123
+ boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
124
+ position: "relative",
125
+ minWidth: "200px"
126
+ },
127
+ children: [
128
+ /* @__PURE__ */ jsx("div", { children: message }),
129
+ /* @__PURE__ */ jsx(
130
+ "button",
131
+ {
132
+ onClick: onClose,
133
+ style: {
134
+ position: "absolute",
135
+ top: "0",
136
+ right: "0",
137
+ background: "none",
138
+ border: "none",
139
+ color: "white",
140
+ cursor: "pointer",
141
+ padding: "0.5rem",
142
+ fontSize: "1rem"
143
+ },
144
+ children: "\u2715"
145
+ }
146
+ )
147
+ ]
148
+ }
149
+ );
150
+ }
151
+
152
+ // src/components/error-boundary/error-utils.tsx
153
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
154
+ function ErrorToast({ errors }) {
155
+ const errorsToRender = errors.map((error, idx) => {
156
+ var _a, _b, _c;
157
+ const message = "extensions" in error ? (_b = (_a = error.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message : error.message;
158
+ const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
159
+ return /* @__PURE__ */ jsxs2(
160
+ "div",
161
+ {
162
+ style: {
163
+ marginTop: idx === 0 ? 0 : 10,
164
+ marginBottom: 14
165
+ },
166
+ children: [
167
+ /* @__PURE__ */ jsx2(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
168
+ code && /* @__PURE__ */ jsxs2(
169
+ "div",
170
+ {
171
+ style: {
172
+ fontWeight: "600",
173
+ marginBottom: 4
174
+ },
175
+ children: [
176
+ "Copilot Cloud Error:",
177
+ " ",
178
+ /* @__PURE__ */ jsx2("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
179
+ ]
180
+ }
181
+ ),
182
+ /* @__PURE__ */ jsx2("div", { children: message })
183
+ ]
184
+ },
185
+ idx
186
+ );
187
+ });
188
+ return /* @__PURE__ */ jsxs2(
189
+ "div",
190
+ {
191
+ style: {
192
+ fontSize: "13px",
193
+ maxWidth: "600px"
194
+ },
195
+ children: [
196
+ errorsToRender,
197
+ /* @__PURE__ */ jsx2("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
198
+ ]
199
+ }
200
+ );
201
+ }
202
+ function useErrorToast() {
203
+ const { addToast } = useToast();
204
+ return useCallback2(
205
+ (error) => {
206
+ const errorId = error.map((err) => {
207
+ var _a, _b;
208
+ const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
209
+ const stack = err.stack || "";
210
+ return btoa(message + stack).slice(0, 32);
211
+ }).join("|");
212
+ addToast({
213
+ type: "error",
214
+ id: errorId,
215
+ // Toast libraries typically dedupe by id
216
+ message: /* @__PURE__ */ jsx2(ErrorToast, { errors: error })
217
+ });
218
+ },
219
+ [addToast]
220
+ );
221
+ }
222
+ function useAsyncCallback(callback, deps) {
223
+ const addErrorToast = useErrorToast();
224
+ return useCallback2((...args) => __async(this, null, function* () {
225
+ try {
226
+ return yield callback(...args);
227
+ } catch (error) {
228
+ console.error("Error in async callback:", error);
229
+ addErrorToast([error]);
230
+ throw error;
231
+ }
232
+ }), deps);
233
+ }
234
+
235
+ export {
236
+ ErrorToast,
237
+ useErrorToast,
238
+ useAsyncCallback,
239
+ useToast,
240
+ ToastProvider
241
+ };
242
+ //# sourceMappingURL=chunk-LNI2Z45S.mjs.map