@copilotkit/react-core 1.9.2-next.8 → 1.9.2

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 (171) hide show
  1. package/CHANGELOG.md +193 -0
  2. package/dist/{chunk-ERXWDCY6.mjs → chunk-36MGCCPZ.mjs} +2 -2
  3. package/dist/{chunk-CCESTGAM.mjs → chunk-3OQM3NEK.mjs} +2 -2
  4. package/dist/{chunk-7G6RR4HE.mjs → chunk-3Q4F7RF2.mjs} +2 -2
  5. package/dist/chunk-57K2ZJ5F.mjs +348 -0
  6. package/dist/chunk-57K2ZJ5F.mjs.map +1 -0
  7. package/dist/{chunk-UBNRUXEK.mjs → chunk-5BSUSFHM.mjs} +2 -2
  8. package/dist/{chunk-RN3ZRHI7.mjs → chunk-AD7DWJNW.mjs} +66 -25
  9. package/dist/chunk-AD7DWJNW.mjs.map +1 -0
  10. package/dist/{chunk-JPMIAGI6.mjs → chunk-BVK7PLK6.mjs} +2 -2
  11. package/dist/{chunk-VJCHRQ7Q.mjs → chunk-DGON3GZX.mjs} +39 -6
  12. package/dist/chunk-DGON3GZX.mjs.map +1 -0
  13. package/dist/{chunk-XFOTNHYA.mjs → chunk-DKZTPL66.mjs} +2 -2
  14. package/dist/{chunk-XFOTNHYA.mjs.map → chunk-DKZTPL66.mjs.map} +1 -1
  15. package/dist/{chunk-S4BOATBG.mjs → chunk-FN3UA2ZE.mjs} +3 -3
  16. package/dist/{chunk-ISYBUDL4.mjs → chunk-JWAXDYOW.mjs} +11 -12
  17. package/dist/chunk-JWAXDYOW.mjs.map +1 -0
  18. package/dist/{chunk-T4ZKC4X4.mjs → chunk-KIXKBJUV.mjs} +3 -3
  19. package/dist/{chunk-I4JPQECN.mjs → chunk-LFAZTKBK.mjs} +5 -5
  20. package/dist/{chunk-JHIZ5HAI.mjs → chunk-NJA5ZLAZ.mjs} +29 -10
  21. package/dist/chunk-NJA5ZLAZ.mjs.map +1 -0
  22. package/dist/{chunk-ZHEEHGLS.mjs → chunk-QGT4JO7R.mjs} +35 -6
  23. package/dist/chunk-QGT4JO7R.mjs.map +1 -0
  24. package/dist/{chunk-JXF732XG.mjs → chunk-S5QUEHJC.mjs} +195 -77
  25. package/dist/chunk-S5QUEHJC.mjs.map +1 -0
  26. package/dist/{chunk-QQZLIEXK.mjs → chunk-SJJNFYGQ.mjs} +3 -3
  27. package/dist/{chunk-CMQV4XNY.mjs → chunk-VDADWRS3.mjs} +2 -2
  28. package/dist/chunk-YAF2LATQ.mjs +310 -0
  29. package/dist/chunk-YAF2LATQ.mjs.map +1 -0
  30. package/dist/{chunk-VF6UPRKM.mjs → chunk-ZGMZ5WJI.mjs} +4 -4
  31. package/dist/components/copilot-provider/copilot-messages.js +37 -4
  32. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  33. package/dist/components/copilot-provider/copilot-messages.mjs +3 -3
  34. package/dist/components/copilot-provider/copilotkit-props.d.ts +14 -9
  35. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  36. package/dist/components/copilot-provider/copilotkit.d.ts +1 -1
  37. package/dist/components/copilot-provider/copilotkit.js +354 -258
  38. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  39. package/dist/components/copilot-provider/copilotkit.mjs +10 -10
  40. package/dist/components/copilot-provider/index.d.ts +1 -1
  41. package/dist/components/copilot-provider/index.js +354 -258
  42. package/dist/components/copilot-provider/index.js.map +1 -1
  43. package/dist/components/copilot-provider/index.mjs +10 -10
  44. package/dist/components/error-boundary/error-boundary.js +135 -146
  45. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  46. package/dist/components/error-boundary/error-boundary.mjs +4 -4
  47. package/dist/components/error-boundary/error-utils.js.map +1 -1
  48. package/dist/components/error-boundary/error-utils.mjs +2 -2
  49. package/dist/components/index.d.ts +1 -1
  50. package/dist/components/index.js +354 -258
  51. package/dist/components/index.js.map +1 -1
  52. package/dist/components/index.mjs +10 -10
  53. package/dist/components/toast/toast-provider.js +118 -85
  54. package/dist/components/toast/toast-provider.js.map +1 -1
  55. package/dist/components/toast/toast-provider.mjs +1 -1
  56. package/dist/components/usage-banner.js +135 -146
  57. package/dist/components/usage-banner.js.map +1 -1
  58. package/dist/components/usage-banner.mjs +1 -1
  59. package/dist/context/copilot-context.d.ts +1 -1
  60. package/dist/context/copilot-context.js +1 -1
  61. package/dist/context/copilot-context.js.map +1 -1
  62. package/dist/context/copilot-context.mjs +1 -1
  63. package/dist/context/index.d.ts +1 -1
  64. package/dist/context/index.js +1 -1
  65. package/dist/context/index.js.map +1 -1
  66. package/dist/context/index.mjs +1 -1
  67. package/dist/{copilot-context-3da805ab.d.ts → copilot-context-3ab4fdf5.d.ts} +3 -3
  68. package/dist/hooks/index.d.ts +1 -1
  69. package/dist/hooks/index.js +249 -88
  70. package/dist/hooks/index.js.map +1 -1
  71. package/dist/hooks/index.mjs +32 -32
  72. package/dist/hooks/use-chat.d.ts +1 -1
  73. package/dist/hooks/use-chat.js +287 -174
  74. package/dist/hooks/use-chat.js.map +1 -1
  75. package/dist/hooks/use-chat.mjs +5 -5
  76. package/dist/hooks/use-coagent-state-render.js +1 -1
  77. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  78. package/dist/hooks/use-coagent-state-render.mjs +3 -3
  79. package/dist/hooks/use-coagent.d.ts +1 -1
  80. package/dist/hooks/use-coagent.js +224 -82
  81. package/dist/hooks/use-coagent.js.map +1 -1
  82. package/dist/hooks/use-coagent.mjs +14 -14
  83. package/dist/hooks/use-copilot-action.js +26 -7
  84. package/dist/hooks/use-copilot-action.js.map +1 -1
  85. package/dist/hooks/use-copilot-action.mjs +4 -4
  86. package/dist/hooks/use-copilot-additional-instructions.js +1 -1
  87. package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
  88. package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
  89. package/dist/hooks/use-copilot-authenticated-action.js +26 -7
  90. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  91. package/dist/hooks/use-copilot-authenticated-action.mjs +5 -5
  92. package/dist/hooks/use-copilot-chat.d.ts +1 -1
  93. package/dist/hooks/use-copilot-chat.js +195 -82
  94. package/dist/hooks/use-copilot-chat.js.map +1 -1
  95. package/dist/hooks/use-copilot-chat.mjs +13 -13
  96. package/dist/hooks/use-copilot-readable.js +1 -1
  97. package/dist/hooks/use-copilot-readable.js.map +1 -1
  98. package/dist/hooks/use-copilot-readable.mjs +2 -2
  99. package/dist/hooks/use-copilot-runtime-client.d.ts +2 -2
  100. package/dist/hooks/use-copilot-runtime-client.js +8 -8
  101. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  102. package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
  103. package/dist/hooks/use-langgraph-interrupt-render.js +1 -1
  104. package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
  105. package/dist/hooks/use-langgraph-interrupt-render.mjs +2 -2
  106. package/dist/hooks/use-langgraph-interrupt.d.ts +1 -1
  107. package/dist/hooks/use-langgraph-interrupt.js +195 -82
  108. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  109. package/dist/hooks/use-langgraph-interrupt.mjs +14 -14
  110. package/dist/hooks/use-make-copilot-document-readable.js +1 -1
  111. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  112. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  113. package/dist/index.d.ts +1 -1
  114. package/dist/index.js +593 -336
  115. package/dist/index.js.map +1 -1
  116. package/dist/index.mjs +33 -33
  117. package/dist/lib/copilot-task.d.ts +1 -1
  118. package/dist/lib/copilot-task.js.map +1 -1
  119. package/dist/lib/copilot-task.mjs +11 -11
  120. package/dist/lib/index.d.ts +1 -1
  121. package/dist/lib/index.js.map +1 -1
  122. package/dist/lib/index.mjs +11 -11
  123. package/dist/setupTests.d.ts +2 -0
  124. package/dist/setupTests.js +26 -0
  125. package/dist/setupTests.js.map +1 -0
  126. package/dist/setupTests.mjs +24 -0
  127. package/dist/setupTests.mjs.map +1 -0
  128. package/dist/types/interrupt-action.d.ts +1 -1
  129. package/dist/utils/extract.d.ts +1 -1
  130. package/dist/utils/extract.js.map +1 -1
  131. package/dist/utils/extract.mjs +10 -10
  132. package/dist/utils/index.d.ts +1 -1
  133. package/dist/utils/index.js.map +1 -1
  134. package/dist/utils/index.mjs +10 -10
  135. package/jest.config.js +4 -0
  136. package/package.json +6 -3
  137. package/src/components/copilot-provider/__tests__/{copilotkit-trace.test.tsx → copilotkit-error.test.tsx} +17 -17
  138. package/src/components/copilot-provider/copilot-messages.tsx +43 -4
  139. package/src/components/copilot-provider/copilotkit-props.tsx +13 -8
  140. package/src/components/copilot-provider/copilotkit.tsx +61 -19
  141. package/src/components/toast/toast-provider.tsx +49 -24
  142. package/src/components/usage-banner.tsx +144 -147
  143. package/src/context/copilot-context.tsx +4 -4
  144. package/src/hooks/__tests__/use-coagent-config.test.ts +284 -0
  145. package/src/hooks/use-chat.ts +249 -61
  146. package/src/hooks/use-coagent.ts +41 -0
  147. package/src/hooks/use-copilot-action.ts +51 -9
  148. package/src/hooks/use-copilot-runtime-client.ts +12 -50
  149. package/src/setupTests.ts +26 -0
  150. package/tsconfig.json +5 -2
  151. package/dist/chunk-HD2GE3DK.mjs +0 -359
  152. package/dist/chunk-HD2GE3DK.mjs.map +0 -1
  153. package/dist/chunk-ISYBUDL4.mjs.map +0 -1
  154. package/dist/chunk-JHIZ5HAI.mjs.map +0 -1
  155. package/dist/chunk-JXF732XG.mjs.map +0 -1
  156. package/dist/chunk-RN3ZRHI7.mjs.map +0 -1
  157. package/dist/chunk-VJCHRQ7Q.mjs.map +0 -1
  158. package/dist/chunk-VRXANACV.mjs +0 -277
  159. package/dist/chunk-VRXANACV.mjs.map +0 -1
  160. package/dist/chunk-ZHEEHGLS.mjs.map +0 -1
  161. /package/dist/{chunk-ERXWDCY6.mjs.map → chunk-36MGCCPZ.mjs.map} +0 -0
  162. /package/dist/{chunk-CCESTGAM.mjs.map → chunk-3OQM3NEK.mjs.map} +0 -0
  163. /package/dist/{chunk-7G6RR4HE.mjs.map → chunk-3Q4F7RF2.mjs.map} +0 -0
  164. /package/dist/{chunk-UBNRUXEK.mjs.map → chunk-5BSUSFHM.mjs.map} +0 -0
  165. /package/dist/{chunk-JPMIAGI6.mjs.map → chunk-BVK7PLK6.mjs.map} +0 -0
  166. /package/dist/{chunk-S4BOATBG.mjs.map → chunk-FN3UA2ZE.mjs.map} +0 -0
  167. /package/dist/{chunk-T4ZKC4X4.mjs.map → chunk-KIXKBJUV.mjs.map} +0 -0
  168. /package/dist/{chunk-I4JPQECN.mjs.map → chunk-LFAZTKBK.mjs.map} +0 -0
  169. /package/dist/{chunk-QQZLIEXK.mjs.map → chunk-SJJNFYGQ.mjs.map} +0 -0
  170. /package/dist/{chunk-CMQV4XNY.mjs.map → chunk-VDADWRS3.mjs.map} +0 -0
  171. /package/dist/{chunk-VF6UPRKM.mjs.map → chunk-ZGMZ5WJI.mjs.map} +0 -0
