@copilotkit/react-core 1.4.8-no-pino-redact.1 → 1.4.8

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 (95) hide show
  1. package/CHANGELOG.md +8 -3
  2. package/dist/{chunk-XBVKTDXP.mjs → chunk-6EMLM6WX.mjs} +17 -14
  3. package/dist/chunk-6EMLM6WX.mjs.map +1 -0
  4. package/dist/{chunk-ODN4H66E.mjs → chunk-7LRDVJH5.mjs} +6 -2
  5. package/dist/chunk-7LRDVJH5.mjs.map +1 -0
  6. package/dist/{chunk-O22KGHOQ.mjs → chunk-FSC4A3JN.mjs} +17 -13
  7. package/dist/chunk-FSC4A3JN.mjs.map +1 -0
  8. package/dist/{chunk-OT67R4NB.mjs → chunk-IFTHM7LF.mjs} +2 -2
  9. package/dist/{chunk-DHGXL5PC.mjs → chunk-IVYL7JRC.mjs} +7 -4
  10. package/dist/chunk-IVYL7JRC.mjs.map +1 -0
  11. package/dist/chunk-NTLCOVE5.mjs +321 -0
  12. package/dist/chunk-NTLCOVE5.mjs.map +1 -0
  13. package/dist/chunk-QCUP6HLK.mjs +37 -0
  14. package/dist/chunk-QCUP6HLK.mjs.map +1 -0
  15. package/dist/{chunk-2KCEHGSI.mjs → chunk-SFPANIOY.mjs} +99 -49
  16. package/dist/chunk-SFPANIOY.mjs.map +1 -0
  17. package/dist/{chunk-JHEAUB3Z.mjs → chunk-X6ZF5WAX.mjs} +1 -1
  18. package/dist/{chunk-JHEAUB3Z.mjs.map → chunk-X6ZF5WAX.mjs.map} +1 -1
  19. package/dist/{chunk-Y7MI4PBB.mjs → chunk-YUY5ZAST.mjs} +6 -3
  20. package/dist/chunk-YUY5ZAST.mjs.map +1 -0
  21. package/dist/components/copilot-provider/copilotkit.js +156 -91
  22. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  23. package/dist/components/copilot-provider/copilotkit.mjs +4 -3
  24. package/dist/components/copilot-provider/index.js +156 -91
  25. package/dist/components/copilot-provider/index.js.map +1 -1
  26. package/dist/components/copilot-provider/index.mjs +4 -3
  27. package/dist/components/error-boundary/error-boundary.d.ts +22 -0
  28. package/dist/components/error-boundary/error-boundary.js +183 -0
  29. package/dist/components/error-boundary/error-boundary.js.map +1 -0
  30. package/dist/components/error-boundary/error-boundary.mjs +12 -0
  31. package/dist/components/error-boundary/error-boundary.mjs.map +1 -0
  32. package/dist/components/error-boundary/error-utils.d.ts +11 -0
  33. package/dist/components/error-boundary/error-utils.js +177 -0
  34. package/dist/components/error-boundary/error-utils.js.map +1 -0
  35. package/dist/components/error-boundary/error-utils.mjs +13 -0
  36. package/dist/components/error-boundary/error-utils.mjs.map +1 -0
  37. package/dist/components/index.js +156 -91
  38. package/dist/components/index.js.map +1 -1
  39. package/dist/components/index.mjs +4 -3
  40. package/dist/components/toast/toast-provider.d.ts +2 -1
  41. package/dist/components/toast/toast-provider.js +76 -62
  42. package/dist/components/toast/toast-provider.js.map +1 -1
  43. package/dist/components/toast/toast-provider.mjs +1 -1
  44. package/dist/hooks/index.js +398 -253
  45. package/dist/hooks/index.js.map +1 -1
  46. package/dist/hooks/index.mjs +9 -8
  47. package/dist/hooks/use-chat.js +343 -199
  48. package/dist/hooks/use-chat.js.map +1 -1
  49. package/dist/hooks/use-chat.mjs +3 -3
  50. package/dist/hooks/use-coagent-state-render.d.ts +2 -2
  51. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  52. package/dist/hooks/use-coagent-state-render.mjs +1 -1
  53. package/dist/hooks/use-coagent.js +378 -233
  54. package/dist/hooks/use-coagent.js.map +1 -1
  55. package/dist/hooks/use-coagent.mjs +7 -6
  56. package/dist/hooks/use-copilot-action.js +132 -7
  57. package/dist/hooks/use-copilot-action.js.map +1 -1
  58. package/dist/hooks/use-copilot-action.mjs +3 -1
  59. package/dist/hooks/use-copilot-chat.js +367 -223
  60. package/dist/hooks/use-copilot-chat.js.map +1 -1
  61. package/dist/hooks/use-copilot-chat.mjs +6 -5
  62. package/dist/hooks/use-copilot-runtime-client.js +110 -4
  63. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  64. package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
  65. package/dist/index.js +439 -335
  66. package/dist/index.js.map +1 -1
  67. package/dist/index.mjs +10 -9
  68. package/dist/lib/copilot-task.js.map +1 -1
  69. package/dist/lib/copilot-task.mjs +5 -4
  70. package/dist/lib/index.js.map +1 -1
  71. package/dist/lib/index.mjs +5 -4
  72. package/dist/utils/extract.js.map +1 -1
  73. package/dist/utils/extract.mjs +4 -3
  74. package/dist/utils/index.js.map +1 -1
  75. package/dist/utils/index.mjs +4 -3
  76. package/package.json +3 -3
  77. package/src/components/copilot-provider/copilotkit.tsx +4 -1
  78. package/src/components/error-boundary/error-boundary.tsx +42 -0
  79. package/src/components/error-boundary/error-utils.tsx +95 -0
  80. package/src/components/toast/toast-provider.tsx +10 -49
  81. package/src/hooks/use-chat.ts +286 -259
  82. package/src/hooks/use-coagent-state-render.ts +2 -2
  83. package/src/hooks/use-coagent.ts +14 -11
  84. package/src/hooks/use-copilot-action.ts +3 -2
  85. package/src/hooks/use-copilot-chat.ts +9 -8
  86. package/src/hooks/use-copilot-runtime-client.ts +4 -0
  87. package/dist/chunk-2KCEHGSI.mjs.map +0 -1
  88. package/dist/chunk-DHGXL5PC.mjs.map +0 -1
  89. package/dist/chunk-EUIBVFV6.mjs +0 -294
  90. package/dist/chunk-EUIBVFV6.mjs.map +0 -1
  91. package/dist/chunk-O22KGHOQ.mjs.map +0 -1
  92. package/dist/chunk-ODN4H66E.mjs.map +0 -1
  93. package/dist/chunk-XBVKTDXP.mjs.map +0 -1
  94. package/dist/chunk-Y7MI4PBB.mjs.map +0 -1
  95. /package/dist/{chunk-OT67R4NB.mjs.map → chunk-IFTHM7LF.mjs.map} +0 -0
