@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
package/dist/index.js ADDED
@@ -0,0 +1,2308 @@
1
+ "use strict";
2
+ "use client";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __defProps = Object.defineProperties;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
13
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
+ var __spreadValues = (a, b) => {
15
+ for (var prop in b || (b = {}))
16
+ if (__hasOwnProp.call(b, prop))
17
+ __defNormalProp(a, prop, b[prop]);
18
+ if (__getOwnPropSymbols)
19
+ for (var prop of __getOwnPropSymbols(b)) {
20
+ if (__propIsEnum.call(b, prop))
21
+ __defNormalProp(a, prop, b[prop]);
22
+ }
23
+ return a;
24
+ };
25
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
26
+ var __restKey = (key) => typeof key === "symbol" ? key : key + "";
27
+ var __objRest = (source, exclude) => {
28
+ var target = {};
29
+ for (var prop in source)
30
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
31
+ target[prop] = source[prop];
32
+ if (source != null && __getOwnPropSymbols)
33
+ for (var prop of __getOwnPropSymbols(source)) {
34
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
35
+ target[prop] = source[prop];
36
+ }
37
+ return target;
38
+ };
39
+ var __export = (target, all) => {
40
+ for (var name in all)
41
+ __defProp(target, name, { get: all[name], enumerable: true });
42
+ };
43
+ var __copyProps = (to, from, except, desc) => {
44
+ if (from && typeof from === "object" || typeof from === "function") {
45
+ for (let key of __getOwnPropNames(from))
46
+ if (!__hasOwnProp.call(to, key) && key !== except)
47
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
48
+ }
49
+ return to;
50
+ };
51
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
52
+ // If the importer is in node compatibility mode or this is not an ESM
53
+ // file that has been converted to a CommonJS file using a Babel-
54
+ // compatible transform (i.e. "__esModule" has not been set), then set
55
+ // "default" to the CommonJS "module.exports" for node compatibility.
56
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
57
+ mod
58
+ ));
59
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
60
+ var __async = (__this, __arguments, generator) => {
61
+ return new Promise((resolve, reject) => {
62
+ var fulfilled = (value) => {
63
+ try {
64
+ step(generator.next(value));
65
+ } catch (e) {
66
+ reject(e);
67
+ }
68
+ };
69
+ var rejected = (value) => {
70
+ try {
71
+ step(generator.throw(value));
72
+ } catch (e) {
73
+ reject(e);
74
+ }
75
+ };
76
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
77
+ step((generator = generator.apply(__this, __arguments)).next());
78
+ });
79
+ };
80
+
81
+ // src/index.tsx
82
+ var src_exports = {};
83
+ __export(src_exports, {
84
+ CopilotContext: () => CopilotContext,
85
+ CopilotKit: () => CopilotKit,
86
+ CopilotMessagesContext: () => CopilotMessagesContext,
87
+ CopilotTask: () => CopilotTask,
88
+ defaultCopilotContextCategories: () => defaultCopilotContextCategories,
89
+ extract: () => extract,
90
+ runAgent: () => runAgent,
91
+ shouldShowDevConsole: () => shouldShowDevConsole,
92
+ startAgent: () => startAgent,
93
+ stopAgent: () => stopAgent,
94
+ useCoAgent: () => useCoAgent,
95
+ useCoAgentStateRender: () => useCoAgentStateRender,
96
+ useCopilotAction: () => useCopilotAction,
97
+ useCopilotAuthenticatedAction: () => useCopilotAuthenticatedAction,
98
+ useCopilotChat: () => useCopilotChat,
99
+ useCopilotContext: () => useCopilotContext,
100
+ useCopilotMessagesContext: () => useCopilotMessagesContext,
101
+ useCopilotReadable: () => useCopilotReadable,
102
+ useCopilotRuntimeClient: () => useCopilotRuntimeClient,
103
+ useMakeCopilotDocumentReadable: () => useMakeCopilotDocumentReadable
104
+ });
105
+ module.exports = __toCommonJS(src_exports);
106
+
107
+ // src/components/copilot-provider/copilotkit.tsx
108
+ var import_react10 = require("react");
109
+
110
+ // src/context/copilot-context.tsx
111
+ var import_react = __toESM(require("react"));
112
+ var emptyCopilotContext = {
113
+ actions: {},
114
+ setAction: () => {
115
+ },
116
+ removeAction: () => {
117
+ },
118
+ coAgentStateRenders: {},
119
+ setCoAgentStateRender: () => {
120
+ },
121
+ removeCoAgentStateRender: () => {
122
+ },
123
+ chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
124
+ getContextString: (documents, categories) => returnAndThrowInDebug(""),
125
+ addContext: () => "",
126
+ removeContext: () => {
127
+ },
128
+ getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
129
+ })),
130
+ isLoading: false,
131
+ setIsLoading: () => returnAndThrowInDebug(false),
132
+ chatInstructions: "",
133
+ setChatInstructions: () => returnAndThrowInDebug(""),
134
+ getDocumentsContext: (categories) => returnAndThrowInDebug([]),
135
+ addDocumentContext: () => returnAndThrowInDebug(""),
136
+ removeDocumentContext: () => {
137
+ },
138
+ runtimeClient: {},
139
+ copilotApiConfig: new class {
140
+ get chatApiEndpoint() {
141
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
142
+ }
143
+ get headers() {
144
+ return {};
145
+ }
146
+ get body() {
147
+ return {};
148
+ }
149
+ }(),
150
+ chatSuggestionConfiguration: {},
151
+ addChatSuggestionConfiguration: () => {
152
+ },
153
+ removeChatSuggestionConfiguration: () => {
154
+ },
155
+ showDevConsole: "auto",
156
+ coagentStates: {},
157
+ setCoagentStates: () => {
158
+ },
159
+ coagentStatesRef: { current: {} },
160
+ setCoagentStatesWithRef: () => {
161
+ },
162
+ agentSession: null,
163
+ setAgentSession: () => {
164
+ },
165
+ forwardedParameters: {},
166
+ agentLock: null,
167
+ threadId: "",
168
+ setThreadId: () => {
169
+ },
170
+ runId: null,
171
+ setRunId: () => {
172
+ },
173
+ chatAbortControllerRef: { current: null },
174
+ availableAgents: [],
175
+ extensions: {},
176
+ setExtensions: () => {
177
+ }
178
+ };
179
+ var CopilotContext = import_react.default.createContext(emptyCopilotContext);
180
+ function useCopilotContext() {
181
+ const context = import_react.default.useContext(CopilotContext);
182
+ if (context === emptyCopilotContext) {
183
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
184
+ }
185
+ return context;
186
+ }
187
+ function returnAndThrowInDebug(_value) {
188
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
189
+ }
190
+
191
+ // src/hooks/use-tree.ts
192
+ var import_shared = require("@copilotkit/shared");
193
+ var import_react2 = require("react");
194
+ var removeNode = (nodes, id) => {
195
+ return nodes.reduce((result, node) => {
196
+ if (node.id !== id) {
197
+ const newNode = __spreadProps(__spreadValues({}, node), { children: removeNode(node.children, id) });
198
+ result.push(newNode);
199
+ }
200
+ return result;
201
+ }, []);
202
+ };
203
+ var addNode = (nodes, newNode, parentId) => {
204
+ if (!parentId) {
205
+ return [...nodes, newNode];
206
+ }
207
+ return nodes.map((node) => {
208
+ if (node.id === parentId) {
209
+ return __spreadProps(__spreadValues({}, node), { children: [...node.children, newNode] });
210
+ } else if (node.children.length) {
211
+ return __spreadProps(__spreadValues({}, node), { children: addNode(node.children, newNode, parentId) });
212
+ }
213
+ return node;
214
+ });
215
+ };
216
+ var treeIndentationRepresentation = (index, indentLevel) => {
217
+ if (indentLevel === 0) {
218
+ return (index + 1).toString();
219
+ } else if (indentLevel === 1) {
220
+ return String.fromCharCode(65 + index);
221
+ } else if (indentLevel === 2) {
222
+ return String.fromCharCode(97 + index);
223
+ } else {
224
+ return "-";
225
+ }
226
+ };
227
+ var printNode = (node, prefix = "", indentLevel = 0) => {
228
+ const indent = " ".repeat(3).repeat(indentLevel);
229
+ const prefixPlusIndentLength = prefix.length + indent.length;
230
+ const subsequentLinesPrefix = " ".repeat(prefixPlusIndentLength);
231
+ const valueLines = node.value.split("\n");
232
+ const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;
233
+ const outputSubsequentLines = valueLines.slice(1).map((line) => `${subsequentLinesPrefix}${line}`).join("\n");
234
+ let output = `${outputFirstLine}
235
+ `;
236
+ if (outputSubsequentLines) {
237
+ output += `${outputSubsequentLines}
238
+ `;
239
+ }
240
+ const childPrePrefix = " ".repeat(prefix.length);
241
+ node.children.forEach(
242
+ (child, index) => output += printNode(
243
+ child,
244
+ `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `,
245
+ indentLevel + 1
246
+ )
247
+ );
248
+ return output;
249
+ };
250
+ function treeReducer(state, action) {
251
+ switch (action.type) {
252
+ case "ADD_NODE": {
253
+ const { value, parentId, id: newNodeId } = action;
254
+ const newNode = {
255
+ id: newNodeId,
256
+ value,
257
+ children: [],
258
+ categories: new Set(action.categories)
259
+ };
260
+ try {
261
+ return addNode(state, newNode, parentId);
262
+ } catch (error) {
263
+ console.error(`Error while adding node with id ${newNodeId}: ${error}`);
264
+ return state;
265
+ }
266
+ }
267
+ case "REMOVE_NODE":
268
+ return removeNode(state, action.id);
269
+ default:
270
+ return state;
271
+ }
272
+ }
273
+ var useTree = () => {
274
+ const [tree, dispatch] = (0, import_react2.useReducer)(treeReducer, []);
275
+ const addElement = (0, import_react2.useCallback)(
276
+ (value, categories, parentId) => {
277
+ const newNodeId = (0, import_shared.randomId)();
278
+ dispatch({
279
+ type: "ADD_NODE",
280
+ value,
281
+ parentId,
282
+ id: newNodeId,
283
+ categories
284
+ });
285
+ return newNodeId;
286
+ },
287
+ []
288
+ );
289
+ const removeElement = (0, import_react2.useCallback)((id) => {
290
+ dispatch({ type: "REMOVE_NODE", id });
291
+ }, []);
292
+ const printTree = (0, import_react2.useCallback)(
293
+ (categories) => {
294
+ const categoriesSet = new Set(categories);
295
+ let output = "";
296
+ tree.forEach((node, index) => {
297
+ if (!setsHaveIntersection(categoriesSet, node.categories)) {
298
+ return;
299
+ }
300
+ if (index !== 0) {
301
+ output += "\n";
302
+ }
303
+ output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);
304
+ });
305
+ return output;
306
+ },
307
+ [tree]
308
+ );
309
+ return { tree, addElement, printTree, removeElement };
310
+ };
311
+ var use_tree_default = useTree;
312
+ function setsHaveIntersection(setA, setB) {
313
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
314
+ for (let item of smallerSet) {
315
+ if (largerSet.has(item)) {
316
+ return true;
317
+ }
318
+ }
319
+ return false;
320
+ }
321
+
322
+ // src/components/copilot-provider/copilotkit.tsx
323
+ var import_react_dom = require("react-dom");
324
+ var import_shared4 = require("@copilotkit/shared");
325
+
326
+ // src/hooks/use-flat-category-store.ts
327
+ var import_react3 = require("react");
328
+ var import_shared2 = require("@copilotkit/shared");
329
+ var useFlatCategoryStore = () => {
330
+ const [elements, dispatch] = (0, import_react3.useReducer)(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
331
+ const addElement = (0, import_react3.useCallback)((value, categories) => {
332
+ const newId = (0, import_shared2.randomId)();
333
+ dispatch({
334
+ type: "ADD_ELEMENT",
335
+ value,
336
+ id: newId,
337
+ categories
338
+ });
339
+ return newId;
340
+ }, []);
341
+ const removeElement = (0, import_react3.useCallback)((id) => {
342
+ dispatch({ type: "REMOVE_ELEMENT", id });
343
+ }, []);
344
+ const allElements = (0, import_react3.useCallback)(
345
+ (categories) => {
346
+ const categoriesSet = new Set(categories);
347
+ const result = [];
348
+ elements.forEach((element) => {
349
+ if (setsHaveIntersection2(categoriesSet, element.categories)) {
350
+ result.push(element.value);
351
+ }
352
+ });
353
+ return result;
354
+ },
355
+ [elements]
356
+ );
357
+ return { addElement, removeElement, allElements };
358
+ };
359
+ var use_flat_category_store_default = useFlatCategoryStore;
360
+ function flatCategoryStoreReducer(state, action) {
361
+ switch (action.type) {
362
+ case "ADD_ELEMENT": {
363
+ const { value, id, categories } = action;
364
+ const newElement = {
365
+ id,
366
+ value,
367
+ categories: new Set(categories)
368
+ };
369
+ const newState = new Map(state);
370
+ newState.set(id, newElement);
371
+ return newState;
372
+ }
373
+ case "REMOVE_ELEMENT": {
374
+ const newState = new Map(state);
375
+ newState.delete(action.id);
376
+ return newState;
377
+ }
378
+ default:
379
+ return state;
380
+ }
381
+ }
382
+ function setsHaveIntersection2(setA, setB) {
383
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
384
+ for (let item of smallerSet) {
385
+ if (largerSet.has(item)) {
386
+ return true;
387
+ }
388
+ }
389
+ return false;
390
+ }
391
+
392
+ // src/components/copilot-provider/copilot-messages.tsx
393
+ var import_react5 = require("react");
394
+
395
+ // src/context/copilot-messages-context.tsx
396
+ var import_react4 = __toESM(require("react"));
397
+ var emptyCopilotContext2 = {
398
+ messages: [],
399
+ setMessages: () => []
400
+ };
401
+ var CopilotMessagesContext = import_react4.default.createContext(emptyCopilotContext2);
402
+ function useCopilotMessagesContext() {
403
+ const context = import_react4.default.useContext(CopilotMessagesContext);
404
+ if (context === emptyCopilotContext2) {
405
+ throw new Error(
406
+ "A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`"
407
+ );
408
+ }
409
+ return context;
410
+ }
411
+
412
+ // src/components/copilot-provider/copilot-messages.tsx
413
+ var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
414
+ var import_jsx_runtime = require("react/jsx-runtime");
415
+ function CopilotMessages(_a) {
416
+ var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
417
+ const [messages, setMessages] = (0, import_react5.useState)([]);
418
+ const { threadId, agentSession, runtimeClient } = useCopilotContext();
419
+ (0, import_react5.useEffect)(() => {
420
+ if (agentSession == null ? void 0 : agentSession.agentName) {
421
+ const fetchAgentState = () => __async(this, null, function* () {
422
+ var _a2, _b2, _c, _d;
423
+ const result = yield runtimeClient.loadAgentState({
424
+ threadId,
425
+ agentName: agentSession.agentName
426
+ });
427
+ if ((_b2 = (_a2 = result.data) == null ? void 0 : _a2.loadAgentState) == null ? void 0 : _b2.threadExists) {
428
+ const messages2 = (0, import_runtime_client_gql.loadMessagesFromJsonRepresentation)(
429
+ JSON.parse(((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.messages) || "[]")
430
+ );
431
+ setMessages(messages2);
432
+ }
433
+ });
434
+ void fetchAgentState();
435
+ }
436
+ }, [threadId, (agentSession == null ? void 0 : agentSession.agentName) !== void 0]);
437
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
438
+ CopilotMessagesContext.Provider,
439
+ {
440
+ value: {
441
+ messages,
442
+ setMessages
443
+ },
444
+ children
445
+ }
446
+ );
447
+ }
448
+
449
+ // src/components/toast/toast-provider.tsx
450
+ var import_react7 = require("react");
451
+
452
+ // src/components/error-boundary/error-utils.tsx
453
+ var import_react6 = require("react");
454
+
455
+ // src/components/toast/exclamation-mark-icon.tsx
456
+ var import_jsx_runtime2 = require("react/jsx-runtime");
457
+ var ExclamationMarkIcon = ({
458
+ className,
459
+ style
460
+ }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
461
+ "svg",
462
+ {
463
+ xmlns: "http://www.w3.org/2000/svg",
464
+ width: "24",
465
+ height: "24",
466
+ viewBox: "0 0 24 24",
467
+ fill: "none",
468
+ stroke: "currentColor",
469
+ strokeWidth: "2",
470
+ strokeLinecap: "round",
471
+ strokeLinejoin: "round",
472
+ className: `lucide lucide-circle-alert ${className ? className : ""}`,
473
+ style,
474
+ children: [
475
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("circle", { cx: "12", cy: "12", r: "10" }),
476
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12", y1: "8", y2: "12" }),
477
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12.01", y1: "16", y2: "16" })
478
+ ]
479
+ }
480
+ );
481
+
482
+ // src/components/error-boundary/error-utils.tsx
483
+ var import_jsx_runtime3 = require("react/jsx-runtime");
484
+ function ErrorToast({ errors }) {
485
+ const errorsToRender = errors.map((error, idx) => {
486
+ var _a, _b, _c;
487
+ const message = "extensions" in error ? (_b = (_a = error.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message : error.message;
488
+ const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
489
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
490
+ "div",
491
+ {
492
+ style: {
493
+ marginTop: idx === 0 ? 0 : 10,
494
+ marginBottom: 14
495
+ },
496
+ children: [
497
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
498
+ code && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
499
+ "div",
500
+ {
501
+ style: {
502
+ fontWeight: "600",
503
+ marginBottom: 4
504
+ },
505
+ children: [
506
+ "Copilot Cloud Error:",
507
+ " ",
508
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
509
+ ]
510
+ }
511
+ ),
512
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { children: message })
513
+ ]
514
+ },
515
+ idx
516
+ );
517
+ });
518
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
519
+ "div",
520
+ {
521
+ style: {
522
+ fontSize: "13px",
523
+ maxWidth: "600px"
524
+ },
525
+ children: [
526
+ errorsToRender,
527
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
528
+ ]
529
+ }
530
+ );
531
+ }
532
+ function useErrorToast() {
533
+ const { addToast } = useToast();
534
+ return (0, import_react6.useCallback)(
535
+ (error) => {
536
+ const errorId = error.map((err) => {
537
+ var _a, _b;
538
+ const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
539
+ const stack = err.stack || "";
540
+ return btoa(message + stack).slice(0, 32);
541
+ }).join("|");
542
+ addToast({
543
+ type: "error",
544
+ id: errorId,
545
+ // Toast libraries typically dedupe by id
546
+ message: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ErrorToast, { errors: error })
547
+ });
548
+ },
549
+ [addToast]
550
+ );
551
+ }
552
+ function useAsyncCallback(callback, deps) {
553
+ const addErrorToast = useErrorToast();
554
+ return (0, import_react6.useCallback)((...args) => __async(this, null, function* () {
555
+ try {
556
+ return yield callback(...args);
557
+ } catch (error) {
558
+ console.error("Error in async callback:", error);
559
+ addErrorToast([error]);
560
+ throw error;
561
+ }
562
+ }), deps);
563
+ }
564
+
565
+ // src/components/toast/toast-provider.tsx
566
+ var import_jsx_runtime4 = require("react/jsx-runtime");
567
+ var ToastContext = (0, import_react7.createContext)(void 0);
568
+ function useToast() {
569
+ const context = (0, import_react7.useContext)(ToastContext);
570
+ if (!context) {
571
+ throw new Error("useToast must be used within a ToastProvider");
572
+ }
573
+ return context;
574
+ }
575
+ function ToastProvider({
576
+ enabled,
577
+ children
578
+ }) {
579
+ const [toasts, setToasts] = (0, import_react7.useState)([]);
580
+ const addToast = (0, import_react7.useCallback)((toast) => {
581
+ var _a;
582
+ const id = (_a = toast.id) != null ? _a : Math.random().toString(36).substring(2, 9);
583
+ setToasts((currentToasts) => {
584
+ if (currentToasts.find((toast2) => toast2.id === id))
585
+ return currentToasts;
586
+ return [...currentToasts, __spreadProps(__spreadValues({}, toast), { id })];
587
+ });
588
+ if (toast.duration) {
589
+ setTimeout(() => {
590
+ removeToast(id);
591
+ }, toast.duration);
592
+ }
593
+ }, []);
594
+ const addGraphQLErrorsToast = (0, import_react7.useCallback)((errors) => {
595
+ addToast({
596
+ type: "error",
597
+ message: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ErrorToast, { errors })
598
+ });
599
+ }, []);
600
+ const removeToast = (0, import_react7.useCallback)((id) => {
601
+ setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));
602
+ }, []);
603
+ const value = {
604
+ toasts,
605
+ addToast,
606
+ addGraphQLErrorsToast,
607
+ removeToast,
608
+ enabled
609
+ };
610
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(ToastContext.Provider, { value, children: [
611
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
612
+ "div",
613
+ {
614
+ style: {
615
+ position: "fixed",
616
+ bottom: "1rem",
617
+ left: "50%",
618
+ transform: "translateX(-50%)",
619
+ zIndex: 50,
620
+ display: "flex",
621
+ flexDirection: "column",
622
+ gap: "0.5rem"
623
+ },
624
+ children: [
625
+ toasts.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { textAlign: "right" }, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
626
+ "button",
627
+ {
628
+ onClick: () => setToasts([]),
629
+ style: {
630
+ padding: "4px 8px",
631
+ fontSize: "12px",
632
+ cursor: "pointer",
633
+ background: "white",
634
+ border: "1px solid rgba(0,0,0,0.2)",
635
+ borderRadius: "4px"
636
+ },
637
+ children: "Close All"
638
+ }
639
+ ) }),
640
+ toasts.map((toast) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
641
+ Toast,
642
+ {
643
+ message: toast.message,
644
+ type: toast.type,
645
+ onClose: () => removeToast(toast.id)
646
+ },
647
+ toast.id
648
+ ))
649
+ ]
650
+ }
651
+ ),
652
+ children
653
+ ] });
654
+ }
655
+ function Toast({
656
+ message,
657
+ type = "info",
658
+ onClose
659
+ }) {
660
+ const bgColors = {
661
+ info: "#3b82f6",
662
+ success: "#22c55e",
663
+ warning: "#eab308",
664
+ error: "#ef4444"
665
+ };
666
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
667
+ "div",
668
+ {
669
+ style: {
670
+ backgroundColor: bgColors[type],
671
+ color: "white",
672
+ padding: "0.5rem 1.5rem",
673
+ borderRadius: "0.25rem",
674
+ boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
675
+ position: "relative",
676
+ minWidth: "200px"
677
+ },
678
+ children: [
679
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: message }),
680
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
681
+ "button",
682
+ {
683
+ onClick: onClose,
684
+ style: {
685
+ position: "absolute",
686
+ top: "0",
687
+ right: "0",
688
+ background: "none",
689
+ border: "none",
690
+ color: "white",
691
+ cursor: "pointer",
692
+ padding: "0.5rem",
693
+ fontSize: "1rem"
694
+ },
695
+ children: "\u2715"
696
+ }
697
+ )
698
+ ]
699
+ }
700
+ );
701
+ }
702
+
703
+ // src/hooks/use-copilot-runtime-client.ts
704
+ var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
705
+ var import_react8 = require("react");
706
+ var useCopilotRuntimeClient = (options) => {
707
+ const { addGraphQLErrorsToast } = useToast();
708
+ const addErrorToast = useErrorToast();
709
+ const runtimeClient = (0, import_react8.useMemo)(() => {
710
+ return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, options), {
711
+ handleGQLErrors: (error) => {
712
+ if (error.graphQLErrors.length) {
713
+ addGraphQLErrorsToast(error.graphQLErrors);
714
+ } else {
715
+ addErrorToast([error]);
716
+ }
717
+ }
718
+ }));
719
+ }, [options, addGraphQLErrorsToast]);
720
+ return runtimeClient;
721
+ };
722
+
723
+ // src/utils/extract.ts
724
+ var import_shared3 = require("@copilotkit/shared");
725
+ var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
726
+ var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
727
+ function extract(_0) {
728
+ return __async(this, arguments, function* ({
729
+ context,
730
+ instructions,
731
+ parameters,
732
+ include,
733
+ data,
734
+ abortSignal,
735
+ stream,
736
+ requestType = import_runtime_client_gql3.CopilotRequestType.Task,
737
+ forwardedParameters
738
+ }) {
739
+ var _a, _b;
740
+ const { messages } = context;
741
+ const action = {
742
+ name: "extract",
743
+ description: instructions,
744
+ parameters,
745
+ handler: (args) => {
746
+ }
747
+ };
748
+ const includeReadable = (_a = include == null ? void 0 : include.readable) != null ? _a : false;
749
+ const includeMessages = (_b = include == null ? void 0 : include.messages) != null ? _b : false;
750
+ let contextString = "";
751
+ if (data) {
752
+ contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
753
+ }
754
+ if (includeReadable) {
755
+ contextString += context.getContextString([], defaultCopilotContextCategories);
756
+ }
757
+ const systemMessage = new import_runtime_client_gql3.TextMessage({
758
+ content: makeSystemMessage(contextString, instructions),
759
+ role: import_runtime_client_gql3.Role.System
760
+ });
761
+ const instructionsMessage = new import_runtime_client_gql3.TextMessage({
762
+ content: makeInstructionsMessage(instructions),
763
+ role: import_runtime_client_gql3.Role.User
764
+ });
765
+ const response = context.runtimeClient.asStream(
766
+ context.runtimeClient.generateCopilotResponse({
767
+ data: {
768
+ frontend: {
769
+ actions: [
770
+ {
771
+ name: action.name,
772
+ description: action.description || "",
773
+ jsonSchema: JSON.stringify((0, import_shared3.actionParametersToJsonSchema)(action.parameters || []))
774
+ }
775
+ ],
776
+ url: window.location.href
777
+ },
778
+ messages: (0, import_runtime_client_gql4.convertMessagesToGqlInput)(
779
+ includeMessages ? [systemMessage, instructionsMessage, ...(0, import_runtime_client_gql4.filterAgentStateMessages)(messages)] : [systemMessage, instructionsMessage]
780
+ ),
781
+ metadata: {
782
+ requestType
783
+ },
784
+ forwardedParameters: __spreadProps(__spreadValues({}, forwardedParameters != null ? forwardedParameters : {}), {
785
+ toolChoice: "function",
786
+ toolChoiceFunctionName: action.name
787
+ })
788
+ },
789
+ properties: context.copilotApiConfig.properties,
790
+ signal: abortSignal
791
+ })
792
+ );
793
+ const reader = response.getReader();
794
+ let isInitial = true;
795
+ let actionExecutionMessage = void 0;
796
+ while (true) {
797
+ const { done, value } = yield reader.read();
798
+ if (done) {
799
+ break;
800
+ }
801
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
802
+ throw new Error("Aborted");
803
+ }
804
+ actionExecutionMessage = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
805
+ value.generateCopilotResponse.messages
806
+ ).find((msg) => msg.isActionExecutionMessage());
807
+ if (!actionExecutionMessage) {
808
+ continue;
809
+ }
810
+ stream == null ? void 0 : stream({
811
+ status: isInitial ? "initial" : "inProgress",
812
+ args: actionExecutionMessage.arguments
813
+ });
814
+ isInitial = false;
815
+ }
816
+ if (!actionExecutionMessage) {
817
+ throw new Error("extract() failed: No function call occurred");
818
+ }
819
+ stream == null ? void 0 : stream({
820
+ status: "complete",
821
+ args: actionExecutionMessage.arguments
822
+ });
823
+ return actionExecutionMessage.arguments;
824
+ });
825
+ }
826
+ function makeInstructionsMessage(instructions) {
827
+ return `
828
+ The user has given you the following task to complete:
829
+
830
+ \`\`\`
831
+ ${instructions}
832
+ \`\`\`
833
+
834
+ Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
835
+ `;
836
+ }
837
+ function makeSystemMessage(contextString, instructions) {
838
+ return `
839
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
840
+
841
+ 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.
842
+ Always be polite and respectful, and prefer brevity over verbosity.
843
+
844
+ The user has provided you with the following context:
845
+ \`\`\`
846
+ ${contextString}
847
+ \`\`\`
848
+
849
+ They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
850
+
851
+ Please assist them as best you can.
852
+
853
+ This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
854
+ `;
855
+ }
856
+
857
+ // src/utils/dev-console.ts
858
+ function shouldShowDevConsole(showDevConsole) {
859
+ if (typeof showDevConsole === "boolean") {
860
+ return showDevConsole;
861
+ }
862
+ return getHostname() === "localhost" || getHostname() === "127.0.0.1" || getHostname() === "0.0.0.0" || getHostname() === "::1";
863
+ }
864
+ function getHostname() {
865
+ if (typeof window !== "undefined" && window.location) {
866
+ return window.location.hostname;
867
+ }
868
+ return "";
869
+ }
870
+
871
+ // src/components/error-boundary/error-boundary.tsx
872
+ var import_react9 = __toESM(require("react"));
873
+ var import_jsx_runtime5 = require("react/jsx-runtime");
874
+ var CopilotErrorBoundary = class extends import_react9.default.Component {
875
+ constructor(props) {
876
+ super(props);
877
+ this.state = { hasError: false };
878
+ }
879
+ static getDerivedStateFromError(error) {
880
+ return { hasError: true, error };
881
+ }
882
+ componentDidCatch(error, errorInfo) {
883
+ console.error("CopilotKit Error:", error, errorInfo);
884
+ }
885
+ render() {
886
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(ErrorToast2, { error: this.state.error, children: this.props.children });
887
+ }
888
+ };
889
+ function ErrorToast2({ error, children }) {
890
+ const addErrorToast = useErrorToast();
891
+ (0, import_react9.useEffect)(() => {
892
+ if (error) {
893
+ addErrorToast([error]);
894
+ }
895
+ }, [error, addErrorToast]);
896
+ return children;
897
+ }
898
+
899
+ // src/components/copilot-provider/copilotkit.tsx
900
+ var import_jsx_runtime6 = require("react/jsx-runtime");
901
+ function CopilotKit(_a) {
902
+ var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
903
+ const showDevConsole = props.showDevConsole === void 0 ? "auto" : props.showDevConsole;
904
+ const enabled = shouldShowDevConsole(showDevConsole);
905
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ToastProvider, { enabled, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(CopilotErrorBoundary, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children })) }) });
906
+ }
907
+ function CopilotKitInternal(_a) {
908
+ var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
909
+ if (!props.runtimeUrl && !props.publicApiKey) {
910
+ throw new Error(
911
+ "Please provide either a runtimeUrl or a publicApiKey to the CopilotKit component."
912
+ );
913
+ }
914
+ const chatApiEndpoint = props.runtimeUrl || import_shared4.COPILOT_CLOUD_CHAT_URL;
915
+ const [actions, setActions] = (0, import_react10.useState)({});
916
+ const [coAgentStateRenders, setCoAgentStateRenders] = (0, import_react10.useState)({});
917
+ const chatComponentsCache = (0, import_react10.useRef)({
918
+ actions: {},
919
+ coAgentStateRenders: {}
920
+ });
921
+ const { addElement, removeElement, printTree } = use_tree_default();
922
+ const [isLoading, setIsLoading] = (0, import_react10.useState)(false);
923
+ const [chatInstructions, setChatInstructions] = (0, import_react10.useState)("");
924
+ const [authStates, setAuthStates] = (0, import_react10.useState)({});
925
+ const [extensions, setExtensions] = (0, import_react10.useState)({});
926
+ const {
927
+ addElement: addDocument,
928
+ removeElement: removeDocument,
929
+ allElements: allDocuments
930
+ } = use_flat_category_store_default();
931
+ const setAction = (0, import_react10.useCallback)((id, action) => {
932
+ setActions((prevPoints) => {
933
+ return __spreadProps(__spreadValues({}, prevPoints), {
934
+ [id]: action
935
+ });
936
+ });
937
+ }, []);
938
+ const removeAction = (0, import_react10.useCallback)((id) => {
939
+ setActions((prevPoints) => {
940
+ const newPoints = __spreadValues({}, prevPoints);
941
+ delete newPoints[id];
942
+ return newPoints;
943
+ });
944
+ }, []);
945
+ const setCoAgentStateRender = (0, import_react10.useCallback)((id, stateRender) => {
946
+ setCoAgentStateRenders((prevPoints) => {
947
+ return __spreadProps(__spreadValues({}, prevPoints), {
948
+ [id]: stateRender
949
+ });
950
+ });
951
+ }, []);
952
+ const removeCoAgentStateRender = (0, import_react10.useCallback)((id) => {
953
+ setCoAgentStateRenders((prevPoints) => {
954
+ const newPoints = __spreadValues({}, prevPoints);
955
+ delete newPoints[id];
956
+ return newPoints;
957
+ });
958
+ }, []);
959
+ const getContextString = (0, import_react10.useCallback)(
960
+ (documents, categories) => {
961
+ const documentsString = documents.map((document) => {
962
+ return `${document.name} (${document.sourceApplication}):
963
+ ${document.getContents()}`;
964
+ }).join("\n\n");
965
+ const nonDocumentStrings = printTree(categories);
966
+ return `${documentsString}
967
+
968
+ ${nonDocumentStrings}`;
969
+ },
970
+ [printTree]
971
+ );
972
+ const addContext = (0, import_react10.useCallback)(
973
+ (context, parentId, categories = defaultCopilotContextCategories) => {
974
+ return addElement(context, categories, parentId);
975
+ },
976
+ [addElement]
977
+ );
978
+ const removeContext = (0, import_react10.useCallback)(
979
+ (id) => {
980
+ removeElement(id);
981
+ },
982
+ [removeElement]
983
+ );
984
+ const getFunctionCallHandler = (0, import_react10.useCallback)(
985
+ (customEntryPoints) => {
986
+ return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
987
+ },
988
+ [actions]
989
+ );
990
+ const getDocumentsContext = (0, import_react10.useCallback)(
991
+ (categories) => {
992
+ return allDocuments(categories);
993
+ },
994
+ [allDocuments]
995
+ );
996
+ const addDocumentContext = (0, import_react10.useCallback)(
997
+ (documentPointer, categories = defaultCopilotContextCategories) => {
998
+ return addDocument(documentPointer, categories);
999
+ },
1000
+ [addDocument]
1001
+ );
1002
+ const removeDocumentContext = (0, import_react10.useCallback)(
1003
+ (documentId) => {
1004
+ removeDocument(documentId);
1005
+ },
1006
+ [removeDocument]
1007
+ );
1008
+ if (!props.publicApiKey) {
1009
+ if (props.cloudRestrictToTopic) {
1010
+ throw new Error(
1011
+ "To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey."
1012
+ );
1013
+ }
1014
+ }
1015
+ const copilotApiConfig = (0, import_react10.useMemo)(() => {
1016
+ var _a2, _b2;
1017
+ let cloud = void 0;
1018
+ if (props.publicApiKey) {
1019
+ cloud = {
1020
+ guardrails: {
1021
+ input: {
1022
+ restrictToTopic: {
1023
+ enabled: props.cloudRestrictToTopic ? true : false,
1024
+ validTopics: ((_a2 = props.cloudRestrictToTopic) == null ? void 0 : _a2.validTopics) || [],
1025
+ invalidTopics: ((_b2 = props.cloudRestrictToTopic) == null ? void 0 : _b2.invalidTopics) || []
1026
+ }
1027
+ }
1028
+ }
1029
+ };
1030
+ }
1031
+ return __spreadProps(__spreadValues({
1032
+ publicApiKey: props.publicApiKey
1033
+ }, cloud ? { cloud } : {}), {
1034
+ chatApiEndpoint,
1035
+ headers: props.headers || {},
1036
+ properties: props.properties || {},
1037
+ transcribeAudioUrl: props.transcribeAudioUrl,
1038
+ textToSpeechUrl: props.textToSpeechUrl,
1039
+ credentials: props.credentials
1040
+ });
1041
+ }, [
1042
+ props.publicApiKey,
1043
+ props.headers,
1044
+ props.properties,
1045
+ props.transcribeAudioUrl,
1046
+ props.textToSpeechUrl,
1047
+ props.credentials,
1048
+ props.cloudRestrictToTopic
1049
+ ]);
1050
+ const headers = (0, import_react10.useMemo)(() => {
1051
+ const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {
1052
+ if (state.status === "authenticated" && state.authHeaders) {
1053
+ return __spreadValues(__spreadValues({}, acc), Object.entries(state.authHeaders).reduce(
1054
+ (headers2, [key, value]) => __spreadProps(__spreadValues({}, headers2), {
1055
+ [key.startsWith("X-Custom-") ? key : `X-Custom-${key}`]: value
1056
+ }),
1057
+ {}
1058
+ ));
1059
+ }
1060
+ return acc;
1061
+ }, {});
1062
+ return __spreadValues(__spreadValues(__spreadValues({}, copilotApiConfig.headers || {}), copilotApiConfig.publicApiKey ? { [import_shared4.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {}), authHeaders);
1063
+ }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);
1064
+ const runtimeClient = useCopilotRuntimeClient({
1065
+ url: copilotApiConfig.chatApiEndpoint,
1066
+ publicApiKey: copilotApiConfig.publicApiKey,
1067
+ headers,
1068
+ credentials: copilotApiConfig.credentials
1069
+ });
1070
+ const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, import_react10.useState)({});
1071
+ const addChatSuggestionConfiguration = (id, suggestion) => {
1072
+ setChatSuggestionConfiguration((prev) => __spreadProps(__spreadValues({}, prev), { [id]: suggestion }));
1073
+ };
1074
+ const removeChatSuggestionConfiguration = (id) => {
1075
+ setChatSuggestionConfiguration((prev) => {
1076
+ const _a2 = prev, { [id]: _ } = _a2, rest = __objRest(_a2, [__restKey(id)]);
1077
+ return rest;
1078
+ });
1079
+ };
1080
+ const [availableAgents, setAvailableAgents] = (0, import_react10.useState)([]);
1081
+ const [coagentStates, setCoagentStates] = (0, import_react10.useState)({});
1082
+ const coagentStatesRef = (0, import_react10.useRef)({});
1083
+ const setCoagentStatesWithRef = (0, import_react10.useCallback)(
1084
+ (value) => {
1085
+ const newValue = typeof value === "function" ? value(coagentStatesRef.current) : value;
1086
+ coagentStatesRef.current = newValue;
1087
+ setCoagentStates((prev) => {
1088
+ return newValue;
1089
+ });
1090
+ },
1091
+ []
1092
+ );
1093
+ (0, import_react10.useEffect)(() => {
1094
+ const fetchData = () => __async(this, null, function* () {
1095
+ var _a2;
1096
+ const result = yield runtimeClient.availableAgents();
1097
+ if ((_a2 = result.data) == null ? void 0 : _a2.availableAgents) {
1098
+ setAvailableAgents(result.data.availableAgents.agents);
1099
+ }
1100
+ });
1101
+ void fetchData();
1102
+ }, []);
1103
+ let initialAgentSession = null;
1104
+ if (props.agent) {
1105
+ initialAgentSession = {
1106
+ agentName: props.agent
1107
+ };
1108
+ }
1109
+ const [agentSession, setAgentSession] = (0, import_react10.useState)(initialAgentSession);
1110
+ const [internalThreadId, setInternalThreadId] = (0, import_react10.useState)(props.threadId || (0, import_shared4.randomUUID)());
1111
+ const setThreadId = (0, import_react10.useCallback)(
1112
+ (value) => {
1113
+ if (props.threadId) {
1114
+ throw new Error("Cannot call setThreadId() when threadId is provided via props.");
1115
+ }
1116
+ setInternalThreadId(value);
1117
+ },
1118
+ [props.threadId]
1119
+ );
1120
+ (0, import_react10.useEffect)(() => {
1121
+ if (props.threadId !== void 0) {
1122
+ setInternalThreadId(props.threadId);
1123
+ }
1124
+ }, [props.threadId]);
1125
+ const [runId, setRunId] = (0, import_react10.useState)(null);
1126
+ const chatAbortControllerRef = (0, import_react10.useRef)(null);
1127
+ const showDevConsole = props.showDevConsole === void 0 ? "auto" : props.showDevConsole;
1128
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1129
+ CopilotContext.Provider,
1130
+ {
1131
+ value: {
1132
+ actions,
1133
+ chatComponentsCache,
1134
+ getFunctionCallHandler,
1135
+ setAction,
1136
+ removeAction,
1137
+ coAgentStateRenders,
1138
+ setCoAgentStateRender,
1139
+ removeCoAgentStateRender,
1140
+ getContextString,
1141
+ addContext,
1142
+ removeContext,
1143
+ getDocumentsContext,
1144
+ addDocumentContext,
1145
+ removeDocumentContext,
1146
+ copilotApiConfig,
1147
+ isLoading,
1148
+ setIsLoading,
1149
+ chatSuggestionConfiguration,
1150
+ addChatSuggestionConfiguration,
1151
+ removeChatSuggestionConfiguration,
1152
+ chatInstructions,
1153
+ setChatInstructions,
1154
+ showDevConsole,
1155
+ coagentStates,
1156
+ setCoagentStates,
1157
+ coagentStatesRef,
1158
+ setCoagentStatesWithRef,
1159
+ agentSession,
1160
+ setAgentSession,
1161
+ runtimeClient,
1162
+ forwardedParameters: props.forwardedParameters || {},
1163
+ agentLock: props.agent || null,
1164
+ threadId: internalThreadId,
1165
+ setThreadId,
1166
+ runId,
1167
+ setRunId,
1168
+ chatAbortControllerRef,
1169
+ availableAgents,
1170
+ authConfig: props.authConfig,
1171
+ authStates,
1172
+ setAuthStates,
1173
+ extensions,
1174
+ setExtensions
1175
+ },
1176
+ children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(CopilotMessages, { children })
1177
+ }
1178
+ );
1179
+ }
1180
+ var defaultCopilotContextCategories = ["global"];
1181
+ function entryPointsToFunctionCallHandler(actions) {
1182
+ return (_0) => __async(this, [_0], function* ({ messages, name, args }) {
1183
+ let actionsByFunctionName = {};
1184
+ for (let action2 of actions) {
1185
+ actionsByFunctionName[action2.name] = action2;
1186
+ }
1187
+ const action = actionsByFunctionName[name];
1188
+ let result = void 0;
1189
+ if (action) {
1190
+ yield new Promise((resolve, reject) => {
1191
+ (0, import_react_dom.flushSync)(() => __async(this, null, function* () {
1192
+ var _a;
1193
+ try {
1194
+ result = yield (_a = action.handler) == null ? void 0 : _a.call(action, args);
1195
+ resolve();
1196
+ } catch (error) {
1197
+ reject(error);
1198
+ }
1199
+ }));
1200
+ });
1201
+ yield new Promise((resolve) => setTimeout(resolve, 20));
1202
+ }
1203
+ return result;
1204
+ });
1205
+ }
1206
+
1207
+ // src/hooks/use-copilot-chat.ts
1208
+ var import_react12 = require("react");
1209
+ var import_runtime_client_gql7 = require("@copilotkit/runtime-client-gql");
1210
+
1211
+ // src/hooks/use-chat.ts
1212
+ var import_react11 = require("react");
1213
+ var import_shared6 = require("@copilotkit/shared");
1214
+ var import_runtime_client_gql6 = require("@copilotkit/runtime-client-gql");
1215
+
1216
+ // src/types/frontend-action.ts
1217
+ var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
1218
+ var import_shared5 = require("@copilotkit/shared");
1219
+ function processActionsForRuntimeRequest(actions) {
1220
+ const filteredActions = actions.filter(
1221
+ (action) => action.available !== import_runtime_client_gql5.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*"
1222
+ ).map((action) => {
1223
+ let available = import_runtime_client_gql5.ActionInputAvailability.Enabled;
1224
+ if (action.disabled) {
1225
+ available = import_runtime_client_gql5.ActionInputAvailability.Disabled;
1226
+ } else if (action.available === "disabled") {
1227
+ available = import_runtime_client_gql5.ActionInputAvailability.Disabled;
1228
+ } else if (action.available === "remote") {
1229
+ available = import_runtime_client_gql5.ActionInputAvailability.Remote;
1230
+ }
1231
+ return {
1232
+ name: action.name,
1233
+ description: action.description || "",
1234
+ jsonSchema: JSON.stringify((0, import_shared5.actionParametersToJsonSchema)(action.parameters || [])),
1235
+ available
1236
+ };
1237
+ });
1238
+ return filteredActions;
1239
+ }
1240
+
1241
+ // src/hooks/use-chat.ts
1242
+ function useChat(options) {
1243
+ const {
1244
+ messages,
1245
+ setMessages,
1246
+ makeSystemMessageCallback,
1247
+ copilotConfig,
1248
+ setIsLoading,
1249
+ initialMessages,
1250
+ isLoading,
1251
+ actions,
1252
+ onFunctionCall,
1253
+ onCoAgentStateRender,
1254
+ setCoagentStatesWithRef,
1255
+ coagentStatesRef,
1256
+ agentSession,
1257
+ setAgentSession,
1258
+ threadId,
1259
+ setThreadId,
1260
+ runId,
1261
+ setRunId,
1262
+ chatAbortControllerRef,
1263
+ agentLock,
1264
+ extensions,
1265
+ setExtensions
1266
+ } = options;
1267
+ const runChatCompletionRef = (0, import_react11.useRef)();
1268
+ const addErrorToast = useErrorToast();
1269
+ const agentSessionRef = (0, import_react11.useRef)(agentSession);
1270
+ agentSessionRef.current = agentSession;
1271
+ const runIdRef = (0, import_react11.useRef)(runId);
1272
+ runIdRef.current = runId;
1273
+ const extensionsRef = (0, import_react11.useRef)(extensions);
1274
+ extensionsRef.current = extensions;
1275
+ const publicApiKey = copilotConfig.publicApiKey;
1276
+ const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared6.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
1277
+ const runtimeClient = useCopilotRuntimeClient({
1278
+ url: copilotConfig.chatApiEndpoint,
1279
+ publicApiKey: copilotConfig.publicApiKey,
1280
+ headers,
1281
+ credentials: copilotConfig.credentials
1282
+ });
1283
+ const runChatCompletion = useAsyncCallback(
1284
+ (previousMessages) => __async(this, null, function* () {
1285
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
1286
+ setIsLoading(true);
1287
+ let newMessages = [
1288
+ new import_runtime_client_gql6.TextMessage({
1289
+ content: "",
1290
+ role: import_runtime_client_gql6.Role.Assistant
1291
+ })
1292
+ ];
1293
+ chatAbortControllerRef.current = new AbortController();
1294
+ setMessages([...previousMessages, ...newMessages]);
1295
+ const systemMessage = makeSystemMessageCallback();
1296
+ const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
1297
+ const isAgentRun = agentSessionRef.current !== null;
1298
+ const stream = runtimeClient.asStream(
1299
+ runtimeClient.generateCopilotResponse({
1300
+ data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
1301
+ frontend: {
1302
+ actions: processActionsForRuntimeRequest(actions),
1303
+ url: window.location.href
1304
+ },
1305
+ threadId,
1306
+ runId: runIdRef.current,
1307
+ extensions: extensionsRef.current,
1308
+ messages: (0, import_runtime_client_gql6.convertMessagesToGqlInput)((0, import_runtime_client_gql6.filterAgentStateMessages)(messagesWithContext))
1309
+ }, copilotConfig.cloud ? {
1310
+ cloud: __spreadValues({}, ((_c = (_b = (_a = copilotConfig.cloud.guardrails) == null ? void 0 : _a.input) == null ? void 0 : _b.restrictToTopic) == null ? void 0 : _c.enabled) ? {
1311
+ guardrails: {
1312
+ inputValidationRules: {
1313
+ allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
1314
+ denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
1315
+ }
1316
+ }
1317
+ } : {})
1318
+ } : {}), {
1319
+ metadata: {
1320
+ requestType: import_runtime_client_gql6.CopilotRequestType.Chat
1321
+ }
1322
+ }), agentSessionRef.current ? {
1323
+ agentSession: agentSessionRef.current
1324
+ } : {}), {
1325
+ agentStates: Object.values(coagentStatesRef.current).map((state) => ({
1326
+ agentName: state.name,
1327
+ state: JSON.stringify(state.state)
1328
+ })),
1329
+ forwardedParameters: options.forwardedParameters || {}
1330
+ }),
1331
+ properties: copilotConfig.properties,
1332
+ signal: (_d = chatAbortControllerRef.current) == null ? void 0 : _d.signal
1333
+ })
1334
+ );
1335
+ const guardrailsEnabled = ((_g = (_f = (_e = copilotConfig.cloud) == null ? void 0 : _e.guardrails) == null ? void 0 : _f.input) == null ? void 0 : _g.restrictToTopic.enabled) || false;
1336
+ const reader = stream.getReader();
1337
+ let executedCoAgentStateRenders = [];
1338
+ let followUp = void 0;
1339
+ let messages2 = [];
1340
+ let syncedMessages = [];
1341
+ try {
1342
+ while (true) {
1343
+ let done, value;
1344
+ try {
1345
+ const readResult = yield reader.read();
1346
+ done = readResult.done;
1347
+ value = readResult.value;
1348
+ } catch (readError) {
1349
+ break;
1350
+ }
1351
+ if (done) {
1352
+ if (chatAbortControllerRef.current.signal.aborted) {
1353
+ return [];
1354
+ }
1355
+ break;
1356
+ }
1357
+ if (!(value == null ? void 0 : value.generateCopilotResponse)) {
1358
+ continue;
1359
+ }
1360
+ runIdRef.current = value.generateCopilotResponse.runId || null;
1361
+ extensionsRef.current = import_runtime_client_gql6.CopilotRuntimeClient.removeGraphQLTypename(
1362
+ value.generateCopilotResponse.extensions || {}
1363
+ );
1364
+ setRunId(runIdRef.current);
1365
+ setExtensions(extensionsRef.current);
1366
+ messages2 = (0, import_runtime_client_gql6.convertGqlOutputToMessages)(
1367
+ (0, import_runtime_client_gql6.filterAdjacentAgentStateMessages)(value.generateCopilotResponse.messages)
1368
+ );
1369
+ if (messages2.length === 0) {
1370
+ continue;
1371
+ }
1372
+ newMessages = [];
1373
+ if (((_h = value.generateCopilotResponse.status) == null ? void 0 : _h.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
1374
+ newMessages = [
1375
+ new import_runtime_client_gql6.TextMessage({
1376
+ role: import_runtime_client_gql6.MessageRole.Assistant,
1377
+ content: ((_i = value.generateCopilotResponse.status.details) == null ? void 0 : _i.guardrailsReason) || ""
1378
+ })
1379
+ ];
1380
+ setMessages([...previousMessages, ...newMessages]);
1381
+ break;
1382
+ } else {
1383
+ newMessages = [...messages2];
1384
+ for (const message of messages2) {
1385
+ if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
1386
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
1387
+ break;
1388
+ }
1389
+ yield onCoAgentStateRender({
1390
+ name: message.agentName,
1391
+ nodeName: message.nodeName,
1392
+ state: message.state
1393
+ });
1394
+ executedCoAgentStateRenders.push(message.id);
1395
+ }
1396
+ }
1397
+ const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
1398
+ if (lastAgentStateMessage) {
1399
+ if (lastAgentStateMessage.state.messages && lastAgentStateMessage.state.messages.length > 0) {
1400
+ syncedMessages = (0, import_runtime_client_gql6.loadMessagesFromJsonRepresentation)(
1401
+ lastAgentStateMessage.state.messages
1402
+ );
1403
+ }
1404
+ setCoagentStatesWithRef((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
1405
+ [lastAgentStateMessage.agentName]: {
1406
+ name: lastAgentStateMessage.agentName,
1407
+ state: lastAgentStateMessage.state,
1408
+ running: lastAgentStateMessage.running,
1409
+ active: lastAgentStateMessage.active,
1410
+ threadId: lastAgentStateMessage.threadId,
1411
+ nodeName: lastAgentStateMessage.nodeName,
1412
+ runId: lastAgentStateMessage.runId
1413
+ }
1414
+ }));
1415
+ if (lastAgentStateMessage.running) {
1416
+ setAgentSession({
1417
+ threadId: lastAgentStateMessage.threadId,
1418
+ agentName: lastAgentStateMessage.agentName,
1419
+ nodeName: lastAgentStateMessage.nodeName
1420
+ });
1421
+ } else {
1422
+ if (agentLock) {
1423
+ setAgentSession({
1424
+ threadId: (0, import_shared6.randomId)(),
1425
+ agentName: agentLock,
1426
+ nodeName: void 0
1427
+ });
1428
+ } else {
1429
+ setAgentSession(null);
1430
+ }
1431
+ }
1432
+ }
1433
+ }
1434
+ if (newMessages.length > 0) {
1435
+ setMessages([...previousMessages, ...newMessages]);
1436
+ }
1437
+ }
1438
+ const finalMessages = constructFinalMessages(syncedMessages, previousMessages, newMessages);
1439
+ let didExecuteAction = false;
1440
+ if (onFunctionCall) {
1441
+ const lastMessages = [];
1442
+ for (let i = finalMessages.length - 1; i >= 0; i--) {
1443
+ const message = finalMessages[i];
1444
+ if (message.isActionExecutionMessage() && message.status.code !== import_runtime_client_gql6.MessageStatusCode.Pending) {
1445
+ lastMessages.unshift(message);
1446
+ } else {
1447
+ break;
1448
+ }
1449
+ }
1450
+ for (const message of lastMessages) {
1451
+ setMessages(finalMessages);
1452
+ const action = actions.find((action2) => action2.name === message.name);
1453
+ if (action) {
1454
+ followUp = action.followUp;
1455
+ let result;
1456
+ let error = null;
1457
+ try {
1458
+ result = yield Promise.race([
1459
+ onFunctionCall({
1460
+ messages: previousMessages,
1461
+ name: message.name,
1462
+ args: message.arguments
1463
+ }),
1464
+ new Promise(
1465
+ (resolve) => {
1466
+ var _a2;
1467
+ return (_a2 = chatAbortControllerRef.current) == null ? void 0 : _a2.signal.addEventListener(
1468
+ "abort",
1469
+ () => resolve("Operation was aborted by the user")
1470
+ );
1471
+ }
1472
+ ),
1473
+ // if the user stopped generation, we also abort consecutive actions
1474
+ new Promise((resolve) => {
1475
+ var _a2;
1476
+ if ((_a2 = chatAbortControllerRef.current) == null ? void 0 : _a2.signal.aborted) {
1477
+ resolve("Operation was aborted by the user");
1478
+ }
1479
+ })
1480
+ ]);
1481
+ } catch (e) {
1482
+ error = e;
1483
+ addErrorToast([error]);
1484
+ result = `Failed to execute action ${message.name}. ${error.message}`;
1485
+ console.error(`Failed to execute action ${message.name}: ${error}`);
1486
+ }
1487
+ didExecuteAction = true;
1488
+ const messageIndex = finalMessages.findIndex((msg) => msg.id === message.id);
1489
+ finalMessages.splice(
1490
+ messageIndex + 1,
1491
+ 0,
1492
+ new import_runtime_client_gql6.ResultMessage({
1493
+ id: "result-" + message.id,
1494
+ result: import_runtime_client_gql6.ResultMessage.encodeResult(
1495
+ error ? {
1496
+ content: result,
1497
+ error: JSON.parse(
1498
+ JSON.stringify(error, Object.getOwnPropertyNames(error))
1499
+ )
1500
+ } : result
1501
+ ),
1502
+ actionExecutionId: message.id,
1503
+ actionName: message.name
1504
+ })
1505
+ );
1506
+ }
1507
+ }
1508
+ setMessages(finalMessages);
1509
+ }
1510
+ if (
1511
+ // if followUp is not explicitly false
1512
+ followUp !== false && // and we executed an action
1513
+ (didExecuteAction || // the last message is a server side result
1514
+ !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage()) && // the user did not stop generation
1515
+ !((_j = chatAbortControllerRef.current) == null ? void 0 : _j.signal.aborted)
1516
+ ) {
1517
+ yield new Promise((resolve) => setTimeout(resolve, 10));
1518
+ return yield runChatCompletionRef.current(finalMessages);
1519
+ } else if ((_k = chatAbortControllerRef.current) == null ? void 0 : _k.signal.aborted) {
1520
+ const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {
1521
+ if (message.isActionExecutionMessage()) {
1522
+ return finalMessages.find(
1523
+ (msg, resultIndex) => msg.isResultMessage() && msg.actionExecutionId === message.id && resultIndex === actionExecutionIndex + 1
1524
+ );
1525
+ }
1526
+ return true;
1527
+ });
1528
+ const repairedMessageIds = repairedMessages.map((message) => message.id);
1529
+ setMessages(repairedMessages);
1530
+ if ((_l = agentSessionRef.current) == null ? void 0 : _l.nodeName) {
1531
+ setAgentSession({
1532
+ threadId: agentSessionRef.current.threadId,
1533
+ agentName: agentSessionRef.current.agentName,
1534
+ nodeName: "__end__"
1535
+ });
1536
+ }
1537
+ return newMessages.filter((message) => repairedMessageIds.includes(message.id));
1538
+ } else {
1539
+ return newMessages.slice();
1540
+ }
1541
+ } finally {
1542
+ setIsLoading(false);
1543
+ }
1544
+ }),
1545
+ [
1546
+ messages,
1547
+ setMessages,
1548
+ makeSystemMessageCallback,
1549
+ copilotConfig,
1550
+ setIsLoading,
1551
+ initialMessages,
1552
+ isLoading,
1553
+ actions,
1554
+ onFunctionCall,
1555
+ onCoAgentStateRender,
1556
+ setCoagentStatesWithRef,
1557
+ coagentStatesRef,
1558
+ agentSession,
1559
+ setAgentSession
1560
+ ]
1561
+ );
1562
+ runChatCompletionRef.current = runChatCompletion;
1563
+ const runChatCompletionAndHandleFunctionCall = useAsyncCallback(
1564
+ (messages2) => __async(this, null, function* () {
1565
+ yield runChatCompletionRef.current(messages2);
1566
+ }),
1567
+ [messages]
1568
+ );
1569
+ const append = useAsyncCallback(
1570
+ (message, options2) => __async(this, null, function* () {
1571
+ var _a;
1572
+ if (isLoading) {
1573
+ return;
1574
+ }
1575
+ const newMessages = [...messages, message];
1576
+ setMessages(newMessages);
1577
+ const followUp = (_a = options2 == null ? void 0 : options2.followUp) != null ? _a : true;
1578
+ if (followUp) {
1579
+ return runChatCompletionAndHandleFunctionCall(newMessages);
1580
+ }
1581
+ }),
1582
+ [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
1583
+ );
1584
+ const reload = useAsyncCallback(() => __async(this, null, function* () {
1585
+ if (isLoading || messages.length === 0) {
1586
+ return;
1587
+ }
1588
+ let newMessages = [...messages];
1589
+ const lastMessage = messages[messages.length - 1];
1590
+ if (lastMessage.isTextMessage() && lastMessage.role === "assistant") {
1591
+ newMessages = newMessages.slice(0, -1);
1592
+ }
1593
+ setMessages(newMessages);
1594
+ return runChatCompletionAndHandleFunctionCall(newMessages);
1595
+ }), [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);
1596
+ const stop = () => {
1597
+ var _a;
1598
+ (_a = chatAbortControllerRef.current) == null ? void 0 : _a.abort("Stop was called");
1599
+ };
1600
+ return {
1601
+ append,
1602
+ reload,
1603
+ stop,
1604
+ runChatCompletion: () => runChatCompletionRef.current(messages)
1605
+ };
1606
+ }
1607
+ function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
1608
+ const finalMessages = syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];
1609
+ if (syncedMessages.length > 0) {
1610
+ const messagesWithAgentState = [...previousMessages, ...newMessages];
1611
+ let previousMessageId = void 0;
1612
+ for (const message of messagesWithAgentState) {
1613
+ if (message.isAgentStateMessage()) {
1614
+ const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);
1615
+ if (index !== -1) {
1616
+ finalMessages.splice(index + 1, 0, message);
1617
+ }
1618
+ }
1619
+ previousMessageId = message.id;
1620
+ }
1621
+ }
1622
+ return finalMessages;
1623
+ }
1624
+
1625
+ // src/hooks/use-copilot-chat.ts
1626
+ function useCopilotChat(_a = {}) {
1627
+ var _b = _a, {
1628
+ makeSystemMessage: makeSystemMessage2
1629
+ } = _b, options = __objRest(_b, [
1630
+ "makeSystemMessage"
1631
+ ]);
1632
+ const {
1633
+ getContextString,
1634
+ getFunctionCallHandler,
1635
+ copilotApiConfig,
1636
+ isLoading,
1637
+ setIsLoading,
1638
+ chatInstructions,
1639
+ actions,
1640
+ coagentStatesRef,
1641
+ setCoagentStatesWithRef,
1642
+ coAgentStateRenders,
1643
+ agentSession,
1644
+ setAgentSession,
1645
+ forwardedParameters,
1646
+ agentLock,
1647
+ threadId,
1648
+ setThreadId,
1649
+ runId,
1650
+ setRunId,
1651
+ chatAbortControllerRef,
1652
+ extensions,
1653
+ setExtensions
1654
+ } = useCopilotContext();
1655
+ const { messages, setMessages } = useCopilotMessagesContext();
1656
+ const latestGetContextString = useUpdatedRef(getContextString);
1657
+ const deleteMessage = (0, import_react12.useCallback)(
1658
+ (messageId) => {
1659
+ setMessages((prev) => prev.filter((message) => message.id !== messageId));
1660
+ },
1661
+ [setMessages]
1662
+ );
1663
+ const makeSystemMessageCallback = (0, import_react12.useCallback)(() => {
1664
+ const systemMessageMaker = makeSystemMessage2 || defaultSystemMessage;
1665
+ const contextString = latestGetContextString.current([], defaultCopilotContextCategories);
1666
+ return new import_runtime_client_gql7.TextMessage({
1667
+ content: systemMessageMaker(contextString, chatInstructions),
1668
+ role: import_runtime_client_gql7.Role.System
1669
+ });
1670
+ }, [getContextString, makeSystemMessage2, chatInstructions]);
1671
+ const onCoAgentStateRender = useAsyncCallback(
1672
+ (args) => __async(this, null, function* () {
1673
+ var _a2;
1674
+ const { name, nodeName, state } = args;
1675
+ let action = Object.values(coAgentStateRenders).find(
1676
+ (action2) => action2.name === name && action2.nodeName === nodeName
1677
+ );
1678
+ if (!action) {
1679
+ action = Object.values(coAgentStateRenders).find(
1680
+ (action2) => action2.name === name && !action2.nodeName
1681
+ );
1682
+ }
1683
+ if (action) {
1684
+ yield (_a2 = action.handler) == null ? void 0 : _a2.call(action, { state, nodeName });
1685
+ }
1686
+ }),
1687
+ [coAgentStateRenders]
1688
+ );
1689
+ const { append, reload, stop, runChatCompletion } = useChat(__spreadProps(__spreadValues({}, options), {
1690
+ actions: Object.values(actions),
1691
+ copilotConfig: copilotApiConfig,
1692
+ initialMessages: options.initialMessages || [],
1693
+ onFunctionCall: getFunctionCallHandler(),
1694
+ onCoAgentStateRender,
1695
+ messages,
1696
+ setMessages,
1697
+ makeSystemMessageCallback,
1698
+ isLoading,
1699
+ setIsLoading,
1700
+ coagentStatesRef,
1701
+ setCoagentStatesWithRef,
1702
+ agentSession,
1703
+ setAgentSession,
1704
+ forwardedParameters,
1705
+ threadId,
1706
+ setThreadId,
1707
+ runId,
1708
+ setRunId,
1709
+ chatAbortControllerRef,
1710
+ agentLock,
1711
+ extensions,
1712
+ setExtensions
1713
+ }));
1714
+ const latestAppend = useUpdatedRef(append);
1715
+ const latestAppendFunc = useAsyncCallback(
1716
+ (message, options2) => __async(this, null, function* () {
1717
+ return yield latestAppend.current(message, options2);
1718
+ }),
1719
+ [latestAppend]
1720
+ );
1721
+ const latestReload = useUpdatedRef(reload);
1722
+ const latestReloadFunc = useAsyncCallback(() => __async(this, null, function* () {
1723
+ return yield latestReload.current();
1724
+ }), [latestReload]);
1725
+ const latestStop = useUpdatedRef(stop);
1726
+ const latestStopFunc = (0, import_react12.useCallback)(() => {
1727
+ return latestStop.current();
1728
+ }, [latestStop]);
1729
+ const latestDelete = useUpdatedRef(deleteMessage);
1730
+ const latestDeleteFunc = (0, import_react12.useCallback)(
1731
+ (messageId) => {
1732
+ return latestDelete.current(messageId);
1733
+ },
1734
+ [latestDelete]
1735
+ );
1736
+ const latestSetMessages = useUpdatedRef(setMessages);
1737
+ const latestSetMessagesFunc = (0, import_react12.useCallback)(
1738
+ (messages2) => {
1739
+ return latestSetMessages.current(messages2);
1740
+ },
1741
+ [latestSetMessages]
1742
+ );
1743
+ const latestRunChatCompletion = useUpdatedRef(runChatCompletion);
1744
+ const latestRunChatCompletionFunc = useAsyncCallback(() => __async(this, null, function* () {
1745
+ return yield latestRunChatCompletion.current();
1746
+ }), [latestRunChatCompletion]);
1747
+ const reset = (0, import_react12.useCallback)(() => {
1748
+ latestStopFunc();
1749
+ setMessages([]);
1750
+ setRunId(null);
1751
+ setCoagentStatesWithRef({});
1752
+ let initialAgentSession = null;
1753
+ if (agentLock) {
1754
+ initialAgentSession = {
1755
+ agentName: agentLock
1756
+ };
1757
+ }
1758
+ setAgentSession(initialAgentSession);
1759
+ }, [
1760
+ latestStopFunc,
1761
+ setMessages,
1762
+ setThreadId,
1763
+ setCoagentStatesWithRef,
1764
+ setAgentSession,
1765
+ agentLock
1766
+ ]);
1767
+ const latestReset = useUpdatedRef(reset);
1768
+ const latestResetFunc = (0, import_react12.useCallback)(() => {
1769
+ return latestReset.current();
1770
+ }, [latestReset]);
1771
+ return {
1772
+ visibleMessages: messages,
1773
+ appendMessage: latestAppendFunc,
1774
+ setMessages: latestSetMessagesFunc,
1775
+ reloadMessages: latestReloadFunc,
1776
+ stopGeneration: latestStopFunc,
1777
+ reset: latestResetFunc,
1778
+ deleteMessage: latestDeleteFunc,
1779
+ runChatCompletion: latestRunChatCompletionFunc,
1780
+ isLoading
1781
+ };
1782
+ }
1783
+ function useUpdatedRef(value) {
1784
+ const ref = (0, import_react12.useRef)(value);
1785
+ (0, import_react12.useEffect)(() => {
1786
+ ref.current = value;
1787
+ }, [value]);
1788
+ return ref;
1789
+ }
1790
+ function defaultSystemMessage(contextString, additionalInstructions) {
1791
+ return `
1792
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
1793
+
1794
+ 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.
1795
+ Always be polite and respectful, and prefer brevity over verbosity.
1796
+
1797
+ The user has provided you with the following context:
1798
+ \`\`\`
1799
+ ${contextString}
1800
+ \`\`\`
1801
+
1802
+ 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.
1803
+
1804
+ Please assist them as best you can.
1805
+
1806
+ 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.
1807
+
1808
+ If you would like to call a function, call it without saying anything else.
1809
+ In case of a function error:
1810
+ - If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.
1811
+ - If the error's source is unclear or seems unrelated to your input, do not attempt further retries.
1812
+ ` + (additionalInstructions ? `
1813
+
1814
+ ${additionalInstructions}` : "");
1815
+ }
1816
+
1817
+ // src/hooks/use-copilot-action.ts
1818
+ var import_shared7 = require("@copilotkit/shared");
1819
+ var import_react13 = require("react");
1820
+ function useCopilotAction(action, dependencies) {
1821
+ const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();
1822
+ const idRef = (0, import_react13.useRef)((0, import_shared7.randomId)());
1823
+ const renderAndWaitRef = (0, import_react13.useRef)(null);
1824
+ action = __spreadValues({}, action);
1825
+ if (
1826
+ // renderAndWaitForResponse is not available for catch all actions
1827
+ isFrontendAction(action) && // check if renderAndWaitForResponse is set
1828
+ (action.renderAndWait || action.renderAndWaitForResponse)
1829
+ ) {
1830
+ const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;
1831
+ action.renderAndWait = void 0;
1832
+ action.renderAndWaitForResponse = void 0;
1833
+ action.handler = useAsyncCallback(() => __async(this, null, function* () {
1834
+ let resolve;
1835
+ let reject;
1836
+ const promise = new Promise((resolvePromise, rejectPromise) => {
1837
+ resolve = resolvePromise;
1838
+ reject = rejectPromise;
1839
+ });
1840
+ renderAndWaitRef.current = { promise, resolve, reject };
1841
+ return yield promise;
1842
+ }), []);
1843
+ action.render = (props) => {
1844
+ let status = props.status;
1845
+ if (props.status === "executing" && !renderAndWaitRef.current) {
1846
+ status = "inProgress";
1847
+ }
1848
+ const waitProps = {
1849
+ status,
1850
+ args: props.args,
1851
+ result: props.result,
1852
+ handler: status === "executing" ? renderAndWaitRef.current.resolve : void 0,
1853
+ respond: status === "executing" ? renderAndWaitRef.current.resolve : void 0
1854
+ };
1855
+ const isNoArgsRenderWait = (_fn) => {
1856
+ var _a;
1857
+ return ((_a = action.parameters) == null ? void 0 : _a.length) === 0;
1858
+ };
1859
+ if (renderAndWait) {
1860
+ if (isNoArgsRenderWait(renderAndWait)) {
1861
+ return renderAndWait(waitProps);
1862
+ } else {
1863
+ return renderAndWait(waitProps);
1864
+ }
1865
+ }
1866
+ return (0, import_react13.createElement)(import_react13.Fragment);
1867
+ };
1868
+ }
1869
+ if (dependencies === void 0) {
1870
+ if (actions[idRef.current]) {
1871
+ if (isFrontendAction(action)) {
1872
+ actions[idRef.current].handler = action.handler;
1873
+ }
1874
+ if (typeof action.render === "function") {
1875
+ if (chatComponentsCache.current !== null) {
1876
+ chatComponentsCache.current.actions[action.name] = action.render;
1877
+ }
1878
+ }
1879
+ }
1880
+ }
1881
+ (0, import_react13.useEffect)(() => {
1882
+ setAction(idRef.current, action);
1883
+ if (chatComponentsCache.current !== null && action.render !== void 0) {
1884
+ chatComponentsCache.current.actions[action.name] = action.render;
1885
+ }
1886
+ return () => {
1887
+ removeAction(idRef.current);
1888
+ };
1889
+ }, [
1890
+ setAction,
1891
+ removeAction,
1892
+ isFrontendAction(action) ? action.description : void 0,
1893
+ action.name,
1894
+ isFrontendAction(action) ? action.disabled : void 0,
1895
+ isFrontendAction(action) ? action.available : void 0,
1896
+ // This should be faster than deep equality checking
1897
+ // In addition, all major JS engines guarantee the order of object keys
1898
+ JSON.stringify(isFrontendAction(action) ? action.parameters : []),
1899
+ // include render only if it's a string
1900
+ typeof action.render === "string" ? action.render : void 0,
1901
+ // dependencies set by the developer
1902
+ ...dependencies || []
1903
+ ]);
1904
+ }
1905
+ function isFrontendAction(action) {
1906
+ return action.name !== "*";
1907
+ }
1908
+
1909
+ // src/hooks/use-coagent-state-render.ts
1910
+ var import_react14 = require("react");
1911
+ var import_shared8 = require("@copilotkit/shared");
1912
+ function useCoAgentStateRender(action, dependencies) {
1913
+ const {
1914
+ setCoAgentStateRender,
1915
+ removeCoAgentStateRender,
1916
+ coAgentStateRenders,
1917
+ chatComponentsCache,
1918
+ availableAgents
1919
+ } = (0, import_react14.useContext)(CopilotContext);
1920
+ const idRef = (0, import_react14.useRef)((0, import_shared8.randomId)());
1921
+ const { addToast } = useToast();
1922
+ (0, import_react14.useEffect)(() => {
1923
+ if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === action.name)) {
1924
+ const message = `(useCoAgentStateRender): Agent "${action.name}" not found. Make sure the agent exists and is properly configured.`;
1925
+ console.warn(message);
1926
+ addToast({ type: "warning", message });
1927
+ }
1928
+ }, [availableAgents]);
1929
+ const key = `${action.name}-${action.nodeName || "global"}`;
1930
+ if (dependencies === void 0) {
1931
+ if (coAgentStateRenders[idRef.current]) {
1932
+ coAgentStateRenders[idRef.current].handler = action.handler;
1933
+ if (typeof action.render === "function") {
1934
+ if (chatComponentsCache.current !== null) {
1935
+ chatComponentsCache.current.coAgentStateRenders[key] = action.render;
1936
+ }
1937
+ }
1938
+ }
1939
+ }
1940
+ (0, import_react14.useEffect)(() => {
1941
+ setCoAgentStateRender(idRef.current, action);
1942
+ if (chatComponentsCache.current !== null && action.render !== void 0) {
1943
+ chatComponentsCache.current.coAgentStateRenders[key] = action.render;
1944
+ }
1945
+ return () => {
1946
+ removeCoAgentStateRender(idRef.current);
1947
+ };
1948
+ }, [
1949
+ setCoAgentStateRender,
1950
+ removeCoAgentStateRender,
1951
+ action.name,
1952
+ // include render only if it's a string
1953
+ typeof action.render === "string" ? action.render : void 0,
1954
+ // dependencies set by the developer
1955
+ ...dependencies || []
1956
+ ]);
1957
+ }
1958
+
1959
+ // src/hooks/use-make-copilot-document-readable.ts
1960
+ var import_react15 = require("react");
1961
+ function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
1962
+ const { addDocumentContext, removeDocumentContext } = useCopilotContext();
1963
+ const idRef = (0, import_react15.useRef)();
1964
+ (0, import_react15.useEffect)(() => {
1965
+ const id = addDocumentContext(document, categories);
1966
+ idRef.current = id;
1967
+ return () => {
1968
+ removeDocumentContext(id);
1969
+ };
1970
+ }, [addDocumentContext, removeDocumentContext, ...dependencies]);
1971
+ return idRef.current;
1972
+ }
1973
+
1974
+ // src/hooks/use-copilot-readable.ts
1975
+ var import_react16 = require("react");
1976
+ function convertToJSON(description, value) {
1977
+ return `${description}: ${typeof value === "string" ? value : JSON.stringify(value)}`;
1978
+ }
1979
+ function useCopilotReadable({ description, value, parentId, categories, convert }, dependencies) {
1980
+ const { addContext, removeContext } = useCopilotContext();
1981
+ const idRef = (0, import_react16.useRef)();
1982
+ convert = convert || convertToJSON;
1983
+ const information = convert(description, value);
1984
+ (0, import_react16.useEffect)(() => {
1985
+ const id = addContext(information, parentId, categories);
1986
+ idRef.current = id;
1987
+ return () => {
1988
+ removeContext(id);
1989
+ };
1990
+ }, [information, parentId, addContext, removeContext, ...dependencies || []]);
1991
+ return idRef.current;
1992
+ }
1993
+
1994
+ // src/hooks/use-coagent.ts
1995
+ var import_react17 = require("react");
1996
+ function useCoAgent(options) {
1997
+ const generalContext = useCopilotContext();
1998
+ const { availableAgents } = generalContext;
1999
+ const { addToast } = useToast();
2000
+ const isExternalStateManagement = (options2) => {
2001
+ return "state" in options2 && "setState" in options2;
2002
+ };
2003
+ const { name } = options;
2004
+ (0, import_react17.useEffect)(() => {
2005
+ if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === name)) {
2006
+ const message = `(useCoAgent): Agent "${name}" not found. Make sure the agent exists and is properly configured.`;
2007
+ console.warn(message);
2008
+ addToast({ type: "warning", message });
2009
+ }
2010
+ }, [availableAgents]);
2011
+ const isInternalStateManagementWithInitial = (options2) => {
2012
+ return "initialState" in options2;
2013
+ };
2014
+ const messagesContext = useCopilotMessagesContext();
2015
+ const context = __spreadValues(__spreadValues({}, generalContext), messagesContext);
2016
+ const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } = context;
2017
+ const { appendMessage, runChatCompletion } = useCopilotChat();
2018
+ const getCoagentState = (coagentStates2, name2) => {
2019
+ if (coagentStates2[name2]) {
2020
+ return coagentStates2[name2];
2021
+ } else {
2022
+ return {
2023
+ name: name2,
2024
+ state: isInternalStateManagementWithInitial(options) ? options.initialState : {},
2025
+ running: false,
2026
+ active: false,
2027
+ threadId: void 0,
2028
+ nodeName: void 0,
2029
+ runId: void 0
2030
+ };
2031
+ }
2032
+ };
2033
+ const runtimeClient = useCopilotRuntimeClient({
2034
+ url: copilotApiConfig.chatApiEndpoint,
2035
+ publicApiKey: copilotApiConfig.publicApiKey,
2036
+ credentials: copilotApiConfig.credentials
2037
+ });
2038
+ const setState = (newState) => {
2039
+ let coagentState2 = getCoagentState(coagentStatesRef.current || {}, name);
2040
+ const updatedState = typeof newState === "function" ? newState(coagentState2.state) : newState;
2041
+ setCoagentStatesWithRef(__spreadProps(__spreadValues({}, coagentStatesRef.current), {
2042
+ [name]: __spreadProps(__spreadValues({}, coagentState2), {
2043
+ state: updatedState
2044
+ })
2045
+ }));
2046
+ };
2047
+ (0, import_react17.useEffect)(() => {
2048
+ const fetchAgentState = () => __async(this, null, function* () {
2049
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2050
+ const result = yield runtimeClient.loadAgentState({
2051
+ threadId,
2052
+ agentName: name
2053
+ });
2054
+ if (((_b = (_a = result.data) == null ? void 0 : _a.loadAgentState) == null ? void 0 : _b.threadExists) && ((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.state) && ((_f = (_e = result.data) == null ? void 0 : _e.loadAgentState) == null ? void 0 : _f.state) != "{}") {
2055
+ const fetchedState = JSON.parse((_h = (_g = result.data) == null ? void 0 : _g.loadAgentState) == null ? void 0 : _h.state);
2056
+ isExternalStateManagement(options) ? options.setState(fetchedState) : setState(fetchedState);
2057
+ }
2058
+ });
2059
+ void fetchAgentState();
2060
+ }, [threadId]);
2061
+ const coagentState = getCoagentState(coagentStates, name);
2062
+ (0, import_react17.useEffect)(() => {
2063
+ if (isExternalStateManagement(options)) {
2064
+ setState(options.state);
2065
+ } else if (coagentStates[name] === void 0) {
2066
+ setState(options.initialState === void 0 ? {} : options.initialState);
2067
+ }
2068
+ }, [
2069
+ isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
2070
+ // reset initialstate on reset
2071
+ coagentStates[name] === void 0
2072
+ ]);
2073
+ const runAgentCallback = useAsyncCallback(
2074
+ (hint) => __async(this, null, function* () {
2075
+ yield runAgent(name, context, appendMessage, runChatCompletion, hint);
2076
+ }),
2077
+ [name, context, appendMessage, runChatCompletion]
2078
+ );
2079
+ return {
2080
+ name,
2081
+ nodeName: coagentState.nodeName,
2082
+ threadId: coagentState.threadId,
2083
+ running: coagentState.running,
2084
+ state: coagentState.state,
2085
+ setState: isExternalStateManagement(options) ? options.setState : setState,
2086
+ start: () => startAgent(name, context),
2087
+ stop: () => stopAgent(name, context),
2088
+ run: runAgentCallback
2089
+ };
2090
+ }
2091
+ function startAgent(name, context) {
2092
+ const { setAgentSession } = context;
2093
+ setAgentSession({
2094
+ agentName: name
2095
+ });
2096
+ }
2097
+ function stopAgent(name, context) {
2098
+ const { agentSession, setAgentSession } = context;
2099
+ if (agentSession && agentSession.agentName === name) {
2100
+ setAgentSession(null);
2101
+ context.setCoagentStates((prevAgentStates) => {
2102
+ return __spreadProps(__spreadValues({}, prevAgentStates), {
2103
+ [name]: __spreadProps(__spreadValues({}, prevAgentStates[name]), {
2104
+ running: false,
2105
+ active: false,
2106
+ threadId: void 0,
2107
+ nodeName: void 0,
2108
+ runId: void 0
2109
+ })
2110
+ });
2111
+ });
2112
+ } else {
2113
+ console.warn(`No agent session found for ${name}`);
2114
+ }
2115
+ }
2116
+ function runAgent(name, context, appendMessage, runChatCompletion, hint) {
2117
+ return __async(this, null, function* () {
2118
+ var _a, _b;
2119
+ const { agentSession, setAgentSession } = context;
2120
+ if (!agentSession || agentSession.agentName !== name) {
2121
+ setAgentSession({
2122
+ agentName: name
2123
+ });
2124
+ }
2125
+ let previousState = null;
2126
+ for (let i = context.messages.length - 1; i >= 0; i--) {
2127
+ const message = context.messages[i];
2128
+ if (message.isAgentStateMessage() && message.agentName === name) {
2129
+ previousState = message.state;
2130
+ }
2131
+ }
2132
+ let state = ((_b = (_a = context.coagentStatesRef.current) == null ? void 0 : _a[name]) == null ? void 0 : _b.state) || {};
2133
+ if (hint) {
2134
+ const hintMessage = hint({ previousState, currentState: state });
2135
+ if (hintMessage) {
2136
+ yield appendMessage(hintMessage);
2137
+ } else {
2138
+ yield runChatCompletion();
2139
+ }
2140
+ } else {
2141
+ yield runChatCompletion();
2142
+ }
2143
+ });
2144
+ }
2145
+
2146
+ // src/hooks/use-copilot-authenticated-action.ts
2147
+ var import_react18 = require("react");
2148
+ var import_react19 = __toESM(require("react"));
2149
+ function useCopilotAuthenticatedAction(action, dependencies) {
2150
+ const { authConfig, authStates, setAuthStates } = useCopilotContext();
2151
+ const pendingActionRef = (0, import_react18.useRef)(null);
2152
+ const executeAction = (0, import_react18.useCallback)(
2153
+ (props) => {
2154
+ if (typeof action.render === "function") {
2155
+ return action.render(props);
2156
+ }
2157
+ return action.render || import_react19.default.createElement(import_react18.Fragment);
2158
+ },
2159
+ [action]
2160
+ );
2161
+ const wrappedRender = (0, import_react18.useCallback)(
2162
+ (props) => {
2163
+ const isAuthenticated = Object.values(authStates || {}).some(
2164
+ (state) => state.status === "authenticated"
2165
+ );
2166
+ if (!isAuthenticated) {
2167
+ pendingActionRef.current = props;
2168
+ return (authConfig == null ? void 0 : authConfig.SignInComponent) ? import_react19.default.createElement(authConfig.SignInComponent, {
2169
+ onSignInComplete: (authState) => {
2170
+ setAuthStates == null ? void 0 : setAuthStates((prev) => __spreadProps(__spreadValues({}, prev), { [action.name]: authState }));
2171
+ if (pendingActionRef.current) {
2172
+ executeAction(pendingActionRef.current);
2173
+ pendingActionRef.current = null;
2174
+ }
2175
+ }
2176
+ }) : import_react19.default.createElement(import_react18.Fragment);
2177
+ }
2178
+ return executeAction(props);
2179
+ },
2180
+ [action, authStates, setAuthStates]
2181
+ );
2182
+ useCopilotAction(
2183
+ __spreadProps(__spreadValues({}, action), {
2184
+ render: wrappedRender
2185
+ }),
2186
+ dependencies
2187
+ );
2188
+ }
2189
+
2190
+ // src/lib/copilot-task.ts
2191
+ var import_runtime_client_gql8 = require("@copilotkit/runtime-client-gql");
2192
+ var CopilotTask = class {
2193
+ constructor(config) {
2194
+ this.instructions = config.instructions;
2195
+ this.actions = config.actions || [];
2196
+ this.includeCopilotReadable = config.includeCopilotReadable !== false;
2197
+ this.includeCopilotActions = config.includeCopilotActions !== false;
2198
+ this.forwardedParameters = config.forwardedParameters;
2199
+ }
2200
+ /**
2201
+ * Run the task.
2202
+ * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.
2203
+ * @param data The data to use for the task.
2204
+ */
2205
+ run(context, data) {
2206
+ return __async(this, null, function* () {
2207
+ var _a, _b, _c;
2208
+ const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
2209
+ for (const fn of this.actions) {
2210
+ actions[fn.name] = fn;
2211
+ }
2212
+ let contextString = "";
2213
+ if (data) {
2214
+ contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
2215
+ }
2216
+ if (this.includeCopilotReadable) {
2217
+ contextString += context.getContextString([], defaultCopilotContextCategories);
2218
+ }
2219
+ const systemMessage = new import_runtime_client_gql8.TextMessage({
2220
+ content: taskSystemMessage(contextString, this.instructions),
2221
+ role: import_runtime_client_gql8.Role.System
2222
+ });
2223
+ const messages = [systemMessage];
2224
+ const runtimeClient = new import_runtime_client_gql8.CopilotRuntimeClient({
2225
+ url: context.copilotApiConfig.chatApiEndpoint,
2226
+ publicApiKey: context.copilotApiConfig.publicApiKey,
2227
+ headers: context.copilotApiConfig.headers,
2228
+ credentials: context.copilotApiConfig.credentials
2229
+ });
2230
+ const response = yield runtimeClient.generateCopilotResponse({
2231
+ data: {
2232
+ frontend: {
2233
+ actions: processActionsForRuntimeRequest(Object.values(actions)),
2234
+ url: window.location.href
2235
+ },
2236
+ messages: (0, import_runtime_client_gql8.convertMessagesToGqlInput)((0, import_runtime_client_gql8.filterAgentStateMessages)(messages)),
2237
+ metadata: {
2238
+ requestType: import_runtime_client_gql8.CopilotRequestType.Task
2239
+ },
2240
+ forwardedParameters: __spreadProps(__spreadValues({}, (_a = this.forwardedParameters) != null ? _a : {}), {
2241
+ toolChoice: "required"
2242
+ })
2243
+ },
2244
+ properties: context.copilotApiConfig.properties
2245
+ }).toPromise();
2246
+ const functionCallHandler = context.getFunctionCallHandler(actions);
2247
+ const functionCalls = (0, import_runtime_client_gql8.convertGqlOutputToMessages)(
2248
+ ((_c = (_b = response.data) == null ? void 0 : _b.generateCopilotResponse) == null ? void 0 : _c.messages) || []
2249
+ ).filter((m) => m.isActionExecutionMessage());
2250
+ for (const functionCall of functionCalls) {
2251
+ yield functionCallHandler({
2252
+ messages,
2253
+ name: functionCall.name,
2254
+ args: functionCall.arguments
2255
+ });
2256
+ }
2257
+ });
2258
+ }
2259
+ };
2260
+ function taskSystemMessage(contextString, instructions) {
2261
+ return `
2262
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
2263
+
2264
+ 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.
2265
+ Always be polite and respectful, and prefer brevity over verbosity.
2266
+
2267
+ The user has provided you with the following context:
2268
+ \`\`\`
2269
+ ${contextString}
2270
+ \`\`\`
2271
+
2272
+ They have also provided you with functions you can call to initiate actions on their behalf.
2273
+
2274
+ Please assist them as best you can.
2275
+
2276
+ This is not a conversation, so please do not ask questions. Just call a function without saying anything else.
2277
+
2278
+ The user has given you the following task to complete:
2279
+
2280
+ \`\`\`
2281
+ ${instructions}
2282
+ \`\`\`
2283
+ `;
2284
+ }
2285
+ // Annotate the CommonJS export names for ESM import in node:
2286
+ 0 && (module.exports = {
2287
+ CopilotContext,
2288
+ CopilotKit,
2289
+ CopilotMessagesContext,
2290
+ CopilotTask,
2291
+ defaultCopilotContextCategories,
2292
+ extract,
2293
+ runAgent,
2294
+ shouldShowDevConsole,
2295
+ startAgent,
2296
+ stopAgent,
2297
+ useCoAgent,
2298
+ useCoAgentStateRender,
2299
+ useCopilotAction,
2300
+ useCopilotAuthenticatedAction,
2301
+ useCopilotChat,
2302
+ useCopilotContext,
2303
+ useCopilotMessagesContext,
2304
+ useCopilotReadable,
2305
+ useCopilotRuntimeClient,
2306
+ useMakeCopilotDocumentReadable
2307
+ });
2308
+ //# sourceMappingURL=index.js.map