@@ -83,6 +83,7 @@ __export(use_chat_exports, {
83
83
  });
84
84
  module.exports = __toCommonJS(use_chat_exports);
85
85
  var import_react5 = require("react");
86
+ var import_react_dom = require("react-dom");
86
87
  var import_shared4 = require("@copilotkit/shared");
87
88
  var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
88
89
 
@@ -111,16 +112,104 @@ function processActionsForRuntimeRequest(actions) {
111
112
  return filteredActions;
112
113
  }
113
114
 
115
+ // src/context/copilot-context.tsx
116
+ var import_react = __toESM(require("react"));
117
+ var emptyCopilotContext = {
118
+ actions: {},
119
+ setAction: () => {
120
+ },
121
+ removeAction: () => {
122
+ },
123
+ coAgentStateRenders: {},
124
+ setCoAgentStateRender: () => {
125
+ },
126
+ removeCoAgentStateRender: () => {
127
+ },
128
+ chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
129
+ getContextString: (documents, categories) => returnAndThrowInDebug(""),
130
+ addContext: () => "",
131
+ removeContext: () => {
132
+ },
133
+ getAllContext: () => [],
134
+ getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
135
+ })),
136
+ isLoading: false,
137
+ setIsLoading: () => returnAndThrowInDebug(false),
138
+ chatInstructions: "",
139
+ setChatInstructions: () => returnAndThrowInDebug(""),
140
+ additionalInstructions: [],
141
+ setAdditionalInstructions: () => returnAndThrowInDebug([]),
142
+ getDocumentsContext: (categories) => returnAndThrowInDebug([]),
143
+ addDocumentContext: () => returnAndThrowInDebug(""),
144
+ removeDocumentContext: () => {
145
+ },
146
+ runtimeClient: {},
147
+ copilotApiConfig: new class {
148
+ get chatApiEndpoint() {
149
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
150
+ }
151
+ get headers() {
152
+ return {};
153
+ }
154
+ get body() {
155
+ return {};
156
+ }
157
+ }(),
158
+ chatSuggestionConfiguration: {},
159
+ addChatSuggestionConfiguration: () => {
160
+ },
161
+ removeChatSuggestionConfiguration: () => {
162
+ },
163
+ showDevConsole: false,
164
+ coagentStates: {},
165
+ setCoagentStates: () => {
166
+ },
167
+ coagentStatesRef: { current: {} },
168
+ setCoagentStatesWithRef: () => {
169
+ },
170
+ agentSession: null,
171
+ setAgentSession: () => {
172
+ },
173
+ forwardedParameters: {},
174
+ agentLock: null,
175
+ threadId: "",
176
+ setThreadId: () => {
177
+ },
178
+ runId: null,
179
+ setRunId: () => {
180
+ },
181
+ chatAbortControllerRef: { current: null },
182
+ availableAgents: [],
183
+ extensions: {},
184
+ setExtensions: () => {
185
+ },
186
+ langGraphInterruptAction: null,
187
+ setLangGraphInterruptAction: () => null,
188
+ removeLangGraphInterruptAction: () => null,
189
+ onError: void 0
190
+ };
191
+ var CopilotContext = import_react.default.createContext(emptyCopilotContext);
192
+ function useCopilotContext() {
193
+ const context = import_react.default.useContext(CopilotContext);
194
+ if (context === emptyCopilotContext) {
195
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
196
+ }
197
+ return context;
198
+ }
199
+ function returnAndThrowInDebug(_value) {
200
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
201
+ }
202
+
114
203
  // src/hooks/use-copilot-runtime-client.ts
