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