@copilotkit/react-core 1.9.2-next.2 → 1.9.2-next.20

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 (170) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/dist/{chunk-UHQMV2CE.mjs → chunk-36MGCCPZ.mjs} +2 -2
  3. package/dist/{chunk-CCESTGAM.mjs → chunk-3OQM3NEK.mjs} +2 -2
  4. package/dist/{chunk-FRZZPPIV.mjs → chunk-3SLA7Q2N.mjs} +2 -2
  5. package/dist/chunk-57K2ZJ5F.mjs +348 -0
  6. package/dist/chunk-57K2ZJ5F.mjs.map +1 -0
  7. package/dist/{chunk-LZDDYZEY.mjs → chunk-5BSUSFHM.mjs} +2 -2
  8. package/dist/{chunk-C6F6EQNA.mjs → chunk-BVK7PLK6.mjs} +2 -2
  9. package/dist/{chunk-6KGEF242.mjs → chunk-DKZTPL66.mjs} +3 -2
  10. package/dist/chunk-DKZTPL66.mjs.map +1 -0
  11. package/dist/{chunk-LDACFA2B.mjs → chunk-FN3UA2ZE.mjs} +3 -3
  12. package/dist/{chunk-RUY6MLHA.mjs → chunk-JWAXDYOW.mjs} +36 -6
  13. package/dist/chunk-JWAXDYOW.mjs.map +1 -0
  14. package/dist/{chunk-4I7PLQF7.mjs → chunk-K42OD3J6.mjs} +5 -5
  15. package/dist/{chunk-2FW7HH6W.mjs → chunk-KIXKBJUV.mjs} +3 -3
  16. package/dist/{chunk-L6QAOAE4.mjs → chunk-KWQPQ4MM.mjs} +69 -25
  17. package/dist/chunk-KWQPQ4MM.mjs.map +1 -0
  18. package/dist/{chunk-MGIXEJWG.mjs → chunk-MTAJI7HV.mjs} +181 -68
  19. package/dist/chunk-MTAJI7HV.mjs.map +1 -0
  20. package/dist/{chunk-T42PN5VN.mjs → chunk-NJA5ZLAZ.mjs} +29 -10
  21. package/dist/chunk-NJA5ZLAZ.mjs.map +1 -0
  22. package/dist/{chunk-NNSXCFQO.mjs → chunk-R2LNRHJP.mjs} +41 -7
  23. package/dist/chunk-R2LNRHJP.mjs.map +1 -0
  24. package/dist/{chunk-QQZLIEXK.mjs → chunk-SJJNFYGQ.mjs} +3 -3
  25. package/dist/{chunk-OUSWPVDT.mjs → chunk-UGJGKBFB.mjs} +4 -4
  26. package/dist/{chunk-Q5D5XQFA.mjs → chunk-VDADWRS3.mjs} +2 -2
  27. package/dist/chunk-YAF2LATQ.mjs +310 -0
  28. package/dist/chunk-YAF2LATQ.mjs.map +1 -0
  29. package/dist/{chunk-CMKIDDQL.mjs → chunk-ZOMEQ3XC.mjs} +11 -8
  30. package/dist/{chunk-CMKIDDQL.mjs.map → chunk-ZOMEQ3XC.mjs.map} +1 -1
  31. package/dist/components/copilot-provider/copilot-messages.js +39 -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 +27 -3
  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 +384 -253
  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 +384 -253
  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 +384 -253
  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 +2 -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 +2 -1
  65. package/dist/context/index.js.map +1 -1
  66. package/dist/context/index.mjs +1 -1
  67. package/dist/{copilot-context-f9b2b4c3.d.ts → copilot-context-3ab4fdf5.d.ts} +6 -2
  68. package/dist/hooks/index.d.ts +1 -1
  69. package/dist/hooks/index.js +232 -71
  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 +295 -156
  74. package/dist/hooks/use-chat.js.map +1 -1
  75. package/dist/hooks/use-chat.mjs +6 -6
  76. package/dist/hooks/use-coagent-state-render.js +2 -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 +207 -65
  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 +27 -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 +2 -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 +27 -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 +204 -65
  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 +2 -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 -0
  100. package/dist/hooks/use-copilot-runtime-client.js +52 -2
  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 +2 -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 +204 -65
  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 +2 -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 +581 -320
  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/types/interrupt-action.d.ts +1 -1
  124. package/dist/utils/extract.d.ts +1 -1
  125. package/dist/utils/extract.js.map +1 -1
  126. package/dist/utils/extract.mjs +10 -10
  127. package/dist/utils/index.d.ts +1 -1
  128. package/dist/utils/index.js.map +1 -1
  129. package/dist/utils/index.mjs +10 -10
  130. package/jest.config.js +7 -3
  131. package/package.json +4 -3
  132. package/src/components/copilot-provider/__tests__/copilotkit-error.test.tsx +75 -0
  133. package/src/components/copilot-provider/copilot-messages.tsx +46 -5
  134. package/src/components/copilot-provider/copilotkit-props.tsx +27 -1
  135. package/src/components/copilot-provider/copilotkit.tsx +64 -18
  136. package/src/components/toast/toast-provider.tsx +49 -24
  137. package/src/components/usage-banner.tsx +144 -147
  138. package/src/context/copilot-context.tsx +8 -2
  139. package/src/hooks/use-chat.ts +247 -61
  140. package/src/hooks/use-coagent.ts +5 -0
  141. package/src/hooks/use-copilot-action.ts +51 -9
  142. package/src/hooks/use-copilot-runtime-client.ts +41 -40
  143. package/tsconfig.json +4 -8
  144. package/tsup.config.ts +6 -6
  145. package/dist/chunk-6KGEF242.mjs.map +0 -1
  146. package/dist/chunk-HD2GE3DK.mjs +0 -359
  147. package/dist/chunk-HD2GE3DK.mjs.map +0 -1
  148. package/dist/chunk-L6QAOAE4.mjs.map +0 -1
  149. package/dist/chunk-MGIXEJWG.mjs.map +0 -1
  150. package/dist/chunk-NNSXCFQO.mjs.map +0 -1
  151. package/dist/chunk-RUY6MLHA.mjs.map +0 -1
  152. package/dist/chunk-T42PN5VN.mjs.map +0 -1
  153. package/dist/chunk-VRXANACV.mjs +0 -277
  154. package/dist/chunk-VRXANACV.mjs.map +0 -1
  155. package/dist/utils/utils.test.d.ts +0 -2
  156. package/dist/utils/utils.test.js +0 -9
  157. package/dist/utils/utils.test.js.map +0 -1
  158. package/dist/utils/utils.test.mjs +0 -7
  159. package/dist/utils/utils.test.mjs.map +0 -1
  160. /package/dist/{chunk-UHQMV2CE.mjs.map → chunk-36MGCCPZ.mjs.map} +0 -0
  161. /package/dist/{chunk-CCESTGAM.mjs.map → chunk-3OQM3NEK.mjs.map} +0 -0
  162. /package/dist/{chunk-FRZZPPIV.mjs.map → chunk-3SLA7Q2N.mjs.map} +0 -0
  163. /package/dist/{chunk-LZDDYZEY.mjs.map → chunk-5BSUSFHM.mjs.map} +0 -0
  164. /package/dist/{chunk-C6F6EQNA.mjs.map → chunk-BVK7PLK6.mjs.map} +0 -0
  165. /package/dist/{chunk-LDACFA2B.mjs.map → chunk-FN3UA2ZE.mjs.map} +0 -0
  166. /package/dist/{chunk-4I7PLQF7.mjs.map → chunk-K42OD3J6.mjs.map} +0 -0
  167. /package/dist/{chunk-2FW7HH6W.mjs.map → chunk-KIXKBJUV.mjs.map} +0 -0
  168. /package/dist/{chunk-QQZLIEXK.mjs.map → chunk-SJJNFYGQ.mjs.map} +0 -0
  169. /package/dist/{chunk-OUSWPVDT.mjs.map → chunk-UGJGKBFB.mjs.map} +0 -0
  170. /package/dist/{chunk-Q5D5XQFA.mjs.map → chunk-VDADWRS3.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,9 +228,36 @@ 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 } = _a, runtimeOptions = __objRest(_a, ["showDevConsole"]);
