"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};

// src/components/chat/Chat.tsx
var Chat_exports = {};
__export(Chat_exports, {
  CopilotChat: () => CopilotChat,
  WrappedCopilotChat: () => WrappedCopilotChat,
  useCopilotChatLogic: () => useCopilotChatLogic
});
module.exports = __toCommonJS(Chat_exports);

// src/components/chat/ChatContext.tsx
var import_react = __toESM(require("react"));

// src/components/chat/Icons.tsx
var import_jsx_runtime = require("react/jsx-runtime");
var OpenIcon = /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
  "svg",
  {
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 24 24",
    fill: "currentColor",
    width: "24",
    height: "24",
    children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("g", { transform: "translate(24, 0) scale(-1, 1)", children: /* @__PURE__ */ (0, import_jsx_runtime.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"
      }
    ) })
  }
);
var CloseIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.jsx)("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M19.5 8.25l-7.5 7.5-7.5-7.5" })
  }
);
var HeaderCloseIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.jsx)("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 18L18 6M6 6l12 12" })
  }
);
var SendIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.jsx)("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 19V5m0 0l-7 7m7-7l7 7" })
  }
);
var MicrophoneIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.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"
      }
    )
  }
);
var StopIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.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"
      }
    )
  }
);
var RegenerateIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.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"
      }
    )
  }
);
var CopyIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.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"
      }
    )
  }
);
var SmallSpinnerIcon = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "copilotKitSpinner", style: { width: "13px", height: "13px" } });
var SpinnerIcon = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "copilotKitSpinner", style: { width: "24px", height: "24px" } });
var ActivityIcon = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: "4px" }, children: [
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "copilotKitActivityDot", style: { animationDelay: "0s" } }),
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "copilotKitActivityDot", style: { animationDelay: "0.2s" } }),
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "copilotKitActivityDot", style: { animationDelay: "0.4s" } })
] });
var ThumbsUpIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.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"
      }
    )
  }
);
var ThumbsDownIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.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"
      }
    )
  }
);
var DownloadIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.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"
      }
    )
  }
);
var UploadIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.jsx)("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 4.5v15m7.5-7.5h-15" })
  }
);
var CheckIcon = /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.jsx)("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M4.5 12.75l6 6 9-13.5" })
  }
);

// src/components/chat/ChatContext.tsx
var import_jsx_runtime2 = require("react/jsx-runtime");
var ChatContext = import_react.default.createContext(void 0);
function useChatContext() {
  const context = import_react.default.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;
}
var ChatContextProvider = ({
  // temperature,
  // instructions,
  // maxFeedback,
  labels,
  icons,
  children,
  open,
  setOpen
}) => {
  const memoizedLabels = (0, import_react.useMemo)(
    () => __spreadValues(__spreadValues({}, {
      initial: "",
      title: "CopilotKit",
      placeholder: "Type a message...",
      error: "\u274C 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 = (0, import_react.useMemo)(
    () => __spreadValues(__spreadValues({}, {
      openIcon: OpenIcon,
      closeIcon: CloseIcon,
      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 = (0, import_react.useMemo)(
    () => ({
      labels: memoizedLabels,
      icons: memoizedIcons,
      open,
      setOpen
    }),
    [memoizedLabels, memoizedIcons, open, setOpen]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ChatContext.Provider, { value: context, children });
};

// src/components/chat/Messages.tsx
var import_react6 = require("react");
var import_react_core = require("@copilotkit/react-core");

// src/components/chat/messages/UserMessage.tsx
var import_jsx_runtime3 = require("react/jsx-runtime");
var UserMessage = (props) => {
  const { message, ImageRenderer: ImageRenderer2 } = props;
  const isImageMessage = message && "image" in message && message.image;
  if (isImageMessage) {
    const imageMessage = message;
    return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "copilotKitMessage copilotKitUserMessage", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ImageRenderer2, { image: imageMessage.image, content: imageMessage.content }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "copilotKitMessage copilotKitUserMessage", children: message == null ? void 0 : message.content });
};

// src/components/chat/Markdown.tsx
var import_react3 = require("react");
var import_react_markdown = __toESM(require("react-markdown"));

// src/components/chat/CodeBlock.tsx
var import_react2 = require("react");
var import_react_syntax_highlighter = require("react-syntax-highlighter");

// src/hooks/use-copy-to-clipboard.tsx
var React2 = __toESM(require("react"));
function useCopyToClipboard({ timeout = 2e3 }) {
  const [isCopied, setIsCopied] = React2.useState(false);
  const copyToClipboard = (value) => {
    var _a;
    if (typeof window === "undefined" || !((_a = navigator.clipboard) == null ? void 0 : _a.writeText)) {
      return;
    }
    if (!value) {
      return;
    }
    navigator.clipboard.writeText(value).then(() => {
      setIsCopied(true);
      setTimeout(() => {
        setIsCopied(false);
      }, timeout);
    });
  };
  return { isCopied, copyToClipboard };
}

// src/components/chat/CodeBlock.tsx
var import_jsx_runtime4 = require("react/jsx-runtime");
var 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"
  // add more file extensions here, make sure the key is same as language prop in CodeBlock.tsx component
};
var generateRandomString = (length, lowercase = false) => {
  const chars = "ABCDEFGHJKLMNPQRSTUVWXY3456789";
  let result = "";
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return lowercase ? result.toLowerCase() : result;
};
var CodeBlock = (0, import_react2.memo)(({ language, value }) => {
  const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2e3 });
  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__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "copilotKitCodeBlock", children: [
    /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "copilotKitCodeBlockToolbar", children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { className: "copilotKitCodeBlockToolbarLanguage", children: language }),
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "copilotKitCodeBlockToolbarButtons", children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("button", { className: "copilotKitCodeBlockToolbarButton", onClick: downloadAsFile, children: DownloadIcon }),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("button", { className: "copilotKitCodeBlockToolbarButton", onClick: onCopy, children: isCopied ? CheckIcon : CopyIcon })
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
      import_react_syntax_highlighter.Prism,
      {
        language,
        style: highlightStyle,
        PreTag: "div",
        customStyle: {
          margin: 0,
          borderBottomLeftRadius: "0.375rem",
          borderBottomRightRadius: "0.375rem"
        },
        children: value
      }
    )
  ] });
});
CodeBlock.displayName = "CodeBlock";
var 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"
  }
};

