rdesign/frontend/node_modules/@copilotkit/react-ui/dist/index.mjs

2688 lines
89 KiB
JavaScript

"use client";
import * as React$1 from "react";
import React, { forwardRef, memo, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { defaultCopilotContextCategories, shouldShowDevConsole, useCopilotChatInternal, useCopilotChatSuggestions as useCopilotChatSuggestions$1, useCopilotContext, useCopilotMessagesContext } from "@copilotkit/react-core";
import { COPILOTKIT_VERSION, CopilotKitError, CopilotKitErrorCode, ErrorVisibility, Severity, isMacOS, randomUUID, styledConsole } from "@copilotkit/shared";
import { Menu, MenuButton, MenuItem, MenuItems } from "@headlessui/react";
import ReactMarkdown from "react-markdown";
import { Light, Prism } from "react-syntax-highlighter";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import rehypeRaw from "rehype-raw";
import { aguiToGQL, gqlToAGUI } from "@copilotkit/runtime-client-gql";
//#region src/components/chat/Icons.tsx
const OpenIcon = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
fill: "currentColor",
width: "24",
height: "24",
children: /* @__PURE__ */ jsx("g", {
transform: "translate(24, 0) scale(-1, 1)",
children: /* @__PURE__ */ jsx("path", {
fillRule: "evenodd",
d: "M5.337 21.718a6.707 6.707 0 01-.533-.074.75.75 0 01-.44-1.223 3.73 3.73 0 00.814-1.686c.023-.115-.022-.317-.254-.543C3.274 16.587 2.25 14.41 2.25 12c0-5.03 4.428-9 9.75-9s9.75 3.97 9.75 9c0 5.03-4.428 9-9.75 9-.833 0-1.643-.097-2.417-.279a6.721 6.721 0 01-4.246.997z",
clipRule: "evenodd"
})
})
});
const CloseIcon$1 = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "1.5",
stroke: "currentColor",
width: "24",
height: "24",
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M19.5 8.25l-7.5 7.5-7.5-7.5"
})
});
const HeaderCloseIcon = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "1.5",
stroke: "currentColor",
width: "24",
height: "24",
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M6 18L18 6M6 6l12 12"
})
});
const SendIcon = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "1.5",
stroke: "currentColor",
width: "24",
height: "24",
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M12 19V5m0 0l-7 7m7-7l7 7"
})
});
const MicrophoneIcon = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "1.5",
stroke: "currentColor",
width: "24",
height: "24",
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M12 18.75a6 6 0 006-6v-1.5m-6 7.5a6 6 0 01-6-6v-1.5m6 7.5v3.75m-3.75 0h7.5M12 15.75a3 3 0 01-3-3V4.5a3 3 0 116 0v8.25a3 3 0 01-3 3z"
})
});
const StopIcon = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "1.5",
stroke: "currentColor",
width: "24",
height: "24",
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M5.25 7.5A2.25 2.25 0 017.5 5.25h9a2.25 2.25 0 012.25 2.25v9a2.25 2.25 0 01-2.25 2.25h-9a2.25 2.25 0 01-2.25-2.25v-9z"
})
});
const RegenerateIcon = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "2",
stroke: "currentColor",
width: "16",
height: "16",
style: {
minWidth: "16px",
minHeight: "16px"
},
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"
})
});
const CopyIcon = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "2",
stroke: "currentColor",
width: "16",
height: "16",
style: {
minWidth: "16px",
minHeight: "16px"
},
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 01-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 011.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 00-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 01-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 00-3.375-3.375h-1.5a1.125 1.125 0 01-1.125-1.125v-1.5a3.375 3.375 0 00-3.375-3.375H9.75"
})
});
const SmallSpinnerIcon = /* @__PURE__ */ jsx("span", {
className: "copilotKitSpinner",
style: {
width: "13px",
height: "13px"
}
});
const SpinnerIcon = /* @__PURE__ */ jsx("span", {
className: "copilotKitSpinner",
style: {
width: "24px",
height: "24px"
}
});
const ActivityIcon = /* @__PURE__ */ jsxs("div", {
style: {
display: "flex",
alignItems: "center",
gap: "4px"
},
children: [
/* @__PURE__ */ jsx("span", {
className: "copilotKitActivityDot",
style: { animationDelay: "0s" }
}),
/* @__PURE__ */ jsx("span", {
className: "copilotKitActivityDot",
style: { animationDelay: "0.2s" }
}),
/* @__PURE__ */ jsx("span", {
className: "copilotKitActivityDot",
style: { animationDelay: "0.4s" }
})
]
});
const ThumbsUpIcon = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "2",
stroke: "currentColor",
width: "16",
height: "16",
style: {
minWidth: "16px",
minHeight: "16px"
},
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M6.633 10.5c.806 0 1.533-.446 2.031-1.08a9.041 9.041 0 012.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 00.322-1.672V3a.75.75 0 01.75-.75A2.25 2.25 0 0116.5 4.5c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 01-2.649 7.521c-.388.482-.987.729-1.605.729H13.48c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 00-1.423-.23H5.904M14.25 9h2.25M5.904 18.75c.083.205.173.405.27.602.197.4-.078.898-.523.898h-.908c-.889 0-1.713-.518-1.972-1.368a12 12 0 01-.521-3.507c0-1.553.295-3.036.831-4.398C3.387 10.203 4.167 9.75 5 9.75h1.053c.472 0 .745.556.5.96a8.958 8.958 0 00-1.302 4.665c0 1.194.232 2.333.654 3.375z"
})
});
const ThumbsDownIcon = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "2",
stroke: "currentColor",
width: "16",
height: "16",
style: {
minWidth: "16px",
minHeight: "16px"
},
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M7.5 15h2.25m8.024-9.75c.011.05.028.1.052.148.591 1.2.924 2.55.924 3.977a8.96 8.96 0 01-.999 4.125m.023-8.25c-.076-.365.183-.75.575-.75h.908c.889 0 1.713.518 1.972 1.368.339 1.11.521 2.287.521 3.507 0 1.553-.295 3.036-.831 4.398C20.613 14.547 19.833 15 19 15h-1.053c-.472 0-.745-.556-.5-.96a8.95 8.95 0 00.303-.54m.023-8.25H16.48a4.5 4.5 0 01-1.423-.23l-3.114-1.04a4.5 4.5 0 00-1.423-.23H6.504c-.618 0-1.217.247-1.605.729A11.95 11.95 0 002.25 12c0 .434.023.863.068 1.285C2.427 14.306 3.346 15 4.372 15h3.126c.618 0 .991.724.725 1.282A7.471 7.471 0 007.5 19.5a2.25 2.25 0 002.25 2.25.75.75 0 00.75-.75v-.633c0-.573.11-1.14.322-1.672.304-.76.93-1.33 1.653-1.715a9.04 9.04 0 002.86-2.4c.498-.634 1.226-1.08 2.032-1.08h.384"
})
});
const DownloadIcon = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "2",
stroke: "currentColor",
width: "16",
height: "16",
style: {
minWidth: "16px",
minHeight: "16px"
},
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"
})
});
const UploadIcon = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "1.5",
stroke: "currentColor",
width: "24",
height: "24",
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M12 4.5v15m7.5-7.5h-15"
})
});
const CheckIcon$1 = /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "2",
stroke: "currentColor",
width: "16",
height: "16",
style: {
minWidth: "16px",
minHeight: "16px"
},
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M4.5 12.75l6 6 9-13.5"
})
});
//#endregion
//#region src/components/chat/ChatContext.tsx
const ChatContext = React.createContext(void 0);
function useChatContext() {
const context = React.useContext(ChatContext);
if (context === void 0) throw new Error("Context not found. Did you forget to wrap your app in a <ChatContextProvider> component?");
return context;
}
const ChatContextProvider = ({ labels, icons, children, open, setOpen }) => {
const memoizedLabels = useMemo(() => ({
initial: "",
title: "CopilotKit",
placeholder: "Type a message...",
error: "❌ An error occurred. Please try again.",
stopGenerating: "Stop generating",
regenerateResponse: "Regenerate response",
copyToClipboard: "Copy to clipboard",
thumbsUp: "Thumbs up",
thumbsDown: "Thumbs down",
copied: "Copied!",
...labels
}), [labels]);
const memoizedIcons = useMemo(() => ({
openIcon: OpenIcon,
closeIcon: CloseIcon$1,
headerCloseIcon: HeaderCloseIcon,
sendIcon: SendIcon,
activityIcon: ActivityIcon,
spinnerIcon: SpinnerIcon,
stopIcon: StopIcon,
regenerateIcon: RegenerateIcon,
pushToTalkIcon: MicrophoneIcon,
copyIcon: CopyIcon,
thumbsUpIcon: ThumbsUpIcon,
thumbsDownIcon: ThumbsDownIcon,
uploadIcon: UploadIcon,
...icons
}), [icons]);
const context = useMemo(() => ({
labels: memoizedLabels,
icons: memoizedIcons,
open,
setOpen
}), [
memoizedLabels,
memoizedIcons,
open,
setOpen
]);
return /* @__PURE__ */ jsx(ChatContext.Provider, {
value: context,
children
});
};
//#endregion
//#region src/components/chat/Window.tsx
const Window = ({ children, clickOutsideToClose, shortcut, hitEscapeToClose }) => {
const windowRef = React.useRef(null);
useCopilotContext();
const { open, setOpen } = useChatContext();
const handleClickOutside = useCallback((event) => {
if (!clickOutsideToClose) return;
const parentElement = windowRef.current?.parentElement;
let className = "";
if (event.target instanceof HTMLElement) className = event.target.className;
if (open && parentElement && !parentElement.contains(event.target) && !className.includes("copilotKitDebugMenu")) setOpen(false);
}, [
clickOutsideToClose,
open,
setOpen
]);
const handleKeyDown = useCallback((event) => {
const target = event.target;
const isInput = target.tagName === "INPUT" || target.tagName === "SELECT" || target.tagName === "TEXTAREA" || target.isContentEditable;
const isDescendantOfWrapper = windowRef.current?.contains(target);
if (open && event.key === "Escape" && (!isInput || isDescendantOfWrapper) && hitEscapeToClose) setOpen(false);
else if (event.key === shortcut && (isMacOS() && event.metaKey || !isMacOS() && event.ctrlKey) && (!isInput || isDescendantOfWrapper)) setOpen(!open);
}, [
hitEscapeToClose,
shortcut,
open,
setOpen
]);
const adjustForMobile = useCallback(() => {
const copilotKitWindow = windowRef.current;
const vv = window.visualViewport;
if (!copilotKitWindow || !vv) return;
if (window.innerWidth < 640 && open) {
copilotKitWindow.style.height = `${vv.height}px`;
copilotKitWindow.style.left = `${vv.offsetLeft}px`;
copilotKitWindow.style.top = `${vv.offsetTop}px`;
document.body.style.position = "fixed";
document.body.style.width = "100%";
document.body.style.height = `${window.innerHeight}px`;
document.body.style.overflow = "hidden";
document.body.style.touchAction = "none";
document.body.addEventListener("touchmove", preventScroll, { passive: false });
} else {
copilotKitWindow.style.height = "";
copilotKitWindow.style.left = "";
copilotKitWindow.style.top = "";
document.body.style.position = "";
document.body.style.height = "";
document.body.style.width = "";
document.body.style.overflow = "";
document.body.style.top = "";
document.body.style.touchAction = "";
document.body.removeEventListener("touchmove", preventScroll);
}
}, [open]);
useEffect(() => {
document.addEventListener("mousedown", handleClickOutside);
document.addEventListener("keydown", handleKeyDown);
if (window.visualViewport) {
window.visualViewport.addEventListener("resize", adjustForMobile);
adjustForMobile();
}
return () => {
document.removeEventListener("mousedown", handleClickOutside);
document.removeEventListener("keydown", handleKeyDown);
if (window.visualViewport) window.visualViewport.removeEventListener("resize", adjustForMobile);
};
}, [
adjustForMobile,
handleClickOutside,
handleKeyDown
]);
return /* @__PURE__ */ jsx("div", {
className: `copilotKitWindow ${open ? " open" : ""}`,
ref: windowRef,
children
});
};
const preventScroll = (event) => {
let targetElement = event.target;
const hasParentWithClass = (element, className) => {
while (element && element !== document.body) {
if (element.classList.contains(className)) return true;
element = element.parentElement;
}
return false;
};
if (!hasParentWithClass(targetElement, "copilotKitMessages")) event.preventDefault();
};
//#endregion
//#region src/components/chat/Button.tsx
const Button = ({}) => {
const { open, setOpen, icons } = useChatContext();
return /* @__PURE__ */ jsx("div", {
onClick: () => setOpen(!open),
children: /* @__PURE__ */ jsxs("button", {
className: `copilotKitButton ${open ? "open" : ""}`,
"aria-label": open ? "Close Chat" : "Open Chat",
children: [/* @__PURE__ */ jsx("div", {
className: "copilotKitButtonIcon copilotKitButtonIconOpen",
children: icons.openIcon
}), /* @__PURE__ */ jsx("div", {
className: "copilotKitButtonIcon copilotKitButtonIconClose",
children: icons.closeIcon
})]
})
});
};
//#endregion
//#region src/components/dev-console/utils.ts
async function getPublishedCopilotKitVersion(current, forceCheck = false) {
const LOCAL_STORAGE_KEY = "__copilotkit_version_check__";
const serializedVersion = localStorage.getItem(LOCAL_STORAGE_KEY);
if (serializedVersion && !forceCheck) try {
const parsedVersion = JSON.parse(serializedVersion);
const oneHour = 3600 * 1e3;
const now = (/* @__PURE__ */ new Date()).getTime();
if (parsedVersion.current === current && now - new Date(parsedVersion.lastChecked).getTime() < oneHour) return parsedVersion;
} catch (error) {
console.error("Failed to parse CopilotKitVersion from localStorage", error);
}
try {
const data = await (await fetch("https://api.cloud.copilotkit.ai/check-for-updates", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ packages: [{
packageName: "@copilotkit/shared",
packageVersion: current
}] })
})).json();
const version = {
current,
lastChecked: (/* @__PURE__ */ new Date()).getTime(),
latest: data.packages[0].latestVersion,
severity: data.packages[0].severity,
advisory: data.packages[0].advisory || null
};
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(version));
return version;
} catch (error) {
console.error("Failed to check for updates", error);
throw error;
}
}
function logReadables(context) {
console.log("%cCurrent Readables:", "font-size: 16px; font-weight: bold;");
const readables = context.getContextString([], defaultCopilotContextCategories).trim();
if (readables.length === 0) {
console.log("No readables found");
return;
}
console.log(readables);
}
function logActions(context) {
console.log("%cCurrent Actions:", "font-size: 16px; font-weight: bold;");
if (Object.values(context.actions).length === 0) {
console.log("No actions found");
return;
}
for (const action of Object.values(context.actions)) {
console.group(action.name);
console.log("name", action.name);
console.log("description", action.description);
console.log("parameters", action.parameters);
console.groupEnd();
}
}
function logMessages(context) {
console.log("%cCurrent Messages:", "font-size: 16px; font-weight: bold;");
if (context.messages.length === 0) {
console.log("No messages found");
return;
}
const tableData = context.messages.map((message) => {
if (message.isTextMessage()) return {
id: message.id,
type: "TextMessage",
role: message.role,
name: void 0,
scope: void 0,
content: message.content
};
else if (message.isActionExecutionMessage()) return {
id: message.id,
type: "ActionExecutionMessage",
role: void 0,
name: message.name,
scope: message.parentMessageId,
content: message.arguments
};
else if (message.isResultMessage()) return {
id: message.id,
type: "ResultMessage",
role: void 0,
name: message.actionName,
scope: message.actionExecutionId,
content: message.result
};
else if (message.isAgentStateMessage()) return {
id: message.id,
type: `AgentStateMessage (running: ${message.running})`,
role: message.role,
name: void 0,
scope: message.threadId,
content: message.state
};
});
console.table(tableData);
}
//#endregion
//#region src/components/dev-console/icons.tsx
const ExclamationMarkTriangleIcon = /* @__PURE__ */ 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__ */ jsx("g", {
id: "Page-1",
stroke: "none",
strokeWidth: "1",
fill: "none",
fillRule: "evenodd",
children: /* @__PURE__ */ jsx("g", {
id: "exclamation-triangle",
fill: "#CD2121",
children: /* @__PURE__ */ 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"
})
})
})
});
const ExclamationMarkIcon = /* @__PURE__ */ jsx("svg", {
width: "14px",
height: "14px",
viewBox: "0 0 14 14",
version: "1.1",
xmlns: "http://www.w3.org/2000/svg",
children: /* @__PURE__ */ jsx("g", {
id: "Page-1",
stroke: "none",
strokeWidth: "1",
fill: "none",
fillRule: "evenodd",
children: /* @__PURE__ */ jsx("g", {
id: "exclamation-circle",
fill: "#EC662C",
children: /* @__PURE__ */ jsx("path", {
d: "M7,14 C10.866,14 14,10.866 14,7 C14,3.13401 10.866,0 7,0 C3.13401,0 0,3.13401 0,7 C0,10.866 3.13401,14 7,14 Z M7,3 C7.41421,3 7.75,3.33579 7.75,3.75 L7.75,6.75 C7.75,7.16421 7.41421,7.5 7,7.5 C6.58579,7.5 6.25,7.16421 6.25,6.75 L6.25,3.75 C6.25,3.33579 6.58579,3 7,3 Z M7,11 C7.55228,11 8,10.5523 8,10 C8,9.4477 7.55228,9 7,9 C6.44772,9 6,9.4477 6,10 C6,10.5523 6.44772,11 7,11 Z",
id: "Shape"
})
})
})
});
const ChevronDownIcon = /* @__PURE__ */ jsx("svg", {
width: "7px",
height: "4px",
viewBox: "0 0 7 4",
version: "1.1",
xmlns: "http://www.w3.org/2000/svg",
fill: "currentColor",
children: /* @__PURE__ */ jsx("g", {
id: "Page-1",
stroke: "none",
strokeWidth: "1",
fill: "none",
fillRule: "evenodd",
children: /* @__PURE__ */ jsx("g", {
id: "Group",
fill: "currentColor",
fillRule: "nonzero",
children: /* @__PURE__ */ jsx("path", {
d: "M3.71690723,3.90271086 C3.59268176,4.03242971 3.39143629,4.03242971 3.26721082,3.90271086 L0.0853966595,0.57605615 C-0.0314221035,0.444981627 -0.0279751448,0.240725043 0.0931934622,0.114040675 C0.214362069,-0.0126436935 0.409725445,-0.0162475626 0.535093061,0.105888951 L3.49205902,3.19746006 L6.44902499,0.105888951 C6.52834574,0.0168884389 6.64780588,-0.0197473458 6.7605411,0.0103538404 C6.87327633,0.0404550266 6.96130636,0.132492308 6.99009696,0.250359396 C7.01888756,0.368226483 6.98384687,0.493124608 6.89872139,0.57605615 L3.71690723,3.90271086 Z",
id: "Path"
})
})
})
});
const CheckIcon = /* @__PURE__ */ jsx("svg", {
width: "14px",
height: "14px",
viewBox: "0 0 14 14",
version: "1.1",
xmlns: "http://www.w3.org/2000/svg",
children: /* @__PURE__ */ jsx("g", {
id: "Page-1",
stroke: "none",
strokeWidth: "1",
fill: "none",
fillRule: "evenodd",
children: /* @__PURE__ */ jsx("g", {
id: "Group-2",
transform: "translate(-118, 0)",
fill: "#1BC030",
fillRule: "nonzero",
children: /* @__PURE__ */ jsx("g", {
id: "Group",
transform: "translate(118, 0)",
children: /* @__PURE__ */ jsx("path", {
d: "M0,7 C0,3.13384615 3.13384615,0 7,0 C10.8661538,0 14,3.13384615 14,7 C14,10.8661538 10.8661538,14 7,14 C3.13384615,14 0,10.8661538 0,7 Z M9.59179487,5.69764103 C9.70905818,5.54139023 9.73249341,5.33388318 9.65303227,5.15541491 C9.57357113,4.97694665 9.40367989,4.85551619 9.20909814,4.83811118 C9.01451638,4.82070616 8.82577109,4.91005717 8.71589744,5.07158974 L6.39261538,8.32389744 L5.22666667,7.15794872 C5.01450582,6.96025518 4.68389046,6.9660885 4.47883563,7.17114332 C4.27378081,7.37619815 4.26794748,7.70681351 4.46564103,7.91897436 L6.08102564,9.53435897 C6.19289944,9.64614839 6.3482622,9.70310251 6.50588106,9.69010587 C6.66349993,9.67710922 6.80743532,9.59547613 6.89948718,9.46687179 L9.59179487,5.69764103 L9.59179487,5.69764103 Z",
id: "Shape"
})
})
})
})
});
//#endregion
//#region src/components/help-modal/icons.tsx
const CloseIcon = () => /* @__PURE__ */ jsx("svg", {
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
strokeWidth: "1.5",
stroke: "currentColor",
width: "20",
height: "20",
children: /* @__PURE__ */ jsx("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
d: "M6 18L18 6M6 6l12 12"
})
});
//#endregion
//#region src/components/help-modal/modal.tsx
function CopilotKitHelpModal() {
const [showHelpModal, setShowHelpModal] = useState(false);
const buttonRef = useRef(null);
const popoverRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (popoverRef.current && !popoverRef.current.contains(event.target) && buttonRef.current && !buttonRef.current.contains(event.target)) setShowHelpModal(false);
};
if (showHelpModal) document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [showHelpModal]);
const HelpButton = () => /* @__PURE__ */ jsx("button", {
ref: buttonRef,
onClick: () => setShowHelpModal(!showHelpModal),
className: "copilotKitDebugMenuTriggerButton relative",
"aria-label": "Open Help",
children: "Help"
});
return /* @__PURE__ */ jsxs("div", {
className: "relative",
children: [/* @__PURE__ */ jsx(HelpButton, {}), showHelpModal && /* @__PURE__ */ jsx("div", {
ref: popoverRef,
className: "absolute mt-2 z-50",
style: {
top: "100%",
right: "-120px",
width: "380px"
},
children: /* @__PURE__ */ jsxs("div", {
className: "copilotKitHelpModal rounded-lg shadow-xl w-full p-4 flex-col relative",
children: [
/* @__PURE__ */ jsx("button", {
className: "copilotKitHelpModalCloseButton absolute text-gray-400 hover:text-gray-600 focus:outline-none",
style: {
top: "10px",
right: "10px"
},
onClick: () => setShowHelpModal(false),
"aria-label": "Close",
children: /* @__PURE__ */ jsx(CloseIcon, {})
}),
/* @__PURE__ */ jsx("div", {
className: "w-full flex mb-6 justify-center",
children: /* @__PURE__ */ jsx("h2", {
className: "text-2xl font-bold",
children: "Help Options"
})
}),
/* @__PURE__ */ jsxs("div", {
className: "space-y-4 mb-4",
children: [
/* @__PURE__ */ jsx("div", {
className: "copilotKitHelpItemButton",
children: /* @__PURE__ */ jsx("a", {
href: "https://docs.copilotkit.ai/coagents/troubleshooting/common-issues",
target: "_blank",
rel: "noopener noreferrer",
children: "Visit the Troubleshooting and FAQ section in the docs"
})
}),
/* @__PURE__ */ jsx("div", {
className: "copilotKitHelpItemButton",
children: /* @__PURE__ */ jsx("a", {
href: "https://go.copilotkit.ai/dev-console-support-discord",
target: "_blank",
rel: "noopener noreferrer",
children: "Go to Discord Support Channel (Community Support)"
})
}),
/* @__PURE__ */ jsx("div", {
className: "copilotKitHelpItemButton",
children: /* @__PURE__ */ jsx("a", {
href: "https://go.copilotkit.ai/dev-console-support-slack",
target: "_blank",
rel: "noopener noreferrer",
children: "Apply for Priority Direct Slack Support"
})
})
]
})
]
})
})]
});
}
//#endregion
//#region src/components/dev-console/console.tsx
function CopilotDevConsole() {
const currentVersion = COPILOTKIT_VERSION;
const context = useCopilotContext();
const [showDevConsole, setShowDevConsole] = useState(false);
useEffect(() => {
setShowDevConsole(shouldShowDevConsole(context.showDevConsole));
}, [context.showDevConsole]);
const dontRunTwiceInDevMode = useRef(false);
const [versionStatus, setVersionStatus] = useState("unknown");
const [latestVersion, setLatestVersion] = useState("");
const consoleRef = useRef(null);
const [debugButtonMode, setDebugButtonMode] = useState("full");
const checkForUpdates = (force = false) => {
setVersionStatus("checking");
getPublishedCopilotKitVersion(currentVersion, force).then((v) => {
setLatestVersion(v.latest);
let versionOk = false;
if (v.current === v.latest) versionOk = true;
else if (/[a-zA-Z]/.test(v.current)) versionOk = true;
if (versionOk) setVersionStatus("latest");
else if (v.severity !== "low") setVersionStatus("outdated");
else setVersionStatus("update-available");
}).catch((e) => {
console.error(e);
setVersionStatus("unknown");
});
};
useEffect(() => {
if (dontRunTwiceInDevMode.current === true) return;
dontRunTwiceInDevMode.current = true;
checkForUpdates();
}, []);
if (!showDevConsole) return null;
return /* @__PURE__ */ jsxs("div", {
ref: consoleRef,
className: "copilotKitDevConsole " + (versionStatus === "update-available" ? "copilotKitDevConsoleUpgrade" : "") + (versionStatus === "outdated" ? "copilotKitDevConsoleWarnOutdated" : ""),
children: [
/* @__PURE__ */ jsx(VersionInfo, {
showDevConsole: context.showDevConsole,
versionStatus,
currentVersion,
latestVersion
}),
/* @__PURE__ */ jsx(CopilotKitHelpModal, {}),
/* @__PURE__ */ jsx(DebugMenuButton, {
setShowDevConsole,
checkForUpdates,
mode: debugButtonMode
})
]
});
}
function VersionInfo({ showDevConsole, versionStatus, currentVersion, latestVersion }) {
const [copyStatus, setCopyStatus] = useState("");
let versionIcon = "";
let currentVersionLabel = currentVersion;
if (versionStatus === "latest") versionIcon = CheckIcon;
else if (versionStatus === "checking") versionIcon = SmallSpinnerIcon;
else if (versionStatus === "update-available") {
versionIcon = ExclamationMarkIcon;
currentVersionLabel = `${currentVersion}${latestVersion}`;
} else if (versionStatus === "outdated") {
versionIcon = ExclamationMarkTriangleIcon;
currentVersionLabel = `${currentVersion}${latestVersion}`;
}
if (showDevConsole === true) {}
const installCommand = [
`npm install`,
`@copilotkit/react-core@${latestVersion}`,
`@copilotkit/react-ui@${latestVersion}`,
`@copilotkit/react-textarea@${latestVersion}`,
`&& npm install @copilotkit/runtime@${latestVersion}`
].join(" ");
const handleCopyClick = () => {
navigator.clipboard.writeText(installCommand.trim()).then(() => {
setCopyStatus("Command copied to clipboard!");
setTimeout(() => setCopyStatus(""), 1e3);
});
};
if (versionStatus === "update-available" || versionStatus === "outdated") return /* @__PURE__ */ jsxs("div", {
className: "copilotKitVersionInfo",
children: [/* @__PURE__ */ jsxs("p", { children: [
currentVersionLabel,
" ",
versionIcon
] }), /* @__PURE__ */ jsx("button", {
onClick: handleCopyClick,
children: copyStatus || installCommand
})]
});
return null;
}
function DebugMenuButton({ setShowDevConsole, checkForUpdates, mode }) {
const context = useCopilotContext();
const messagesContext = useCopilotMessagesContext();
return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsxs(Menu, { children: [/* @__PURE__ */ jsx(MenuButton, {
className: `copilotKitDebugMenuTriggerButton ${mode === "compact" ? "compact" : ""}`,
children: mode == "compact" ? "Debug" : /* @__PURE__ */ jsxs(Fragment, { children: ["Debug ", ChevronDownIcon] })
}), /* @__PURE__ */ jsxs(MenuItems, {
transition: true,
anchor: "bottom end",
className: "copilotKitDebugMenu",
style: { zIndex: 40 },
children: [
/* @__PURE__ */ jsx(MenuItem, { children: /* @__PURE__ */ jsx("button", {
className: "copilotKitDebugMenuItem",
onClick: () => logReadables(context),
children: "Log Readables"
}) }),
/* @__PURE__ */ jsx(MenuItem, { children: /* @__PURE__ */ jsx("button", {
className: "copilotKitDebugMenuItem",
onClick: () => logActions(context),
children: "Log Actions"
}) }),
/* @__PURE__ */ jsx(MenuItem, { children: /* @__PURE__ */ jsx("button", {
className: "copilotKitDebugMenuItem",
onClick: () => logMessages(messagesContext),
children: "Log Messages"
}) }),
/* @__PURE__ */ jsx(MenuItem, { children: /* @__PURE__ */ jsx("button", {
className: "copilotKitDebugMenuItem",
onClick: () => checkForUpdates(true),
children: "Check for Updates"
}) }),
/* @__PURE__ */ jsx("hr", {}),
/* @__PURE__ */ jsx(MenuItem, { children: /* @__PURE__ */ jsx("button", {
className: "copilotKitDebugMenuItem",
onClick: () => setShowDevConsole(false),
children: "Hide Dev Console"
}) })
]
})] }) });
}
//#endregion
//#region src/components/chat/Header.tsx
const Header = ({}) => {
const { setOpen, icons, labels } = useChatContext();
return /* @__PURE__ */ jsxs("div", {
className: "copilotKitHeader",
children: [/* @__PURE__ */ jsx("div", { children: labels.title }), /* @__PURE__ */ jsxs("div", {
className: "copilotKitHeaderControls",
children: [/* @__PURE__ */ jsx(CopilotDevConsole, {}), /* @__PURE__ */ jsx("button", {
onClick: () => setOpen(false),
"aria-label": "Close",
className: "copilotKitHeaderCloseButton",
children: icons.headerCloseIcon
})]
})]
});
};
//#endregion
//#region src/components/chat/messages/UserMessage.tsx
const getTextContent = (content) => {
if (typeof content === "undefined") return;
if (typeof content === "string") return content;
return content.map((part) => {
if (part.type === "text") return part.text;
}).filter((value) => typeof value === "string" && value.length > 0).join(" ").trim() || void 0;
};
const UserMessage = (props) => {
const { message, ImageRenderer } = props;
if (message && "image" in message && Boolean(message.image)) {
const imageMessage = message;
const content = getTextContent(imageMessage?.content);
return /* @__PURE__ */ jsx("div", {
className: "copilotKitMessage copilotKitUserMessage",
children: /* @__PURE__ */ jsx(ImageRenderer, {
image: imageMessage.image,
content
})
});
}
return /* @__PURE__ */ jsx("div", {
className: "copilotKitMessage copilotKitUserMessage",
children: getTextContent(message?.content)
});
};
//#endregion
//#region src/hooks/use-copy-to-clipboard.tsx
function useCopyToClipboard({ timeout = 2e3 }) {
const [isCopied, setIsCopied] = React$1.useState(false);
const copyToClipboard = (value) => {
if (typeof window === "undefined" || !navigator.clipboard?.writeText) return;
if (!value) return;
navigator.clipboard.writeText(value).then(() => {
setIsCopied(true);
setTimeout(() => {
setIsCopied(false);
}, timeout);
});
};
return {
isCopied,
copyToClipboard
};
}
//#endregion
//#region src/components/chat/CodeBlock.tsx
const programmingLanguages = {
javascript: ".js",
python: ".py",
java: ".java",
c: ".c",
cpp: ".cpp",
"c++": ".cpp",
"c#": ".cs",
ruby: ".rb",
php: ".php",
swift: ".swift",
"objective-c": ".m",
kotlin: ".kt",
typescript: ".ts",
go: ".go",
perl: ".pl",
rust: ".rs",
scala: ".scala",
haskell: ".hs",
lua: ".lua",
shell: ".sh",
sql: ".sql",
html: ".html",
css: ".css"
};
const generateRandomString = (length, lowercase = false) => {
const chars = "ABCDEFGHJKLMNPQRSTUVWXY3456789";
let result = "";
for (let i = 0; i < length; i++) result += chars.charAt(Math.floor(Math.random() * 30));
return lowercase ? result.toLowerCase() : result;
};
const CodeBlock = memo(({ language, value }) => {
const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2e3 });
const [SyntaxHighlighter, setSyntaxHighlighter] = useState(() => Light);
useEffect(() => {
try {
setSyntaxHighlighter(() => Prism);
} catch {
setSyntaxHighlighter(() => Light);
}
}, []);
const downloadAsFile = () => {
if (typeof window === "undefined") return;
const fileExtension = programmingLanguages[language] || ".file";
const suggestedFileName = `file-${generateRandomString(3, true)}${fileExtension}`;
const fileName = window.prompt("Enter file name", suggestedFileName);
if (!fileName) return;
const blob = new Blob([value], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.download = fileName;
link.href = url;
link.style.display = "none";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
const onCopy = () => {
if (isCopied) return;
copyToClipboard(value);
};
return /* @__PURE__ */ jsxs("div", {
className: "copilotKitCodeBlock",
children: [/* @__PURE__ */ jsxs("div", {
className: "copilotKitCodeBlockToolbar",
children: [/* @__PURE__ */ jsx("span", {
className: "copilotKitCodeBlockToolbarLanguage",
children: language
}), /* @__PURE__ */ jsxs("div", {
className: "copilotKitCodeBlockToolbarButtons",
children: [/* @__PURE__ */ jsx("button", {
className: "copilotKitCodeBlockToolbarButton",
onClick: downloadAsFile,
children: DownloadIcon
}), /* @__PURE__ */ jsx("button", {
className: "copilotKitCodeBlockToolbarButton",
onClick: onCopy,
children: isCopied ? CheckIcon$1 : CopyIcon
})]
})]
}), /* @__PURE__ */ jsx(SyntaxHighlighter, {
language,
style: highlightStyle,
PreTag: "div",
customStyle: {
margin: 0,
borderBottomLeftRadius: "0.375rem",
borderBottomRightRadius: "0.375rem"
},
children: value
})]
});
});
CodeBlock.displayName = "CodeBlock";
const highlightStyle = {
"pre[class*=\"language-\"]": {
color: "#d4d4d4",
fontSize: "13px",
textShadow: "none",
fontFamily: "Menlo, Monaco, Consolas, \"Andale Mono\", \"Ubuntu Mono\", \"Courier New\", monospace",
direction: "ltr",
textAlign: "left",
whiteSpace: "pre",
wordSpacing: "normal",
wordBreak: "normal",
lineHeight: "1.5",
MozTabSize: "4",
OTabSize: "4",
tabSize: "4",
WebkitHyphens: "none",
MozHyphens: "none",
msHyphens: "none",
hyphens: "none",
padding: "1em",
margin: ".5em 0",
overflow: "auto",
background: "#1e1e1e"
},
"code[class*=\"language-\"]": {
color: "#d4d4d4",
fontSize: "13px",
textShadow: "none",
fontFamily: "Menlo, Monaco, Consolas, \"Andale Mono\", \"Ubuntu Mono\", \"Courier New\", monospace",
direction: "ltr",
textAlign: "left",
whiteSpace: "pre",
wordSpacing: "normal",
wordBreak: "normal",
lineHeight: "1.5",
MozTabSize: "4",
OTabSize: "4",
tabSize: "4",
WebkitHyphens: "none",
MozHyphens: "none",
msHyphens: "none",
hyphens: "none"
},
"pre[class*=\"language-\"]::selection": {
textShadow: "none",
background: "#264F78"
},
"code[class*=\"language-\"]::selection": {
textShadow: "none",
background: "#264F78"
},
"pre[class*=\"language-\"] *::selection": {
textShadow: "none",
background: "#264F78"
},
"code[class*=\"language-\"] *::selection": {
textShadow: "none",
background: "#264F78"
},
":not(pre) > code[class*=\"language-\"]": {
padding: ".1em .3em",
borderRadius: ".3em",
color: "#db4c69",
background: "#1e1e1e"
},
".namespace": { Opacity: ".7" },
"doctype.doctype-tag": { color: "#569CD6" },
"doctype.name": { color: "#9cdcfe" },
comment: { color: "#6a9955" },
prolog: { color: "#6a9955" },
punctuation: { color: "#d4d4d4" },
".language-html .language-css .token.punctuation": { color: "#d4d4d4" },
".language-html .language-javascript .token.punctuation": { color: "#d4d4d4" },
property: { color: "#9cdcfe" },
tag: { color: "#569cd6" },
boolean: { color: "#569cd6" },
number: { color: "#b5cea8" },
constant: { color: "#9cdcfe" },
symbol: { color: "#b5cea8" },
inserted: { color: "#b5cea8" },
unit: { color: "#b5cea8" },
selector: { color: "#d7ba7d" },
"attr-name": { color: "#9cdcfe" },
string: { color: "#ce9178" },
char: { color: "#ce9178" },
builtin: { color: "#ce9178" },
deleted: { color: "#ce9178" },
".language-css .token.string.url": { textDecoration: "underline" },
operator: { color: "#d4d4d4" },
entity: { color: "#569cd6" },
"operator.arrow": { color: "#569CD6" },
atrule: { color: "#ce9178" },
"atrule.rule": { color: "#c586c0" },
"atrule.url": { color: "#9cdcfe" },
"atrule.url.function": { color: "#dcdcaa" },
"atrule.url.punctuation": { color: "#d4d4d4" },
keyword: { color: "#569CD6" },
"keyword.module": { color: "#c586c0" },
"keyword.control-flow": { color: "#c586c0" },
function: { color: "#dcdcaa" },
"function.maybe-class-name": { color: "#dcdcaa" },
regex: { color: "#d16969" },
important: { color: "#569cd6" },
italic: { fontStyle: "italic" },
"class-name": { color: "#4ec9b0" },
"maybe-class-name": { color: "#4ec9b0" },
console: { color: "#9cdcfe" },
parameter: { color: "#9cdcfe" },
interpolation: { color: "#9cdcfe" },
"punctuation.interpolation-punctuation": { color: "#569cd6" },
variable: { color: "#9cdcfe" },
"imports.maybe-class-name": { color: "#9cdcfe" },
"exports.maybe-class-name": { color: "#9cdcfe" },
escape: { color: "#d7ba7d" },
"tag.punctuation": { color: "#808080" },
cdata: { color: "#808080" },
"attr-value": { color: "#ce9178" },
"attr-value.punctuation": { color: "#ce9178" },
"attr-value.punctuation.attr-equals": { color: "#d4d4d4" },
namespace: { color: "#4ec9b0" },
"pre[class*=\"language-javascript\"]": { color: "#9cdcfe" },
"code[class*=\"language-javascript\"]": { color: "#9cdcfe" },
"pre[class*=\"language-jsx\"]": { color: "#9cdcfe" },
"code[class*=\"language-jsx\"]": { color: "#9cdcfe" },
"pre[class*=\"language-typescript\"]": { color: "#9cdcfe" },
"code[class*=\"language-typescript\"]": { color: "#9cdcfe" },
"pre[class*=\"language-tsx\"]": { color: "#9cdcfe" },
"code[class*=\"language-tsx\"]": { color: "#9cdcfe" },
"pre[class*=\"language-css\"]": { color: "#ce9178" },
"code[class*=\"language-css\"]": { color: "#ce9178" },
"pre[class*=\"language-html\"]": { color: "#d4d4d4" },
"code[class*=\"language-html\"]": { color: "#d4d4d4" },
".language-regex .token.anchor": { color: "#dcdcaa" },
".language-html .token.punctuation": { color: "#808080" },
"pre[class*=\"language-\"] > code[class*=\"language-\"]": {
position: "relative",
zIndex: "1"
},
".line-highlight.line-highlight": {
background: "#f7ebc6",
boxShadow: "inset 5px 0 0 #f7d87c",
zIndex: "0"
}
};
//#endregion
//#region src/components/chat/Markdown.tsx
const defaultComponents = {
a({ children, ...props }) {
return /* @__PURE__ */ jsx("a", {
className: "copilotKitMarkdownElement",
...props,
target: "_blank",
rel: "noopener noreferrer",
children
});
},
code({ children, className, inline, ...props }) {
if (Array.isArray(children) && children.length) {
if (children[0] == "▍") return /* @__PURE__ */ jsx("span", {
style: {
animation: "pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",
marginTop: "0.25rem"
},
children: "▍"
});
children[0] = (children?.[0]).replace("`▍`", "▍");
}
const match = /language-(\w+)/.exec(className || "");
const hasLanguage = match && match[1];
const hasNewlines = String(children).includes("\n");
if (!hasLanguage && !hasNewlines) return /* @__PURE__ */ jsx("code", {
className: `copilotKitMarkdownElement copilotKitInlineCode ${className || ""}`,
...props,
children
});
return /* @__PURE__ */ jsx(CodeBlock, {
language: match && match[1] || "",
value: String(children).replace(/\n$/, ""),
...props
}, Math.random());
},
h1: ({ children, ...props }) => /* @__PURE__ */ jsx("h1", {
className: "copilotKitMarkdownElement",
...props,
children
}),
h2: ({ children, ...props }) => /* @__PURE__ */ jsx("h2", {
className: "copilotKitMarkdownElement",
...props,
children
}),
h3: ({ children, ...props }) => /* @__PURE__ */ jsx("h3", {
className: "copilotKitMarkdownElement",
...props,
children
}),
h4: ({ children, ...props }) => /* @__PURE__ */ jsx("h4", {
className: "copilotKitMarkdownElement",
...props,
children
}),
h5: ({ children, ...props }) => /* @__PURE__ */ jsx("h5", {
className: "copilotKitMarkdownElement",
...props,
children
}),
h6: ({ children, ...props }) => /* @__PURE__ */ jsx("h6", {
className: "copilotKitMarkdownElement",
...props,
children
}),
p: ({ children, ...props }) => /* @__PURE__ */ jsx("p", {
className: "copilotKitMarkdownElement",
...props,
children
}),
pre: ({ children, ...props }) => /* @__PURE__ */ jsx("pre", {
className: "copilotKitMarkdownElement",
...props,
children
}),
blockquote: ({ children, ...props }) => /* @__PURE__ */ jsx("blockquote", {
className: "copilotKitMarkdownElement",
...props,
children
}),
ul: ({ children, ...props }) => /* @__PURE__ */ jsx("ul", {
className: "copilotKitMarkdownElement",
...props,
children
}),
li: ({ children, ...props }) => /* @__PURE__ */ jsx("li", {
className: "copilotKitMarkdownElement",
...props,
children
})
};
const MemoizedReactMarkdown = memo(ReactMarkdown, (prevProps, nextProps) => prevProps.children === nextProps.children && prevProps.components === nextProps.components);
const Markdown = ({ content, components }) => {
return /* @__PURE__ */ jsx("div", {
className: "copilotKitMarkdown",
children: /* @__PURE__ */ jsx(MemoizedReactMarkdown, {
components: {
...defaultComponents,
...components
},
remarkPlugins: [remarkGfm, [remarkMath, { singleDollarTextMath: false }]],
rehypePlugins: [rehypeRaw],
children: content
})
});
};
//#endregion
//#region src/components/chat/messages/AssistantMessage.tsx
const AssistantMessage = (props) => {
const { icons, labels } = useChatContext();
const { message, isLoading, onRegenerate, onCopy, onThumbsUp, onThumbsDown, isCurrentMessage, feedback, markdownTagRenderers } = props;
const [copied, setCopied] = useState(false);
const handleCopy = () => {
const content = message?.content || "";
if (content && onCopy) {
navigator.clipboard.writeText(content);
setCopied(true);
onCopy(content);
setTimeout(() => setCopied(false), 2e3);
} else if (content) {
navigator.clipboard.writeText(content);
setCopied(true);
setTimeout(() => setCopied(false), 2e3);
}
};
const handleRegenerate = () => {
if (onRegenerate) onRegenerate();
};
const handleThumbsUp = () => {
if (onThumbsUp && message) onThumbsUp(message);
};
const handleThumbsDown = () => {
if (onThumbsDown && message) onThumbsDown(message);
};
const LoadingIcon = () => /* @__PURE__ */ jsx("span", { children: icons.activityIcon });
const content = message?.content || "";
const subComponent = message?.generativeUI?.() ?? props.subComponent;
const subComponentPosition = message?.generativeUIPosition ?? "after";
const renderBefore = subComponent && subComponentPosition === "before";
const renderAfter = subComponent && subComponentPosition !== "before";
return /* @__PURE__ */ jsxs(Fragment, { children: [
renderBefore ? /* @__PURE__ */ jsx("div", {
style: { marginBottom: "0.5rem" },
children: subComponent
}) : null,
content && /* @__PURE__ */ jsxs("div", {
className: "copilotKitMessage copilotKitAssistantMessage",
children: [content && /* @__PURE__ */ jsx(Markdown, {
content,
components: markdownTagRenderers
}), content && !isLoading && /* @__PURE__ */ jsxs("div", {
className: `copilotKitMessageControls ${isCurrentMessage ? "currentMessage" : ""}`,
children: [
/* @__PURE__ */ jsx("button", {
className: "copilotKitMessageControlButton",
onClick: handleRegenerate,
"aria-label": labels.regenerateResponse,
title: labels.regenerateResponse,
children: icons.regenerateIcon
}),
/* @__PURE__ */ jsx("button", {
className: "copilotKitMessageControlButton",
onClick: handleCopy,
"aria-label": labels.copyToClipboard,
title: labels.copyToClipboard,
children: copied ? /* @__PURE__ */ jsx("span", {
style: {
fontSize: "10px",
fontWeight: "bold"
},
children: "✓"
}) : icons.copyIcon
}),
onThumbsUp && /* @__PURE__ */ jsx("button", {
className: `copilotKitMessageControlButton ${feedback === "thumbsUp" ? "active" : ""}`,
onClick: handleThumbsUp,
"aria-label": labels.thumbsUp,
title: labels.thumbsUp,
children: icons.thumbsUpIcon
}),
onThumbsDown && /* @__PURE__ */ jsx("button", {
className: `copilotKitMessageControlButton ${feedback === "thumbsDown" ? "active" : ""}`,
onClick: handleThumbsDown,
"aria-label": labels.thumbsDown,
title: labels.thumbsDown,
children: icons.thumbsDownIcon
})
]
})]
}),
renderAfter ? /* @__PURE__ */ jsx("div", {
style: { marginBottom: "0.5rem" },
children: subComponent
}) : null,
isLoading && /* @__PURE__ */ jsx(LoadingIcon, {})
] });
};
//#endregion
//#region src/components/chat/messages/ImageRenderer.tsx
/**
* Default image rendering component that can be customized by users.
* Uses CSS classes for styling so users can override styles.
*/
const ImageRenderer = ({ image, content, className = "" }) => {
const [imageError, setImageError] = useState(false);
const imageSrc = `data:image/${image.format};base64,${image.bytes}`;
const altText = content || "User uploaded image";
const handleImageError = () => {
setImageError(true);
};
if (imageError) return /* @__PURE__ */ jsxs("div", {
className: `copilotKitImageRendering copilotKitImageRenderingError ${className}`,
children: [/* @__PURE__ */ jsx("div", {
className: "copilotKitImageRenderingErrorMessage",
children: "Failed to load image"
}), content && /* @__PURE__ */ jsx("div", {
className: "copilotKitImageRenderingContent",
children: content
})]
});
return /* @__PURE__ */ jsxs("div", {
className: `copilotKitImageRendering ${className}`,
children: [/* @__PURE__ */ jsx("img", {
src: imageSrc,
alt: altText,
className: "copilotKitImageRenderingImage",
onError: handleImageError
}), content && /* @__PURE__ */ jsx("div", {
className: "copilotKitImageRenderingContent",
children: content
})]
});
};
//#endregion
//#region src/components/chat/messages/RenderMessage.tsx
function RenderMessage({ UserMessage: UserMessage$4 = UserMessage, AssistantMessage: AssistantMessage$3 = AssistantMessage, ImageRenderer: ImageRenderer$2 = ImageRenderer, ...props }) {
const { message, messages, inProgress, index, isCurrentMessage, onRegenerate, onCopy, onThumbsUp, onThumbsDown, messageFeedback, markdownTagRenderers } = props;
switch (message.role) {
case "user": return /* @__PURE__ */ jsx(UserMessage$4, {
rawData: message,
"data-message-role": "user",
message,
ImageRenderer: ImageRenderer$2
}, index);
case "assistant": return /* @__PURE__ */ jsx(AssistantMessage$3, {
"data-message-role": "assistant",
subComponent: message.generativeUI?.(),
rawData: message,
message,
messages,
isLoading: inProgress && isCurrentMessage && !message.content,
isGenerating: inProgress && isCurrentMessage && !!message.content,
isCurrentMessage,
onRegenerate: () => onRegenerate?.(message.id),
onCopy,
onThumbsUp,
onThumbsDown,
feedback: messageFeedback?.[message.id] || null,
markdownTagRenderers,
ImageRenderer: ImageRenderer$2
}, index);
default: return null;
}
}
//#endregion
//#region src/components/chat/messages/LegacyRenderMessage.tsx
/**
* Legacy message adapter component that maps old render props to new message types.
* This component provides backwards compatibility for the deprecated render props.
*/
const LegacyRenderMessage = ({ message, messages, inProgress, index, isCurrentMessage, actionResult, AssistantMessage, UserMessage, ImageRenderer, onRegenerate, onCopy, onThumbsUp, onThumbsDown, markdownTagRenderers, legacyProps }) => {
const { RenderTextMessage, RenderActionExecutionMessage, RenderAgentStateMessage, RenderResultMessage, RenderImageMessage } = legacyProps;
const deprecatedMessage = aguiToGQL(message)[0] ?? void 0;
if (deprecatedMessage.isTextMessage() && RenderTextMessage) return /* @__PURE__ */ jsx(RenderTextMessage, {
message,
messages,
inProgress,
index,
isCurrentMessage,
AssistantMessage,
UserMessage,
onRegenerate,
onCopy,
onThumbsUp,
onThumbsDown,
markdownTagRenderers
});
if (deprecatedMessage.isActionExecutionMessage() && RenderActionExecutionMessage) return /* @__PURE__ */ jsx(RenderActionExecutionMessage, {
messages,
message,
inProgress,
index,
isCurrentMessage,
actionResult,
AssistantMessage,
UserMessage
});
if (deprecatedMessage.isAgentStateMessage() && RenderAgentStateMessage) return /* @__PURE__ */ jsx(RenderAgentStateMessage, {
messages,
message,
inProgress,
index,
isCurrentMessage,
AssistantMessage,
UserMessage
});
if (deprecatedMessage.isResultMessage() && RenderResultMessage) return /* @__PURE__ */ jsx(RenderResultMessage, {
messages,
message,
inProgress,
index,
isCurrentMessage,
AssistantMessage,
UserMessage
});
if (deprecatedMessage.isImageMessage() && RenderImageMessage) return /* @__PURE__ */ jsx(RenderImageMessage, {
messages,
message,
inProgress,
index,
isCurrentMessage,
AssistantMessage,
UserMessage
});
return /* @__PURE__ */ jsx(RenderMessage, {
messages,
message,
inProgress,
index,
isCurrentMessage,
AssistantMessage,
UserMessage,
ImageRenderer,
onRegenerate,
onCopy,
onThumbsUp,
onThumbsDown,
markdownTagRenderers
});
};
//#endregion
//#region src/components/chat/Messages.tsx
const Messages = ({ inProgress, children, RenderMessage, AssistantMessage, UserMessage, ErrorMessage, ImageRenderer, onRegenerate, onCopy, onThumbsUp, onThumbsDown, messageFeedback, markdownTagRenderers, chatError, RenderTextMessage, RenderActionExecutionMessage, RenderAgentStateMessage, RenderResultMessage, RenderImageMessage }) => {
const { labels, icons } = useChatContext();
const { messages: visibleMessages, interrupt } = useCopilotChatInternal();
const messages = [...useMemo(() => makeInitialMessages(labels.initial), [labels.initial]), ...visibleMessages];
const { messagesContainerRef, messagesEndRef } = useScrollToBottom(messages);
const hasLegacyProps = !!(RenderTextMessage || RenderActionExecutionMessage || RenderAgentStateMessage || RenderResultMessage || RenderImageMessage);
useEffect(() => {
if (hasLegacyProps) console.warn("[CopilotKit] Legacy message render props (RenderTextMessage, RenderActionExecutionMessage, etc.) are deprecated. Please use the unified 'RenderMessage' prop instead. See migration guide: https://docs.copilotkit.ai/migration/render-message");
}, [hasLegacyProps]);
const legacyProps = useMemo(() => ({
RenderTextMessage,
RenderActionExecutionMessage,
RenderAgentStateMessage,
RenderResultMessage,
RenderImageMessage
}), [
RenderTextMessage,
RenderActionExecutionMessage,
RenderAgentStateMessage,
RenderResultMessage,
RenderImageMessage
]);
const MessageRenderer = hasLegacyProps ? (props) => /* @__PURE__ */ jsx(LegacyRenderMessage, {
...props,
legacyProps
}) : RenderMessage;
const LoadingIcon = () => /* @__PURE__ */ jsx("span", { children: icons.activityIcon });
return /* @__PURE__ */ jsxs("div", {
className: "copilotKitMessages",
ref: messagesContainerRef,
children: [/* @__PURE__ */ jsxs("div", {
className: "copilotKitMessagesContainer",
children: [
messages.map((message, index) => {
return /* @__PURE__ */ jsx(MessageRenderer, {
message,
messages,
inProgress,
index,
isCurrentMessage: index === messages.length - 1,
AssistantMessage,
UserMessage,
ImageRenderer,
onRegenerate,
onCopy,
onThumbsUp,
onThumbsDown,
messageFeedback,
markdownTagRenderers
}, index);
}),
messages[messages.length - 1]?.role === "user" && inProgress && /* @__PURE__ */ jsx(LoadingIcon, {}),
interrupt,
chatError && ErrorMessage && /* @__PURE__ */ jsx(ErrorMessage, {
error: chatError,
isCurrentMessage: true
})
]
}), /* @__PURE__ */ jsx("footer", {
className: "copilotKitMessagesFooter",
ref: messagesEndRef,
children
})]
});
};
function makeInitialMessages(initial) {
if (!initial) return [];
if (Array.isArray(initial)) return initial.map((message) => {
return {
id: message,
role: "assistant",
content: message
};
});
return [{
id: initial,
role: "assistant",
content: initial
}];
}
function useScrollToBottom(messages) {
const messagesEndRef = useRef(null);
const messagesContainerRef = useRef(null);
const isProgrammaticScrollRef = useRef(false);
const isUserScrollUpRef = useRef(false);
const scrollToBottom = () => {
if (messagesContainerRef.current && messagesEndRef.current) {
isProgrammaticScrollRef.current = true;
messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight;
}
};
const handleScroll = () => {
if (isProgrammaticScrollRef.current) {
isProgrammaticScrollRef.current = false;
return;
}
if (messagesContainerRef.current) {
const { scrollTop, scrollHeight, clientHeight } = messagesContainerRef.current;
isUserScrollUpRef.current = scrollTop + clientHeight < scrollHeight;
}
};
useEffect(() => {
const container = messagesContainerRef.current;
if (container) container.addEventListener("scroll", handleScroll);
return () => {
if (container) container.removeEventListener("scroll", handleScroll);
};
}, []);
useEffect(() => {
const container = messagesContainerRef.current;
if (!container) return;
const mutationObserver = new MutationObserver(() => {
if (!isUserScrollUpRef.current) scrollToBottom();
});
mutationObserver.observe(container, {
childList: true,
subtree: true,
characterData: true
});
return () => {
mutationObserver.disconnect();
};
}, []);
useEffect(() => {
isUserScrollUpRef.current = false;
scrollToBottom();
}, [messages.filter((m) => m.role === "user").length]);
return {
messagesEndRef,
messagesContainerRef
};
}
//#endregion
//#region src/components/chat/Textarea.tsx
const AutoResizingTextarea = forwardRef(({ maxRows = 1, placeholder, value, onChange, onKeyDown, onCompositionStart, onCompositionEnd, autoFocus }, ref) => {
const internalTextareaRef = useRef(null);
const [maxHeight, setMaxHeight] = useState(0);
useImperativeHandle(ref, () => internalTextareaRef.current);
useEffect(() => {
const calculateMaxHeight = () => {
const textarea = internalTextareaRef.current;
if (textarea) {
textarea.style.height = "auto";
const singleRowHeight = textarea.scrollHeight;
setMaxHeight(singleRowHeight * maxRows);
if (autoFocus) textarea.focus();
}
};
calculateMaxHeight();
}, [maxRows]);
useEffect(() => {
const textarea = internalTextareaRef.current;
if (textarea) {
textarea.style.height = "auto";
textarea.style.height = `${Math.min(textarea.scrollHeight, maxHeight)}px`;
}
}, [value, maxHeight]);
return /* @__PURE__ */ jsx("textarea", {
ref: internalTextareaRef,
value,
onChange,
onKeyDown,
onCompositionStart,
onCompositionEnd,
placeholder,
style: {
overflow: "auto",
resize: "none",
maxHeight: `${maxHeight}px`
},
rows: 1
});
});
//#endregion
//#region src/hooks/use-push-to-talk.tsx
const startRecording = async (mediaStreamRef, mediaRecorderRef, audioContextRef, recordedChunks, onStop) => {
if (!mediaStreamRef.current || !audioContextRef.current) {
mediaStreamRef.current = await navigator.mediaDevices.getUserMedia({ audio: true });
audioContextRef.current = new window.AudioContext();
await audioContextRef.current.resume();
}
mediaRecorderRef.current = new MediaRecorder(mediaStreamRef.current);
mediaRecorderRef.current.start(1e3);
mediaRecorderRef.current.ondataavailable = (event) => {
recordedChunks.push(event.data);
};
mediaRecorderRef.current.onstop = onStop;
};
const stopRecording = (mediaRecorderRef) => {
if (mediaRecorderRef.current && mediaRecorderRef.current.state !== "inactive") mediaRecorderRef.current.stop();
};
const transcribeAudio = async (recordedChunks, transcribeAudioUrl) => {
const completeBlob = new Blob(recordedChunks, { type: "audio/mp4" });
const formData = new FormData();
formData.append("file", completeBlob, "recording.mp4");
const response = await fetch(transcribeAudioUrl, {
method: "POST",
body: formData
});
if (!response.ok) throw new Error(`Error: ${response.statusText}`);
return (await response.json()).text;
};
const playAudioResponse = (text, textToSpeechUrl, audioContext) => {
const url = `${textToSpeechUrl}?text=${encodeURIComponent(text)}`;
fetch(url).then((response) => response.arrayBuffer()).then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer)).then((audioBuffer) => {
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start(0);
}).catch((error) => {
console.error("Error with decoding audio data", error);
});
};
const usePushToTalk = ({ sendFunction, inProgress }) => {
const [pushToTalkState, setPushToTalkState] = useState("idle");
const mediaStreamRef = useRef(null);
const audioContextRef = useRef(null);
const mediaRecorderRef = useRef(null);
const recordedChunks = useRef([]);
const generalContext = useCopilotContext();
const messagesContext = useCopilotMessagesContext();
const context = {
...generalContext,
...messagesContext
};
const [startReadingFromMessageId, setStartReadingFromMessageId] = useState(null);
useEffect(() => {
if (pushToTalkState === "recording") startRecording(mediaStreamRef, mediaRecorderRef, audioContextRef, recordedChunks.current, () => {
setPushToTalkState("transcribing");
});
else {
stopRecording(mediaRecorderRef);
if (pushToTalkState === "transcribing") transcribeAudio(recordedChunks.current, context.copilotApiConfig.transcribeAudioUrl).then(async (transcription) => {
recordedChunks.current = [];
setPushToTalkState("idle");
setStartReadingFromMessageId((await sendFunction(transcription)).id);
});
}
return () => {
stopRecording(mediaRecorderRef);
};
}, [pushToTalkState]);
useEffect(() => {
if (inProgress === false && startReadingFromMessageId) {
const lastMessageIndex = context.messages.findIndex((message) => message.id === startReadingFromMessageId);
playAudioResponse(gqlToAGUI(context.messages).slice(lastMessageIndex + 1).filter((message) => message.role === "assistant").map((message) => message.content).join("\n"), context.copilotApiConfig.textToSpeechUrl, audioContextRef.current);
setStartReadingFromMessageId(null);
}
}, [startReadingFromMessageId, inProgress]);
return {
pushToTalkState,
setPushToTalkState
};
};
//#endregion
//#region src/hooks/use-dark-mode.ts
const useDarkMode = () => {
if (typeof window === "undefined") return false;
return document.documentElement.classList.contains("dark") || document.body.classList.contains("dark") || document.documentElement.getAttribute("data-theme") === "dark" || document.body.getAttribute("data-theme") === "dark" || window.matchMedia("(prefers-color-scheme: dark)").matches;
};
//#endregion
//#region src/components/chat/PoweredByTag.tsx
function PoweredByTag({ showPoweredBy = true }) {
const [mounted, setMounted] = useState(false);
const isDark = useDarkMode();
useEffect(() => {
setMounted(true);
}, []);
if (!showPoweredBy) return null;
return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx("p", {
className: "poweredBy",
style: {
visibility: "visible",
display: "block",
position: "static",
textAlign: "center",
fontSize: "12px",
padding: "3px 0",
color: mounted && isDark ? "rgb(69, 69, 69)" : "rgb(214, 214, 214)"
},
children: "Powered by CopilotKit"
}) });
}
//#endregion
//#region src/components/chat/Input.tsx
const MAX_NEWLINES = 6;
const Input = ({ inProgress, onSend, chatReady = false, onStop, onUpload, hideStopButton = false }) => {
const context = useChatContext();
const copilotContext = useCopilotContext();
const showPoweredBy = !copilotContext.copilotApiConfig?.publicApiKey;
const pushToTalkConfigured = copilotContext.copilotApiConfig.textToSpeechUrl !== void 0 && copilotContext.copilotApiConfig.transcribeAudioUrl !== void 0;
const textareaRef = useRef(null);
const [isComposing, setIsComposing] = useState(false);
const handleDivClick = (event) => {
const target = event.target;
if (target.closest("button")) return;
if (target.tagName === "TEXTAREA") return;
textareaRef.current?.focus();
};
const [text, setText] = useState("");
const send = () => {
if (inProgress) return;
onSend(text);
setText("");
textareaRef.current?.focus();
};
const { pushToTalkState, setPushToTalkState } = usePushToTalk({
sendFunction: onSend,
inProgress
});
const isInProgress = inProgress || pushToTalkState === "transcribing";
const { buttonIcon, buttonAlt } = useMemo(() => {
if (!chatReady) return {
buttonIcon: context.icons.spinnerIcon,
buttonAlt: "Loading"
};
return isInProgress && !hideStopButton && chatReady ? {
buttonIcon: context.icons.stopIcon,
buttonAlt: "Stop"
} : {
buttonIcon: context.icons.sendIcon,
buttonAlt: "Send"
};
}, [
isInProgress,
chatReady,
hideStopButton,
context.icons.stopIcon,
context.icons.sendIcon
]);
const showPushToTalk = pushToTalkConfigured && (pushToTalkState === "idle" || pushToTalkState === "recording") && !inProgress;
const { interrupt } = useCopilotChatInternal();
const canSend = useMemo(() => {
return !isInProgress && text.trim().length > 0 && pushToTalkState === "idle" && !interrupt;
}, [
interrupt,
isInProgress,
text,
pushToTalkState
]);
const canStop = useMemo(() => {
return isInProgress && !hideStopButton;
}, [isInProgress, hideStopButton]);
const sendDisabled = !canSend && !canStop;
return /* @__PURE__ */ jsxs("div", {
className: `copilotKitInputContainer ${showPoweredBy ? "poweredByContainer" : ""}`,
children: [/* @__PURE__ */ jsxs("div", {
className: "copilotKitInput",
onClick: handleDivClick,
children: [/* @__PURE__ */ jsx(AutoResizingTextarea, {
ref: textareaRef,
placeholder: context.labels.placeholder,
autoFocus: false,
maxRows: MAX_NEWLINES,
value: text,
onChange: (event) => setText(event.target.value),
onCompositionStart: () => setIsComposing(true),
onCompositionEnd: () => setIsComposing(false),
onKeyDown: (event) => {
if (event.key === "Enter" && !event.shiftKey && !isComposing) {
event.preventDefault();
if (canSend) send();
}
}
}), /* @__PURE__ */ jsxs("div", {
className: "copilotKitInputControls",
children: [
onUpload && /* @__PURE__ */ jsx("button", {
onClick: onUpload,
className: "copilotKitInputControlButton",
children: context.icons.uploadIcon
}),
/* @__PURE__ */ jsx("div", { style: { flexGrow: 1 } }),
showPushToTalk && /* @__PURE__ */ jsx("button", {
onClick: () => setPushToTalkState(pushToTalkState === "idle" ? "recording" : "transcribing"),
className: pushToTalkState === "recording" ? "copilotKitInputControlButton copilotKitPushToTalkRecording" : "copilotKitInputControlButton",
children: context.icons.pushToTalkIcon
}),
/* @__PURE__ */ jsx("button", {
disabled: sendDisabled,
onClick: isInProgress && !hideStopButton ? onStop : send,
"data-copilotkit-in-progress": inProgress,
"data-test-id": inProgress ? "copilot-chat-request-in-progress" : "copilot-chat-ready",
className: "copilotKitInputControlButton",
"aria-label": buttonAlt,
children: buttonIcon
})
]
})]
}), /* @__PURE__ */ jsx(PoweredByTag, { showPoweredBy })]
});
};
//#endregion
//#region src/components/chat/ImageUploadQueue.tsx
const ImageUploadQueue = ({ images, onRemoveImage, className = "" }) => {
if (images.length === 0) return null;
return /* @__PURE__ */ jsx("div", {
className: `copilotKitImageUploadQueue ${className}`,
style: {
display: "flex",
flexWrap: "wrap",
gap: "8px",
margin: "8px",
padding: "8px"
},
children: images.map((image, index) => /* @__PURE__ */ jsxs("div", {
className: "copilotKitImageUploadQueueItem",
style: {
position: "relative",
display: "inline-block",
width: "60px",
height: "60px",
borderRadius: "4px",
overflow: "hidden"
},
children: [/* @__PURE__ */ jsx("img", {
src: `data:${image.contentType};base64,${image.bytes}`,
alt: `Selected image ${index + 1}`,
style: {
width: "100%",
height: "100%",
objectFit: "cover"
}
}), /* @__PURE__ */ jsx("button", {
onClick: () => onRemoveImage(index),
className: "copilotKitImageUploadQueueRemoveButton",
style: {
position: "absolute",
top: "2px",
right: "2px",
background: "rgba(0,0,0,0.6)",
color: "white",
border: "none",
borderRadius: "50%",
width: "18px",
height: "18px",
display: "flex",
alignItems: "center",
justifyContent: "center",
cursor: "pointer",
fontSize: "10px",
padding: 0
},
children: "✕"
})]
}, index))
});
};
//#endregion
//#region src/components/chat/Suggestion.tsx
function Suggestion({ title, onClick, partial, className }) {
const { isLoading } = useCopilotChatInternal();
if (!title) return null;
return /* @__PURE__ */ jsx("button", {
disabled: partial || isLoading,
onClick: (e) => {
e.preventDefault();
onClick();
},
className: `suggestion ${className ?? ""} ${partial ? "loading" : ""}`,
"data-test-id": "suggestion",
type: "button",
children: partial ? SmallSpinnerIcon : /* @__PURE__ */ jsx("span", { children: title })
});
}
//#endregion
//#region src/components/chat/Suggestions.tsx
function Suggestions({ suggestions, onSuggestionClick, isLoading }) {
return /* @__PURE__ */ jsx("div", {
className: "suggestions",
children: suggestions.map((suggestion, index) => /* @__PURE__ */ jsx(Suggestion, {
title: suggestion.title,
message: suggestion.message,
partial: suggestion.isLoading ?? suggestion.partial ?? isLoading,
className: suggestion.className,
onClick: () => onSuggestionClick(suggestion.message)
}, index))
});
}
//#endregion
//#region src/components/chat/Chat.tsx
/**
* <br/>
* <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/CopilotChat.gif" width="500" />
*
* A chatbot panel component for the CopilotKit framework. The component allows for a high degree
* of customization through various props and custom CSS.
*
* ## Install Dependencies
*
* This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.
*
* ```shell npm2yarn \"@copilotkit/react-ui"\
* npm install @copilotkit/react-core @copilotkit/react-ui
* ```
*
* ## Usage
*
* ```tsx
* import { CopilotChat } from "@copilotkit/react-ui";
* import "@copilotkit/react-ui/styles.css";
*
* <CopilotChat
* labels={{
* title: "Your Assistant",
* initial: "Hi! 👋 How can I assist you today?",
* }}
* />
* ```
*
* ### With Observability Hooks
*
* To monitor user interactions, provide the `observabilityHooks` prop.
* **Note:** This requires a `publicApiKey` in the `<CopilotKit>` provider.
*
* ```tsx
* <CopilotKit publicApiKey="YOUR_PUBLIC_API_KEY">
* <CopilotChat
* observabilityHooks={{
* onMessageSent: (message) => {
* console.log("Message sent:", message);
* },
* }}
* />
* </CopilotKit>
* ```
*
* ### Look & Feel
*
* By default, CopilotKit components do not have any styles. You can import CopilotKit's stylesheet at the root of your project:
* ```tsx title="YourRootComponent.tsx"
* ...
* import "@copilotkit/react-ui/styles.css"; // [!code highlight]
*
* export function YourRootComponent() {
* return (
* <CopilotKit>
* ...
* </CopilotKit>
* );
* }
* ```
* For more information about how to customize the styles, check out the [Customize Look & Feel](/guides/custom-look-and-feel/customize-built-in-ui-components) guide.
*/
function CopilotChat({ instructions, suggestions = "auto", onSubmitMessage, makeSystemMessage, disableSystemMessage, onInProgress, onStopGeneration, onReloadMessages, onRegenerate, onCopy, onThumbsUp, onThumbsDown, markdownTagRenderers, Messages: Messages$2 = Messages, RenderMessage: RenderMessage$1 = RenderMessage, RenderSuggestionsList = Suggestions, Input: Input$2 = Input, className, icons, labels, AssistantMessage: AssistantMessage$2 = AssistantMessage, UserMessage: UserMessage$3 = UserMessage, ImageRenderer: ImageRenderer$1 = ImageRenderer, ErrorMessage, imageUploadsEnabled, inputFileAccept = "image/*", hideStopButton, observabilityHooks, renderError, onError, RenderTextMessage, RenderActionExecutionMessage, RenderAgentStateMessage, RenderResultMessage, RenderImageMessage }) {
const { additionalInstructions, setChatInstructions, copilotApiConfig, setBannerError, setInternalErrorHandler, removeInternalErrorHandler } = useCopilotContext();
const { publicApiKey, chatApiEndpoint } = copilotApiConfig;
const [selectedImages, setSelectedImages] = useState([]);
const [chatError, setChatError] = useState(null);
const [messageFeedback, setMessageFeedback] = useState({});
const fileInputRef = useRef(null);
const triggerObservabilityHook = useCallback((hookName, ...args) => {
if (publicApiKey && observabilityHooks?.[hookName]) observabilityHooks[hookName](...args);
if (observabilityHooks?.[hookName] && !publicApiKey) {
setBannerError(new CopilotKitError({
message: "observabilityHooks requires a publicApiKey to function.",
code: CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
severity: Severity.CRITICAL,
visibility: ErrorVisibility.BANNER
}));
styledConsole.publicApiKeyRequired("observabilityHooks");
}
}, [
publicApiKey,
observabilityHooks,
setBannerError
]);
const triggerChatError = useCallback((error, operation, originalError) => {
setChatError({
message: error?.message || error?.toString() || "An error occurred",
operation,
timestamp: Date.now()
});
const errorEvent = {
type: "error",
timestamp: Date.now(),
context: {
source: "ui",
request: {
operation,
url: chatApiEndpoint,
startTime: Date.now()
},
technical: {
environment: "browser",
userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
stackTrace: originalError instanceof Error ? originalError.stack : void 0
}
},
error
};
if (onError) onError(errorEvent);
if (publicApiKey && observabilityHooks?.onError) observabilityHooks.onError(errorEvent);
if (observabilityHooks?.onError && !publicApiKey) {
setBannerError(new CopilotKitError({
message: "observabilityHooks.onError requires a publicApiKey to function.",
code: CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
severity: Severity.CRITICAL,
visibility: ErrorVisibility.BANNER
}));
styledConsole.publicApiKeyRequired("observabilityHooks.onError");
}
}, [
publicApiKey,
chatApiEndpoint,
observabilityHooks,
setBannerError
]);
useEffect(() => {
const id = "chat-component";
setInternalErrorHandler({ [id]: (error) => {
if (!error) return;
triggerChatError(error.error, "sendMessage");
} });
return () => {
removeInternalErrorHandler?.(id);
};
}, [
triggerChatError,
setInternalErrorHandler,
removeInternalErrorHandler
]);
useEffect(() => {
if (!imageUploadsEnabled) return;
const handlePaste = async (e) => {
if (!e.target.parentElement?.classList.contains("copilotKitInput")) return;
const imageItems = Array.from(e.clipboardData?.items || []).filter((item) => item.type.startsWith("image/"));
if (imageItems.length === 0) return;
e.preventDefault();
const imagePromises = imageItems.map((item) => {
const file = item.getAsFile();
if (!file) return Promise.resolve(null);
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const base64String = (e.target?.result)?.split(",")[1];
if (base64String) resolve({
contentType: file.type,
bytes: base64String
});
else resolve(null);
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
});
try {
const loadedImages = (await Promise.all(imagePromises)).filter((img) => img !== null);
setSelectedImages((prev) => [...prev, ...loadedImages]);
} catch (error) {
triggerChatError(error, "processClipboardImages", error);
console.error("Error processing pasted images:", error);
}
};
document.addEventListener("paste", handlePaste);
return () => document.removeEventListener("paste", handlePaste);
}, [imageUploadsEnabled, triggerChatError]);
useEffect(() => {
if (!additionalInstructions?.length) {
setChatInstructions(instructions || "");
return;
}
setChatInstructions([
instructions,
"Additionally, follow these instructions:",
...additionalInstructions.map((instruction) => `- ${instruction}`)
].join("\n") || "");
}, [instructions, additionalInstructions]);
const { messages, isLoading, sendMessage, stopGeneration, reloadMessages, suggestions: currentSuggestions, isLoadingSuggestions, agent } = useCopilotChatInternal({
suggestions,
onInProgress,
onSubmitMessage,
onStopGeneration,
onReloadMessages
});
const prevIsLoading = useRef(isLoading);
useEffect(() => {
if (prevIsLoading.current !== isLoading) {
if (isLoading) triggerObservabilityHook("onChatStarted");
else triggerObservabilityHook("onChatStopped");
prevIsLoading.current = isLoading;
}
}, [isLoading, triggerObservabilityHook]);
const handleSendMessage = (text) => {
setSelectedImages([]);
if (fileInputRef.current) fileInputRef.current.value = "";
triggerObservabilityHook("onMessageSent", text);
return sendMessage({
id: randomUUID(),
content: text,
role: "user"
});
};
const chatContext = React.useContext(ChatContext);
const isVisible = chatContext ? chatContext.open : true;
const handleRegenerate = (messageId) => {
if (onRegenerate) onRegenerate(messageId);
triggerObservabilityHook("onMessageRegenerated", messageId);
reloadMessages(messageId);
};
const handleCopy = (message) => {
if (onCopy) onCopy(message);
triggerObservabilityHook("onMessageCopied", message);
};
const handleImageUpload = async (event) => {
if (!event.target.files || event.target.files.length === 0) return;
const files = Array.from(event.target.files).filter((file) => file.type.startsWith("image/"));
if (files.length === 0) return;
const fileReadPromises = files.map((file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const base64String = (e.target?.result)?.split(",")[1] || "";
if (base64String) resolve({
contentType: file.type,
bytes: base64String
});
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
});
try {
const loadedImages = await Promise.all(fileReadPromises);
setSelectedImages((prev) => [...prev, ...loadedImages]);
} catch (error) {
triggerChatError(error, "processUploadedImages", error);
console.error("Error reading files:", error);
}
};
const removeSelectedImage = (index) => {
setSelectedImages((prev) => prev.filter((_, i) => i !== index));
};
const handleThumbsUp = (message) => {
if (onThumbsUp) onThumbsUp(message);
setMessageFeedback((prev) => ({
...prev,
[message.id]: "thumbsUp"
}));
triggerObservabilityHook("onFeedbackGiven", message.id, "thumbsUp");
};
const handleThumbsDown = (message) => {
if (onThumbsDown) onThumbsDown(message);
setMessageFeedback((prev) => ({
...prev,
[message.id]: "thumbsDown"
}));
triggerObservabilityHook("onFeedbackGiven", message.id, "thumbsDown");
};
return /* @__PURE__ */ jsxs(WrappedCopilotChat, {
icons,
labels,
className,
children: [
chatError && renderError && renderError({
...chatError,
onDismiss: () => setChatError(null),
onRetry: () => {
setChatError(null);
}
}),
/* @__PURE__ */ jsx(Messages$2, {
AssistantMessage: AssistantMessage$2,
UserMessage: UserMessage$3,
RenderMessage: RenderMessage$1,
messages,
inProgress: isLoading,
onRegenerate: handleRegenerate,
onCopy: handleCopy,
onThumbsUp: handleThumbsUp,
onThumbsDown: handleThumbsDown,
messageFeedback,
markdownTagRenderers,
ImageRenderer: ImageRenderer$1,
ErrorMessage,
chatError,
RenderTextMessage,
RenderActionExecutionMessage,
RenderAgentStateMessage,
RenderResultMessage,
RenderImageMessage,
children: currentSuggestions.length > 0 && /* @__PURE__ */ jsx(RenderSuggestionsList, {
onSuggestionClick: handleSendMessage,
suggestions: currentSuggestions,
isLoading: isLoadingSuggestions
})
}),
imageUploadsEnabled && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ImageUploadQueue, {
images: selectedImages,
onRemoveImage: removeSelectedImage
}), /* @__PURE__ */ jsx("input", {
type: "file",
multiple: true,
ref: fileInputRef,
onChange: handleImageUpload,
accept: inputFileAccept,
style: { display: "none" }
})] }),
/* @__PURE__ */ jsx(Input$2, {
inProgress: isLoading,
chatReady: Boolean(agent),
onSend: handleSendMessage,
isVisible,
onStop: stopGeneration,
onUpload: imageUploadsEnabled ? () => fileInputRef.current?.click() : void 0,
hideStopButton
})
]
});
}
function WrappedCopilotChat({ children, icons, labels, className }) {
if (!React.useContext(ChatContext)) return /* @__PURE__ */ jsx(ChatContextProvider, {
icons,
labels,
open: true,
setOpen: () => {},
children: /* @__PURE__ */ jsx("div", {
className: `copilotKitChat ${className ?? ""}`,
children
})
});
return /* @__PURE__ */ jsx(Fragment, { children });
}
//#endregion
//#region src/components/chat/Modal.tsx
const CopilotModalInner = ({ observabilityHooks, onSetOpen, clickOutsideToClose, hitEscapeToClose, shortcut, className, children, Window, Button, Header, ...chatProps }) => {
const { copilotApiConfig, setBannerError } = useCopilotContext();
const { publicApiKey } = copilotApiConfig;
const triggerObservabilityHook = useCallback((hookName, ...args) => {
if (publicApiKey && observabilityHooks?.[hookName]) observabilityHooks[hookName](...args);
if (observabilityHooks?.[hookName] && !publicApiKey) {
setBannerError(new CopilotKitError({
message: "observabilityHooks requires a publicApiKey to function.",
code: CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
severity: Severity.CRITICAL,
visibility: ErrorVisibility.BANNER
}));
styledConsole.publicApiKeyRequired("observabilityHooks");
}
}, [
publicApiKey,
observabilityHooks,
setBannerError
]);
const { open } = useChatContext();
const prevOpen = useRef(open);
useEffect(() => {
if (prevOpen.current !== open) {
onSetOpen?.(open);
if (open) triggerObservabilityHook("onChatExpanded");
else triggerObservabilityHook("onChatMinimized");
prevOpen.current = open;
}
}, [
open,
onSetOpen,
triggerObservabilityHook
]);
const memoizedHeader = useMemo(() => /* @__PURE__ */ jsx(Header, {}), [Header]);
return /* @__PURE__ */ jsxs(Fragment, { children: [useMemo(() => children, [children]), /* @__PURE__ */ jsxs("div", {
className,
children: [/* @__PURE__ */ jsx(Button, {}), /* @__PURE__ */ jsxs(Window, {
clickOutsideToClose,
shortcut,
hitEscapeToClose,
children: [memoizedHeader, /* @__PURE__ */ jsx(CopilotChat, {
...chatProps,
observabilityHooks
})]
})]
})] });
};
const CopilotModal = ({ instructions, defaultOpen = false, clickOutsideToClose = true, hitEscapeToClose = true, onSetOpen, onSubmitMessage, onStopGeneration, onReloadMessages, shortcut = "/", icons, labels, makeSystemMessage, onInProgress, Window: Window$1 = Window, Button: Button$1 = Button, Header: Header$1 = Header, Messages: Messages$1 = Messages, Input: Input$1 = Input, AssistantMessage: AssistantMessage$1 = AssistantMessage, UserMessage: UserMessage$2 = UserMessage, onThumbsUp, onThumbsDown, onCopy, onRegenerate, markdownTagRenderers, className, children, observabilityHooks, ...props }) => {
const [openState, setOpenState] = React.useState(defaultOpen);
return /* @__PURE__ */ jsx(ChatContextProvider, {
icons,
labels,
open: openState,
setOpen: setOpenState,
children: /* @__PURE__ */ jsx(CopilotModalInner, {
observabilityHooks,
onSetOpen,
clickOutsideToClose: clickOutsideToClose ?? true,
hitEscapeToClose: hitEscapeToClose ?? true,
shortcut: shortcut ?? "/",
className,
Window: Window$1,
Button: Button$1,
Header: Header$1,
instructions,
onSubmitMessage,
onStopGeneration,
onReloadMessages,
makeSystemMessage,
onInProgress,
Messages: Messages$1,
Input: Input$1,
AssistantMessage: AssistantMessage$1,
UserMessage: UserMessage$2,
onThumbsUp,
onThumbsDown,
onCopy,
onRegenerate,
markdownTagRenderers,
...props,
children
})
});
};
//#endregion
//#region src/components/chat/Popup.tsx
/**
* <br/>
* <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/CopilotPopup.gif" width="500" />
*
* A chatbot popup component for the CopilotKit framework. The component allows for a high degree
* of customization through various props and custom CSS.
*
* See [CopilotSidebar](/reference/v1/components/chat/CopilotSidebar) for a sidebar version of this component.
*
* ## Install Dependencies
*
* This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.
*
* ```shell npm2yarn \"@copilotkit/react-ui"\
* npm install @copilotkit/react-core @copilotkit/react-ui
* ```
* ## Usage
*
* ```tsx
* import { CopilotPopup } from "@copilotkit/react-ui";
* import "@copilotkit/react-ui/styles.css";
*
* <CopilotPopup
* labels={{
* title: "Your Assistant",
* initial: "Hi! 👋 How can I assist you today?",
* }}
* />
* ```
*
* ### With Observability Hooks
*
* To monitor user interactions, provide the `observabilityHooks` prop.
* **Note:** This requires a `publicApiKey` in the `<CopilotKit>` provider.
*
* ```tsx
* <CopilotKit publicApiKey="YOUR_PUBLIC_API_KEY">
* <CopilotPopup
* observabilityHooks={{
* onChatExpanded: () => {
* console.log("Popup opened");
* },
* onChatMinimized: () => {
* console.log("Popup closed");
* },
* }}
* />
* </CopilotKit>
* ```
*
* ### Look & Feel
*
* By default, CopilotKit components do not have any styles. You can import CopilotKit's stylesheet at the root of your project:
* ```tsx title="YourRootComponent.tsx"
* ...
* import "@copilotkit/react-ui/styles.css"; // [!code highlight]
*
* export function YourRootComponent() {
* return (
* <CopilotKit>
* ...
* </CopilotKit>
* );
* }
* ```
* For more information about how to customize the styles, check out the [Customize Look & Feel](/guides/custom-look-and-feel/customize-built-in-ui-components) guide.
*/
function CopilotPopup(props) {
props = {
...props,
className: props.className ? props.className + " copilotKitPopup" : "copilotKitPopup"
};
return /* @__PURE__ */ jsx(CopilotModal, {
...props,
children: props.children
});
}
//#endregion
//#region src/components/chat/Sidebar.tsx
/**
* <br/>
* <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/CopilotSidebar.gif" width="500" />
*
* A chatbot sidebar component for the CopilotKit framework. Highly customizable through various props and custom CSS.
*
* See [CopilotPopup](/reference/v1/components/chat/CopilotPopup) for a popup version of this component.
*
* ## Install Dependencies
*
* This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.
*
* ```shell npm2yarn \"@copilotkit/react-ui"\
* npm install @copilotkit/react-core @copilotkit/react-ui
* ```
*
* ## Usage
*
* ```tsx
* import { CopilotSidebar } from "@copilotkit/react-ui";
* import "@copilotkit/react-ui/styles.css";
*
* <CopilotSidebar
* labels={{
* title: "Your Assistant",
* initial: "Hi! 👋 How can I assist you today?",
* }}
* >
* <YourApp/>
* </CopilotSidebar>
* ```
*
* ### With Observability Hooks
*
* To monitor user interactions, provide the `observabilityHooks` prop.
* **Note:** This requires a `publicApiKey` in the `<CopilotKit>` provider.
*
* ```tsx
* <CopilotKit publicApiKey="YOUR_PUBLIC_API_KEY">
* <CopilotSidebar
* observabilityHooks={{
* onChatExpanded: () => {
* console.log("Sidebar opened");
* },
* onChatMinimized: () => {
* console.log("Sidebar closed");
* },
* }}
* >
* <YourApp/>
* </CopilotSidebar>
* </CopilotKit>
* ```
*
* ### Look & Feel
*
* By default, CopilotKit components do not have any styles. You can import CopilotKit's stylesheet at the root of your project:
* ```tsx title="YourRootComponent.tsx"
* ...
* import "@copilotkit/react-ui/styles.css"; // [!code highlight]
*
* export function YourRootComponent() {
* return (
* <CopilotKit>
* ...
* </CopilotKit>
* );
* }
* ```
* For more information about how to customize the styles, check out the [Customize Look & Feel](/guides/custom-look-and-feel/customize-built-in-ui-components) guide.
*/
function CopilotSidebar(props) {
props = {
...props,
className: props.className ? props.className + " copilotKitSidebar" : "copilotKitSidebar"
};
const [expandedClassName, setExpandedClassName] = useState(props.defaultOpen ? "sidebarExpanded" : "");
const onSetOpen = (open) => {
props.onSetOpen?.(open);
setExpandedClassName(open ? "sidebarExpanded" : "");
};
return /* @__PURE__ */ jsx("div", {
className: `copilotKitSidebarContentWrapper ${expandedClassName}`,
children: /* @__PURE__ */ jsx(CopilotModal, {
...props,
onSetOpen,
children: props.children
})
});
}
//#endregion
//#region src/hooks/use-copilot-chat-suggestions.tsx
/**
* <Callout type="warning">
* useCopilotChatSuggestions is experimental. The interface is not final and
* can change without notice.
* </Callout>
*
* `useCopilotReadable` is a React hook that provides app-state and other information
* to the Copilot. Optionally, the hook can also handle hierarchical state within your
* application, passing these parent-child relationships to the Copilot.
*
* <br/>
* <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-chat-suggestions/use-copilot-chat-suggestions.gif" width="500" />
*
* ## Usage
*
* ### Install Dependencies
*
* This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.
*
* ```shell npm2yarn \"@copilotkit/react-ui"\
* npm install @copilotkit/react-core @copilotkit/react-ui
* ```
*
* ### Simple Usage
*
* ```tsx
* import { useCopilotChatSuggestions } from "@copilotkit/react-ui";
*
* export function MyComponent() {
* const [employees, setEmployees] = useState([]);
*
* useCopilotChatSuggestions({
* instructions: `The following employees are on duty: ${JSON.stringify(employees)}`,
* });
* }
* ```
*
* ### Dependency Management
*
* ```tsx
* import { useCopilotChatSuggestions } from "@copilotkit/react-ui";
*
* export function MyComponent() {
* useCopilotChatSuggestions(
* {
* instructions: "Suggest the most relevant next actions.",
* },
* [appState],
* );
* }
* ```
*
* In the example above, the suggestions are generated based on the given instructions.
* The hook monitors `appState`, and updates suggestions accordingly whenever it changes.
*
* ### Behavior and Lifecycle
*
* The hook registers the configuration with the chat context upon component mount and
* removes it on unmount, ensuring a clean and efficient lifecycle management.
*/
function useCopilotChatSuggestions(config, dependencies = []) {
useCopilotChatSuggestions$1(config, dependencies);
}
//#endregion
export { AssistantMessage, CopilotChat, CopilotDevConsole, CopilotPopup, CopilotSidebar, ImageRenderer, Markdown, Suggestion as RenderSuggestion, Suggestions as RenderSuggestionsList, UserMessage, shouldShowDevConsole, useChatContext, useCopilotChatSuggestions };
//# sourceMappingURL=index.mjs.map