@copilotkit/react-core 1.9.2-next.7 → 1.9.2-next.9

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 (102) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/{chunk-CCESTGAM.mjs → chunk-3OQM3NEK.mjs} +2 -2
  3. package/dist/{chunk-T4ZKC4X4.mjs → chunk-3YHYWAHK.mjs} +2 -2
  4. package/dist/{chunk-ISYBUDL4.mjs → chunk-55QZ2SVJ.mjs} +4 -5
  5. package/dist/chunk-55QZ2SVJ.mjs.map +1 -0
  6. package/dist/chunk-57K2ZJ5F.mjs +348 -0
  7. package/dist/chunk-57K2ZJ5F.mjs.map +1 -0
  8. package/dist/{chunk-ZHEEHGLS.mjs → chunk-ADIITPD2.mjs} +8 -5
  9. package/dist/{chunk-ZHEEHGLS.mjs.map → chunk-ADIITPD2.mjs.map} +1 -1
  10. package/dist/{chunk-S4BOATBG.mjs → chunk-EF5BNM34.mjs} +2 -2
  11. package/dist/{chunk-I4JPQECN.mjs → chunk-EXU7GWLC.mjs} +4 -4
  12. package/dist/{chunk-7G6RR4HE.mjs → chunk-FXK6RQIN.mjs} +2 -2
  13. package/dist/{chunk-JXF732XG.mjs → chunk-G7LYGERN.mjs} +80 -13
  14. package/dist/chunk-G7LYGERN.mjs.map +1 -0
  15. package/dist/{chunk-VJCHRQ7Q.mjs → chunk-JDEWNLNP.mjs} +37 -4
  16. package/dist/chunk-JDEWNLNP.mjs.map +1 -0
  17. package/dist/{chunk-JHIZ5HAI.mjs → chunk-NQVCZQ5T.mjs} +3 -3
  18. package/dist/{chunk-VF6UPRKM.mjs → chunk-OF4SZTLL.mjs} +3 -3
  19. package/dist/{chunk-QQZLIEXK.mjs → chunk-SJJNFYGQ.mjs} +3 -3
  20. package/dist/{chunk-RN3ZRHI7.mjs → chunk-WOGURSAL.mjs} +5 -5
  21. package/dist/chunk-YAF2LATQ.mjs +310 -0
  22. package/dist/chunk-YAF2LATQ.mjs.map +1 -0
  23. package/dist/components/copilot-provider/copilot-messages.js +35 -2
  24. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  25. package/dist/components/copilot-provider/copilot-messages.mjs +2 -2
  26. package/dist/components/copilot-provider/copilotkit.js +289 -234
  27. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  28. package/dist/components/copilot-provider/copilotkit.mjs +7 -7
  29. package/dist/components/copilot-provider/index.js +289 -234
  30. package/dist/components/copilot-provider/index.js.map +1 -1
  31. package/dist/components/copilot-provider/index.mjs +7 -7
  32. package/dist/components/error-boundary/error-boundary.js +135 -146
  33. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  34. package/dist/components/error-boundary/error-boundary.mjs +4 -4
  35. package/dist/components/error-boundary/error-utils.js.map +1 -1
  36. package/dist/components/error-boundary/error-utils.mjs +2 -2
  37. package/dist/components/index.js +289 -234
  38. package/dist/components/index.js.map +1 -1
  39. package/dist/components/index.mjs +7 -7
  40. package/dist/components/toast/toast-provider.js +118 -85
  41. package/dist/components/toast/toast-provider.js.map +1 -1
  42. package/dist/components/toast/toast-provider.mjs +1 -1
  43. package/dist/components/usage-banner.js +135 -146
  44. package/dist/components/usage-banner.js.map +1 -1
  45. package/dist/components/usage-banner.mjs +1 -1
  46. package/dist/hooks/index.js +75 -10
  47. package/dist/hooks/index.js.map +1 -1
  48. package/dist/hooks/index.mjs +14 -14
  49. package/dist/hooks/use-chat.js +72 -10
  50. package/dist/hooks/use-chat.js.map +1 -1
  51. package/dist/hooks/use-chat.mjs +4 -4
  52. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  53. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  54. package/dist/hooks/use-coagent.js +75 -10
  55. package/dist/hooks/use-coagent.js.map +1 -1
  56. package/dist/hooks/use-coagent.mjs +10 -10
  57. package/dist/hooks/use-copilot-action.js.map +1 -1
  58. package/dist/hooks/use-copilot-action.mjs +3 -3
  59. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  60. package/dist/hooks/use-copilot-authenticated-action.mjs +4 -4
  61. package/dist/hooks/use-copilot-chat.js +72 -10
  62. package/dist/hooks/use-copilot-chat.js.map +1 -1
  63. package/dist/hooks/use-copilot-chat.mjs +9 -9
  64. package/dist/hooks/use-copilot-runtime-client.js +1 -1
  65. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  66. package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
  67. package/dist/hooks/use-langgraph-interrupt.js +72 -10
  68. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  69. package/dist/hooks/use-langgraph-interrupt.mjs +10 -10
  70. package/dist/index.js +363 -243
  71. package/dist/index.js.map +1 -1
  72. package/dist/index.mjs +15 -15
  73. package/dist/lib/copilot-task.mjs +8 -8
  74. package/dist/lib/index.mjs +8 -8
  75. package/dist/utils/extract.mjs +7 -7
  76. package/dist/utils/index.mjs +7 -7
  77. package/jest.config.js +7 -3
  78. package/package.json +4 -3
  79. package/src/components/copilot-provider/__tests__/copilotkit-trace.test.tsx +1 -0
  80. package/src/components/copilot-provider/copilot-messages.tsx +42 -3
  81. package/src/components/toast/toast-provider.tsx +49 -24
  82. package/src/components/usage-banner.tsx +144 -147
  83. package/src/hooks/use-chat.ts +106 -6
  84. package/src/hooks/use-coagent.ts +5 -0
  85. package/src/hooks/use-copilot-runtime-client.ts +2 -39
  86. package/tsconfig.json +1 -8
  87. package/dist/chunk-HD2GE3DK.mjs +0 -359
  88. package/dist/chunk-HD2GE3DK.mjs.map +0 -1
  89. package/dist/chunk-ISYBUDL4.mjs.map +0 -1
  90. package/dist/chunk-JXF732XG.mjs.map +0 -1
  91. package/dist/chunk-VJCHRQ7Q.mjs.map +0 -1
  92. package/dist/chunk-VRXANACV.mjs +0 -277
  93. package/dist/chunk-VRXANACV.mjs.map +0 -1
  94. /package/dist/{chunk-CCESTGAM.mjs.map → chunk-3OQM3NEK.mjs.map} +0 -0
  95. /package/dist/{chunk-T4ZKC4X4.mjs.map → chunk-3YHYWAHK.mjs.map} +0 -0
  96. /package/dist/{chunk-S4BOATBG.mjs.map → chunk-EF5BNM34.mjs.map} +0 -0
  97. /package/dist/{chunk-I4JPQECN.mjs.map → chunk-EXU7GWLC.mjs.map} +0 -0
  98. /package/dist/{chunk-7G6RR4HE.mjs.map → chunk-FXK6RQIN.mjs.map} +0 -0
  99. /package/dist/{chunk-JHIZ5HAI.mjs.map → chunk-NQVCZQ5T.mjs.map} +0 -0
  100. /package/dist/{chunk-VF6UPRKM.mjs.map → chunk-OF4SZTLL.mjs.map} +0 -0
  101. /package/dist/{chunk-QQZLIEXK.mjs.map → chunk-SJJNFYGQ.mjs.map} +0 -0
  102. /package/dist/{chunk-RN3ZRHI7.mjs.map → chunk-WOGURSAL.mjs.map} +0 -0