143
- const lastStructuredErrorRef = (0, import_react2.useRef)(null);
144
- const runtimeClient = (0, import_react2.useMemo)(() => {
231
+ const _a = options, { showDevConsole, onError } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onError"]);
232
+ const lastStructuredErrorRef = (0, import_react3.useRef)(null);
233
+ const traceUIError = (error, originalError) => __async(void 0, null, function* () {
234
+ if (!onError || !runtimeOptions.publicApiKey)
235
+ return;
236
+ try {
237
+ const errorEvent = {
238
+ type: "error",
239
+ timestamp: Date.now(),
240
+ context: {
241
+ source: "ui",
242
+ request: {
243
+ operation: "runtimeClient",
244
+ url: runtimeOptions.url,
245
+ startTime: Date.now()
246
+ },
247
+ technical: {
248
+ environment: "browser",
249
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
250
+ stackTrace: originalError instanceof Error ? originalError.stack : void 0
251
+ }
252
+ },
253
+ error
254
+ };
255
+ yield onError(errorEvent);
256
+ } catch (error2) {
257
+ console.error("Error in onError handler:", error2);
258
+ }
259
+ });
260
+ const runtimeClient = (0, import_react3.useMemo)(() => {
145
261
  return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, runtimeOptions), {
146
262
  handleGQLErrors: (error) => {
147
263
  var _a2;
@@ -168,12 +284,14 @@ var useCopilotRuntimeClient = (options) => {
168
284
  const ckError = createStructuredError(gqlError);
169
285
  if (ckError) {
170
286
  setBannerError(ckError);
287
+ traceUIError(ckError, gqlError);
171
288
  } else {
172
289
  const fallbackError = new import_shared3.CopilotKitError({
173
290
  message: gqlError.message,
174
291
  code: import_shared3.CopilotKitErrorCode.UNKNOWN
175
292
  });
176
293
  setBannerError(fallbackError);
294
+ traceUIError(fallbackError, gqlError);
177
295
  }
178
296
  };
179
297
  graphQLErrors.forEach(routeError);
@@ -187,6 +305,7 @@ var useCopilotRuntimeClient = (options) => {
187
305
  code: import_shared3.CopilotKitErrorCode.UNKNOWN
188
306
  });
189
307
  setBannerError(fallbackError);
308
+ traceUIError(fallbackError, error);
190
309
  }
191
310
  }
192
311
  },
@@ -199,7 +318,7 @@ var useCopilotRuntimeClient = (options) => {
199
318
  setBannerError(warningError);
200
319
  }
201
320
  }));