// src/components/chat/Markdown.tsx
var import_remark_gfm = __toESM(require("remark-gfm"));
var import_remark_math = __toESM(require("remark-math"));
var import_rehype_raw = __toESM(require("rehype-raw"));
var import_jsx_runtime5 = require("react/jsx-runtime");
var defaultComponents = {
  a(_a) {
    var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("a", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { target: "_blank", rel: "noopener noreferrer", children }));
  },
  // @ts-expect-error -- inline
  code(_c) {
    var _d = _c, { children, className, inline } = _d, props = __objRest(_d, ["children", "className", "inline"]);
    if (Array.isArray(children) && children.length) {
      if (children[0] == "\u258D") {
        return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
          "span",
          {
            style: {
              animation: "pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",
              marginTop: "0.25rem"
            },
            children: "\u258D"
          }
        );
      }
      children[0] = (children == null ? void 0 : children[0]).replace("`\u258D`", "\u258D");
    }
    const match = /language-(\w+)/.exec(className || "");
    const hasLanguage = match && match[1];
    const content = String(children);
    const hasNewlines = content.includes("\n");
    const isInline = !hasLanguage && !hasNewlines;
    if (isInline) {
      return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
        "code",
        __spreadProps(__spreadValues({
          className: `copilotKitMarkdownElement copilotKitInlineCode ${className || ""}`
        }, props), {
          children
        })
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
      CodeBlock,
      __spreadValues({
        language: match && match[1] || "",
        value: String(children).replace(/\n$/, "")
      }, props),
      Math.random()
    );
  },
  h1: (_e) => {
    var _f = _e, { children } = _f, props = __objRest(_f, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("h1", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { children }));
  },
  h2: (_g) => {
    var _h = _g, { children } = _h, props = __objRest(_h, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("h2", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { children }));
  },
  h3: (_i) => {
    var _j = _i, { children } = _j, props = __objRest(_j, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("h3", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { children }));
  },
  h4: (_k) => {
    var _l = _k, { children } = _l, props = __objRest(_l, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("h4", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { children }));
  },
  h5: (_m) => {
    var _n = _m, { children } = _n, props = __objRest(_n, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("h5", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { children }));
  },
  h6: (_o) => {
    var _p = _o, { children } = _p, props = __objRest(_p, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("h6", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { children }));
  },
  p: (_q) => {
    var _r = _q, { children } = _r, props = __objRest(_r, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { children }));
  },
  pre: (_s) => {
    var _t = _s, { children } = _t, props = __objRest(_t, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("pre", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { children }));
  },
  blockquote: (_u) => {
    var _v = _u, { children } = _v, props = __objRest(_v, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("blockquote", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { children }));
  },
  ul: (_w) => {
    var _x = _w, { children } = _x, props = __objRest(_x, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("ul", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { children }));
  },
  li: (_y) => {
    var _z = _y, { children } = _z, props = __objRest(_z, ["children"]);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("li", __spreadProps(__spreadValues({ className: "copilotKitMarkdownElement" }, props), { children }));
  }
};
var MemoizedReactMarkdown = (0, import_react3.memo)(
  import_react_markdown.default,
  (prevProps, nextProps) => prevProps.children === nextProps.children && prevProps.components === nextProps.components
);
var Markdown = ({ content, components }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "copilotKitMarkdown", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
    MemoizedReactMarkdown,
    {
      components: __spreadValues(__spreadValues({}, defaultComponents), components),
      remarkPlugins: [import_remark_gfm.default, [import_remark_math.default, { singleDollarTextMath: false }]],
      rehypePlugins: [import_rehype_raw.default],
      children: content
    }
  ) });
};

// src/components/chat/messages/AssistantMessage.tsx
var import_react4 = require("react");
var import_jsx_runtime6 = require("react/jsx-runtime");
var AssistantMessage = (props) => {
  var _a;
  const { icons, labels } = useChatContext();
  const {
    message,
    isLoading,
    onRegenerate,
    onCopy,
    onThumbsUp,
    onThumbsDown,
    isCurrentMessage,
    markdownTagRenderers
  } = props;
  const [copied, setCopied] = (0, import_react4.useState)(false);
  const handleCopy = () => {
    const content2 = (message == null ? void 0 : message.content) || "";
    if (content2 && onCopy) {
      navigator.clipboard.writeText(content2);
      setCopied(true);
      onCopy(content2);
      setTimeout(() => setCopied(false), 2e3);
    } else if (content2) {
      navigator.clipboard.writeText(content2);
      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__ */ (0, import_jsx_runtime6.jsx)("span", { children: icons.activityIcon });
  const content = (message == null ? void 0 : message.content) || "";
  const subComponent = (_a = message == null ? void 0 : message.generativeUI) == null ? void 0 : _a.call(message);
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_jsx_runtime6.Fragment, { children: [
    content && /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "copilotKitMessage copilotKitAssistantMessage", children: [
      content && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Markdown, { content, components: markdownTagRenderers }),
      content && !isLoading && /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
        "div",
        {
          className: `copilotKitMessageControls ${isCurrentMessage ? "currentMessage" : ""}`,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
              "button",
              {
                className: "copilotKitMessageControlButton",
                onClick: handleRegenerate,
                "aria-label": labels.regenerateResponse,
                title: labels.regenerateResponse,
                children: icons.regenerateIcon
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
              "button",
              {
                className: "copilotKitMessageControlButton",
                onClick: handleCopy,
                "aria-label": labels.copyToClipboard,
                title: labels.copyToClipboard,
                children: copied ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { style: { fontSize: "10px", fontWeight: "bold" }, children: "\u2713" }) : icons.copyIcon
              }
            ),
            onThumbsUp && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
              "button",
              {
                className: "copilotKitMessageControlButton",
                onClick: handleThumbsUp,
                "aria-label": labels.thumbsUp,
                title: labels.thumbsUp,
                children: icons.thumbsUpIcon
              }
            ),
            onThumbsDown && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
              "button",
              {
                className: "copilotKitMessageControlButton",
                onClick: handleThumbsDown,
                "aria-label": labels.thumbsDown,
                title: labels.thumbsDown,
                children: icons.thumbsDownIcon
              }
            )
          ]
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("div", { style: { marginBottom: "0.5rem" }, children: subComponent }),
    isLoading && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(LoadingIcon, {})
  ] });
};