115
204
  var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
116
205
 
117
206
  // src/components/toast/toast-provider.tsx
118
- var import_react = require("react");
207
+ var import_react2 = require("react");
119
208
  var import_shared2 = require("@copilotkit/shared");
120
209
  var import_jsx_runtime = require("react/jsx-runtime");
121
- var ToastContext = (0, import_react.createContext)(void 0);
210
+ var ToastContext = (0, import_react2.createContext)(void 0);
122
211
  function useToast() {
123
- const context = (0, import_react.useContext)(ToastContext);
212
+ const context = (0, import_react2.useContext)(ToastContext);
124
213
  if (!context) {
125
214
  throw new Error("useToast must be used within a ToastProvider");
126
215
  }
@@ -128,7 +217,7 @@ function useToast() {
128
217
  }
129
218
 
130
219
  // src/hooks/use-copilot-runtime-client.ts
131
- var import_react2 = require("react");
220
+ var import_react3 = require("react");
132
221
  var import_shared3 = require("@copilotkit/shared");
133
222
 
134
223
  // src/utils/dev-console.ts
@@ -139,13 +228,13 @@ function shouldShowDevConsole(showDevConsole) {
139
228
  // src/hooks/use-copilot-runtime-client.ts
140
229
  var useCopilotRuntimeClient = (options) => {
141
230
  const { setBannerError } = useToast();
142
- const _a = options, { showDevConsole, onTrace } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onTrace"]);
143
- const lastStructuredErrorRef = (0, import_react2.useRef)(null);
231
+ const _a = options, { showDevConsole, onError } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onError"]);
232
+ const lastStructuredErrorRef = (0, import_react3.useRef)(null);
144
233
  const traceUIError = (error, originalError) => __async(void 0, null, function* () {
145
- if (!onTrace || !runtimeOptions.publicApiKey)
234
+ if (!onError || !runtimeOptions.publicApiKey)
146
235
  return;
147
236
  try {
148
- const traceEvent = {
237
+ const errorEvent = {
149
238
  type: "error",
150
239
  timestamp: Date.now(),
151
240
  context: {
@@ -156,19 +245,19 @@ var useCopilotRuntimeClient = (options) => {
156
245
  startTime: Date.now()
157
246
  },
158
247
  technical: {
159
- environment: process.env.NODE_ENV,
248
+ environment: "browser",
160
249
  userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
161
250
  stackTrace: originalError instanceof Error ? originalError.stack : void 0
162
251
  }
163
252
  },
164
253
  error
165
254
  };
166
- yield onTrace(traceEvent);
167
- } catch (traceError) {
168
- console.error("Error in onTrace handler:", traceError);
255
+ yield onError(errorEvent);
256
+ } catch (error2) {
257
+ console.error("Error in onError handler:", error2);
169
258
  }
170
259
  });
171
- const runtimeClient = (0, import_react2.useMemo)(() => {
260
+ const runtimeClient = (0, import_react3.useMemo)(() => {
172
261
  return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, runtimeOptions), {
173
262
  handleGQLErrors: (error) => {
174
263
  var _a2;
@@ -229,7 +318,7 @@ var useCopilotRuntimeClient = (options) => {
229
318
  setBannerError(warningError);
230
319
  }
231
320
  }));
232
- }, [runtimeOptions, setBannerError, showDevConsole, onTrace]);
321
+ }, [runtimeOptions, setBannerError, showDevConsole, onError]);
233
322
  return runtimeClient;
234
323
  };
235
324
  function createStructuredError(gqlError) {
@@ -256,94 +345,6 @@ function createStructuredError(gqlError) {
256
345
  return null;
257
346
  }
258
347
 
259
- // src/context/copilot-context.tsx
260
- var import_react3 = __toESM(require("react"));
261
- var emptyCopilotContext = {
262
- actions: {},
263
- setAction: () => {
264
- },
265
- removeAction: () => {
266
- },
267
- coAgentStateRenders: {},
268
- setCoAgentStateRender: () => {
269
- },
270
- removeCoAgentStateRender: () => {
271
- },
272
- chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
273
- getContextString: (documents, categories) => returnAndThrowInDebug(""),
274
- addContext: () => "",
275
- removeContext: () => {
276
- },
277
- getAllContext: () => [],
278
- getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
279
- })),
280
- isLoading: false,
281
- setIsLoading: () => returnAndThrowInDebug(false),
282
- chatInstructions: "",
283
- setChatInstructions: () => returnAndThrowInDebug(""),
284
- additionalInstructions: [],
285
- setAdditionalInstructions: () => returnAndThrowInDebug([]),
286
- getDocumentsContext: (categories) => returnAndThrowInDebug([]),
287
- addDocumentContext: () => returnAndThrowInDebug(""),
288
- removeDocumentContext: () => {
289
- },
290
- runtimeClient: {},
291
- copilotApiConfig: new class {
292
- get chatApiEndpoint() {
293
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
294
- }
295
- get headers() {
296
- return {};
297
- }
298
- get body() {
299
- return {};
300
- }
301
- }(),
302
- chatSuggestionConfiguration: {},
303
- addChatSuggestionConfiguration: () => {
304
- },
305
- removeChatSuggestionConfiguration: () => {
306
- },
307
- showDevConsole: false,
308
- coagentStates: {},
309
- setCoagentStates: () => {
310
- },
311
- coagentStatesRef: { current: {} },
312
- setCoagentStatesWithRef: () => {
313
- },
314
- agentSession: null,
315
- setAgentSession: () => {
316
- },
317
- forwardedParameters: {},
318
- agentLock: null,
319
- threadId: "",
320
- setThreadId: () => {
321
- },
322
- runId: null,
323
- setRunId: () => {
324
- },
325
- chatAbortControllerRef: { current: null },
326
- availableAgents: [],
327
- extensions: {},
328
- setExtensions: () => {
329
- },
330
- langGraphInterruptAction: null,
331
- setLangGraphInterruptAction: () => null,
332
- removeLangGraphInterruptAction: () => null,
333
- onTrace: void 0
334
- };
335
- var CopilotContext = import_react3.default.createContext(emptyCopilotContext);
336
- function useCopilotContext() {
337
- const context = import_react3.default.useContext(CopilotContext);
338
- if (context === emptyCopilotContext) {
339
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
340
- }
341
- return context;
342
- }
343
- function returnAndThrowInDebug(_value) {
344
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
345
- }
346
-
347
348
  // src/components/error-boundary/error-utils.tsx
