@copilotkit/react-core 1.10.0-next.2 → 1.10.0-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 (190) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/{chunk-VOMGRGWT.mjs → chunk-2JAX6WE6.mjs} +7 -7
  3. package/dist/chunk-2JAX6WE6.mjs.map +1 -0
  4. package/dist/{chunk-WUORFPJ7.mjs → chunk-2WYJIO6D.mjs} +4 -4
  5. package/dist/chunk-373NOCJI.mjs +79 -0
  6. package/dist/chunk-373NOCJI.mjs.map +1 -0
  7. package/dist/{chunk-XGRBCWK6.mjs → chunk-47GMU44Z.mjs} +4 -1
  8. package/dist/chunk-47GMU44Z.mjs.map +1 -0
  9. package/dist/{chunk-DF4YG4PF.mjs → chunk-57MBVQPX.mjs} +2 -2
  10. package/dist/{chunk-JZQOCH4A.mjs → chunk-5JL5ELUS.mjs} +2 -2
  11. package/dist/{chunk-LNAQ7JG3.mjs → chunk-AC2GVFW6.mjs} +2 -2
  12. package/dist/{chunk-RGKZCCPA.mjs → chunk-AVMA2MCW.mjs} +3 -3
  13. package/dist/chunk-AWFAFFO5.mjs +221 -0
  14. package/dist/chunk-AWFAFFO5.mjs.map +1 -0
  15. package/dist/{chunk-4XVBXDCX.mjs → chunk-BBK7LXZ6.mjs} +5 -5
  16. package/dist/{chunk-YAF2LATQ.mjs → chunk-EFL5OBKN.mjs} +1 -1
  17. package/dist/chunk-EFL5OBKN.mjs.map +1 -0
  18. package/dist/{chunk-4CFY3CON.mjs → chunk-EQQSE6KM.mjs} +2 -2
  19. package/dist/{chunk-JWAXDYOW.mjs → chunk-FAUNHSQU.mjs} +3 -3
  20. package/dist/{chunk-NXCJELW7.mjs → chunk-G7J6NY5J.mjs} +3 -3
  21. package/dist/chunk-ICIK2BSB.mjs +17 -0
  22. package/dist/chunk-ICIK2BSB.mjs.map +1 -0
  23. package/dist/{chunk-PYULBXCD.mjs → chunk-JLQZVKFX.mjs} +4 -4
  24. package/dist/chunk-KDAZGZ24.mjs +1 -0
  25. package/dist/{chunk-OMVNJ7S3.mjs → chunk-L7CWMU4O.mjs} +34 -19
  26. package/dist/chunk-L7CWMU4O.mjs.map +1 -0
  27. package/dist/{chunk-3OQM3NEK.mjs → chunk-N4WEHORG.mjs} +2 -2
  28. package/dist/{chunk-Q6FZZJ5A.mjs → chunk-OL3VRQKU.mjs} +2 -2
  29. package/dist/chunk-PQ5IXT4Z.mjs +18 -0
  30. package/dist/chunk-PQ5IXT4Z.mjs.map +1 -0
  31. package/dist/{chunk-VM7CVIET.mjs → chunk-PRKL7T7P.mjs} +6 -6
  32. package/dist/chunk-PRKL7T7P.mjs.map +1 -0
  33. package/dist/{chunk-KV25ZRMH.mjs → chunk-XIHAYU6C.mjs} +4 -4
  34. package/dist/chunk-XIHAYU6C.mjs.map +1 -0
  35. package/dist/{chunk-SGF6C7I6.mjs → chunk-ZTZJIDRJ.mjs} +9 -14
  36. package/dist/chunk-ZTZJIDRJ.mjs.map +1 -0
  37. package/dist/components/copilot-provider/copilot-messages.js +12 -1
  38. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  39. package/dist/components/copilot-provider/copilot-messages.mjs +4 -4
  40. package/dist/components/copilot-provider/copilotkit-props.d.ts +1 -1
  41. package/dist/components/copilot-provider/copilotkit.d.ts +1 -1
  42. package/dist/components/copilot-provider/copilotkit.js +307 -550
  43. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  44. package/dist/components/copilot-provider/copilotkit.mjs +9 -9
  45. package/dist/components/copilot-provider/index.d.ts +1 -1
  46. package/dist/components/copilot-provider/index.js +307 -550
  47. package/dist/components/copilot-provider/index.js.map +1 -1
  48. package/dist/components/copilot-provider/index.mjs +9 -9
  49. package/dist/components/error-boundary/error-boundary.js +172 -323
  50. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  51. package/dist/components/error-boundary/error-boundary.mjs +4 -4
  52. package/dist/components/error-boundary/error-utils.js.map +1 -1
  53. package/dist/components/error-boundary/error-utils.mjs +2 -2
  54. package/dist/components/index.d.ts +1 -1
  55. package/dist/components/index.js +307 -550
  56. package/dist/components/index.js.map +1 -1
  57. package/dist/components/index.mjs +9 -9
  58. package/dist/components/toast/toast-provider.js.map +1 -1
  59. package/dist/components/toast/toast-provider.mjs +1 -1
  60. package/dist/components/usage-banner.d.ts +8 -3
  61. package/dist/components/usage-banner.js +172 -302
  62. package/dist/components/usage-banner.js.map +1 -1
  63. package/dist/components/usage-banner.mjs +3 -1
  64. package/dist/context/copilot-context.d.ts +1 -1
  65. package/dist/context/copilot-context.js +3 -0
  66. package/dist/context/copilot-context.js.map +1 -1
  67. package/dist/context/copilot-context.mjs +1 -1
  68. package/dist/context/index.d.ts +1 -1
  69. package/dist/context/index.js +3 -0
  70. package/dist/context/index.js.map +1 -1
  71. package/dist/context/index.mjs +1 -1
  72. package/dist/{copilot-context-bd88d30d.d.ts → copilot-context-78fc727c.d.ts} +3 -1
  73. package/dist/hooks/index.d.ts +5 -3
  74. package/dist/hooks/index.js +143 -57
  75. package/dist/hooks/index.js.map +1 -1
  76. package/dist/hooks/index.mjs +32 -24
  77. package/dist/hooks/use-chat.d.ts +1 -1
  78. package/dist/hooks/use-chat.js +12 -1
  79. package/dist/hooks/use-chat.js.map +1 -1
  80. package/dist/hooks/use-chat.mjs +6 -6
  81. package/dist/hooks/use-coagent-state-render.js +3 -0
  82. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  83. package/dist/hooks/use-coagent-state-render.mjs +3 -3
  84. package/dist/hooks/use-coagent.d.ts +1 -1
  85. package/dist/hooks/use-coagent.js +15 -4
  86. package/dist/hooks/use-coagent.js.map +1 -1
  87. package/dist/hooks/use-coagent.mjs +13 -13
  88. package/dist/hooks/use-copilot-action.js +3 -0
  89. package/dist/hooks/use-copilot-action.js.map +1 -1
  90. package/dist/hooks/use-copilot-action.mjs +4 -4
  91. package/dist/hooks/use-copilot-additional-instructions.js +3 -0
  92. package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
  93. package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
  94. package/dist/hooks/use-copilot-authenticated-action.js +3 -0
  95. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  96. package/dist/hooks/use-copilot-authenticated-action.mjs +5 -5
  97. package/dist/hooks/use-copilot-chat-light.d.ts +211 -0
  98. package/dist/hooks/use-copilot-chat-light.js +1770 -0
  99. package/dist/hooks/use-copilot-chat-light.js.map +1 -0
  100. package/dist/hooks/use-copilot-chat-light.mjs +28 -0
  101. package/dist/hooks/use-copilot-chat-light.mjs.map +1 -0
  102. package/dist/hooks/use-copilot-chat.d.ts +9 -81
  103. package/dist/hooks/use-copilot-chat.js +77 -5
  104. package/dist/hooks/use-copilot-chat.js.map +1 -1
  105. package/dist/hooks/use-copilot-chat.mjs +15 -13
  106. package/dist/hooks/use-copilot-chat_internal.d.ts +91 -0
  107. package/dist/hooks/use-copilot-chat_internal.js +1760 -0
  108. package/dist/hooks/use-copilot-chat_internal.js.map +1 -0
  109. package/dist/hooks/use-copilot-chat_internal.mjs +29 -0
  110. package/dist/hooks/use-copilot-chat_internal.mjs.map +1 -0
  111. package/dist/hooks/use-copilot-readable.js +3 -0
  112. package/dist/hooks/use-copilot-readable.js.map +1 -1
  113. package/dist/hooks/use-copilot-readable.mjs +2 -2
  114. package/dist/hooks/use-copilot-runtime-client.js +9 -1
  115. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  116. package/dist/hooks/use-copilot-runtime-client.mjs +3 -3
  117. package/dist/hooks/use-langgraph-interrupt-render.js +3 -0
  118. package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
  119. package/dist/hooks/use-langgraph-interrupt-render.mjs +2 -2
  120. package/dist/hooks/use-langgraph-interrupt.d.ts +1 -1
  121. package/dist/hooks/use-langgraph-interrupt.js +15 -4
  122. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  123. package/dist/hooks/use-langgraph-interrupt.mjs +13 -13
  124. package/dist/hooks/use-make-copilot-document-readable.js +3 -0
  125. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  126. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  127. package/dist/index.d.ts +4 -2
  128. package/dist/index.js +384 -449
  129. package/dist/index.js.map +1 -1
  130. package/dist/index.mjs +34 -26
  131. package/dist/lib/copilot-task.d.ts +1 -1
  132. package/dist/lib/copilot-task.js.map +1 -1
  133. package/dist/lib/copilot-task.mjs +10 -10
  134. package/dist/lib/index.d.ts +1 -1
  135. package/dist/lib/index.js.map +1 -1
  136. package/dist/lib/index.mjs +10 -10
  137. package/dist/types/interrupt-action.d.ts +1 -1
  138. package/dist/utils/dev-console.d.ts +1 -1
  139. package/dist/utils/dev-console.js +9 -1
  140. package/dist/utils/dev-console.js.map +1 -1
  141. package/dist/utils/dev-console.mjs +1 -1
  142. package/dist/utils/extract.d.ts +1 -1
  143. package/dist/utils/extract.js.map +1 -1
  144. package/dist/utils/extract.mjs +9 -9
  145. package/dist/utils/index.d.ts +1 -1
  146. package/dist/utils/index.js +9 -1
  147. package/dist/utils/index.js.map +1 -1
  148. package/dist/utils/index.mjs +9 -9
  149. package/dist/utils/suggestions.d.ts +1 -1
  150. package/dist/utils/suggestions.js.map +1 -1
  151. package/dist/utils/suggestions.mjs +9 -9
  152. package/package.json +3 -3
  153. package/src/components/copilot-provider/copilotkit.tsx +16 -5
  154. package/src/components/error-boundary/error-boundary.tsx +5 -15
  155. package/src/components/toast/toast-provider.tsx +1 -3
  156. package/src/components/usage-banner.tsx +187 -315
  157. package/src/context/copilot-context.tsx +12 -1
  158. package/src/hooks/__tests__/use-coagent-config.test.ts +1 -1
  159. package/src/hooks/index.ts +6 -0
  160. package/src/hooks/use-coagent.ts +1 -1
  161. package/src/hooks/use-copilot-chat-light.ts +219 -0
  162. package/src/hooks/use-copilot-chat.ts +89 -430
  163. package/src/hooks/use-copilot-chat_internal.ts +437 -0
  164. package/src/hooks/use-langgraph-interrupt.ts +1 -1
  165. package/src/utils/dev-console.ts +18 -2
  166. package/dist/chunk-57K2ZJ5F.mjs +0 -348
  167. package/dist/chunk-57K2ZJ5F.mjs.map +0 -1
  168. package/dist/chunk-CQPYJIBH.mjs +0 -1
  169. package/dist/chunk-GFJW4RIM.mjs +0 -9
  170. package/dist/chunk-GFJW4RIM.mjs.map +0 -1
  171. package/dist/chunk-KV25ZRMH.mjs.map +0 -1
  172. package/dist/chunk-OMVNJ7S3.mjs.map +0 -1
  173. package/dist/chunk-SGF6C7I6.mjs.map +0 -1
  174. package/dist/chunk-VM7CVIET.mjs.map +0 -1
  175. package/dist/chunk-VOMGRGWT.mjs.map +0 -1
  176. package/dist/chunk-XGRBCWK6.mjs.map +0 -1
  177. package/dist/chunk-YAF2LATQ.mjs.map +0 -1
  178. /package/dist/{chunk-WUORFPJ7.mjs.map → chunk-2WYJIO6D.mjs.map} +0 -0
  179. /package/dist/{chunk-DF4YG4PF.mjs.map → chunk-57MBVQPX.mjs.map} +0 -0
  180. /package/dist/{chunk-JZQOCH4A.mjs.map → chunk-5JL5ELUS.mjs.map} +0 -0
  181. /package/dist/{chunk-LNAQ7JG3.mjs.map → chunk-AC2GVFW6.mjs.map} +0 -0
  182. /package/dist/{chunk-RGKZCCPA.mjs.map → chunk-AVMA2MCW.mjs.map} +0 -0
  183. /package/dist/{chunk-4XVBXDCX.mjs.map → chunk-BBK7LXZ6.mjs.map} +0 -0
  184. /package/dist/{chunk-4CFY3CON.mjs.map → chunk-EQQSE6KM.mjs.map} +0 -0
  185. /package/dist/{chunk-JWAXDYOW.mjs.map → chunk-FAUNHSQU.mjs.map} +0 -0
  186. /package/dist/{chunk-NXCJELW7.mjs.map → chunk-G7J6NY5J.mjs.map} +0 -0
  187. /package/dist/{chunk-PYULBXCD.mjs.map → chunk-JLQZVKFX.mjs.map} +0 -0
  188. /package/dist/{chunk-CQPYJIBH.mjs.map → chunk-KDAZGZ24.mjs.map} +0 -0
  189. /package/dist/{chunk-3OQM3NEK.mjs.map → chunk-N4WEHORG.mjs.map} +0 -0
  190. /package/dist/{chunk-Q6FZZJ5A.mjs.map → chunk-OL3VRQKU.mjs.map} +0 -0