// src/components/chat/messages/ImageRenderer.tsx
var import_react5 = require("react");
var import_jsx_runtime7 = require("react/jsx-runtime");
var ImageRenderer = ({ image, content, className = "" }) => {
  const [imageError, setImageError] = (0, import_react5.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__ */ (0, import_jsx_runtime7.jsxs)("div", { className: `copilotKitImageRendering copilotKitImageRenderingError ${className}`, children: [
      /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { className: "copilotKitImageRenderingErrorMessage", children: "Failed to load image" }),
      content && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { className: "copilotKitImageRenderingContent", children: content })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: `copilotKitImageRendering ${className}`, children: [
    /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
      "img",
      {
        src: imageSrc,
        alt: altText,
        className: "copilotKitImageRenderingImage",
        onError: handleImageError
      }
    ),
    content && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { className: "copilotKitImageRenderingContent", children: content })
  ] });
};

// src/components/chat/messages/RenderMessage.tsx
var import_jsx_runtime8 = require("react/jsx-runtime");
function RenderMessage(_a) {
  var _b = _a, {
    UserMessage: UserMessage2 = UserMessage,
    AssistantMessage: AssistantMessage2 = AssistantMessage,
    ImageRenderer: ImageRenderer2 = ImageRenderer
  } = _b, props = __objRest(_b, [
    "UserMessage",
    "AssistantMessage",
    "ImageRenderer"
  ]);
  var _a2;
  const {
    message,
    inProgress,
    index,
    isCurrentMessage,
    onRegenerate,
    onCopy,
    onThumbsUp,
    onThumbsDown,
    markdownTagRenderers
  } = props;
  switch (message.role) {
    case "user":
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        UserMessage2,
        {
          rawData: message,
          "data-message-role": "user",
          message,
          ImageRenderer: ImageRenderer2
        },
        index
      );
    case "assistant":
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        AssistantMessage2,
        {
          "data-message-role": "assistant",
          subComponent: (_a2 = message.generativeUI) == null ? void 0 : _a2.call(message),
          rawData: message,
          message,
          isLoading: inProgress && isCurrentMessage && !message.content,
          isGenerating: inProgress && isCurrentMessage && !!message.content,
          isCurrentMessage,
          onRegenerate: () => onRegenerate == null ? void 0 : onRegenerate(message.id),
          onCopy,
          onThumbsUp,
          onThumbsDown,
          markdownTagRenderers,
          ImageRenderer: ImageRenderer2
        },
        index
      );
  }
}

// src/components/chat/messages/LegacyRenderMessage.tsx
var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
var import_jsx_runtime9 = require("react/jsx-runtime");
var LegacyRenderMessage = ({
  message,
  inProgress,
  index,
  isCurrentMessage,
  actionResult,
  AssistantMessage: AssistantMessage2,
  UserMessage: UserMessage2,
  ImageRenderer: ImageRenderer2,
  onRegenerate,
  onCopy,
  onThumbsUp,
  onThumbsDown,
  markdownTagRenderers,
  legacyProps
}) => {
  var _a;
  const {
    RenderTextMessage,
    RenderActionExecutionMessage,
    RenderAgentStateMessage,
    RenderResultMessage,
    RenderImageMessage
  } = legacyProps;
  const deprecatedMessage = (_a = (0, import_runtime_client_gql.aguiToGQL)(message)[0]) != null ? _a : void 0;
  if (deprecatedMessage.isTextMessage() && RenderTextMessage) {
    return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
      RenderTextMessage,
      {
        message,
        inProgress,
        index,
        isCurrentMessage,
        AssistantMessage: AssistantMessage2,
        UserMessage: UserMessage2,
        onRegenerate,
        onCopy,
        onThumbsUp,
        onThumbsDown,
        markdownTagRenderers
      }
    );
  }
  if (deprecatedMessage.isActionExecutionMessage() && RenderActionExecutionMessage) {
    return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
      RenderActionExecutionMessage,
      {
        message,
        inProgress,
        index,
        isCurrentMessage,
        actionResult,
        AssistantMessage: AssistantMessage2,
        UserMessage: UserMessage2
      }
    );
  }
  if (deprecatedMessage.isAgentStateMessage() && RenderAgentStateMessage) {
    return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
      RenderAgentStateMessage,
      {
        message,
        inProgress,
        index,
        isCurrentMessage,
        AssistantMessage: AssistantMessage2,
        UserMessage: UserMessage2
      }
    );
  }
  if (deprecatedMessage.isResultMessage() && RenderResultMessage) {
    return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
      RenderResultMessage,
      {
        message,
        inProgress,
        index,
        isCurrentMessage,
        AssistantMessage: AssistantMessage2,
        UserMessage: UserMessage2
      }
    );
  }
  if (deprecatedMessage.isImageMessage() && RenderImageMessage) {
    return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
      RenderImageMessage,
      {
        message,
        inProgress,
        index,
        isCurrentMessage,
        AssistantMessage: AssistantMessage2,
        UserMessage: UserMessage2
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
    RenderMessage,
    {
      message,
      inProgress,
      index,
      isCurrentMessage,
      AssistantMessage: AssistantMessage2,
      UserMessage: UserMessage2,
      ImageRenderer: ImageRenderer2,
      onRegenerate,
      onCopy,
      onThumbsUp,
      onThumbsDown,
      markdownTagRenderers
    }
  );
};

