import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import React, { useCallback, useRef, useImperativeHandle, forwardRef, useState } from "react";
import { Box } from "ink";
import path from "path";
import { ApprovalStatus, DenialReason, isUserMessage } from "@dexto/core";
import {
  ApprovalPrompt
} from "../components/ApprovalPrompt.js";
import {
  SlashCommandAutocomplete
} from "../components/SlashCommandAutocomplete.js";
import ResourceAutocomplete from "../components/ResourceAutocomplete.js";
import ModelSelectorRefactored from "../components/overlays/ModelSelectorRefactored.js";
import {
  ReasoningOverlay
} from "../components/overlays/ReasoningOverlay.js";
import SessionSelectorRefactored from "../components/overlays/SessionSelectorRefactored.js";
import LogLevelSelector from "../components/overlays/LogLevelSelector.js";
import StreamSelector from "../components/overlays/StreamSelector.js";
import SoundsSelector from "../components/overlays/SoundsSelector.js";
import ToolBrowser from "../components/overlays/ToolBrowser.js";
import {
  CommandOutputOverlay
} from "../components/overlays/CommandOutputOverlay.js";
import McpServerList from "../components/overlays/McpServerList.js";
import McpServerActions from "../components/overlays/McpServerActions.js";
import McpAddChoice from "../components/overlays/McpAddChoice.js";
import McpAddSelector from "../components/overlays/McpAddSelector.js";
import SessionSubcommandSelector from "../components/overlays/SessionSubcommandSelector.js";
import McpCustomTypeSelector from "../components/overlays/McpCustomTypeSelector.js";
import McpCustomWizard from "../components/overlays/McpCustomWizard.js";
import CustomModelWizard from "../components/overlays/CustomModelWizard.js";
import ChatGPTUsageCapOverlay from "../components/overlays/ChatGPTUsageCapOverlay.js";
import InsufficientCreditsOverlay from "../components/overlays/InsufficientCreditsOverlay.js";
import { getLLMProviderDisplayName } from "../utils/llm-provider-display.js";
import { resolveChatGPTFallbackModel } from "../utils/chatgpt-rate-limit.js";
import {
  getProviderKeyStatus,
  loadGlobalPreferences,
  recordRecentModel,
  updateGlobalPreferences
} from "@dexto/agent-management";
import ApiKeyInput from "../components/overlays/ApiKeyInput.js";
import SearchOverlay from "../components/overlays/SearchOverlay.js";
import PromptList from "../components/overlays/PromptList.js";
import PromptAddChoice from "../components/overlays/PromptAddChoice.js";
import PromptAddWizard from "../components/overlays/PromptAddWizard.js";
import PromptDeleteSelector from "../components/overlays/PromptDeleteSelector.js";
import SessionRenameOverlay from "../components/overlays/SessionRenameOverlay.js";
import ContextStatsOverlay from "../components/overlays/ContextStatsOverlay.js";
import ExportWizard from "../components/overlays/ExportWizard.js";
import PluginManager from "../components/overlays/PluginManager.js";
import PluginList from "../components/overlays/PluginList.js";
import PluginActions from "../components/overlays/PluginActions.js";
import MarketplaceBrowser from "../components/overlays/MarketplaceBrowser.js";
import MarketplaceAddPrompt from "../components/overlays/MarketplaceAddPrompt.js";
import LoginOverlay from "../components/overlays/LoginOverlay.js";
import LogoutOverlay from "../components/overlays/LogoutOverlay.js";
import ConnectOverlay from "../components/overlays/ConnectOverlay.js";
import { LLM_PROVIDERS, getModelDisplayName, getReasoningProfile } from "@dexto/llm";
import { DextoValidationError, LLMErrorCode } from "@dexto/core";
import { createUserMessage, convertHistoryToUIMessages } from "../utils/messageFormatting.js";
import { generateMessageId } from "../utils/idGenerator.js";
import { canUseDextoProvider, captureAnalytics } from "../host/index.js";
import { FocusOverlayFrame } from "../components/shared/FocusOverlayFrame.js";
import { shouldHideCliChrome } from "../utils/overlayPresentation.js";
import { refreshDextoNovaAuthAfterLogin } from "../utils/dexto-auth-refresh.js";
function isLLMProvider(value) {
  if (typeof value !== "string") return false;
  for (const provider of LLM_PROVIDERS) {
    if (provider === value) return true;
  }
  return false;
}
function getProviderFromIssueContext(context) {
  if (typeof context !== "object" || context === null) return null;
  const provider = Reflect.get(context, "provider");
  return isLLMProvider(provider) ? provider : null;
}
function buildReasoningSwitchUpdate(provider, model, reasoningVariant) {
  if (reasoningVariant === void 0) {
    return {};
  }
  const defaultVariant = getReasoningProfile(provider, model).defaultVariant;
  if (defaultVariant !== void 0 && reasoningVariant === defaultVariant) {
    return { reasoning: null };
  }
  return { reasoning: { variant: reasoningVariant } };
}
const OverlayContainer = forwardRef(
  function OverlayContainer2({
    ui,
    input,
    session,
    approval,
    setInput,
    setUi,
    setSession,
    setMessages,
    setApproval,
    setApprovalQueue,
    agent,
    inputService,
    buffer,
    configFilePath,
    refreshStatic,
    onSubmitPromptCommand
  }, ref) {
    const approvalRef = useRef(null);
    const slashAutocompleteRef = useRef(null);
    const resourceAutocompleteRef = useRef(null);
    const modelSelectorRef = useRef(null);
    const reasoningOverlayRef = useRef(null);
    const sessionSelectorRef = useRef(null);
    const logLevelSelectorRef = useRef(null);
    const streamSelectorRef = useRef(null);
    const soundsSelectorRef = useRef(null);
    const toolBrowserRef = useRef(null);
    const commandOutputRef = useRef(null);
    const mcpServerListRef = useRef(null);
    const mcpServerActionsRef = useRef(null);
    const mcpAddChoiceRef = useRef(null);
    const mcpAddSelectorRef = useRef(null);
    const mcpCustomTypeSelectorRef = useRef(null);
    const mcpCustomWizardRef = useRef(null);
    const customModelWizardRef = useRef(null);
    const sessionSubcommandSelectorRef = useRef(null);
    const chatGPTUsageCapRef = useRef(null);
    const insufficientCreditsRef = useRef(null);
    const apiKeyInputRef = useRef(null);
    const loginOverlayRef = useRef(null);
    const logoutOverlayRef = useRef(null);
    const connectOverlayRef = useRef(null);
    const searchOverlayRef = useRef(null);
    const promptListRef = useRef(null);
    const promptAddChoiceRef = useRef(null);
    const promptAddWizardRef = useRef(null);
    const promptDeleteSelectorRef = useRef(null);
    const sessionRenameRef = useRef(null);
    const contextStatsRef = useRef(null);
    const exportWizardRef = useRef(null);
    const pluginManagerRef = useRef(null);
    const pluginListRef = useRef(null);
    const pluginActionsRef = useRef(null);
    const marketplaceBrowserRef = useRef(null);
    const [selectedPlugin, setSelectedPlugin] = useState(null);
    const marketplaceAddPromptRef = useRef(null);
    const getConfigFilePathOrWarn = useCallback(
      (action) => {
        if (configFilePath) {
          return configFilePath;
        }
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: `\u26A0\uFE0F Cannot ${action}: this agent is not file-backed (no config path).`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
        return null;
      },
      [configFilePath, setMessages]
    );
    useImperativeHandle(
      ref,
      () => ({
        handleInput: (inputStr, key) => {
          if (approval && approvalRef.current) {
            return approvalRef.current.handleInput(inputStr, key);
          }
          switch (ui.activeOverlay) {
            case "slash-autocomplete":
              return slashAutocompleteRef.current?.handleInput(inputStr, key) ?? false;
            case "resource-autocomplete":
              return resourceAutocompleteRef.current?.handleInput(inputStr, key) ?? false;
            case "model-selector":
              return modelSelectorRef.current?.handleInput(inputStr, key) ?? false;
            case "reasoning":
              return reasoningOverlayRef.current?.handleInput(inputStr, key) ?? false;
            case "session-selector":
              return sessionSelectorRef.current?.handleInput(inputStr, key) ?? false;
            case "log-level-selector":
              return logLevelSelectorRef.current?.handleInput(inputStr, key) ?? false;
            case "stream-selector":
              return streamSelectorRef.current?.handleInput(inputStr, key) ?? false;
            case "sounds-selector":
              return soundsSelectorRef.current?.handleInput(inputStr, key) ?? false;
            case "tool-browser":
              return toolBrowserRef.current?.handleInput(inputStr, key) ?? false;
            case "command-output":
              return commandOutputRef.current?.handleInput(inputStr, key) ?? false;
            case "mcp-server-list":
              return mcpServerListRef.current?.handleInput(inputStr, key) ?? false;
            case "mcp-server-actions":
              return mcpServerActionsRef.current?.handleInput(inputStr, key) ?? false;
            case "mcp-add-choice":
              return mcpAddChoiceRef.current?.handleInput(inputStr, key) ?? false;
            case "mcp-add-selector":
              return mcpAddSelectorRef.current?.handleInput(inputStr, key) ?? false;
            case "mcp-custom-type-selector":
              return mcpCustomTypeSelectorRef.current?.handleInput(inputStr, key) ?? false;
            case "mcp-custom-wizard":
              return mcpCustomWizardRef.current?.handleInput(inputStr, key) ?? false;
            case "custom-model-wizard":
              return customModelWizardRef.current?.handleInput(inputStr, key) ?? false;
            case "session-subcommand-selector":
              return sessionSubcommandSelectorRef.current?.handleInput(inputStr, key) ?? false;
            case "chatgpt-usage-cap":
              return chatGPTUsageCapRef.current?.handleInput(inputStr, key) ?? false;
            case "insufficient-credits":
              return insufficientCreditsRef.current?.handleInput(inputStr, key) ?? false;
            case "api-key-input":
              return apiKeyInputRef.current?.handleInput(inputStr, key) ?? false;
            case "login":
              return loginOverlayRef.current?.handleInput(inputStr, key) ?? false;
            case "logout":
              return logoutOverlayRef.current?.handleInput(inputStr, key) ?? false;
            case "connect":
              return connectOverlayRef.current?.handleInput(inputStr, key) ?? false;
            case "search":
              return searchOverlayRef.current?.handleInput(inputStr, key) ?? false;
            case "prompt-list":
              return promptListRef.current?.handleInput(inputStr, key) ?? false;
            case "prompt-add-choice":
              return promptAddChoiceRef.current?.handleInput(inputStr, key) ?? false;
            case "prompt-add-wizard":
              return promptAddWizardRef.current?.handleInput(inputStr, key) ?? false;
            case "prompt-delete-selector":
              return promptDeleteSelectorRef.current?.handleInput(inputStr, key) ?? false;
            case "session-rename":
              return sessionRenameRef.current?.handleInput(inputStr, key) ?? false;
            case "context-stats":
              return contextStatsRef.current?.handleInput(inputStr, key) ?? false;
            case "export-wizard":
              return exportWizardRef.current?.handleInput(inputStr, key) ?? false;
            case "plugin-manager":
              return pluginManagerRef.current?.handleInput(inputStr, key) ?? false;
            case "plugin-list":
              return pluginListRef.current?.handleInput(inputStr, key) ?? false;
            case "plugin-actions":
              return pluginActionsRef.current?.handleInput(inputStr, key) ?? false;
            case "marketplace-browser":
              return marketplaceBrowserRef.current?.handleInput(inputStr, key) ?? false;
            case "marketplace-add":
              return marketplaceAddPromptRef.current?.handleInput(inputStr, key) ?? false;
            default:
              return false;
          }
        }
      }),
      [approval, ui.activeOverlay]
    );
    const completeApproval = useCallback(() => {
      setApprovalQueue((queue) => {
        if (queue.length > 0) {
          const [next, ...rest] = queue;
          setApproval(next);
          setUi((prev) => ({ ...prev, activeOverlay: "approval" }));
          return rest;
        } else {
          setApproval(null);
          setUi((prev) => ({ ...prev, activeOverlay: "none" }));
          return [];
        }
      });
    }, [setApproval, setApprovalQueue, setUi]);
    const handleApprove = useCallback(
      (options) => {
        if (!approval) return;
        if (options.enableAcceptEditsMode) {
          setUi((prev) => ({ ...prev, autoApproveEdits: true }));
        }
        const toolName = approval.metadata.toolName;
        if (toolName === "plan_create" || toolName === "plan_review") {
          setUi((prev) => ({
            ...prev,
            planModeActive: false,
            planModeInitialized: false
          }));
        }
        agent.emit("approval:response", {
          approvalId: approval.approvalId,
          status: ApprovalStatus.APPROVED,
          sessionId: approval.sessionId,
          hostRuntime: approval.hostRuntime,
          data: {
            rememberChoice: options.rememberChoice,
            formData: options.formData
          }
        });
        completeApproval();
      },
      [approval, agent, completeApproval, setUi]
    );
    const handleDeny = useCallback(
      (feedback) => {
        if (!approval) return;
        const message = feedback ? `User requested changes: ${feedback}` : "User denied the tool execution";
        agent.emit("approval:response", {
          approvalId: approval.approvalId,
          status: ApprovalStatus.DENIED,
          sessionId: approval.sessionId,
          hostRuntime: approval.hostRuntime,
          reason: DenialReason.USER_DENIED,
          message
        });
        completeApproval();
      },
      [approval, agent, completeApproval]
    );
    const handleCancelApproval = useCallback(() => {
      if (!approval) return;
      agent.emit("approval:response", {
        approvalId: approval.approvalId,
        status: ApprovalStatus.CANCELLED,
        sessionId: approval.sessionId,
        hostRuntime: approval.hostRuntime,
        reason: DenialReason.USER_CANCELLED,
        message: "User cancelled the approval request"
      });
      completeApproval();
    }, [approval, agent, completeApproval]);
    const isApiKeyMissingError = (error) => {
      if (error instanceof DextoValidationError) {
        const apiKeyIssue = error.issues.find(
          (issue) => issue.code === LLMErrorCode.API_KEY_MISSING
        );
        if (apiKeyIssue && apiKeyIssue.context) {
          return getProviderFromIssueContext(apiKeyIssue.context);
        }
      }
      return null;
    };
    const persistRecentModel = useCallback(
      async (provider, model, baseURL) => {
        try {
          await recordRecentModel({
            provider,
            model,
            ...baseURL ? { baseURL } : {}
          });
        } catch (error) {
          const modelKey = baseURL ? `${provider}/${model} (${baseURL})` : `${provider}/${model}`;
          agent.logger.debug(
            `Failed to persist recent model (${modelKey}): ${error instanceof Error ? error.message : String(error)}`
          );
        }
      },
      [agent]
    );
    const handleModelSelect = useCallback(
      async (provider, model, displayName, baseURL, reasoningVariant) => {
        const providerLabel = getLLMProviderDisplayName(provider, baseURL);
        if (provider === "dexto-nova") {
          try {
            const canUse = await canUseDextoProvider();
            if (!canUse) {
              setMessages((prev) => [
                ...prev,
                {
                  id: generateMessageId("system"),
                  role: "system",
                  content: "Cannot switch to Dexto Nova model - authentication required. Run /login to authenticate.",
                  timestamp: /* @__PURE__ */ new Date()
                }
              ]);
              return;
            }
          } catch (error) {
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("error"),
                role: "system",
                content: `Failed to verify Dexto Nova auth: ${error instanceof Error ? error.message : String(error)}`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
            return;
          }
        }
        setUi((prev) => ({ ...prev, activeOverlay: "none", mcpWizardServerType: null }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        try {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u{1F504} Switching to ${displayName || model} (${providerLabel})...`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          await agent.switchLLM(
            {
              provider,
              model,
              baseURL,
              ...buildReasoningSwitchUpdate(provider, model, reasoningVariant)
            },
            session.id || void 0
          );
          await persistRecentModel(provider, model, baseURL);
          setSession((prev) => ({ ...prev, modelName: displayName || model }));
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u2705 Successfully switched to ${displayName || model} (${providerLabel})`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        } catch (error) {
          const missingProvider = isApiKeyMissingError(error);
          if (missingProvider) {
            const missingProviderLabel = getLLMProviderDisplayName(
              missingProvider,
              missingProvider === provider ? baseURL : void 0
            );
            setUi((prev) => ({
              ...prev,
              activeOverlay: "api-key-input",
              pendingModelSwitch: {
                provider: missingProvider,
                model,
                ...displayName && { displayName },
                ...baseURL && { baseURL },
                ...reasoningVariant !== void 0 && { reasoningVariant }
              }
            }));
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("system"),
                role: "system",
                content: `\u{1F511} API key required for ${missingProviderLabel}`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
            return;
          }
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("error"),
              role: "system",
              content: `Failed to switch model: ${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        }
      },
      [
        setUi,
        setInput,
        setMessages,
        setSession,
        agent,
        session.id,
        buffer,
        persistRecentModel
      ]
    );
    const handleSetDefaultModel = useCallback(
      async (provider, model, displayName, baseURL, reasoningVariant) => {
        const providerLabel = getLLMProviderDisplayName(provider, baseURL);
        try {
          let providerEnvVar;
          try {
            const providerKeyStatus = await getProviderKeyStatus(provider);
            providerEnvVar = providerKeyStatus?.envVar;
          } catch (error) {
            agent.logger.debug(
              `Failed to resolve provider API key env var: ${error instanceof Error ? error.message : String(error)}`
            );
          }
          let existing = null;
          try {
            existing = await loadGlobalPreferences();
          } catch {
            existing = null;
          }
          const existingReasoning = existing?.llm.reasoning;
          const defaultReasoningVariant = getReasoningProfile(
            provider,
            model
          ).defaultVariant;
          const nextReasoning = reasoningVariant === void 0 ? existingReasoning : defaultReasoningVariant !== void 0 && reasoningVariant === defaultReasoningVariant ? void 0 : { variant: reasoningVariant };
          const preferencesUpdate = {
            provider,
            model,
            ...baseURL ? { baseURL } : {},
            ...nextReasoning ? { reasoning: nextReasoning } : {}
          };
          const switchReasoningUpdate = buildReasoningSwitchUpdate(
            provider,
            model,
            reasoningVariant
          );
          if (existing?.llm.provider === provider && existing?.llm.apiKey) {
            preferencesUpdate.apiKey = existing.llm.apiKey;
          } else if (providerEnvVar) {
            preferencesUpdate.apiKey = "$" + providerEnvVar;
          }
          await updateGlobalPreferences({
            llm: preferencesUpdate
          });
          try {
            await agent.switchLLM(
              {
                provider,
                model,
                ...baseURL ? { baseURL } : {},
                ...switchReasoningUpdate
              },
              session.id || void 0
            );
            await persistRecentModel(provider, model, baseURL);
            setSession((prev) => ({ ...prev, modelName: displayName || model }));
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("system"),
                role: "system",
                content: `\u2705 Default model set to ${displayName || model} (${providerLabel})`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
          } catch (error) {
            const missingProvider = isApiKeyMissingError(error);
            if (missingProvider) {
              const missingProviderLabel = getLLMProviderDisplayName(
                missingProvider,
                missingProvider === provider ? baseURL : void 0
              );
              setUi((prev) => ({
                ...prev,
                activeOverlay: "api-key-input",
                pendingModelSwitch: {
                  provider: missingProvider,
                  model,
                  ...displayName && { displayName },
                  ...baseURL && { baseURL },
                  ...reasoningVariant !== void 0 && { reasoningVariant }
                }
              }));
              setMessages((prev) => [
                ...prev,
                {
                  id: generateMessageId("system"),
                  role: "system",
                  content: `\u{1F511} API key required for ${missingProviderLabel}`,
                  timestamp: /* @__PURE__ */ new Date()
                }
              ]);
              return;
            }
            throw error;
          }
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("error"),
              role: "system",
              content: `Failed to set default model: ${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        }
      },
      [agent, setMessages, setSession, setUi, session.id, persistRecentModel]
    );
    const [editingModel, setEditingModel] = useState(null);
    const handleAddCustomModel = useCallback(() => {
      setEditingModel(null);
      setUi((prev) => ({ ...prev, activeOverlay: "custom-model-wizard" }));
    }, [setUi]);
    const handleEditCustomModel = useCallback(
      (model) => {
        setEditingModel(model);
        setUi((prev) => ({ ...prev, activeOverlay: "custom-model-wizard" }));
      },
      [setUi]
    );
    const handleCustomModelComplete = useCallback(
      async (model) => {
        const wasEditing = editingModel !== null;
        setEditingModel(null);
        setUi((prev) => ({ ...prev, activeOverlay: "none" }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        if (wasEditing) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u2705 Custom model "${model.displayName || model.name}" updated`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        } else {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u2705 Custom model "${model.displayName || model.name}" saved`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          await handleModelSelect(
            model.provider,
            model.name,
            model.displayName,
            model.baseURL
          );
        }
      },
      [setUi, setInput, setMessages, buffer, editingModel, handleModelSelect]
    );
    const handleChatGPTUsageCapClose = useCallback(() => {
      setUi((prev) => ({
        ...prev,
        activeOverlay: "none"
      }));
    }, [setUi]);
    const handleInsufficientCreditsClose = useCallback(() => {
      setUi((prev) => ({
        ...prev,
        activeOverlay: "none",
        insufficientCredits: null
      }));
    }, [setUi]);
    const handleInsufficientCreditsResolved = useCallback(() => {
      setUi((prev) => ({
        ...prev,
        activeOverlay: "none",
        insufficientCredits: null
      }));
      setMessages((prev) => [
        ...prev,
        {
          id: generateMessageId("system"),
          role: "system",
          content: "Billing opened in your browser. Retry your request when ready.",
          timestamp: /* @__PURE__ */ new Date()
        }
      ]);
    }, [setMessages, setUi]);
    const handleChatGPTUsageCapConfirm = useCallback(async () => {
      const currentLLMConfig2 = session.id ? agent.getCurrentLLMConfig(session.id) : agent.getCurrentLLMConfig();
      const fallbackTarget = resolveChatGPTFallbackModel(currentLLMConfig2.model);
      const providerKeyStatus = getProviderKeyStatus(fallbackTarget.provider);
      const reasoningVariant = fallbackTarget.usedDefaultFallback ? void 0 : currentLLMConfig2.reasoning?.variant;
      if (providerKeyStatus.hasApiKey) {
        setUi((prev) => ({
          ...prev,
          activeOverlay: "none"
        }));
        await handleModelSelect(
          fallbackTarget.provider,
          fallbackTarget.model,
          fallbackTarget.displayName,
          void 0,
          reasoningVariant
        );
        return;
      }
      setUi((prev) => ({
        ...prev,
        activeOverlay: "api-key-input",
        pendingModelSwitch: {
          provider: fallbackTarget.provider,
          model: fallbackTarget.model,
          displayName: fallbackTarget.displayName,
          ...reasoningVariant !== void 0 ? { reasoningVariant } : {}
        }
      }));
      setMessages((prev) => [
        ...prev,
        {
          id: generateMessageId("system"),
          role: "system",
          content: "\u{1F511} ChatGPT Login hit its usage cap. Add an OpenAI API key to continue with the API provider.",
          timestamp: /* @__PURE__ */ new Date()
        }
      ]);
    }, [agent, handleModelSelect, session.id, setMessages, setUi]);
    const handleApiKeySaved = useCallback(
      async (meta) => {
        const pending = ui.pendingModelSwitch;
        if (!pending) {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "none",
            pendingModelSwitch: null
          }));
          return;
        }
        setUi((prev) => ({
          ...prev,
          activeOverlay: "none",
          pendingModelSwitch: null
        }));
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: `\u2705 API key saved for ${meta.provider}`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
        try {
          const pendingDisplayName = pending.displayName || pending.model;
          const pendingProviderLabel = getLLMProviderDisplayName(
            pending.provider,
            pending.baseURL
          );
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u{1F504} Retrying switch to ${pendingDisplayName} (${pendingProviderLabel})...`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          await agent.switchLLM(
            {
              provider: pending.provider,
              model: pending.model,
              ...pending.baseURL && { baseURL: pending.baseURL },
              ...buildReasoningSwitchUpdate(
                pending.provider,
                pending.model,
                pending.reasoningVariant
              )
            },
            session.id || void 0
          );
          await persistRecentModel(
            pending.provider,
            pending.model,
            pending.baseURL
          );
          setSession((prev) => ({ ...prev, modelName: pendingDisplayName }));
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u2705 Successfully switched to ${pendingDisplayName} (${pendingProviderLabel})`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("error"),
              role: "system",
              content: `Failed to switch model: ${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        }
      },
      [
        ui.pendingModelSwitch,
        setUi,
        setMessages,
        setSession,
        agent,
        session.id,
        persistRecentModel
      ]
    );
    const handleApiKeyClose = useCallback(() => {
      setUi((prev) => ({
        ...prev,
        activeOverlay: "none",
        pendingModelSwitch: null
      }));
    }, [setUi]);
    const handleSearchResultSelect = useCallback(
      (result) => {
        setUi((prev) => ({ ...prev, activeOverlay: "none" }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        const roleLabel = result.message.role === "user" ? "\u{1F464} User" : result.message.role === "assistant" ? "\u{1F916} Assistant" : `\u{1F4CB} ${result.message.role}`;
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: `\u{1F50D} Search Result from session ${result.sessionId.slice(0, 8)}:

${roleLabel}:
${result.context}`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
      },
      [setUi, setInput, setMessages, buffer]
    );
    const handleSessionSelect = useCallback(
      async (newSessionId) => {
        setUi((prev) => ({ ...prev, activeOverlay: "none", mcpWizardServerType: null }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        try {
          if (newSessionId === session.id) {
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("system"),
                role: "system",
                content: `\u2139\uFE0F  Already using session ${newSessionId.slice(0, 8)}`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
            return;
          }
          captureAnalytics("dexto_session_switched", {
            source: "cli",
            fromSessionId: session.id || null,
            toSessionId: newSessionId
          });
          setMessages([]);
          setApproval(null);
          setApprovalQueue([]);
          const sessionData = await agent.getSession(newSessionId);
          if (!sessionData) {
            throw new Error(`Session ${newSessionId} not found`);
          }
          const newSessionConfig = agent.getCurrentLLMConfig(newSessionId);
          const newSessionModelName = getModelDisplayName(
            newSessionConfig.model,
            newSessionConfig.provider
          );
          setSession({
            id: newSessionId,
            hasActiveSession: true,
            modelName: newSessionModelName
          });
          const history = await agent.getSessionHistory(newSessionId);
          if (history && history.length > 0) {
            const historyMessages = convertHistoryToUIMessages(history, newSessionId);
            setMessages(historyMessages);
            const userInputHistory = history.filter(isUserMessage).map((msg) => {
              if (typeof msg.content === "string") {
                return msg.content;
              }
              if (Array.isArray(msg.content)) {
                return msg.content.filter(
                  (part) => typeof part === "object" && part.type === "text"
                ).map((part) => part.text).join("\n");
              }
              return "";
            }).filter((text) => text.trim().length > 0);
            setInput((prev) => ({
              ...prev,
              history: userInputHistory,
              historyIndex: -1
            }));
          }
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u2705 Switched to session ${newSessionId.slice(0, 8)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          refreshStatic?.();
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("error"),
              role: "system",
              content: `Failed to switch session: ${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        }
      },
      [
        setUi,
        setInput,
        setMessages,
        setApproval,
        setApprovalQueue,
        setSession,
        agent,
        session.id,
        session.modelName,
        buffer,
        refreshStatic
      ]
    );
    const handlePromptSelect = useCallback(
      async (prompt) => {
        const commandName = prompt.displayName || prompt.name;
        const commandText = `/${commandName}`;
        setUi((prev) => ({ ...prev, activeOverlay: "none", mcpWizardServerType: null }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        if (onSubmitPromptCommand) {
          await onSubmitPromptCommand(commandText);
          return;
        }
        const userMessage = createUserMessage(commandText);
        setMessages((prev) => [...prev, userMessage]);
        setUi((prev) => ({ ...prev, isProcessing: true, isCancelling: false }));
        const { CommandService } = await import("../services/CommandService.js");
        const commandService = new CommandService();
        try {
          const result = await commandService.executeCommand(
            commandName,
            [],
            agent,
            session.id || void 0
          );
          if (result.type === "output" && result.output) {
            const output = result.output;
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("command"),
                role: "system",
                content: output,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
          }
          if (result.type === "styled" && result.styled) {
            const { fallbackText, styledType, styledData } = result.styled;
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("command"),
                role: "system",
                content: fallbackText,
                timestamp: /* @__PURE__ */ new Date(),
                styledType,
                styledData
              }
            ]);
          }
          setUi((prev) => ({
            ...prev,
            isProcessing: false,
            isCancelling: false,
            isThinking: false
          }));
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("error"),
              role: "system",
              content: `${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          setUi((prev) => ({
            ...prev,
            isProcessing: false,
            isCancelling: false,
            isThinking: false
          }));
        }
      },
      [setUi, setInput, setMessages, agent, session.id, buffer, onSubmitPromptCommand]
    );
    const handleSystemCommandSelect = useCallback(
      async (command) => {
        const { getCommandOverlay } = await import("../utils/commandOverlays.js");
        const overlay = getCommandOverlay(command, [], agent);
        if (overlay) {
          buffer.setText("");
          setInput((prev) => ({ ...prev, historyIndex: -1 }));
          setUi((prev) => ({
            ...prev,
            activeOverlay: overlay,
            mcpWizardServerType: null
          }));
          return;
        }
        const commandText = `/${command}`;
        setUi((prev) => ({ ...prev, activeOverlay: "none", mcpWizardServerType: null }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        const userMessage = createUserMessage(commandText);
        setMessages((prev) => [...prev, userMessage]);
        setUi((prev) => ({ ...prev, isProcessing: true, isCancelling: false }));
        const { CommandService } = await import("../services/CommandService.js");
        const commandService = new CommandService();
        try {
          const result = await commandService.executeCommand(
            command,
            [],
            agent,
            session.id || void 0
          );
          if (result.type === "output" && result.output) {
            const output = result.output;
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("command"),
                role: "system",
                content: output,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
          }
          if (result.type === "styled" && result.styled) {
            const { fallbackText, styledType, styledData } = result.styled;
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("command"),
                role: "system",
                content: fallbackText,
                timestamp: /* @__PURE__ */ new Date(),
                styledType,
                styledData
              }
            ]);
          }
          setUi((prev) => ({
            ...prev,
            isProcessing: false,
            isCancelling: false,
            isThinking: false
          }));
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("error"),
              role: "system",
              content: `${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          setUi((prev) => ({
            ...prev,
            isProcessing: false,
            isCancelling: false,
            isThinking: false
          }));
        }
      },
      [setInput, setUi, setMessages, agent, session.id, buffer]
    );
    const handleLoadIntoInput = useCallback(
      (text) => {
        buffer.setText(text);
        setInput((prev) => ({ ...prev, value: text }));
        setUi((prev) => ({ ...prev, activeOverlay: "none", mcpWizardServerType: null }));
      },
      [buffer, setInput, setUi]
    );
    const handleResourceSelect = useCallback(
      (resource) => {
        const atIndex = input.value.lastIndexOf("@");
        if (atIndex >= 0) {
          const before = input.value.slice(0, atIndex + 1);
          const uriParts = resource.uri.split(/[\\/]/);
          let reference = resource.name || uriParts[uriParts.length - 1] || resource.uri;
          const rawUri = resource.uri.replace(/^(fs|file):\/\//, "");
          if (path.isAbsolute(rawUri)) {
            try {
              const relativePath = path.relative(process.cwd(), rawUri);
              reference = relativePath;
            } catch {
            }
          }
          const newValue = `${before}${reference} `;
          buffer.setText(newValue);
          setInput((prev) => ({ ...prev, value: newValue }));
        }
        setUi((prev) => ({ ...prev, activeOverlay: "none", mcpWizardServerType: null }));
      },
      [input.value, buffer, setInput, setUi]
    );
    const handleClose = useCallback(() => {
      setUi((prev) => ({
        ...prev,
        activeOverlay: "none",
        mcpWizardServerType: null,
        commandOutput: null,
        insufficientCredits: null
      }));
    }, [setUi]);
    const handleLoginDone = useCallback(
      (outcome) => {
        void (async () => {
          handleClose();
          if (outcome.outcome === "closed") {
            return;
          }
          if (outcome.outcome === "cancelled") {
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("system"),
                role: "system",
                content: "Login cancelled.",
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
            return;
          }
          let refreshWarning = null;
          if (outcome.hasDextoApiKey) {
            try {
              await refreshDextoNovaAuthAfterLogin(agent, session.id || void 0);
            } catch (error) {
              refreshWarning = `Logged in, but failed to refresh the active Dexto Nova session: ${error instanceof Error ? error.message : String(error)}`;
            }
          }
          const userLabel = outcome.email ? ` as ${outcome.email}` : "";
          const keyLine = outcome.hasDextoApiKey ? `\u{1F511} DEXTO_API_KEY ready${outcome.keyId ? ` (Key ID: ${outcome.keyId})` : ""}` : "\u26A0\uFE0F Failed to provision DEXTO_API_KEY (you can still use your own API keys)";
          const content = [
            `\u2705 Logged in${userLabel}`,
            keyLine,
            ...refreshWarning ? [`\u26A0\uFE0F ${refreshWarning}`] : []
          ].join("\n");
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        })();
      },
      [agent, handleClose, session.id, setMessages]
    );
    const handleLogoutDone = useCallback(
      (outcome) => {
        handleClose();
        if (outcome.outcome === "closed") {
          return;
        }
        if (outcome.outcome === "cancelled") {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: "Logout cancelled.",
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          return;
        }
        const warning = outcome.wasUsingDextoCredits ? "\n\nNext steps:\n\u2022 Run `/login` to log back in\n\u2022 Or run `dexto setup` to configure a different provider" : "";
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: `\u2705 Successfully logged out${warning}`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
      },
      [handleClose, setMessages]
    );
    const handleConnectDone = useCallback(
      async (outcome) => {
        handleClose();
        if (outcome.outcome === "closed") {
          return;
        }
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: outcome.outcome === "success" ? `\u2705 ${outcome.message}` : "Model provider connection cancelled.",
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
        if (outcome.outcome !== "success") {
          return;
        }
        const currentConfig = agent.getCurrentLLMConfig(session.id || void 0);
        if (currentConfig.provider !== outcome.providerId) {
          return;
        }
        try {
          await agent.switchLLM(
            {
              provider: currentConfig.provider,
              model: currentConfig.model,
              ...currentConfig.baseURL ? { baseURL: currentConfig.baseURL } : {},
              ...currentConfig.reasoning ? { reasoning: currentConfig.reasoning } : {}
            },
            session.id || void 0
          );
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("error"),
              role: "system",
              content: `Failed to apply model provider connection: ${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        }
      },
      [agent, handleClose, session.id, setMessages]
    );
    const handleLogLevelSelect = useCallback(
      (level) => {
        setUi((prev) => ({ ...prev, activeOverlay: "none", mcpWizardServerType: null }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        void agent.setLogLevel(
          level,
          session.id ? { sessionId: session.id } : void 0
        );
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: `\u{1F4CA} Log level set to: ${level}`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
      },
      [setUi, setInput, setMessages, agent, buffer, getConfigFilePathOrWarn, session.id]
    );
    const handleStreamSelect = useCallback(
      (enabled) => {
        setUi((prev) => ({ ...prev, activeOverlay: "none", mcpWizardServerType: null }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: enabled ? "\u25B6\uFE0F Streaming enabled - responses will appear as they are generated" : "\u23F8\uFE0F Streaming disabled - responses will appear when complete",
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
      },
      [setUi, setInput, setMessages, buffer]
    );
    const handleToggleShowReasoning = useCallback(() => {
      setUi((prev) => ({ ...prev, showReasoning: !prev.showReasoning }));
    }, [setUi]);
    const handleReasoningNotify = useCallback(
      (message) => {
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: `\u{1F9E0} ${message}`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
      },
      [setMessages]
    );
    const handleSetReasoningBudgetTokens = useCallback(
      async (budgetTokens) => {
        const sessionId = session.id || void 0;
        const current = agent.getCurrentLLMConfig(sessionId);
        const profile = getReasoningProfile(current.provider, current.model);
        const defaultVariant = profile.defaultVariant;
        const variant = current.reasoning?.variant ?? defaultVariant ?? profile.supportedVariants[0];
        if (variant === void 0) {
          return;
        }
        const reasoningUpdate = budgetTokens === void 0 && defaultVariant !== void 0 && variant === defaultVariant ? { reasoning: null } : {
          reasoning: {
            variant,
            ...typeof budgetTokens === "number" ? { budgetTokens } : {}
          }
        };
        await agent.switchLLM(
          {
            provider: current.provider,
            model: current.model,
            ...reasoningUpdate
          },
          sessionId
        );
      },
      [agent, session.id]
    );
    const handleMcpServerListAction = useCallback(
      (action) => {
        if (action.type === "select-server") {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "mcp-server-actions",
            selectedMcpServer: action.server
          }));
        } else if (action.type === "add-new") {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "mcp-add-choice"
          }));
        }
      },
      [setUi]
    );
    const handleMcpServerAction = useCallback(
      async (action) => {
        const { server } = action;
        if (action.type === "back") {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "mcp-server-list",
            selectedMcpServer: null
          }));
          return;
        }
        setUi((prev) => ({
          ...prev,
          activeOverlay: "none",
          selectedMcpServer: null,
          mcpWizardServerType: null,
          isProcessing: true,
          isCancelling: false
        }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        if (action.type === "enable" || action.type === "disable") {
          const newEnabled = action.type === "enable";
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `${newEnabled ? "\u25B6\uFE0F" : "\u23F8\uFE0F"} ${newEnabled ? "Enabling" : "Disabling"} ${server.name}...`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          try {
            if (newEnabled) {
              try {
                await agent.enableMcpServer(server.name);
              } catch (connectError) {
                setMessages((prev) => [
                  ...prev,
                  {
                    id: generateMessageId("system"),
                    role: "system",
                    content: `\u26A0\uFE0F Failed to enable server: ${connectError instanceof Error ? connectError.message : String(connectError)}`,
                    timestamp: /* @__PURE__ */ new Date()
                  }
                ]);
                setUi((prev) => ({
                  ...prev,
                  isProcessing: false,
                  isCancelling: false,
                  isThinking: false
                }));
                return;
              }
            } else {
              await agent.disableMcpServer(server.name);
            }
            const { updateMcpServerField } = await import("@dexto/agent-management");
            const agentPath = getConfigFilePathOrWarn("persist MCP server settings");
            if (!agentPath) {
              return;
            }
            await updateMcpServerField(agentPath, server.name, "enabled", newEnabled);
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("system"),
                role: "system",
                content: `\u2705 ${server.name} ${newEnabled ? "enabled" : "disabled"}`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
          } catch (error) {
            let errorMessage = error instanceof Error ? error.message : String(error);
            if (error instanceof DextoValidationError && error.issues.length > 0) {
              const issueDetails = error.issues.map((i) => {
                const path2 = i.path?.length ? `[${i.path.join(".")}] ` : "";
                return `  - ${path2}${i.message}`;
              }).join("\n");
              errorMessage = `Validation failed:
${issueDetails}`;
            }
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("error"),
                role: "system",
                content: `Failed to ${action.type} server: ${errorMessage}`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
          }
        } else if (action.type === "authenticate") {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u{1F510} Authenticating ${server.name}...`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          try {
            await agent.restartMcpServer(server.name);
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("system"),
                role: "system",
                content: `\u2705 Authenticated ${server.name}`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
          } catch (error) {
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("error"),
                role: "system",
                content: `Failed to authenticate server: ${error instanceof Error ? error.message : String(error)}`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
          }
        } else if (action.type === "delete") {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u{1F5D1}\uFE0F Deleting ${server.name}...`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          try {
            const { removeMcpServerFromConfig } = await import("@dexto/agent-management");
            const agentPath = getConfigFilePathOrWarn("persist MCP server deletion");
            if (agentPath) {
              await removeMcpServerFromConfig(agentPath, server.name);
            }
            try {
              await agent.removeMcpServer(server.name);
            } catch {
            }
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("system"),
                role: "system",
                content: `\u2705 Deleted ${server.name}`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
          } catch (error) {
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("error"),
                role: "system",
                content: `Failed to delete server: ${error instanceof Error ? error.message : String(error)}`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
          }
        }
        setUi((prev) => ({
          ...prev,
          isProcessing: false,
          isCancelling: false,
          isThinking: false
        }));
      },
      [setUi, setInput, setMessages, agent, buffer]
    );
    const handleMcpAddChoice = useCallback(
      (choice) => {
        if (choice === "back") {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "mcp-server-list"
          }));
        } else if (choice === "registry") {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "mcp-add-selector"
          }));
        } else if (choice === "custom") {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "mcp-custom-type-selector"
          }));
        }
      },
      [setUi]
    );
    const handleMcpAddSelect = useCallback(
      async (result) => {
        setUi((prev) => ({ ...prev, activeOverlay: "none", mcpWizardServerType: null }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        setUi((prev) => ({ ...prev, isProcessing: true, isCancelling: false }));
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: `\u{1F50C} Connecting to ${result.entry.name}...`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
        try {
          const mcpConfig = result.entry.config;
          await agent.addMcpServer(result.entry.id, mcpConfig);
          captureAnalytics("dexto_mcp_server_connected", {
            source: "cli",
            serverName: result.entry.name,
            transportType: mcpConfig.type
          });
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u2705 Connected to ${result.entry.name}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `Failed to connect: ${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        }
        setUi((prev) => ({
          ...prev,
          isProcessing: false,
          isCancelling: false,
          isThinking: false
        }));
      },
      [setUi, setInput, setMessages, agent, buffer]
    );
    const handleMcpCustomTypeSelect = useCallback(
      (serverType) => {
        setUi((prev) => ({
          ...prev,
          mcpWizardServerType: serverType,
          activeOverlay: "mcp-custom-wizard"
        }));
      },
      [setUi]
    );
    const handleMcpCustomWizardComplete = useCallback(
      async (config) => {
        setUi((prev) => ({ ...prev, activeOverlay: "none", mcpWizardServerType: null }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        setUi((prev) => ({ ...prev, isProcessing: true, isCancelling: false }));
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: `\u{1F50C} Connecting to ${config.name}...`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
        try {
          let serverConfig;
          if (config.serverType === "stdio") {
            serverConfig = {
              type: "stdio",
              command: config.command,
              args: config.args || []
            };
          } else if (config.serverType === "http") {
            serverConfig = {
              type: "http",
              url: config.url
            };
          } else {
            serverConfig = {
              type: "sse",
              url: config.url
            };
          }
          await agent.addMcpServer(config.name, serverConfig);
          captureAnalytics("dexto_mcp_server_connected", {
            source: "cli",
            serverName: config.name,
            transportType: serverConfig.type
          });
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u2705 Connected to ${config.name}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `Failed to connect: ${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        }
        setUi((prev) => ({
          ...prev,
          isProcessing: false,
          isCancelling: false,
          isThinking: false
        }));
      },
      [setUi, setInput, setMessages, agent, buffer]
    );
    const handlePluginManagerAction = useCallback(
      (action) => {
        if (action === "list") {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "plugin-list"
          }));
        } else if (action === "marketplace") {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "marketplace-browser"
          }));
        }
      },
      [setUi]
    );
    const handlePluginSelect = useCallback(
      (plugin) => {
        setSelectedPlugin(plugin);
        setUi((prev) => ({
          ...prev,
          activeOverlay: "plugin-actions"
        }));
      },
      [setUi]
    );
    const handlePluginAction = useCallback(
      async (action) => {
        if (action.type === "back") {
          setSelectedPlugin(null);
          setUi((prev) => ({
            ...prev,
            activeOverlay: "plugin-list"
          }));
          return;
        }
        if (action.type === "uninstall") {
          setUi((prev) => ({ ...prev, activeOverlay: "none", isProcessing: true }));
          try {
            const { uninstallPlugin, reloadAgentConfigFromFile, enrichAgentConfig } = await import("@dexto/agent-management");
            await uninstallPlugin(action.plugin.name);
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("system"),
                role: "system",
                content: `Plugin '${action.plugin.name}' has been uninstalled.`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
            try {
              const agentPath = getConfigFilePathOrWarn(
                "refresh prompts after plugin uninstall"
              );
              if (!agentPath) {
                return;
              }
              const newConfig = await reloadAgentConfigFromFile(agentPath);
              const enrichedConfig = enrichAgentConfig(newConfig, agentPath);
              await agent.refreshPrompts(enrichedConfig.prompts);
            } catch {
            }
          } catch (error) {
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("error"),
                role: "system",
                content: `Failed to uninstall plugin: ${error instanceof Error ? error.message : String(error)}`,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
          }
          setSelectedPlugin(null);
          setUi((prev) => ({ ...prev, isProcessing: false }));
        }
      },
      [setUi, setMessages, agent, getConfigFilePathOrWarn]
    );
    const handleMarketplaceBrowserAction = useCallback(
      async (action) => {
        if (action.type === "add-marketplace") {
          setUi((prev) => ({ ...prev, activeOverlay: "marketplace-add" }));
        } else if (action.type === "plugin-installed") {
          setUi((prev) => ({ ...prev, activeOverlay: "none" }));
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u2705 Plugin '${action.pluginName}' installed from ${action.marketplace}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          try {
            const { reloadAgentConfigFromFile, enrichAgentConfig } = await import("@dexto/agent-management");
            const agentPath = getConfigFilePathOrWarn(
              "refresh prompts after plugin install"
            );
            if (!agentPath) {
              return;
            }
            const newConfig = await reloadAgentConfigFromFile(agentPath);
            const enrichedConfig = enrichAgentConfig(newConfig, agentPath);
            await agent.refreshPrompts(enrichedConfig.prompts);
          } catch (error) {
          }
        }
      },
      [setUi, setMessages, agent, getConfigFilePathOrWarn]
    );
    const handleMarketplaceAddComplete = useCallback(
      (name, pluginCount) => {
        setUi((prev) => ({ ...prev, activeOverlay: "marketplace-browser" }));
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: `\u2705 Marketplace '${name}' added (${pluginCount} plugins found)`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
      },
      [setUi, setMessages]
    );
    const handleSessionSubcommandSelect = useCallback(
      async (action) => {
        if (action === "switch") {
          setInput((prev) => ({ ...prev, value: "/session switch" }));
          setUi((prev) => ({ ...prev, activeOverlay: "session-selector" }));
          return;
        }
        setUi((prev) => ({ ...prev, activeOverlay: "none", mcpWizardServerType: null }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        setUi((prev) => ({ ...prev, isProcessing: true, isCancelling: false }));
        try {
          const { CommandService } = await import("../services/CommandService.js");
          const commandService = new CommandService();
          const result = await commandService.executeCommand(
            "session",
            [action],
            agent,
            session.id || void 0
          );
          if (result.type === "output" && result.output) {
            const output = result.output;
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("command"),
                role: "system",
                content: output,
                timestamp: /* @__PURE__ */ new Date()
              }
            ]);
          }
          if (result.type === "styled" && result.styled) {
            const { fallbackText, styledType, styledData } = result.styled;
            setMessages((prev) => [
              ...prev,
              {
                id: generateMessageId("command"),
                role: "system",
                content: fallbackText,
                timestamp: /* @__PURE__ */ new Date(),
                styledType,
                styledData
              }
            ]);
          }
          setUi((prev) => ({
            ...prev,
            isProcessing: false,
            isCancelling: false,
            isThinking: false
          }));
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("error"),
              role: "system",
              content: `${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          setUi((prev) => ({
            ...prev,
            isProcessing: false,
            isCancelling: false,
            isThinking: false
          }));
        }
      },
      [setInput, setUi, setMessages, agent, session.id, buffer]
    );
    const handlePromptListAction = useCallback(
      async (action) => {
        if (action.type === "add-prompt") {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "prompt-add-choice"
          }));
        } else if (action.type === "delete-prompt") {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "prompt-delete-selector"
          }));
        } else if (action.type === "select-prompt") {
          const displayName = action.prompt.displayName || action.prompt.name;
          const commandText = `/${displayName}`;
          setUi((prev) => ({
            ...prev,
            activeOverlay: "none",
            promptAddWizard: null
          }));
          buffer.setText("");
          setInput((prev) => ({ ...prev, historyIndex: -1 }));
          if (onSubmitPromptCommand) {
            await onSubmitPromptCommand(commandText);
          }
        }
      },
      [setUi, setInput, buffer, onSubmitPromptCommand]
    );
    const handlePromptLoadIntoInput = useCallback(
      (text) => {
        buffer.setText(text);
        setInput((prev) => ({ ...prev, value: text }));
        setUi((prev) => ({
          ...prev,
          activeOverlay: "none",
          promptAddWizard: null
        }));
      },
      [buffer, setInput, setUi]
    );
    const handlePromptAddChoice = useCallback(
      (choice) => {
        if (choice === "back") {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "prompt-list"
          }));
        } else {
          setUi((prev) => ({
            ...prev,
            activeOverlay: "prompt-add-wizard",
            promptAddWizard: {
              scope: choice,
              step: "name",
              name: "",
              title: "",
              description: "",
              content: ""
            }
          }));
        }
      },
      [setUi]
    );
    const handlePromptAddComplete = useCallback(
      async (data) => {
        const scope = ui.promptAddWizard?.scope || "agent";
        setUi((prev) => ({
          ...prev,
          activeOverlay: "none",
          promptAddWizard: null
        }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: `\u{1F4DD} Creating ${scope === "shared" ? "shared" : "agent"} prompt "${data.name}"...`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
        try {
          const { mkdir, writeFile } = await import("fs/promises");
          const { dirname, join } = await import("path");
          const SAFE_NAME_PATTERN = /^[a-z0-9][a-z0-9-_]*$/i;
          if (!SAFE_NAME_PATTERN.test(data.name)) {
            throw new Error(
              `Invalid prompt name "${data.name}". Names must start with a letter or number and contain only letters, numbers, hyphens, and underscores.`
            );
          }
          const frontmatterLines = [
            "---",
            `id: ${data.name}`,
            data.title ? `title: "${data.title}"` : null,
            data.description ? `description: "${data.description}"` : null,
            data.argumentHint ? `argument-hint: ${data.argumentHint}` : null,
            "---"
          ].filter(Boolean);
          const fileContent = `${frontmatterLines.join("\n")}

${data.content}
`;
          let filePath;
          if (scope === "shared") {
            const {
              getExecutionContext,
              findDextoSourceRoot,
              findDextoProjectRoot,
              getDextoGlobalPath
            } = await import("@dexto/agent-management");
            const context = getExecutionContext();
            let commandsDir;
            if (context === "dexto-source") {
              const isDevMode = process.env.DEXTO_DEV_MODE === "true";
              if (isDevMode) {
                const sourceRoot = findDextoSourceRoot();
                commandsDir = sourceRoot ? join(sourceRoot, "commands") : getDextoGlobalPath("commands");
              } else {
                commandsDir = getDextoGlobalPath("commands");
              }
            } else if (context === "dexto-project") {
              const projectRoot = findDextoProjectRoot();
              commandsDir = projectRoot ? join(projectRoot, "commands") : getDextoGlobalPath("commands");
            } else {
              commandsDir = getDextoGlobalPath("commands");
            }
            filePath = join(commandsDir, `${data.name}.md`);
            await mkdir(commandsDir, { recursive: true });
            await writeFile(filePath, fileContent, "utf-8");
            const { reloadAgentConfigFromFile, enrichAgentConfig } = await import("@dexto/agent-management");
            const agentPath = getConfigFilePathOrWarn(
              "refresh prompts after creating shared prompt"
            );
            if (!agentPath) {
              return;
            }
            const newConfig = await reloadAgentConfigFromFile(agentPath);
            const enrichedConfig = enrichAgentConfig(newConfig, agentPath);
            await agent.refreshPrompts(enrichedConfig.prompts);
          } else {
            const agentPath = getConfigFilePathOrWarn(
              "create prompt in agent prompts directory"
            );
            if (!agentPath) {
              return;
            }
            const agentDir = dirname(agentPath);
            const promptsDir = join(agentDir, "prompts");
            filePath = join(promptsDir, `${data.name}.md`);
            await mkdir(promptsDir, { recursive: true });
            await writeFile(filePath, fileContent, "utf-8");
            const {
              addPromptToAgentConfig,
              reloadAgentConfigFromFile,
              enrichAgentConfig
            } = await import("@dexto/agent-management");
            await addPromptToAgentConfig(agentPath, {
              type: "file",
              file: `\${{dexto.agent_dir}}/prompts/${data.name}.md`
            });
            const newConfig = await reloadAgentConfigFromFile(agentPath);
            const enrichedConfig = enrichAgentConfig(newConfig, agentPath);
            await agent.refreshPrompts(enrichedConfig.prompts);
          }
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u2705 Created prompt "${data.name}"
\u{1F4C4} File: ${filePath}

Use /${data.name} to run it.`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("error"),
              role: "system",
              content: `Failed to create prompt: ${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        }
      },
      [
        ui.promptAddWizard?.scope,
        setUi,
        setInput,
        setMessages,
        buffer,
        agent,
        getConfigFilePathOrWarn
      ]
    );
    const handlePromptDelete = useCallback(
      async (deletable) => {
        const displayName = deletable.prompt.displayName || deletable.prompt.name;
        setMessages((prev) => [
          ...prev,
          {
            id: generateMessageId("system"),
            role: "system",
            content: `\u{1F5D1}\uFE0F Deleting prompt "${displayName}"...`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
        try {
          const { deletePromptByMetadata, reloadAgentConfigFromFile, enrichAgentConfig } = await import("@dexto/agent-management");
          const agentPath = getConfigFilePathOrWarn("delete prompt");
          if (!agentPath) {
            return;
          }
          const promptMetadata = deletable.prompt.metadata;
          const result = await deletePromptByMetadata(
            agentPath,
            {
              name: deletable.prompt.name,
              metadata: {
                filePath: deletable.filePath,
                originalId: promptMetadata?.originalId
              }
            },
            { deleteFile: true }
          );
          if (!result.success) {
            throw new Error(result.error || "Failed to delete prompt");
          }
          const newConfig = await reloadAgentConfigFromFile(agentPath);
          const enrichedConfig = enrichAgentConfig(newConfig, agentPath);
          await agent.refreshPrompts(enrichedConfig.prompts);
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u2705 Deleted prompt "${displayName}"`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          setUi((prev) => ({
            ...prev,
            activeOverlay: "prompt-list"
          }));
          promptListRef.current?.refresh();
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("error"),
              role: "system",
              content: `Failed to delete prompt: ${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
          setUi((prev) => ({
            ...prev,
            activeOverlay: "prompt-list"
          }));
        }
      },
      [setUi, setMessages, agent, getConfigFilePathOrWarn]
    );
    const handlePromptAddWizardClose = useCallback(() => {
      setUi((prev) => ({
        ...prev,
        activeOverlay: "prompt-add-choice",
        promptAddWizard: null
      }));
    }, [setUi]);
    const handlePromptDeleteClose = useCallback(() => {
      setUi((prev) => ({
        ...prev,
        activeOverlay: "prompt-list"
      }));
      promptListRef.current?.refresh();
    }, [setUi]);
    const handlePromptAddChoiceClose = useCallback(() => {
      setUi((prev) => ({
        ...prev,
        activeOverlay: "prompt-list"
      }));
    }, [setUi]);
    const [currentSessionTitle, setCurrentSessionTitle] = useState(
      void 0
    );
    React.useEffect(() => {
      if (ui.activeOverlay === "session-rename" && session.id) {
        void agent.getSessionTitle(session.id).then(setCurrentSessionTitle);
      }
    }, [ui.activeOverlay, session.id, agent]);
    const handleSessionRename = useCallback(
      async (newTitle) => {
        if (!session.id) return;
        setUi((prev) => ({ ...prev, activeOverlay: "none" }));
        buffer.setText("");
        setInput((prev) => ({ ...prev, historyIndex: -1 }));
        try {
          await agent.setSessionTitle(session.id, newTitle);
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("system"),
              role: "system",
              content: `\u2705 Session renamed to: ${newTitle}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        } catch (error) {
          setMessages((prev) => [
            ...prev,
            {
              id: generateMessageId("error"),
              role: "system",
              content: `Failed to rename session: ${error instanceof Error ? error.message : String(error)}`,
              timestamp: /* @__PURE__ */ new Date()
            }
          ]);
        }
      },
      [session.id, setUi, setInput, setMessages, agent, buffer]
    );
    const handleSessionRenameClose = useCallback(() => {
      setUi((prev) => ({ ...prev, activeOverlay: "none" }));
    }, [setUi]);
    const currentLLMConfig = session.id ? agent.getCurrentLLMConfig(session.id) : agent.getCurrentLLMConfig();
    const chatGPTFallbackTarget = resolveChatGPTFallbackModel(currentLLMConfig.model);
    const chatGPTFallbackKeyStatus = getProviderKeyStatus(chatGPTFallbackTarget.provider);
    const hideCliChrome = shouldHideCliChrome(ui.activeOverlay, approval);
    const overlayContent = /* @__PURE__ */ jsxs(Fragment, { children: [
      approval && /* @__PURE__ */ jsx(
        ApprovalPrompt,
        {
          ref: approvalRef,
          approval,
          onApprove: handleApprove,
          onDeny: handleDeny,
          onCancel: handleCancelApproval
        }
      ),
      ui.activeOverlay === "slash-autocomplete" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        SlashCommandAutocomplete,
        {
          ref: slashAutocompleteRef,
          isVisible: true,
          searchQuery: input.value,
          onSelectPrompt: handlePromptSelect,
          onSelectSystemCommand: handleSystemCommandSelect,
          onLoadIntoInput: handleLoadIntoInput,
          onSubmitRaw: onSubmitPromptCommand,
          onClose: handleClose,
          agent
        }
      ) }),
      ui.activeOverlay === "resource-autocomplete" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        ResourceAutocomplete,
        {
          ref: resourceAutocompleteRef,
          isVisible: true,
          searchQuery: input.value,
          onSelectResource: handleResourceSelect,
          onLoadIntoInput: handleLoadIntoInput,
          onClose: handleClose,
          agent
        }
      ) }),
      ui.activeOverlay === "model-selector" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        ModelSelectorRefactored,
        {
          ref: modelSelectorRef,
          isVisible: true,
          onSelectModel: handleModelSelect,
          onSetDefaultModel: handleSetDefaultModel,
          onClose: handleClose,
          onAddCustomModel: handleAddCustomModel,
          onEditCustomModel: handleEditCustomModel,
          agent
        }
      ) }),
      ui.activeOverlay === "reasoning" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        ReasoningOverlay,
        {
          ref: reasoningOverlayRef,
          isVisible: true,
          agent,
          sessionId: session.id,
          showReasoning: ui.showReasoning,
          onToggleShowReasoning: handleToggleShowReasoning,
          onSetBudgetTokens: handleSetReasoningBudgetTokens,
          onNotify: handleReasoningNotify,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "session-selector" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        SessionSelectorRefactored,
        {
          ref: sessionSelectorRef,
          isVisible: true,
          onSelectSession: handleSessionSelect,
          onClose: handleClose,
          agent,
          currentSessionId: session.id || void 0
        }
      ) }),
      ui.activeOverlay === "log-level-selector" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        LogLevelSelector,
        {
          ref: logLevelSelectorRef,
          isVisible: true,
          onSelect: handleLogLevelSelect,
          onClose: handleClose,
          agent,
          sessionId: session.id
        }
      ) }),
      ui.activeOverlay === "stream-selector" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        StreamSelector,
        {
          ref: streamSelectorRef,
          isVisible: true,
          onSelect: handleStreamSelect,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "sounds-selector" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        SoundsSelector,
        {
          ref: soundsSelectorRef,
          isVisible: true,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "tool-browser" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        ToolBrowser,
        {
          ref: toolBrowserRef,
          isVisible: true,
          onClose: handleClose,
          agent,
          sessionId: session.id
        }
      ) }),
      ui.activeOverlay === "command-output" && ui.commandOutput && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        CommandOutputOverlay,
        {
          ref: commandOutputRef,
          isVisible: true,
          title: ui.commandOutput.title,
          content: ui.commandOutput.content,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "mcp-server-list" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        McpServerList,
        {
          ref: mcpServerListRef,
          isVisible: true,
          onAction: handleMcpServerListAction,
          onClose: handleClose,
          agent
        }
      ) }),
      ui.activeOverlay === "mcp-server-actions" && ui.selectedMcpServer && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        McpServerActions,
        {
          ref: mcpServerActionsRef,
          isVisible: true,
          server: ui.selectedMcpServer,
          onAction: handleMcpServerAction,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "mcp-add-choice" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        McpAddChoice,
        {
          ref: mcpAddChoiceRef,
          isVisible: true,
          onSelect: handleMcpAddChoice,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "mcp-add-selector" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        McpAddSelector,
        {
          ref: mcpAddSelectorRef,
          isVisible: true,
          onSelect: handleMcpAddSelect,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "mcp-custom-type-selector" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        McpCustomTypeSelector,
        {
          ref: mcpCustomTypeSelectorRef,
          isVisible: true,
          onSelect: handleMcpCustomTypeSelect,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "mcp-custom-wizard" && ui.mcpWizardServerType && /* @__PURE__ */ jsx(
        McpCustomWizard,
        {
          ref: mcpCustomWizardRef,
          isVisible: true,
          serverType: ui.mcpWizardServerType,
          onComplete: handleMcpCustomWizardComplete,
          onClose: handleClose
        }
      ),
      ui.activeOverlay === "custom-model-wizard" && /* @__PURE__ */ jsx(
        CustomModelWizard,
        {
          ref: customModelWizardRef,
          isVisible: true,
          onComplete: handleCustomModelComplete,
          onClose: () => {
            setEditingModel(null);
            handleClose();
          },
          initialModel: editingModel
        }
      ),
      ui.activeOverlay === "plugin-manager" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        PluginManager,
        {
          ref: pluginManagerRef,
          isVisible: true,
          onAction: handlePluginManagerAction,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "plugin-list" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        PluginList,
        {
          ref: pluginListRef,
          isVisible: true,
          onPluginSelect: handlePluginSelect,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "plugin-actions" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        PluginActions,
        {
          ref: pluginActionsRef,
          isVisible: true,
          plugin: selectedPlugin,
          onAction: handlePluginAction,
          onClose: () => {
            setSelectedPlugin(null);
            setUi((prev) => ({
              ...prev,
              activeOverlay: "plugin-list"
            }));
          }
        }
      ) }),
      ui.activeOverlay === "marketplace-browser" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        MarketplaceBrowser,
        {
          ref: marketplaceBrowserRef,
          isVisible: true,
          onAction: handleMarketplaceBrowserAction,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "marketplace-add" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        MarketplaceAddPrompt,
        {
          ref: marketplaceAddPromptRef,
          isVisible: true,
          onComplete: handleMarketplaceAddComplete,
          onClose: () => setUi((prev) => ({ ...prev, activeOverlay: "marketplace-browser" }))
        }
      ) }),
      ui.activeOverlay === "session-subcommand-selector" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        SessionSubcommandSelector,
        {
          ref: sessionSubcommandSelectorRef,
          isVisible: true,
          onSelect: handleSessionSubcommandSelect,
          onClose: handleClose
        }
      ) }),
      ui.activeOverlay === "chatgpt-usage-cap" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        ChatGPTUsageCapOverlay,
        {
          ref: chatGPTUsageCapRef,
          isVisible: true,
          currentModelDisplayName: session.modelName,
          fallbackModelDisplayName: chatGPTFallbackTarget.displayName,
          usedDefaultFallback: chatGPTFallbackTarget.usedDefaultFallback,
          apiKeyConfigured: chatGPTFallbackKeyStatus.hasApiKey,
          status: ui.chatgptRateLimitStatus,
          onConfirm: handleChatGPTUsageCapConfirm,
          onClose: handleChatGPTUsageCapClose
        }
      ) }),
      ui.activeOverlay === "insufficient-credits" && ui.insufficientCredits && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        InsufficientCreditsOverlay,
        {
          ref: insufficientCreditsRef,
          isVisible: true,
          initialBalanceUsd: ui.insufficientCredits.balanceUsd,
          onResolved: handleInsufficientCreditsResolved,
          onClose: handleInsufficientCreditsClose
        }
      ) }),
      ui.activeOverlay === "login" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        LoginOverlay,
        {
          ref: loginOverlayRef,
          isVisible: true,
          onDone: handleLoginDone
        }
      ) }),
      ui.activeOverlay === "logout" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        LogoutOverlay,
        {
          ref: logoutOverlayRef,
          isVisible: true,
          onDone: handleLogoutDone
        }
      ) }),
      ui.activeOverlay === "connect" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        ConnectOverlay,
        {
          ref: connectOverlayRef,
          isVisible: true,
          onDone: handleConnectDone
        }
      ) }),
      ui.activeOverlay === "api-key-input" && ui.pendingModelSwitch && /* @__PURE__ */ jsx(
        ApiKeyInput,
        {
          ref: apiKeyInputRef,
          isVisible: true,
          provider: ui.pendingModelSwitch.provider,
          onSaved: handleApiKeySaved,
          onClose: handleApiKeyClose
        }
      ),
      ui.activeOverlay === "search" && /* @__PURE__ */ jsx(
        SearchOverlay,
        {
          ref: searchOverlayRef,
          isVisible: true,
          agent,
          onClose: handleClose,
          onSelectResult: handleSearchResultSelect
        }
      ),
      ui.activeOverlay === "prompt-list" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        PromptList,
        {
          ref: promptListRef,
          isVisible: true,
          onAction: handlePromptListAction,
          onLoadIntoInput: handlePromptLoadIntoInput,
          onClose: handleClose,
          agent
        }
      ) }),
      ui.activeOverlay === "prompt-add-choice" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        PromptAddChoice,
        {
          ref: promptAddChoiceRef,
          isVisible: true,
          onSelect: handlePromptAddChoice,
          onClose: handlePromptAddChoiceClose
        }
      ) }),
      ui.activeOverlay === "prompt-add-wizard" && ui.promptAddWizard && /* @__PURE__ */ jsx(
        PromptAddWizard,
        {
          ref: promptAddWizardRef,
          isVisible: true,
          scope: ui.promptAddWizard.scope,
          onComplete: handlePromptAddComplete,
          onClose: handlePromptAddWizardClose
        }
      ),
      ui.activeOverlay === "prompt-delete-selector" && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        PromptDeleteSelector,
        {
          ref: promptDeleteSelectorRef,
          isVisible: true,
          onDelete: handlePromptDelete,
          onClose: handlePromptDeleteClose,
          agent
        }
      ) }),
      ui.activeOverlay === "session-rename" && /* @__PURE__ */ jsx(
        SessionRenameOverlay,
        {
          ref: sessionRenameRef,
          isVisible: true,
          currentTitle: currentSessionTitle,
          onRename: handleSessionRename,
          onClose: handleSessionRenameClose
        }
      ),
      ui.activeOverlay === "context-stats" && session.id && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
        ContextStatsOverlay,
        {
          ref: contextStatsRef,
          isVisible: true,
          onClose: handleClose,
          agent,
          sessionId: session.id ?? ""
        }
      ) }),
      ui.activeOverlay === "export-wizard" && /* @__PURE__ */ jsx(
        ExportWizard,
        {
          ref: exportWizardRef,
          isVisible: true,
          agent,
          sessionId: session.id,
          onClose: handleClose
        }
      )
    ] });
    return hideCliChrome ? /* @__PURE__ */ jsx(FocusOverlayFrame, { children: overlayContent }) : overlayContent;
  }
);
export {
  OverlayContainer
};
