"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var ToolBrowser_exports = {};
__export(ToolBrowser_exports, {
  default: () => ToolBrowser_default
});
module.exports = __toCommonJS(ToolBrowser_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
var import_useTerminalSize = require("../../hooks/useTerminalSize.js");
var import_clipboardUtils = require("../../utils/clipboardUtils.js");
var import_overlaySizing = require("../../utils/overlaySizing.js");
var import_HintBar = require("../shared/HintBar.js");
const LIST_ACTIONS = ["view", "config", "back"];
const ToolBrowser = (0, import_react.forwardRef)(function ToolBrowser2({ isVisible, onClose, agent, sessionId }, ref) {
  const { columns, rows } = (0, import_useTerminalSize.useTerminalSize)();
  const maxVisibleTools = (0, import_react.useMemo)(() => {
    return (0, import_overlaySizing.getMaxVisibleItemsForTerminalRows)({
      rows,
      hardCap: 10,
      reservedRows: 16
    });
  }, [rows]);
  const [tools, setTools] = (0, import_react.useState)([]);
  const [isLoading, setIsLoading] = (0, import_react.useState)(false);
  const [loadError, setLoadError] = (0, import_react.useState)(null);
  const [selection, setSelection] = (0, import_react.useState)({ index: 0, offset: 0 });
  const [searchQuery, setSearchQuery] = (0, import_react.useState)("");
  const [viewMode, setViewMode] = (0, import_react.useState)("list");
  const [selectedTool, setSelectedTool] = (0, import_react.useState)(null);
  const [detailScrollOffset, setDetailScrollOffset] = (0, import_react.useState)(0);
  const [copyFeedback, setCopyFeedback] = (0, import_react.useState)(null);
  const [listActionsIndex, setListActionsIndex] = (0, import_react.useState)(0);
  const [configIndex, setConfigIndex] = (0, import_react.useState)(0);
  const [scopeToolName, setScopeToolName] = (0, import_react.useState)(null);
  const [scopeNextEnabled, setScopeNextEnabled] = (0, import_react.useState)(true);
  const [scopeTarget, setScopeTarget] = (0, import_react.useState)("session");
  const selectedIndexRef = (0, import_react.useRef)(0);
  const viewModeRef = (0, import_react.useRef)(viewMode);
  const detailScrollOffsetRef = (0, import_react.useRef)(detailScrollOffset);
  const detailMaxScrollOffsetRef = (0, import_react.useRef)(0);
  const selectedToolRef = (0, import_react.useRef)(null);
  const toolsRef = (0, import_react.useRef)([]);
  const listActionsIndexRef = (0, import_react.useRef)(listActionsIndex);
  const configIndexRef = (0, import_react.useRef)(configIndex);
  const scopeTargetRef = (0, import_react.useRef)(scopeTarget);
  const scopeNextEnabledRef = (0, import_react.useRef)(scopeNextEnabled);
  const scopeToolNameRef = (0, import_react.useRef)(scopeToolName);
  selectedIndexRef.current = selection.index;
  viewModeRef.current = viewMode;
  detailScrollOffsetRef.current = detailScrollOffset;
  selectedToolRef.current = selectedTool;
  toolsRef.current = tools;
  listActionsIndexRef.current = listActionsIndex;
  configIndexRef.current = configIndex;
  scopeTargetRef.current = scopeTarget;
  scopeNextEnabledRef.current = scopeNextEnabled;
  scopeToolNameRef.current = scopeToolName;
  (0, import_react.useEffect)(() => {
    if (!isVisible) return;
    let cancelled = false;
    setIsLoading(true);
    setSearchQuery("");
    setSelection({ index: 0, offset: 0 });
    setViewMode("list");
    setSelectedTool(null);
    setListActionsIndex(0);
    setConfigIndex(0);
    setLoadError(null);
    const fetchTools = async () => {
      try {
        const [allTools, mcpTools, enabledTools, autoApprovedTools] = await Promise.all([
          agent.getAllTools(),
          agent.getAllMcpTools(),
          agent.getEnabledTools(sessionId || void 0),
          sessionId ? agent.getSessionAutoApproveTools(sessionId) : Promise.resolve([])
        ]);
        const toolList = [];
        const mcpToolNames = new Set(Object.keys(mcpTools));
        const enabledToolNames = new Set(Object.keys(enabledTools));
        const autoApprovedToolNames = new Set(autoApprovedTools ?? []);
        for (const [toolName, toolInfo] of Object.entries(allTools)) {
          const isMcpTool = mcpToolNames.has(toolName) || toolName.startsWith("mcp--");
          let serverName;
          if (toolName.startsWith("mcp--")) {
            const parts = toolName.split("--");
            if (parts.length >= 2) {
              serverName = parts[1];
            }
          }
          toolList.push({
            name: toolName,
            description: toolInfo.description || "No description available",
            source: isMcpTool ? "mcp" : "local",
            serverName,
            inputSchema: toolInfo.parameters,
            isEnabled: enabledToolNames.has(toolName),
            isAutoApproved: autoApprovedToolNames.has(toolName)
          });
        }
        toolList.sort((a, b) => {
          if (a.source !== b.source) {
            return a.source === "local" ? -1 : 1;
          }
          return a.name.localeCompare(b.name);
        });
        if (!cancelled) {
          setTools(toolList);
          setIsLoading(false);
          setLoadError(null);
        }
      } catch (error) {
        if (!cancelled) {
          const message = error instanceof Error ? error.message : "Unknown error";
          setTools([]);
          setIsLoading(false);
          setLoadError(`Failed to load tools: ${message}`);
        }
      }
    };
    void fetchTools();
    return () => {
      cancelled = true;
    };
  }, [isVisible, agent, sessionId]);
  const filteredTools = (0, import_react.useMemo)(() => {
    if (!searchQuery.trim()) {
      return tools;
    }
    const query = searchQuery.toLowerCase();
    return tools.filter((tool) => {
      const name = tool.name.toLowerCase();
      const desc = tool.description.toLowerCase();
      const server = (tool.serverName || "").toLowerCase();
      return name.includes(query) || desc.includes(query) || server.includes(query);
    });
  }, [tools, searchQuery]);
  (0, import_react.useEffect)(() => {
    setSelection((prev) => {
      const maxIndex = Math.max(0, filteredTools.length - 1);
      const nextIndex = Math.min(prev.index, maxIndex);
      let nextOffset = prev.offset;
      if (nextIndex < nextOffset) {
        nextOffset = nextIndex;
      } else if (nextIndex >= nextOffset + maxVisibleTools) {
        nextOffset = Math.max(0, nextIndex - maxVisibleTools + 1);
      }
      const maxOffset = Math.max(0, filteredTools.length - maxVisibleTools);
      nextOffset = Math.min(maxOffset, Math.max(0, nextOffset));
      if (nextIndex === prev.index && nextOffset === prev.offset) {
        return prev;
      }
      selectedIndexRef.current = nextIndex;
      return { index: nextIndex, offset: nextOffset };
    });
  }, [filteredTools.length, maxVisibleTools]);
  const openListActions = (tool) => {
    setSelectedTool(tool);
    setListActionsIndex(0);
    setViewMode("list-actions");
  };
  const openToolDetails = (tool) => {
    setSelectedTool(tool);
    setViewMode("detail");
    setDetailScrollOffset(0);
  };
  const openConfigMenu = (tool) => {
    setSelectedTool(tool);
    setConfigIndex(0);
    setViewMode("config");
  };
  const openScopePrompt = (tool) => {
    const nextEnabled = !tool.isEnabled;
    const nextScope = sessionId ? "session" : "global";
    setSelectedTool(tool);
    setScopeToolName(tool.name);
    setScopeNextEnabled(nextEnabled);
    setScopeTarget(nextScope);
    setViewMode("scope");
    scopeToolNameRef.current = tool.name;
    scopeNextEnabledRef.current = nextEnabled;
    scopeTargetRef.current = nextScope;
  };
  const closeScopePrompt = () => {
    setViewMode("config");
    setScopeToolName(null);
  };
  const applyToolToggle = async (overrideTarget) => {
    const targetToolName = scopeToolNameRef.current ?? scopeToolName ?? selectedToolRef.current?.name;
    if (!targetToolName) return;
    const effectiveTarget = overrideTarget ?? scopeTargetRef.current;
    const nextEnabled = scopeNextEnabledRef.current;
    const previousTools = toolsRef.current;
    const updatedTools = previousTools.map((tool) => {
      if (tool.name !== targetToolName) {
        return tool;
      }
      const updatedTool = { ...tool, isEnabled: nextEnabled };
      if (!nextEnabled && tool.isAutoApproved) {
        updatedTool.isAutoApproved = false;
      }
      return updatedTool;
    });
    setTools(updatedTools);
    const updatedSelected = updatedTools.find((tool) => tool.name === targetToolName) ?? null;
    setSelectedTool(updatedSelected);
    const autoApprovedTools = updatedTools.filter((tool) => tool.isAutoApproved).map((tool) => tool.name);
    if (sessionId) {
      await agent.setSessionAutoApproveTools(sessionId, autoApprovedTools);
    }
    const disabledTools = updatedTools.filter((tool) => !tool.isEnabled).map((tool) => tool.name);
    if (effectiveTarget === "session" && sessionId) {
      await agent.setSessionDisabledTools(sessionId, disabledTools);
    } else if (effectiveTarget === "global") {
      try {
        const { updateAgentPreferences, saveAgentPreferences, agentPreferencesExist } = await import("@dexto/agent-management");
        if (agentPreferencesExist(agent.config.agentId)) {
          await updateAgentPreferences(agent.config.agentId, {
            tools: { disabled: disabledTools }
          });
        } else {
          await saveAgentPreferences(agent.config.agentId, {
            tools: { disabled: disabledTools }
          });
        }
        agent.setGlobalDisabledTools(disabledTools);
      } catch (_error) {
        if (sessionId) {
          await agent.setSessionDisabledTools(sessionId, disabledTools);
        } else {
          setTools(previousTools);
          setSelectedTool(
            previousTools.find((tool) => tool.name === targetToolName) ?? null
          );
        }
      }
    }
    closeScopePrompt();
  };
  const toggleAutoApprove = async () => {
    if (!sessionId) return;
    const previousTools = toolsRef.current;
    const previousSelectedToolName = selectedToolRef.current?.name;
    const updatedTools = toolsRef.current.map(
      (tool) => tool.name === selectedToolRef.current?.name ? { ...tool, isAutoApproved: !tool.isAutoApproved } : tool
    );
    const updatedSelected = updatedTools.find(
      (tool) => tool.name === selectedToolRef.current?.name
    );
    setTools(updatedTools);
    setSelectedTool(updatedSelected ?? null);
    const autoApprovedTools = updatedTools.filter((tool) => tool.isAutoApproved).map((tool) => tool.name);
    try {
      await agent.setSessionAutoApproveTools(sessionId, autoApprovedTools);
    } catch (_error) {
      setTools(previousTools);
      setSelectedTool(
        previousTools.find((tool) => tool.name === previousSelectedToolName) ?? null
      );
    }
  };
  const closeConfigMenu = () => {
    setViewMode("list-actions");
  };
  const closeDetailView = () => {
    setViewMode("list-actions");
  };
  const closeListActions = () => {
    setViewMode("list");
    setSelectedTool(null);
  };
  (0, import_react.useImperativeHandle)(
    ref,
    () => ({
      handleInput: (input, key) => {
        if (!isVisible) return false;
        if (isLoading) {
          if (key.escape) {
            onClose();
          }
          return true;
        }
        if (viewModeRef.current === "scope") {
          if (key.escape || key.backspace || key.delete) {
            closeScopePrompt();
            return true;
          }
          if (key.upArrow || key.downArrow) {
            setScopeTarget((prev) => prev === "session" ? "global" : "session");
            return true;
          }
          if (key.return) {
            if (scopeTargetRef.current === "session" && !sessionId) {
              setScopeTarget("global");
              scopeTargetRef.current = "global";
              void applyToolToggle("global");
              return true;
            }
            void applyToolToggle();
            return true;
          }
          return true;
        }
        if (viewModeRef.current === "config") {
          if (key.escape || key.backspace || key.delete) {
            closeConfigMenu();
            return true;
          }
          if (key.upArrow) {
            const nextIndex = (configIndexRef.current - 1 + 3) % 3;
            setConfigIndex(nextIndex);
            return true;
          }
          if (key.downArrow) {
            const nextIndex = (configIndexRef.current + 1) % 3;
            setConfigIndex(nextIndex);
            return true;
          }
          if (key.return) {
            const tool = selectedToolRef.current;
            if (tool) {
              if (configIndexRef.current === 0) {
                openScopePrompt(tool);
              } else if (configIndexRef.current === 1) {
                if (sessionId && tool.isEnabled) {
                  void toggleAutoApprove();
                }
              } else {
                closeConfigMenu();
              }
            }
            return true;
          }
          return true;
        }
        if (viewModeRef.current === "detail") {
          if (key.escape || key.backspace || key.delete) {
            closeDetailView();
            return true;
          }
          if (key.upArrow) {
            if (detailScrollOffsetRef.current > 0) {
              setDetailScrollOffset((prev) => prev - 1);
            }
            return true;
          }
          if (key.downArrow) {
            if (detailScrollOffsetRef.current < detailMaxScrollOffsetRef.current) {
              setDetailScrollOffset((prev) => prev + 1);
            }
            return true;
          }
          if (input === "c" || input === "C") {
            const tool = selectedToolRef.current;
            if (tool) {
              const schema = {
                type: "function",
                name: tool.name,
                description: tool.description,
                parameters: tool.inputSchema || {}
              };
              void (0, import_clipboardUtils.writeToClipboard)(JSON.stringify(schema, null, 2)).then(
                (success) => {
                  setCopyFeedback(success ? "Copied!" : "Copy failed");
                  setTimeout(() => setCopyFeedback(null), 1500);
                }
              );
            }
            return true;
          }
          if (key.return) {
            const tool = selectedToolRef.current;
            if (tool) {
              openConfigMenu(tool);
            }
            return true;
          }
          return true;
        }
        if (viewModeRef.current === "list-actions") {
          if (key.escape || key.backspace || key.delete) {
            closeListActions();
            return true;
          }
          if (key.upArrow) {
            const nextIndex = (listActionsIndexRef.current - 1 + LIST_ACTIONS.length) % LIST_ACTIONS.length;
            setListActionsIndex(nextIndex);
            return true;
          }
          if (key.downArrow) {
            const nextIndex = (listActionsIndexRef.current + 1) % LIST_ACTIONS.length;
            setListActionsIndex(nextIndex);
            return true;
          }
          if (key.return) {
            const tool = selectedToolRef.current;
            const action = LIST_ACTIONS[listActionsIndexRef.current];
            if (!tool) {
              closeListActions();
              return true;
            }
            if (action === "view") {
              openToolDetails(tool);
            } else if (action === "config") {
              openConfigMenu(tool);
            } else {
              closeListActions();
            }
            return true;
          }
          return true;
        }
        if (key.escape) {
          onClose();
          return true;
        }
        if (input && !key.return && !key.upArrow && !key.downArrow && !key.tab) {
          if (key.backspace || key.delete) {
            setSearchQuery((prev) => prev.slice(0, -1));
            return true;
          }
          if (input.length === 1 && input.charCodeAt(0) >= 32) {
            setSearchQuery((prev) => prev + input);
            selectedIndexRef.current = 0;
            setSelection({ index: 0, offset: 0 });
            return true;
          }
        }
        if (key.backspace || key.delete) {
          setSearchQuery((prev) => prev.slice(0, -1));
          return true;
        }
        const itemsLength = filteredTools.length;
        if (itemsLength === 0) return false;
        if (key.upArrow) {
          const nextIndex = (selectedIndexRef.current - 1 + itemsLength) % itemsLength;
          selectedIndexRef.current = nextIndex;
          setSelection((prev) => {
            let nextOffset = prev.offset;
            if (nextIndex < prev.offset) {
              nextOffset = nextIndex;
            } else if (nextIndex >= prev.offset + maxVisibleTools) {
              nextOffset = Math.max(0, nextIndex - maxVisibleTools + 1);
            }
            const maxOffset = Math.max(0, itemsLength - maxVisibleTools);
            nextOffset = Math.min(maxOffset, Math.max(0, nextOffset));
            return { index: nextIndex, offset: nextOffset };
          });
          return true;
        }
        if (key.downArrow) {
          const nextIndex = (selectedIndexRef.current + 1) % itemsLength;
          selectedIndexRef.current = nextIndex;
          setSelection((prev) => {
            let nextOffset = prev.offset;
            if (nextIndex < prev.offset) {
              nextOffset = nextIndex;
            } else if (nextIndex >= prev.offset + maxVisibleTools) {
              nextOffset = Math.max(0, nextIndex - maxVisibleTools + 1);
            }
            const maxOffset = Math.max(0, itemsLength - maxVisibleTools);
            nextOffset = Math.min(maxOffset, Math.max(0, nextOffset));
            return { index: nextIndex, offset: nextOffset };
          });
          return true;
        }
        if (key.return && itemsLength > 0) {
          const tool = filteredTools[selectedIndexRef.current];
          if (tool) {
            openListActions(tool);
            return true;
          }
        }
        return false;
      }
    }),
    [isVisible, isLoading, filteredTools, maxVisibleTools, onClose, sessionId]
  );
  if (!isVisible) return null;
  if (viewMode === "list-actions" && selectedTool) {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      ToolActionsMenu,
      {
        tool: selectedTool,
        columns,
        listActionsIndex
      }
    );
  }
  if (viewMode === "detail" && selectedTool) {
    const maxVisibleLines = Math.min(18, Math.max(5, rows - 6));
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      ToolDetailView,
      {
        tool: selectedTool,
        columns,
        scrollOffset: detailScrollOffset,
        maxVisibleLines,
        maxScrollOffsetRef: detailMaxScrollOffsetRef,
        copyFeedback
      }
    );
  }
  if (viewMode === "config" && selectedTool) {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      ToolSettingsView,
      {
        tool: selectedTool,
        columns,
        configIndex,
        sessionAvailable: Boolean(sessionId)
      }
    );
  }
  if (viewMode === "scope" && selectedTool) {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      ToolScopeView,
      {
        tool: selectedTool,
        columns,
        scopeTarget,
        scopeNextEnabled,
        sessionAvailable: Boolean(sessionId)
      }
    );
  }
  const selectedIndex = selection.index;
  const scrollOffset = selection.offset;
  const visibleTools = filteredTools.slice(scrollOffset, scrollOffset + maxVisibleTools);
  const filteredLocalCount = filteredTools.filter((t) => t.source === "local").length;
  const filteredMcpCount = filteredTools.filter((t) => t.source === "mcp").length;
  const selectedToolInList = filteredTools[selectedIndex];
  let detailLine = "";
  if (isLoading) {
    detailLine = "Loading tools\u2026";
  } else if (loadError) {
    detailLine = loadError;
  } else if (searchQuery.trim() && filteredTools.length === 0) {
    detailLine = "No tools match your search";
  } else if (selectedToolInList) {
    detailLine = selectedToolInList.description;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", width: columns, children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { paddingX: 0, paddingY: 0, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", bold: true, children: "Tools" }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
        " ",
        "(",
        filteredTools.length,
        " tools: ",
        filteredLocalCount,
        " local, ",
        filteredMcpCount,
        " ",
        "MCP)"
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { paddingX: 0, paddingY: 0, marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Search: " }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: searchQuery ? "white" : "gray", wrap: "truncate-end", children: searchQuery || "Type to filter tools\u2026" })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { flexDirection: "column", height: maxVisibleTools, marginTop: 1, children: isLoading || filteredTools.length === 0 ? Array.from({ length: maxVisibleTools }, (_, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: " " }) }, `tool-empty-${index}`)) : Array.from({ length: maxVisibleTools }, (_, rowIndex) => {
      const tool = visibleTools[rowIndex];
      if (!tool) {
        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: " " }) }, `tool-empty-${rowIndex}`);
      }
      const actualIndex = scrollOffset + rowIndex;
      const isSelected = actualIndex === selectedIndex;
      return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { paddingX: 0, paddingY: 0, children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "white", children: isSelected ? "\u25B6 " : "  " }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "cyan" : "white", bold: isSelected, children: truncateText(tool.name, 35) }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: tool.source === "local" ? "magenta" : "blue", children: [
          " ",
          "[",
          tool.source === "local" ? "Local" : "MCP",
          "]"
        ] }),
        tool.serverName && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
          " (",
          tool.serverName,
          ")"
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: tool.isEnabled ? "green" : "red", children: [
          " ",
          tool.isEnabled ? "Enabled" : "Disabled"
        ] }),
        tool.isAutoApproved && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellow", children: " [auto-approved]" })
      ] }, tool.name);
    }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: loadError ? "red" : "gray", wrap: "truncate-end", children: detailLine }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_HintBar.HintBar, { hints: ["\u2191\u2193 navigate", "Enter options", "Esc close"] }) })
  ] });
});
function buildDetailLineData(tool, maxWidth) {
  const lines = [];
  lines.push({ type: "title", text: tool.name });
  lines.push({ type: "source", source: tool.source, serverName: tool.serverName });
  lines.push({ type: "empty" });
  lines.push({ type: "header", text: "Description:" });
  const descriptionLines = wrapText(tool.description, maxWidth - 2).split("\n");
  for (const descLine of descriptionLines) {
    lines.push({ type: "description", text: descLine });
  }
  if (tool.inputSchema) {
    const properties = tool.inputSchema.properties;
    const required = tool.inputSchema.required || [];
    if (properties && Object.keys(properties).length > 0) {
      lines.push({ type: "empty" });
      lines.push({ type: "header", text: "Parameters:" });
      for (const [propName, propSchema] of Object.entries(properties)) {
        const paramType = propSchema.type || "any";
        const description = propSchema.description;
        const isRequired = required.includes(propName);
        const enumValues = propSchema.enum;
        lines.push({
          type: "param-name",
          name: propName,
          paramType,
          required: isRequired
        });
        if (description) {
          const descLines = wrapText(description, maxWidth - 2).split("\n");
          for (const descLine of descLines) {
            lines.push({ type: "param-desc", text: descLine });
          }
        }
        if (enumValues && enumValues.length > 0) {
          lines.push({ type: "param-enum", values: enumValues });
        }
      }
    }
  }
  return lines;
}
function renderDetailLine(line, _index) {
  switch (line.type) {
    case "title":
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", bold: true, children: line.text });
    case "source":
      return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: line.source === "local" ? "magenta" : "blue", children: [
        line.source === "local" ? "Local Tool" : "MCP Tool",
        line.serverName ? ` (${line.serverName})` : ""
      ] });
    case "empty":
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: " " });
    case "header":
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: line.text });
    case "description":
      return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: " " }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: line.text })
      ] });
    case "param-name":
      return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: " " }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", children: line.name }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
          " (",
          line.paramType,
          ")"
        ] }),
        line.required && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "red", children: " *required" })
      ] });
    case "param-desc":
      return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: " " }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: line.text })
      ] });
    case "param-enum":
      return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: " " }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
          "Allowed: ",
          line.values.join(" | ")
        ] })
      ] });
  }
}
function ToolActionsMenu({
  tool,
  columns,
  listActionsIndex
}) {
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", width: columns, children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { paddingX: 0, paddingY: 0, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", bold: true, children: "Tool Options" }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
        " ",
        tool.name
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: listActionsIndex === 0 ? "cyan" : "gray", children: [
      listActionsIndex === 0 ? "\u25B6 " : "  ",
      "View details"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: listActionsIndex === 1 ? "cyan" : "gray", children: [
      listActionsIndex === 1 ? "\u25B6 " : "  ",
      "Edit tool settings"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: listActionsIndex === 2 ? "cyan" : "gray", children: [
      listActionsIndex === 2 ? "\u25B6 " : "  ",
      "Back"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "\u2191\u2193 select \xB7 Enter confirm \xB7 Esc back" }) })
  ] });
}
function ToolDetailView({
  tool,
  columns,
  scrollOffset,
  maxVisibleLines,
  maxScrollOffsetRef,
  copyFeedback
}) {
  const maxWidth = Math.min(80, columns - 4);
  const lineData = (0, import_react.useMemo)(() => buildDetailLineData(tool, maxWidth), [tool, maxWidth]);
  const totalLines = lineData.length;
  const maxScrollOffset = Math.max(0, totalLines - maxVisibleLines);
  maxScrollOffsetRef.current = maxScrollOffset;
  const clampedOffset = Math.min(scrollOffset, maxScrollOffset);
  const hasMoreAbove = clampedOffset > 0;
  const hasMoreBelow = clampedOffset + maxVisibleLines < totalLines;
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", width: columns, children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { paddingX: 0, paddingY: 0, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", bold: true, children: "Tool Details" }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: " - \u2191\u2193 scroll, c copy schema, Enter settings, Esc back" }),
      copyFeedback && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "green", bold: true, children: [
        " ",
        copyFeedback
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "\u2500".repeat(Math.min(60, columns - 2)) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: hasMoreAbove ? `\u2191 ${clampedOffset} more above` : " " }) }),
    Array.from({ length: maxVisibleLines }, (_, i) => {
      const absoluteIndex = clampedOffset + i;
      const line = lineData[absoluteIndex];
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: line ? renderDetailLine(line, absoluteIndex) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: " " }) }, i);
    }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: hasMoreBelow ? `\u2193 ${totalLines - clampedOffset - maxVisibleLines} more below` : " " }) })
  ] });
}
function ToolSettingsView({
  tool,
  columns,
  configIndex,
  sessionAvailable
}) {
  const autoApproveDisabled = !tool.isEnabled;
  const autoApproveUnavailable = !sessionAvailable || autoApproveDisabled;
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", width: columns, children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { paddingX: 0, paddingY: 0, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", bold: true, children: "Tool Settings" }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
        " ",
        tool.name
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { paddingX: 0, paddingY: 0, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Status: " }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: tool.isEnabled ? "green" : "red", children: tool.isEnabled ? "Enabled" : "Disabled" }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: " \xB7 Auto-approve: " }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: tool.isAutoApproved ? "green" : "red", children: tool.isAutoApproved ? "On" : "Off" }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: " (session)" })
    ] }),
    autoApproveDisabled && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellow", children: "Enable the tool to allow auto-approve." }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: configIndex === 0 ? "cyan" : "gray", children: [
      configIndex === 0 ? "\u25B6 " : "  ",
      tool.isEnabled ? "Disable tool" : "Enable tool"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
      import_ink.Text,
      {
        color: configIndex === 1 ? autoApproveUnavailable ? "yellow" : "cyan" : "gray",
        children: [
          configIndex === 1 ? "\u25B6 " : "  ",
          tool.isAutoApproved ? "Disable auto-approve (session)" : "Enable auto-approve (session)"
        ]
      }
    ) }),
    !sessionAvailable && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellow", children: "Auto-approve requires an active session." }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: configIndex === 2 ? "cyan" : "gray", children: [
      configIndex === 2 ? "\u25B6 " : "  ",
      "Back"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "\u2191\u2193 select \xB7 Enter confirm \xB7 Esc back" }) })
  ] });
}
function ToolScopeView({
  tool,
  columns,
  scopeTarget,
  scopeNextEnabled,
  sessionAvailable
}) {
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", width: columns, children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { paddingX: 0, paddingY: 0, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", bold: true, children: scopeNextEnabled ? "Enable Tool" : "Disable Tool" }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
        " ",
        tool.name
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Apply to:" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: scopeTarget === "session" ? "cyan" : "gray", children: [
      scopeTarget === "session" ? "\u25B6 " : "  ",
      "Session (default)"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: scopeTarget === "global" ? "cyan" : "gray", children: [
      scopeTarget === "global" ? "\u25B6 " : "  ",
      "Global (persisted)"
    ] }) }),
    !sessionAvailable && scopeTarget === "session" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellow", children: "No active session; switching to global." }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "\u2191\u2193 choose scope \xB7 Enter confirm \xB7 Esc back" }) })
  ] });
}
function truncateText(text, maxLength) {
  if (text.length <= maxLength) return text;
  return text.slice(0, maxLength - 1) + "\u2026";
}
function wrapText(text, maxWidth) {
  if (text.length <= maxWidth) return text;
  const words = text.split(" ");
  const lines = [];
  let currentLine = "";
  for (const word of words) {
    if (currentLine.length + word.length + 1 <= maxWidth) {
      currentLine += (currentLine ? " " : "") + word;
    } else {
      if (currentLine) lines.push(currentLine);
      currentLine = word;
    }
  }
  if (currentLine) lines.push(currentLine);
  return lines.join("\n");
}
var ToolBrowser_default = ToolBrowser;