// src/components/chat/Messages.tsx
var import_jsx_runtime10 = require("react/jsx-runtime");
var Messages = ({
  inProgress,
  children,
  RenderMessage: RenderMessage2,
  AssistantMessage: AssistantMessage2,
  UserMessage: UserMessage2,
  ImageRenderer: ImageRenderer2,
  onRegenerate,
  onCopy,
  onThumbsUp,
  onThumbsDown,
  markdownTagRenderers,
  // Legacy props
  RenderTextMessage,
  RenderActionExecutionMessage,
  RenderAgentStateMessage,
  RenderResultMessage,
  RenderImageMessage
}) => {
  const { labels } = useChatContext();
  const { messages: visibleMessages, interrupt } = (0, import_react_core.useCopilotChatInternal)();
  const initialMessages = (0, import_react6.useMemo)(() => makeInitialMessages(labels.initial), [labels.initial]);
  const messages = [...initialMessages, ...visibleMessages];
  const { messagesContainerRef, messagesEndRef } = useScrollToBottom(messages);
  const hasLegacyProps = !!(RenderTextMessage || RenderActionExecutionMessage || RenderAgentStateMessage || RenderResultMessage || RenderImageMessage);
  (0, import_react6.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 = (0, import_react6.useMemo)(
    () => ({
      RenderTextMessage,
      RenderActionExecutionMessage,
      RenderAgentStateMessage,
      RenderResultMessage,
      RenderImageMessage
    }),
    [
      RenderTextMessage,
      RenderActionExecutionMessage,
      RenderAgentStateMessage,
      RenderResultMessage,
      RenderImageMessage
    ]
  );
  const MessageRenderer = hasLegacyProps ? (props) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(LegacyRenderMessage, __spreadProps(__spreadValues({}, props), { legacyProps })) : RenderMessage2;
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: "copilotKitMessages", ref: messagesContainerRef, children: [
    /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: "copilotKitMessagesContainer", children: [
      messages.map((message, index) => {
        const isCurrentMessage = index === messages.length - 1;
        return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
          MessageRenderer,
          {
            message,
            inProgress,
            index,
            isCurrentMessage,
            AssistantMessage: AssistantMessage2,
            UserMessage: UserMessage2,
            ImageRenderer: ImageRenderer2,
            onRegenerate,
            onCopy,
            onThumbsUp,
            onThumbsDown,
            markdownTagRenderers
          },
          index
        );
      }),
      interrupt
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime10.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 = (0, import_react6.useRef)(null);
  const messagesContainerRef = (0, import_react6.useRef)(null);
  const isProgrammaticScrollRef = (0, import_react6.useRef)(false);
  const isUserScrollUpRef = (0, import_react6.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;
    }
  };
  (0, import_react6.useEffect)(() => {
    const container = messagesContainerRef.current;
    if (container) {
      container.addEventListener("scroll", handleScroll);
    }
    return () => {
      if (container) {
        container.removeEventListener("scroll", handleScroll);
      }
    };
  }, []);
  (0, import_react6.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();
    };
  }, []);
  (0, import_react6.useEffect)(() => {
    isUserScrollUpRef.current = false;
    scrollToBottom();
  }, [messages.filter((m) => m.role === "user").length]);
  return { messagesEndRef, messagesContainerRef };
}

// src/components/chat/Input.tsx
var import_react9 = require("react");

// src/components/chat/Textarea.tsx
var import_react7 = require("react");
var import_jsx_runtime11 = require("react/jsx-runtime");
var AutoResizingTextarea = (0, import_react7.forwardRef)(
  ({
    maxRows = 1,
    placeholder,
    value,
    onChange,
    onKeyDown,
    onCompositionStart,
    onCompositionEnd,
    autoFocus
  }, ref) => {
    const internalTextareaRef = (0, import_react7.useRef)(null);
    const [maxHeight, setMaxHeight] = (0, import_react7.useState)(0);
    (0, import_react7.useImperativeHandle)(ref, () => internalTextareaRef.current);
    (0, import_react7.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]);
    (0, import_react7.useEffect)(() => {
      const textarea = internalTextareaRef.current;
      if (textarea) {
        textarea.style.height = "auto";
        textarea.style.height = `${Math.min(textarea.scrollHeight, maxHeight)}px`;
      }
    }, [value, maxHeight]);
    return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
      "textarea",
      {
        ref: internalTextareaRef,
        value,
        onChange,
        onKeyDown,
        onCompositionStart,
        onCompositionEnd,
        placeholder,
        style: {
          overflow: "auto",
          resize: "none",
          maxHeight: `${maxHeight}px`
        },
        rows: 1
      }
    );
  }
);
var Textarea_default = AutoResizingTextarea;

// src/hooks/use-push-to-talk.tsx
var import_react_core2 = require("@copilotkit/react-core");
var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
var import_react8 = require("react");
var startRecording = (mediaStreamRef, mediaRecorderRef, audioContextRef, recordedChunks, onStop) => __async(void 0, null, function* () {
  if (!mediaStreamRef.current || !audioContextRef.current) {
    mediaStreamRef.current = yield navigator.mediaDevices.getUserMedia({ audio: true });
    audioContextRef.current = new window.AudioContext();
    yield 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;
});
var stopRecording = (mediaRecorderRef) => {
  if (mediaRecorderRef.current && mediaRecorderRef.current.state !== "inactive") {
    mediaRecorderRef.current.stop();
  }
};
var transcribeAudio = (recordedChunks, transcribeAudioUrl) => __async(void 0, null, function* () {
  const completeBlob = new Blob(recordedChunks, { type: "audio/mp4" });
  const formData = new FormData();
  formData.append("file", completeBlob, "recording.mp4");
  const response = yield fetch(transcribeAudioUrl, {
    method: "POST",
    body: formData
  });
  if (!response.ok) {
    throw new Error(`Error: ${response.statusText}`);
  }
  const transcription = yield response.json();
  return transcription.text;
});
var playAudioResponse = (text, textToSpeechUrl, audioContext) => {
  const encodedText = encodeURIComponent(text);
  const url = `${textToSpeechUrl}?text=${encodedText}`;
  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);
  });
};
var usePushToTalk = ({
  sendFunction,
  inProgress
}) => {
  const [pushToTalkState, setPushToTalkState] = (0, import_react8.useState)("idle");
  const mediaStreamRef = (0, import_react8.useRef)(null);
  const audioContextRef = (0, import_react8.useRef)(null);
  const mediaRecorderRef = (0, import_react8.useRef)(null);
  const recordedChunks = (0, import_react8.useRef)([]);
  const generalContext = (0, import_react_core2.useCopilotContext)();
  const messagesContext = (0, import_react_core2.useCopilotMessagesContext)();
  const context = __spreadValues(__spreadValues({}, generalContext), messagesContext);
  const [startReadingFromMessageId, setStartReadingFromMessageId] = (0, import_react8.useState)(null);
  (0, import_react8.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(
          (transcription) => __async(void 0, null, function* () {
            recordedChunks.current = [];
            setPushToTalkState("idle");
            const message = yield sendFunction(transcription);
            setStartReadingFromMessageId(message.id);
          })
        );
      }
    }
    return () => {
      stopRecording(mediaRecorderRef);
    };
  }, [pushToTalkState]);
  (0, import_react8.useEffect)(() => {
    if (inProgress === false && startReadingFromMessageId) {
      const lastMessageIndex = context.messages.findIndex(
        (message) => message.id === startReadingFromMessageId
      );
      const aguiMessages = (0, import_runtime_client_gql2.gqlToAGUI)(context.messages);
      const messagesAfterLast = aguiMessages.slice(lastMessageIndex + 1).filter((message) => message.role === "assistant");
      const text = messagesAfterLast.map((message) => message.content).join("\n");
      playAudioResponse(text, context.copilotApiConfig.textToSpeechUrl, audioContextRef.current);
      setStartReadingFromMessageId(null);
    }
  }, [startReadingFromMessageId, inProgress]);
  return { pushToTalkState, setPushToTalkState };
};

