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