@@ -0,0 +1,1760 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __objRest = (source, exclude) => {
26
+ var target = {};
27
+ for (var prop in source)
28
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
+ target[prop] = source[prop];
30
+ if (source != null && __getOwnPropSymbols)
31
+ for (var prop of __getOwnPropSymbols(source)) {
32
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
+ target[prop] = source[prop];
34
+ }
35
+ return target;
36
+ };
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, { get: all[name], enumerable: true });
40
+ };
41
+ var __copyProps = (to, from, except, desc) => {
42
+ if (from && typeof from === "object" || typeof from === "function") {
43
+ for (let key of __getOwnPropNames(from))
44
+ if (!__hasOwnProp.call(to, key) && key !== except)
45
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
46
+ }
47
+ return to;
48
+ };
49
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
+ // If the importer is in node compatibility mode or this is not an ESM
51
+ // file that has been converted to a CommonJS file using a Babel-
52
+ // compatible transform (i.e. "__esModule" has not been set), then set
53
+ // "default" to the CommonJS "module.exports" for node compatibility.
54
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
+ mod
56
+ ));
57
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
58
+ var __async = (__this, __arguments, generator) => {
59
+ return new Promise((resolve, reject) => {
60
+ var fulfilled = (value) => {
61
+ try {
62
+ step(generator.next(value));
63
+ } catch (e) {
64
+ reject(e);
65
+ }
66
+ };
67
+ var rejected = (value) => {
68
+ try {
69
+ step(generator.throw(value));
70
+ } catch (e) {
71
+ reject(e);
72
+ }
73
+ };
74
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
75
+ step((generator = generator.apply(__this, __arguments)).next());
76
+ });
77
+ };
78
+
79
+ // src/hooks/use-copilot-chat_internal.ts
80
+ var use_copilot_chat_internal_exports = {};
81
+ __export(use_copilot_chat_internal_exports, {
82
+ defaultSystemMessage: () => defaultSystemMessage,
83
+ useCopilotChat: () => useCopilotChat
84
+ });
85
+ module.exports = __toCommonJS(use_copilot_chat_internal_exports);
86
+ var import_react9 = require("react");
87
+
88
+ // src/context/copilot-context.tsx
89
+ var import_react = __toESM(require("react"));
90
+ var emptyCopilotContext = {
91
+ actions: {},
92
+ setAction: () => {
93
+ },
94
+ removeAction: () => {
95
+ },
96
+ coAgentStateRenders: {},
97
+ setCoAgentStateRender: () => {
98
+ },
99
+ removeCoAgentStateRender: () => {
100
+ },
101
+ chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
102
+ getContextString: (documents, categories) => returnAndThrowInDebug(""),
103
+ addContext: () => "",
104
+ removeContext: () => {
105
+ },
106
+ getAllContext: () => [],
107
+ getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
108
+ })),
109
+ isLoading: false,
110
+ setIsLoading: () => returnAndThrowInDebug(false),
111
+ chatInstructions: "",
112
+ setChatInstructions: () => returnAndThrowInDebug(""),
113
+ additionalInstructions: [],
114
+ setAdditionalInstructions: () => returnAndThrowInDebug([]),
115
+ getDocumentsContext: (categories) => returnAndThrowInDebug([]),
116
+ addDocumentContext: () => returnAndThrowInDebug(""),
117
+ removeDocumentContext: () => {
118
+ },
119
+ runtimeClient: {},
120
+ copilotApiConfig: new class {
121
+ get chatApiEndpoint() {
122
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
123
+ }
124
+ get headers() {
125
+ return {};
126
+ }
127
+ get body() {
128
+ return {};
129
+ }
130
+ }(),
131
+ chatSuggestionConfiguration: {},
132
+ addChatSuggestionConfiguration: () => {
133
+ },
134
+ removeChatSuggestionConfiguration: () => {
135
+ },
136
+ showDevConsole: false,
137
+ coagentStates: {},
138
+ setCoagentStates: () => {
139
+ },
140
+ coagentStatesRef: { current: {} },
141
+ setCoagentStatesWithRef: () => {
142
+ },
143
+ agentSession: null,
144
+ setAgentSession: () => {
145
+ },
146
+ forwardedParameters: {},
147
+ agentLock: null,
148
+ threadId: "",
149
+ setThreadId: () => {
150
+ },
151
+ runId: null,
152
+ setRunId: () => {
153
+ },
154
+ chatAbortControllerRef: { current: null },
155
+ availableAgents: [],
156
+ extensions: {},
157
+ setExtensions: () => {
158
+ },
159
+ langGraphInterruptAction: null,
160
+ setLangGraphInterruptAction: () => null,
161
+ removeLangGraphInterruptAction: () => null,
162
+ onError: void 0,
163
+ suggestions: [],
164
+ bannerError: null,
165
+ setBannerError: () => {
166
+ },
167
+ setSuggestions: () => {
168
+ }
169
+ };
170
+ var CopilotContext = import_react.default.createContext(emptyCopilotContext);
171
+ function useCopilotContext() {
172
+ const context = import_react.default.useContext(CopilotContext);
173
+ if (context === emptyCopilotContext) {
174
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
175
+ }
176
+ return context;
177
+ }
178
+ function returnAndThrowInDebug(_value) {
179
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
180
+ }
181
+
182
+ // src/context/copilot-messages-context.tsx
183
+ var import_react2 = __toESM(require("react"));
184
+ var emptyCopilotContext2 = {
185
+ messages: [],
186
+ setMessages: () => []
187
+ };
188
+ var CopilotMessagesContext = import_react2.default.createContext(emptyCopilotContext2);
189
+ function useCopilotMessagesContext() {
190
+ const context = import_react2.default.useContext(CopilotMessagesContext);
191
+ if (context === emptyCopilotContext2) {
192
+ throw new Error(
193
+ "A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`"
194
+ );
195
+ }
196
+ return context;
197
+ }
198
+
199
+ // src/hooks/use-chat.ts
200
+ var import_react6 = require("react");
201
+ var import_react_dom = require("react-dom");
202
+ var import_shared4 = require("@copilotkit/shared");
203
+ var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
204
+
205
+ // src/types/frontend-action.ts
206
+ var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
207
+ var import_shared = require("@copilotkit/shared");
208
+ function processActionsForRuntimeRequest(actions) {
209
+ const filteredActions = actions.filter(
210
+ (action) => action.available !== import_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*" && action.available != "frontend" && !action.pairedAction
211
+ ).map((action) => {
212
+ let available = import_runtime_client_gql.ActionInputAvailability.Enabled;
213
+ if (action.disabled) {
214
+ available = import_runtime_client_gql.ActionInputAvailability.Disabled;
215
+ } else if (action.available === "disabled") {
216
+ available = import_runtime_client_gql.ActionInputAvailability.Disabled;
217
+ } else if (action.available === "remote") {
218
+ available = import_runtime_client_gql.ActionInputAvailability.Remote;
219
+ }
220
+ return {
221
+ name: action.name,
222
+ description: action.description || "",
223
+ jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
224
+ available
225
+ };
226
+ });
227
+ return filteredActions;
228
+ }
229
+
230
+ // src/hooks/use-copilot-runtime-client.ts
231
+ var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
232
+
233
+ // src/components/toast/toast-provider.tsx
234
+ var import_react3 = require("react");
235
+ var import_shared2 = require("@copilotkit/shared");
236
+ var import_jsx_runtime = require("react/jsx-runtime");
237
+ var ToastContext = (0, import_react3.createContext)(void 0);
238
+ function useToast() {
239
+ const context = (0, import_react3.useContext)(ToastContext);
240
+ if (!context) {
241
+ throw new Error("useToast must be used within a ToastProvider");
242
+ }
243
+ return context;
244
+ }
245
+
246
+ // src/hooks/use-copilot-runtime-client.ts
247
+ var import_react4 = require("react");
248
+ var import_shared3 = require("@copilotkit/shared");
249
+
250
+ // src/utils/dev-console.ts
251
+ function isLocalhost() {
252
+ if (typeof window === "undefined")
253
+ return false;
254
+ return window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "0.0.0.0";
255
+ }
256
+ function shouldShowDevConsole(showDevConsole) {
257
+ if (showDevConsole !== void 0) {
258
+ return showDevConsole;
259
+ }
260
+ return isLocalhost();
261
+ }
262
+
263
+ // src/hooks/use-copilot-runtime-client.ts
264
+ var useCopilotRuntimeClient = (options) => {
265
+ const { setBannerError } = useToast();
266
+ const _a = options, { showDevConsole, onError } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onError"]);
267
+ const lastStructuredErrorRef = (0, import_react4.useRef)(null);
268
+ const traceUIError = (error, originalError) => __async(void 0, null, function* () {
269
+ if (!onError || !runtimeOptions.publicApiKey)
270
+ return;
271
+ try {
272
+ const errorEvent = {
273
+ type: "error",
274
+ timestamp: Date.now(),
275
+ context: {
276
+ source: "ui",
277
+ request: {
278
+ operation: "runtimeClient",
279
+ url: runtimeOptions.url,
280
+ startTime: Date.now()
281
+ },
282
+ technical: {
283
+ environment: "browser",
284
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
285
+ stackTrace: originalError instanceof Error ? originalError.stack : void 0
286
+ }
287
+ },
288
+ error
289
+ };
290
+ yield onError(errorEvent);
291
+ } catch (error2) {
292
+ console.error("Error in onError handler:", error2);
293
+ }
294
+ });
295
+ const runtimeClient = (0, import_react4.useMemo)(() => {
296
+ return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, runtimeOptions), {
297
+ handleGQLErrors: (error) => {
298
+ var _a2;
299
+ if ((_a2 = error.graphQLErrors) == null ? void 0 : _a2.length) {
300
+ const graphQLErrors = error.graphQLErrors;
301
+ const routeError = (gqlError) => {
302
+ const extensions = gqlError.extensions;
303
+ const visibility = extensions == null ? void 0 : extensions.visibility;
304
+ const isDev = shouldShowDevConsole(showDevConsole != null ? showDevConsole : false);
305
+ if (visibility === import_shared3.ErrorVisibility.SILENT) {
306
+ console.error("CopilotKit Silent Error:", gqlError.message);
307
+ return;
308
+ }
309
+ if (!isDev) {
310
+ console.error("CopilotKit Error (hidden in production):", gqlError.message);
311
+ return;
312
+ }
313
+ const now = Date.now();
314
+ const errorMessage = gqlError.message;
315
+ if (lastStructuredErrorRef.current && lastStructuredErrorRef.current.message === errorMessage && now - lastStructuredErrorRef.current.timestamp < 150) {
316
+ return;
317
+ }
318
+ lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };
319
+ const ckError = createStructuredError(gqlError);
320
+ if (ckError) {
321
+ setBannerError(ckError);
322
+ traceUIError(ckError, gqlError);
323
+ } else {
324
+ const fallbackError = new import_shared3.CopilotKitError({
325
+ message: gqlError.message,
326
+ code: import_shared3.CopilotKitErrorCode.UNKNOWN
327
+ });
328
+ setBannerError(fallbackError);
329
+ traceUIError(fallbackError, gqlError);
330
+ }
331
+ };
332
+ graphQLErrors.forEach(routeError);
333
+ } else {
334
+ const isDev = shouldShowDevConsole(showDevConsole != null ? showDevConsole : false);
335
+ if (!isDev) {
336
+ console.error("CopilotKit Error (hidden in production):", error);
337
+ } else {
338
+ const fallbackError = new import_shared3.CopilotKitError({
339
+ message: (error == null ? void 0 : error.message) || String(error),
340
+ code: import_shared3.CopilotKitErrorCode.UNKNOWN
341
+ });
342
+ setBannerError(fallbackError);
343
+ traceUIError(fallbackError, error);
344
+ }
345
+ }
346
+ },
347
+ handleGQLWarning: (message) => {
348
+ console.warn(message);
349
+ const warningError = new import_shared3.CopilotKitError({
350
+ message,
351
+ code: import_shared3.CopilotKitErrorCode.UNKNOWN
352
+ });
353
+ setBannerError(warningError);
354
+ }
355
+ }));
356
+ }, [runtimeOptions, setBannerError, showDevConsole, onError]);
357
+ return runtimeClient;
358
+ };
359
+ function createStructuredError(gqlError) {
360
+ var _a, _b, _c;
361
+ const extensions = gqlError.extensions;
362
+ const originalError = extensions == null ? void 0 : extensions.originalError;
363
+ const message = (originalError == null ? void 0 : originalError.message) || gqlError.message;
364
+ const code = extensions == null ? void 0 : extensions.code;
365
+ if (code) {
366
+ return new import_shared3.CopilotKitError({ message, code });
367
+ }
368
+ if ((_a = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _a.includes("CopilotApiDiscoveryError")) {
369
+ return new import_shared3.CopilotKitApiDiscoveryError({ message });
370
+ }
371
+ if ((_b = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _b.includes("CopilotKitRemoteEndpointDiscoveryError")) {
372
+ return new import_shared3.CopilotKitRemoteEndpointDiscoveryError({ message });
373
+ }
374
+ if ((_c = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _c.includes("CopilotKitAgentDiscoveryError")) {
375
+ return new import_shared3.CopilotKitAgentDiscoveryError({
376
+ agentName: "",
377
+ availableAgents: []
378
+ });
379
+ }
380
+ return null;
381
+ }
382
+
383
+ // src/components/error-boundary/error-utils.tsx
384
+ var import_react5 = require("react");
385
+
386
+ // src/components/toast/exclamation-mark-icon.tsx
387
+ var import_jsx_runtime2 = require("react/jsx-runtime");
388
+ var ExclamationMarkIcon = ({
389
+ className,
390
+ style
391
+ }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
392
+ "svg",
393
+ {
394
+ xmlns: "http://www.w3.org/2000/svg",
395
+ width: "24",
396
+ height: "24",
397
+ viewBox: "0 0 24 24",
398
+ fill: "none",
399
+ stroke: "currentColor",
400
+ strokeWidth: "2",
401
+ strokeLinecap: "round",
402
+ strokeLinejoin: "round",
403
+ className: `lucide lucide-circle-alert ${className ? className : ""}`,
404
+ style,
405
+ children: [
406
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("circle", { cx: "12", cy: "12", r: "10" }),
407
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12", y1: "8", y2: "12" }),
408
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12.01", y1: "16", y2: "16" })
409
+ ]
410
+ }
411
+ );
412
+
413
+ // src/components/error-boundary/error-utils.tsx
414
+ var import_react_markdown = __toESM(require("react-markdown"));
415
+ var import_jsx_runtime3 = require("react/jsx-runtime");
416
+ function ErrorToast({ errors }) {
417
+ const errorsToRender = errors.map((error, idx) => {
418
+ var _a, _b, _c;
419
+ const originalError = "extensions" in error ? (_a = error.extensions) == null ? void 0 : _a.originalError : {};
420
+ const message = (_b = originalError == null ? void 0 : originalError.message) != null ? _b : error.message;
421
+ const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
422
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
423
+ "div",
424
+ {
425
+ style: {
426
+ marginTop: idx === 0 ? 0 : 10,
427
+ marginBottom: 14
428
+ },
429
+ children: [
430
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
431
+ code && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
432
+ "div",
433
+ {
434
+ style: {
435
+ fontWeight: "600",
436
+ marginBottom: 4
437
+ },
438
+ children: [
439
+ "Copilot Runtime Error:",
440
+ " ",
441
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
442
+ ]
443
+ }
444
+ ),
445
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react_markdown.default, { children: message })
446
+ ]
447
+ },
448
+ idx
449
+ );
450
+ });
451
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
452
+ "div",
453
+ {
454
+ style: {
455
+ fontSize: "13px",
456
+ maxWidth: "600px"
457
+ },
458
+ children: [
459
+ errorsToRender,
460
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
461
+ ]
462
+ }
463
+ );
464
+ }
465
+ function useErrorToast() {
466
+ const { addToast } = useToast();
467
+ return (0, import_react5.useCallback)(
468
+ (error) => {
469
+ const errorId = error.map((err) => {
470
+ var _a, _b;
471
+ const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
472
+ const stack = err.stack || "";
473
+ return btoa(message + stack).slice(0, 32);
474
+ }).join("|");
475
+ addToast({
476
+ type: "error",
477
+ id: errorId,
478
+ // Toast libraries typically dedupe by id
479
+ message: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ErrorToast, { errors: error })
480
+ });
481
+ },
482
+ [addToast]
483
+ );
484
+ }
485
+ function useAsyncCallback(callback, deps) {
486
+ const addErrorToast = useErrorToast();
487
+ return (0, import_react5.useCallback)((...args) => __async(this, null, function* () {
488
+ try {
489
+ return yield callback(...args);
490
+ } catch (error) {
491
+ console.error("Error in async callback:", error);
492
+ addErrorToast([error]);
493
+ throw error;
494
+ }
495
+ }), deps);
496
+ }
497
+
498
+ // src/hooks/use-chat.ts
499
+ function useChat(options) {
500
+ const {
501
+ messages,
502
+ setMessages,
503
+ makeSystemMessageCallback,
504
+ copilotConfig,
505
+ setIsLoading,
506
+ initialMessages,
507
+ isLoading,
508
+ actions,
509
+ onFunctionCall,
510
+ onCoAgentStateRender,
511
+ setCoagentStatesWithRef,
512
+ coagentStatesRef,
513
+ agentSession,
514
+ setAgentSession,
515
+ threadId,
516
+ setThreadId,
517
+ runId,
518
+ setRunId,
519
+ chatAbortControllerRef,
520
+ agentLock,
521
+ extensions,
522
+ setExtensions,
523
+ langGraphInterruptAction,
524
+ setLangGraphInterruptAction
525
+ } = options;
526
+ const runChatCompletionRef = (0, import_react6.useRef)();
527
+ const addErrorToast = useErrorToast();
528
+ const { setBannerError } = useToast();
529
+ const { onError } = useCopilotContext();
530
+ const traceUIError = (error, originalError) => __async(this, null, function* () {
531
+ if (!onError || !(copilotConfig == null ? void 0 : copilotConfig.publicApiKey))
532
+ return;
533
+ try {
534
+ const traceEvent = {
535
+ type: "error",
536
+ timestamp: Date.now(),
537
+ context: {
538
+ source: "ui",
539
+ request: {
540
+ operation: "useChatCompletion",
541
+ url: copilotConfig.chatApiEndpoint,
542
+ startTime: Date.now()
543
+ },
544
+ technical: {
545
+ environment: "browser",
546
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
547
+ stackTrace: originalError instanceof Error ? originalError.stack : void 0
548
+ }
549
+ },
550
+ error
551
+ };
552
+ yield onError(traceEvent);
553
+ } catch (traceError) {
554
+ console.error("Error in use-chat onError handler:", traceError);
555
+ }
556
+ });
557
+ const agentSessionRef = (0, import_react6.useRef)(agentSession);
558
+ agentSessionRef.current = agentSession;
559
+ const runIdRef = (0, import_react6.useRef)(runId);
560
+ runIdRef.current = runId;
561
+ const extensionsRef = (0, import_react6.useRef)(extensions);
562
+ extensionsRef.current = extensions;
563
+ const publicApiKey = copilotConfig.publicApiKey;
564
+ const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared4.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
565
+ const { showDevConsole } = useCopilotContext();
566
+ const runtimeClient = useCopilotRuntimeClient({
567
+ url: copilotConfig.chatApiEndpoint,
568
+ publicApiKey: copilotConfig.publicApiKey,
569
+ headers,
570
+ credentials: copilotConfig.credentials,
571
+ showDevConsole
572
+ });
573
+ const pendingAppendsRef = (0, import_react6.useRef)([]);
574
+ const runChatCompletion = useAsyncCallback(
575
+ (previousMessages) => __async(this, null, function* () {
576
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
577
+ setIsLoading(true);
578
+ const interruptEvent = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event;
579
+ if ((interruptEvent == null ? void 0 : interruptEvent.name) === import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent && (interruptEvent == null ? void 0 : interruptEvent.value) && !(interruptEvent == null ? void 0 : interruptEvent.response) && agentSessionRef.current) {
580
+ addErrorToast([
581
+ new Error(
582
+ "A message was sent while interrupt is active. This will cause failure on the agent side"
583
+ )
584
+ ]);
585
+ }
586
+ let newMessages = [
587
+ new import_runtime_client_gql3.TextMessage({
588
+ content: "",
589
+ role: import_runtime_client_gql3.Role.Assistant
590
+ })
591
+ ];
592
+ chatAbortControllerRef.current = new AbortController();
593
+ setMessages([...previousMessages, ...newMessages]);
594
+ const systemMessage = makeSystemMessageCallback();
595
+ const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
596
+ const finalProperties = __spreadValues({}, copilotConfig.properties || {});
597
+ let mcpServersToUse = null;
598
+ if (copilotConfig.mcpServers && Array.isArray(copilotConfig.mcpServers) && copilotConfig.mcpServers.length > 0) {
599
+ mcpServersToUse = copilotConfig.mcpServers;
600
+ } else if (((_a = copilotConfig.properties) == null ? void 0 : _a.mcpServers) && Array.isArray(copilotConfig.properties.mcpServers) && copilotConfig.properties.mcpServers.length > 0) {
601
+ mcpServersToUse = copilotConfig.properties.mcpServers;
602
+ }
603
+ if (mcpServersToUse) {
604
+ finalProperties.mcpServers = mcpServersToUse;
605
+ copilotConfig.mcpServers = mcpServersToUse;
606
+ }
607
+ const isAgentRun = agentSessionRef.current !== null;
608
+ const stream = runtimeClient.asStream(
609
+ runtimeClient.generateCopilotResponse({
610
+ data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
611
+ frontend: {
612
+ actions: processActionsForRuntimeRequest(actions),
613
+ url: window.location.href
614
+ },
615
+ threadId,
616
+ runId: runIdRef.current,
617
+ extensions: extensionsRef.current,
618
+ metaEvents: composeAndFlushMetaEventsInput([langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event]),
619
+ messages: (0, import_runtime_client_gql3.convertMessagesToGqlInput)((0, import_runtime_client_gql3.filterAgentStateMessages)(messagesWithContext))
620
+ }, copilotConfig.cloud ? {
621
+ cloud: __spreadValues({}, ((_d = (_c = (_b = copilotConfig.cloud.guardrails) == null ? void 0 : _b.input) == null ? void 0 : _c.restrictToTopic) == null ? void 0 : _d.enabled) ? {
622
+ guardrails: {
623
+ inputValidationRules: {
624
+ allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
625
+ denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
626
+ }
627
+ }
628
+ } : {})
629
+ } : {}), {
630
+ metadata: {
631
+ requestType: import_runtime_client_gql3.CopilotRequestType.Chat
632
+ }
633
+ }), agentSessionRef.current ? {
634
+ agentSession: agentSessionRef.current
635
+ } : {}), {
636
+ agentStates: Object.values(coagentStatesRef.current).map((state) => {
637
+ const stateObject = {
638
+ agentName: state.name,
639
+ state: JSON.stringify(state.state)
640
+ };
641
+ if (state.config !== void 0) {
642
+ stateObject.config = JSON.stringify(state.config);
643
+ }
644
+ return stateObject;
645
+ }),
646
+ forwardedParameters: options.forwardedParameters || {}
647
+ }),
648
+ properties: finalProperties,
649
+ signal: (_e = chatAbortControllerRef.current) == null ? void 0 : _e.signal
650
+ })
651
+ );
652
+ const guardrailsEnabled = ((_h = (_g = (_f = copilotConfig.cloud) == null ? void 0 : _f.guardrails) == null ? void 0 : _g.input) == null ? void 0 : _h.restrictToTopic.enabled) || false;
653
+ const reader = stream.getReader();
654
+ let executedCoAgentStateRenders = [];
655
+ let followUp = void 0;
656
+ let messages2 = [];
657
+ let syncedMessages = [];
658
+ let interruptMessages = [];
659
+ try {
660
+ while (true) {
661
+ let done, value;
662
+ try {
663
+ const readResult = yield reader.read();
664
+ done = readResult.done;
665
+ value = readResult.value;
666
+ } catch (readError) {
667
+ break;
668
+ }
669
+ if (done) {
670
+ if (chatAbortControllerRef.current.signal.aborted) {
671
+ return [];
672
+ }
673
+ break;
674
+ }
675
+ if (!(value == null ? void 0 : value.generateCopilotResponse)) {
676
+ continue;
677
+ }
678
+ runIdRef.current = value.generateCopilotResponse.runId || null;
679
+ extensionsRef.current = import_runtime_client_gql3.CopilotRuntimeClient.removeGraphQLTypename(
680
+ value.generateCopilotResponse.extensions || {}
681
+ );
682
+ setRunId(runIdRef.current);
683
+ setExtensions(extensionsRef.current);
684
+ let rawMessagesResponse = value.generateCopilotResponse.messages;
685
+ const metaEvents = (_j = (_i = value.generateCopilotResponse) == null ? void 0 : _i.metaEvents) != null ? _j : [];
686
+ (metaEvents != null ? metaEvents : []).forEach((ev) => {
687
+ if (ev.name === import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent) {
688
+ let eventValue = (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev).value;
689
+ eventValue = (0, import_shared4.parseJson)(eventValue, eventValue);
690
+ setLangGraphInterruptAction({
691
+ event: __spreadProps(__spreadValues({}, (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev)), {
692
+ value: eventValue
693
+ })
694
+ });
695
+ }
696
+ if (ev.name === import_runtime_client_gql3.MetaEventName.CopilotKitLangGraphInterruptEvent) {
697
+ const data = ev.data;
698
+ rawMessagesResponse = [...rawMessagesResponse, ...data.messages];
699
+ interruptMessages = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
700
+ // @ts-ignore
701
+ (0, import_runtime_client_gql3.filterAdjacentAgentStateMessages)(data.messages)
702
+ );
703
+ }
704
+ });
705
+ messages2 = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
706
+ (0, import_runtime_client_gql3.filterAdjacentAgentStateMessages)(rawMessagesResponse)
707
+ );
708
+ newMessages = [];
709
+ if (((_k = value.generateCopilotResponse.status) == null ? void 0 : _k.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
710
+ const guardrailsReason = ((_l = value.generateCopilotResponse.status.details) == null ? void 0 : _l.guardrailsReason) || "";
711
+ newMessages = [
712
+ new import_runtime_client_gql3.TextMessage({
713
+ role: import_runtime_client_gql3.MessageRole.Assistant,
714
+ content: guardrailsReason
715
+ })
716
+ ];
717
+ const guardrailsError = new import_shared4.CopilotKitError({
718
+ message: `Guardrails validation failed: ${guardrailsReason}`,
719
+ code: import_shared4.CopilotKitErrorCode.MISUSE
720
+ });
721
+ yield traceUIError(guardrailsError, {
722
+ statusReason: value.generateCopilotResponse.status.reason,
723
+ statusDetails: value.generateCopilotResponse.status.details
724
+ });
725
+ setMessages([...previousMessages, ...newMessages]);
726
+ break;
727
+ }
728
+ if (((_m = value.generateCopilotResponse.status) == null ? void 0 : _m.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "UNKNOWN_ERROR") {
729
+ const errorMessage = ((_n = value.generateCopilotResponse.status.details) == null ? void 0 : _n.description) || "An unknown error occurred";
730
+ const statusDetails = value.generateCopilotResponse.status.details;
731
+ const originalError = (statusDetails == null ? void 0 : statusDetails.originalError) || (statusDetails == null ? void 0 : statusDetails.error);
732
+ const originalCode = (originalError == null ? void 0 : originalError.code) || ((_o = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _o.code);
733
+ const originalSeverity = (originalError == null ? void 0 : originalError.severity) || ((_p = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _p.severity);
734
+ const originalVisibility = (originalError == null ? void 0 : originalError.visibility) || ((_q = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _q.visibility);
735
+ let errorCode = import_shared4.CopilotKitErrorCode.NETWORK_ERROR;
736
+ if (originalCode && Object.values(import_shared4.CopilotKitErrorCode).includes(originalCode)) {
737
+ errorCode = originalCode;
738
+ }
739
+ const structuredError = new import_shared4.CopilotKitError({
740
+ message: errorMessage,
741
+ code: errorCode,
742
+ severity: originalSeverity,
743
+ visibility: originalVisibility
744
+ });
745
+ setBannerError(structuredError);
746
+ yield traceUIError(structuredError, {
747
+ statusReason: value.generateCopilotResponse.status.reason,
748
+ statusDetails: value.generateCopilotResponse.status.details,
749
+ originalErrorCode: originalCode,
750
+ preservedStructure: !!originalCode
751
+ });
752
+ setIsLoading(false);
753
+ break;
754
+ } else if (messages2.length > 0) {
755
+ newMessages = [...messages2];
756
+ for (const message of messages2) {
757
+ if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
758
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
759
+ break;
760
+ }
761
+ yield onCoAgentStateRender({
762
+ name: message.agentName,
763
+ nodeName: message.nodeName,
764
+ state: message.state
765
+ });
766
+ executedCoAgentStateRenders.push(message.id);
767
+ }
768
+ }
769
+ const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
770
+ if (lastAgentStateMessage) {
771
+ if (lastAgentStateMessage.state.messages && lastAgentStateMessage.state.messages.length > 0) {
772
+ syncedMessages = (0, import_runtime_client_gql3.loadMessagesFromJsonRepresentation)(
773
+ lastAgentStateMessage.state.messages
774
+ );
775
+ }
776
+ setCoagentStatesWithRef((prevAgentStates) => {
777
+ var _a2;
778
+ return __spreadProps(__spreadValues({}, prevAgentStates), {
779
+ [lastAgentStateMessage.agentName]: {
780
+ name: lastAgentStateMessage.agentName,
781
+ state: lastAgentStateMessage.state,
782
+ running: lastAgentStateMessage.running,
783
+ active: lastAgentStateMessage.active,
784
+ threadId: lastAgentStateMessage.threadId,
785
+ nodeName: lastAgentStateMessage.nodeName,
786
+ runId: lastAgentStateMessage.runId,
787
+ // Preserve existing config from previous state
788
+ config: (_a2 = prevAgentStates[lastAgentStateMessage.agentName]) == null ? void 0 : _a2.config
789
+ }
790
+ });
791
+ });
792
+ if (lastAgentStateMessage.running) {
793
+ setAgentSession({
794
+ threadId: lastAgentStateMessage.threadId,
795
+ agentName: lastAgentStateMessage.agentName,
796
+ nodeName: lastAgentStateMessage.nodeName
797
+ });
798
+ } else {
799
+ if (agentLock) {
800
+ setAgentSession({
801
+ threadId: (0, import_shared4.randomId)(),
802
+ agentName: agentLock,
803
+ nodeName: void 0
804
+ });
805
+ } else {
806
+ setAgentSession(null);
807
+ }
808
+ }
809
+ }
810
+ }
811
+ if (newMessages.length > 0) {
812
+ setMessages([...previousMessages, ...newMessages]);
813
+ }
814
+ }
815
+ let finalMessages = constructFinalMessages(
816
+ [...syncedMessages, ...interruptMessages],
817
+ previousMessages,
818
+ newMessages
819
+ );
820
+ let didExecuteAction = false;
821
+ const executeActionFromMessage = (currentAction, actionMessage) => __async(this, null, function* () {
822
+ var _a2;
823
+ const isInterruptAction = interruptMessages.find((m) => m.id === actionMessage.id);
824
+ followUp = (_a2 = currentAction == null ? void 0 : currentAction.followUp) != null ? _a2 : !isInterruptAction;
825
+ if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
826
+ currentAction._setActivatingMessageId(actionMessage.id);
827
+ }
828
+ const resultMessage = yield executeAction({
829
+ onFunctionCall,
830
+ message: actionMessage,
831
+ chatAbortControllerRef,
832
+ onError: (error) => {
833
+ addErrorToast([error]);
834
+ console.error(`Failed to execute action ${actionMessage.name}: ${error}`);
835
+ },
836
+ setMessages,
837
+ getFinalMessages: () => finalMessages,
838
+ isRenderAndWait: (currentAction == null ? void 0 : currentAction._isRenderAndWait) || false
839
+ });
840
+ didExecuteAction = true;
841
+ const messageIndex = finalMessages.findIndex((msg) => msg.id === actionMessage.id);
842
+ finalMessages.splice(messageIndex + 1, 0, resultMessage);
843
+ if (currentAction == null ? void 0 : currentAction._isRenderAndWait) {
844
+ const messagesForImmediateUpdate = [...finalMessages];
845
+ (0, import_react_dom.flushSync)(() => {
846
+ setMessages(messagesForImmediateUpdate);
847
+ });
848
+ }
849
+ if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
850
+ currentAction._setActivatingMessageId(null);
851
+ }
852
+ return resultMessage;
853
+ });
854
+ if (onFunctionCall) {
855
+ const lastMessages = [];
856
+ for (let i = finalMessages.length - 1; i >= 0; i--) {
857
+ const message = finalMessages[i];
858
+ if ((message.isActionExecutionMessage() || message.isResultMessage()) && message.status.code !== import_runtime_client_gql3.MessageStatusCode.Pending) {
859
+ lastMessages.unshift(message);
860
+ } else if (!message.isAgentStateMessage()) {
861
+ break;
862
+ }
863
+ }
864
+ for (const message of lastMessages) {
865
+ setMessages(finalMessages);
866
+ const action = actions.find(
867
+ (action2) => action2.name === message.name
868
+ );
869
+ if (action && action.available === "frontend") {
870
+ continue;
871
+ }
872
+ const currentResultMessagePairedFeAction = message.isResultMessage() ? getPairedFeAction(actions, message) : null;
873
+ if (action && message.isActionExecutionMessage()) {
874
+ const isRenderAndWaitAction = (action == null ? void 0 : action._isRenderAndWait) || false;
875
+ const alreadyProcessed = isRenderAndWaitAction && finalMessages.some(
876
+ (fm) => fm.isResultMessage() && fm.actionExecutionId === message.id
877
+ );
878
+ if (alreadyProcessed) {
879
+ } else {
880
+ const resultMessage = yield executeActionFromMessage(
881
+ action,
882
+ message
883
+ );
884
+ const pairedFeAction = getPairedFeAction(actions, resultMessage);
885
+ if (pairedFeAction) {
886
+ const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
887
+ name: pairedFeAction.name,
888
+ arguments: (0, import_shared4.parseJson)(resultMessage.result, resultMessage.result),
889
+ status: message.status,
890
+ createdAt: message.createdAt,
891
+ parentMessageId: message.parentMessageId
892
+ });
893
+ yield executeActionFromMessage(pairedFeAction, newExecutionMessage);
894
+ }
895
+ }
896
+ } else if (message.isResultMessage() && currentResultMessagePairedFeAction) {
897
+ const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
898
+ name: currentResultMessagePairedFeAction.name,
899
+ arguments: (0, import_shared4.parseJson)(message.result, message.result),
900
+ status: message.status,
901
+ createdAt: message.createdAt
902
+ });
903
+ finalMessages.push(newExecutionMessage);
904
+ yield executeActionFromMessage(
905
+ currentResultMessagePairedFeAction,
906
+ newExecutionMessage
907
+ );
908
+ }
909
+ }
910
+ setMessages(finalMessages);
911
+ }
912
+ if (followUp !== false && (didExecuteAction || // the last message is a server side result
913
+ !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage()) && // the user did not stop generation
914
+ !((_r = chatAbortControllerRef.current) == null ? void 0 : _r.signal.aborted)) {
915
+ yield new Promise((resolve) => setTimeout(resolve, 10));
916
+ return yield runChatCompletionRef.current(finalMessages);
917
+ } else if ((_s = chatAbortControllerRef.current) == null ? void 0 : _s.signal.aborted) {
918
+ const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {
919
+ if (message.isActionExecutionMessage()) {
920
+ return finalMessages.find(
921
+ (msg, resultIndex) => msg.isResultMessage() && msg.actionExecutionId === message.id && resultIndex === actionExecutionIndex + 1
922
+ );
923
+ }
924
+ return true;
925
+ });
926
+ const repairedMessageIds = repairedMessages.map((message) => message.id);
927
+ setMessages(repairedMessages);
928
+ if ((_t = agentSessionRef.current) == null ? void 0 : _t.nodeName) {
929
+ setAgentSession({
930
+ threadId: agentSessionRef.current.threadId,
931
+ agentName: agentSessionRef.current.agentName,
932
+ nodeName: "__end__"
933
+ });
934
+ }
935
+ return newMessages.filter((message) => repairedMessageIds.includes(message.id));
936
+ } else {
937
+ return newMessages.slice();
938
+ }
939
+ } finally {
940
+ setIsLoading(false);
941
+ }
942
+ }),
943
+ [
944
+ messages,
945
+ setMessages,
946
+ makeSystemMessageCallback,
947
+ copilotConfig,
948
+ setIsLoading,
949
+ initialMessages,
950
+ isLoading,
951
+ actions,
952
+ onFunctionCall,
953
+ onCoAgentStateRender,
954
+ setCoagentStatesWithRef,
955
+ coagentStatesRef,
956
+ agentSession,
957
+ setAgentSession
958
+ ]
959
+ );
960
+ runChatCompletionRef.current = runChatCompletion;
961
+ const runChatCompletionAndHandleFunctionCall = useAsyncCallback(
962
+ (messages2) => __async(this, null, function* () {
963
+ yield runChatCompletionRef.current(messages2);
964
+ }),
965
+ [messages]
966
+ );
967
+ (0, import_react6.useEffect)(() => {
968
+ if (!isLoading && pendingAppendsRef.current.length > 0) {
969
+ const pending = pendingAppendsRef.current.splice(0);
970
+ const followUp = pending.some((p) => p.followUp);
971
+ const newMessages = [...messages, ...pending.map((p) => p.message)];
972
+ setMessages(newMessages);
973
+ if (followUp) {
974
+ runChatCompletionAndHandleFunctionCall(newMessages);
975
+ }
976
+ }
977
+ }, [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);
978
+ const composeAndFlushMetaEventsInput = (0, import_react6.useCallback)(
979
+ (metaEvents) => {
980
+ return metaEvents.reduce((acc, event) => {
981
+ if (!event)
982
+ return acc;
983
+ switch (event.name) {
984
+ case import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent:
985
+ if (event.response) {
986
+ setLangGraphInterruptAction(null);
987
+ const value = event.value;
988
+ return [
989
+ ...acc,
990
+ {
991
+ name: event.name,
992
+ value: typeof value === "string" ? value : JSON.stringify(value),
993
+ response: typeof event.response === "string" ? event.response : JSON.stringify(event.response)
994
+ }
995
+ ];
996
+ }
997
+ return acc;
998
+ default:
999
+ return acc;
1000
+ }
1001
+ }, []);
1002
+ },
1003
+ [setLangGraphInterruptAction]
1004
+ );
1005
+ const append = useAsyncCallback(
1006
+ (message, options2) => __async(this, null, function* () {
1007
+ var _a;
1008
+ const followUp = (_a = options2 == null ? void 0 : options2.followUp) != null ? _a : true;
1009
+ if (isLoading) {
1010
+ pendingAppendsRef.current.push({ message, followUp });
1011
+ return;
1012
+ }
1013
+ const newMessages = [...messages, message];
1014
+ setMessages(newMessages);
1015
+ if (followUp) {
1016
+ return runChatCompletionAndHandleFunctionCall(newMessages);
1017
+ }
1018
+ }),
1019
+ [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
1020
+ );
1021
+ const reload = useAsyncCallback(
1022
+ (reloadMessageId) => __async(this, null, function* () {
1023
+ if (isLoading || messages.length === 0) {
1024
+ return;
1025
+ }
1026
+ const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);
1027
+ if (reloadMessageIndex === -1) {
1028
+ console.warn(`Message with id ${reloadMessageId} not found`);
1029
+ return;
1030
+ }
1031
+ const reloadMessageRole = messages[reloadMessageIndex].role;
1032
+ if (reloadMessageRole !== import_runtime_client_gql3.MessageRole.Assistant) {
1033
+ console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
1034
+ return;
1035
+ }
1036
+ let historyCutoff = [];
1037
+ if (messages.length > 2) {
1038
+ const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find(
1039
+ (msg) => (
1040
+ // @ts-expect-error -- message has role
1041
+ msg.role === import_runtime_client_gql3.MessageRole.User
1042
+ )
1043
+ );
1044
+ const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(
1045
+ (msg) => msg.id === lastUserMessageBeforeRegenerate.id
1046
+ );
1047
+ historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
1048
+ }
1049
+ setMessages(historyCutoff);
1050
+ return runChatCompletionAndHandleFunctionCall(historyCutoff);
1051
+ }),
1052
+ [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
1053
+ );
1054
+ const stop = () => {
1055
+ var _a;
1056
+ (_a = chatAbortControllerRef.current) == null ? void 0 : _a.abort("Stop was called");
1057
+ };
1058
+ return {
1059
+ append,
1060
+ reload,
1061
+ stop,
1062
+ runChatCompletion: () => runChatCompletionRef.current(messages)
1063
+ };
1064
+ }
1065
+ function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
1066
+ const finalMessages = syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];
1067
+ if (syncedMessages.length > 0) {
1068
+ const messagesWithAgentState = [...previousMessages, ...newMessages];
1069
+ let previousMessageId = void 0;
1070
+ for (const message of messagesWithAgentState) {
1071
+ if (message.isAgentStateMessage()) {
1072
+ const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);
1073
+ if (index !== -1) {
1074
+ finalMessages.splice(index + 1, 0, message);
1075
+ }
1076
+ }
1077
+ previousMessageId = message.id;
1078
+ }
1079
+ }
1080
+ return finalMessages;
1081
+ }
1082
+ function executeAction(_0) {
1083
+ return __async(this, arguments, function* ({
1084
+ onFunctionCall,
1085
+ message,
1086
+ chatAbortControllerRef,
1087
+ onError,
1088
+ setMessages,
1089
+ getFinalMessages,
1090
+ isRenderAndWait
1091
+ }) {
1092
+ let result;
1093
+ let error = null;
1094
+ const currentMessagesForHandler = getFinalMessages();
1095
+ const handlerReturnedPromise = onFunctionCall({
1096
+ messages: currentMessagesForHandler,
1097
+ name: message.name,
1098
+ args: message.arguments
1099
+ });
1100
+ if (isRenderAndWait) {
1101
+ const currentMessagesForRender = getFinalMessages();
1102
+ (0, import_react_dom.flushSync)(() => {
1103
+ setMessages([...currentMessagesForRender]);
1104
+ });
1105
+ }
1106
+ try {
1107
+ result = yield Promise.race([
1108
+ handlerReturnedPromise,
1109
+ // Await the promise returned by the handler
1110
+ new Promise(
1111
+ (resolve) => {
1112
+ var _a;
1113
+ return (_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.addEventListener(
1114
+ "abort",
1115
+ () => resolve("Operation was aborted by the user")
1116
+ );
1117
+ }
1118
+ ),
1119
+ // if the user stopped generation, we also abort consecutive actions
1120
+ new Promise((resolve) => {
1121
+ var _a;
1122
+ if ((_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.aborted) {
1123
+ resolve("Operation was aborted by the user");
1124
+ }
1125
+ })
1126
+ ]);
1127
+ } catch (e) {
1128
+ onError(e);
1129
+ }
1130
+ return new import_runtime_client_gql3.ResultMessage({
1131
+ id: "result-" + message.id,
1132
+ result: import_runtime_client_gql3.ResultMessage.encodeResult(
1133
+ error ? {
1134
+ content: result,
1135
+ error: JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)))
1136
+ } : result
1137
+ ),
1138
+ actionExecutionId: message.id,
1139
+ actionName: message.name
1140
+ });
1141
+ });
1142
+ }
1143
+ function getPairedFeAction(actions, message) {
1144
+ let actionName = null;
1145
+ if (message.isActionExecutionMessage()) {
1146
+ actionName = message.name;
1147
+ } else if (message.isResultMessage()) {
1148
+ actionName = message.actionName;
1149
+ }
1150
+ return actions.find(
1151
+ (action) => action.name === actionName && action.available === "frontend" || action.pairedAction === actionName
1152
+ );
1153
+ }
1154
+
1155
+ // src/components/copilot-provider/copilotkit.tsx
1156
+ var import_react7 = require("react");
1157
+ var import_react_dom2 = require("react-dom");
1158
+ var import_shared7 = require("@copilotkit/shared");
1159
+
1160
+ // src/utils/extract.ts
1161
+ var import_shared5 = require("@copilotkit/shared");
1162
+ var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
1163
+ var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
1164
+ function extract(_0) {
1165
+ return __async(this, arguments, function* ({
1166
+ context,
1167
+ instructions,
1168
+ parameters,
1169
+ include,
1170
+ data,
1171
+ abortSignal,
1172
+ stream,
1173
+ requestType = import_runtime_client_gql4.CopilotRequestType.Task,
1174
+ forwardedParameters
1175
+ }) {
1176
+ var _a, _b;
1177
+ const { messages } = context;
1178
+ const action = {
1179
+ name: "extract",
1180
+ description: instructions,
1181
+ parameters,
1182
+ handler: (args) => {
1183
+ }
1184
+ };
1185
+ const includeReadable = (_a = include == null ? void 0 : include.readable) != null ? _a : false;
1186
+ const includeMessages = (_b = include == null ? void 0 : include.messages) != null ? _b : false;
1187
+ let contextString = "";
1188
+ if (data) {
1189
+ contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
1190
+ }
1191
+ if (includeReadable) {
1192
+ contextString += context.getContextString([], defaultCopilotContextCategories);
1193
+ }
1194
+ const systemMessage = new import_runtime_client_gql4.TextMessage({
1195
+ content: makeSystemMessage(contextString, instructions),
1196
+ role: import_runtime_client_gql4.Role.System
1197
+ });
1198
+ const instructionsMessage = new import_runtime_client_gql4.TextMessage({
1199
+ content: makeInstructionsMessage(instructions),
1200
+ role: import_runtime_client_gql4.Role.User
1201
+ });
1202
+ const response = context.runtimeClient.asStream(
1203
+ context.runtimeClient.generateCopilotResponse({
1204
+ data: {
1205
+ frontend: {
1206
+ actions: [
1207
+ {
1208
+ name: action.name,
1209
+ description: action.description || "",
1210
+ jsonSchema: JSON.stringify((0, import_shared5.actionParametersToJsonSchema)(action.parameters || []))
1211
+ }
1212
+ ],
1213
+ url: window.location.href
1214
+ },
1215
+ messages: (0, import_runtime_client_gql5.convertMessagesToGqlInput)(
1216
+ includeMessages ? [systemMessage, instructionsMessage, ...(0, import_runtime_client_gql5.filterAgentStateMessages)(messages)] : [systemMessage, instructionsMessage]
1217
+ ),
1218
+ metadata: {
1219
+ requestType
1220
+ },
1221
+ forwardedParameters: __spreadProps(__spreadValues({}, forwardedParameters != null ? forwardedParameters : {}), {
1222
+ toolChoice: "function",
1223
+ toolChoiceFunctionName: action.name
1224
+ })
1225
+ },
1226
+ properties: context.copilotApiConfig.properties,
1227
+ signal: abortSignal
1228
+ })
1229
+ );
1230
+ const reader = response.getReader();
1231
+ let isInitial = true;
1232
+ let actionExecutionMessage = void 0;
1233
+ while (true) {
1234
+ const { done, value } = yield reader.read();
1235
+ if (done) {
1236
+ break;
1237
+ }
1238
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
1239
+ throw new Error("Aborted");
1240
+ }
1241
+ actionExecutionMessage = (0, import_runtime_client_gql4.convertGqlOutputToMessages)(
1242
+ value.generateCopilotResponse.messages
1243
+ ).find((msg) => msg.isActionExecutionMessage());
1244
+ if (!actionExecutionMessage) {
1245
+ continue;
1246
+ }
1247
+ stream == null ? void 0 : stream({
1248
+ status: isInitial ? "initial" : "inProgress",
1249
+ args: actionExecutionMessage.arguments
1250
+ });
1251
+ isInitial = false;
1252
+ }
1253
+ if (!actionExecutionMessage) {
1254
+ throw new Error("extract() failed: No function call occurred");
1255
+ }
1256
+ stream == null ? void 0 : stream({
1257
+ status: "complete",
1258
+ args: actionExecutionMessage.arguments
1259
+ });
1260
+ return actionExecutionMessage.arguments;
1261
+ });
1262
+ }
1263
+ function makeInstructionsMessage(instructions) {
1264
+ return `
1265
+ The user has given you the following task to complete:
1266
+
1267
+ \`\`\`
1268
+ ${instructions}
1269
+ \`\`\`
1270
+
1271
+ Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
1272
+ `;
1273
+ }
1274
+ function makeSystemMessage(contextString, instructions) {
1275
+ return `
1276
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
1277
+
1278
+ 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.
1279
+ Always be polite and respectful, and prefer brevity over verbosity.
1280
+
1281
+ The user has provided you with the following context:
1282
+ \`\`\`
1283
+ ${contextString}
1284
+ \`\`\`
1285
+
1286
+ They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
1287
+
1288
+ Please assist them as best you can.
1289
+
1290
+ This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
1291
+ `;
1292
+ }
1293
+
1294
+ // src/utils/suggestions.ts
1295
+ var import_shared6 = require("@copilotkit/shared");
1296
+ var import_runtime_client_gql6 = require("@copilotkit/runtime-client-gql");
1297
+ var reloadSuggestions = (context, chatSuggestionConfiguration, setCurrentSuggestions, abortControllerRef) => __async(void 0, null, function* () {
1298
+ const abortController = abortControllerRef.current;
1299
+ if (abortController == null ? void 0 : abortController.signal.aborted) {
1300
+ return;
1301
+ }
1302
+ const setSuggestionsIfNotAborted = (suggestions) => {
1303
+ if (!(abortController == null ? void 0 : abortController.signal.aborted) && abortControllerRef.current === abortController) {
1304
+ setCurrentSuggestions(suggestions);
1305
+ }
1306
+ };
1307
+ try {
1308
+ const tools = JSON.stringify(
1309
+ Object.values(context.actions).map((action) => ({
1310
+ name: action.name,
1311
+ description: action.description,
1312
+ jsonSchema: JSON.stringify((0, import_shared6.actionParametersToJsonSchema)(action.parameters))
1313
+ }))
1314
+ );
1315
+ const allSuggestions = [];
1316
+ let hasSuccessfulSuggestions = false;
1317
+ let hasErrors = false;
1318
+ let lastError = null;
1319
+ const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(
1320
+ (config) => config.instructions && config.instructions.trim().length > 0
1321
+ );
1322
+ if (enabledConfigs.length === 0) {
1323
+ return;
1324
+ }
1325
+ setSuggestionsIfNotAborted([]);
1326
+ for (const config of enabledConfigs) {
1327
+ if (abortController == null ? void 0 : abortController.signal.aborted) {
1328
+ setSuggestionsIfNotAborted([]);
1329
+ return;
1330
+ }
1331
+ try {
1332
+ const result = yield extract({
1333
+ context,
1334
+ instructions: "Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. ",
1335
+ data: `${config.instructions}
1336
+
1337
+ Available tools: ${tools}
1338
+
1339
+ `,
1340
+ requestType: import_runtime_client_gql6.CopilotRequestType.Task,
1341
+ parameters: [
1342
+ {
1343
+ name: "suggestions",
1344
+ type: "object[]",
1345
+ attributes: [
1346
+ {
1347
+ name: "title",
1348
+ description: "The title of the suggestion. This is shown as a button and should be short.",
1349
+ type: "string"
1350
+ },
1351
+ {
1352
+ name: "message",
1353
+ description: "The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI.",
1354
+ type: "string"
1355
+ }
1356
+ ]
1357
+ }
1358
+ ],
1359
+ include: {
1360
+ messages: true,
1361
+ readable: true
1362
+ },
1363
+ abortSignal: abortController == null ? void 0 : abortController.signal,
1364
+ stream: ({ status, args }) => {
1365
+ if (abortController == null ? void 0 : abortController.signal.aborted) {
1366
+ return;
1367
+ }
1368
+ const suggestions = args.suggestions || [];
1369
+ const newSuggestions = [];
1370
+ for (let i = 0; i < suggestions.length; i++) {
1371
+ if (config.maxSuggestions !== void 0 && i >= config.maxSuggestions) {
1372
+ break;
1373
+ }
1374
+ const suggestion = suggestions[i];
1375
+ if (!suggestion || typeof suggestion !== "object") {
1376
+ continue;
1377
+ }
1378
+ const { title, message } = suggestion;
1379
+ const hasValidTitle = title && typeof title === "string" && title.trim().length > 0;
1380
+ const hasValidMessage = message && typeof message === "string" && message.trim().length > 0;
1381
+ if (!hasValidTitle) {
1382
+ continue;
1383
+ }
1384
+ const partial = i === suggestions.length - 1 && status !== "complete";
1385
+ newSuggestions.push({
1386
+ title: title.trim(),
1387
+ message: hasValidMessage ? message.trim() : "",
1388
+ // Use title as fallback
1389
+ partial,
1390
+ className: config.className
1391
+ });
1392
+ }
1393
+ setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);
1394
+ }
1395
+ });
1396
+ if ((result == null ? void 0 : result.suggestions) && Array.isArray(result.suggestions)) {
1397
+ const validSuggestions = result.suggestions.filter(
1398
+ (suggestion) => suggestion && typeof suggestion.title === "string" && suggestion.title.trim().length > 0
1399
+ ).map((suggestion) => ({
1400
+ title: suggestion.title.trim(),
1401
+ message: suggestion.message && typeof suggestion.message === "string" && suggestion.message.trim() ? suggestion.message.trim() : suggestion.title.trim()
1402
+ }));
1403
+ if (validSuggestions.length > 0) {
1404
+ allSuggestions.push(...validSuggestions);
1405
+ hasSuccessfulSuggestions = true;
1406
+ }
1407
+ }
1408
+ } catch (error) {
1409
+ hasErrors = true;
1410
+ lastError = error instanceof Error ? error : new Error(String(error));
1411
+ }
1412
+ }
1413
+ if (hasSuccessfulSuggestions && allSuggestions.length > 0) {
1414
+ const uniqueSuggestions = allSuggestions.filter(
1415
+ (suggestion, index, self) => index === self.findIndex((s) => s.message === suggestion.message)
1416
+ );
1417
+ setSuggestionsIfNotAborted(uniqueSuggestions);
1418
+ } else if (hasErrors) {
1419
+ const errorMessage = lastError ? lastError.message : "Failed to generate suggestions due to API errors";
1420
+ throw new Error(errorMessage);
1421
+ }
1422
+ } catch (error) {
1423
+ throw error;
1424
+ }
1425
+ });
1426
+
1427
+ // src/components/copilot-provider/copilotkit.tsx
1428
+ var import_jsx_runtime4 = require("react/jsx-runtime");
1429
+ var defaultCopilotContextCategories = ["global"];
1430
+
1431
+ // src/hooks/use-copilot-chat_internal.ts
1432
+ var import_runtime_client_gql7 = require("@copilotkit/runtime-client-gql");
1433
+
1434
+ // src/hooks/use-langgraph-interrupt-render.ts
1435
+ var import_react8 = __toESM(require("react"));
1436
+ var InterruptRenderer = ({ event, result, render, resolve }) => {
1437
+ return render({ event, result, resolve });
1438
+ };
1439
+ function useLangGraphInterruptRender() {
1440
+ const { langGraphInterruptAction, setLangGraphInterruptAction, agentSession } = useCopilotContext();
1441
+ const responseRef = import_react8.default.useRef();
1442
+ const resolveInterrupt = (0, import_react8.useCallback)(
1443
+ (response) => {
1444
+ responseRef.current = response;
1445
+ setTimeout(() => {
1446
+ setLangGraphInterruptAction({ event: { response } });
1447
+ }, 0);
1448
+ },
1449
+ [setLangGraphInterruptAction]
1450
+ );
1451
+ if (!langGraphInterruptAction || !langGraphInterruptAction.event || !langGraphInterruptAction.render)
1452
+ return null;
1453
+ const { render, handler, event, enabled } = langGraphInterruptAction;
1454
+ const conditionsMet = !agentSession || !enabled ? true : enabled({ eventValue: event.value, agentMetadata: agentSession });
1455
+ if (!conditionsMet) {
1456
+ return null;
1457
+ }
1458
+ let result = null;
1459
+ if (handler) {
1460
+ result = handler({
1461
+ event,
1462
+ resolve: resolveInterrupt
1463
+ });
1464
+ }
1465
+ return import_react8.default.createElement(InterruptRenderer, {
1466
+ event,
1467
+ result,
1468
+ render,
1469
+ resolve: resolveInterrupt
1470
+ });
1471
+ }
1472
+
1473
+ // src/hooks/use-copilot-chat_internal.ts
1474
+ var globalSuggestionPromise = null;
1475
+ function useCopilotChat(options = {}) {
1476
+ var _a;
1477
+ const makeSystemMessage2 = (_a = options.makeSystemMessage) != null ? _a : defaultSystemMessage;
1478
+ const {
1479
+ getContextString,
1480
+ getFunctionCallHandler,
1481
+ copilotApiConfig,
1482
+ isLoading,
1483
+ setIsLoading,
1484
+ chatInstructions,
1485
+ actions,
1486
+ coagentStatesRef,
1487
+ setCoagentStatesWithRef,
1488
+ coAgentStateRenders,
1489
+ agentSession,
1490
+ setAgentSession,
1491
+ forwardedParameters,
1492
+ agentLock,
1493
+ threadId,
1494
+ setThreadId,
1495
+ runId,
1496
+ setRunId,
1497
+ chatAbortControllerRef,
1498
+ extensions,
1499
+ setExtensions,
1500
+ langGraphInterruptAction,
1501
+ setLangGraphInterruptAction,
1502
+ chatSuggestionConfiguration,
1503
+ suggestions,
1504
+ setSuggestions,
1505
+ runtimeClient
1506
+ } = useCopilotContext();
1507
+ const { messages, setMessages } = useCopilotMessagesContext();
1508
+ const [mcpServers, setLocalMcpServers] = (0, import_react9.useState)([]);
1509
+ const suggestionsAbortControllerRef = (0, import_react9.useRef)(null);
1510
+ const isLoadingSuggestionsRef = (0, import_react9.useRef)(false);
1511
+ const abortSuggestions = (0, import_react9.useCallback)(
1512
+ (clear = true) => {
1513
+ var _a2;
1514
+ (_a2 = suggestionsAbortControllerRef.current) == null ? void 0 : _a2.abort("suggestions aborted by user");
1515
+ suggestionsAbortControllerRef.current = null;
1516
+ if (clear) {
1517
+ setSuggestions([]);
1518
+ }
1519
+ },
1520
+ [setSuggestions]
1521
+ );
1522
+ const stableContext = (0, import_react9.useMemo)(() => {
1523
+ return {
1524
+ actions,
1525
+ copilotApiConfig,
1526
+ chatSuggestionConfiguration,
1527
+ messages,
1528
+ setMessages,
1529
+ getContextString,
1530
+ runtimeClient
1531
+ };
1532
+ }, [
1533
+ JSON.stringify(Object.keys(actions)),
1534
+ copilotApiConfig.chatApiEndpoint,
1535
+ messages.length,
1536
+ Object.keys(chatSuggestionConfiguration).length
1537
+ ]);
1538
+ const generateSuggestionsFunc = (0, import_react9.useCallback)(() => __async(this, null, function* () {
1539
+ if (globalSuggestionPromise) {
1540
+ return globalSuggestionPromise;
1541
+ }
1542
+ globalSuggestionPromise = (() => __async(this, null, function* () {
1543
+ try {
1544
+ abortSuggestions();
1545
+ isLoadingSuggestionsRef.current = true;
1546
+ suggestionsAbortControllerRef.current = new AbortController();
1547
+ setSuggestions([]);
1548
+ yield reloadSuggestions(
1549
+ stableContext,
1550
+ chatSuggestionConfiguration,
1551
+ setSuggestions,
1552
+ suggestionsAbortControllerRef
1553
+ );
1554
+ } catch (error) {
1555
+ throw error;
1556
+ } finally {
1557
+ isLoadingSuggestionsRef.current = false;
1558
+ globalSuggestionPromise = null;
1559
+ }
1560
+ }))();
1561
+ return globalSuggestionPromise;
1562
+ }), [stableContext, chatSuggestionConfiguration, setSuggestions, abortSuggestions]);
1563
+ const resetSuggestions = (0, import_react9.useCallback)(() => {
1564
+ setSuggestions([]);
1565
+ }, [setSuggestions]);
1566
+ (0, import_react9.useEffect)(() => {
1567
+ if (mcpServers.length > 0) {
1568
+ const serversCopy = [...mcpServers];
1569
+ copilotApiConfig.mcpServers = serversCopy;
1570
+ if (!copilotApiConfig.properties) {
1571
+ copilotApiConfig.properties = {};
1572
+ }
1573
+ copilotApiConfig.properties.mcpServers = serversCopy;
1574
+ }
1575
+ }, [mcpServers, copilotApiConfig]);
1576
+ const setMcpServers = (0, import_react9.useCallback)((servers) => {
1577
+ setLocalMcpServers(servers);
1578
+ }, []);
1579
+ const onCoAgentStateRender = useAsyncCallback(
1580
+ (args) => __async(this, null, function* () {
1581
+ var _a2;
1582
+ const { name, nodeName, state } = args;
1583
+ let action = Object.values(coAgentStateRenders).find(
1584
+ (action2) => action2.name === name && action2.nodeName === nodeName
1585
+ );
1586
+ if (!action) {
1587
+ action = Object.values(coAgentStateRenders).find(
1588
+ (action2) => action2.name === name && !action2.nodeName
1589
+ );
1590
+ }
1591
+ if (action) {
1592
+ yield (_a2 = action.handler) == null ? void 0 : _a2.call(action, { state, nodeName });
1593
+ }
1594
+ }),
1595
+ [coAgentStateRenders]
1596
+ );
1597
+ const makeSystemMessageCallback = (0, import_react9.useCallback)(() => {
1598
+ const systemMessageMaker = makeSystemMessage2 || defaultSystemMessage;
1599
+ const contextString = getContextString([], defaultCopilotContextCategories);
1600
+ return new import_runtime_client_gql7.TextMessage({
1601
+ content: systemMessageMaker(contextString, chatInstructions),
1602
+ role: import_runtime_client_gql7.Role.System
1603
+ });
1604
+ }, [getContextString, makeSystemMessage2, chatInstructions]);
1605
+ const deleteMessage = (0, import_react9.useCallback)(
1606
+ (messageId) => {
1607
+ setMessages((prev) => prev.filter((message) => message.id !== messageId));
1608
+ },
1609
+ [setMessages]
1610
+ );
1611
+ const { append, reload, stop, runChatCompletion } = useChat(__spreadProps(__spreadValues({}, options), {
1612
+ actions: Object.values(actions),
1613
+ copilotConfig: copilotApiConfig,
1614
+ initialMessages: (0, import_runtime_client_gql7.aguiToGQL)(options.initialMessages || []),
1615
+ onFunctionCall: getFunctionCallHandler(),
1616
+ onCoAgentStateRender,
1617
+ messages,
1618
+ setMessages,
1619
+ makeSystemMessageCallback,
1620
+ isLoading,
1621
+ setIsLoading,
1622
+ coagentStatesRef,
1623
+ setCoagentStatesWithRef,
1624
+ agentSession,
1625
+ setAgentSession,
1626
+ forwardedParameters,
1627
+ threadId,
1628
+ setThreadId,
1629
+ runId,
1630
+ setRunId,
1631
+ chatAbortControllerRef,
1632
+ agentLock,
1633
+ extensions,
1634
+ setExtensions,
1635
+ langGraphInterruptAction,
1636
+ setLangGraphInterruptAction
1637
+ }));
1638
+ const latestAppend = useUpdatedRef(append);
1639
+ const latestAppendFunc = useAsyncCallback(
1640
+ (message, options2) => __async(this, null, function* () {
1641
+ abortSuggestions(options2 == null ? void 0 : options2.clearSuggestions);
1642
+ return yield latestAppend.current((0, import_runtime_client_gql7.aguiToGQL)([message])[0], options2);
1643
+ }),
1644
+ [latestAppend]
1645
+ );
1646
+ const latestReload = useUpdatedRef(reload);
1647
+ const latestReloadFunc = useAsyncCallback(
1648
+ (messageId) => __async(this, null, function* () {
1649
+ return yield latestReload.current(messageId);
1650
+ }),
1651
+ [latestReload]
1652
+ );
1653
+ const latestStop = useUpdatedRef(stop);
1654
+ const latestStopFunc = (0, import_react9.useCallback)(() => {
1655
+ return latestStop.current();
1656
+ }, [latestStop]);
1657
+ const latestDelete = useUpdatedRef(deleteMessage);
1658
+ const latestDeleteFunc = (0, import_react9.useCallback)(
1659
+ (messageId) => {
1660
+ return latestDelete.current(messageId);
1661
+ },
1662
+ [latestDelete]
1663
+ );
1664
+ const latestSetMessages = useUpdatedRef(setMessages);
1665
+ const latestSetMessagesFunc = (0, import_react9.useCallback)(
1666
+ (messages2) => {
1667
+ return latestSetMessages.current((0, import_runtime_client_gql7.aguiToGQL)(messages2));
1668
+ },
1669
+ [latestSetMessages]
1670
+ );
1671
+ const latestRunChatCompletion = useUpdatedRef(runChatCompletion);
1672
+ const latestRunChatCompletionFunc = useAsyncCallback(() => __async(this, null, function* () {
1673
+ return yield latestRunChatCompletion.current();
1674
+ }), [latestRunChatCompletion]);
1675
+ const reset = (0, import_react9.useCallback)(() => {
1676
+ latestStopFunc();
1677
+ setMessages([]);
1678
+ setRunId(null);
1679
+ setCoagentStatesWithRef({});
1680
+ let initialAgentSession = null;
1681
+ if (agentLock) {
1682
+ initialAgentSession = {
1683
+ agentName: agentLock
1684
+ };
1685
+ }
1686
+ setAgentSession(initialAgentSession);
1687
+ resetSuggestions();
1688
+ }, [
1689
+ latestStopFunc,
1690
+ setMessages,
1691
+ setThreadId,
1692
+ setCoagentStatesWithRef,
1693
+ setAgentSession,
1694
+ agentLock,
1695
+ resetSuggestions
1696
+ ]);
1697
+ const latestReset = useUpdatedRef(reset);
1698
+ const latestResetFunc = (0, import_react9.useCallback)(() => {
1699
+ return latestReset.current();
1700
+ }, [latestReset]);
1701
+ const interrupt = useLangGraphInterruptRender();
1702
+ return {
1703
+ visibleMessages: (0, import_runtime_client_gql7.gqlToAGUI)(messages, actions, coAgentStateRenders),
1704
+ appendMessage: latestAppendFunc,
1705
+ setMessages: latestSetMessagesFunc,
1706
+ reloadMessages: latestReloadFunc,
1707
+ stopGeneration: latestStopFunc,
1708
+ reset: latestResetFunc,
1709
+ deleteMessage: latestDeleteFunc,
1710
+ runChatCompletion: latestRunChatCompletionFunc,
1711
+ isLoading,
1712
+ mcpServers,
1713
+ setMcpServers,
1714
+ suggestions,
1715
+ setSuggestions,
1716
+ generateSuggestions: generateSuggestionsFunc,
1717
+ resetSuggestions,
1718
+ isLoadingSuggestions: isLoadingSuggestionsRef.current,
1719
+ interrupt
1720
+ };
1721
+ }
1722
+ function useUpdatedRef(value) {
1723
+ const ref = (0, import_react9.useRef)(value);
1724
+ (0, import_react9.useEffect)(() => {
1725
+ ref.current = value;
1726
+ }, [value]);
1727
+ return ref;
1728
+ }
1729
+ function defaultSystemMessage(contextString, additionalInstructions) {
1730
+ return `
1731
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
1732
+
1733
+ 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.
1734
+ Always be polite and respectful, and prefer brevity over verbosity.
1735
+
1736
+ The user has provided you with the following context:
1737
+ \`\`\`
1738
+ ${contextString}
1739
+ \`\`\`
1740
+
1741
+ 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.
1742
+
1743
+ Please assist them as best you can.
1744
+
1745
+ 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.
1746
+
1747
+ If you would like to call a function, call it without saying anything else.
1748
+ In case of a function error:
1749
+ - If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.
1750
+ - If the error's source is unclear or seems unrelated to your input, do not attempt further retries.
1751
+ ` + (additionalInstructions ? `
1752
+
1753
+ ${additionalInstructions}` : "");
1754
+ }
1755
+ // Annotate the CommonJS export names for ESM import in node:
1756
+ 0 && (module.exports = {
1757
+ defaultSystemMessage,
1758
+ useCopilotChat
1759
+ });
1760
+ //# sourceMappingURL=use-copilot-chat_internal.js.map