348
349
  var import_react4 = require("react");
349
350
 
@@ -489,6 +490,35 @@ function useChat(options) {
489
490
  } = options;
490
491
  const runChatCompletionRef = (0, import_react5.useRef)();
491
492
  const addErrorToast = useErrorToast();
493
+ const { setBannerError } = useToast();
494
+ const { onError } = useCopilotContext();
495
+ const traceUIError = (error, originalError) => __async(this, null, function* () {
496
+ if (!onError || !(copilotConfig == null ? void 0 : copilotConfig.publicApiKey))
497
+ return;
498
+ try {
499
+ const traceEvent = {
500
+ type: "error",
501
+ timestamp: Date.now(),
502
+ context: {
503
+ source: "ui",
504
+ request: {
505
+ operation: "useChatCompletion",
506
+ url: copilotConfig.chatApiEndpoint,
507
+ startTime: Date.now()
508
+ },
509
+ technical: {
510
+ environment: "browser",
511
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
512
+ stackTrace: originalError instanceof Error ? originalError.stack : void 0
513
+ }
514
+ },
515
+ error
516
+ };
517
+ yield onError(traceEvent);
518
+ } catch (traceError) {
519
+ console.error("Error in use-chat onError handler:", traceError);
520
+ }
521
+ });
492
522
  const agentSessionRef = (0, import_react5.useRef)(agentSession);
