"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var useCLIState_exports = {};
__export(useCLIState_exports, {
  useCLIState: () => useCLIState
});
module.exports = __toCommonJS(useCLIState_exports);
var import_react = require("react");
var import_ink = require("ink");
var import_llm = require("@dexto/llm");
var import_core = require("@dexto/core");
var import_useAgentEvents = require("./useAgentEvents.js");
var import_useInputOrchestrator = require("./useInputOrchestrator.js");
var import_services = require("../services/index.js");
var import_messageFormatting = require("../utils/messageFormatting.js");
var import_text_buffer = require("../components/shared/text-buffer.js");
function useCLIState({
  agent,
  initialSessionId,
  startupInfo,
  initialBypassPermissions = false,
  onKeyboardScroll: _onKeyboardScroll
}) {
  const [messages, setMessages] = (0, import_react.useState)([]);
  const [pendingMessages, setPendingMessages] = (0, import_react.useState)([]);
  const [dequeuedBuffer, setDequeuedBuffer] = (0, import_react.useState)([]);
  const [steerMessages, setSteerMessages] = (0, import_react.useState)([]);
  const [queuedMessages, setQueuedMessages] = (0, import_react.useState)([]);
  const [todos, setTodos] = (0, import_react.useState)([]);
  const [ui, setUi] = (0, import_react.useState)({
    isProcessing: false,
    isCancelling: false,
    isThinking: false,
    isCompacting: false,
    activeOverlay: "none",
    showReasoning: true,
    exitWarningShown: false,
    exitWarningTimestamp: null,
    mcpWizardServerType: null,
    copyModeEnabled: false,
    pendingModelSwitch: null,
    selectedMcpServer: null,
    historySearch: {
      isActive: false,
      query: "",
      matchIndex: 0,
      originalInput: "",
      lastMatch: ""
    },
    promptAddWizard: null,
    autoApproveEdits: false,
    bypassPermissions: initialBypassPermissions,
    todoExpanded: true,
    // Default to expanded to show full todo list
    backgroundTasksRunning: 0,
    backgroundTasksExpanded: false,
    backgroundTasks: [],
    chatgptRateLimitStatus: null,
    insufficientCredits: null,
    planModeActive: false,
    planModeInitialized: false,
    commandOutput: null
  });
  const [input, setInput] = (0, import_react.useState)({
    value: "",
    history: [],
    historyIndex: -1,
    draftBeforeHistory: "",
    images: [],
    pastedBlocks: [],
    pasteCounter: 0,
    editingQueuedFollowUp: false
  });
  const initialConfig = agent.getCurrentLLMConfig();
  const [session, setSession] = (0, import_react.useState)({
    id: initialSessionId,
    hasActiveSession: initialSessionId !== null,
    modelName: (0, import_llm.getModelDisplayName)(initialConfig.model, initialConfig.provider)
  });
  const [approval, setApproval] = (0, import_react.useState)(null);
  const [approvalQueue, setApprovalQueue] = (0, import_react.useState)([]);
  const inputService = (0, import_react.useMemo)(() => new import_services.InputService(), []);
  const messageService = (0, import_react.useMemo)(() => new import_services.MessageService(), []);
  const { stdout } = (0, import_ink.useStdout)();
  const terminalWidth = stdout?.columns || 80;
  const inputWidth = Math.max(20, terminalWidth - 4);
  const handleBufferChange = (0, import_react.useCallback)((text) => {
    setInput((prev) => ({ ...prev, value: text }));
  }, []);
  const buffer = (0, import_text_buffer.useTextBuffer)({
    initialText: "",
    viewport: { width: inputWidth, height: 10 },
    onChange: handleBufferChange
  });
  (0, import_react.useEffect)(() => {
    buffer.setViewport(inputWidth, 10);
  }, [inputWidth, buffer.setViewport]);
  const overlayContainerRef = (0, import_react.useRef)(null);
  (0, import_useAgentEvents.useAgentEvents)({
    agent,
    setMessages,
    setPendingMessages,
    setUi,
    setSession,
    setInput,
    setApproval,
    setApprovalQueue,
    setSteerMessages,
    setQueuedMessages,
    currentSessionId: session.id,
    buffer
  });
  const approvalHandler = (0, import_react.useCallback)((inputStr, key) => {
    return overlayContainerRef.current?.handleInput(inputStr, key) ?? false;
  }, []);
  const overlayHandler = (0, import_react.useCallback)((inputStr, key) => {
    return overlayContainerRef.current?.handleInput(inputStr, key) ?? false;
  }, []);
  (0, import_useInputOrchestrator.useInputOrchestrator)({
    ui,
    approval,
    input,
    session,
    steerMessages,
    buffer,
    setUi,
    setInput,
    setMessages,
    setPendingMessages,
    setSteerMessages,
    agent,
    handlers: {
      approval: approvalHandler,
      overlay: overlayHandler
    }
  });
  (0, import_react.useEffect)(() => {
    setTodos([]);
  }, [session.id]);
  (0, import_react.useEffect)(() => {
    if (!initialSessionId || !session.hasActiveSession || messages.length > 0) {
      return;
    }
    let cancelled = false;
    (async () => {
      try {
        const history = await agent.getSessionHistory(initialSessionId);
        if (!history?.length || cancelled) return;
        const historyMessages = (0, import_messageFormatting.convertHistoryToUIMessages)(history, initialSessionId);
        setMessages(historyMessages);
        const userInputHistory = history.filter(import_core.isUserMessage).map(
          (msg) => msg.content.filter(
            (part) => part.type === "text"
          ).map((part) => part.text).join("\n")
        ).filter((text) => text.trim().length > 0);
        setInput((prev) => ({
          ...prev,
          history: userInputHistory,
          historyIndex: -1,
          editingQueuedFollowUp: false
        }));
      } catch (error) {
        if (cancelled) return;
        setMessages((prev) => [
          ...prev,
          {
            id: `error-${Date.now()}`,
            role: "system",
            content: `Error: ${error instanceof Error ? error.message : String(error)}`,
            timestamp: /* @__PURE__ */ new Date()
          }
        ]);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [agent, initialSessionId, messages.length, session.hasActiveSession]);
  const visibleMessages = messages;
  return {
    messages,
    setMessages,
    pendingMessages,
    setPendingMessages,
    dequeuedBuffer,
    setDequeuedBuffer,
    steerMessages,
    setSteerMessages,
    queuedMessages,
    setQueuedMessages,
    todos,
    setTodos,
    ui,
    setUi,
    input,
    setInput,
    session,
    setSession,
    approval,
    setApproval,
    approvalQueue,
    setApprovalQueue,
    buffer,
    inputService,
    messageService,
    overlayContainerRef,
    visibleMessages,
    agent,
    startupInfo
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useCLIState
});
