@copilotkit/react-core 1.53.0 → 1.53.1-next.1

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.
@@ -0,0 +1,2161 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+
27
+ //#endregion
28
+ let react = require("react");
29
+ react = __toESM(react);
30
+ let _copilotkitnext_react = require("@copilotkitnext/react");
31
+ let _copilotkit_shared = require("@copilotkit/shared");
32
+ let react_dom = require("react-dom");
33
+ let react_jsx_runtime = require("react/jsx-runtime");
34
+ let react_markdown = require("react-markdown");
35
+ react_markdown = __toESM(react_markdown);
36
+
37
+ //#region src/context/copilot-context.tsx
38
+ const emptyCopilotContext$1 = {
39
+ actions: {},
40
+ setAction: () => {},
41
+ removeAction: () => {},
42
+ setRegisteredActions: () => "",
43
+ removeRegisteredAction: () => {},
44
+ chatComponentsCache: { current: {
45
+ actions: {},
46
+ coAgentStateRenders: {}
47
+ } },
48
+ getContextString: (documents, categories) => returnAndThrowInDebug(""),
49
+ addContext: () => "",
50
+ removeContext: () => {},
51
+ getAllContext: () => [],
52
+ getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),
53
+ isLoading: false,
54
+ setIsLoading: () => returnAndThrowInDebug(false),
55
+ chatInstructions: "",
56
+ setChatInstructions: () => returnAndThrowInDebug(""),
57
+ additionalInstructions: [],
58
+ setAdditionalInstructions: () => returnAndThrowInDebug([]),
59
+ getDocumentsContext: (categories) => returnAndThrowInDebug([]),
60
+ addDocumentContext: () => returnAndThrowInDebug(""),
61
+ removeDocumentContext: () => {},
62
+ copilotApiConfig: new class {
63
+ get chatApiEndpoint() {
64
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
65
+ }
66
+ get headers() {
67
+ return {};
68
+ }
69
+ get body() {
70
+ return {};
71
+ }
72
+ }(),
73
+ chatSuggestionConfiguration: {},
74
+ addChatSuggestionConfiguration: () => {},
75
+ removeChatSuggestionConfiguration: () => {},
76
+ showDevConsole: false,
77
+ coagentStates: {},
78
+ setCoagentStates: () => {},
79
+ coagentStatesRef: { current: {} },
80
+ setCoagentStatesWithRef: () => {},
81
+ agentSession: null,
82
+ setAgentSession: () => {},
83
+ forwardedParameters: {},
84
+ agentLock: null,
85
+ threadId: "",
86
+ setThreadId: () => {},
87
+ runId: null,
88
+ setRunId: () => {},
89
+ chatAbortControllerRef: { current: null },
90
+ availableAgents: [],
91
+ extensions: {},
92
+ setExtensions: () => {},
93
+ interruptActions: {},
94
+ setInterruptAction: () => {},
95
+ removeInterruptAction: () => {},
96
+ interruptEventQueue: {},
97
+ addInterruptEvent: () => {},
98
+ resolveInterruptEvent: () => {},
99
+ onError: () => {},
100
+ bannerError: null,
101
+ setBannerError: () => {},
102
+ internalErrorHandlers: {},
103
+ setInternalErrorHandler: () => {},
104
+ removeInternalErrorHandler: () => {}
105
+ };
106
+ const CopilotContext = react.default.createContext(emptyCopilotContext$1);
107
+ function useCopilotContext() {
108
+ const context = react.default.useContext(CopilotContext);
109
+ if (context === emptyCopilotContext$1) throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
110
+ return context;
111
+ }
112
+ function returnAndThrowInDebug(_value) {
113
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
114
+ }
115
+
116
+ //#endregion
117
+ //#region src/hooks/use-tree.ts
118
+ const removeNode = (nodes, id) => {
119
+ return nodes.reduce((result, node) => {
120
+ if (node.id !== id) {
121
+ const newNode = {
122
+ ...node,
123
+ children: removeNode(node.children, id)
124
+ };
125
+ result.push(newNode);
126
+ }
127
+ return result;
128
+ }, []);
129
+ };
130
+ const addNode = (nodes, newNode, parentId) => {
131
+ if (!parentId) return [...nodes, newNode];
132
+ return nodes.map((node) => {
133
+ if (node.id === parentId) return {
134
+ ...node,
135
+ children: [...node.children, newNode]
136
+ };
137
+ else if (node.children.length) return {
138
+ ...node,
139
+ children: addNode(node.children, newNode, parentId)
140
+ };
141
+ return node;
142
+ });
143
+ };
144
+ const treeIndentationRepresentation = (index, indentLevel) => {
145
+ if (indentLevel === 0) return (index + 1).toString();
146
+ else if (indentLevel === 1) return String.fromCharCode(65 + index);
147
+ else if (indentLevel === 2) return String.fromCharCode(97 + index);
148
+ else return "-";
149
+ };
150
+ const printNode = (node, prefix = "", indentLevel = 0) => {
151
+ const indent = " ".repeat(3).repeat(indentLevel);
152
+ const prefixPlusIndentLength = prefix.length + indent.length;
153
+ const subsequentLinesPrefix = " ".repeat(prefixPlusIndentLength);
154
+ const valueLines = node.value.split("\n");
155
+ const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;
156
+ const outputSubsequentLines = valueLines.slice(1).map((line) => `${subsequentLinesPrefix}${line}`).join("\n");
157
+ let output = `${outputFirstLine}\n`;
158
+ if (outputSubsequentLines) output += `${outputSubsequentLines}\n`;
159
+ const childPrePrefix = " ".repeat(prefix.length);
160
+ node.children.forEach((child, index) => output += printNode(child, `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `, indentLevel + 1));
161
+ return output;
162
+ };
163
+ function treeReducer(state, action) {
164
+ switch (action.type) {
165
+ case "ADD_NODE": {
166
+ const { value, parentId, id: newNodeId } = action;
167
+ const newNode = {
168
+ id: newNodeId,
169
+ value,
170
+ children: [],
171
+ categories: new Set(action.categories)
172
+ };
173
+ try {
174
+ return addNode(state, newNode, parentId);
175
+ } catch (error) {
176
+ console.error(`Error while adding node with id ${newNodeId}: ${error}`);
177
+ return state;
178
+ }
179
+ }
180
+ case "REMOVE_NODE": return removeNode(state, action.id);
181
+ default: return state;
182
+ }
183
+ }
184
+ const useTree = () => {
185
+ const [tree, dispatch] = (0, react.useReducer)(treeReducer, []);
186
+ const addElement = (0, react.useCallback)((value, categories, parentId) => {
187
+ const newNodeId = (0, _copilotkit_shared.randomId)();
188
+ dispatch({
189
+ type: "ADD_NODE",
190
+ value,
191
+ parentId,
192
+ id: newNodeId,
193
+ categories
194
+ });
195
+ return newNodeId;
196
+ }, []);
197
+ const removeElement = (0, react.useCallback)((id) => {
198
+ dispatch({
199
+ type: "REMOVE_NODE",
200
+ id
201
+ });
202
+ }, []);
203
+ const getAllElements = (0, react.useCallback)(() => {
204
+ return tree;
205
+ }, [tree]);
206
+ return {
207
+ tree,
208
+ addElement,
209
+ printTree: (0, react.useCallback)((categories) => {
210
+ const categoriesSet = new Set(categories);
211
+ let output = "";
212
+ tree.forEach((node, index) => {
213
+ if (!setsHaveIntersection$1(categoriesSet, node.categories)) return;
214
+ if (index !== 0) output += "\n";
215
+ output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);
216
+ });
217
+ return output;
218
+ }, [tree]),
219
+ removeElement,
220
+ getAllElements
221
+ };
222
+ };
223
+ function setsHaveIntersection$1(setA, setB) {
224
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
225
+ for (let item of smallerSet) if (largerSet.has(item)) return true;
226
+ return false;
227
+ }
228
+
229
+ //#endregion
230
+ //#region src/hooks/use-flat-category-store.ts
231
+ const useFlatCategoryStore = () => {
232
+ const [elements, dispatch] = (0, react.useReducer)(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
233
+ return {
234
+ addElement: (0, react.useCallback)((value, categories) => {
235
+ const newId = (0, _copilotkit_shared.randomId)();
236
+ dispatch({
237
+ type: "ADD_ELEMENT",
238
+ value,
239
+ id: newId,
240
+ categories
241
+ });
242
+ return newId;
243
+ }, []),
244
+ removeElement: (0, react.useCallback)((id) => {
245
+ dispatch({
246
+ type: "REMOVE_ELEMENT",
247
+ id
248
+ });
249
+ }, []),
250
+ allElements: (0, react.useCallback)((categories) => {
251
+ const categoriesSet = new Set(categories);
252
+ const result = [];
253
+ elements.forEach((element) => {
254
+ if (setsHaveIntersection(categoriesSet, element.categories)) result.push(element.value);
255
+ });
256
+ return result;
257
+ }, [elements])
258
+ };
259
+ };
260
+ function flatCategoryStoreReducer(state, action) {
261
+ switch (action.type) {
262
+ case "ADD_ELEMENT": {
263
+ const { value, id, categories } = action;
264
+ const newElement = {
265
+ id,
266
+ value,
267
+ categories: new Set(categories)
268
+ };
269
+ const newState = new Map(state);
270
+ newState.set(id, newElement);
271
+ return newState;
272
+ }
273
+ case "REMOVE_ELEMENT": {
274
+ const newState = new Map(state);
275
+ newState.delete(action.id);
276
+ return newState;
277
+ }
278
+ default: return state;
279
+ }
280
+ }
281
+ function setsHaveIntersection(setA, setB) {
282
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
283
+ for (let item of smallerSet) if (largerSet.has(item)) return true;
284
+ return false;
285
+ }
286
+
287
+ //#endregion
288
+ //#region src/context/copilot-messages-context.tsx
289
+ const emptyCopilotContext = {
290
+ messages: [],
291
+ setMessages: () => [],
292
+ suggestions: [],
293
+ setSuggestions: () => []
294
+ };
295
+ const CopilotMessagesContext = react.default.createContext(emptyCopilotContext);
296
+ function useCopilotMessagesContext() {
297
+ const context = react.default.useContext(CopilotMessagesContext);
298
+ if (context === emptyCopilotContext) throw new Error("A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`");
299
+ return context;
300
+ }
301
+
302
+ //#endregion
303
+ //#region src/components/toast/toast-provider.tsx
304
+ const ToastContext = (0, react.createContext)(void 0);
305
+ function getErrorSeverity(error) {
306
+ if (error.severity) switch (error.severity) {
307
+ case _copilotkit_shared.Severity.CRITICAL: return "critical";
308
+ case _copilotkit_shared.Severity.WARNING: return "warning";
309
+ case _copilotkit_shared.Severity.INFO: return "info";
310
+ default: return "info";
311
+ }
312
+ const message = error.message.toLowerCase();
313
+ if (message.includes("api key") || message.includes("401") || message.includes("unauthorized") || message.includes("authentication") || message.includes("incorrect api key")) return "critical";
314
+ return "info";
315
+ }
316
+ function getErrorColors(severity) {
317
+ switch (severity) {
318
+ case "critical": return {
319
+ background: "#fee2e2",
320
+ border: "#dc2626",
321
+ text: "#7f1d1d",
322
+ icon: "#dc2626"
323
+ };
324
+ case "warning": return {
325
+ background: "#fef3c7",
326
+ border: "#d97706",
327
+ text: "#78350f",
328
+ icon: "#d97706"
329
+ };
330
+ case "info": return {
331
+ background: "#dbeafe",
332
+ border: "#2563eb",
333
+ text: "#1e3a8a",
334
+ icon: "#2563eb"
335
+ };
336
+ }
337
+ }
338
+ function useToast() {
339
+ const context = (0, react.useContext)(ToastContext);
340
+ if (!context) throw new Error("useToast must be used within a ToastProvider");
341
+ return context;
342
+ }
343
+ function ToastProvider({ enabled, children }) {
344
+ const [toasts, setToasts] = (0, react.useState)([]);
345
+ const [bannerError, setBannerErrorState] = (0, react.useState)(null);
346
+ const removeToast = (0, react.useCallback)((id) => {
347
+ setToasts((prev) => prev.filter((toast) => toast.id !== id));
348
+ }, []);
349
+ const addToast = (0, react.useCallback)((toast) => {
350
+ if (!enabled) return;
351
+ const id = toast.id ?? Math.random().toString(36).substring(2, 9);
352
+ setToasts((currentToasts) => {
353
+ if (currentToasts.find((toast) => toast.id === id)) return currentToasts;
354
+ return [...currentToasts, {
355
+ ...toast,
356
+ id
357
+ }];
358
+ });
359
+ if (toast.duration) setTimeout(() => {
360
+ removeToast(id);
361
+ }, toast.duration);
362
+ }, [enabled, removeToast]);
363
+ const setBannerError = (0, react.useCallback)((error) => {
364
+ if (!enabled && error !== null) return;
365
+ setBannerErrorState(error);
366
+ }, [enabled]);
367
+ const value = {
368
+ toasts,
369
+ addToast,
370
+ addGraphQLErrorsToast: (0, react.useCallback)((errors) => {
371
+ console.warn("addGraphQLErrorsToast is deprecated. All errors now show as banners.");
372
+ }, []),
373
+ removeToast,
374
+ enabled,
375
+ bannerError,
376
+ setBannerError
377
+ };
378
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(ToastContext.Provider, {
379
+ value,
380
+ children: [bannerError && (() => {
381
+ const colors = getErrorColors(getErrorSeverity(bannerError));
382
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
383
+ style: {
384
+ position: "fixed",
385
+ bottom: "20px",
386
+ left: "50%",
387
+ transform: "translateX(-50%)",
388
+ zIndex: 9999,
389
+ backgroundColor: colors.background,
390
+ border: `1px solid ${colors.border}`,
391
+ borderLeft: `4px solid ${colors.border}`,
392
+ borderRadius: "8px",
393
+ padding: "12px 16px",
394
+ fontSize: "13px",
395
+ boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
396
+ backdropFilter: "blur(8px)",
397
+ maxWidth: "min(90vw, 700px)",
398
+ width: "100%",
399
+ boxSizing: "border-box",
400
+ overflow: "hidden"
401
+ },
402
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
403
+ style: {
404
+ display: "flex",
405
+ justifyContent: "space-between",
406
+ alignItems: "center",
407
+ gap: "10px"
408
+ },
409
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
410
+ style: {
411
+ display: "flex",
412
+ alignItems: "center",
413
+ gap: "8px",
414
+ flex: 1,
415
+ minWidth: 0
416
+ },
417
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: {
418
+ width: "12px",
419
+ height: "12px",
420
+ borderRadius: "50%",
421
+ backgroundColor: colors.border,
422
+ flexShrink: 0
423
+ } }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
424
+ style: {
425
+ display: "flex",
426
+ alignItems: "center",
427
+ gap: "10px",
428
+ flex: 1,
429
+ minWidth: 0
430
+ },
431
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
432
+ style: {
433
+ color: colors.text,
434
+ lineHeight: "1.4",
435
+ fontWeight: "400",
436
+ fontSize: "13px",
437
+ flex: 1,
438
+ wordBreak: "break-all",
439
+ overflowWrap: "break-word",
440
+ maxWidth: "550px",
441
+ overflow: "hidden",
442
+ display: "-webkit-box",
443
+ WebkitLineClamp: 10,
444
+ WebkitBoxOrient: "vertical"
445
+ },
446
+ children: (() => {
447
+ let message = bannerError.message;
448
+ const jsonMatch = message.match(/'message':\s*'([^']+)'/);
449
+ if (jsonMatch) return jsonMatch[1];
450
+ message = message.split(" - ")[0];
451
+ message = message.split(": Error code")[0];
452
+ message = message.replace(/:\s*\d{3}$/, "");
453
+ message = message.replace(/See more:.*$/g, "");
454
+ message = message.trim();
455
+ return message || "Configuration error occurred.";
456
+ })()
457
+ }), (() => {
458
+ const message = bannerError.message;
459
+ const markdownLinkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
460
+ const plainUrlRegex = /(https?:\/\/[^\s)]+)/g;
461
+ let url = null;
462
+ let buttonText = "See More";
463
+ const markdownMatch = markdownLinkRegex.exec(message);
464
+ if (markdownMatch) {
465
+ url = markdownMatch[2];
466
+ buttonText = "See More";
467
+ } else {
468
+ const urlMatch = plainUrlRegex.exec(message);
469
+ if (urlMatch) {
470
+ url = urlMatch[0].replace(/[.,;:'"]*$/, "");
471
+ buttonText = "See More";
472
+ }
473
+ }
474
+ if (!url) return null;
475
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
476
+ onClick: () => window.open(url, "_blank", "noopener,noreferrer"),
477
+ style: {
478
+ background: colors.border,
479
+ color: "white",
480
+ border: "none",
481
+ borderRadius: "5px",
482
+ padding: "4px 10px",
483
+ fontSize: "11px",
484
+ fontWeight: "500",
485
+ cursor: "pointer",
486
+ transition: "all 0.2s ease",
487
+ flexShrink: 0
488
+ },
489
+ onMouseEnter: (e) => {
490
+ e.currentTarget.style.opacity = "0.9";
491
+ e.currentTarget.style.transform = "translateY(-1px)";
492
+ },
493
+ onMouseLeave: (e) => {
494
+ e.currentTarget.style.opacity = "1";
495
+ e.currentTarget.style.transform = "translateY(0)";
496
+ },
497
+ children: buttonText
498
+ });
499
+ })()]
500
+ })]
501
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
502
+ onClick: () => setBannerError(null),
503
+ style: {
504
+ background: "transparent",
505
+ border: "none",
506
+ color: colors.text,
507
+ cursor: "pointer",
508
+ padding: "2px",
509
+ borderRadius: "3px",
510
+ fontSize: "14px",
511
+ lineHeight: "1",
512
+ opacity: .6,
513
+ transition: "all 0.2s ease",
514
+ flexShrink: 0
515
+ },
516
+ title: "Dismiss",
517
+ onMouseEnter: (e) => {
518
+ e.currentTarget.style.opacity = "1";
519
+ e.currentTarget.style.background = "rgba(0, 0, 0, 0.05)";
520
+ },
521
+ onMouseLeave: (e) => {
522
+ e.currentTarget.style.opacity = "0.6";
523
+ e.currentTarget.style.background = "transparent";
524
+ },
525
+ children: "×"
526
+ })]
527
+ })
528
+ });
529
+ })(), children]
530
+ });
531
+ }
532
+
533
+ //#endregion
534
+ //#region src/utils/dev-console.ts
535
+ function isLocalhost() {
536
+ if (typeof window === "undefined") return false;
537
+ return window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "0.0.0.0";
538
+ }
539
+ function shouldShowDevConsole(showDevConsole) {
540
+ if (showDevConsole !== void 0) return showDevConsole;
541
+ return isLocalhost();
542
+ }
543
+
544
+ //#endregion
545
+ //#region src/components/copilot-provider/copilot-messages.tsx
546
+ /**
547
+ * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context
548
+ */
549
+ const MessagesTapContext = (0, react.createContext)(null);
550
+ function useMessagesTap() {
551
+ const tap = (0, react.useContext)(MessagesTapContext);
552
+ if (!tap) throw new Error("useMessagesTap must be used inside <MessagesTapProvider>");
553
+ return tap;
554
+ }
555
+ function MessagesTapProvider({ children }) {
556
+ const messagesRef = (0, react.useRef)([]);
557
+ const tapRef = (0, react.useRef)({
558
+ getMessagesFromTap: () => messagesRef.current,
559
+ updateTapMessages: (messages) => {
560
+ messagesRef.current = messages;
561
+ }
562
+ });
563
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MessagesTapContext.Provider, {
564
+ value: tapRef.current,
565
+ children
566
+ });
567
+ }
568
+ /**
569
+ * CopilotKit messages context.
570
+ */
571
+ function CopilotMessages({ children }) {
572
+ const [messages, setMessages] = (0, react.useState)([]);
573
+ (0, react.useRef)(void 0);
574
+ (0, react.useRef)(void 0);
575
+ (0, react.useRef)(void 0);
576
+ const { updateTapMessages } = useMessagesTap();
577
+ const { threadId, agentSession, showDevConsole, onError, copilotApiConfig } = useCopilotContext();
578
+ const { setBannerError } = useToast();
579
+ const traceUIError = (0, react.useCallback)(async (error, originalError) => {
580
+ if (!onError || !copilotApiConfig.publicApiKey) return;
581
+ try {
582
+ await onError({
583
+ type: "error",
584
+ timestamp: Date.now(),
585
+ context: {
586
+ source: "ui",
587
+ request: {
588
+ operation: "loadAgentState",
589
+ url: copilotApiConfig.chatApiEndpoint,
590
+ startTime: Date.now()
591
+ },
592
+ technical: {
593
+ environment: "browser",
594
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
595
+ stackTrace: originalError instanceof Error ? originalError.stack : void 0
596
+ }
597
+ },
598
+ error
599
+ });
600
+ } catch (traceError) {
601
+ console.error("Error in CopilotMessages onError handler:", traceError);
602
+ }
603
+ }, [
604
+ onError,
605
+ copilotApiConfig.publicApiKey,
606
+ copilotApiConfig.chatApiEndpoint
607
+ ]);
608
+ const createStructuredError = (gqlError) => {
609
+ const extensions = gqlError.extensions;
610
+ const originalError = extensions?.originalError;
611
+ if (originalError?.stack) {
612
+ if (originalError.stack.includes("CopilotApiDiscoveryError")) return new _copilotkit_shared.CopilotKitApiDiscoveryError({ message: originalError.message });
613
+ if (originalError.stack.includes("CopilotKitRemoteEndpointDiscoveryError")) return new _copilotkit_shared.CopilotKitRemoteEndpointDiscoveryError({ message: originalError.message });
614
+ if (originalError.stack.includes("CopilotKitAgentDiscoveryError")) return new _copilotkit_shared.CopilotKitAgentDiscoveryError({
615
+ agentName: "",
616
+ availableAgents: []
617
+ });
618
+ }
619
+ const message = originalError?.message || gqlError.message;
620
+ const code = extensions?.code;
621
+ if (code) return new _copilotkit_shared.CopilotKitError({
622
+ message,
623
+ code
624
+ });
625
+ return null;
626
+ };
627
+ (0, react.useCallback)((error) => {
628
+ if (error.graphQLErrors?.length) {
629
+ const graphQLErrors = error.graphQLErrors;
630
+ const routeError = (gqlError) => {
631
+ const visibility = gqlError.extensions?.visibility;
632
+ if (!shouldShowDevConsole(showDevConsole)) {
633
+ console.error("CopilotKit Error (hidden in production):", gqlError.message);
634
+ return;
635
+ }
636
+ if (visibility === _copilotkit_shared.ErrorVisibility.SILENT) {
637
+ console.error("CopilotKit Silent Error:", gqlError.message);
638
+ return;
639
+ }
640
+ const ckError = createStructuredError(gqlError);
641
+ if (ckError) {
642
+ setBannerError(ckError);
643
+ traceUIError(ckError, gqlError);
644
+ } else {
645
+ const fallbackError = new _copilotkit_shared.CopilotKitError({
646
+ message: gqlError.message,
647
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
648
+ });
649
+ setBannerError(fallbackError);
650
+ traceUIError(fallbackError, gqlError);
651
+ }
652
+ };
653
+ graphQLErrors.forEach(routeError);
654
+ } else if (!shouldShowDevConsole(showDevConsole)) console.error("CopilotKit Error (hidden in production):", error);
655
+ else {
656
+ const fallbackError = new _copilotkit_shared.CopilotKitError({
657
+ message: error?.message || String(error),
658
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
659
+ });
660
+ setBannerError(fallbackError);
661
+ traceUIError(fallbackError, error);
662
+ }
663
+ }, [
664
+ setBannerError,
665
+ showDevConsole,
666
+ traceUIError
667
+ ]);
668
+ (0, react.useEffect)(() => {
669
+ updateTapMessages(messages);
670
+ }, [messages, updateTapMessages]);
671
+ const memoizedChildren = (0, react.useMemo)(() => children, [children]);
672
+ const [suggestions, setSuggestions] = (0, react.useState)([]);
673
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotMessagesContext.Provider, {
674
+ value: {
675
+ messages,
676
+ setMessages,
677
+ suggestions,
678
+ setSuggestions
679
+ },
680
+ children: memoizedChildren
681
+ });
682
+ }
683
+
684
+ //#endregion
685
+ //#region src/components/usage-banner.tsx
686
+ function UsageBanner({ severity = _copilotkit_shared.Severity.CRITICAL, message = "", onClose, actions }) {
687
+ if (!message || !severity) return null;
688
+ const theme = {
689
+ [_copilotkit_shared.Severity.INFO]: {
690
+ bg: "#f8fafc",
691
+ border: "#e2e8f0",
692
+ text: "#475569",
693
+ accent: "#3b82f6"
694
+ },
695
+ [_copilotkit_shared.Severity.WARNING]: {
696
+ bg: "#fffbeb",
697
+ border: "#fbbf24",
698
+ text: "#92400e",
699
+ accent: "#f59e0b"
700
+ },
701
+ [_copilotkit_shared.Severity.CRITICAL]: {
702
+ bg: "#fef2f2",
703
+ border: "#fecaca",
704
+ text: "#dc2626",
705
+ accent: "#ef4444"
706
+ }
707
+ }[severity];
708
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { children: `
709
+ @keyframes slideUp {
710
+ from { opacity: 0; transform: translateX(-50%) translateY(8px); }
711
+ to { opacity: 1; transform: translateX(-50%) translateY(0); }
712
+ }
713
+
714
+ .usage-banner {
715
+ position: fixed;
716
+ bottom: 24px;
717
+ left: 50%;
718
+ transform: translateX(-50%);
719
+ width: min(600px, calc(100vw - 32px));
720
+ z-index: 10000;
721
+ animation: slideUp 0.2s cubic-bezier(0.16, 1, 0.3, 1);
722
+ }
723
+
724
+ .banner-content {
725
+ background: linear-gradient(135deg, ${theme.bg} 0%, ${theme.bg}f5 100%);
726
+ border: 1px solid ${theme.border};
727
+ border-radius: 12px;
728
+ padding: 18px 20px;
729
+ box-shadow:
730
+ 0 4px 24px rgba(0, 0, 0, 0.08),
731
+ 0 2px 8px rgba(0, 0, 0, 0.04),
732
+ inset 0 1px 0 rgba(255, 255, 255, 0.7);
733
+ display: flex;
734
+ align-items: center;
735
+ gap: 16px;
736
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
737
+ backdrop-filter: blur(12px);
738
+ position: relative;
739
+ overflow: hidden;
740
+ }
741
+
742
+ .banner-content::before {
743
+ content: '';
744
+ position: absolute;
745
+ top: 0;
746
+ left: 0;
747
+ right: 0;
748
+ height: 1px;
749
+ background: linear-gradient(90deg, transparent, ${theme.accent}40, transparent);
750
+ }
751
+
752
+ .banner-message {
753
+ color: ${theme.text};
754
+ font-size: 14px;
755
+ line-height: 1.5;
756
+ font-weight: 500;
757
+ flex: 1;
758
+ letter-spacing: -0.01em;
759
+ }
760
+
761
+ .close-btn {
762
+ background: rgba(0, 0, 0, 0.05);
763
+ border: none;
764
+ color: ${theme.text};
765
+ cursor: pointer;
766
+ padding: 0;
767
+ border-radius: 6px;
768
+ opacity: 0.6;
769
+ transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);
770
+ font-size: 14px;
771
+ line-height: 1;
772
+ flex-shrink: 0;
773
+ width: 24px;
774
+ height: 24px;
775
+ display: flex;
776
+ align-items: center;
777
+ justify-content: center;
778
+ }
779
+
780
+ .close-btn:hover {
781
+ opacity: 1;
782
+ background: rgba(0, 0, 0, 0.08);
783
+ transform: scale(1.05);
784
+ }
785
+
786
+ .btn-primary {
787
+ background: linear-gradient(135deg, ${theme.accent} 0%, ${theme.accent}e6 100%);
788
+ color: white;
789
+ border: none;
790
+ border-radius: 8px;
791
+ padding: 10px 18px;
792
+ font-size: 13px;
793
+ font-weight: 600;
794
+ cursor: pointer;
795
+ transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);
796
+ font-family: inherit;
797
+ flex-shrink: 0;
798
+ box-shadow:
799
+ 0 2px 8px ${theme.accent}30,
800
+ inset 0 1px 0 rgba(255, 255, 255, 0.2);
801
+ letter-spacing: -0.01em;
802
+ }
803
+
804
+ .btn-primary:hover {
805
+ transform: translateY(-1px) scale(1.02);
806
+ box-shadow:
807
+ 0 4px 12px ${theme.accent}40,
808
+ inset 0 1px 0 rgba(255, 255, 255, 0.25);
809
+ }
810
+
811
+ .btn-primary:active {
812
+ transform: translateY(0) scale(0.98);
813
+ transition: all 0.08s cubic-bezier(0.16, 1, 0.3, 1);
814
+ }
815
+
816
+ @media (max-width: 640px) {
817
+ .usage-banner {
818
+ width: calc(100vw - 24px);
819
+ }
820
+
821
+ .banner-content {
822
+ padding: 16px;
823
+ gap: 12px;
824
+ }
825
+
826
+ .banner-message {
827
+ font-size: 13px;
828
+ line-height: 1.45;
829
+ }
830
+
831
+ .btn-primary {
832
+ padding: 8px 14px;
833
+ font-size: 12px;
834
+ }
835
+
836
+ .close-btn {
837
+ width: 22px;
838
+ height: 22px;
839
+ font-size: 12px;
840
+ }
841
+ }
842
+ ` }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
843
+ className: "usage-banner",
844
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
845
+ className: "banner-content",
846
+ children: [
847
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
848
+ className: "banner-message",
849
+ children: message
850
+ }),
851
+ actions?.primary && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
852
+ className: "btn-primary",
853
+ onClick: actions.primary.onClick,
854
+ children: actions.primary.label
855
+ }),
856
+ onClose && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
857
+ className: "close-btn",
858
+ onClick: onClose,
859
+ title: "Close",
860
+ children: "×"
861
+ })
862
+ ]
863
+ })
864
+ })] });
865
+ }
866
+ const getErrorActions = (error) => {
867
+ switch (error.code) {
868
+ case _copilotkit_shared.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR: return { primary: {
869
+ label: "Show me how",
870
+ onClick: () => window.open("https://docs.copilotkit.ai/premium#how-do-i-get-access-to-premium-features", "_blank", "noopener,noreferrer")
871
+ } };
872
+ case _copilotkit_shared.CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR: return { primary: {
873
+ label: "Upgrade",
874
+ onClick: () => window.open("https://cloud.copilotkit.ai", "_blank", "noopener,noreferrer")
875
+ } };
876
+ default: return;
877
+ }
878
+ };
879
+
880
+ //#endregion
881
+ //#region src/lib/status-checker.ts
882
+ const STATUS_CHECK_INTERVAL = 1e3 * 60 * 5;
883
+ var StatusChecker = class {
884
+ constructor() {
885
+ this.activeKey = null;
886
+ this.intervalId = null;
887
+ this.instanceCount = 0;
888
+ this.lastResponse = null;
889
+ }
890
+ async start(publicApiKey, onUpdate) {
891
+ this.instanceCount++;
892
+ if (this.activeKey === publicApiKey) return;
893
+ if (this.intervalId) clearInterval(this.intervalId);
894
+ const checkStatus = async () => {
895
+ try {
896
+ const response = await fetch(`${_copilotkit_shared.COPILOT_CLOUD_API_URL}/ciu`, {
897
+ method: "GET",
898
+ headers: { [_copilotkit_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey }
899
+ }).then((response) => response.json());
900
+ this.lastResponse = response;
901
+ onUpdate?.(response);
902
+ return response;
903
+ } catch (error) {
904
+ return null;
905
+ }
906
+ };
907
+ const initialResponse = await checkStatus();
908
+ this.intervalId = setInterval(checkStatus, STATUS_CHECK_INTERVAL);
909
+ this.activeKey = publicApiKey;
910
+ return initialResponse;
911
+ }
912
+ getLastResponse() {
913
+ return this.lastResponse;
914
+ }
915
+ stop() {
916
+ this.instanceCount--;
917
+ if (this.instanceCount === 0) {
918
+ if (this.intervalId) {
919
+ clearInterval(this.intervalId);
920
+ this.intervalId = null;
921
+ this.activeKey = null;
922
+ this.lastResponse = null;
923
+ }
924
+ }
925
+ }
926
+ };
927
+
928
+ //#endregion
929
+ //#region src/components/toast/exclamation-mark-icon.tsx
930
+ const ExclamationMarkIcon = ({ className, style }) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
931
+ xmlns: "http://www.w3.org/2000/svg",
932
+ width: "24",
933
+ height: "24",
934
+ viewBox: "0 0 24 24",
935
+ fill: "none",
936
+ stroke: "currentColor",
937
+ strokeWidth: "2",
938
+ strokeLinecap: "round",
939
+ strokeLinejoin: "round",
940
+ className: `lucide lucide-circle-alert ${className ? className : ""}`,
941
+ style,
942
+ children: [
943
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
944
+ cx: "12",
945
+ cy: "12",
946
+ r: "10"
947
+ }),
948
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("line", {
949
+ x1: "12",
950
+ x2: "12",
951
+ y1: "8",
952
+ y2: "12"
953
+ }),
954
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("line", {
955
+ x1: "12",
956
+ x2: "12.01",
957
+ y1: "16",
958
+ y2: "16"
959
+ })
960
+ ]
961
+ });
962
+
963
+ //#endregion
964
+ //#region src/components/error-boundary/error-utils.tsx
965
+ function ErrorToast({ errors }) {
966
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
967
+ style: {
968
+ fontSize: "13px",
969
+ maxWidth: "600px"
970
+ },
971
+ children: [errors.map((error, idx) => {
972
+ const message = ("extensions" in error ? error.extensions?.originalError : {})?.message ?? error.message;
973
+ const code = "extensions" in error ? error.extensions?.code : null;
974
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
975
+ style: {
976
+ marginTop: idx === 0 ? 0 : 10,
977
+ marginBottom: 14
978
+ },
979
+ children: [
980
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
981
+ code && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
982
+ style: {
983
+ fontWeight: "600",
984
+ marginBottom: 4
985
+ },
986
+ children: [
987
+ "Copilot Runtime Error:",
988
+ " ",
989
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
990
+ style: {
991
+ fontFamily: "monospace",
992
+ fontWeight: "normal"
993
+ },
994
+ children: code
995
+ })
996
+ ]
997
+ }),
998
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_markdown.default, { children: message })
999
+ ]
1000
+ }, idx);
1001
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1002
+ style: {
1003
+ fontSize: "11px",
1004
+ opacity: .75
1005
+ },
1006
+ children: "NOTE: This error only displays during local development."
1007
+ })]
1008
+ });
1009
+ }
1010
+ function useErrorToast() {
1011
+ const { addToast } = useToast();
1012
+ return (0, react.useCallback)((errors) => {
1013
+ addToast({
1014
+ type: "error",
1015
+ id: errors.map((err) => {
1016
+ const message = "extensions" in err ? (err.extensions?.originalError)?.message || err.message : err.message;
1017
+ const stack = err.stack || "";
1018
+ return btoa(message + stack).slice(0, 32);
1019
+ }).join("|"),
1020
+ message: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ErrorToast, { errors })
1021
+ });
1022
+ }, [addToast]);
1023
+ }
1024
+ function useAsyncCallback(callback, deps) {
1025
+ const addErrorToast = useErrorToast();
1026
+ return (0, react.useCallback)(async (...args) => {
1027
+ try {
1028
+ return await callback(...args);
1029
+ } catch (error) {
1030
+ console.error("Error in async callback:", error);
1031
+ addErrorToast([error]);
1032
+ throw error;
1033
+ }
1034
+ }, deps);
1035
+ }
1036
+
1037
+ //#endregion
1038
+ //#region src/components/error-boundary/error-boundary.tsx
1039
+ const statusChecker = new StatusChecker();
1040
+ var CopilotErrorBoundary = class extends react.default.Component {
1041
+ constructor(props) {
1042
+ super(props);
1043
+ this.state = { hasError: false };
1044
+ }
1045
+ static getDerivedStateFromError(error) {
1046
+ return {
1047
+ hasError: true,
1048
+ error
1049
+ };
1050
+ }
1051
+ componentDidMount() {
1052
+ if (this.props.publicApiKey) statusChecker.start(this.props.publicApiKey, (newStatus) => {
1053
+ this.setState((prevState) => {
1054
+ if (newStatus?.severity !== prevState.status?.severity) return { status: newStatus ?? void 0 };
1055
+ return null;
1056
+ });
1057
+ });
1058
+ }
1059
+ componentWillUnmount() {
1060
+ statusChecker.stop();
1061
+ }
1062
+ componentDidCatch(error, errorInfo) {
1063
+ console.error("CopilotKit Error:", error, errorInfo);
1064
+ }
1065
+ render() {
1066
+ if (this.state.hasError) {
1067
+ if (this.state.error instanceof _copilotkit_shared.CopilotKitError) return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [this.props.children, this.props.showUsageBanner && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UsageBanner, {
1068
+ severity: this.state.status?.severity ?? this.state.error.severity,
1069
+ message: this.state.status?.message ?? this.state.error.message,
1070
+ actions: getErrorActions(this.state.error)
1071
+ })] });
1072
+ throw this.state.error;
1073
+ }
1074
+ return this.props.children;
1075
+ }
1076
+ };
1077
+
1078
+ //#endregion
1079
+ //#region src/context/coagent-state-renders-context.tsx
1080
+ const CoAgentStateRendersContext = (0, react.createContext)(void 0);
1081
+ function CoAgentStateRendersProvider({ children }) {
1082
+ const [coAgentStateRenders, setCoAgentStateRenders] = (0, react.useState)({});
1083
+ const setCoAgentStateRender = (0, react.useCallback)((id, stateRender) => {
1084
+ setCoAgentStateRenders((prevPoints) => ({
1085
+ ...prevPoints,
1086
+ [id]: stateRender
1087
+ }));
1088
+ }, []);
1089
+ const removeCoAgentStateRender = (0, react.useCallback)((id) => {
1090
+ setCoAgentStateRenders((prevPoints) => {
1091
+ const newPoints = { ...prevPoints };
1092
+ delete newPoints[id];
1093
+ return newPoints;
1094
+ });
1095
+ }, []);
1096
+ const claimsRef = (0, react.useRef)({});
1097
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CoAgentStateRendersContext.Provider, {
1098
+ value: {
1099
+ coAgentStateRenders,
1100
+ setCoAgentStateRender,
1101
+ removeCoAgentStateRender,
1102
+ claimsRef
1103
+ },
1104
+ children
1105
+ });
1106
+ }
1107
+ function useCoAgentStateRenders() {
1108
+ const context = (0, react.useContext)(CoAgentStateRendersContext);
1109
+ if (!context) throw new Error("useCoAgentStateRenders must be used within CoAgentStateRendersProvider");
1110
+ return context;
1111
+ }
1112
+
1113
+ //#endregion
1114
+ //#region src/context/threads-context.tsx
1115
+ const ThreadsContext = (0, react.createContext)(void 0);
1116
+ function ThreadsProvider({ children, threadId: explicitThreadId }) {
1117
+ const [internalThreadId, setThreadId] = (0, react.useState)(() => (0, _copilotkit_shared.randomUUID)());
1118
+ const threadId = explicitThreadId ?? internalThreadId;
1119
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ThreadsContext.Provider, {
1120
+ value: {
1121
+ threadId,
1122
+ setThreadId
1123
+ },
1124
+ children
1125
+ });
1126
+ }
1127
+ function useThreads() {
1128
+ const context = (0, react.useContext)(ThreadsContext);
1129
+ if (!context) throw new Error("useThreads must be used within ThreadsProvider");
1130
+ return context;
1131
+ }
1132
+
1133
+ //#endregion
1134
+ //#region src/hooks/use-coagent-state-render-bridge.helpers.ts
1135
+ let RenderStatus = /* @__PURE__ */ function(RenderStatus) {
1136
+ RenderStatus["InProgress"] = "inProgress";
1137
+ RenderStatus["Complete"] = "complete";
1138
+ return RenderStatus;
1139
+ }({});
1140
+ let ClaimAction = /* @__PURE__ */ function(ClaimAction) {
1141
+ ClaimAction["Create"] = "create";
1142
+ ClaimAction["Override"] = "override";
1143
+ ClaimAction["Existing"] = "existing";
1144
+ ClaimAction["Block"] = "block";
1145
+ return ClaimAction;
1146
+ }({});
1147
+ function getStateWithoutConstantKeys(state) {
1148
+ if (!state) return {};
1149
+ const { messages, tools, copilotkit, ...stateWithoutConstantKeys } = state;
1150
+ return stateWithoutConstantKeys;
1151
+ }
1152
+ function areStatesEquals(a, b) {
1153
+ if (a && !b || !a && b) return false;
1154
+ const { messages, tools, copilotkit, ...aWithoutConstantKeys } = a;
1155
+ const { messages: bMessages, tools: bTools, copilotkit: bCopilotkit, ...bWithoutConstantKeys } = b;
1156
+ return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);
1157
+ }
1158
+ function isPlaceholderMessageId(messageId) {
1159
+ return !!messageId && messageId.startsWith("coagent-state-render-");
1160
+ }
1161
+ function isPlaceholderMessageName(messageName) {
1162
+ return messageName === "coagent-state-render";
1163
+ }
1164
+ function readCachedMessageEntry(entry) {
1165
+ if (!entry || typeof entry !== "object") return {
1166
+ snapshot: entry,
1167
+ runId: void 0
1168
+ };
1169
+ return {
1170
+ snapshot: "snapshot" in entry ? entry.snapshot : entry,
1171
+ runId: "runId" in entry ? entry.runId : void 0
1172
+ };
1173
+ }
1174
+ function getEffectiveRunId({ existingClaimRunId, cachedMessageRunId, runId }) {
1175
+ return existingClaimRunId || cachedMessageRunId || runId || "pending";
1176
+ }
1177
+ /**
1178
+ * Resolve whether a message can claim a render slot.
1179
+ * This is a pure decision function; the caller applies claim mutations.
1180
+ */
1181
+ function resolveClaim({ claims, context, stateSnapshot }) {
1182
+ const { messageId, stateRenderId, runId, messageIndex } = context;
1183
+ const existing = claims[messageId];
1184
+ if (existing) {
1185
+ const canRender = existing.stateRenderId === stateRenderId;
1186
+ const shouldUpdateRunId = canRender && runId && (!existing.runId || existing.runId === "pending");
1187
+ return {
1188
+ canRender,
1189
+ action: canRender ? ClaimAction.Existing : ClaimAction.Block,
1190
+ updateRunId: shouldUpdateRunId ? runId : void 0
1191
+ };
1192
+ }
1193
+ const normalizedRunId = runId ?? "pending";
1194
+ const renderClaimedByOtherMessageEntry = Object.entries(claims).find(([, claim]) => claim.stateRenderId === stateRenderId && (claim.runId ?? "pending") === normalizedRunId && (0, _copilotkit_shared.dataToUUID)(getStateWithoutConstantKeys(claim.stateSnapshot)) === (0, _copilotkit_shared.dataToUUID)(getStateWithoutConstantKeys(stateSnapshot)));
1195
+ const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry?.[1];
1196
+ const claimedMessageId = renderClaimedByOtherMessageEntry?.[0];
1197
+ if (renderClaimedByOtherMessage) {
1198
+ if (messageIndex !== void 0 && renderClaimedByOtherMessage.messageIndex !== void 0 && messageIndex > renderClaimedByOtherMessage.messageIndex) return {
1199
+ canRender: true,
1200
+ action: ClaimAction.Override,
1201
+ nextClaim: {
1202
+ stateRenderId,
1203
+ runId,
1204
+ messageIndex
1205
+ },
1206
+ lockOthers: runId === renderClaimedByOtherMessage.runId || isPlaceholderMessageId(claimedMessageId)
1207
+ };
1208
+ if (runId && renderClaimedByOtherMessage.runId && runId !== renderClaimedByOtherMessage.runId) return {
1209
+ canRender: true,
1210
+ action: ClaimAction.Override,
1211
+ nextClaim: {
1212
+ stateRenderId,
1213
+ runId,
1214
+ messageIndex
1215
+ },
1216
+ lockOthers: isPlaceholderMessageId(claimedMessageId)
1217
+ };
1218
+ if (isPlaceholderMessageId(claimedMessageId)) return {
1219
+ canRender: true,
1220
+ action: ClaimAction.Override,
1221
+ nextClaim: {
1222
+ stateRenderId,
1223
+ runId,
1224
+ messageIndex
1225
+ },
1226
+ lockOthers: true
1227
+ };
1228
+ if (stateSnapshot && renderClaimedByOtherMessage.stateSnapshot && !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, stateSnapshot)) return {
1229
+ canRender: true,
1230
+ action: ClaimAction.Override,
1231
+ nextClaim: {
1232
+ stateRenderId,
1233
+ runId
1234
+ }
1235
+ };
1236
+ return {
1237
+ canRender: false,
1238
+ action: ClaimAction.Block
1239
+ };
1240
+ }
1241
+ if (!runId) return {
1242
+ canRender: false,
1243
+ action: ClaimAction.Block
1244
+ };
1245
+ return {
1246
+ canRender: true,
1247
+ action: ClaimAction.Create,
1248
+ nextClaim: {
1249
+ stateRenderId,
1250
+ runId,
1251
+ messageIndex
1252
+ }
1253
+ };
1254
+ }
1255
+ /**
1256
+ * Select the best snapshot to render for this message.
1257
+ * Priority order is:
1258
+ * 1) explicit message snapshot
1259
+ * 2) live agent state (latest assistant only)
1260
+ * 3) cached snapshot for message
1261
+ * 4) cached snapshot for stateRenderId+runId
1262
+ * 5) last cached snapshot for stateRenderId
1263
+ */
1264
+ function selectSnapshot({ messageId, messageName, allowLiveState, skipLatestCache, stateRenderId, effectiveRunId, stateSnapshotProp, agentState, agentMessages, existingClaim, caches }) {
1265
+ const lastAssistantId = agentMessages ? [...agentMessages].reverse().find((msg) => msg.role === "assistant")?.id : void 0;
1266
+ const latestSnapshot = stateRenderId !== void 0 ? caches.byStateRenderAndRun[`${stateRenderId}::latest`] : void 0;
1267
+ const messageIndex = agentMessages ? agentMessages.findIndex((msg) => msg.id === messageId) : -1;
1268
+ const messageRole = messageIndex >= 0 && agentMessages ? agentMessages[messageIndex]?.role : void 0;
1269
+ let previousUserMessageId;
1270
+ if (messageIndex > 0 && agentMessages) {
1271
+ for (let i = messageIndex - 1; i >= 0; i -= 1) if (agentMessages[i]?.role === "user") {
1272
+ previousUserMessageId = agentMessages[i]?.id;
1273
+ break;
1274
+ }
1275
+ }
1276
+ const liveStateIsStale = stateSnapshotProp === void 0 && latestSnapshot !== void 0 && agentState !== void 0 && areStatesEquals(latestSnapshot, agentState);
1277
+ const shouldUseLiveState = (Boolean(allowLiveState) || !lastAssistantId || messageId === lastAssistantId) && !liveStateIsStale;
1278
+ const snapshot = stateSnapshotProp ? (0, _copilotkit_shared.parseJson)(stateSnapshotProp, stateSnapshotProp) : shouldUseLiveState ? agentState : void 0;
1279
+ const hasSnapshotKeys = !!(snapshot && Object.keys(snapshot).length > 0);
1280
+ const allowEmptySnapshot = snapshot !== void 0 && !hasSnapshotKeys && (stateSnapshotProp !== void 0 || shouldUseLiveState);
1281
+ const messageCacheEntry = caches.byMessageId[messageId];
1282
+ const cachedMessageSnapshot = readCachedMessageEntry(messageCacheEntry).snapshot;
1283
+ const cacheKey = stateRenderId !== void 0 ? `${stateRenderId}::${effectiveRunId}` : void 0;
1284
+ let cachedSnapshot = cachedMessageSnapshot ?? caches.byMessageId[messageId];
1285
+ if (cachedSnapshot === void 0 && cacheKey && caches.byStateRenderAndRun[cacheKey] !== void 0) cachedSnapshot = caches.byStateRenderAndRun[cacheKey];
1286
+ if (cachedSnapshot === void 0 && stateRenderId && previousUserMessageId && caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`] !== void 0) cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`];
1287
+ if (cachedSnapshot === void 0 && !skipLatestCache && stateRenderId && messageRole !== "assistant" && (stateSnapshotProp !== void 0 || agentState && Object.keys(agentState).length > 0)) cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::latest`];
1288
+ const snapshotForClaim = existingClaim?.locked ? existingClaim.stateSnapshot ?? cachedSnapshot : hasSnapshotKeys ? snapshot : existingClaim?.stateSnapshot ?? cachedSnapshot;
1289
+ return {
1290
+ snapshot,
1291
+ hasSnapshotKeys,
1292
+ cachedSnapshot,
1293
+ allowEmptySnapshot,
1294
+ snapshotForClaim
1295
+ };
1296
+ }
1297
+
1298
+ //#endregion
1299
+ //#region src/hooks/use-coagent-state-render-registry.ts
1300
+ const LAST_SNAPSHOTS_BY_RENDER_AND_RUN = "__lastSnapshotsByStateRenderIdAndRun";
1301
+ const LAST_SNAPSHOTS_BY_MESSAGE = "__lastSnapshotsByMessageId";
1302
+ function getClaimsStore(claimsRef) {
1303
+ return claimsRef.current;
1304
+ }
1305
+ function getSnapshotCaches(claimsRef) {
1306
+ const store = getClaimsStore(claimsRef);
1307
+ return {
1308
+ byStateRenderAndRun: store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {},
1309
+ byMessageId: store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}
1310
+ };
1311
+ }
1312
+ function useStateRenderRegistry({ agentId, stateRenderId, message, messageIndex, stateSnapshot, agentState, agentMessages, claimsRef }) {
1313
+ const store = getClaimsStore(claimsRef);
1314
+ const runId = message.runId;
1315
+ const cachedMessageEntry = store[LAST_SNAPSHOTS_BY_MESSAGE]?.[message.id];
1316
+ const { runId: cachedMessageRunId } = readCachedMessageEntry(cachedMessageEntry);
1317
+ const existingClaimRunId = claimsRef.current[message.id]?.runId;
1318
+ const effectiveRunId = getEffectiveRunId({
1319
+ existingClaimRunId,
1320
+ cachedMessageRunId,
1321
+ runId
1322
+ });
1323
+ (0, react.useEffect)(() => {
1324
+ return () => {
1325
+ const existingClaim = claimsRef.current[message.id];
1326
+ if (existingClaim?.stateSnapshot && Object.keys(existingClaim.stateSnapshot).length > 0) {
1327
+ const snapshotCache = { ...store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {} };
1328
+ const cacheKey = `${existingClaim.stateRenderId}::${existingClaim.runId ?? "pending"}`;
1329
+ snapshotCache[cacheKey] = existingClaim.stateSnapshot;
1330
+ snapshotCache[`${existingClaim.stateRenderId}::latest`] = existingClaim.stateSnapshot;
1331
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1332
+ const messageCache = { ...store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {} };
1333
+ messageCache[message.id] = {
1334
+ snapshot: existingClaim.stateSnapshot,
1335
+ runId: existingClaim.runId ?? effectiveRunId
1336
+ };
1337
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1338
+ }
1339
+ delete claimsRef.current[message.id];
1340
+ };
1341
+ }, [
1342
+ claimsRef,
1343
+ effectiveRunId,
1344
+ message.id
1345
+ ]);
1346
+ if (!stateRenderId) return { canRender: false };
1347
+ const caches = getSnapshotCaches(claimsRef);
1348
+ const existingClaim = claimsRef.current[message.id];
1349
+ const { snapshot, hasSnapshotKeys, allowEmptySnapshot, snapshotForClaim } = selectSnapshot({
1350
+ messageId: message.id,
1351
+ messageName: message.name,
1352
+ allowLiveState: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),
1353
+ skipLatestCache: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),
1354
+ stateRenderId,
1355
+ effectiveRunId,
1356
+ stateSnapshotProp: stateSnapshot,
1357
+ agentState,
1358
+ agentMessages,
1359
+ existingClaim,
1360
+ caches
1361
+ });
1362
+ const resolution = resolveClaim({
1363
+ claims: claimsRef.current,
1364
+ context: {
1365
+ agentId,
1366
+ messageId: message.id,
1367
+ stateRenderId,
1368
+ runId: effectiveRunId,
1369
+ messageIndex
1370
+ },
1371
+ stateSnapshot: snapshotForClaim
1372
+ });
1373
+ if (resolution.action === ClaimAction.Block) return { canRender: false };
1374
+ if (resolution.updateRunId && claimsRef.current[message.id]) claimsRef.current[message.id].runId = resolution.updateRunId;
1375
+ if (resolution.nextClaim) claimsRef.current[message.id] = resolution.nextClaim;
1376
+ if (resolution.lockOthers) Object.entries(claimsRef.current).forEach(([id, claim]) => {
1377
+ if (id !== message.id && claim.stateRenderId === stateRenderId) claim.locked = true;
1378
+ });
1379
+ if (existingClaim && !existingClaim.locked && agentMessages?.length) {
1380
+ const indexInAgentMessages = agentMessages.findIndex((msg) => msg.id === message.id);
1381
+ if (indexInAgentMessages >= 0 && indexInAgentMessages < agentMessages.length - 1) existingClaim.locked = true;
1382
+ }
1383
+ const existingSnapshot = claimsRef.current[message.id].stateSnapshot;
1384
+ const snapshotChanged = stateSnapshot && existingSnapshot !== void 0 && !areStatesEquals(existingSnapshot, snapshot);
1385
+ if (snapshot && (stateSnapshot || hasSnapshotKeys || allowEmptySnapshot) && (!claimsRef.current[message.id].locked || snapshotChanged)) {
1386
+ if (!claimsRef.current[message.id].locked || snapshotChanged) {
1387
+ claimsRef.current[message.id].stateSnapshot = snapshot;
1388
+ const snapshotCache = { ...store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {} };
1389
+ const cacheKey = `${stateRenderId}::${effectiveRunId}`;
1390
+ snapshotCache[cacheKey] = snapshot;
1391
+ snapshotCache[`${stateRenderId}::latest`] = snapshot;
1392
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1393
+ const messageCache = { ...store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {} };
1394
+ messageCache[message.id] = {
1395
+ snapshot,
1396
+ runId: effectiveRunId
1397
+ };
1398
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1399
+ if (stateSnapshot) claimsRef.current[message.id].locked = true;
1400
+ }
1401
+ } else if (snapshotForClaim) {
1402
+ if (!claimsRef.current[message.id].stateSnapshot) {
1403
+ claimsRef.current[message.id].stateSnapshot = snapshotForClaim;
1404
+ const snapshotCache = { ...store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {} };
1405
+ const cacheKey = `${stateRenderId}::${effectiveRunId}`;
1406
+ snapshotCache[cacheKey] = snapshotForClaim;
1407
+ snapshotCache[`${stateRenderId}::latest`] = snapshotForClaim;
1408
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1409
+ const messageCache = { ...store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {} };
1410
+ messageCache[message.id] = {
1411
+ snapshot: snapshotForClaim,
1412
+ runId: effectiveRunId
1413
+ };
1414
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1415
+ }
1416
+ }
1417
+ return { canRender: true };
1418
+ }
1419
+
1420
+ //#endregion
1421
+ //#region src/hooks/use-coagent-state-render-bridge.tsx
1422
+ function useCoagentStateRenderBridge(agentId, props) {
1423
+ const { stateSnapshot, message } = props;
1424
+ const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();
1425
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId });
1426
+ const [nodeName, setNodeName] = (0, react.useState)(void 0);
1427
+ const [, forceUpdate] = (0, react.useState)(0);
1428
+ (0, react.useEffect)(() => {
1429
+ if (!agent) return;
1430
+ const { unsubscribe } = agent.subscribe({
1431
+ onStateChanged: () => {
1432
+ forceUpdate((value) => value + 1);
1433
+ },
1434
+ onStepStartedEvent: ({ event }) => {
1435
+ if (event.stepName !== nodeName) setNodeName(event.stepName);
1436
+ },
1437
+ onStepFinishedEvent: ({ event }) => {
1438
+ if (event.stepName === nodeName) setNodeName(void 0);
1439
+ }
1440
+ });
1441
+ return () => {
1442
+ unsubscribe();
1443
+ };
1444
+ }, [agentId, nodeName]);
1445
+ const getStateRender = (0, react.useCallback)((messageId) => {
1446
+ return Object.entries(coAgentStateRenders).find(([stateRenderId, stateRender]) => {
1447
+ if (claimsRef.current[messageId]) return stateRenderId === claimsRef.current[messageId].stateRenderId;
1448
+ const matchingAgentName = stateRender.name === agentId;
1449
+ const matchesNodeContext = stateRender.nodeName ? stateRender.nodeName === nodeName : true;
1450
+ return matchingAgentName && matchesNodeContext;
1451
+ });
1452
+ }, [
1453
+ coAgentStateRenders,
1454
+ nodeName,
1455
+ agentId
1456
+ ]);
1457
+ const stateRenderEntry = (0, react.useMemo)(() => getStateRender(message.id), [getStateRender, message.id]);
1458
+ const stateRenderId = stateRenderEntry?.[0];
1459
+ const stateRender = stateRenderEntry?.[1];
1460
+ const { canRender } = useStateRenderRegistry({
1461
+ agentId,
1462
+ stateRenderId,
1463
+ message: {
1464
+ ...message,
1465
+ runId: props.runId ?? message.runId
1466
+ },
1467
+ messageIndex: props.messageIndex,
1468
+ stateSnapshot,
1469
+ agentState: agent?.state,
1470
+ agentMessages: agent?.messages,
1471
+ claimsRef
1472
+ });
1473
+ return (0, react.useMemo)(() => {
1474
+ if (!stateRender || !stateRenderId) return null;
1475
+ if (!canRender) return null;
1476
+ if (stateRender.handler) stateRender.handler({
1477
+ state: stateSnapshot ? (0, _copilotkit_shared.parseJson)(stateSnapshot, stateSnapshot) : agent?.state ?? {},
1478
+ nodeName: nodeName ?? ""
1479
+ });
1480
+ if (stateRender.render) {
1481
+ const status = agent?.isRunning ? RenderStatus.InProgress : RenderStatus.Complete;
1482
+ if (typeof stateRender.render === "string") return stateRender.render;
1483
+ return stateRender.render({
1484
+ status,
1485
+ state: claimsRef.current[message.id].stateSnapshot ?? {},
1486
+ nodeName: nodeName ?? ""
1487
+ });
1488
+ }
1489
+ }, [
1490
+ stateRender,
1491
+ stateRenderId,
1492
+ agent?.state,
1493
+ agent?.isRunning,
1494
+ nodeName,
1495
+ message.id,
1496
+ stateSnapshot,
1497
+ canRender
1498
+ ]);
1499
+ }
1500
+ function CoAgentStateRenderBridge(props) {
1501
+ return useCoagentStateRenderBridge(props.agentId, props);
1502
+ }
1503
+
1504
+ //#endregion
1505
+ //#region src/components/CopilotListeners.tsx
1506
+ const usePredictStateSubscription = (agent) => {
1507
+ const predictStateToolsRef = (0, react.useRef)([]);
1508
+ const getSubscriber = (0, react.useCallback)((agent) => ({
1509
+ onCustomEvent: ({ event }) => {
1510
+ if (event.name === "PredictState") predictStateToolsRef.current = event.value;
1511
+ },
1512
+ onToolCallArgsEvent: ({ partialToolCallArgs, toolCallName }) => {
1513
+ predictStateToolsRef.current.forEach((t) => {
1514
+ if (t?.tool !== toolCallName) return;
1515
+ const emittedState = typeof partialToolCallArgs === "string" ? (0, _copilotkit_shared.parseJson)(partialToolCallArgs, partialToolCallArgs) : partialToolCallArgs;
1516
+ agent.setState({ [t.state_key]: emittedState[t.state_key] });
1517
+ });
1518
+ }
1519
+ }), []);
1520
+ (0, react.useEffect)(() => {
1521
+ if (!agent) return;
1522
+ const subscriber = getSubscriber(agent);
1523
+ const { unsubscribe } = agent.subscribe(subscriber);
1524
+ return () => {
1525
+ unsubscribe();
1526
+ };
1527
+ }, [agent, getSubscriber]);
1528
+ };
1529
+ function CopilotListeners() {
1530
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
1531
+ const resolvedAgentId = (0, _copilotkitnext_react.useCopilotChatConfiguration)()?.agentId;
1532
+ const { setBannerError } = useToast();
1533
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId: resolvedAgentId });
1534
+ usePredictStateSubscription(agent);
1535
+ (0, react.useEffect)(() => {
1536
+ const subscription = copilotkit.subscribe({ onError: ({ error }) => {
1537
+ setBannerError(new _copilotkit_shared.CopilotKitLowLevelError({
1538
+ error,
1539
+ message: error.message,
1540
+ url: typeof window !== "undefined" ? window.location.href : ""
1541
+ }));
1542
+ } });
1543
+ return () => {
1544
+ subscription.unsubscribe();
1545
+ };
1546
+ }, [copilotkit?.subscribe]);
1547
+ return null;
1548
+ }
1549
+
1550
+ //#endregion
1551
+ //#region src/components/copilot-provider/copilotkit.tsx
1552
+ /**
1553
+ * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.
1554
+ *
1555
+ * ## Example
1556
+ *
1557
+ * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).
1558
+ *
1559
+ * ```tsx
1560
+ * import { CopilotKit } from "@copilotkit/react-core";
1561
+ *
1562
+ * <CopilotKit runtimeUrl="<your-runtime-url>">
1563
+ * // ... your app ...
1564
+ * </CopilotKit>
1565
+ * ```
1566
+ */
1567
+ function CopilotKit({ children, ...props }) {
1568
+ const enabled = shouldShowDevConsole(props.showDevConsole);
1569
+ const showInspector = shouldShowDevConsole(props.enableInspector);
1570
+ const publicApiKey = props.publicApiKey || props.publicLicenseKey;
1571
+ const renderArr = (0, react.useMemo)(() => [{ render: CoAgentStateRenderBridge }], []);
1572
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToastProvider, {
1573
+ enabled,
1574
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotErrorBoundary, {
1575
+ publicApiKey,
1576
+ showUsageBanner: enabled,
1577
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ThreadsProvider, {
1578
+ threadId: props.threadId,
1579
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkitnext_react.CopilotKitProvider, {
1580
+ ...props,
1581
+ showDevConsole: showInspector,
1582
+ renderCustomMessages: renderArr,
1583
+ useSingleEndpoint: props.useSingleEndpoint ?? true,
1584
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitInternal, {
1585
+ ...props,
1586
+ children
1587
+ })
1588
+ })
1589
+ })
1590
+ })
1591
+ });
1592
+ }
1593
+ /**
1594
+ * Bridge component that subscribes to v2.x copilotkit core error events
1595
+ * and forwards them to v1.x error handling system.
1596
+ * This ensures only ONE subscription exists regardless of how many times
1597
+ * Chat components are rendered.
1598
+ */
1599
+ function CopilotKitErrorBridge() {
1600
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
1601
+ const { onError, copilotApiConfig } = useCopilotContext();
1602
+ (0, react.useEffect)(() => {
1603
+ if (!copilotkit) return;
1604
+ const subscription = copilotkit.subscribe({ onError: async (event) => {
1605
+ const errorEvent = {
1606
+ type: "error",
1607
+ timestamp: Date.now(),
1608
+ context: {
1609
+ source: "agent",
1610
+ request: {
1611
+ operation: event.code || "unknown",
1612
+ url: copilotApiConfig?.chatApiEndpoint,
1613
+ startTime: Date.now()
1614
+ },
1615
+ technical: {
1616
+ environment: "browser",
1617
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
1618
+ stackTrace: event.error.stack
1619
+ },
1620
+ ...event.context
1621
+ },
1622
+ error: event.error
1623
+ };
1624
+ try {
1625
+ await onError(errorEvent);
1626
+ } catch (handlerError) {
1627
+ console.error("Error in onError handler:", handlerError);
1628
+ }
1629
+ } });
1630
+ return () => {
1631
+ subscription.unsubscribe();
1632
+ };
1633
+ }, [
1634
+ copilotkit,
1635
+ onError,
1636
+ copilotApiConfig
1637
+ ]);
1638
+ return null;
1639
+ }
1640
+ function CopilotKitInternal(cpkProps) {
1641
+ const { children, ...props } = cpkProps;
1642
+ /**
1643
+ * This will throw an error if the props are invalid.
1644
+ */
1645
+ validateProps(cpkProps);
1646
+ const publicApiKey = props.publicLicenseKey || props.publicApiKey;
1647
+ const chatApiEndpoint = props.runtimeUrl || _copilotkit_shared.COPILOT_CLOUD_CHAT_URL;
1648
+ const [actions, setActions] = (0, react.useState)({});
1649
+ const [registeredActionConfigs, setRegisteredActionConfigs] = (0, react.useState)(/* @__PURE__ */ new Map());
1650
+ const chatComponentsCache = (0, react.useRef)({
1651
+ actions: {},
1652
+ coAgentStateRenders: {}
1653
+ });
1654
+ const { addElement, removeElement, printTree, getAllElements } = useTree();
1655
+ const [isLoading, setIsLoading] = (0, react.useState)(false);
1656
+ const [chatInstructions, setChatInstructions] = (0, react.useState)("");
1657
+ const [authStates, setAuthStates] = (0, react.useState)({});
1658
+ const [extensions, setExtensions] = (0, react.useState)({});
1659
+ const [additionalInstructions, setAdditionalInstructions] = (0, react.useState)([]);
1660
+ const { addElement: addDocument, removeElement: removeDocument, allElements: allDocuments } = useFlatCategoryStore();
1661
+ const setAction = (0, react.useCallback)((id, action) => {
1662
+ setActions((prevPoints) => {
1663
+ return {
1664
+ ...prevPoints,
1665
+ [id]: action
1666
+ };
1667
+ });
1668
+ }, []);
1669
+ const removeAction = (0, react.useCallback)((id) => {
1670
+ setActions((prevPoints) => {
1671
+ const newPoints = { ...prevPoints };
1672
+ delete newPoints[id];
1673
+ return newPoints;
1674
+ });
1675
+ }, []);
1676
+ const getContextString = (0, react.useCallback)((documents, categories) => {
1677
+ return `${documents.map((document) => {
1678
+ return `${document.name} (${document.sourceApplication}):\n${document.getContents()}`;
1679
+ }).join("\n\n")}\n\n${printTree(categories)}`;
1680
+ }, [printTree]);
1681
+ const addContext = (0, react.useCallback)((context, parentId, categories = defaultCopilotContextCategories) => {
1682
+ return addElement(context, categories, parentId);
1683
+ }, [addElement]);
1684
+ const removeContext = (0, react.useCallback)((id) => {
1685
+ removeElement(id);
1686
+ }, [removeElement]);
1687
+ const getAllContext = (0, react.useCallback)(() => {
1688
+ return getAllElements();
1689
+ }, [getAllElements]);
1690
+ const getFunctionCallHandler = (0, react.useCallback)((customEntryPoints) => {
1691
+ return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
1692
+ }, [actions]);
1693
+ const getDocumentsContext = (0, react.useCallback)((categories) => {
1694
+ return allDocuments(categories);
1695
+ }, [allDocuments]);
1696
+ const addDocumentContext = (0, react.useCallback)((documentPointer, categories = defaultCopilotContextCategories) => {
1697
+ return addDocument(documentPointer, categories);
1698
+ }, [addDocument]);
1699
+ const removeDocumentContext = (0, react.useCallback)((documentId) => {
1700
+ removeDocument(documentId);
1701
+ }, [removeDocument]);
1702
+ const copilotApiConfig = (0, react.useMemo)(() => {
1703
+ let cloud = void 0;
1704
+ if (publicApiKey) cloud = { guardrails: { input: { restrictToTopic: {
1705
+ enabled: Boolean(props.guardrails_c),
1706
+ validTopics: props.guardrails_c?.validTopics || [],
1707
+ invalidTopics: props.guardrails_c?.invalidTopics || []
1708
+ } } } };
1709
+ return {
1710
+ publicApiKey,
1711
+ ...cloud ? { cloud } : {},
1712
+ chatApiEndpoint,
1713
+ headers: props.headers || {},
1714
+ properties: props.properties || {},
1715
+ transcribeAudioUrl: props.transcribeAudioUrl,
1716
+ textToSpeechUrl: props.textToSpeechUrl,
1717
+ credentials: props.credentials
1718
+ };
1719
+ }, [
1720
+ publicApiKey,
1721
+ props.headers,
1722
+ props.properties,
1723
+ props.transcribeAudioUrl,
1724
+ props.textToSpeechUrl,
1725
+ props.credentials,
1726
+ props.cloudRestrictToTopic,
1727
+ props.guardrails_c
1728
+ ]);
1729
+ (0, react.useMemo)(() => {
1730
+ const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {
1731
+ if (state.status === "authenticated" && state.authHeaders) return {
1732
+ ...acc,
1733
+ ...Object.entries(state.authHeaders).reduce((headers, [key, value]) => ({
1734
+ ...headers,
1735
+ [key.startsWith("X-Custom-") ? key : `X-Custom-${key}`]: value
1736
+ }), {})
1737
+ };
1738
+ return acc;
1739
+ }, {});
1740
+ return {
1741
+ ...copilotApiConfig.headers || {},
1742
+ ...copilotApiConfig.publicApiKey ? { [_copilotkit_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {},
1743
+ ...authHeaders
1744
+ };
1745
+ }, [
1746
+ copilotApiConfig.headers,
1747
+ copilotApiConfig.publicApiKey,
1748
+ authStates
1749
+ ]);
1750
+ const [internalErrorHandlers, _setInternalErrorHandler] = (0, react.useState)({});
1751
+ const setInternalErrorHandler = (0, react.useCallback)((handler) => {
1752
+ _setInternalErrorHandler((prev) => ({
1753
+ ...prev,
1754
+ ...handler
1755
+ }));
1756
+ }, []);
1757
+ const removeInternalErrorHandler = (0, react.useCallback)((key) => {
1758
+ _setInternalErrorHandler((prev) => {
1759
+ const { [key]: _removed, ...rest } = prev;
1760
+ return rest;
1761
+ });
1762
+ }, []);
1763
+ const onErrorRef = (0, react.useRef)(props.onError);
1764
+ (0, react.useEffect)(() => {
1765
+ onErrorRef.current = props.onError;
1766
+ }, [props.onError]);
1767
+ const internalHandlersRef = (0, react.useRef)({});
1768
+ (0, react.useEffect)(() => {
1769
+ internalHandlersRef.current = internalErrorHandlers;
1770
+ }, [internalErrorHandlers]);
1771
+ const handleErrors = (0, react.useCallback)(async (error) => {
1772
+ if (copilotApiConfig.publicApiKey && onErrorRef.current) try {
1773
+ await onErrorRef.current(error);
1774
+ } catch (e) {
1775
+ console.error("Error in public onError handler:", e);
1776
+ }
1777
+ const handlers = Object.values(internalHandlersRef.current);
1778
+ await Promise.all(handlers.map((h) => Promise.resolve(h(error)).catch((e) => console.error("Error in internal error handler:", e))));
1779
+ }, [copilotApiConfig.publicApiKey]);
1780
+ const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, react.useState)({});
1781
+ const addChatSuggestionConfiguration = (0, react.useCallback)((id, suggestion) => {
1782
+ setChatSuggestionConfiguration((prev) => ({
1783
+ ...prev,
1784
+ [id]: suggestion
1785
+ }));
1786
+ }, [setChatSuggestionConfiguration]);
1787
+ const removeChatSuggestionConfiguration = (0, react.useCallback)((id) => {
1788
+ setChatSuggestionConfiguration((prev) => {
1789
+ const { [id]: _, ...rest } = prev;
1790
+ return rest;
1791
+ });
1792
+ }, [setChatSuggestionConfiguration]);
1793
+ const [availableAgents, setAvailableAgents] = (0, react.useState)([]);
1794
+ const [coagentStates, setCoagentStates] = (0, react.useState)({});
1795
+ const coagentStatesRef = (0, react.useRef)({});
1796
+ const setCoagentStatesWithRef = (0, react.useCallback)((value) => {
1797
+ const newValue = typeof value === "function" ? value(coagentStatesRef.current) : value;
1798
+ coagentStatesRef.current = newValue;
1799
+ setCoagentStates((prev) => {
1800
+ return newValue;
1801
+ });
1802
+ }, []);
1803
+ let initialAgentSession = null;
1804
+ if (props.agent) initialAgentSession = { agentName: props.agent };
1805
+ const [agentSession, setAgentSession] = (0, react.useState)(initialAgentSession);
1806
+ (0, react.useEffect)(() => {
1807
+ if (props.agent) setAgentSession({ agentName: props.agent });
1808
+ else setAgentSession(null);
1809
+ }, [props.agent]);
1810
+ const { threadId, setThreadId: setInternalThreadId } = useThreads();
1811
+ const setThreadId = (0, react.useCallback)((value) => {
1812
+ if (props.threadId) throw new Error("Cannot call setThreadId() when threadId is provided via props.");
1813
+ setInternalThreadId(value);
1814
+ }, [props.threadId]);
1815
+ const [runId, setRunId] = (0, react.useState)(null);
1816
+ const chatAbortControllerRef = (0, react.useRef)(null);
1817
+ const showDevConsole = shouldShowDevConsole(props.showDevConsole);
1818
+ const [interruptActions, _setInterruptActions] = (0, react.useState)({});
1819
+ const setInterruptAction = (0, react.useCallback)((action) => {
1820
+ _setInterruptActions((prev) => {
1821
+ if (action == null || !action.id) return prev;
1822
+ return {
1823
+ ...prev,
1824
+ [action.id]: {
1825
+ ...prev[action.id] ?? {},
1826
+ ...action
1827
+ }
1828
+ };
1829
+ });
1830
+ }, []);
1831
+ const removeInterruptAction = (0, react.useCallback)((actionId) => {
1832
+ _setInterruptActions((prev) => {
1833
+ const { [actionId]: _, ...rest } = prev;
1834
+ return rest;
1835
+ });
1836
+ }, []);
1837
+ const [interruptEventQueue, setInterruptEventQueue] = (0, react.useState)({});
1838
+ const addInterruptEvent = (0, react.useCallback)((queuedEvent) => {
1839
+ setInterruptEventQueue((prev) => {
1840
+ const threadQueue = prev[queuedEvent.threadId] || [];
1841
+ return {
1842
+ ...prev,
1843
+ [queuedEvent.threadId]: [...threadQueue, queuedEvent]
1844
+ };
1845
+ });
1846
+ }, []);
1847
+ const resolveInterruptEvent = (0, react.useCallback)((threadId, eventId, response) => {
1848
+ setInterruptEventQueue((prev) => {
1849
+ const threadQueue = prev[threadId] || [];
1850
+ return {
1851
+ ...prev,
1852
+ [threadId]: threadQueue.map((queuedEvent) => queuedEvent.eventId === eventId ? {
1853
+ ...queuedEvent,
1854
+ event: {
1855
+ ...queuedEvent.event,
1856
+ response
1857
+ }
1858
+ } : queuedEvent)
1859
+ };
1860
+ });
1861
+ }, []);
1862
+ const memoizedChildren = (0, react.useMemo)(() => children, [children]);
1863
+ const [bannerError, setBannerError] = (0, react.useState)(null);
1864
+ const agentLock = (0, react.useMemo)(() => props.agent ?? null, [props.agent]);
1865
+ const forwardedParameters = (0, react.useMemo)(() => props.forwardedParameters ?? {}, [props.forwardedParameters]);
1866
+ const updateExtensions = (0, react.useCallback)((newExtensions) => {
1867
+ setExtensions((prev) => {
1868
+ const resolved = typeof newExtensions === "function" ? newExtensions(prev) : newExtensions;
1869
+ return Object.keys(resolved).length === Object.keys(prev).length && Object.entries(resolved).every(([key, value]) => prev[key] === value) ? prev : resolved;
1870
+ });
1871
+ }, [setExtensions]);
1872
+ const updateAuthStates = (0, react.useCallback)((newAuthStates) => {
1873
+ setAuthStates((prev) => {
1874
+ const resolved = typeof newAuthStates === "function" ? newAuthStates(prev) : newAuthStates;
1875
+ return Object.keys(resolved).length === Object.keys(prev).length && Object.entries(resolved).every(([key, value]) => prev[key] === value) ? prev : resolved;
1876
+ });
1877
+ }, [setAuthStates]);
1878
+ const handleSetRegisteredActions = (0, react.useCallback)((actionConfig) => {
1879
+ const key = actionConfig.action.name || (0, _copilotkit_shared.randomUUID)();
1880
+ setRegisteredActionConfigs((prev) => {
1881
+ const newMap = new Map(prev);
1882
+ newMap.set(key, actionConfig);
1883
+ return newMap;
1884
+ });
1885
+ return key;
1886
+ }, []);
1887
+ const handleRemoveRegisteredAction = (0, react.useCallback)((actionKey) => {
1888
+ setRegisteredActionConfigs((prev) => {
1889
+ const newMap = new Map(prev);
1890
+ newMap.delete(actionKey);
1891
+ return newMap;
1892
+ });
1893
+ }, []);
1894
+ const RegisteredActionsRenderer = (0, react.useMemo)(() => {
1895
+ return () => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: Array.from(registeredActionConfigs.entries()).map(([key, config]) => {
1896
+ const Component = config.component;
1897
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Component, { action: config.action }, key);
1898
+ }) });
1899
+ }, [registeredActionConfigs]);
1900
+ const copilotContextValue = (0, react.useMemo)(() => ({
1901
+ actions,
1902
+ chatComponentsCache,
1903
+ getFunctionCallHandler,
1904
+ setAction,
1905
+ removeAction,
1906
+ setRegisteredActions: handleSetRegisteredActions,
1907
+ removeRegisteredAction: handleRemoveRegisteredAction,
1908
+ getContextString,
1909
+ addContext,
1910
+ removeContext,
1911
+ getAllContext,
1912
+ getDocumentsContext,
1913
+ addDocumentContext,
1914
+ removeDocumentContext,
1915
+ copilotApiConfig,
1916
+ isLoading,
1917
+ setIsLoading,
1918
+ chatSuggestionConfiguration,
1919
+ addChatSuggestionConfiguration,
1920
+ removeChatSuggestionConfiguration,
1921
+ chatInstructions,
1922
+ setChatInstructions,
1923
+ additionalInstructions,
1924
+ setAdditionalInstructions,
1925
+ showDevConsole,
1926
+ coagentStates,
1927
+ setCoagentStates,
1928
+ coagentStatesRef,
1929
+ setCoagentStatesWithRef,
1930
+ agentSession,
1931
+ setAgentSession,
1932
+ forwardedParameters,
1933
+ agentLock,
1934
+ threadId,
1935
+ setThreadId,
1936
+ runId,
1937
+ setRunId,
1938
+ chatAbortControllerRef,
1939
+ availableAgents,
1940
+ authConfig_c: props.authConfig_c,
1941
+ authStates_c: authStates,
1942
+ setAuthStates_c: updateAuthStates,
1943
+ extensions,
1944
+ setExtensions: updateExtensions,
1945
+ interruptActions,
1946
+ setInterruptAction,
1947
+ removeInterruptAction,
1948
+ interruptEventQueue,
1949
+ addInterruptEvent,
1950
+ resolveInterruptEvent,
1951
+ bannerError,
1952
+ setBannerError,
1953
+ onError: handleErrors,
1954
+ internalErrorHandlers,
1955
+ setInternalErrorHandler,
1956
+ removeInternalErrorHandler
1957
+ }), [
1958
+ actions,
1959
+ chatComponentsCache,
1960
+ getFunctionCallHandler,
1961
+ setAction,
1962
+ removeAction,
1963
+ handleSetRegisteredActions,
1964
+ handleRemoveRegisteredAction,
1965
+ getContextString,
1966
+ addContext,
1967
+ removeContext,
1968
+ getAllContext,
1969
+ getDocumentsContext,
1970
+ addDocumentContext,
1971
+ removeDocumentContext,
1972
+ copilotApiConfig,
1973
+ isLoading,
1974
+ chatSuggestionConfiguration,
1975
+ addChatSuggestionConfiguration,
1976
+ removeChatSuggestionConfiguration,
1977
+ chatInstructions,
1978
+ additionalInstructions,
1979
+ showDevConsole,
1980
+ coagentStates,
1981
+ setCoagentStatesWithRef,
1982
+ agentSession,
1983
+ setAgentSession,
1984
+ forwardedParameters,
1985
+ agentLock,
1986
+ threadId,
1987
+ setThreadId,
1988
+ runId,
1989
+ availableAgents,
1990
+ props.authConfig_c,
1991
+ authStates,
1992
+ updateAuthStates,
1993
+ extensions,
1994
+ updateExtensions,
1995
+ interruptActions,
1996
+ setInterruptAction,
1997
+ removeInterruptAction,
1998
+ interruptEventQueue,
1999
+ addInterruptEvent,
2000
+ resolveInterruptEvent,
2001
+ bannerError,
2002
+ handleErrors,
2003
+ internalErrorHandlers,
2004
+ setInternalErrorHandler,
2005
+ removeInternalErrorHandler
2006
+ ]);
2007
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkitnext_react.CopilotChatConfigurationProvider, {
2008
+ agentId: props.agent ?? "default",
2009
+ threadId,
2010
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CopilotContext.Provider, {
2011
+ value: copilotContextValue,
2012
+ children: [
2013
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotListeners, {}),
2014
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitErrorBridge, {}),
2015
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CoAgentStateRendersProvider, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(MessagesTapProvider, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CopilotMessages, { children: [memoizedChildren, /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RegisteredActionsRenderer, {})] }) }), bannerError && showDevConsole && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UsageBanner, {
2016
+ severity: bannerError.severity,
2017
+ message: bannerError.message,
2018
+ onClose: () => setBannerError(null),
2019
+ actions: getErrorActions(bannerError)
2020
+ })] })
2021
+ ]
2022
+ })
2023
+ });
2024
+ }
2025
+ const defaultCopilotContextCategories = ["global"];
2026
+ function entryPointsToFunctionCallHandler(actions) {
2027
+ return async ({ name, args }) => {
2028
+ let actionsByFunctionName = {};
2029
+ for (let action of actions) actionsByFunctionName[action.name] = action;
2030
+ const action = actionsByFunctionName[name];
2031
+ let result = void 0;
2032
+ if (action) {
2033
+ await new Promise((resolve, reject) => {
2034
+ (0, react_dom.flushSync)(async () => {
2035
+ try {
2036
+ result = await action.handler?.(args);
2037
+ resolve();
2038
+ } catch (error) {
2039
+ reject(error);
2040
+ }
2041
+ });
2042
+ });
2043
+ await new Promise((resolve) => setTimeout(resolve, 20));
2044
+ }
2045
+ return result;
2046
+ };
2047
+ }
2048
+ function formatFeatureName(featureName) {
2049
+ return featureName.replace(/_c$/, "").split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
2050
+ }
2051
+ function validateProps(props) {
2052
+ const cloudFeatures = Object.keys(props).filter((key) => key.endsWith("_c"));
2053
+ const hasApiKey = props.publicApiKey || props.publicLicenseKey;
2054
+ if (!props.runtimeUrl && !hasApiKey) throw new _copilotkit_shared.ConfigurationError("Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'");
2055
+ if (cloudFeatures.length > 0 && !hasApiKey) throw new _copilotkit_shared.MissingPublicApiKeyError(`Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures.map(formatFeatureName).join(", ")}`);
2056
+ }
2057
+
2058
+ //#endregion
2059
+ Object.defineProperty(exports, 'CoAgentStateRenderBridge', {
2060
+ enumerable: true,
2061
+ get: function () {
2062
+ return CoAgentStateRenderBridge;
2063
+ }
2064
+ });
2065
+ Object.defineProperty(exports, 'CoAgentStateRendersContext', {
2066
+ enumerable: true,
2067
+ get: function () {
2068
+ return CoAgentStateRendersContext;
2069
+ }
2070
+ });
2071
+ Object.defineProperty(exports, 'CoAgentStateRendersProvider', {
2072
+ enumerable: true,
2073
+ get: function () {
2074
+ return CoAgentStateRendersProvider;
2075
+ }
2076
+ });
2077
+ Object.defineProperty(exports, 'CopilotContext', {
2078
+ enumerable: true,
2079
+ get: function () {
2080
+ return CopilotContext;
2081
+ }
2082
+ });
2083
+ Object.defineProperty(exports, 'CopilotKit', {
2084
+ enumerable: true,
2085
+ get: function () {
2086
+ return CopilotKit;
2087
+ }
2088
+ });
2089
+ Object.defineProperty(exports, 'CopilotMessagesContext', {
2090
+ enumerable: true,
2091
+ get: function () {
2092
+ return CopilotMessagesContext;
2093
+ }
2094
+ });
2095
+ Object.defineProperty(exports, 'ThreadsContext', {
2096
+ enumerable: true,
2097
+ get: function () {
2098
+ return ThreadsContext;
2099
+ }
2100
+ });
2101
+ Object.defineProperty(exports, 'ThreadsProvider', {
2102
+ enumerable: true,
2103
+ get: function () {
2104
+ return ThreadsProvider;
2105
+ }
2106
+ });
2107
+ Object.defineProperty(exports, '__toESM', {
2108
+ enumerable: true,
2109
+ get: function () {
2110
+ return __toESM;
2111
+ }
2112
+ });
2113
+ Object.defineProperty(exports, 'defaultCopilotContextCategories', {
2114
+ enumerable: true,
2115
+ get: function () {
2116
+ return defaultCopilotContextCategories;
2117
+ }
2118
+ });
2119
+ Object.defineProperty(exports, 'shouldShowDevConsole', {
2120
+ enumerable: true,
2121
+ get: function () {
2122
+ return shouldShowDevConsole;
2123
+ }
2124
+ });
2125
+ Object.defineProperty(exports, 'useAsyncCallback', {
2126
+ enumerable: true,
2127
+ get: function () {
2128
+ return useAsyncCallback;
2129
+ }
2130
+ });
2131
+ Object.defineProperty(exports, 'useCoAgentStateRenders', {
2132
+ enumerable: true,
2133
+ get: function () {
2134
+ return useCoAgentStateRenders;
2135
+ }
2136
+ });
2137
+ Object.defineProperty(exports, 'useCopilotContext', {
2138
+ enumerable: true,
2139
+ get: function () {
2140
+ return useCopilotContext;
2141
+ }
2142
+ });
2143
+ Object.defineProperty(exports, 'useCopilotMessagesContext', {
2144
+ enumerable: true,
2145
+ get: function () {
2146
+ return useCopilotMessagesContext;
2147
+ }
2148
+ });
2149
+ Object.defineProperty(exports, 'useThreads', {
2150
+ enumerable: true,
2151
+ get: function () {
2152
+ return useThreads;
2153
+ }
2154
+ });
2155
+ Object.defineProperty(exports, 'useToast', {
2156
+ enumerable: true,
2157
+ get: function () {
2158
+ return useToast;
2159
+ }
2160
+ });
2161
+ //# sourceMappingURL=copilotkit-C94ayZbs.cjs.map