@@ -1,359 +0,0 @@
1
- // src/components/usage-banner.tsx
2
- import { Severity, ERROR_NAMES, ErrorVisibility } from "@copilotkit/shared";
3
- import { jsx, jsxs } from "react/jsx-runtime";
4
- var defaultIcons = {
5
- [Severity.CRITICAL]: /* @__PURE__ */ jsxs(
6
- "svg",
7
- {
8
- viewBox: "0 0 24 24",
9
- width: "18",
10
- height: "18",
11
- stroke: "currentColor",
12
- strokeWidth: "2.5",
13
- fill: "none",
14
- strokeLinecap: "round",
15
- strokeLinejoin: "round",
16
- children: [
17
- /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "10" }),
18
- /* @__PURE__ */ jsx("line", { x1: "15", y1: "9", x2: "9", y2: "15" }),
19
- /* @__PURE__ */ jsx("line", { x1: "9", y1: "9", x2: "15", y2: "15" })
20
- ]
21
- }
22
- ),
23
- [Severity.WARNING]: /* @__PURE__ */ jsxs(
24
- "svg",
25
- {
26
- viewBox: "0 0 24 24",
27
- width: "18",
28
- height: "18",
29
- stroke: "currentColor",
30
- strokeWidth: "2.5",
31
- fill: "none",
32
- strokeLinecap: "round",
33
- strokeLinejoin: "round",
34
- children: [
35
- /* @__PURE__ */ jsx("path", { d: "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" }),
36
- /* @__PURE__ */ jsx("line", { x1: "12", y1: "9", x2: "12", y2: "13" }),
37
- /* @__PURE__ */ jsx("line", { x1: "12", y1: "17", x2: "12.01", y2: "17" })
38
- ]
39
- }
40
- ),
41
- [Severity.INFO]: /* @__PURE__ */ jsxs(
42
- "svg",
43
- {
44
- viewBox: "0 0 24 24",
45
- width: "18",
46
- height: "18",
47
- stroke: "currentColor",
48
- strokeWidth: "2.5",
49
- fill: "none",
50
- strokeLinecap: "round",
51
- strokeLinejoin: "round",
52
- children: [
53
- /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "10" }),
54
- /* @__PURE__ */ jsx("line", { x1: "12", y1: "16", x2: "12", y2: "12" }),
55
- /* @__PURE__ */ jsx("line", { x1: "12", y1: "8", x2: "12.01", y2: "8" })
56
- ]
57
- }
58
- )
59
- };
60
- function UsageBanner({
61
- severity = Severity.CRITICAL,
62
- message = "",
63
- icon,
64
- onClose,
65
- actions
66
- }) {
67
- if (!message || !severity) {
68
- return null;
69
- }
70
- const parseMessage = (rawMessage) => {
71
- const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
72
- const matches = Array.from(rawMessage.matchAll(linkRegex));
73
- if (matches.length > 0) {
74
- let cleanMessage2 = rawMessage.replace(/\.\s*See more:\s*\[([^\]]+)\]\(([^)]+)\)/g, ".").replace(/See more:\s*\[([^\]]+)\]\(([^)]+)\)/g, "").trim();
75
- return cleanMessage2;
76
- }
77
- return rawMessage;
78
- };
79
- const cleanMessage = parseMessage(message);
80
- const Icon = icon || defaultIcons[severity];
81
- const themeConfigs = {
82
- [Severity.INFO]: {
83
- bg: "linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%)",
84
- border: "#93c5fd",
85
- text: "#1e40af",
86
- icon: "#3b82f6",
87
- primaryBtn: "#3b82f6",
88
- primaryBtnHover: "#2563eb"
89
- },
90
- [Severity.WARNING]: {
91
- bg: "linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%)",
92
- border: "#fbbf24",
93
- text: "#92400e",
94
- icon: "#f59e0b",
95
- primaryBtn: "#f59e0b",
96
- primaryBtnHover: "#d97706"
97
- },
98
- [Severity.CRITICAL]: {
99
- bg: "linear-gradient(135deg, #fef2f2 0%, #fecaca 100%)",
100
- border: "#f87171",
101
- text: "#991b1b",
102
- icon: "#ef4444",
103
- primaryBtn: "#ef4444",
104
- primaryBtnHover: "#dc2626"
105
- }
106
- };
107
- const themeConfig = themeConfigs[severity] || themeConfigs[Severity.CRITICAL];
108
- return /* @__PURE__ */ jsxs(
109
- "div",
110
- {
111
- style: {
112
- position: "fixed",
113
- bottom: "20px",
114
- left: "50%",
115
- transform: "translateX(-50%)",
116
- maxWidth: "min(95vw, 680px)",
117
- width: "100%",
118
- zIndex: 1e4,
119
- animation: "bannerSlideIn 0.4s cubic-bezier(0.16, 1, 0.3, 1)"
120
- },
121
- children: [
122
- /* @__PURE__ */ jsx("style", { children: `
123
- @keyframes bannerSlideIn {
124
- from {
125
- opacity: 0;
126
- transform: translateX(-50%) translateY(10px);
127
- }
128
- to {
129
- opacity: 1;
130
- transform: translateX(-50%) translateY(0);
131
- }
132
- }
133
- ` }),
134
- /* @__PURE__ */ jsxs(
135
- "div",
136
- {
137
- style: {
138
- display: "flex",
139
- alignItems: "flex-start",
140
- gap: "14px",
141
- borderRadius: "16px",
142
- border: `1px solid ${themeConfig.border}`,
143
- background: themeConfig.bg,
144
- padding: "18px 20px",
145
- boxShadow: "0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1)",
146
- position: "relative",
147
- backdropFilter: "blur(10px)",
148
- WebkitBackdropFilter: "blur(10px)"
149
- },
150
- children: [
151
- onClose && /* @__PURE__ */ jsx(
152
- "button",
153
- {
154
- onClick: onClose,
155
- style: {
156
- position: "absolute",
157
- top: "12px",
158
- right: "12px",
159
- background: "rgba(255, 255, 255, 0.8)",
160
- border: "none",
161
- color: themeConfig.text,
162
- cursor: "pointer",
163
- fontSize: "18px",
164
- lineHeight: "1",
165
- padding: "6px",
166
- borderRadius: "8px",
167
- opacity: 0.7,
168
- transition: "all 0.2s ease",
169
- display: "flex",
170
- alignItems: "center",
171
- justifyContent: "center",
172
- width: "28px",
173
- height: "28px"
174
- },
175
- title: "Close",
176
- onMouseOver: (e) => {
177
- e.currentTarget.style.opacity = "1";
178
- e.currentTarget.style.background = "rgba(255, 255, 255, 1)";
179
- e.currentTarget.style.transform = "scale(1.05)";
180
- },
181
- onMouseOut: (e) => {
182
- e.currentTarget.style.opacity = "0.7";
183
- e.currentTarget.style.background = "rgba(255, 255, 255, 0.8)";
184
- e.currentTarget.style.transform = "scale(1)";
185
- },
186
- children: "\xD7"
187
- }
188
- ),
189
- /* @__PURE__ */ jsx(
190
- "div",
191
- {
192
- style: {
193
- color: themeConfig.icon,
194
- flexShrink: 0,
195
- marginTop: "1px",
196
- padding: "6px",
197
- borderRadius: "10px",
198
- background: "rgba(255, 255, 255, 0.7)",
199
- display: "flex",
200
- alignItems: "center",
201
- justifyContent: "center"
202
- },
203
- children: Icon
204
- }
205
- ),
206
- /* @__PURE__ */ jsxs("div", { style: { flex: 1, paddingRight: onClose ? "40px" : "0" }, children: [
207
- /* @__PURE__ */ jsx(
208
- "div",
209
- {
210
- style: {
211
- fontSize: "15px",
212
- fontWeight: 600,
213
- color: themeConfig.text,
214
- lineHeight: "1.5",
215
- marginBottom: actions ? "12px" : "0",
216
- fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
217
- },
218
- children: cleanMessage
219
- }
220
- ),
221
- actions && /* @__PURE__ */ jsxs(
222
- "div",
223
- {
224
- style: {
225
- display: "flex",
226
- gap: "10px",
227
- flexWrap: "wrap"
228
- },
229
- children: [
230
- actions.secondary && /* @__PURE__ */ jsx(
231
- "button",
232
- {
233
- onClick: actions.secondary.onClick,
234
- style: {
235
- borderRadius: "10px",
236
- padding: "8px 16px",
237
- fontSize: "14px",
238
- fontWeight: 500,
239
- color: themeConfig.text,
240
- backgroundColor: "rgba(255, 255, 255, 0.8)",
241
- border: `1.5px solid ${themeConfig.border}`,
242
- cursor: "pointer",
243
- transition: "all 0.2s ease",
244
- fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
245
- },
246
- onMouseOver: (e) => {
247
- e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 1)";
248
- e.currentTarget.style.transform = "translateY(-1px)";
249
- e.currentTarget.style.boxShadow = "0 4px 12px rgba(0, 0, 0, 0.15)";
250
- },
251
- onMouseOut: (e) => {
252
- e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.8)";
253
- e.currentTarget.style.transform = "translateY(0)";
254
- e.currentTarget.style.boxShadow = "none";
255
- },
256
- children: actions.secondary.label
257
- }
258
- ),
259
- actions.primary && /* @__PURE__ */ jsx(
260
- "button",
261
- {
262
- onClick: actions.primary.onClick,
263
- style: {
264
- borderRadius: "10px",
265
- padding: "8px 16px",
266
- fontSize: "14px",
267
- fontWeight: 600,
268
- color: "#fff",
269
- backgroundColor: themeConfig.primaryBtn,
270
- border: "none",
271
- cursor: "pointer",
272
- transition: "all 0.2s ease",
273
- boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
274
- fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
275
- },
276
- onMouseOver: (e) => {
277
- e.currentTarget.style.backgroundColor = themeConfig.primaryBtnHover;
278
- e.currentTarget.style.transform = "translateY(-1px)";
279
- e.currentTarget.style.boxShadow = "0 6px 16px rgba(0, 0, 0, 0.2)";
280
- },
281
- onMouseOut: (e) => {
282
- e.currentTarget.style.backgroundColor = themeConfig.primaryBtn;
283
- e.currentTarget.style.transform = "translateY(0)";
284
- e.currentTarget.style.boxShadow = "0 4px 12px rgba(0, 0, 0, 0.15)";
285
- },
286
- children: actions.primary.label
287
- }
288
- )
289
- ]
290
- }
291
- )
292
- ] })
293
- ]
294
- }
295
- )
296
- ]
297
- }
298
- );
299
- }
300
- function renderCopilotKitUsage(error, onClose) {
301
- if (error.visibility !== ErrorVisibility.BANNER) {
302
- return null;
303
- }
304
- const extractUrlFromMessage = (message) => {
305
- const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
306
- const match = linkRegex.exec(message);
307
- return match ? match[2] : null;
308
- };
309
- const getErrorActions = (error2) => {
310
- switch (error2.name) {
311
- case ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR:
312
- return {
313
- primary: {
314
- label: "Sign In",
315
- onClick: () => window.location.href = "https://cloud.copilotkit.ai"
316
- }
317
- };
318
- case ERROR_NAMES.UPGRADE_REQUIRED_ERROR:
319
- return {
320
- primary: {
321
- label: "Upgrade",
322
- onClick: () => window.location.href = "https://copilotkit.ai/"
323
- }
324
- };
325
- case ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR:
326
- case ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:
327
- case ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR:
328
- return {
329
- primary: {
330
- label: "View Docs",
331
- onClick: () => {
332
- var _a;
333
- const urlFromMessage = extractUrlFromMessage(error2.message);
334
- const urlFromExtensions = (_a = error2.extensions) == null ? void 0 : _a.troubleshootingUrl;
335
- const url = urlFromMessage || urlFromExtensions || "https://docs.copilotkit.ai/troubleshooting/common-issues";
336
- window.open(url, "_blank");
337
- }
338
- }
339
- };
340
- default:
341
- return void 0;
342
- }
343
- };
344
- return /* @__PURE__ */ jsx(
345
- UsageBanner,
346
- {
347
- severity: error.severity || Severity.CRITICAL,
348
- message: error.message,
349
- onClose,
350
- actions: getErrorActions(error)
351
- }
352
- );
353
- }
354
-
355
- export {
356
- UsageBanner,
357
- renderCopilotKitUsage
358
- };
359
- //# sourceMappingURL=chunk-HD2GE3DK.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/usage-banner.tsx"],"sourcesContent":["import { Severity, CopilotKitError, ERROR_NAMES, ErrorVisibility } from \"@copilotkit/shared\";\n\ninterface UsageBannerProps {\n severity?: Severity;\n message?: string;\n icon?: React.ReactNode;\n onClose?: () => void;\n actions?: {\n primary?: {\n label: string;\n onClick: () => void;\n };\n secondary?: {\n label: string;\n onClick: () => void;\n };\n };\n}\n\nconst defaultIcons: Record<Severity, JSX.Element> = {\n [Severity.CRITICAL]: (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"18\"\n height=\"18\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"15\" y1=\"9\" x2=\"9\" y2=\"15\" />\n <line x1=\"9\" y1=\"9\" x2=\"15\" y2=\"15\" />\n </svg>\n ),\n [Severity.WARNING]: (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"18\"\n height=\"18\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z\" />\n <line x1=\"12\" y1=\"9\" x2=\"12\" y2=\"13\" />\n <line x1=\"12\" y1=\"17\" x2=\"12.01\" y2=\"17\" />\n </svg>\n ),\n [Severity.INFO]: (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"18\"\n height=\"18\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"12\" y1=\"16\" x2=\"12\" y2=\"12\" />\n <line x1=\"12\" y1=\"8\" x2=\"12.01\" y2=\"8\" />\n </svg>\n ),\n};\n\nexport function UsageBanner({\n severity = Severity.CRITICAL,\n message = \"\",\n icon,\n onClose,\n actions,\n}: UsageBannerProps) {\n if (!message || !severity) {\n return null;\n }\n\n // Parse markdown links from message and clean it up\n const parseMessage = (rawMessage: string) => {\n // Extract markdown links: [text](url)\n const linkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const matches = Array.from(rawMessage.matchAll(linkRegex));\n\n if (matches.length > 0) {\n // Remove \"See more:\" and markdown links from the main message\n let cleanMessage = rawMessage\n .replace(/\\.\\s*See more:\\s*\\[([^\\]]+)\\]\\(([^)]+)\\)/g, \".\")\n .replace(/See more:\\s*\\[([^\\]]+)\\]\\(([^)]+)\\)/g, \"\")\n .trim();\n\n return cleanMessage;\n }\n\n return rawMessage;\n };\n\n const cleanMessage = parseMessage(message);\n const Icon = icon || defaultIcons[severity];\n\n const themeConfigs = {\n [Severity.INFO]: {\n bg: \"linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%)\",\n border: \"#93c5fd\",\n text: \"#1e40af\",\n icon: \"#3b82f6\",\n primaryBtn: \"#3b82f6\",\n primaryBtnHover: \"#2563eb\",\n },\n [Severity.WARNING]: {\n bg: \"linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%)\",\n border: \"#fbbf24\",\n text: \"#92400e\",\n icon: \"#f59e0b\",\n primaryBtn: \"#f59e0b\",\n primaryBtnHover: \"#d97706\",\n },\n [Severity.CRITICAL]: {\n bg: \"linear-gradient(135deg, #fef2f2 0%, #fecaca 100%)\",\n border: \"#f87171\",\n text: \"#991b1b\",\n icon: \"#ef4444\",\n primaryBtn: \"#ef4444\",\n primaryBtnHover: \"#dc2626\",\n },\n };\n\n const themeConfig = themeConfigs[severity] || themeConfigs[Severity.CRITICAL];\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n maxWidth: \"min(95vw, 680px)\",\n width: \"100%\",\n zIndex: 10000,\n animation: \"bannerSlideIn 0.4s cubic-bezier(0.16, 1, 0.3, 1)\",\n }}\n >\n <style>\n {`\n @keyframes bannerSlideIn {\n from {\n opacity: 0;\n transform: translateX(-50%) translateY(10px);\n }\n to {\n opacity: 1;\n transform: translateX(-50%) translateY(0);\n }\n }\n `}\n </style>\n <div\n style={{\n display: \"flex\",\n alignItems: \"flex-start\",\n gap: \"14px\",\n borderRadius: \"16px\",\n border: `1px solid ${themeConfig.border}`,\n background: themeConfig.bg,\n padding: \"18px 20px\",\n boxShadow: \"0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1)\",\n position: \"relative\",\n backdropFilter: \"blur(10px)\",\n WebkitBackdropFilter: \"blur(10px)\",\n }}\n >\n {/* Close button */}\n {onClose && (\n <button\n onClick={onClose}\n style={{\n position: \"absolute\",\n top: \"12px\",\n right: \"12px\",\n background: \"rgba(255, 255, 255, 0.8)\",\n border: \"none\",\n color: themeConfig.text,\n cursor: \"pointer\",\n fontSize: \"18px\",\n lineHeight: \"1\",\n padding: \"6px\",\n borderRadius: \"8px\",\n opacity: 0.7,\n transition: \"all 0.2s ease\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n width: \"28px\",\n height: \"28px\",\n }}\n title=\"Close\"\n onMouseOver={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(255, 255, 255, 1)\";\n e.currentTarget.style.transform = \"scale(1.05)\";\n }}\n onMouseOut={(e) => {\n e.currentTarget.style.opacity = \"0.7\";\n e.currentTarget.style.background = \"rgba(255, 255, 255, 0.8)\";\n e.currentTarget.style.transform = \"scale(1)\";\n }}\n >\n ×\n </button>\n )}\n\n {/* Icon */}\n <div\n style={{\n color: themeConfig.icon,\n flexShrink: 0,\n marginTop: \"1px\",\n padding: \"6px\",\n borderRadius: \"10px\",\n background: \"rgba(255, 255, 255, 0.7)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n {Icon}\n </div>\n\n {/* Content */}\n <div style={{ flex: 1, paddingRight: onClose ? \"40px\" : \"0\" }}>\n {/* Message */}\n <div\n style={{\n fontSize: \"15px\",\n fontWeight: 600,\n color: themeConfig.text,\n lineHeight: \"1.5\",\n marginBottom: actions ? \"12px\" : \"0\",\n fontFamily: \"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\",\n }}\n >\n {cleanMessage}\n </div>\n\n {/* Actions */}\n {actions && (\n <div\n style={{\n display: \"flex\",\n gap: \"10px\",\n flexWrap: \"wrap\",\n }}\n >\n {actions.secondary && (\n <button\n onClick={actions.secondary.onClick}\n style={{\n borderRadius: \"10px\",\n padding: \"8px 16px\",\n fontSize: \"14px\",\n fontWeight: 500,\n color: themeConfig.text,\n backgroundColor: \"rgba(255, 255, 255, 0.8)\",\n border: `1.5px solid ${themeConfig.border}`,\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n fontFamily: \"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\",\n }}\n onMouseOver={(e) => {\n e.currentTarget.style.backgroundColor = \"rgba(255, 255, 255, 1)\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n e.currentTarget.style.boxShadow = \"0 4px 12px rgba(0, 0, 0, 0.15)\";\n }}\n onMouseOut={(e) => {\n e.currentTarget.style.backgroundColor = \"rgba(255, 255, 255, 0.8)\";\n e.currentTarget.style.transform = \"translateY(0)\";\n e.currentTarget.style.boxShadow = \"none\";\n }}\n >\n {actions.secondary.label}\n </button>\n )}\n {actions.primary && (\n <button\n onClick={actions.primary.onClick}\n style={{\n borderRadius: \"10px\",\n padding: \"8px 16px\",\n fontSize: \"14px\",\n fontWeight: 600,\n color: \"#fff\",\n backgroundColor: themeConfig.primaryBtn,\n border: \"none\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n fontFamily: \"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\",\n }}\n onMouseOver={(e) => {\n e.currentTarget.style.backgroundColor = themeConfig.primaryBtnHover;\n e.currentTarget.style.transform = \"translateY(-1px)\";\n e.currentTarget.style.boxShadow = \"0 6px 16px rgba(0, 0, 0, 0.2)\";\n }}\n onMouseOut={(e) => {\n e.currentTarget.style.backgroundColor = themeConfig.primaryBtn;\n e.currentTarget.style.transform = \"translateY(0)\";\n e.currentTarget.style.boxShadow = \"0 4px 12px rgba(0, 0, 0, 0.15)\";\n }}\n >\n {actions.primary.label}\n </button>\n )}\n </div>\n )}\n </div>\n </div>\n </div>\n );\n}\n\nexport function renderCopilotKitUsage(error: CopilotKitError, onClose?: () => void) {\n // Route based on error visibility level\n if (error.visibility !== ErrorVisibility.BANNER) {\n return null;\n }\n\n // Extract URL from markdown links in the message\n const extractUrlFromMessage = (message: string): string | null => {\n const linkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const match = linkRegex.exec(message);\n return match ? match[2] : null;\n };\n\n // Get action button based on error type\n const getErrorActions = (error: CopilotKitError) => {\n switch (error.name) {\n case ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR:\n return {\n primary: {\n label: \"Sign In\",\n onClick: () => (window.location.href = \"https://cloud.copilotkit.ai\"),\n },\n };\n case ERROR_NAMES.UPGRADE_REQUIRED_ERROR:\n return {\n primary: {\n label: \"Upgrade\",\n onClick: () => (window.location.href = \"https://copilotkit.ai/\"),\n },\n };\n case ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR:\n case ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:\n case ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR:\n return {\n primary: {\n label: \"View Docs\",\n onClick: () => {\n // Try to get URL from the error message first, then extensions, then default\n const urlFromMessage = extractUrlFromMessage(error.message);\n const urlFromExtensions = (error.extensions as any)?.troubleshootingUrl;\n const url =\n urlFromMessage ||\n urlFromExtensions ||\n \"https://docs.copilotkit.ai/troubleshooting/common-issues\";\n window.open(url, \"_blank\");\n },\n },\n };\n default:\n return undefined;\n }\n };\n\n return (\n <UsageBanner\n severity={error.severity || Severity.CRITICAL}\n message={error.message}\n onClose={onClose}\n actions={getErrorActions(error)}\n />\n );\n}\n"],"mappings":";AAAA,SAAS,UAA2B,aAAa,uBAAuB;AAqBpE,SAUE,KAVF;AAFJ,IAAM,eAA8C;AAAA,EAClD,CAAC,SAAS,QAAQ,GAChB;AAAA,IAAC;AAAA;AAAA,MACC,SAAQ;AAAA,MACR,OAAM;AAAA,MACN,QAAO;AAAA,MACP,QAAO;AAAA,MACP,aAAY;AAAA,MACZ,MAAK;AAAA,MACL,eAAc;AAAA,MACd,gBAAe;AAAA,MAEf;AAAA,4BAAC,YAAO,IAAG,MAAK,IAAG,MAAK,GAAE,MAAK;AAAA,QAC/B,oBAAC,UAAK,IAAG,MAAK,IAAG,KAAI,IAAG,KAAI,IAAG,MAAK;AAAA,QACpC,oBAAC,UAAK,IAAG,KAAI,IAAG,KAAI,IAAG,MAAK,IAAG,MAAK;AAAA;AAAA;AAAA,EACtC;AAAA,EAEF,CAAC,SAAS,OAAO,GACf;AAAA,IAAC;AAAA;AAAA,MACC,SAAQ;AAAA,MACR,OAAM;AAAA,MACN,QAAO;AAAA,MACP,QAAO;AAAA,MACP,aAAY;AAAA,MACZ,MAAK;AAAA,MACL,eAAc;AAAA,MACd,gBAAe;AAAA,MAEf;AAAA,4BAAC,UAAK,GAAE,6EAA4E;AAAA,QACpF,oBAAC,UAAK,IAAG,MAAK,IAAG,KAAI,IAAG,MAAK,IAAG,MAAK;AAAA,QACrC,oBAAC,UAAK,IAAG,MAAK,IAAG,MAAK,IAAG,SAAQ,IAAG,MAAK;AAAA;AAAA;AAAA,EAC3C;AAAA,EAEF,CAAC,SAAS,IAAI,GACZ;AAAA,IAAC;AAAA;AAAA,MACC,SAAQ;AAAA,MACR,OAAM;AAAA,MACN,QAAO;AAAA,MACP,QAAO;AAAA,MACP,aAAY;AAAA,MACZ,MAAK;AAAA,MACL,eAAc;AAAA,MACd,gBAAe;AAAA,MA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AM,CAAC,IAAI;AAAA,EAC5B;AAGA,QAAM,kBAAkB,CAACC,WAA2B;AAClD,YAAQA,OAAM,MAAM;AAAA,MAClB,KAAK,YAAY;AACf,eAAO;AAAA,UACL,SAAS;AAAA,YACP,OAAO;AAAA,YACP,SAAS,MAAO,OAAO,SAAS,OAAO;AAAA,UACzC;AAAA,QACF;AAAA,MACF,KAAK,YAAY;AACf,eAAO;AAAA,UACL,SAAS;AAAA,YACP,OAAO;AAAA,YACP,SAAS,MAAO,OAAO,SAAS,OAAO;AAAA,UACzC;AAAA,QACF;AAAA,MACF,KAAK,YAAY;AAAA,MACjB,KAAK,YAAY;AAAA,MACjB,KAAK,YAAY;AACf,eAAO;AAAA,UACL,SAAS;AAAA,YACP,OAAO;AAAA,YACP,SAAS,MAAM;AAvW3B;AAyWc,oBAAM,iBAAiB,sBAAsBA,OAAM,OAAO;AAC1D,oBAAM,qBAAqB,KAAAA,OAAM,eAAN,mBAA0B;AACrD,oBAAM,MACJ,kBACA,qBACA;AACF,qBAAO,KAAK,KAAK,QAAQ;AAAA,YAC3B;AAAA,UACF;AAAA,QACF;AAAA,MACF;AACE,eAAO;AAAA,IACX;AAAA,EACF;AAEA,SACE;AAAA,IAAC;AAAA;AAAA,MACC,UAAU,MAAM,YAAY,SAAS;AAAA,MACrC,SAAS,MAAM;AAAA,MACf;AAAA,MACA,SAAS,gBAAgB,KAAK;AAAA;AAAA,EAChC;AAEJ;","names":["cleanMessage","error"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/use-copilot-runtime-client.ts"],"sourcesContent":["import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo, useRef } from \"react\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n ERROR_CONFIG,\n CopilotTraceHandler,\n CopilotTraceEvent,\n} from \"@copilotkit/shared\";\nimport { shouldShowDevConsole } from \"../utils/dev-console\";\n\nexport interface CopilotRuntimeClientHookOptions extends CopilotRuntimeClientOptions {\n showDevConsole?: boolean;\n onTrace?: CopilotTraceHandler;\n}\n\nexport const useCopilotRuntimeClient = (options: CopilotRuntimeClientHookOptions) => {\n const { setBannerError } = useToast();\n const { showDevConsole, onTrace, ...runtimeOptions } = options;\n\n // Deduplication state for structured errors\n const lastStructuredErrorRef = useRef<{ message: string; timestamp: number } | null>(null);\n\n // Helper function to trace UI errors\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\n if (!onTrace || !runtimeOptions.publicApiKey) return;\n\n try {\n const traceEvent: CopilotTraceEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"ui\",\n request: {\n operation: \"runtimeClient\",\n url: runtimeOptions.url,\n startTime: Date.now(),\n },\n technical: {\n environment: process.env.NODE_ENV,\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n\n await onTrace(traceEvent);\n } catch (traceError) {\n console.error(\"Error in onTrace handler:\", traceError);\n }\n };\n\n const runtimeClient = useMemo(() => {\n return new CopilotRuntimeClient({\n ...runtimeOptions,\n handleGQLErrors: (error) => {\n if ((error as any).graphQLErrors?.length) {\n const graphQLErrors = (error as any).graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole ?? false);\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // Respect showDevConsole setting for ALL errors\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", gqlError.message);\n return;\n }\n\n // All errors (including DEV_ONLY) show as banners for consistency\n // Deduplicate to prevent spam\n const now = Date.now();\n const errorMessage = gqlError.message;\n if (\n lastStructuredErrorRef.current &&\n lastStructuredErrorRef.current.message === errorMessage &&\n now - lastStructuredErrorRef.current.timestamp < 150\n ) {\n return; // Skip duplicate\n }\n lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };\n\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the error\n traceUIError(ckError, gqlError);\n } else {\n // Fallback for unstructured errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole ?? false);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n }\n }\n },\n handleGQLWarning: (message: string) => {\n console.warn(message);\n // Show warnings as banners too for consistency\n const warningError = new CopilotKitError({\n message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(warningError);\n },\n });\n }, [runtimeOptions, setBannerError, showDevConsole, onTrace]);\n\n return runtimeClient;\n};\n\n// Helper to determine if error should show as banner based on structured error system\nfunction shouldShowAsBanner(gqlError: GraphQLError): boolean {\n const extensions = gqlError.extensions;\n if (!extensions) return false;\n\n // Primary: Check error code and use structured config\n const code = extensions.code as CopilotKitErrorCode;\n if (code && ERROR_CONFIG[code]?.visibility === ErrorVisibility.BANNER) {\n return true;\n }\n\n // Fallback: Check for API key errors which should always be banners\n const errorMessage = gqlError.message.toLowerCase();\n if (\n errorMessage.includes(\"api key\") ||\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"unauthorized\") ||\n errorMessage.includes(\"authentication\") ||\n errorMessage.includes(\"incorrect api key\")\n ) {\n return true;\n }\n\n // Legacy: Check by stack trace for discovery errors (for backward compatibility)\n const originalError = extensions.originalError as any;\n if (originalError?.stack) {\n return (\n originalError.stack.includes(\"CopilotApiDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")\n );\n }\n\n return false;\n}\n\n// Create appropriate structured error from GraphQL error\nfunction createStructuredError(gqlError: GraphQLError): CopilotKitError | null {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n // Legacy error detection by stack trace\n if (originalError?.stack?.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,OAGK;AAEP,SAAS,SAAS,cAAc;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAQA,IAAM,0BAA0B,CAAC,YAA6C;AACnF,QAAM,EAAE,eAAe,IAAI,SAAS;AACpC,QAAuD,cAA/C,kBAAgB,QA3B1B,IA2ByD,IAAnB,2BAAmB,IAAnB,CAA5B,kBAAgB;AAGxB,QAAM,yBAAyB,OAAsD,IAAI;AAGzF,QAAM,eAAe,CAAO,OAAwB,kBAAwB;AAC1E,QAA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e,UAAf,mBAAsB,SAAS,6BAA6B;AAC9D,WAAO,IAAI,4BAA4B,EAAE,QAAQ,CAAC;AAAA,EACpD;AACA,OAAI,oDAAe,UAAf,mBAAsB,SAAS,2CAA2C;AAC5E,WAAO,IAAI,uCAAuC,EAAE,QAAQ,CAAC;AAAA,EAC/D;AACA,OAAI,oDAAe,UAAf,mBAAsB,SAAS,kCAAkC;AACnE,WAAO,IAAI,8BAA8B;AAAA,MACvC,WAAW;AAAA,MACX,iBAAiB,CAAC;AAAA,IACpB,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":["_a"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/use-chat.ts"],"sourcesContent":["import React, { useCallback, useEffect, useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n CoAgentStateRenderHandler,\n randomId,\n parseJson,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ResultMessage,\n convertMessagesToGqlInput,\n filterAdjacentAgentStateMessages,\n filterAgentStateMessages,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n ForwardedParametersInput,\n loadMessagesFromJsonRepresentation,\n ExtensionsInput,\n CopilotRuntimeClient,\n langGraphInterruptEvent,\n MetaEvent,\n MetaEventName,\n ActionExecutionMessage,\n CopilotKitLangGraphInterruptEvent,\n LangGraphInterruptEvent,\n MetaEventInput,\n AgentStateInput,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession } from \"../context/copilot-context\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { useAsyncCallback, useErrorToast } from \"../components/error-boundary/error-utils\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n\n /**\n * Callback function to be called when a coagent action is received.\n */\n onCoAgentStateRender?: CoAgentStateRenderHandler;\n\n /**\n * Function definitions to be sent to the API.\n */\n actions: FrontendAction<any>[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * The current list of coagent states.\n */\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStatesWithRef: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n\n /**\n * The current agent session.\n */\n agentSession: AgentSession | null;\n\n /**\n * setState-powered method to update the agent session\n */\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n /**\n * The forwarded parameters.\n */\n forwardedParameters?: Pick<ForwardedParametersInput, \"temperature\">;\n\n /**\n * The current thread ID.\n */\n threadId: string;\n /**\n * set the current thread ID\n */\n setThreadId: (threadId: string) => void;\n /**\n * The current run ID.\n */\n runId: string | null;\n /**\n * set the current run ID\n */\n setRunId: (runId: string | null) => void;\n /**\n * The global chat abort controller.\n */\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n /**\n * The agent lock.\n */\n agentLock: string | null;\n /**\n * The extensions.\n */\n extensions: ExtensionsInput;\n /**\n * The setState-powered method to update the extensions.\n */\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n\n langGraphInterruptAction: LangGraphInterruptAction | null;\n\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (messageId: string) => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Run the chat completion.\n */\n runChatCompletion: () => Promise<Message[]>;\n};\n\nexport interface AppendMessageOptions {\n /**\n * Whether to run the chat completion after appending the message. Defaults to `true`.\n */\n followUp?: boolean;\n}\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStatesWithRef,\n coagentStatesRef,\n agentSession,\n setAgentSession,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n } = options;\n const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();\n const addErrorToast = useErrorToast();\n // We need to keep a ref of coagent states and session because of renderAndWait - making sure\n // the latest state is sent to the API\n // This is a workaround and needs to be addressed in the future\n const agentSessionRef = useRef<AgentSession | null>(agentSession);\n agentSessionRef.current = agentSession;\n\n const runIdRef = useRef<string | null>(runId);\n runIdRef.current = runId;\n const extensionsRef = useRef<ExtensionsInput>(extensions);\n extensionsRef.current = extensions;\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const { showDevConsole } = useCopilotContext();\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n showDevConsole,\n });\n\n const pendingAppendsRef = useRef<{ message: Message; followUp: boolean }[]>([]);\n\n const runChatCompletion = useAsyncCallback(\n async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n const interruptEvent = langGraphInterruptAction?.event;\n // In case an interrupt event exist and valid but has no response yet, we cannot process further messages to an agent\n if (\n interruptEvent?.name === MetaEventName.LangGraphInterruptEvent &&\n interruptEvent?.value &&\n !interruptEvent?.response &&\n agentSessionRef.current\n ) {\n addErrorToast([\n new Error(\n \"A message was sent while interrupt is active. This will cause failure on the agent side\",\n ),\n ]);\n }\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n\n chatAbortControllerRef.current = new AbortController();\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n // ----- Set mcpServers in properties -----\n // Create a copy of properties to avoid modifying the original object\n const finalProperties = { ...(copilotConfig.properties || {}) };\n\n // Look for mcpServers in either direct property or properties\n let mcpServersToUse = null;\n\n // First check direct mcpServers property\n if (\n copilotConfig.mcpServers &&\n Array.isArray(copilotConfig.mcpServers) &&\n copilotConfig.mcpServers.length > 0\n ) {\n mcpServersToUse = copilotConfig.mcpServers;\n }\n // Then check mcpServers in properties\n else if (\n copilotConfig.properties?.mcpServers &&\n Array.isArray(copilotConfig.properties.mcpServers) &&\n copilotConfig.properties.mcpServers.length > 0\n ) {\n mcpServersToUse = copilotConfig.properties.mcpServers;\n }\n\n // Apply the mcpServers to properties if found\n if (mcpServersToUse) {\n // Set in finalProperties\n finalProperties.mcpServers = mcpServersToUse;\n\n // Also set in copilotConfig directly for future use\n copilotConfig.mcpServers = mcpServersToUse;\n }\n // -------------------------------------------------------------\n\n const isAgentRun = agentSessionRef.current !== null;\n\n const stream = runtimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(actions),\n url: window.location.href,\n },\n threadId: threadId,\n runId: runIdRef.current,\n extensions: extensionsRef.current,\n metaEvents: composeAndFlushMetaEventsInput([langGraphInterruptAction?.event]),\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: agentSessionRef.current,\n }\n : {}),\n agentStates: Object.values(coagentStatesRef.current!).map((state) => {\n const stateObject: AgentStateInput = {\n agentName: state.name,\n state: JSON.stringify(state.state),\n };\n\n if (state.config !== undefined) {\n stateObject.config = JSON.stringify(state.config);\n }\n\n return stateObject;\n }),\n forwardedParameters: options.forwardedParameters || {},\n },\n properties: finalProperties,\n signal: chatAbortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let executedCoAgentStateRenders: string[] = [];\n let followUp: FrontendAction[\"followUp\"] = undefined;\n\n let messages: Message[] = [];\n let syncedMessages: Message[] = [];\n let interruptMessages: Message[] = [];\n\n try {\n while (true) {\n let done, value;\n\n try {\n const readResult = await reader.read();\n done = readResult.done;\n value = readResult.value;\n } catch (readError) {\n break;\n }\n\n if (done) {\n if (chatAbortControllerRef.current.signal.aborted) {\n return [];\n }\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n // in the output, graphql inserts __typename, which leads to an error when sending it along\n // as input to the next request.\n extensionsRef.current = CopilotRuntimeClient.removeGraphQLTypename(\n value.generateCopilotResponse.extensions || {},\n );\n\n // setThreadId(threadIdRef.current);\n setRunId(runIdRef.current);\n setExtensions(extensionsRef.current);\n let rawMessagesResponse = value.generateCopilotResponse.messages;\n\n const metaEvents: MetaEvent[] | undefined =\n value.generateCopilotResponse?.metaEvents ?? [];\n (metaEvents ?? []).forEach((ev) => {\n if (ev.name === MetaEventName.LangGraphInterruptEvent) {\n let eventValue = langGraphInterruptEvent(ev as LangGraphInterruptEvent).value;\n eventValue = parseJson(eventValue, eventValue);\n setLangGraphInterruptAction({\n event: {\n ...langGraphInterruptEvent(ev as LangGraphInterruptEvent),\n value: eventValue,\n },\n });\n }\n if (ev.name === MetaEventName.CopilotKitLangGraphInterruptEvent) {\n const data = (ev as CopilotKitLangGraphInterruptEvent).data;\n\n // @ts-expect-error -- same type of messages\n rawMessagesResponse = [...rawMessagesResponse, ...data.messages];\n interruptMessages = convertGqlOutputToMessages(\n // @ts-ignore\n filterAdjacentAgentStateMessages(data.messages),\n );\n }\n });\n\n messages = convertGqlOutputToMessages(\n filterAdjacentAgentStateMessages(rawMessagesResponse),\n );\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message and quit\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n setMessages([...previousMessages, ...newMessages]);\n break;\n }\n\n // add messages to the chat\n else {\n newMessages = [...messages];\n\n for (const message of messages) {\n // execute onCoAgentStateRender handler\n if (\n message.isAgentStateMessage() &&\n !message.active &&\n !executedCoAgentStateRenders.includes(message.id) &&\n onCoAgentStateRender\n ) {\n // Do not execute a coagent action if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute coagent action\n await onCoAgentStateRender({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoAgentStateRenders.push(message.id);\n }\n }\n\n const lastAgentStateMessage = [...messages]\n .reverse()\n .find((message) => message.isAgentStateMessage());\n\n if (lastAgentStateMessage) {\n if (\n lastAgentStateMessage.state.messages &&\n lastAgentStateMessage.state.messages.length > 0\n ) {\n syncedMessages = loadMessagesFromJsonRepresentation(\n lastAgentStateMessage.state.messages,\n );\n }\n setCoagentStatesWithRef((prevAgentStates) => ({\n ...prevAgentStates,\n [lastAgentStateMessage.agentName]: {\n name: lastAgentStateMessage.agentName,\n state: lastAgentStateMessage.state,\n running: lastAgentStateMessage.running,\n active: lastAgentStateMessage.active,\n threadId: lastAgentStateMessage.threadId,\n nodeName: lastAgentStateMessage.nodeName,\n runId: lastAgentStateMessage.runId,\n },\n }));\n if (lastAgentStateMessage.running) {\n setAgentSession({\n threadId: lastAgentStateMessage.threadId,\n agentName: lastAgentStateMessage.agentName,\n nodeName: lastAgentStateMessage.nodeName,\n });\n } else {\n if (agentLock) {\n setAgentSession({\n threadId: randomId(),\n agentName: agentLock,\n nodeName: undefined,\n });\n } else {\n setAgentSession(null);\n }\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Update message state\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n let finalMessages = constructFinalMessages(\n [...syncedMessages, ...interruptMessages],\n previousMessages,\n newMessages,\n );\n\n let didExecuteAction = false;\n\n // execute regular action executions that are specific to the frontend (last actions)\n if (onFunctionCall) {\n // Find consecutive action execution messages at the end\n const lastMessages = [];\n\n for (let i = finalMessages.length - 1; i >= 0; i--) {\n const message = finalMessages[i];\n if (\n (message.isActionExecutionMessage() || message.isResultMessage()) &&\n message.status.code !== MessageStatusCode.Pending\n ) {\n lastMessages.unshift(message);\n } else if (!message.isAgentStateMessage()) {\n break;\n }\n }\n\n for (const message of lastMessages) {\n // We update the message state before calling the handler so that the render\n // function can be called with `executing` state\n setMessages(finalMessages);\n\n const action = actions.find(\n (action) => action.name === (message as ActionExecutionMessage).name,\n );\n const currentResultMessagePairedFeAction = message.isResultMessage()\n ? getPairedFeAction(actions, message)\n : null;\n\n const executeActionFromMessage = async (\n action: FrontendAction<any>,\n message: ActionExecutionMessage,\n ) => {\n const isInterruptAction = interruptMessages.find((m) => m.id === message.id);\n followUp = action?.followUp ?? !isInterruptAction;\n const resultMessage = await executeAction({\n onFunctionCall,\n previousMessages,\n message,\n chatAbortControllerRef,\n onError: (error: Error) => {\n addErrorToast([error]);\n console.error(`Failed to execute action ${message.name}: ${error}`);\n },\n });\n didExecuteAction = true;\n const messageIndex = finalMessages.findIndex((msg) => msg.id === message.id);\n finalMessages.splice(messageIndex + 1, 0, resultMessage);\n\n return resultMessage;\n };\n\n // execution message which has an action registered with the hook (remote availability):\n // execute that action first, and then the \"paired FE action\"\n if (action && message.isActionExecutionMessage()) {\n const resultMessage = await executeActionFromMessage(action, message);\n const pairedFeAction = getPairedFeAction(actions, resultMessage);\n\n if (pairedFeAction) {\n const newExecutionMessage = new ActionExecutionMessage({\n name: pairedFeAction.name,\n arguments: parseJson(resultMessage.result, resultMessage.result),\n status: message.status,\n createdAt: message.createdAt,\n parentMessageId: message.parentMessageId,\n });\n await executeActionFromMessage(pairedFeAction, newExecutionMessage);\n }\n } else if (message.isResultMessage() && currentResultMessagePairedFeAction) {\n // Actions which are set up in runtime actions array: Grab the result, executed paired FE action with it as args.\n const newExecutionMessage = new ActionExecutionMessage({\n name: currentResultMessagePairedFeAction.name,\n arguments: parseJson(message.result, message.result),\n status: message.status,\n createdAt: message.createdAt,\n });\n finalMessages.push(newExecutionMessage);\n await executeActionFromMessage(\n currentResultMessagePairedFeAction,\n newExecutionMessage,\n );\n }\n }\n\n setMessages(finalMessages);\n }\n\n if (\n // if followUp is not explicitly false\n followUp !== false &&\n // and we executed an action\n (didExecuteAction ||\n // the last message is a server side result\n (!isAgentRun &&\n finalMessages.length &&\n finalMessages[finalMessages.length - 1].isResultMessage())) &&\n // the user did not stop generation\n !chatAbortControllerRef.current?.signal.aborted\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletionRef.current!(finalMessages);\n } else if (chatAbortControllerRef.current?.signal.aborted) {\n // filter out all the action execution messages that do not have a consecutive matching result message\n const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {\n if (message.isActionExecutionMessage()) {\n return finalMessages.find(\n (msg, resultIndex) =>\n msg.isResultMessage() &&\n msg.actionExecutionId === message.id &&\n resultIndex === actionExecutionIndex + 1,\n );\n }\n return true;\n });\n const repairedMessageIds = repairedMessages.map((message) => message.id);\n setMessages(repairedMessages);\n\n // LangGraph needs two pieces of information to continue execution:\n // 1. The threadId\n // 2. The nodeName it came from\n // When stopping the agent, we don't know the nodeName the agent would have ended with\n // Therefore, we set the nodeName to the most reasonable thing we can guess, which\n // is \"__end__\"\n if (agentSessionRef.current?.nodeName) {\n setAgentSession({\n threadId: agentSessionRef.current.threadId,\n agentName: agentSessionRef.current.agentName,\n nodeName: \"__end__\",\n });\n }\n // only return new messages that were not filtered out\n return newMessages.filter((message) => repairedMessageIds.includes(message.id));\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n },\n [\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStatesWithRef,\n coagentStatesRef,\n agentSession,\n setAgentSession,\n ],\n );\n\n runChatCompletionRef.current = runChatCompletion;\n\n const runChatCompletionAndHandleFunctionCall = useAsyncCallback(\n async (messages: Message[]): Promise<void> => {\n await runChatCompletionRef.current!(messages);\n },\n [messages],\n );\n\n useEffect(() => {\n if (!isLoading && pendingAppendsRef.current.length > 0) {\n const pending = pendingAppendsRef.current.splice(0);\n const followUp = pending.some((p) => p.followUp);\n const newMessages = [...messages, ...pending.map((p) => p.message)];\n setMessages(newMessages);\n if (followUp) {\n runChatCompletionAndHandleFunctionCall(newMessages);\n }\n }\n }, [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);\n\n // Go over all events and see that they include data that should be returned to the agent\n const composeAndFlushMetaEventsInput = useCallback(\n (metaEvents: (MetaEvent | undefined | null)[]) => {\n return metaEvents.reduce((acc: MetaEventInput[], event) => {\n if (!event) return acc;\n\n switch (event.name) {\n case MetaEventName.LangGraphInterruptEvent:\n if (event.response) {\n // Flush interrupt event from state\n setLangGraphInterruptAction(null);\n const value = (event as LangGraphInterruptEvent).value;\n return [\n ...acc,\n {\n name: event.name,\n value: typeof value === \"string\" ? value : JSON.stringify(value),\n response:\n typeof event.response === \"string\"\n ? event.response\n : JSON.stringify(event.response),\n },\n ];\n }\n return acc;\n default:\n return acc;\n }\n }, []);\n },\n [setLangGraphInterruptAction],\n );\n\n const append = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions): Promise<void> => {\n const followUp = options?.followUp ?? true;\n if (isLoading) {\n pendingAppendsRef.current.push({ message, followUp });\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n if (followUp) {\n return runChatCompletionAndHandleFunctionCall(newMessages);\n }\n },\n [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall],\n );\n\n const reload = useAsyncCallback(\n async (messageId: string): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n\n const index = messages.findIndex((msg) => msg.id === messageId);\n if (index === -1) {\n console.warn(`Message with id ${messageId} not found`);\n return;\n }\n\n let newMessages = messages.slice(0, index); // excludes the message with messageId\n if (newMessages.length > 0 && newMessages[newMessages.length - 1].isAgentStateMessage()) {\n newMessages = newMessages.slice(0, newMessages.length - 1); // remove last one too\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n },\n [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall],\n );\n\n const stop = (): void => {\n chatAbortControllerRef.current?.abort(\"Stop was called\");\n };\n\n return {\n append,\n reload,\n stop,\n runChatCompletion: () => runChatCompletionRef.current!(messages),\n };\n}\n\nfunction constructFinalMessages(\n syncedMessages: Message[],\n previousMessages: Message[],\n newMessages: Message[],\n): Message[] {\n const finalMessages =\n syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];\n\n if (syncedMessages.length > 0) {\n const messagesWithAgentState = [...previousMessages, ...newMessages];\n\n let previousMessageId: string | undefined = undefined;\n\n for (const message of messagesWithAgentState) {\n if (message.isAgentStateMessage()) {\n // insert this message into finalMessages after the position of previousMessageId\n const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);\n if (index !== -1) {\n finalMessages.splice(index + 1, 0, message);\n }\n }\n\n previousMessageId = message.id;\n }\n }\n\n return finalMessages;\n}\n\nasync function executeAction({\n onFunctionCall,\n previousMessages,\n message,\n chatAbortControllerRef,\n onError,\n}: {\n onFunctionCall: FunctionCallHandler;\n previousMessages: Message[];\n message: ActionExecutionMessage;\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n onError: (error: Error) => void;\n}) {\n let result: any;\n let error: Error | null = null;\n try {\n result = await Promise.race([\n onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n }),\n new Promise((resolve) =>\n chatAbortControllerRef.current?.signal.addEventListener(\"abort\", () =>\n resolve(\"Operation was aborted by the user\"),\n ),\n ),\n // if the user stopped generation, we also abort consecutive actions\n new Promise((resolve) => {\n if (chatAbortControllerRef.current?.signal.aborted) {\n resolve(\"Operation was aborted by the user\");\n }\n }),\n ]);\n } catch (e) {\n onError(e as Error);\n }\n return new ResultMessage({\n id: \"result-\" + message.id,\n result: ResultMessage.encodeResult(\n error\n ? {\n content: result,\n error: JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error))),\n }\n : result,\n ),\n actionExecutionId: message.id,\n actionName: message.name,\n });\n}\n\nfunction getPairedFeAction(\n actions: FrontendAction<any>[],\n message: ActionExecutionMessage | ResultMessage,\n) {\n let actionName = null;\n if (message.isActionExecutionMessage()) {\n actionName = message.name;\n } else if (message.isResultMessage()) {\n actionName = message.actionName;\n }\n return actions.find(\n (action) =>\n (action.name === actionName && action.available === \"frontend\") ||\n action.pairedAction === actionName,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAgB,aAAa,WAAW,cAAc;AACtD;AAAA,EAEE;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OAKK;AA+JA,SAAS,QAAQ,SAAyC;AAC/D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AACJ,QAAM,uBAAuB,OAA4D;AACzF,QAAM,gBAAgB,cAAc;AAIpC,QAAM,kBAAkB,OAA4B,YAAY;AAChE,kBAAgB,UAAU;AAE1B,QAAM,WAAW,OAAsB,KAAK;AAC5C,WAAS,UAAU;AACnB,QAAM,gBAAgB,OAAwB,UAAU;AACxD,gBAAc,UAAU;AAExB,QAAM,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AC,YAAY;AAt3B/B;AAu3BQ,eAAI,4BAAuB,YAAvB,mBAAgC,OAAO,SAAS;AAClD,oBAAQ,mCAAmC;AAAA,UAC7C;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AAAA,IACH,SAAS,GAAP;AACA,cAAQ,CAAU;AAAA,IACpB;AACA,WAAO,IAAI,cAAc;AAAA,MACvB,IAAI,YAAY,QAAQ;AAAA,MACxB,QAAQ,cAAc;AAAA,QACpB,QACI;AAAA,UACE,SAAS;AAAA,UACT,OAAO,KAAK,MAAM,KAAK,UAAU,OAAO,OAAO,oBAAoB,KAAK,CAAC,CAAC;AAAA,QAC5E,IACA;AAAA,MACN;AAAA,MACA,mBAAmB,QAAQ;AAAA,MAC3B,YAAY,QAAQ;AAAA,IACtB,CAAC;AAAA,EACH;AAAA;AAEA,SAAS,kBACP,SACA,SACA;AACA,MAAI,aAAa;AACjB,MAAI,QAAQ,yBAAyB,GAAG;AACtC,iBAAa,QAAQ;AAAA,EACvB,WAAW,QAAQ,gBAAgB,GAAG;AACpC,iBAAa,QAAQ;AAAA,EACvB;AACA,SAAO,QAAQ;AAAA,IACb,CAAC,WACE,OAAO,SAAS,cAAc,OAAO,cAAc,cACpD,OAAO,iBAAiB;AAAA,EAC5B;AACF;","names":["messages","action","message","_a","options"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/copilot-provider/copilot-messages.tsx"],"sourcesContent":["/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { ReactNode, useEffect, useState, useRef, useCallback, useMemo } from \"react\";\nimport { CopilotMessagesContext } from \"../../context/copilot-messages-context\";\nimport {\n loadMessagesFromJsonRepresentation,\n Message,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useCopilotContext } from \"../../context/copilot-context\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { shouldShowDevConsole } from \"../../utils/dev-console\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n} from \"@copilotkit/shared\";\n\n// Helper to determine if error should show as banner based on visibility and legacy patterns\nfunction shouldShowAsBanner(gqlError: GraphQLError): boolean {\n const extensions = gqlError.extensions;\n if (!extensions) return false;\n\n // Priority 1: Check error code for discovery errors (these should always be banners)\n const code = extensions.code as CopilotKitErrorCode;\n if (\n code === CopilotKitErrorCode.AGENT_NOT_FOUND ||\n code === CopilotKitErrorCode.API_NOT_FOUND ||\n code === CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND ||\n code === CopilotKitErrorCode.CONFIGURATION_ERROR ||\n code === CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR ||\n code === CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR\n ) {\n return true;\n }\n\n // Priority 2: Check banner visibility\n if (extensions.visibility === ErrorVisibility.BANNER) {\n return true;\n }\n\n // Priority 3: Check for critical errors that should be banners regardless of formal classification\n const errorMessage = gqlError.message.toLowerCase();\n if (\n errorMessage.includes(\"api key\") ||\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"unauthorized\") ||\n errorMessage.includes(\"authentication\") ||\n errorMessage.includes(\"incorrect api key\")\n ) {\n return true;\n }\n\n // Priority 4: Legacy stack trace detection for discovery errors\n const originalError = extensions.originalError as any;\n if (originalError?.stack) {\n return (\n originalError.stack.includes(\"CopilotApiDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")\n );\n }\n\n return false;\n}\n\nexport function CopilotMessages({ children }: { children: ReactNode }) {\n const [messages, setMessages] = useState<Message[]>([]);\n const lastLoadedThreadId = useRef<string>();\n const lastLoadedAgentName = useRef<string>();\n const lastLoadedMessages = useRef<string>();\n\n const { threadId, agentSession, runtimeClient, showDevConsole } = useCopilotContext();\n const { setBannerError } = useToast();\n\n const createStructuredError = (gqlError: GraphQLError): CopilotKitError | null => {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n\n // Priority: Check stack trace for discovery errors first\n if (originalError?.stack) {\n if (originalError.stack.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message: originalError.message });\n }\n if (originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message: originalError.message });\n }\n if (originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n }\n\n // Fallback: Use the formal error code if available\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n return null;\n };\n\n const handleGraphQLErrors = useCallback(\n (error: any) => {\n if (error.graphQLErrors?.length) {\n const graphQLErrors = error.graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole);\n\n // If dev console is disabled, don't show ANY error UI to users\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", gqlError.message);\n return;\n }\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // All other errors (including DEV_ONLY) show as banners for consistency\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n } else {\n // Fallback: create a generic error for unstructured GraphQL errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n }\n }\n },\n [setBannerError, showDevConsole],\n );\n\n useEffect(() => {\n if (!threadId || threadId === lastLoadedThreadId.current) return;\n if (\n threadId === lastLoadedThreadId.current &&\n agentSession?.agentName === lastLoadedAgentName.current\n ) {\n return;\n }\n\n const fetchMessages = async () => {\n if (!agentSession?.agentName) return;\n\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: agentSession?.agentName,\n });\n\n // Check for GraphQL errors and manually trigger error handling\n if (result.error) {\n // Update refs to prevent infinite retries of the same failed request\n lastLoadedThreadId.current = threadId;\n lastLoadedAgentName.current = agentSession?.agentName;\n handleGraphQLErrors(result.error);\n return; // Don't try to process the data if there's an error\n }\n\n const newMessages = result.data?.loadAgentState?.messages;\n if (newMessages === lastLoadedMessages.current) return;\n\n if (result.data?.loadAgentState?.threadExists) {\n lastLoadedMessages.current = newMessages;\n lastLoadedThreadId.current = threadId;\n lastLoadedAgentName.current = agentSession?.agentName;\n\n const messages = loadMessagesFromJsonRepresentation(JSON.parse(newMessages || \"[]\"));\n setMessages(messages);\n }\n };\n void fetchMessages();\n }, [threadId, agentSession?.agentName, runtimeClient]); // handleGraphQLErrors should NOT be in deps - causes infinite loop\n\n const memoizedChildren = useMemo(() => children, [children]);\n\n return (\n <CopilotMessagesContext.Provider\n value={{\n messages,\n setMessages,\n }}\n >\n {memoizedChildren}\n </CopilotMessagesContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAIA,SAAoB,WAAW,UAAU,QAAQ,aAAa,eAAe;AAE7E;AAAA,EACE;AAAA,OAGK;AAIP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA8LH;AA5IG,SAAS,gBAAgB,EAAE,SAAS,GAA4B;AACrE,QAAM,CAAC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