@copilotkit/react-core
Version:
<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />
1,373 lines (1,340 loc) • 133 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __restKey = (key) => typeof key === "symbol" ? key : key + "";
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/components/copilot-provider/copilotkit.tsx
var copilotkit_exports = {};
__export(copilotkit_exports, {
CopilotKit: () => CopilotKit,
CopilotKitInternal: () => CopilotKitInternal,
defaultCopilotContextCategories: () => defaultCopilotContextCategories
});
module.exports = __toCommonJS(copilotkit_exports);
var import_react11 = require("react");
// src/context/copilot-context.tsx
var import_react = __toESM(require("react"));
var emptyCopilotContext = {
actions: {},
setAction: () => {
},
removeAction: () => {
},
coAgentStateRenders: {},
setCoAgentStateRender: () => {
},
removeCoAgentStateRender: () => {
},
chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
getContextString: (documents, categories) => returnAndThrowInDebug(""),
addContext: () => "",
removeContext: () => {
},
getAllContext: () => [],
getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
})),
isLoading: false,
setIsLoading: () => returnAndThrowInDebug(false),
chatInstructions: "",
setChatInstructions: () => returnAndThrowInDebug(""),
additionalInstructions: [],
setAdditionalInstructions: () => returnAndThrowInDebug([]),
getDocumentsContext: (categories) => returnAndThrowInDebug([]),
addDocumentContext: () => returnAndThrowInDebug(""),
removeDocumentContext: () => {
},
runtimeClient: {},
copilotApiConfig: new class {
get chatApiEndpoint() {
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
}
get headers() {
return {};
}
get body() {
return {};
}
}(),
chatSuggestionConfiguration: {},
addChatSuggestionConfiguration: () => {
},
removeChatSuggestionConfiguration: () => {
},
showDevConsole: false,
coagentStates: {},
setCoagentStates: () => {
},
coagentStatesRef: { current: {} },
setCoagentStatesWithRef: () => {
},
agentSession: null,
setAgentSession: () => {
},
forwardedParameters: {},
agentLock: null,
threadId: "",
setThreadId: () => {
},
runId: null,
setRunId: () => {
},
chatAbortControllerRef: { current: null },
availableAgents: [],
extensions: {},
setExtensions: () => {
},
langGraphInterruptAction: null,
setLangGraphInterruptAction: () => null,
removeLangGraphInterruptAction: () => null,
onError: void 0,
bannerError: null,
setBannerError: () => {
}
};
var CopilotContext = import_react.default.createContext(emptyCopilotContext);
function useCopilotContext() {
const context = import_react.default.useContext(CopilotContext);
if (context === emptyCopilotContext) {
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
}
return context;
}
function returnAndThrowInDebug(_value) {
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
}
// src/hooks/use-tree.ts
var import_shared = require("@copilotkit/shared");
var import_react2 = require("react");
var removeNode = (nodes, id) => {
return nodes.reduce((result, node) => {
if (node.id !== id) {
const newNode = __spreadProps(__spreadValues({}, node), { children: removeNode(node.children, id) });
result.push(newNode);
}
return result;
}, []);
};
var addNode = (nodes, newNode, parentId) => {
if (!parentId) {
return [...nodes, newNode];
}
return nodes.map((node) => {
if (node.id === parentId) {
return __spreadProps(__spreadValues({}, node), { children: [...node.children, newNode] });
} else if (node.children.length) {
return __spreadProps(__spreadValues({}, node), { children: addNode(node.children, newNode, parentId) });
}
return node;
});
};
var treeIndentationRepresentation = (index, indentLevel) => {
if (indentLevel === 0) {
return (index + 1).toString();
} else if (indentLevel === 1) {
return String.fromCharCode(65 + index);
} else if (indentLevel === 2) {
return String.fromCharCode(97 + index);
} else {
return "-";
}
};
var printNode = (node, prefix = "", indentLevel = 0) => {
const indent = " ".repeat(3).repeat(indentLevel);
const prefixPlusIndentLength = prefix.length + indent.length;
const subsequentLinesPrefix = " ".repeat(prefixPlusIndentLength);
const valueLines = node.value.split("\n");
const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;
const outputSubsequentLines = valueLines.slice(1).map((line) => `${subsequentLinesPrefix}${line}`).join("\n");
let output = `${outputFirstLine}
`;
if (outputSubsequentLines) {
output += `${outputSubsequentLines}
`;
}
const childPrePrefix = " ".repeat(prefix.length);
node.children.forEach(
(child, index) => output += printNode(
child,
`${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `,
indentLevel + 1
)
);
return output;
};
function treeReducer(state, action) {
switch (action.type) {
case "ADD_NODE": {
const { value, parentId, id: newNodeId } = action;
const newNode = {
id: newNodeId,
value,
children: [],
categories: new Set(action.categories)
};
try {
return addNode(state, newNode, parentId);
} catch (error) {
console.error(`Error while adding node with id ${newNodeId}: ${error}`);
return state;
}
}
case "REMOVE_NODE":
return removeNode(state, action.id);
default:
return state;
}
}
var useTree = () => {
const [tree, dispatch] = (0, import_react2.useReducer)(treeReducer, []);
const addElement = (0, import_react2.useCallback)(
(value, categories, parentId) => {
const newNodeId = (0, import_shared.randomId)();
dispatch({
type: "ADD_NODE",
value,
parentId,
id: newNodeId,
categories
});
return newNodeId;
},
[]
);
const removeElement = (0, import_react2.useCallback)((id) => {
dispatch({ type: "REMOVE_NODE", id });
}, []);
const getAllElements = (0, import_react2.useCallback)(() => {
return tree;
}, [tree]);
const printTree = (0, import_react2.useCallback)(
(categories) => {
const categoriesSet = new Set(categories);
let output = "";
tree.forEach((node, index) => {
if (!setsHaveIntersection(categoriesSet, node.categories)) {
return;
}
if (index !== 0) {
output += "\n";
}
output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);
});
return output;
},
[tree]
);
return { tree, addElement, printTree, removeElement, getAllElements };
};
var use_tree_default = useTree;
function setsHaveIntersection(setA, setB) {
const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
for (let item of smallerSet) {
if (largerSet.has(item)) {
return true;
}
}
return false;
}
// src/components/copilot-provider/copilotkit.tsx
var import_react_dom = require("react-dom");
var import_shared10 = require("@copilotkit/shared");
// src/hooks/use-flat-category-store.ts
var import_react3 = require("react");
var import_shared2 = require("@copilotkit/shared");
var useFlatCategoryStore = () => {
const [elements, dispatch] = (0, import_react3.useReducer)(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
const addElement = (0, import_react3.useCallback)((value, categories) => {
const newId = (0, import_shared2.randomId)();
dispatch({
type: "ADD_ELEMENT",
value,
id: newId,
categories
});
return newId;
}, []);
const removeElement = (0, import_react3.useCallback)((id) => {
dispatch({ type: "REMOVE_ELEMENT", id });
}, []);
const allElements = (0, import_react3.useCallback)(
(categories) => {
const categoriesSet = new Set(categories);
const result = [];
elements.forEach((element) => {
if (setsHaveIntersection2(categoriesSet, element.categories)) {
result.push(element.value);
}
});
return result;
},
[elements]
);
return { addElement, removeElement, allElements };
};
var use_flat_category_store_default = useFlatCategoryStore;
function flatCategoryStoreReducer(state, action) {
switch (action.type) {
case "ADD_ELEMENT": {
const { value, id, categories } = action;
const newElement = {
id,
value,
categories: new Set(categories)
};
const newState = new Map(state);
newState.set(id, newElement);
return newState;
}
case "REMOVE_ELEMENT": {
const newState = new Map(state);
newState.delete(action.id);
return newState;
}
default:
return state;
}
}
function setsHaveIntersection2(setA, setB) {
const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
for (let item of smallerSet) {
if (largerSet.has(item)) {
return true;
}
}
return false;
}
// src/components/copilot-provider/copilot-messages.tsx
var import_react6 = require("react");
// src/context/copilot-messages-context.tsx
var import_react4 = __toESM(require("react"));
var emptyCopilotContext2 = {
messages: [],
setMessages: () => [],
// suggestions state
suggestions: [],
setSuggestions: () => []
};
var CopilotMessagesContext = import_react4.default.createContext(emptyCopilotContext2);
function useCopilotMessagesContext() {
const context = import_react4.default.useContext(CopilotMessagesContext);
if (context === emptyCopilotContext2) {
throw new Error(
"A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`"
);
}
return context;
}
// src/components/copilot-provider/copilot-messages.tsx
var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
// src/components/toast/toast-provider.tsx
var import_react5 = require("react");
var import_shared3 = require("@copilotkit/shared");
var import_jsx_runtime = require("react/jsx-runtime");
var ToastContext = (0, import_react5.createContext)(void 0);
function getErrorSeverity(error) {
if (error.severity) {
switch (error.severity) {
case import_shared3.Severity.CRITICAL:
return "critical";
case import_shared3.Severity.WARNING:
return "warning";
case import_shared3.Severity.INFO:
return "info";
default:
return "info";
}
}
const message = error.message.toLowerCase();
if (message.includes("api key") || message.includes("401") || message.includes("unauthorized") || message.includes("authentication") || message.includes("incorrect api key")) {
return "critical";
}
return "info";
}
function getErrorColors(severity) {
switch (severity) {
case "critical":
return {
background: "#fee2e2",
border: "#dc2626",
text: "#7f1d1d",
icon: "#dc2626"
};
case "warning":
return {
background: "#fef3c7",
border: "#d97706",
text: "#78350f",
icon: "#d97706"
};
case "info":
return {
background: "#dbeafe",
border: "#2563eb",
text: "#1e3a8a",
icon: "#2563eb"
};
}
}
function useToast() {
const context = (0, import_react5.useContext)(ToastContext);
if (!context) {
throw new Error("useToast must be used within a ToastProvider");
}
return context;
}
function ToastProvider({
enabled,
children
}) {
const [toasts, setToasts] = (0, import_react5.useState)([]);
const [bannerError, setBannerErrorState] = (0, import_react5.useState)(null);
const removeToast = (0, import_react5.useCallback)((id) => {
setToasts((prev) => prev.filter((toast) => toast.id !== id));
}, []);
const addToast = (0, import_react5.useCallback)(
(toast) => {
var _a;
if (!enabled) {
return;
}
const id = (_a = toast.id) != null ? _a : Math.random().toString(36).substring(2, 9);
setToasts((currentToasts) => {
if (currentToasts.find((toast2) => toast2.id === id))
return currentToasts;
return [...currentToasts, __spreadProps(__spreadValues({}, toast), { id })];
});
if (toast.duration) {
setTimeout(() => {
removeToast(id);
}, toast.duration);
}
},
[enabled, removeToast]
);
const setBannerError = (0, import_react5.useCallback)(
(error) => {
if (!enabled && error !== null) {
return;
}
setBannerErrorState(error);
},
[enabled]
);
const addGraphQLErrorsToast = (0, import_react5.useCallback)((errors) => {
console.warn("addGraphQLErrorsToast is deprecated. All errors now show as banners.");
}, []);
const value = {
toasts,
addToast,
addGraphQLErrorsToast,
removeToast,
enabled,
bannerError,
setBannerError
};
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(ToastContext.Provider, { value, children: [
bannerError && (() => {
const severity = getErrorSeverity(bannerError);
const colors = getErrorColors(severity);
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
"div",
{
style: {
position: "fixed",
bottom: "20px",
left: "50%",
transform: "translateX(-50%)",
zIndex: 9999,
backgroundColor: colors.background,
border: `1px solid ${colors.border}`,
borderLeft: `4px solid ${colors.border}`,
borderRadius: "8px",
padding: "12px 16px",
fontSize: "13px",
boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
backdropFilter: "blur(8px)",
maxWidth: "min(90vw, 700px)",
width: "100%",
boxSizing: "border-box",
overflow: "hidden"
},
children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
"div",
{
style: {
display: "flex",
justifyContent: "space-between",
alignItems: "center",
gap: "10px"
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
"div",
{
style: {
display: "flex",
alignItems: "center",
gap: "8px",
flex: 1,
minWidth: 0
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(
"div",
{
style: {
width: "12px",
height: "12px",
borderRadius: "50%",
backgroundColor: colors.border,
flexShrink: 0
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
"div",
{
style: {
display: "flex",
alignItems: "center",
gap: "10px",
flex: 1,
minWidth: 0
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(
"div",
{
style: {
color: colors.text,
lineHeight: "1.4",
fontWeight: "400",
fontSize: "13px",
flex: 1,
wordBreak: "break-all",
overflowWrap: "break-word",
maxWidth: "550px",
overflow: "hidden",
display: "-webkit-box",
WebkitLineClamp: 10,
WebkitBoxOrient: "vertical"
},
children: (() => {
let message = bannerError.message;
const jsonMatch = message.match(/'message':\s*'([^']+)'/);
if (jsonMatch) {
return jsonMatch[1];
}
message = message.split(" - ")[0];
message = message.split(": Error code")[0];
message = message.replace(/:\s*\d{3}$/, "");
message = message.replace(/See more:.*$/g, "");
message = message.trim();
return message || "Configuration error occurred.";
})()
}
),
(() => {
const message = bannerError.message;
const markdownLinkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
const plainUrlRegex = /(https?:\/\/[^\s)]+)/g;
let url = null;
let buttonText = "See More";
const markdownMatch = markdownLinkRegex.exec(message);
if (markdownMatch) {
url = markdownMatch[2];
buttonText = "See More";
} else {
const urlMatch = plainUrlRegex.exec(message);
if (urlMatch) {
url = urlMatch[0].replace(/[.,;:'"]*$/, "");
buttonText = "See More";
}
}
if (!url)
return null;
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
"button",
{
onClick: () => window.open(url, "_blank", "noopener,noreferrer"),
style: {
background: colors.border,
color: "white",
border: "none",
borderRadius: "5px",
padding: "4px 10px",
fontSize: "11px",
fontWeight: "500",
cursor: "pointer",
transition: "all 0.2s ease",
flexShrink: 0
},
onMouseEnter: (e) => {
e.currentTarget.style.opacity = "0.9";
e.currentTarget.style.transform = "translateY(-1px)";
},
onMouseLeave: (e) => {
e.currentTarget.style.opacity = "1";
e.currentTarget.style.transform = "translateY(0)";
},
children: buttonText
}
);
})()
]
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(
"button",
{
onClick: () => setBannerError(null),
style: {
background: "transparent",
border: "none",
color: colors.text,
cursor: "pointer",
padding: "2px",
borderRadius: "3px",
fontSize: "14px",
lineHeight: "1",
opacity: 0.6,
transition: "all 0.2s ease",
flexShrink: 0
},
title: "Dismiss",
onMouseEnter: (e) => {
e.currentTarget.style.opacity = "1";
e.currentTarget.style.background = "rgba(0, 0, 0, 0.05)";
},
onMouseLeave: (e) => {
e.currentTarget.style.opacity = "0.6";
e.currentTarget.style.background = "transparent";
},
children: "\xD7"
}
)
]
}
)
}
);
})(),
children
] });
}
// src/utils/dev-console.ts
function isLocalhost() {
if (typeof window === "undefined")
return false;
return window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "0.0.0.0";
}
function shouldShowDevConsole(showDevConsole) {
if (showDevConsole !== void 0) {
return showDevConsole;
}
return isLocalhost();
}
// src/components/copilot-provider/copilot-messages.tsx
var import_shared4 = require("@copilotkit/shared");
var import_jsx_runtime2 = require("react/jsx-runtime");
var MessagesTapContext = (0, import_react6.createContext)(null);
function useMessagesTap() {
const tap = (0, import_react6.useContext)(MessagesTapContext);
if (!tap)
throw new Error("useMessagesTap must be used inside <MessagesTapProvider>");
return tap;
}
function MessagesTapProvider({ children }) {
const messagesRef = (0, import_react6.useRef)([]);
const tapRef = (0, import_react6.useRef)({
getMessagesFromTap: () => messagesRef.current,
updateTapMessages: (messages) => {
messagesRef.current = messages;
}
});
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(MessagesTapContext.Provider, { value: tapRef.current, children });
}
function CopilotMessages({ children }) {
const [messages, setMessages] = (0, import_react6.useState)([]);
const lastLoadedThreadId = (0, import_react6.useRef)();
const lastLoadedAgentName = (0, import_react6.useRef)();
const lastLoadedMessages = (0, import_react6.useRef)();
const { updateTapMessages } = useMessagesTap();
const { threadId, agentSession, runtimeClient, showDevConsole, onError, copilotApiConfig } = useCopilotContext();
const { setBannerError } = useToast();
const traceUIError = (0, import_react6.useCallback)(
(error, originalError) => __async(this, null, function* () {
if (!onError || !copilotApiConfig.publicApiKey)
return;
try {
const traceEvent = {
type: "error",
timestamp: Date.now(),
context: {
source: "ui",
request: {
operation: "loadAgentState",
url: copilotApiConfig.chatApiEndpoint,
startTime: Date.now()
},
technical: {
environment: "browser",
userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
stackTrace: originalError instanceof Error ? originalError.stack : void 0
}
},
error
};
yield onError(traceEvent);
} catch (traceError) {
console.error("Error in CopilotMessages onError handler:", traceError);
}
}),
[onError, copilotApiConfig.publicApiKey, copilotApiConfig.chatApiEndpoint]
);
const createStructuredError2 = (gqlError) => {
const extensions = gqlError.extensions;
const originalError = extensions == null ? void 0 : extensions.originalError;
if (originalError == null ? void 0 : originalError.stack) {
if (originalError.stack.includes("CopilotApiDiscoveryError")) {
return new import_shared4.CopilotKitApiDiscoveryError({ message: originalError.message });
}
if (originalError.stack.includes("CopilotKitRemoteEndpointDiscoveryError")) {
return new import_shared4.CopilotKitRemoteEndpointDiscoveryError({ message: originalError.message });
}
if (originalError.stack.includes("CopilotKitAgentDiscoveryError")) {
return new import_shared4.CopilotKitAgentDiscoveryError({
agentName: "",
availableAgents: []
});
}
}
const message = (originalError == null ? void 0 : originalError.message) || gqlError.message;
const code = extensions == null ? void 0 : extensions.code;
if (code) {
return new import_shared4.CopilotKitError({ message, code });
}
return null;
};
const handleGraphQLErrors = (0, import_react6.useCallback)(
(error) => {
var _a;
if ((_a = error.graphQLErrors) == null ? void 0 : _a.length) {
const graphQLErrors = error.graphQLErrors;
const routeError = (gqlError) => {
const extensions = gqlError.extensions;
const visibility = extensions == null ? void 0 : extensions.visibility;
const isDev = shouldShowDevConsole(showDevConsole);
if (!isDev) {
console.error("CopilotKit Error (hidden in production):", gqlError.message);
return;
}
if (visibility === import_shared4.ErrorVisibility.SILENT) {
console.error("CopilotKit Silent Error:", gqlError.message);
return;
}
const ckError = createStructuredError2(gqlError);
if (ckError) {
setBannerError(ckError);
traceUIError(ckError, gqlError);
} else {
const fallbackError = new import_shared4.CopilotKitError({
message: gqlError.message,
code: import_shared4.CopilotKitErrorCode.UNKNOWN
});
setBannerError(fallbackError);
traceUIError(fallbackError, gqlError);
}
};
graphQLErrors.forEach(routeError);
} else {
const isDev = shouldShowDevConsole(showDevConsole);
if (!isDev) {
console.error("CopilotKit Error (hidden in production):", error);
} else {
const fallbackError = new import_shared4.CopilotKitError({
message: (error == null ? void 0 : error.message) || String(error),
code: import_shared4.CopilotKitErrorCode.UNKNOWN
});
setBannerError(fallbackError);
traceUIError(fallbackError, error);
}
}
},
[setBannerError, showDevConsole, traceUIError]
);
(0, import_react6.useEffect)(() => {
if (!threadId || threadId === lastLoadedThreadId.current)
return;
if (threadId === lastLoadedThreadId.current && (agentSession == null ? void 0 : agentSession.agentName) === lastLoadedAgentName.current) {
return;
}
const fetchMessages = () => __async(this, null, function* () {
var _a, _b, _c, _d;
if (!(agentSession == null ? void 0 : agentSession.agentName))
return;
const result = yield runtimeClient.loadAgentState({
threadId,
agentName: agentSession == null ? void 0 : agentSession.agentName
});
if (result.error) {
lastLoadedThreadId.current = threadId;
lastLoadedAgentName.current = agentSession == null ? void 0 : agentSession.agentName;
handleGraphQLErrors(result.error);
return;
}
const newMessages = (_b = (_a = result.data) == null ? void 0 : _a.loadAgentState) == null ? void 0 : _b.messages;
if (newMessages === lastLoadedMessages.current)
return;
if ((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.threadExists) {
lastLoadedMessages.current = newMessages;
lastLoadedThreadId.current = threadId;
lastLoadedAgentName.current = agentSession == null ? void 0 : agentSession.agentName;
const messages2 = (0, import_runtime_client_gql.loadMessagesFromJsonRepresentation)(JSON.parse(newMessages || "[]"));
setMessages(messages2);
}
});
void fetchMessages();
}, [threadId, agentSession == null ? void 0 : agentSession.agentName]);
(0, import_react6.useEffect)(() => {
updateTapMessages(messages);
}, [messages, updateTapMessages]);
const memoizedChildren = (0, import_react6.useMemo)(() => children, [children]);
const [suggestions, setSuggestions] = (0, import_react6.useState)([]);
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
CopilotMessagesContext.Provider,
{
value: {
messages,
setMessages,
suggestions,
setSuggestions
},
children: memoizedChildren
}
);
}
// src/components/usage-banner.tsx
var import_shared5 = require("@copilotkit/shared");
var import_jsx_runtime3 = require("react/jsx-runtime");
function UsageBanner({
severity = import_shared5.Severity.CRITICAL,
message = "",
onClose,
actions
}) {
if (!message || !severity) {
return null;
}
const themes = {
[import_shared5.Severity.INFO]: {
bg: "#f8fafc",
border: "#e2e8f0",
text: "#475569",
accent: "#3b82f6"
},
[import_shared5.Severity.WARNING]: {
bg: "#fffbeb",
border: "#fbbf24",
text: "#92400e",
accent: "#f59e0b"
},
[import_shared5.Severity.CRITICAL]: {
bg: "#fef2f2",
border: "#fecaca",
text: "#dc2626",
accent: "#ef4444"
}
};
const theme = themes[severity];
return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("style", { children: `
@keyframes slideUp {
from { opacity: 0; transform: translateX(-50%) translateY(8px); }
to { opacity: 1; transform: translateX(-50%) translateY(0); }
}
.usage-banner {
position: fixed;
bottom: 24px;
left: 50%;
transform: translateX(-50%);
width: min(600px, calc(100vw - 32px));
z-index: 10000;
animation: slideUp 0.2s cubic-bezier(0.16, 1, 0.3, 1);
}
.banner-content {
background: linear-gradient(135deg, ${theme.bg} 0%, ${theme.bg}f5 100%);
border: 1px solid ${theme.border};
border-radius: 12px;
padding: 18px 20px;
box-shadow:
0 4px 24px rgba(0, 0, 0, 0.08),
0 2px 8px rgba(0, 0, 0, 0.04),
inset 0 1px 0 rgba(255, 255, 255, 0.7);
display: flex;
align-items: center;
gap: 16px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
backdrop-filter: blur(12px);
position: relative;
overflow: hidden;
}
.banner-content::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 1px;
background: linear-gradient(90deg, transparent, ${theme.accent}40, transparent);
}
.banner-message {
color: ${theme.text};
font-size: 14px;
line-height: 1.5;
font-weight: 500;
flex: 1;
letter-spacing: -0.01em;
}
.close-btn {
background: rgba(0, 0, 0, 0.05);
border: none;
color: ${theme.text};
cursor: pointer;
padding: 0;
border-radius: 6px;
opacity: 0.6;
transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);
font-size: 14px;
line-height: 1;
flex-shrink: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
}
.close-btn:hover {
opacity: 1;
background: rgba(0, 0, 0, 0.08);
transform: scale(1.05);
}
.btn-primary {
background: linear-gradient(135deg, ${theme.accent} 0%, ${theme.accent}e6 100%);
color: white;
border: none;
border-radius: 8px;
padding: 10px 18px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);
font-family: inherit;
flex-shrink: 0;
box-shadow:
0 2px 8px ${theme.accent}30,
inset 0 1px 0 rgba(255, 255, 255, 0.2);
letter-spacing: -0.01em;
}
.btn-primary:hover {
transform: translateY(-1px) scale(1.02);
box-shadow:
0 4px 12px ${theme.accent}40,
inset 0 1px 0 rgba(255, 255, 255, 0.25);
}
.btn-primary:active {
transform: translateY(0) scale(0.98);
transition: all 0.08s cubic-bezier(0.16, 1, 0.3, 1);
}
@media (max-width: 640px) {
.usage-banner {
width: calc(100vw - 24px);
}
.banner-content {
padding: 16px;
gap: 12px;
}
.banner-message {
font-size: 13px;
line-height: 1.45;
}
.btn-primary {
padding: 8px 14px;
font-size: 12px;
}
.close-btn {
width: 22px;
height: 22px;
font-size: 12px;
}
}
` }),
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "usage-banner", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "banner-content", children: [
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "banner-message", children: message }),
(actions == null ? void 0 : actions.primary) && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "btn-primary", onClick: actions.primary.onClick, children: actions.primary.label }),
onClose && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "close-btn", onClick: onClose, title: "Close", children: "\xD7" })
] }) })
] });
}
var getErrorActions = (error) => {
switch (error.code) {
case import_shared5.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR:
return {
primary: {
label: "Show me how",
onClick: () => window.open(
"https://docs.copilotkit.ai/premium#how-do-i-get-access-to-premium-features",
"_blank",
"noopener,noreferrer"
)
}
};
case import_shared5.CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR:
return {
primary: {
label: "Upgrade",
onClick: () => window.open("https://cloud.copilotkit.ai", "_blank", "noopener,noreferrer")
}
};
default:
return void 0;
}
};
// src/hooks/use-copilot-runtime-client.ts
var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
var import_react7 = require("react");
var import_shared6 = require("@copilotkit/shared");
var useCopilotRuntimeClient = (options) => {
const { setBannerError } = useToast();
const _a = options, { showDevConsole, onError } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onError"]);
const lastStructuredErrorRef = (0, import_react7.useRef)(null);
const traceUIError = (error, originalError) => __async(void 0, null, function* () {
if (!onError || !runtimeOptions.publicApiKey)
return;
try {
const errorEvent = {
type: "error",
timestamp: Date.now(),
context: {
source: "ui",
request: {
operation: "runtimeClient",
url: runtimeOptions.url,
startTime: Date.now()
},
technical: {
environment: "browser",
userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
stackTrace: originalError instanceof Error ? originalError.stack : void 0
}
},
error
};
yield onError(errorEvent);
} catch (error2) {
console.error("Error in onError handler:", error2);
}
});
const runtimeClient = (0, import_react7.useMemo)(() => {
return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, runtimeOptions), {
handleGQLErrors: (error) => {
var _a2;
if ((_a2 = error.graphQLErrors) == null ? void 0 : _a2.length) {
const graphQLErrors = error.graphQLErrors;
const routeError = (gqlError) => {
const extensions = gqlError.extensions;
const visibility = extensions == null ? void 0 : extensions.visibility;
const isDev = shouldShowDevConsole(showDevConsole != null ? showDevConsole : false);
if (visibility === import_shared6.ErrorVisibility.SILENT) {
console.error("CopilotKit Silent Error:", gqlError.message);
return;
}
if (!isDev) {
console.error("CopilotKit Error (hidden in production):", gqlError.message);
return;
}
const now = Date.now();
const errorMessage = gqlError.message;
if (lastStructuredErrorRef.current && lastStructuredErrorRef.current.message === errorMessage && now - lastStructuredErrorRef.current.timestamp < 150) {
return;
}
lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };
const ckError = createStructuredError(gqlError);
if (ckError) {
setBannerError(ckError);
traceUIError(ckError, gqlError);
} else {
const fallbackError = new import_shared6.CopilotKitError({
message: gqlError.message,
code: import_shared6.CopilotKitErrorCode.UNKNOWN
});
setBannerError(fallbackError);
traceUIError(fallbackError, gqlError);
}
};
graphQLErrors.forEach(routeError);
} else {
const isDev = shouldShowDevConsole(showDevConsole != null ? showDevConsole : false);
if (!isDev) {
console.error("CopilotKit Error (hidden in production):", error);
} else {
const fallbackError = new import_shared6.CopilotKitError({
message: (error == null ? void 0 : error.message) || String(error),
code: import_shared6.CopilotKitErrorCode.UNKNOWN
});
setBannerError(fallbackError);
traceUIError(fallbackError, error);
}
}
},
handleGQLWarning: (message) => {
console.warn(message);
const warningError = new import_shared6.CopilotKitError({
message,
code: import_shared6.CopilotKitErrorCode.UNKNOWN
});
setBannerError(warningError);
}
}));
}, [runtimeOptions, setBannerError, showDevConsole, onError]);
return runtimeClient;
};
function createStructuredError(gqlError) {
var _a, _b, _c;
const extensions = gqlError.extensions;
const originalError = extensions == null ? void 0 : extensions.originalError;
const message = (originalError == null ? void 0 : originalError.message) || gqlError.message;
const code = extensions == null ? void 0 : extensions.code;
if (code) {
return new import_shared6.CopilotKitError({ message, code });
}
if ((_a = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _a.includes("CopilotApiDiscoveryError")) {
return new import_shared6.CopilotKitApiDiscoveryError({ message });
}
if ((_b = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _b.includes("CopilotKitRemoteEndpointDiscoveryError")) {
return new import_shared6.CopilotKitRemoteEndpointDiscoveryError({ message });
}
if ((_c = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _c.includes("CopilotKitAgentDiscoveryError")) {
return new import_shared6.CopilotKitAgentDiscoveryError({
agentName: "",
availableAgents: []
});
}
return null;
}
// src/components/error-boundary/error-boundary.tsx
var import_react8 = __toESM(require("react"));
var import_shared8 = require("@copilotkit/shared");
// src/lib/status-checker.ts
var import_shared7 = require("@copilotkit/shared");
var STATUS_CHECK_INTERVAL = 1e3 * 60 * 5;
var StatusChecker = class {
constructor() {
this.activeKey = null;
this.intervalId = null;
this.instanceCount = 0;
this.lastResponse = null;
}
start(publicApiKey, onUpdate) {
return __async(this, null, function* () {
this.instanceCount++;
if (this.activeKey === publicApiKey)
return;
if (this.intervalId)
clearInterval(this.intervalId);
const checkStatus = () => __async(this, null, function* () {
try {
const response = yield fetch(`${import_shared7.COPILOT_CLOUD_API_URL}/ciu`, {
method: "GET",
headers: {
[import_shared7.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey
}
}).then((response2) => response2.json());
this.lastResponse = response;
onUpdate == null ? void 0 : onUpdate(response);
return response;
} catch (error) {
return null;
}
});
const initialResponse = yield checkStatus();
this.intervalId = setInterval(checkStatus, STATUS_CHECK_INTERVAL);
this.activeKey = publicApiKey;
return initialResponse;
});
}
getLastResponse() {
return this.lastResponse;
}
stop() {
this.instanceCount--;
if (this.instanceCount === 0) {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
this.activeKey = null;
this.lastResponse = null;
}
}
}
};
// src/components/error-boundary/error-boundary.tsx
var import_jsx_runtime4 = require("react/jsx-runtime");
var statusChecker = new StatusChecker();
var CopilotErrorBoundary = class extends import_react8.default.Component {
constructor(props) {
super(props);
this.state = {
hasError: false
};
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidMount() {
if (this.props.publicApiKey) {
statusChecker.start(this.props.publicApiKey, (newStatus) => {
this.setState((prevState) => {
var _a;
if ((newStatus == null ? void 0 : newStatus.severity) !== ((_a = prevState.status) == null ? void 0 : _a.severity)) {
return { status: newStatus != null ? newStatus : void 0 };
}
return null;
});
});
}
}
componentWillUnmount() {
statusChecker.stop();
}
componentDidCatch(error, errorInfo) {
console.error("CopilotKit Error:", error, errorInfo);
}
render() {
var _a, _b, _c, _d;
if (this.state.hasError) {
if (this.state.error instanceof import_shared8.CopilotKitError) {
return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
this.props.children,
this.props.showUsageBanner && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
UsageBanner,
{
severity: (_b = (_a = this.state.status) == null ? void 0 : _a.severity) != null ? _b : this.state.error.severity,
message: (_d = (_c = this.state.status) == null ? void 0 : _c.message) != null ? _d : this.state.error.message,
actions: getErrorActions(this.state.error)
}
)
] });
}
throw this.state.error;
}
return this.props.children;
}
};
// src/components/dev-console/console-trigger.tsx
var import_react10 = require("react");
// src/components/dev-console/icons.tsx
var import_jsx_runtime5 = require("react/jsx-runtime");
var ExclamationMarkTriangleIcon = () => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
"svg",
{
width: "13.3967723px",
height: "12px",
viewBox: "0 0 13.3967723 12",
version: "1.1",
xmlns: "http://www.w3.org/2000/svg",
children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("g", { id: "Page-1", stroke: "none", strokeWidth: "1", fill: "none", fillRule: "evenodd", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("g", { id: "exclamation-triangle", fill: "#CD2121", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
"path",
{
d: "M5.39935802,0.75 C5.97670802,-0.25 7.42007802,-0.25 7.99742802,0.75 L13.193588,9.75 C13.770888,10.75 13.049288,12 11.894588,12 L1.50223802,12 C0.34753802,12 -0.37414898,10.75 0.20319802,9.75 L5.39935802,0.75 Z M6.69838802,2.5 C7.11260802,2.5 7.44838802,2.83579 7.44838802,3.25 L7.44838802,6.25 C7.44838802,6.66421 7.11260802,7 6.69838802,7 C6.28417802,7 5.94838802,6.66421 5.94838802,6.25 L5.94838802,3.25 C5.94838802,2.83579 6.28417802,2.5 6.69838802,2.5 Z M6.69838802,10.5 C7.25067802,10.5 7.69838802,10.0523 7.69838802,9.5 C7.69838802,8.9477 7.25067802,8.5 6.69838802,8.5 C6.14610802,8.5 5.69838802,8.9477 5.69838802,9.5 C5.69838802,10.0523 6.14610802,10.5 6.69838802,10.5 Z",
id: "Shape"
}
) }) })
}
);
var CheckIcon = () => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
"svg",
{
width: "14px",
height: "14px",
viewBox: "0 0 14 14",
version: "1.1",
xmlns: "http://www.w3.org/2000/svg",
children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("g", { id: "Page-1", stroke: "none", strokeWidth: "1", fill: "none", fillRule: "evenodd", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("g", { id: "Group-2", transform: "translate(-118, 0)", fill: "#1BC030", fillRule: "nonzero", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("g", { id: "Group", transform: "translate(118, 0)", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
"path",