// src/components/chat/Input.tsx
var import_react_core3 = require("@copilotkit/react-core");

// src/hooks/use-dark-mode.ts
var 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;
};

// src/components/chat/PoweredByTag.tsx
var import_jsx_runtime12 = require("react/jsx-runtime");
function PoweredByTag({ showPoweredBy = true }) {
  const isDark = useDarkMode();
  if (!showPoweredBy) {
    return null;
  }
  const poweredByStyle = {
    visibility: "visible",
    display: "block",
    position: "static",
    textAlign: "center",
    fontSize: "12px",
    padding: "3px 0",
    color: isDark ? "rgb(69, 69, 69)" : "rgb(214, 214, 214)"
  };
  return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("p", { className: "poweredBy", style: poweredByStyle, children: "Powered by CopilotKit" }) });
}

// src/components/chat/Input.tsx
var import_jsx_runtime13 = require("react/jsx-runtime");
var MAX_NEWLINES = 6;
var Input = ({
  inProgress,
  onSend,
  isVisible = false,
  onStop,
  onUpload,
  hideStopButton = false
}) => {
  var _a, _b;
  const context = useChatContext();
  const copilotContext = (0, import_react_core3.useCopilotContext)();
  const showPoweredBy = !((_a = copilotContext.copilotApiConfig) == null ? void 0 : _a.publicApiKey);
  const pushToTalkConfigured = copilotContext.copilotApiConfig.textToSpeechUrl !== void 0 && copilotContext.copilotApiConfig.transcribeAudioUrl !== void 0;
  const textareaRef = (0, import_react9.useRef)(null);
  const [isComposing, setIsComposing] = (0, import_react9.useState)(false);
  const handleDivClick = (event) => {
    var _a2;
    const target = event.target;
    if (target.closest("button"))
      return;
    if (target.tagName === "TEXTAREA")
      return;
    (_a2 = textareaRef.current) == null ? void 0 : _a2.focus();
  };
  const [text, setText] = (0, import_react9.useState)("");
  const send = () => {
    var _a2;
    if (inProgress)
      return;
    onSend(text);
    setText("");
    (_a2 = textareaRef.current) == null ? void 0 : _a2.focus();
  };
  const { pushToTalkState, setPushToTalkState } = usePushToTalk({
    sendFunction: onSend,
    inProgress
  });
  const isInProgress = inProgress || pushToTalkState === "transcribing";
  const buttonIcon = isInProgress && !hideStopButton ? context.icons.stopIcon : context.icons.sendIcon;
  const showPushToTalk = pushToTalkConfigured && (pushToTalkState === "idle" || pushToTalkState === "recording") && !inProgress;
  const canSend = (0, import_react9.useMemo)(() => {
    var _a2;
    const interruptEvent = (_a2 = copilotContext.langGraphInterruptAction) == null ? void 0 : _a2.event;
    const interruptInProgress = (interruptEvent == null ? void 0 : interruptEvent.name) === "LangGraphInterruptEvent" && !(interruptEvent == null ? void 0 : interruptEvent.response);
    return !isInProgress && text.trim().length > 0 && pushToTalkState === "idle" && !interruptInProgress;
  }, [(_b = copilotContext.langGraphInterruptAction) == null ? void 0 : _b.event, isInProgress, text, pushToTalkState]);
  const canStop = (0, import_react9.useMemo)(() => {
    return isInProgress && !hideStopButton;
  }, [isInProgress, hideStopButton]);
  const sendDisabled = !canSend && !canStop;
  return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: `copilotKitInputContainer ${showPoweredBy ? "poweredByContainer" : ""}`, children: [
    /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "copilotKitInput", onClick: handleDivClick, children: [
      /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
        Textarea_default,
        {
          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__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "copilotKitInputControls", children: [
        onUpload && /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("button", { onClick: onUpload, className: "copilotKitInputControlButton", children: context.icons.uploadIcon }),
        /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { style: { flexGrow: 1 } }),
        showPushToTalk && /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
          "button",
          {
            onClick: () => setPushToTalkState(pushToTalkState === "idle" ? "recording" : "transcribing"),
            className: pushToTalkState === "recording" ? "copilotKitInputControlButton copilotKitPushToTalkRecording" : "copilotKitInputControlButton",
            children: context.icons.pushToTalkIcon
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime13.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",
            children: buttonIcon
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(PoweredByTag, { showPoweredBy })
  ] });
};

// src/components/chat/Chat.tsx
var import_react10 = __toESM(require("react"));
var import_react_core5 = require("@copilotkit/react-core");
var import_shared = require("@copilotkit/shared");
var import_shared2 = require("@copilotkit/shared");
var import_react_core6 = require("@copilotkit/react-core");

// src/components/chat/ImageUploadQueue.tsx
var import_jsx_runtime14 = require("react/jsx-runtime");
var ImageUploadQueue = ({
  images,
  onRemoveImage,
  className = ""
}) => {
  if (images.length === 0)
    return null;
  return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
    "div",
    {
      className: `copilotKitImageUploadQueue ${className}`,
      style: {
        display: "flex",
        flexWrap: "wrap",
        gap: "8px",
        margin: "8px",
        padding: "8px"
      },
      children: images.map((image, index) => /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
        "div",
        {
          className: "copilotKitImageUploadQueueItem",
          style: {
            position: "relative",
            display: "inline-block",
            width: "60px",
            height: "60px",
            borderRadius: "4px",
            overflow: "hidden"
          },
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
              "img",
              {
                src: `data:${image.contentType};base64,${image.bytes}`,
                alt: `Selected image ${index + 1}`,
                style: {
                  width: "100%",
                  height: "100%",
                  objectFit: "cover"
                }
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime14.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: "\u2715"
              }
            )
          ]
        },
        index
      ))
    }
  );
};