202
- }, [runtimeOptions, setBannerError, showDevConsole]);
321
+ }, [runtimeOptions, setBannerError, showDevConsole, onError]);
203
322
  return runtimeClient;
204
323
  };
205
324
  function createStructuredError(gqlError) {
@@ -226,93 +345,6 @@ function createStructuredError(gqlError) {
226
345
  return null;
227
346
  }
228
347
 
229
- // src/context/copilot-context.tsx
230
- var import_react3 = __toESM(require("react"));
231
- var emptyCopilotContext = {
232
- actions: {},
233
- setAction: () => {
234
- },
235
- removeAction: () => {
236
- },
237
- coAgentStateRenders: {},
238
- setCoAgentStateRender: () => {
239
- },
240
- removeCoAgentStateRender: () => {
241
- },
242
- chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
243
- getContextString: (documents, categories) => returnAndThrowInDebug(""),
244
- addContext: () => "",
245
- removeContext: () => {
246
- },
247
- getAllContext: () => [],
248
- getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
249
- })),
250
- isLoading: false,
251
- setIsLoading: () => returnAndThrowInDebug(false),
252
- chatInstructions: "",
253
- setChatInstructions: () => returnAndThrowInDebug(""),
254
- additionalInstructions: [],
255
- setAdditionalInstructions: () => returnAndThrowInDebug([]),
256
- getDocumentsContext: (categories) => returnAndThrowInDebug([]),
257
- addDocumentContext: () => returnAndThrowInDebug(""),
258
- removeDocumentContext: () => {
259
- },
260
- runtimeClient: {},
261
- copilotApiConfig: new class {
262
- get chatApiEndpoint() {
263
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
264
- }
265
- get headers() {
266
- return {};
267
- }
268
- get body() {
269
- return {};
270
- }
271
- }(),
272
- chatSuggestionConfiguration: {},
273
- addChatSuggestionConfiguration: () => {
274
- },
275
- removeChatSuggestionConfiguration: () => {
276
- },
277
- showDevConsole: false,
278
- coagentStates: {},
279
- setCoagentStates: () => {
280
- },
281
- coagentStatesRef: { current: {} },
282
- setCoagentStatesWithRef: () => {
283
- },
284
- agentSession: null,
285
- setAgentSession: () => {
286
- },
287
- forwardedParameters: {},
288
- agentLock: null,
289
- threadId: "",
290
- setThreadId: () => {
291
- },
292
- runId: null,
293
- setRunId: () => {
294
- },
295
- chatAbortControllerRef: { current: null },
296
- availableAgents: [],
297
- extensions: {},
298
- setExtensions: () => {
299
- },
300
- langGraphInterruptAction: null,
301
- setLangGraphInterruptAction: () => null,
302
- removeLangGraphInterruptAction: () => null
303
- };
304
- var CopilotContext = import_react3.default.createContext(emptyCopilotContext);
305
- function useCopilotContext() {
306
- const context = import_react3.default.useContext(CopilotContext);
307
- if (context === emptyCopilotContext) {
308
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
309
- }
310
- return context;
311
- }
312
- function returnAndThrowInDebug(_value) {
313
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
314
- }
315
-
316
348
  // src/components/error-boundary/error-utils.tsx
