@copilotkit/react-core 1.5.1-next.3 → 1.5.1-next.4

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