@copilotkit/react-core 1.5.8 → 1.5.10-next.0

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