// src/components/chat/Suggestion.tsx
var import_react_core4 = require("@copilotkit/react-core");
var import_jsx_runtime15 = require("react/jsx-runtime");
function Suggestion({ title, onClick, partial, className }) {
  if (!title)
    return null;
  const { isLoading } = (0, import_react_core4.useCopilotChatInternal)();
  return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
    "button",
    {
      disabled: partial || isLoading,
      onClick: (e) => {
        e.preventDefault();
        onClick();
      },
      className: className || (partial ? "suggestion loading" : "suggestion"),
      "data-test-id": "suggestion",
      children: partial ? SmallSpinnerIcon : /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("span", { children: title })
    }
  );
}

// src/components/chat/Suggestions.tsx
var import_jsx_runtime16 = require("react/jsx-runtime");
function Suggestions({ suggestions, onSuggestionClick }) {
  return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("div", { className: "suggestions", children: suggestions.map((suggestion, index) => /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
    Suggestion,
    {
      title: suggestion.title,
      message: suggestion.message,
      partial: suggestion.partial,
      className: suggestion.className,
      onClick: () => onSuggestionClick(suggestion.message)
    },
    index
  )) });
}

// src/components/chat/Chat.tsx
var import_jsx_runtime17 = require("react/jsx-runtime");
function CopilotChat({
  instructions,
  suggestions = "auto",
  onSubmitMessage,
  makeSystemMessage,
  onInProgress,
  onStopGeneration,
  onReloadMessages,
  onRegenerate,
  onCopy,
  onThumbsUp,
  onThumbsDown,
  markdownTagRenderers,
  Messages: Messages2 = Messages,
  RenderMessage: RenderMessage2 = RenderMessage,
  RenderSuggestionsList = Suggestions,
  Input: Input2 = Input,
  className,
  icons,
  labels,
  AssistantMessage: AssistantMessage2 = AssistantMessage,
  UserMessage: UserMessage2 = UserMessage,
  ImageRenderer: ImageRenderer2 = ImageRenderer,
  imageUploadsEnabled,
  inputFileAccept = "image/*",
  hideStopButton,
  observabilityHooks,
  renderError,
  // Legacy props - deprecated
  RenderTextMessage,
  RenderActionExecutionMessage,
  RenderAgentStateMessage,
  RenderResultMessage,
  RenderImageMessage
}) {
  const { additionalInstructions, setChatInstructions, copilotApiConfig, setBannerError } = (0, import_react_core5.useCopilotContext)();
  const { publicApiKey, chatApiEndpoint } = copilotApiConfig;
  const [selectedImages, setSelectedImages] = (0, import_react10.useState)([]);
  const [chatError, setChatError] = (0, import_react10.useState)(null);
  const fileInputRef = (0, import_react10.useRef)(null);
  const triggerObservabilityHook = (0, import_react10.useCallback)(
    (hookName, ...args) => {
      if (publicApiKey && (observabilityHooks == null ? void 0 : observabilityHooks[hookName])) {
        observabilityHooks[hookName](...args);
      }
      if ((observabilityHooks == null ? void 0 : observabilityHooks[hookName]) && !publicApiKey) {
        setBannerError(
          new import_shared.CopilotKitError({
            message: "observabilityHooks requires a publicApiKey to function.",
            code: import_shared.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
            severity: import_shared.Severity.CRITICAL,
            visibility: import_shared.ErrorVisibility.BANNER
          })
        );
        import_shared.styledConsole.publicApiKeyRequired("observabilityHooks");
      }
    },
    [publicApiKey, observabilityHooks, setBannerError]
  );
  const triggerChatError = (0, import_react10.useCallback)(
    (error, operation, originalError) => {
      const errorMessage = (error == null ? void 0 : error.message) || (error == null ? void 0 : error.toString()) || "An error occurred";
      setChatError({
        message: errorMessage,
        operation,
        timestamp: Date.now()
      });
      if (publicApiKey && (observabilityHooks == null ? void 0 : observabilityHooks.onError)) {
        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
        };
        observabilityHooks.onError(errorEvent);
      }
      if ((observabilityHooks == null ? void 0 : observabilityHooks.onError) && !publicApiKey) {
        setBannerError(
          new import_shared.CopilotKitError({
            message: "observabilityHooks.onError requires a publicApiKey to function.",
            code: import_shared.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
            severity: import_shared.Severity.CRITICAL,
            visibility: import_shared.ErrorVisibility.BANNER
          })
        );
        import_shared.styledConsole.publicApiKeyRequired("observabilityHooks.onError");
      }
    },
    [publicApiKey, chatApiEndpoint, observabilityHooks, setBannerError]
  );
  (0, import_react10.useEffect)(() => {
    if (!imageUploadsEnabled)
      return;
    const handlePaste = (e) => __async(this, null, function* () {
      var _a, _b;
      const target = e.target;
      if (!((_a = target.parentElement) == null ? void 0 : _a.classList.contains("copilotKitInput")))
        return;
      const items = Array.from(((_b = e.clipboardData) == null ? void 0 : _b.items) || []);
      const imageItems = 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 = (e2) => {
            var _a2, _b2;
            const base64String = (_b2 = (_a2 = e2.target) == null ? void 0 : _a2.result) == null ? void 0 : _b2.split(",")[1];
            if (base64String) {
              resolve({
                contentType: file.type,
                bytes: base64String
              });
            } else {
              resolve(null);
            }
          };
          reader.onerror = reject;
          reader.readAsDataURL(file);
        });
      });
      try {
        const loadedImages = (yield 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]);
  (0, import_react10.useEffect)(() => {
    if (!(additionalInstructions == null ? void 0 : additionalInstructions.length)) {
      setChatInstructions(instructions || "");
      return;
    }
    const combinedAdditionalInstructions = [
      instructions,
      "Additionally, follow these instructions:",
      ...additionalInstructions.map((instruction) => `- ${instruction}`)
    ];
    setChatInstructions(combinedAdditionalInstructions.join("\n") || "");
  }, [instructions, additionalInstructions]);
  const {
    messages,
    isLoading,
    sendMessage,
    stopGeneration,
    reloadMessages,
    suggestions: currentSuggestions
  } = useCopilotChatLogic(
    suggestions,
    makeSystemMessage,
    onInProgress,
    onSubmitMessage,
    onStopGeneration,
    onReloadMessages
  );
  const prevIsLoading = (0, import_react10.useRef)(isLoading);
  (0, import_react10.useEffect)(() => {
    if (prevIsLoading.current !== isLoading) {
      if (isLoading) {
        triggerObservabilityHook("onChatStarted");
      } else {
        triggerObservabilityHook("onChatStopped");
      }
      prevIsLoading.current = isLoading;
    }
  }, [isLoading, triggerObservabilityHook]);
  const handleSendMessage = (text) => {
    const images = selectedImages;
    setSelectedImages([]);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
    triggerObservabilityHook("onMessageSent", text);
    return sendMessage(text, images);
  };
  const chatContext = import_react10.default.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 = (event) => __async(this, null, function* () {
    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) => {
          var _a, _b;
          const base64String = ((_b = (_a = e.target) == null ? void 0 : _a.result) == null ? void 0 : _b.split(",")[1]) || "";
          if (base64String) {
            resolve({
              contentType: file.type,
              bytes: base64String
            });
          }
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });
    });
    try {
      const loadedImages = yield 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);
    }
    triggerObservabilityHook("onFeedbackGiven", message.id, "thumbsUp");
  };
  const handleThumbsDown = (message) => {
    if (onThumbsDown) {
      onThumbsDown(message);
    }
    triggerObservabilityHook("onFeedbackGiven", message.id, "thumbsDown");
  };
  return /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)(WrappedCopilotChat, { icons, labels, className, children: [
    chatError && renderError && renderError(__spreadProps(__spreadValues({}, chatError), {
      onDismiss: () => setChatError(null),
      onRetry: () => {
        setChatError(null);
      }
    })),
    /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
      Messages2,
      {
        AssistantMessage: AssistantMessage2,
        UserMessage: UserMessage2,
        RenderMessage: RenderMessage2,
        messages,
        inProgress: isLoading,
        onRegenerate: handleRegenerate,
        onCopy: handleCopy,
        onThumbsUp: handleThumbsUp,
        onThumbsDown: handleThumbsDown,
        markdownTagRenderers,
        ImageRenderer: ImageRenderer2,
        RenderTextMessage,
        RenderActionExecutionMessage,
        RenderAgentStateMessage,
        RenderResultMessage,
        RenderImageMessage,
        children: currentSuggestions.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
          RenderSuggestionsList,
          {
            onSuggestionClick: handleSendMessage,
            suggestions: currentSuggestions
          }
        )
      }
    ),
    imageUploadsEnabled && /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)(import_jsx_runtime17.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(ImageUploadQueue, { images: selectedImages, onRemoveImage: removeSelectedImage }),
      /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
        "input",
        {
          type: "file",
          multiple: true,
          ref: fileInputRef,
          onChange: handleImageUpload,
          accept: inputFileAccept,
          style: { display: "none" }
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
      Input2,
      {
        inProgress: isLoading,
        onSend: handleSendMessage,
        isVisible,
        onStop: stopGeneration,
        onUpload: imageUploadsEnabled ? () => {
          var _a;
          return (_a = fileInputRef.current) == null ? void 0 : _a.click();
        } : void 0,
        hideStopButton
      }
    )
  ] });
}
function WrappedCopilotChat({
  children,
  icons,
  labels,
  className
}) {
  const chatContext = import_react10.default.useContext(ChatContext);
  if (!chatContext) {
    return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(ChatContextProvider, { icons, labels, open: true, setOpen: () => {
    }, children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)("div", { className: `copilotKitChat ${className != null ? className : ""}`, children }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_jsx_runtime17.Fragment, { children });
}
var useCopilotChatLogic = (chatSuggestions, makeSystemMessage, onInProgress, onSubmitMessage, onStopGeneration, onReloadMessages) => {
  var _a;
  const {
    messages,
    sendMessage,
    setMessages,
    reloadMessages: defaultReloadMessages,
    stopGeneration: defaultStopGeneration,
    runChatCompletion,
    isLoading,
    suggestions,
    setSuggestions,
    generateSuggestions,
    resetSuggestions: resetSuggestionsFromHook,
    isLoadingSuggestions
  } = (0, import_react_core5.useCopilotChatInternal)({
    makeSystemMessage
  });
  const generalContext = (0, import_react_core5.useCopilotContext)();
  const messagesContext = (0, import_react_core5.useCopilotMessagesContext)();
  const { actions } = generalContext;
  const [suggestionsFailed, setSuggestionsFailed] = (0, import_react10.useState)(false);
  const hasGeneratedInitialSuggestions = (0, import_react10.useRef)(false);
  (0, import_react10.useEffect)(() => {
    if (Array.isArray(chatSuggestions)) {
      setSuggestions(chatSuggestions);
      hasGeneratedInitialSuggestions.current = true;
    }
  }, [JSON.stringify(chatSuggestions), setSuggestions]);
  const generateSuggestionsWithErrorHandling = (0, import_react10.useCallback)(
    (context) => __async(void 0, null, function* () {
      try {
        yield generateSuggestions();
      } catch (error) {
        console.error("Failed to generate suggestions:", error);
        setSuggestionsFailed(true);
      }
    }),
    [generateSuggestions]
  );
  (0, import_react10.useEffect)(() => {
    if (chatSuggestions !== "auto" || isLoadingSuggestions || suggestionsFailed) {
      return;
    }
    if (isLoading) {
      return;
    }
    if (Object.keys(generalContext.chatSuggestionConfiguration).length === 0) {
      return;
    }
    if (messages.length === 0 && !hasGeneratedInitialSuggestions.current) {
      hasGeneratedInitialSuggestions.current = true;
      generateSuggestionsWithErrorHandling("initial");
      return;
    }
    if (messages.length > 0 && suggestions.length === 0) {
      generateSuggestionsWithErrorHandling("post-message");
      return;
    }
  }, [
    chatSuggestions,
    isLoadingSuggestions,
    suggestionsFailed,
    messages.length,
    isLoading,
    suggestions.length,
    Object.keys(generalContext.chatSuggestionConfiguration).join(","),
    // Use stable string instead of object reference
    generateSuggestionsWithErrorHandling
  ]);
  (0, import_react10.useEffect)(() => {
    if (chatSuggestions !== "auto") {
      hasGeneratedInitialSuggestions.current = false;
      setSuggestionsFailed(false);
    }
  }, [chatSuggestions]);
  const stableContext = (0, import_react10.useMemo)(
    () => __spreadValues(__spreadValues({}, generalContext), messagesContext),
    [
      // Only include stable dependencies
      generalContext.actions,
      messagesContext.messages.length,
      generalContext.isLoading
    ]
  );
  const resetSuggestions = (0, import_react10.useCallback)(() => {
    resetSuggestionsFromHook();
    setSuggestionsFailed(false);
    hasGeneratedInitialSuggestions.current = false;
  }, [resetSuggestionsFromHook]);
  (0, import_react10.useEffect)(() => {
    onInProgress == null ? void 0 : onInProgress(isLoading);
  }, [onInProgress, isLoading]);
  const safelySendMessage = (messageContent, imagesToUse) => __async(void 0, null, function* () {
    const images = imagesToUse || [];
    if (chatSuggestions === "auto" || chatSuggestions === "manual") {
      setSuggestions([]);
    }
    let firstMessage = null;
    if (messageContent.trim().length > 0) {
      const textMessage = {
        id: (0, import_shared2.randomId)(),
        role: "user",
        content: messageContent
      };
      if (onSubmitMessage) {
        try {
          yield onSubmitMessage(messageContent);
        } catch (error) {
          console.error("Error in onSubmitMessage:", error);
        }
      }
      yield sendMessage(textMessage, {
        followUp: images.length === 0,
        clearSuggestions: chatSuggestions === "auto" || chatSuggestions === "manual"
      });
      if (!firstMessage) {
        firstMessage = textMessage;
      }
    }
    if (images.length > 0) {
      for (let i = 0; i < images.length; i++) {
        const imageMessage = {
          id: (0, import_shared2.randomId)(),
          role: "user",
          image: {
            format: images[i].contentType.replace("image/", ""),
            bytes: images[i].bytes
          }
        };
        yield sendMessage(imageMessage, { followUp: i === images.length - 1 });
        if (!firstMessage) {
          firstMessage = imageMessage;
        }
      }
    }
    if (!firstMessage) {
      return { role: "user", content: "", id: (0, import_shared2.randomId)() };
    }
    return firstMessage;
  });
  const currentAgentName = (_a = generalContext.agentSession) == null ? void 0 : _a.agentName;
  const restartCurrentAgent = (hint) => __async(void 0, null, function* () {
    if (generalContext.agentSession) {
      generalContext.setAgentSession(__spreadProps(__spreadValues({}, generalContext.agentSession), {
        nodeName: void 0,
        threadId: void 0
      }));
      generalContext.setCoagentStates((prevAgentStates) => {
        return __spreadProps(__spreadValues({}, prevAgentStates), {
          [generalContext.agentSession.agentName]: __spreadProps(__spreadValues({}, prevAgentStates[generalContext.agentSession.agentName]), {
            threadId: void 0,
            nodeName: void 0,
            runId: void 0
          })
        });
      });
    }
  });
  const runCurrentAgent = (hint) => __async(void 0, null, function* () {
    if (generalContext.agentSession) {
      yield (0, import_react_core6.runAgent)(
        generalContext.agentSession.agentName,
        stableContext,
        messagesContext.messages,
        sendMessage,
        runChatCompletion
      );
    }
  });
  const stopCurrentAgent = () => {
    if (generalContext.agentSession) {
      (0, import_react_core6.stopAgent)(generalContext.agentSession.agentName, stableContext);
    }
  };
  const setCurrentAgentState = (state) => {
    if (generalContext.agentSession) {
      generalContext.setCoagentStates((prevAgentStates) => {
        return __spreadProps(__spreadValues({}, prevAgentStates), {
          [generalContext.agentSession.agentName]: {
            state
          }
        });
      });
    }
  };
  function stopGeneration() {
    setSuggestions([]);
    if (onStopGeneration) {
      onStopGeneration({
        messages,
        setMessages,
        stopGeneration: defaultStopGeneration,
        currentAgentName,
        restartCurrentAgent,
        stopCurrentAgent,
        runCurrentAgent,
        setCurrentAgentState
      });
    } else {
      defaultStopGeneration();
    }
  }
  function reloadMessages(messageId) {
    if (onReloadMessages) {
      onReloadMessages({
        messages,
        setMessages,
        stopGeneration: defaultStopGeneration,
        currentAgentName,
        restartCurrentAgent,
        stopCurrentAgent,
        runCurrentAgent,
        setCurrentAgentState,
        messageId
      });
    } else {
      defaultReloadMessages(messageId);
    }
  }
  return {
    messages,
    isLoading,
    suggestions,
    sendMessage: safelySendMessage,
    stopGeneration,
    reloadMessages,
    resetSuggestions,
    context: stableContext,
    actions
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CopilotChat,
  WrappedCopilotChat,
  useCopilotChatLogic
});
//# sourceMappingURL=Chat.js.map