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