@@ -60,16 +60,131 @@ __export(use_chat_exports, {
60
60
  useChat: () => useChat
61
61
  });
62
62
  module.exports = __toCommonJS(use_chat_exports);
63
- var import_react3 = require("react");
63
+ var import_react4 = require("react");
64
64
  var import_shared = require("@copilotkit/shared");
65
65
  var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
66
66
 
67
67
  // src/components/toast/toast-provider.tsx
68
+ var import_react2 = require("react");
69
+
70
+ // src/components/error-boundary/error-utils.tsx
68
71
  var import_react = require("react");
72
+
73
+ // src/components/toast/exclamation-mark-icon.tsx
69
74
  var import_jsx_runtime = require("react/jsx-runtime");
70
- var ToastContext = (0, import_react.createContext)(void 0);
75
+ var ExclamationMarkIcon = ({
76
+ className,
77
+ style
78
+ }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
79
+ "svg",
80
+ {
81
+ xmlns: "http://www.w3.org/2000/svg",
82
+ width: "24",
83
+ height: "24",
84
+ viewBox: "0 0 24 24",
85
+ fill: "none",
86
+ stroke: "currentColor",
87
+ strokeWidth: "2",
88
+ strokeLinecap: "round",
89
+ strokeLinejoin: "round",
90
+ className: `lucide lucide-circle-alert ${className ? className : ""}`,
91
+ style,
92
+ children: [
93
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("circle", { cx: "12", cy: "12", r: "10" }),
94
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("line", { x1: "12", x2: "12", y1: "8", y2: "12" }),
95
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("line", { x1: "12", x2: "12.01", y1: "16", y2: "16" })
96
+ ]
97
+ }
98
+ );
99
+
100
+ // src/components/error-boundary/error-utils.tsx
101
+ var import_jsx_runtime2 = require("react/jsx-runtime");
102
+ function ErrorToast({ errors }) {
103
+ const errorsToRender = errors.map((error, idx) => {
104
+ var _a, _b, _c;
105
+ const message = "extensions" in error ? (_b = (_a = error.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message : error.message;
106
+ const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
107
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
108
+ "div",
109
+ {
110
+ style: {
111
+ marginTop: idx === 0 ? 0 : 10,
112
+ marginBottom: 14
113
+ },
114
+ children: [
115
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
116
+ code && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
117
+ "div",
118
+ {
119
+ style: {
120
+ fontWeight: "600",
121
+ marginBottom: 4
122
+ },
123
+ children: [
124
+ "Copilot Cloud Error:",
125
+ " ",
126
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
127
+ ]
128
+ }
129
+ ),
130
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { children: message })
131
+ ]
132
+ },
133
+ idx
134
+ );
135
+ });
136
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
137
+ "div",
138
+ {
139
+ style: {
140
+ fontSize: "13px",
141
+ maxWidth: "600px"
142
+ },
143
+ children: [
144
+ errorsToRender,
145
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
146
+ ]
147
+ }
148
+ );
149
+ }
150
+ function useErrorToast() {
151
+ const { addToast } = useToast();
152
+ return (0, import_react.useCallback)(
153
+ (error) => {
154
+ const errorId = error.map((err) => {
155
+ var _a, _b;
156
+ const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
157
+ const stack = err.stack || "";
158
+ return btoa(message + stack).slice(0, 32);
159
+ }).join("|");
160
+ addToast({
161
+ type: "error",
162
+ id: errorId,
163
+ // Toast libraries typically dedupe by id
164
+ message: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ErrorToast, { errors: error })
165
+ });
166
+ },
167
+ [addToast]
168
+ );
169
+ }
170
+ function useAsyncCallback(callback, deps) {
171
+ const addErrorToast = useErrorToast();
172
+ return (0, import_react.useCallback)((...args) => __async(this, null, function* () {
173
+ try {
174
+ return yield callback(...args);
175
+ } catch (error) {
176
+ console.error("Error in async callback:", error);
177
+ addErrorToast([error]);
178
+ throw error;
179
+ }
180
+ }), deps);
181
+ }
182
+
183
+ // src/components/toast/toast-provider.tsx
184
+ var import_jsx_runtime3 = require("react/jsx-runtime");
185
+ var ToastContext = (0, import_react2.createContext)(void 0);
71
186
  function useToast() {
72
- const context = (0, import_react.useContext)(ToastContext);
187
+ const context = (0, import_react2.useContext)(ToastContext);
73
188
  if (!context) {
74
189
  throw new Error("useToast must be used within a ToastProvider");
75
190
  }
@@ -78,14 +193,17 @@ function useToast() {
78
193
 
79
194
  // src/hooks/use-copilot-runtime-client.ts
80
195
  var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
81
- var import_react2 = require("react");
196
+ var import_react3 = require("react");
82
197
  var useCopilotRuntimeClient = (options) => {
83
198
  const { addGraphQLErrorsToast } = useToast();
84
- const runtimeClient = (0, import_react2.useMemo)(() => {
199
+ const addErrorToast = useErrorToast();
200
+ const runtimeClient = (0, import_react3.useMemo)(() => {
85
201
  return new import_runtime_client_gql.CopilotRuntimeClient(__spreadProps(__spreadValues({}, options), {
86
202
  handleGQLErrors: (error) => {
87
203
  if (error.graphQLErrors.length) {
88
204
  addGraphQLErrorsToast(error.graphQLErrors);
205
+ } else {
206
+ addErrorToast([error]);
89
207
  }
90
208
  }
91
209
  }));
@@ -111,12 +229,12 @@ function useChat(options) {
111
229
  agentSession,
112
230
  setAgentSession
113
231
  } = options;
114
- const abortControllerRef = (0, import_react3.useRef)();
115
- const threadIdRef = (0, import_react3.useRef)(null);
116
- const runIdRef = (0, import_react3.useRef)(null);
232
+ const abortControllerRef = (0, import_react4.useRef)();
233
+ const threadIdRef = (0, import_react4.useRef)(null);
234
+ const runIdRef = (0, import_react4.useRef)(null);
117
235
  const { addGraphQLErrorsToast } = useToast();
118
- const runChatCompletionRef = (0, import_react3.useRef)();
119
- const agentSessionRef = (0, import_react3.useRef)(agentSession);
236
+ const runChatCompletionRef = (0, import_react4.useRef)();
237
+ const agentSessionRef = (0, import_react4.useRef)(agentSession);
120
238
  agentSessionRef.current = agentSession;
121
239
  const publicApiKey = copilotConfig.publicApiKey;
122
240
  const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
@@ -126,210 +244,236 @@ function useChat(options) {
126
244
  headers,
127
245
  credentials: copilotConfig.credentials
128
246
  });
129
- const runChatCompletion = (previousMessages) => __async(this, null, function* () {
130
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
131
- setIsLoading(true);
132
- let newMessages = [
133
- new import_runtime_client_gql2.TextMessage({
134
- content: "",
135
- role: import_runtime_client_gql2.Role.Assistant
136
- })
137
- ];
138
- const abortController = new AbortController();
139
- abortControllerRef.current = abortController;
140
- setMessages([...previousMessages, ...newMessages]);
141
- const systemMessage = makeSystemMessageCallback();
142
- const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
143
- const stream = runtimeClient.asStream(
144
- runtimeClient.generateCopilotResponse({
145
- data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
146
- frontend: {
147
- actions: actions.filter(
148
- (action) => action.available !== import_runtime_client_gql2.ActionInputAvailability.Disabled || !action.disabled
149
- ).map((action) => {
150
- let available = import_runtime_client_gql2.ActionInputAvailability.Enabled;
151
- if (action.disabled) {
152
- available = import_runtime_client_gql2.ActionInputAvailability.Disabled;
153
- } else if (action.available === "disabled") {
154
- available = import_runtime_client_gql2.ActionInputAvailability.Disabled;
155
- } else if (action.available === "remote") {
156
- available = import_runtime_client_gql2.ActionInputAvailability.Remote;
157
- }
158
- return {
159
- name: action.name,
160
- description: action.description || "",
161
- jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
162
- available
163
- };
164
- }),
165
- url: window.location.href
166
- },
167
- threadId: threadIdRef.current,
168
- runId: runIdRef.current,
169
- messages: (0, import_runtime_client_gql2.convertMessagesToGqlInput)((0, import_runtime_client_gql2.filterAgentStateMessages)(messagesWithContext))
170
- }, copilotConfig.cloud ? {
171
- cloud: __spreadValues({}, ((_c = (_b = (_a = copilotConfig.cloud.guardrails) == null ? void 0 : _a.input) == null ? void 0 : _b.restrictToTopic) == null ? void 0 : _c.enabled) ? {
172
- guardrails: {
173
- inputValidationRules: {
174
- allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
175
- denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
247
+ const runChatCompletion = useAsyncCallback(
248
+ (previousMessages) => __async(this, null, function* () {
249
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
250
+ setIsLoading(true);
251
+ let newMessages = [
252
+ new import_runtime_client_gql2.TextMessage({
253
+ content: "",
254
+ role: import_runtime_client_gql2.Role.Assistant
255
+ })
256
+ ];
257
+ const abortController = new AbortController();
258
+ abortControllerRef.current = abortController;
259
+ setMessages([...previousMessages, ...newMessages]);
260
+ const systemMessage = makeSystemMessageCallback();
261
+ const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
262
+ const stream = runtimeClient.asStream(
263
+ runtimeClient.generateCopilotResponse({
264
+ data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
265
+ frontend: {
266
+ actions: actions.filter(
267
+ (action) => action.available !== import_runtime_client_gql2.ActionInputAvailability.Disabled || !action.disabled
268
+ ).map((action) => {
269
+ let available = import_runtime_client_gql2.ActionInputAvailability.Enabled;
270
+ if (action.disabled) {
271
+ available = import_runtime_client_gql2.ActionInputAvailability.Disabled;
272
+ } else if (action.available === "disabled") {
273
+ available = import_runtime_client_gql2.ActionInputAvailability.Disabled;
274
+ } else if (action.available === "remote") {
275
+ available = import_runtime_client_gql2.ActionInputAvailability.Remote;
276
+ }
277
+ return {
278
+ name: action.name,
279
+ description: action.description || "",
280
+ jsonSchema: JSON.stringify(
281
+ (0, import_shared.actionParametersToJsonSchema)(action.parameters || [])
282
+ ),
283
+ available
284
+ };
285
+ }),
286
+ url: window.location.href
287
+ },
288
+ threadId: threadIdRef.current,
289
+ runId: runIdRef.current,
290
+ messages: (0, import_runtime_client_gql2.convertMessagesToGqlInput)((0, import_runtime_client_gql2.filterAgentStateMessages)(messagesWithContext))
291
+ }, copilotConfig.cloud ? {
292
+ cloud: __spreadValues({}, ((_c = (_b = (_a = copilotConfig.cloud.guardrails) == null ? void 0 : _a.input) == null ? void 0 : _b.restrictToTopic) == null ? void 0 : _c.enabled) ? {
293
+ guardrails: {
294
+ inputValidationRules: {
295
+ allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
296
+ denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
297
+ }
176
298
  }
299
+ } : {})
300
+ } : {}), {
301
+ metadata: {
302
+ requestType: import_runtime_client_gql2.CopilotRequestType.Chat
177
303
  }
178
- } : {})
179
- } : {}), {
180
- metadata: {
181
- requestType: import_runtime_client_gql2.CopilotRequestType.Chat
304
+ }), agentSessionRef.current ? {
305
+ agentSession: agentSessionRef.current
306
+ } : {}), {
307
+ agentStates: Object.values(coagentStatesRef.current).map((state) => ({
308
+ agentName: state.name,
309
+ state: JSON.stringify(state.state)
310
+ }))
311
+ }),
312
+ properties: copilotConfig.properties,
313
+ signal: (_d = abortControllerRef.current) == null ? void 0 : _d.signal
314
+ })
315
+ );
316
+ const guardrailsEnabled = ((_g = (_f = (_e = copilotConfig.cloud) == null ? void 0 : _e.guardrails) == null ? void 0 : _f.input) == null ? void 0 : _g.restrictToTopic.enabled) || false;
317
+ const reader = stream.getReader();
318
+ let actionResults = {};
319
+ let executedCoAgentStateRenders = [];
320
+ let followUp = void 0;
321
+ try {
322
+ while (true) {
323
+ let done, value;
324
+ try {
325
+ const readResult = yield reader.read();
326
+ done = readResult.done;
327
+ value = readResult.value;
328
+ } catch (readError) {
329
+ break;
182
330
  }
183
- }), agentSessionRef.current ? {
184
- agentSession: agentSessionRef.current
185
- } : {}), {
186
- agentStates: Object.values(coagentStatesRef.current).map((state) => ({
187
- agentName: state.name,
188
- state: JSON.stringify(state.state)
189
- }))
190
- }),
191
- properties: copilotConfig.properties,
192
- signal: (_d = abortControllerRef.current) == null ? void 0 : _d.signal
193
- })
194
- );
195
- const guardrailsEnabled = ((_g = (_f = (_e = copilotConfig.cloud) == null ? void 0 : _e.guardrails) == null ? void 0 : _f.input) == null ? void 0 : _g.restrictToTopic.enabled) || false;
196
- const reader = stream.getReader();
197
- let actionResults = {};
198
- let executedCoAgentStateRenders = [];
199
- let followUp = void 0;
200
- try {
201
- while (true) {
202
- let done, value;
203
- try {
204
- const readResult = yield reader.read();
205
- done = readResult.done;
206
- value = readResult.value;
207
- } catch (readError) {
208
- break;
209
- }
210
- if (done) {
211
- break;
212
- }
213
- if (!(value == null ? void 0 : value.generateCopilotResponse)) {
214
- continue;
215
- }
216
- threadIdRef.current = value.generateCopilotResponse.threadId || null;
217
- runIdRef.current = value.generateCopilotResponse.runId || null;
218
- const messages2 = (0, import_runtime_client_gql2.convertGqlOutputToMessages)(
219
- (0, import_runtime_client_gql2.filterAdjacentAgentStateMessages)(value.generateCopilotResponse.messages)
220
- );
221
- if (messages2.length === 0) {
222
- continue;
223
- }
224
- newMessages = [];
225
- if (((_h = value.generateCopilotResponse.status) == null ? void 0 : _h.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
226
- newMessages = [
227
- new import_runtime_client_gql2.TextMessage({
228
- role: import_runtime_client_gql2.MessageRole.Assistant,
229
- content: ((_i = value.generateCopilotResponse.status.details) == null ? void 0 : _i.guardrailsReason) || ""
230
- })
231
- ];
232
- } else {
233
- for (const message of messages2) {
234
- newMessages.push(message);
235
- if (message.isActionExecutionMessage() && message.status.code !== import_runtime_client_gql2.MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
236
- if (!(message.id in actionResults)) {
331
+ if (done) {
332
+ break;
333
+ }
334
+ if (!(value == null ? void 0 : value.generateCopilotResponse)) {
335
+ continue;
336
+ }
337
+ threadIdRef.current = value.generateCopilotResponse.threadId || null;
338
+ runIdRef.current = value.generateCopilotResponse.runId || null;
339
+ const messages2 = (0, import_runtime_client_gql2.convertGqlOutputToMessages)(
340
+ (0, import_runtime_client_gql2.filterAdjacentAgentStateMessages)(value.generateCopilotResponse.messages)
341
+ );
342
+ if (messages2.length === 0) {
343
+ continue;
344
+ }
345
+ newMessages = [];
346
+ if (((_h = value.generateCopilotResponse.status) == null ? void 0 : _h.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
347
+ newMessages = [
348
+ new import_runtime_client_gql2.TextMessage({
349
+ role: import_runtime_client_gql2.MessageRole.Assistant,
350
+ content: ((_i = value.generateCopilotResponse.status.details) == null ? void 0 : _i.guardrailsReason) || ""
351
+ })
352
+ ];
353
+ } else {
354
+ for (const message of messages2) {
355
+ newMessages.push(message);
356
+ if (message.isActionExecutionMessage() && message.status.code !== import_runtime_client_gql2.MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
357
+ if (!(message.id in actionResults)) {
358
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
359
+ break;
360
+ }
361
+ try {
362
+ setMessages([...previousMessages, ...newMessages]);
363
+ const action = actions.find((action2) => action2.name === message.name);
364
+ if (action) {
365
+ followUp = action.followUp;
366
+ }
367
+ const result = yield onFunctionCall({
368
+ messages: previousMessages,
369
+ name: message.name,
370
+ args: message.arguments
371
+ });
372
+ actionResults[message.id] = result;
373
+ } catch (e) {
374
+ actionResults[message.id] = `Failed to execute action ${message.name}`;
375
+ console.error(`Failed to execute action ${message.name}: ${e}`);
376
+ }
377
+ }
378
+ newMessages.push(
379
+ new import_runtime_client_gql2.ResultMessage({
380
+ result: import_runtime_client_gql2.ResultMessage.encodeResult(actionResults[message.id]),
381
+ actionExecutionId: message.id,
382
+ actionName: message.name
383
+ })
384
+ );
385
+ }
386
+ if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
237
387
  if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
238
388
  break;
239
389
  }
240
- try {
241
- setMessages([...previousMessages, ...newMessages]);
242
- const action = actions.find((action2) => action2.name === message.name);
243
- if (action) {
244
- followUp = action.followUp;
245
- }
246
- const result = yield onFunctionCall({
247
- messages: previousMessages,
248
- name: message.name,
249
- args: message.arguments
250
- });
251
- actionResults[message.id] = result;
252
- } catch (e) {
253
- actionResults[message.id] = `Failed to execute action ${message.name}`;
254
- console.error(`Failed to execute action ${message.name}: ${e}`);
255
- }
390
+ yield onCoAgentStateRender({
391
+ name: message.agentName,
392
+ nodeName: message.nodeName,
393
+ state: message.state
394
+ });
395
+ executedCoAgentStateRenders.push(message.id);
256
396
  }
257
- newMessages.push(
258
- new import_runtime_client_gql2.ResultMessage({
259
- result: import_runtime_client_gql2.ResultMessage.encodeResult(actionResults[message.id]),
260
- actionExecutionId: message.id,
261
- actionName: message.name
262
- })
263
- );
264
397
  }
265
- if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
266
- if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
267
- break;
398
+ const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
399
+ if (lastAgentStateMessage) {
400
+ setCoagentStatesWithRef((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
401
+ [lastAgentStateMessage.agentName]: {
402
+ name: lastAgentStateMessage.agentName,
403
+ state: lastAgentStateMessage.state,
404
+ running: lastAgentStateMessage.running,
405
+ active: lastAgentStateMessage.active,
406
+ threadId: lastAgentStateMessage.threadId,
407
+ nodeName: lastAgentStateMessage.nodeName,
408
+ runId: lastAgentStateMessage.runId
409
+ }
410
+ }));
411
+ if (lastAgentStateMessage.running) {
412
+ setAgentSession({
413
+ threadId: lastAgentStateMessage.threadId,
414
+ agentName: lastAgentStateMessage.agentName,
415
+ nodeName: lastAgentStateMessage.nodeName
416
+ });
417
+ } else {
418
+ setAgentSession(null);
268
419
  }
269
- yield onCoAgentStateRender({
270
- name: message.agentName,
271
- nodeName: message.nodeName,
272
- state: message.state
273
- });
274
- executedCoAgentStateRenders.push(message.id);
275
420
  }
276
421
  }
277
- const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
278
- if (lastAgentStateMessage) {
279
- setCoagentStatesWithRef((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
280
- [lastAgentStateMessage.agentName]: {
281
- name: lastAgentStateMessage.agentName,
282
- state: lastAgentStateMessage.state,
283
- running: lastAgentStateMessage.running,
284
- active: lastAgentStateMessage.active,
285
- threadId: lastAgentStateMessage.threadId,
286
- nodeName: lastAgentStateMessage.nodeName,
287
- runId: lastAgentStateMessage.runId
288
- }
289
- }));
290
- if (lastAgentStateMessage.running) {
291
- setAgentSession({
292
- threadId: lastAgentStateMessage.threadId,
293
- agentName: lastAgentStateMessage.agentName,
294
- nodeName: lastAgentStateMessage.nodeName
295
- });
296
- } else {
297
- setAgentSession(null);
298
- }
422
+ if (newMessages.length > 0) {
423
+ setMessages([...previousMessages, ...newMessages]);
299
424
  }
300
425
  }
301
- if (newMessages.length > 0) {
302
- setMessages([...previousMessages, ...newMessages]);
426
+ if (
427
+ // if followUp is not explicitly false
428
+ followUp !== false && // if we have client side results
429
+ (Object.values(actionResults).length || // or the last message we received is a result
430
+ newMessages.length && newMessages[newMessages.length - 1].isResultMessage())
431
+ ) {
432
+ yield new Promise((resolve) => setTimeout(resolve, 10));
433
+ return yield runChatCompletionRef.current([...previousMessages, ...newMessages]);
434
+ } else {
435
+ return newMessages.slice();
303
436
  }
437
+ } finally {
438
+ setIsLoading(false);
304
439
  }
305
- if (
306
- // if followUp is not explicitly false
307
- followUp !== false && // if we have client side results
308
- (Object.values(actionResults).length || // or the last message we received is a result
309
- newMessages.length && newMessages[newMessages.length - 1].isResultMessage())
310
- ) {
311
- yield new Promise((resolve) => setTimeout(resolve, 10));
312
- return yield runChatCompletionRef.current([...previousMessages, ...newMessages]);
313
- } else {
314
- return newMessages.slice();
315
- }
316
- } finally {
317
- setIsLoading(false);
318
- }
319
- });
440
+ }),
441
+ [
442
+ messages,
443
+ setMessages,
444
+ makeSystemMessageCallback,
445
+ copilotConfig,
446
+ setIsLoading,
447
+ initialMessages,
448
+ isLoading,
449
+ actions,
450
+ onFunctionCall,
451
+ onCoAgentStateRender,
452
+ setCoagentStatesWithRef,
453
+ coagentStatesRef,
454
+ agentSession,
455
+ setAgentSession
456
+ ]
457
+ );
320
458
  runChatCompletionRef.current = runChatCompletion;
321
- const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
322
- yield runChatCompletionRef.current(messages2);
323
- });
324
- const append = (message) => __async(this, null, function* () {
325
- if (isLoading) {
326
- return;
327
- }
328
- const newMessages = [...messages, message];
329
- setMessages(newMessages);
330
- return runChatCompletionAndHandleFunctionCall(newMessages);
331
- });
332
- const reload = () => __async(this, null, function* () {
459
+ const runChatCompletionAndHandleFunctionCall = useAsyncCallback(
460
+ (messages2) => __async(this, null, function* () {
461
+ yield runChatCompletionRef.current(messages2);
462
+ }),
463
+ [messages]
464
+ );
465
+ const append = useAsyncCallback(
466
+ (message) => __async(this, null, function* () {
467
+ if (isLoading) {
468
+ return;
469
+ }
470
+ const newMessages = [...messages, message];
471
+ setMessages(newMessages);
472
+ return runChatCompletionAndHandleFunctionCall(newMessages);
473
+ }),
474
+ [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
475
+ );
476
+ const reload = useAsyncCallback(() => __async(this, null, function* () {
333
477
  if (isLoading || messages.length === 0) {
334
478
  return;
335
479
  }
@@ -340,7 +484,7 @@ function useChat(options) {
340
484
  }
341
485
  setMessages(newMessages);
342
486
  return runChatCompletionAndHandleFunctionCall(newMessages);
343
- });
487
+ }), [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);
344
488
  const stop = () => {
345
489
  var _a;
346
490
  (_a = abortControllerRef.current) == null ? void 0 : _a.abort();