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