317
349
  var import_react4 = require("react");
318
350
 
@@ -458,6 +490,35 @@ function useChat(options) {
458
490
  } = options;
459
491
  const runChatCompletionRef = (0, import_react5.useRef)();
460
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
+ });
461
522
  const agentSessionRef = (0, import_react5.useRef)(agentSession);
462
523
  agentSessionRef.current = agentSession;
463
524
  const runIdRef = (0, import_react5.useRef)(runId);
@@ -477,7 +538,7 @@ function useChat(options) {
477
538
  const pendingAppendsRef = (0, import_react5.useRef)([]);
478
539
  const runChatCompletion = useAsyncCallback(
479
540
  (previousMessages) => __async(this, null, function* () {
480
- 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;
481
542
  setIsLoading(true);
482
543
  const interruptEvent = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event;
483
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) {
@@ -609,20 +670,53 @@ function useChat(options) {
609
670
  messages2 = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
610
671
  (0, import_runtime_client_gql3.filterAdjacentAgentStateMessages)(rawMessagesResponse)
611
672
  );
612
- if (messages2.length === 0) {
613
- continue;
614
- }
615
673
  newMessages = [];
616
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) || "";
617
676
  newMessages = [
618
677
  new import_runtime_client_gql3.TextMessage({
619
678
  role: import_runtime_client_gql3.MessageRole.Assistant,
620
- content: ((_l = value.generateCopilotResponse.status.details) == null ? void 0 : _l.guardrailsReason) || ""
679
+ content: guardrailsReason
621
680
  })
622
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
+ });
623
690
  setMessages([...previousMessages, ...newMessages]);
624
691
  break;
625
- } 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) {
626
720
  newMessages = [...messages2];
627
721
  for (const message of messages2) {
628
722
  if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
@@ -684,6 +778,39 @@ function useChat(options) {
684
778
  newMessages
685
779
  );
686
780
  let didExecuteAction = false;
781
+ const executeActionFromMessage = (currentAction, actionMessage) => __async(this, null, function* () {
782
+ var _a2;
783
+ const isInterruptAction = interruptMessages.find((m) => m.id === actionMessage.id);
784
+ followUp = (_a2 = currentAction == null ? void 0 : currentAction.followUp) != null ? _a2 : !isInterruptAction;
785
+ if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
786
+ currentAction._setActivatingMessageId(actionMessage.id);
787
+ }
788
+ const resultMessage = yield executeAction({
789
+ onFunctionCall,
790
+ message: actionMessage,
791
+ chatAbortControllerRef,
792
+ onError: (error) => {
793
+ addErrorToast([error]);
794
+ console.error(`Failed to execute action ${actionMessage.name}: ${error}`);
795
+ },
796
+ setMessages,
797
+ getFinalMessages: () => finalMessages,
798
+ isRenderAndWait: (currentAction == null ? void 0 : currentAction._isRenderAndWait) || false
799
+ });
800
+ didExecuteAction = true;
801
+ const messageIndex = finalMessages.findIndex((msg) => msg.id === actionMessage.id);
802
+ finalMessages.splice(messageIndex + 1, 0, resultMessage);
803
+ if (currentAction == null ? void 0 : currentAction._isRenderAndWait) {
804
+ const messagesForImmediateUpdate = [...finalMessages];
805
+ (0, import_react_dom.flushSync)(() => {
806
+ setMessages(messagesForImmediateUpdate);
807
+ });
808
+ }
809
+ if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
810
+ currentAction._setActivatingMessageId(null);
811
+ }
812
+ return resultMessage;
813
+ });
687
814
  if (onFunctionCall) {
688
815
  const lastMessages = [];
689
816
  for (let i = finalMessages.length - 1; i >= 0; i--) {
@@ -700,37 +827,28 @@ function useChat(options) {
700
827
  (action2) => action2.name === message.name
701
828
  );
702
829
  const currentResultMessagePairedFeAction = message.isResultMessage() ? getPairedFeAction(actions, message) : null;
703
- const executeActionFromMessage = (action2, message2) => __async(this, null, function* () {
704
- var _a2;
705
- const isInterruptAction = interruptMessages.find((m) => m.id === message2.id);
706
- followUp = (_a2 = action2 == null ? void 0 : action2.followUp) != null ? _a2 : !isInterruptAction;
707
- const resultMessage = yield executeAction({
708
- onFunctionCall,
709
- previousMessages,
710
- message: message2,
711
- chatAbortControllerRef,
712
- onError: (error) => {
713
- addErrorToast([error]);
714
- console.error(`Failed to execute action ${message2.name}: ${error}`);
715
- }
716
- });
717
- didExecuteAction = true;
718
- const messageIndex = finalMessages.findIndex((msg) => msg.id === message2.id);
719
- finalMessages.splice(messageIndex + 1, 0, resultMessage);
720
- return resultMessage;
721
- });
722
830
  if (action && message.isActionExecutionMessage()) {
723
- const resultMessage = yield executeActionFromMessage(action, message);
724
- const pairedFeAction = getPairedFeAction(actions, resultMessage);
725
- if (pairedFeAction) {
726
- const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
727
- name: pairedFeAction.name,
728
- arguments: (0, import_shared4.parseJson)(resultMessage.result, resultMessage.result),
729
- status: message.status,
730
- createdAt: message.createdAt,
731
- parentMessageId: message.parentMessageId
732
- });
733
- yield executeActionFromMessage(pairedFeAction, newExecutionMessage);
831
+ const isRenderAndWaitAction = (action == null ? void 0 : action._isRenderAndWait) || false;
832
+ const alreadyProcessed = isRenderAndWaitAction && finalMessages.some(
833
+ (fm) => fm.isResultMessage() && fm.actionExecutionId === message.id
834
+ );
835
+ if (alreadyProcessed) {
836
+ } else {
837
+ const resultMessage = yield executeActionFromMessage(
838
+ action,
839
+ message
840
+ );
841
+ const pairedFeAction = getPairedFeAction(actions, resultMessage);
842
+ if (pairedFeAction) {
843
+ const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
844
+ name: pairedFeAction.name,
845
+ arguments: (0, import_shared4.parseJson)(resultMessage.result, resultMessage.result),
846
+ status: message.status,
847
+ createdAt: message.createdAt,
848
+ parentMessageId: message.parentMessageId
849
+ });
850
+ yield executeActionFromMessage(pairedFeAction, newExecutionMessage);
851
+ }
734
852
  }