493
523
  agentSessionRef.current = agentSession;
494
524
  const runIdRef = (0, import_react5.useRef)(runId);
@@ -508,7 +538,7 @@ function useChat(options) {
508
538
  const pendingAppendsRef = (0, import_react5.useRef)([]);
509
539
  const runChatCompletion = useAsyncCallback(
510
540
  (previousMessages) => __async(this, null, function* () {
511
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
541
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
512
542
  setIsLoading(true);
513
543
  const interruptEvent = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event;
514
544
  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) {
@@ -640,20 +670,53 @@ function useChat(options) {
640
670
  messages2 = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
641
671
  (0, import_runtime_client_gql3.filterAdjacentAgentStateMessages)(rawMessagesResponse)
642
672
  );
643
- if (messages2.length === 0) {
644
- continue;
645
- }
646
673
  newMessages = [];
647
674
  if (((_k = value.generateCopilotResponse.status) == null ? void 0 : _k.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
675
+ const guardrailsReason = ((_l = value.generateCopilotResponse.status.details) == null ? void 0 : _l.guardrailsReason) || "";
648
676
  newMessages = [
649
677
  new import_runtime_client_gql3.TextMessage({
650
678
  role: import_runtime_client_gql3.MessageRole.Assistant,
651
- content: ((_l = value.generateCopilotResponse.status.details) == null ? void 0 : _l.guardrailsReason) || ""
679
+ content: guardrailsReason
652
680
  })
653
681
  ];
682
+ const guardrailsError = new import_shared4.CopilotKitError({
683
+ message: `Guardrails validation failed: ${guardrailsReason}`,
684
+ code: import_shared4.CopilotKitErrorCode.MISUSE
685
+ });
686
+ yield traceUIError(guardrailsError, {
687
+ statusReason: value.generateCopilotResponse.status.reason,
688
+ statusDetails: value.generateCopilotResponse.status.details
689
+ });
654
690
  setMessages([...previousMessages, ...newMessages]);
655
691
  break;
656
- } else {
692
+ }
693
+ if (((_m = value.generateCopilotResponse.status) == null ? void 0 : _m.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "UNKNOWN_ERROR") {
694
+ const errorMessage = ((_n = value.generateCopilotResponse.status.details) == null ? void 0 : _n.description) || "An unknown error occurred";
695
+ const statusDetails = value.generateCopilotResponse.status.details;
696
+ const originalError = (statusDetails == null ? void 0 : statusDetails.originalError) || (statusDetails == null ? void 0 : statusDetails.error);
697
+ const originalCode = (originalError == null ? void 0 : originalError.code) || ((_o = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _o.code);
698
+ const originalSeverity = (originalError == null ? void 0 : originalError.severity) || ((_p = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _p.severity);
699
+ const originalVisibility = (originalError == null ? void 0 : originalError.visibility) || ((_q = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _q.visibility);
700
+ let errorCode = import_shared4.CopilotKitErrorCode.NETWORK_ERROR;
701
+ if (originalCode && Object.values(import_shared4.CopilotKitErrorCode).includes(originalCode)) {
702
+ errorCode = originalCode;
703
+ }
704
+ const structuredError = new import_shared4.CopilotKitError({
705
+ message: errorMessage,
706
+ code: errorCode,
707
+ severity: originalSeverity,
708
+ visibility: originalVisibility
709
+ });
710
+ setBannerError(structuredError);
711
+ yield traceUIError(structuredError, {
712
+ statusReason: value.generateCopilotResponse.status.reason,
713
+ statusDetails: value.generateCopilotResponse.status.details,
714
+ originalErrorCode: originalCode,
715
+ preservedStructure: !!originalCode
716
+ });
717
+ setIsLoading(false);
718
+ break;
719
+ } else if (messages2.length > 0) {
657
720
  newMessages = [...messages2];
658
721
  for (const message of messages2) {
659
722
  if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
@@ -675,17 +738,22 @@ function useChat(options) {
675
738
  lastAgentStateMessage.state.messages
676
739
  );
677
740
  }
678
- setCoagentStatesWithRef((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
679
- [lastAgentStateMessage.agentName]: {
680
- name: lastAgentStateMessage.agentName,
681
- state: lastAgentStateMessage.state,
682
- running: lastAgentStateMessage.running,
683
- active: lastAgentStateMessage.active,
684
- threadId: lastAgentStateMessage.threadId,
685
- nodeName: lastAgentStateMessage.nodeName,
686
- runId: lastAgentStateMessage.runId
687
- }
688
- }));
741
+ setCoagentStatesWithRef((prevAgentStates) => {
742
+ var _a2;
743
+ return __spreadProps(__spreadValues({}, prevAgentStates), {
744
+ [lastAgentStateMessage.agentName]: {
745
+ name: lastAgentStateMessage.agentName,
746
+ state: lastAgentStateMessage.state,
747
+ running: lastAgentStateMessage.running,
748
+ active: lastAgentStateMessage.active,
749
+ threadId: lastAgentStateMessage.threadId,
750
+ nodeName: lastAgentStateMessage.nodeName,
751
+ runId: lastAgentStateMessage.runId,
752
+ // Preserve existing config from previous state
753
+ config: (_a2 = prevAgentStates[lastAgentStateMessage.agentName]) == null ? void 0 : _a2.config
754
+ }
755
+ });
756
+ });
689
757
  if (lastAgentStateMessage.running) {
690
758
  setAgentSession({
691
759
  threadId: lastAgentStateMessage.threadId,
@@ -715,6 +783,39 @@ function useChat(options) {
715
783
  newMessages
716
784
  );
717
785
  let didExecuteAction = false;
786
+ const executeActionFromMessage = (currentAction, actionMessage) => __async(this, null, function* () {
787
+ var _a2;
788
+ const isInterruptAction = interruptMessages.find((m) => m.id === actionMessage.id);
789
+ followUp = (_a2 = currentAction == null ? void 0 : currentAction.followUp) != null ? _a2 : !isInterruptAction;
790
+ if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
791
+ currentAction._setActivatingMessageId(actionMessage.id);
792
+ }
793
+ const resultMessage = yield executeAction({
794
+ onFunctionCall,
795
+ message: actionMessage,
796
+ chatAbortControllerRef,
797
+ onError: (error) => {
798
+ addErrorToast([error]);
799
+ console.error(`Failed to execute action ${actionMessage.name}: ${error}`);
800
+ },
801
+ setMessages,
802
+ getFinalMessages: () => finalMessages,
803
+ isRenderAndWait: (currentAction == null ? void 0 : currentAction._isRenderAndWait) || false
804
+ });
805
+ didExecuteAction = true;
806
+ const messageIndex = finalMessages.findIndex((msg) => msg.id === actionMessage.id);
807
+ finalMessages.splice(messageIndex + 1, 0, resultMessage);
808
+ if (currentAction == null ? void 0 : currentAction._isRenderAndWait) {
809
+ const messagesForImmediateUpdate = [...finalMessages];
810
+ (0, import_react_dom.flushSync)(() => {
811
+ setMessages(messagesForImmediateUpdate);
812
+ });
813
+ }
814
+ if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
815
+ currentAction._setActivatingMessageId(null);
816
+ }
817
+ return resultMessage;
818
+ });
718
819
  if (onFunctionCall) {
719
820
  const lastMessages = [];
720
821
  for (let i = finalMessages.length - 1; i >= 0; i--) {
@@ -731,37 +832,28 @@ function useChat(options) {
731
832
  (action2) => action2.name === message.name
732
833
  );
733
834
  const currentResultMessagePairedFeAction = message.isResultMessage() ? getPairedFeAction(actions, message) : null;
734
- const executeActionFromMessage = (action2, message2) => __async(this, null, function* () {
735
- var _a2;
736
- const isInterruptAction = interruptMessages.find((m) => m.id === message2.id);
737
- followUp = (_a2 = action2 == null ? void 0 : action2.followUp) != null ? _a2 : !isInterruptAction;
738
- const resultMessage = yield executeAction({
739
- onFunctionCall,
740
- previousMessages,
741
- message: message2,
742
- chatAbortControllerRef,
743
- onError: (error) => {
744
- addErrorToast([error]);
745
- console.error(`Failed to execute action ${message2.name}: ${error}`);
746
- }
747
- });
748
- didExecuteAction = true;
749
- const messageIndex = finalMessages.findIndex((msg) => msg.id === message2.id);
750
- finalMessages.splice(messageIndex + 1, 0, resultMessage);
751
- return resultMessage;
752
- });
753
835
  if (action && message.isActionExecutionMessage()) {
754
- const resultMessage = yield executeActionFromMessage(action, message);
755
- const pairedFeAction = getPairedFeAction(actions, resultMessage);
756
- if (pairedFeAction) {
757
- const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
758
- name: pairedFeAction.name,
759
- arguments: (0, import_shared4.parseJson)(resultMessage.result, resultMessage.result),
760
- status: message.status,
761
- createdAt: message.createdAt,
762
- parentMessageId: message.parentMessageId
763
- });
764
- yield executeActionFromMessage(pairedFeAction, newExecutionMessage);
836
+ const isRenderAndWaitAction = (action == null ? void 0 : action._isRenderAndWait) || false;
837
+ const alreadyProcessed = isRenderAndWaitAction && finalMessages.some(
838
+ (fm) => fm.isResultMessage() && fm.actionExecutionId === message.id
839
+ );
840
+ if (alreadyProcessed) {
841
+ } else {
842
+ const resultMessage = yield executeActionFromMessage(
843
+ action,
844
+ message
845
+ );
846
+ const pairedFeAction = getPairedFeAction(actions, resultMessage);
847
+ if (pairedFeAction) {
848
+ const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
849
+ name: pairedFeAction.name,
850
+ arguments: (0, import_shared4.parseJson)(resultMessage.result, resultMessage.result),
851
+ status: message.status,
852
+ createdAt: message.createdAt,
853
+ parentMessageId: message.parentMessageId
854
+ });
855
+ yield executeActionFromMessage(pairedFeAction, newExecutionMessage);
856
+ }
765
857
  }
766
858
  } else if (message.isResultMessage() && currentResultMessagePairedFeAction) {
767
859
  const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
@@ -779,16 +871,12 @@ function useChat(options) {
779
871
  }
780
872
  setMessages(finalMessages);
781
873
  }
782
- if (
783
- // if followUp is not explicitly false
784
- followUp !== false && // and we executed an action
785
- (didExecuteAction || // the last message is a server side result
786
- !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage()) && // the user did not stop generation
787
- !((_m = chatAbortControllerRef.current) == null ? void 0 : _m.signal.aborted)
788
- ) {
874
+ if (followUp !== false && (didExecuteAction || // the last message is a server side result
875
+ !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage()) && // the user did not stop generation
876
+ !((_r = chatAbortControllerRef.current) == null ? void 0 : _r.signal.aborted)) {
789
877
  yield new Promise((resolve) => setTimeout(resolve, 10));
790
878
  return yield runChatCompletionRef.current(finalMessages);
791
- } else if ((_n = chatAbortControllerRef.current) == null ? void 0 : _n.signal.aborted) {
879
+ } else if ((_s = chatAbortControllerRef.current) == null ? void 0 : _s.signal.aborted) {
792
880
  const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {
793
881
  if (message.isActionExecutionMessage()) {
794
882
  return finalMessages.find(
@@ -799,7 +887,7 @@ function useChat(options) {
799
887
  });
800
888
  const repairedMessageIds = repairedMessages.map((message) => message.id);
801
889
  setMessages(repairedMessages);
802
- if ((_o = agentSessionRef.current) == null ? void 0 : _o.nodeName) {
890
+ if ((_t = agentSessionRef.current) == null ? void 0 : _t.nodeName) {
803
891
  setAgentSession({
804
892
  threadId: agentSessionRef.current.threadId,
805
893
  agentName: agentSessionRef.current.agentName,
@@ -893,21 +981,35 @@ function useChat(options) {
893
981
  [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
894
982
  );
895
983
  const reload = useAsyncCallback(
896
- (messageId) => __async(this, null, function* () {
984
+ (reloadMessageId) => __async(this, null, function* () {
897
985
  if (isLoading || messages.length === 0) {
898
986
  return;
899
987
  }
900
- const index = messages.findIndex((msg) => msg.id === messageId);
901
- if (index === -1) {
902
- console.warn(`Message with id ${messageId} not found`);
988
+ const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);
989
+ if (reloadMessageIndex === -1) {
990
+ console.warn(`Message with id ${reloadMessageId} not found`);
903
991
  return;
904
992
  }
905
- let newMessages = messages.slice(0, index);
906
- if (newMessages.length > 0 && newMessages[newMessages.length - 1].isAgentStateMessage()) {
907
- newMessages = newMessages.slice(0, newMessages.length - 1);
993
+ const reloadMessageRole = messages[reloadMessageIndex].role;
994
+ if (reloadMessageRole !== import_runtime_client_gql3.MessageRole.Assistant) {
995
+ console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
996
+ return;
908
997
  }
909
- setMessages(newMessages);
910
- return runChatCompletionAndHandleFunctionCall(newMessages);
998
+ let historyCutoff = [];
999
+ if (messages.length > 2) {
1000
+ const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find(
1001
+ (msg) => (
1002
+ // @ts-expect-error -- message has role
1003
+ msg.role === import_runtime_client_gql3.MessageRole.User
1004
+ )
1005
+ );
1006
+ const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(
1007
+ (msg) => msg.id === lastUserMessageBeforeRegenerate.id
1008
+ );
1009
+ historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
1010
+ }
1011
+ setMessages(historyCutoff);
1012
+ return runChatCompletionAndHandleFunctionCall(historyCutoff);
911
1013
  }),
912
1014
  [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
913
1015
  );
@@ -942,20 +1044,31 @@ function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
942
1044
  function executeAction(_0) {
943
1045
  return __async(this, arguments, function* ({
944
1046
  onFunctionCall,
945
- previousMessages,
946
1047
  message,
947
1048
  chatAbortControllerRef,
948
- onError
1049
+ onError,
1050
+ setMessages,
1051
+ getFinalMessages,
1052
+ isRenderAndWait
949
1053
  }) {
950
1054
  let result;
951
1055
  let error = null;
1056
+ const currentMessagesForHandler = getFinalMessages();
1057
+ const handlerReturnedPromise = onFunctionCall({
1058
+ messages: currentMessagesForHandler,
1059
+ name: message.name,
1060
+ args: message.arguments
1061
+ });
1062
+ if (isRenderAndWait) {
1063
+ const currentMessagesForRender = getFinalMessages();
1064
+ (0, import_react_dom.flushSync)(() => {
1065
+ setMessages([...currentMessagesForRender]);
1066
+ });
1067
+ }
952
1068
  try {
953
1069
  result = yield Promise.race([
954
- onFunctionCall({
955
- messages: previousMessages,
956
- name: message.name,
957
- args: message.arguments
958
- }),
1070
+ handlerReturnedPromise,
1071
+ // Await the promise returned by the handler
959
1072
  new Promise(
960
1073
  (resolve) => {
961
1074
  var _a;