@copilotkit/react-core
Version:
<div align="center"> <a href="https://copilotkit.ai" target="_blank"> <img src="https://github.com/copilotkit/copilotkit/raw/main/assets/banner.png" alt="CopilotKit Logo"> </a>
1,472 lines (1,442 loc) • 107 kB
JavaScript
"use strict";
"use client";
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/index.tsx
var src_exports = {};
__export(src_exports, {
CopilotContext: () => CopilotContext,
CopilotKit: () => CopilotKit,
CopilotMessagesContext: () => CopilotMessagesContext,
CopilotTask: () => CopilotTask,
defaultCopilotContextCategories: () => defaultCopilotContextCategories,
extract: () => extract,
runAgent: () => runAgent,
shouldShowDevConsole: () => shouldShowDevConsole,
startAgent: () => startAgent,
stopAgent: () => stopAgent,
useCoAgent: () => useCoAgent,
useCoAgentStateRender: () => useCoAgentStateRender,
useCopilotAction: () => useCopilotAction,
useCopilotAdditionalInstructions: () => useCopilotAdditionalInstructions,
useCopilotAuthenticatedAction_c: () => useCopilotAuthenticatedAction_c,
useCopilotChat: () => useCopilotChat,
useCopilotContext: () => useCopilotContext,
useCopilotMessagesContext: () => useCopilotMessagesContext,
useCopilotReadable: () => useCopilotReadable,
useCopilotRuntimeClient: () => useCopilotRuntimeClient,
useLangGraphInterrupt: () => useLangGraphInterrupt,
useLangGraphInterruptRender: () => useLangGraphInterruptRender,
useMakeCopilotDocumentReadable: () => useMakeCopilotDocumentReadable
});
module.exports = __toCommonJS(src_exports);
// src/components/copilot-provider/copilotkit.tsx
var import_react10 = 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: () => {
},
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: "auto",
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
};
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 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 };
};
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_shared8 = 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_react5 = require("react");
// src/context/copilot-messages-context.tsx
var import_react4 = __toESM(require("react"));
var emptyCopilotContext2 = {
messages: [],
setMessages: () => []
};
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");
var import_jsx_runtime = require("react/jsx-runtime");
function CopilotMessages({ children }) {
const [messages, setMessages] = (0, import_react5.useState)([]);
const lastLoadedThreadId = (0, import_react5.useRef)();
const lastLoadedAgentName = (0, import_react5.useRef)();
const lastLoadedMessages = (0, import_react5.useRef)();
const { threadId, agentSession, runtimeClient } = useCopilotContext();
(0, import_react5.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
});
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]);
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
CopilotMessagesContext.Provider,
{
value: {
messages,
setMessages
},
children
}
);
}
// src/components/toast/toast-provider.tsx
var import_react7 = require("react");
// src/components/error-boundary/error-utils.tsx
var import_react6 = require("react");
// src/components/toast/exclamation-mark-icon.tsx
var import_jsx_runtime2 = require("react/jsx-runtime");
var ExclamationMarkIcon = ({
className,
style
}) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
"svg",
{
xmlns: "http://www.w3.org/2000/svg",
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
className: `lucide lucide-circle-alert ${className ? className : ""}`,
style,
children: [
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("circle", { cx: "12", cy: "12", r: "10" }),
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12", y1: "8", y2: "12" }),
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12.01", y1: "16", y2: "16" })
]
}
);
// src/components/error-boundary/error-utils.tsx
var import_react_markdown = __toESM(require("react-markdown"));
var import_jsx_runtime3 = require("react/jsx-runtime");
function ErrorToast({ errors }) {
const errorsToRender = errors.map((error, idx) => {
var _a, _b, _c;
const originalError = "extensions" in error ? (_a = error.extensions) == null ? void 0 : _a.originalError : {};
const message = (_b = originalError == null ? void 0 : originalError.message) != null ? _b : error.message;
const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
"div",
{
style: {
marginTop: idx === 0 ? 0 : 10,
marginBottom: 14
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
code && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
"div",
{
style: {
fontWeight: "600",
marginBottom: 4
},
children: [
"Copilot Cloud Error:",
" ",
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react_markdown.default, { children: message })
]
},
idx
);
});
return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
"div",
{
style: {
fontSize: "13px",
maxWidth: "600px"
},
children: [
errorsToRender,
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
]
}
);
}
function useErrorToast() {
const { addToast } = useToast();
return (0, import_react6.useCallback)(
(error) => {
const errorId = error.map((err) => {
var _a, _b;
const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
const stack = err.stack || "";
return btoa(message + stack).slice(0, 32);
}).join("|");
addToast({
type: "error",
id: errorId,
// Toast libraries typically dedupe by id
message: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ErrorToast, { errors: error })
});
},
[addToast]
);
}
function useAsyncCallback(callback, deps) {
const addErrorToast = useErrorToast();
return (0, import_react6.useCallback)((...args) => __async(this, null, function* () {
try {
return yield callback(...args);
} catch (error) {
console.error("Error in async callback:", error);
addErrorToast([error]);
throw error;
}
}), deps);
}
// src/components/toast/toast-provider.tsx
var import_jsx_runtime4 = require("react/jsx-runtime");
var ToastContext = (0, import_react7.createContext)(void 0);
function useToast() {
const context = (0, import_react7.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_react7.useState)([]);
const addToast = (0, import_react7.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]
);
const addGraphQLErrorsToast = (0, import_react7.useCallback)((errors) => {
addToast({
type: "error",
message: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ErrorToast, { errors })
});
}, []);
const removeToast = (0, import_react7.useCallback)((id) => {
setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));
}, []);
const value = {
toasts,
addToast,
addGraphQLErrorsToast,
removeToast,
enabled
};
return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(ToastContext.Provider, { value, children: [
/* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
"div",
{
style: {
position: "fixed",
bottom: "1rem",
left: "50%",
transform: "translateX(-50%)",
zIndex: 50,
display: "flex",
flexDirection: "column",
gap: "0.5rem"
},
children: [
toasts.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { textAlign: "right" }, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
"button",
{
onClick: () => setToasts([]),
style: {
padding: "4px 8px",
fontSize: "12px",
cursor: "pointer",
background: "white",
border: "1px solid rgba(0,0,0,0.2)",
borderRadius: "4px"
},
children: "Close All"
}
) }),
toasts.map((toast) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
Toast,
{
message: toast.message,
type: toast.type,
onClose: () => removeToast(toast.id)
},
toast.id
))
]
}
),
children
] });
}
function Toast({
message,
type = "info",
onClose
}) {
const bgColors = {
info: "#3b82f6",
success: "#22c55e",
warning: "#eab308",
error: "#ef4444"
};
return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
"div",
{
style: {
backgroundColor: bgColors[type],
color: "white",
padding: "0.5rem 1.5rem",
borderRadius: "0.25rem",
boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
position: "relative",
minWidth: "200px"
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: message }),
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
"button",
{
onClick: onClose,
style: {
position: "absolute",
top: "0",
right: "0",
background: "none",
border: "none",
color: "white",
cursor: "pointer",
padding: "0.5rem",
fontSize: "1rem"
},
children: "\u2715"
}
)
]
}
);
}
// src/hooks/use-copilot-runtime-client.ts
var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
var import_react8 = require("react");
var useCopilotRuntimeClient = (options) => {
const { addGraphQLErrorsToast } = useToast();
const addErrorToast = useErrorToast();
const { addToast } = useToast();
const runtimeClient = (0, import_react8.useMemo)(() => {
return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, options), {
handleGQLErrors: (error) => {
if (error.graphQLErrors.length) {
addGraphQLErrorsToast(error.graphQLErrors);
} else {
addErrorToast([error]);
}
},
handleGQLWarning: (message) => {
console.warn(message);
addToast({ type: "warning", message });
}
}));
}, [options, addGraphQLErrorsToast, addToast]);
return runtimeClient;
};
// src/utils/extract.ts
var import_shared3 = require("@copilotkit/shared");
var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
function extract(_0) {
return __async(this, arguments, function* ({
context,
instructions,
parameters,
include,
data,
abortSignal,
stream,
requestType = import_runtime_client_gql3.CopilotRequestType.Task,
forwardedParameters
}) {
var _a, _b;
const { messages } = context;
const action = {
name: "extract",
description: instructions,
parameters,
handler: (args) => {
}
};
const includeReadable = (_a = include == null ? void 0 : include.readable) != null ? _a : false;
const includeMessages = (_b = include == null ? void 0 : include.messages) != null ? _b : false;
let contextString = "";
if (data) {
contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
}
if (includeReadable) {
contextString += context.getContextString([], defaultCopilotContextCategories);
}
const systemMessage = new import_runtime_client_gql3.TextMessage({
content: makeSystemMessage(contextString, instructions),
role: import_runtime_client_gql3.Role.System
});
const instructionsMessage = new import_runtime_client_gql3.TextMessage({
content: makeInstructionsMessage(instructions),
role: import_runtime_client_gql3.Role.User
});
const response = context.runtimeClient.asStream(
context.runtimeClient.generateCopilotResponse({
data: {
frontend: {
actions: [
{
name: action.name,
description: action.description || "",
jsonSchema: JSON.stringify((0, import_shared3.actionParametersToJsonSchema)(action.parameters || []))
}
],
url: window.location.href
},
messages: (0, import_runtime_client_gql4.convertMessagesToGqlInput)(
includeMessages ? [systemMessage, instructionsMessage, ...(0, import_runtime_client_gql4.filterAgentStateMessages)(messages)] : [systemMessage, instructionsMessage]
),
metadata: {
requestType
},
forwardedParameters: __spreadProps(__spreadValues({}, forwardedParameters != null ? forwardedParameters : {}), {
toolChoice: "function",
toolChoiceFunctionName: action.name
})
},
properties: context.copilotApiConfig.properties,
signal: abortSignal
})
);
const reader = response.getReader();
let isInitial = true;
let actionExecutionMessage = void 0;
while (true) {
const { done, value } = yield reader.read();
if (done) {
break;
}
if (abortSignal == null ? void 0 : abortSignal.aborted) {
throw new Error("Aborted");
}
actionExecutionMessage = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
value.generateCopilotResponse.messages
).find((msg) => msg.isActionExecutionMessage());
if (!actionExecutionMessage) {
continue;
}
stream == null ? void 0 : stream({
status: isInitial ? "initial" : "inProgress",
args: actionExecutionMessage.arguments
});
isInitial = false;
}
if (!actionExecutionMessage) {
throw new Error("extract() failed: No function call occurred");
}
stream == null ? void 0 : stream({
status: "complete",
args: actionExecutionMessage.arguments
});
return actionExecutionMessage.arguments;
});
}
function makeInstructionsMessage(instructions) {
return `
The user has given you the following task to complete:
\`\`\`
${instructions}
\`\`\`
Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
`;
}
function makeSystemMessage(contextString, instructions) {
return `
Please act as an efficient, competent, conscientious, and industrious professional assistant.
Help the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.
Always be polite and respectful, and prefer brevity over verbosity.
The user has provided you with the following context:
\`\`\`
${contextString}
\`\`\`
They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
Please assist them as best you can.
This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
`;
}
// src/utils/dev-console.ts
function shouldShowDevConsole(showDevConsole) {
if (typeof showDevConsole === "boolean") {
return showDevConsole;
}
return getHostname() === "localhost" || getHostname() === "127.0.0.1" || getHostname() === "0.0.0.0" || getHostname() === "::1";
}
function getHostname() {
if (typeof window !== "undefined" && window.location) {
return window.location.hostname;
}
return "";
}
// src/components/error-boundary/error-boundary.tsx
var import_react9 = __toESM(require("react"));
var import_shared6 = require("@copilotkit/shared");
// src/lib/status-checker.ts
var import_shared4 = 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_shared4.COPILOT_CLOUD_API_URL}/ciu`, {
method: "GET",
headers: {
[import_shared4.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/usage-banner.tsx
var import_shared5 = require("@copilotkit/shared");
var import_jsx_runtime5 = require("react/jsx-runtime");
var defaultIcons = {
[import_shared5.Severity.Error]: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
"svg",
{
viewBox: "0 0 24 24",
width: "20",
height: "20",
stroke: "currentColor",
strokeWidth: "2",
fill: "none",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [
/* @__PURE__ */ (0, import_jsx_runtime5.jsx)("circle", { cx: "12", cy: "12", r: "10" }),
/* @__PURE__ */ (0, import_jsx_runtime5.jsx)("line", { x1: "15", y1: "9", x2: "9", y2: "15" }),
/* @__PURE__ */ (0, import_jsx_runtime5.jsx)("line", { x1: "9", y1: "9", x2: "15", y2: "15" })
]
}
)
};
function UsageBanner({
severity = import_shared5.Severity.Error,
message = "",
icon,
actions
}) {
if (!message || !severity) {
return null;
}
const Icon = icon || defaultIcons[severity];
const bgColor = {
info: "#dbeafe",
warning: "#fef3c7",
error: "#fee2e2"
}[severity];
const textColor = {
info: "#1e40af",
warning: "#854d0e",
error: "#991b1b"
}[severity];
const iconColor = {
info: "#3b82f6",
warning: "#eab308",
error: "#ef4444"
}[severity];
const primaryButtonColor = {
info: "#3b82f6",
warning: "#eab308",
error: "#ef4444"
}[severity];
const primaryButtonHoverColor = {
info: "#2563eb",
warning: "#ca8a04",
error: "#dc2626"
}[severity];
return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
"div",
{
style: {
position: "fixed",
bottom: "16px",
left: "50%",
transform: "translateX(-50%)",
maxWidth: "90%",
zIndex: 9999
},
children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
"div",
{
style: {
display: "flex",
flexWrap: "wrap",
alignItems: "center",
gap: "12px",
borderRadius: "9999px",
border: "1px solid #e5e7eb",
backgroundColor: bgColor,
padding: "8px 16px",
boxShadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1)"
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: { color: iconColor }, children: Icon }),
/* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
"span",
{
style: {
flex: 1,
fontSize: "14px",
fontWeight: 500,
color: textColor,
whiteSpace: "normal",
wordBreak: "break-word"
},
children: message
}
),
/* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
"div",
{
style: {
display: "flex",
gap: "8px",
flexWrap: "wrap"
},
children: [
(actions == null ? void 0 : actions.secondary) && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
"button",
{
onClick: actions.secondary.onClick,
style: {
borderRadius: "9999px",
padding: "4px 12px",
fontSize: "14px",
fontWeight: 500,
color: textColor,
backgroundColor: "transparent",
border: "none",
cursor: "pointer",
transition: "background-color 0.2s"
},
onMouseOver: (e) => e.currentTarget.style.backgroundColor = "rgba(255,255,255,0.5)",
onMouseOut: (e) => e.currentTarget.style.backgroundColor = "transparent",
children: actions.secondary.label
}
),
(actions == null ? void 0 : actions.primary) && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
"button",
{
onClick: actions.primary.onClick,
style: {
borderRadius: "9999px",
padding: "4px 12px",
fontSize: "14px",
fontWeight: 500,
color: "#fff",
backgroundColor: primaryButtonColor,
border: "none",
cursor: "pointer",
transition: "background-color 0.2s"
},
onMouseOver: (e) => e.currentTarget.style.backgroundColor = primaryButtonHoverColor,
onMouseOut: (e) => e.currentTarget.style.backgroundColor = primaryButtonColor,
children: actions.primary.label
}
)
]
}
)
]
}
)
}
);
}
function renderCopilotKitUsage(error) {
switch (error.name) {
case import_shared5.ERROR_NAMES.CONFIGURATION_ERROR:
return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(UsageBanner, { severity: error.severity, message: error.message });
case import_shared5.ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR:
return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
UsageBanner,
{
severity: error.severity,
message: error.message,
actions: {
primary: {
label: "Sign In",
onClick: () => {
window.location.href = "https://cloud.copilotkit.ai";
}
}
}
}
);
case import_shared5.ERROR_NAMES.UPGRADE_REQUIRED_ERROR:
return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
UsageBanner,
{
severity: error.severity,
message: error.message,
actions: {
primary: {
label: "Upgrade",
onClick: () => {
window.location.href = "https://copilotkit.ai/";
}
}
}
}
);
}
}
// src/components/error-boundary/error-boundary.tsx
var import_shared7 = require("@copilotkit/shared");
var import_jsx_runtime6 = require("react/jsx-runtime");
var statusChecker = new StatusChecker();
var CopilotErrorBoundary = class extends import_react9.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;
if (this.state.hasError) {
if (this.state.error instanceof import_shared6.CopilotKitError) {
if (import_shared7.COPILOT_CLOUD_ERROR_NAMES.includes(this.state.error.name)) {
return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ErrorToast2, { error: this.state.error, children: renderCopilotKitUsage(this.state.error) });
}
return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_jsx_runtime6.Fragment, { children: [
this.props.children,
this.props.showUsageBanner && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
UsageBanner,
{
severity: (_a = this.state.status) == null ? void 0 : _a.severity,
message: (_b = this.state.status) == null ? void 0 : _b.message
}
)
] });
}
throw this.state.error;
}
return this.props.children;
}
};
function ErrorToast2({ error, children }) {
const addErrorToast = useErrorToast();
(0, import_react9.useEffect)(() => {
if (error) {
addErrorToast([error]);
}
}, [error, addErrorToast]);
if (!error)
throw error;
return children;
}
// src/components/copilot-provider/copilotkit.tsx
var import_jsx_runtime7 = require("react/jsx-runtime");
function CopilotKit(_a) {
var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
const showDevConsole = props.showDevConsole === void 0 ? "auto" : props.showDevConsole;
const enabled = shouldShowDevConsole(showDevConsole);
return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(ToastProvider, { enabled, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(CopilotErrorBoundary, { publicApiKey: props.publicApiKey, showUsageBanner: enabled, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children })) }) });
}
function CopilotKitInternal(cpkProps) {
const _a = cpkProps, { children } = _a, props = __objRest(_a, ["children"]);
validateProps(cpkProps);
const chatApiEndpoint = props.runtimeUrl || import_shared8.COPILOT_CLOUD_CHAT_URL;
const [actions, setActions] = (0, import_react10.useState)({});
const [coAgentStateRenders, setCoAgentStateRenders] = (0, import_react10.useState)({});
const chatComponentsCache = (0, import_react10.useRef)({
actions: {},
coAgentStateRenders: {}
});
const { addElement, removeElement, printTree } = use_tree_default();
const [isLoading, setIsLoading] = (0, import_react10.useState)(false);
const [chatInstructions, setChatInstructions] = (0, import_react10.useState)("");
const [authStates, setAuthStates] = (0, import_react10.useState)({});
const [extensions, setExtensions] = (0, import_react10.useState)({});
const [additionalInstructions, setAdditionalInstructions] = (0, import_react10.useState)([]);
const {
addElement: addDocument,
removeElement: removeDocument,
allElements: allDocuments
} = use_flat_category_store_default();
const setAction = (0, import_react10.useCallback)((id, action) => {
setActions((prevPoints) => {
return __spreadProps(__spreadValues({}, prevPoints), {
[id]: action
});
});
}, []);
const removeAction = (0, import_react10.useCallback)((id) => {
setActions((prevPoints) => {
const newPoints = __spreadValues({}, prevPoints);
delete newPoints[id];
return newPoints;
});
}, []);
const setCoAgentStateRender = (0, import_react10.useCallback)((id, stateRender) => {
setCoAgentStateRenders((prevPoints) => {
return __spreadProps(__spreadValues({}, prevPoints), {
[id]: stateRender
});
});
}, []);
const removeCoAgentStateRender = (0, import_react10.useCallback)((id) => {
setCoAgentStateRenders((prevPoints) => {
const newPoints = __spreadValues({}, prevPoints);
delete newPoints[id];
return newPoints;
});
}, []);
const getContextString = (0, import_react10.useCallback)(
(documents, categories) => {
const documentsString = documents.map((document) => {
return `${document.name} (${document.sourceApplication}):
${document.getContents()}`;
}).join("\n\n");
const nonDocumentStrings = printTree(categories);
return `${documentsString}
${nonDocumentStrings}`;
},
[printTree]
);
const addContext = (0, import_react10.useCallback)(
(context, parentId, categories = defaultCopilotContextCategories) => {
return addElement(context, categories, parentId);
},
[addElement]
);
const removeContext = (0, import_react10.useCallback)(
(id) => {
removeElement(id);
},
[removeElement]
);
const getFunctionCallHandler = (0, import_react10.useCallback)(
(customEntryPoints) => {
return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
},
[actions]
);
const getDocumentsContext = (0, import_react10.useCallback)(
(categories) => {
return allDocuments(categories);
},
[allDocuments]
);
const addDocumentContext = (0, import_react10.useCallback)(
(documentPointer, categories = defaultCopilotContextCategories) => {
return addDocument(documentPointer, categories);
},
[addDocument]
);
const removeDocumentContext = (0, import_react10.useCallback)(
(documentId) => {
removeDocument(documentId);
},
[removeDocument]
);
const copilotApiConfig = (0, import_react10.useMemo)(() => {
var _a2, _b;
let cloud = void 0;
if (props.publicApiKey) {
cloud = {
guardrails: {
input: {
restrictToTopic: {
enabled: Boolean(props.guardrails_c),
validTopics: ((_a2 = props.guardrails_c) == null ? void 0 : _a2.validTopics) || [],
invalidTopics: ((_b = props.guardrails_c) == null ? void 0 : _b.invalidTopics) || []
}
}
}
};
}
return __spreadProps(__spreadValues({
publicApiKey: props.publicApiKey
}, cloud ? { cloud } : {}), {
chatApiEndpoint,
headers: props.headers || {},
properties: props.properties || {},
transcribeAudioUrl: props.transcribeAudioUrl,
textToSpeechUrl: props.textToSpeechUrl,
credentials: props.credentials
});
}, [
props.publicApiKey,
props.headers,
props.properties,
props.transcribeAudioUrl,
props.textToSpeechUrl,
props.credentials,
props.cloudRestrictToTopic
]);
const headers = (0, import_react10.useMemo)(() => {
const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {
if (state.status === "authenticated" && state.authHeaders) {
return __spreadValues(__spreadValues({}, acc), Object.entries(state.authHeaders).reduce(
(headers2, [key, value]) => __spreadProps(__spreadValues({}, headers2), {
[key.startsWith("X-Custom-") ? key : `X-Custom-${key}`]: value
}),
{}
));
}
return acc;
}, {});
return __spreadValues(__spreadValues(__spreadValues({}, copilotApiConfig.headers || {}), copilotApiConfig.publicApiKey ? { [import_shared8.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {}), authHeaders);
}, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);
const runtimeClient = useCopilotRuntimeClient({
url: copilotApiConfig.chatApiEndpoint,
publicApiKey: copilotApiConfig.publicApiKey,
headers,
credentials: copilotApiConfig.credentials
});
const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, import_react10.useState)({});
const addChatSuggestionConfiguration = (id, suggestion) => {
setChatSuggestionConfiguration((prev) => __spreadProps(__spreadValues({}, prev), { [id]: suggestion }));
};
const removeChatSuggestionConfiguration = (id) => {
setChatSuggestionConfiguration((prev) => {
const _a2 = prev, { [id]: _ } = _a2, rest = __objRest(_a2, [__restKey(id)]);
return rest;
});
};
const [availableAgents, setAvailableAgents] = (0, import_react10.useState)([]);
const [coagentStates, setCoagentStates] = (0, import_react10.useState)({});
const coagentStatesRef = (0, import_react10.useRef)({});
const setCoagentStatesWithRef = (0, import_react10.useCallback)(
(value) => {
const newValue = typeof value === "function" ? value(coagentStatesRef.current) : value;
coagentStatesRef.current = newValue;
setCoagentStates((prev) => {
return newValue;
});
},
[]
);
const hasLoadedAgents = (0, import_react10.useRef)(false);
(0, import_react10.useEffect)(() => {
if (hasLoadedAgents.current)
return;
const fetchData = () => __async(this, null, function* () {
var _a2;
const result = yield runtimeClient.availableAgents();
if ((_a2 = result.data) == null ? void 0 : _a2.availableAgents) {
setAvailableAgents(result.data.availableAgents.agents);
}
hasLoadedAgents.current = true;
});
void fetchData();
}, []);
let initialAgentSession = null;
if (props.agent) {
initialAgentSession = {
agentName: props.agent
};
}
const [agentSession, setAgentSession] = (0, import_react10.useState)(initialAgentSession);
(0, import_react10.useEffect)(() => {
if (props.agent) {
setAgentSession({
agentName: props.agent
});
} else {
setAgentSession(null);
}
}, [props.agent]);
const [internalThreadId, setInternalThreadId] = (0, import_react10.useState)(props.threadId || (0, import_shared8.randomUUID)());
const setThreadId = (0, import_react10.useCallback)(
(value) => {
if (props.threadId) {
throw new Error("Cannot call setThreadId() when threadId is provided via props.");
}
setInternalThreadId(value);
},
[props.threadId]
);
(0, import_react10.useEffect)(() => {
if (props.threadId !== void 0) {
setInternalThreadId(props.threadId);
}
}, [props.threadId]);
const [runId, setRunId] = (0, import_react10.useState)(null);
const chatAbortControllerRef = (0, import_react10.useRef)(null);
const showDevConsole = props.showDevConsole === void 0 ? "auto" : props.showDevConsole;
const [langGraphInterruptAction, _setLangGraphInterruptAction] = (0, import_react10.useState)(null);
const setLangGraphInterruptAction = (0, import_react10.useCallback)((action) => {
_setLangGraphInterruptAction((prev) => {
if (prev == null)
return action;
if (action == null)
return null;
let event = prev.event;
if (action.event) {
event = __spreadValues(__spreadValues({}, prev.event), action.event);
}
return __spreadProps(__spreadValues(__spreadValues({}, prev), action), { event });
});
}, []);
const removeLangGraphInterruptAction = (0, import_react10.useCallback)(() => {
setLangGr