735
853
  } else if (message.isResultMessage() && currentResultMessagePairedFeAction) {
736
854
  const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
@@ -748,16 +866,12 @@ function useChat(options) {
748
866
  }
749
867
  setMessages(finalMessages);
750
868
  }
751
- if (
752
- // if followUp is not explicitly false
753
- followUp !== false && // and we executed an action
754
- (didExecuteAction || // the last message is a server side result
755
- !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage()) && // the user did not stop generation
756
- !((_m = chatAbortControllerRef.current) == null ? void 0 : _m.signal.aborted)
757
- ) {
869
+ if (followUp !== false && (didExecuteAction || // the last message is a server side result
870
+ !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage()) && // the user did not stop generation
871
+ !((_r = chatAbortControllerRef.current) == null ? void 0 : _r.signal.aborted)) {
758
872
  yield new Promise((resolve) => setTimeout(resolve, 10));
759
873
  return yield runChatCompletionRef.current(finalMessages);
760
- } else if ((_n = chatAbortControllerRef.current) == null ? void 0 : _n.signal.aborted) {
874
+ } else if ((_s = chatAbortControllerRef.current) == null ? void 0 : _s.signal.aborted) {
761
875
  const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {
762
876
  if (message.isActionExecutionMessage()) {
763
877
  return finalMessages.find(
@@ -768,7 +882,7 @@ function useChat(options) {
768
882
  });
769
883
  const repairedMessageIds = repairedMessages.map((message) => message.id);
770
884
  setMessages(repairedMessages);
771
- if ((_o = agentSessionRef.current) == null ? void 0 : _o.nodeName) {
885
+ if ((_t = agentSessionRef.current) == null ? void 0 : _t.nodeName) {
772
886
  setAgentSession({
773
887
  threadId: agentSessionRef.current.threadId,
774
888
  agentName: agentSessionRef.current.agentName,
@@ -862,21 +976,35 @@ function useChat(options) {
862
976
  [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
863
977
  );
864
978
  const reload = useAsyncCallback(
865
- (messageId) => __async(this, null, function* () {
979
+ (reloadMessageId) => __async(this, null, function* () {
866
980
  if (isLoading || messages.length === 0) {
867
981
  return;
868
982
  }
869
- const index = messages.findIndex((msg) => msg.id === messageId);
870
- if (index === -1) {
871
- console.warn(`Message with id ${messageId} not found`);
983
+ const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);
984
+ if (reloadMessageIndex === -1) {
985
+ console.warn(`Message with id ${reloadMessageId} not found`);
872
986
  return;
873
987
  }
874
- let newMessages = messages.slice(0, index);
875
- if (newMessages.length > 0 && newMessages[newMessages.length - 1].isAgentStateMessage()) {
876
- newMessages = newMessages.slice(0, newMessages.length - 1);
988
+ const reloadMessageRole = messages[reloadMessageIndex].role;
989
+ if (reloadMessageRole !== import_runtime_client_gql3.MessageRole.Assistant) {
990
+ console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
991
+ return;
877
992
  }
878
- setMessages(newMessages);
879
- return runChatCompletionAndHandleFunctionCall(newMessages);
993
+ let historyCutoff = [];
994
+ if (messages.length > 2) {
995
+ const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find(
996
+ (msg) => (
997
+ // @ts-expect-error -- message has role
998
+ msg.role === import_runtime_client_gql3.MessageRole.User
999
+ )
1000
+ );
1001
+ const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(
1002
+ (msg) => msg.id === lastUserMessageBeforeRegenerate.id
1003
+ );
1004
+ historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
1005
+ }
1006
+ setMessages(historyCutoff);
1007
+ return runChatCompletionAndHandleFunctionCall(historyCutoff);
880
1008
  }),
881
1009
  [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
882
1010
  );
@@ -911,20 +1039,31 @@ function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
911
1039
  function executeAction(_0) {
912
1040
  return __async(this, arguments, function* ({
913
1041
  onFunctionCall,
914
- previousMessages,
915
1042
  message,
916
1043
  chatAbortControllerRef,
917
- onError
1044
+ onError,
1045
+ setMessages,
1046
+ getFinalMessages,
1047
+ isRenderAndWait
918
1048
  }) {
919
1049
  let result;
920
1050
  let error = null;
1051
+ const currentMessagesForHandler = getFinalMessages();
1052
+ const handlerReturnedPromise = onFunctionCall({
1053
+ messages: currentMessagesForHandler,
1054
+ name: message.name,
1055
+ args: message.arguments
1056
+ });
1057
+ if (isRenderAndWait) {
1058
+ const currentMessagesForRender = getFinalMessages();
1059
+ (0, import_react_dom.flushSync)(() => {
1060
+ setMessages([...currentMessagesForRender]);
1061
+ });
1062
+ }
921
1063
  try {
922
1064
  result = yield Promise.race([
923
- onFunctionCall({
924
- messages: previousMessages,
925
- name: message.name,
926
- args: message.arguments
927
- }),
1065
+ handlerReturnedPromise,
1066
+ // Await the promise returned by the handler
928
1067
  new Promise(
929
1068
  (resolve) => {
930
1069
  var _a;