// @bun
import {
  editFileInEditor,
  init_promptEditor
} from "./chunk-pb9v47qr.js";
import {
  Select,
  clearMemoryFileCaches,
  getAgentMemoryDir,
  getMemoryFiles,
  init_AppState,
  init_CustomSelect,
  init_agentMemory,
  init_claudemd,
  init_config1 as init_config,
  init_consolidationLock,
  isAutoDreamEnabled,
  readLastConsolidatedAt,
  useAppState
} from "./chunk-421yegj3.js";
import"./chunk-aaxz8a5g.js";
import"./chunk-2kcgxnvp.js";
import"./chunk-14p6wvsq.js";
import"./chunk-6s0q1s5r.js";
import"./chunk-0cpg8qh8.js";
import"./chunk-9phn5khx.js";
import"./chunk-vk9xcryd.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-ptxteaeh.js";
import"./chunk-7fcmqvbz.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-q3b4n194.js";
import"./chunk-zaqfb3tz.js";
import"./chunk-6hzx0kqr.js";
import"./chunk-71sdcaq6.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-dxa3y9vh.js";
import"./chunk-gjvhjywj.js";
import"./chunk-1w20m7gw.js";
import"./chunk-3gam18xn.js";
import"./chunk-rpmntgyh.js";
import"./chunk-24kv69g3.js";
import {
  init_useExitOnCtrlCDWithKeybindings,
  useExitOnCtrlCDWithKeybindings
} from "./chunk-tzcrwnrf.js";
import"./chunk-k7xszak2.js";
import"./chunk-ztmb7geg.js";
import"./chunk-tbdkekz3.js";
import {
  init_useKeybinding
} from "./chunk-65zbgg1n.js";
import"./chunk-4spgkgr3.js";
import"./chunk-60fkafk2.js";
import"./chunk-h5zz0vxy.js";
import"./chunk-6hygvrhn.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-8gv2pjby.js";
import"./chunk-pn23dh3d.js";
import"./chunk-rpdh02rm.js";
import"./chunk-j1wktfe2.js";
import"./chunk-fjtzfz1t.js";
import {
  init_browser,
  openPath
} from "./chunk-6hr7742d.js";
import"./chunk-xyg1sk2w.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-hem4f4gz.js";
import"./chunk-hqxp6b72.js";
import"./chunk-ccw8pse0.js";
import"./chunk-wsnxtggw.js";
import"./chunk-k8nwt8yq.js";
import"./chunk-vxbjzggp.js";
import"./chunk-d6h68rz1.js";
import"./chunk-8yvsnrkr.js";
import"./chunk-5mmhfbxb.js";
import {
  getAutoMemPath,
  getDisplayPath,
  init_file,
  init_paths,
  init_settings1 as init_settings,
  isAutoMemoryEnabled,
  updateSettingsForSource
} from "./chunk-s2t5anwv.js";
import"./chunk-ga1jkyqy.js";
import"./chunk-9hbhydvp.js";
import"./chunk-ck9r8hpf.js";
import"./chunk-k7hexw3v.js";
import"./chunk-trqrj23e.js";
import"./chunk-za3k6h2h.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-hjxqmtg5.js";
import"./chunk-bzyzrq0k.js";
import"./chunk-vwenx8ke.js";
import"./chunk-q2h79ncs.js";
import"./chunk-v4ypszbb.js";
import"./chunk-qfsn720k.js";
import"./chunk-7qx3xhv3.js";
import"./chunk-j9475b46.js";
import"./chunk-fdwabr8p.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-dbts5q5p.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import {
  formatRelativeTimeAgo,
  init_format
} from "./chunk-q1vrhh0q.js";
import"./chunk-hn4w9pkj.js";
import {
  Dialog,
  Link,
  ListItem,
  ThemedBox_default,
  ThemedText,
  init_source,
  init_src,
  source_default,
  useKeybinding
} from "./chunk-2g0ytd9d.js";
import {
  require_jsx_dev_runtime,
  require_react
} from "./chunk-de0qnnf7.js";
import {
  init_analytics,
  logEvent
} from "./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-92bjkrf2.js";
import {
  findGitRoot,
  init_git
} from "./chunk-10k5jfc5.js";
import"./chunk-n9g24mwe.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-hzmzwte2.js";
import {
  getCwd,
  init_cwd
} from "./chunk-pdvg91cg.js";
import"./chunk-c696122m.js";
import"./chunk-xbj5keyy.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import"./chunk-aeysytks.js";
import {
  getClaudeConfigHomeDir,
  getErrnoCode,
  init_envUtils,
  init_errors,
  init_log,
  logError
} from "./chunk-s3hafnk3.js";
import"./chunk-kb3758f7.js";
import {
  getOriginalCwd,
  init_state
} from "./chunk-9h9k5vz3.js";
import"./chunk-xmpgmeb8.js";
import"./chunk-2kz09j2s.js";
import"./chunk-c0k7b0jw.js";
import"./chunk-pecy49yr.js";
import"./chunk-azbab59e.js";
import"./chunk-3nk9q8dr.js";
import {
  __esm,
  __toESM
} from "./chunk-hhsxm2yr.js";

// src/utils/memory/versions.ts
function projectIsInGitRepo(cwd) {
  return findGitRoot(cwd) !== null;
}
var init_versions = __esm(() => {
  init_git();
});

// src/components/memory/MemoryFileSelector.tsx
import { mkdir } from "fs/promises";
import { join } from "path";
function MemoryFileSelector({ onSelect, onCancel }) {
  const existingMemoryFiles = import_react.use(getMemoryFiles());
  const userMemoryPath = join(getClaudeConfigHomeDir(), "CLAUDE.md");
  const projectMemoryPath = join(getOriginalCwd(), "CLAUDE.md");
  const hasUserMemory = existingMemoryFiles.some((f) => f.path === userMemoryPath);
  const hasProjectMemory = existingMemoryFiles.some((f) => f.path === projectMemoryPath);
  const allMemoryFiles = [
    ...existingMemoryFiles.filter((f) => f.type !== "AutoMem" && f.type !== "TeamMem").map((f) => ({ ...f, exists: true })),
    ...hasUserMemory ? [] : [
      {
        path: userMemoryPath,
        type: "User",
        content: "",
        exists: false
      }
    ],
    ...hasProjectMemory ? [] : [
      {
        path: projectMemoryPath,
        type: "Project",
        content: "",
        exists: false
      }
    ]
  ];
  const depths = new Map;
  const memoryOptions = allMemoryFiles.map((file) => {
    const displayPath = getDisplayPath(file.path);
    const existsLabel = file.exists ? "" : " (new)";
    const depth = file.parent ? (depths.get(file.parent) ?? 0) + 1 : 0;
    depths.set(file.path, depth);
    const indent = depth > 0 ? "  ".repeat(depth - 1) : "";
    let label;
    if (file.type === "User" && !file.isNested && file.path === userMemoryPath) {
      label = `User memory`;
    } else if (file.type === "Project" && !file.isNested && file.path === projectMemoryPath) {
      label = `Project memory`;
    } else if (depth > 0) {
      label = `${indent}L ${displayPath}${existsLabel}`;
    } else {
      label = `${displayPath}`;
    }
    let description;
    const isGit = projectIsInGitRepo(getOriginalCwd());
    if (file.type === "User" && !file.isNested) {
      description = "Saved in ~/.claude/CLAUDE.md";
    } else if (file.type === "Project" && !file.isNested && file.path === projectMemoryPath) {
      description = `${isGit ? "Checked in at" : "Saved in"} ./CLAUDE.md`;
    } else if (file.parent) {
      description = "@-imported";
    } else if (file.isNested) {
      description = "dynamically loaded";
    } else {
      description = "";
    }
    return {
      label,
      value: file.path,
      description
    };
  });
  const folderOptions = [];
  const agentDefinitions = useAppState((s) => s.agentDefinitions);
  if (isAutoMemoryEnabled()) {
    folderOptions.push({
      label: "Open auto-memory folder",
      value: `${OPEN_FOLDER_PREFIX}${getAutoMemPath()}`,
      description: ""
    });
    if (false) {}
    for (const agent of agentDefinitions.activeAgents) {
      if (agent.memory) {
        const agentDir = getAgentMemoryDir(agent.agentType, agent.memory);
        folderOptions.push({
          label: `Open ${source_default.bold(agent.agentType)} agent memory`,
          value: `${OPEN_FOLDER_PREFIX}${agentDir}`,
          description: `${agent.memory} scope`
        });
      }
    }
  }
  memoryOptions.push(...folderOptions);
  const initialPath = lastSelectedPath && memoryOptions.some((opt) => opt.value === lastSelectedPath) ? lastSelectedPath : memoryOptions[0]?.value || "";
  const [autoMemoryOn, setAutoMemoryOn] = import_react.useState(isAutoMemoryEnabled);
  const [autoDreamOn, setAutoDreamOn] = import_react.useState(isAutoDreamEnabled);
  const [showDreamRow] = import_react.useState(isAutoMemoryEnabled);
  const isDreamRunning = useAppState((s) => Object.values(s.tasks).some((t) => t.type === "dream" && t.status === "running"));
  const [lastDreamAt, setLastDreamAt] = import_react.useState(null);
  import_react.useEffect(() => {
    if (!showDreamRow)
      return;
    readLastConsolidatedAt().then(setLastDreamAt);
  }, [showDreamRow, isDreamRunning]);
  const dreamStatus = isDreamRunning ? "running" : lastDreamAt === null ? "" : lastDreamAt === 0 ? "never" : `last ran ${formatRelativeTimeAgo(new Date(lastDreamAt))}`;
  const [focusedToggle, setFocusedToggle] = import_react.useState(null);
  const toggleFocused = focusedToggle !== null;
  const lastToggleIndex = showDreamRow ? 1 : 0;
  function handleToggleAutoMemory() {
    const newValue = !autoMemoryOn;
    updateSettingsForSource("userSettings", { autoMemoryEnabled: newValue });
    setAutoMemoryOn(newValue);
    logEvent("tengu_auto_memory_toggled", { enabled: newValue });
  }
  function handleToggleAutoDream() {
    const newValue = !autoDreamOn;
    updateSettingsForSource("userSettings", { autoDreamEnabled: newValue });
    setAutoDreamOn(newValue);
    logEvent("tengu_auto_dream_toggled", { enabled: newValue });
  }
  useExitOnCtrlCDWithKeybindings();
  useKeybinding("confirm:no", onCancel, { context: "Confirmation" });
  useKeybinding("confirm:yes", () => {
    if (focusedToggle === 0)
      handleToggleAutoMemory();
    else if (focusedToggle === 1)
      handleToggleAutoDream();
  }, { context: "Confirmation", isActive: toggleFocused });
  useKeybinding("select:next", () => {
    setFocusedToggle((prev) => prev !== null && prev < lastToggleIndex ? prev + 1 : null);
  }, { context: "Select", isActive: toggleFocused });
  useKeybinding("select:previous", () => {
    setFocusedToggle((prev) => prev !== null && prev > 0 ? prev - 1 : prev);
  }, { context: "Select", isActive: toggleFocused });
  return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
    flexDirection: "column",
    width: "100%",
    children: [
      /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
        flexDirection: "column",
        marginBottom: 1,
        children: [
          /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ListItem, {
            isFocused: focusedToggle === 0,
            children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
              children: [
                "Auto-memory: ",
                autoMemoryOn ? "on" : "off"
              ]
            }, undefined, true, undefined, this)
          }, undefined, false, undefined, this),
          showDreamRow && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ListItem, {
            isFocused: focusedToggle === 1,
            styled: false,
            children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
              color: focusedToggle === 1 ? "suggestion" : undefined,
              children: [
                "Auto-dream: ",
                autoDreamOn ? "on" : "off",
                dreamStatus && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                  dimColor: true,
                  children: [
                    " \xB7 ",
                    dreamStatus
                  ]
                }, undefined, true, undefined, this),
                !isDreamRunning && autoDreamOn && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                  dimColor: true,
                  children: " \xB7 /dream to run"
                }, undefined, false, undefined, this)
              ]
            }, undefined, true, undefined, this)
          }, undefined, false, undefined, this)
        ]
      }, undefined, true, undefined, this),
      /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Select, {
        defaultFocusValue: initialPath,
        options: memoryOptions,
        isDisabled: toggleFocused,
        onChange: (value) => {
          if (value.startsWith(OPEN_FOLDER_PREFIX)) {
            const folderPath = value.slice(OPEN_FOLDER_PREFIX.length);
            mkdir(folderPath, { recursive: true }).catch(() => {}).then(() => openPath(folderPath));
            return;
          }
          lastSelectedPath = value;
          onSelect(value);
        },
        onCancel,
        onUpFromFirstItem: () => setFocusedToggle(lastToggleIndex)
      }, undefined, false, undefined, this)
    ]
  }, undefined, true, undefined, this);
}
var import_react, jsx_dev_runtime, lastSelectedPath, OPEN_FOLDER_PREFIX = "__open_folder__";
var init_MemoryFileSelector = __esm(() => {
  init_source();
  init_state();
  init_useExitOnCtrlCDWithKeybindings();
  init_src();
  init_useKeybinding();
  init_paths();
  init_analytics();
  init_config();
  init_consolidationLock();
  init_AppState();
  init_agentMemory();
  init_browser();
  init_claudemd();
  init_envUtils();
  init_file();
  init_format();
  init_versions();
  init_settings();
  init_CustomSelect();
  import_react = __toESM(require_react(), 1);
  jsx_dev_runtime = __toESM(require_jsx_dev_runtime(), 1);
});

// src/components/memory/MemoryUpdateNotification.tsx
import { homedir } from "os";
import { relative } from "path";
function getRelativeMemoryPath(path) {
  const homeDir = homedir();
  const cwd = getCwd();
  const relativeToHome = path.startsWith(homeDir) ? "~" + path.slice(homeDir.length) : null;
  const relativeToCwd = path.startsWith(cwd) ? "./" + relative(cwd, path) : null;
  if (relativeToHome && relativeToCwd) {
    return relativeToHome.length <= relativeToCwd.length ? relativeToHome : relativeToCwd;
  }
  return relativeToHome || relativeToCwd || path;
}
var jsx_dev_runtime2;
var init_MemoryUpdateNotification = __esm(() => {
  init_src();
  init_cwd();
  jsx_dev_runtime2 = __toESM(require_jsx_dev_runtime(), 1);
});

// src/commands/memory/memory.tsx
import { mkdir as mkdir2, writeFile } from "fs/promises";
function MemoryCommand({
  onDone
}) {
  const handleSelectMemoryFile = async (memoryPath) => {
    try {
      if (memoryPath.includes(getClaudeConfigHomeDir())) {
        await mkdir2(getClaudeConfigHomeDir(), { recursive: true });
      }
      try {
        await writeFile(memoryPath, "", { encoding: "utf8", flag: "wx" });
      } catch (e) {
        if (getErrnoCode(e) !== "EEXIST") {
          throw e;
        }
      }
      await editFileInEditor(memoryPath);
      let editorSource = "default";
      let editorValue = "";
      if (process.env.VISUAL) {
        editorSource = "$VISUAL";
        editorValue = process.env.VISUAL;
      } else if (process.env.EDITOR) {
        editorSource = "$EDITOR";
        editorValue = process.env.EDITOR;
      }
      const editorInfo = editorSource !== "default" ? `Using ${editorSource}="${editorValue}".` : "";
      const editorHint = editorInfo ? `> ${editorInfo} To change editor, set $EDITOR or $VISUAL environment variable.` : `> To use a different editor, set the $EDITOR or $VISUAL environment variable.`;
      onDone(`Opened memory file at ${getRelativeMemoryPath(memoryPath)}

${editorHint}`, { display: "system" });
    } catch (error) {
      logError(error);
      onDone(`Error opening memory file: ${error}`);
    }
  };
  const handleCancel = () => {
    onDone("Cancelled memory editing", { display: "system" });
  };
  return /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(Dialog, {
    title: "Memory",
    onCancel: handleCancel,
    color: "remember",
    children: /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedBox_default, {
      flexDirection: "column",
      children: [
        /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(React.Suspense, {
          fallback: null,
          children: /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(MemoryFileSelector, {
            onSelect: handleSelectMemoryFile,
            onCancel: handleCancel
          }, undefined, false, undefined, this)
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedBox_default, {
          marginTop: 1,
          children: /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedText, {
            dimColor: true,
            children: [
              "Learn more: ",
              /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(Link, {
                url: "https://code.claude.com/docs/en/memory"
              }, undefined, false, undefined, this)
            ]
          }, undefined, true, undefined, this)
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this)
  }, undefined, false, undefined, this);
}
var React, jsx_dev_runtime3, call = async (onDone) => {
  clearMemoryFileCaches();
  await getMemoryFiles();
  return /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(MemoryCommand, {
    onDone
  }, undefined, false, undefined, this);
};
var init_memory = __esm(() => {
  init_src();
  init_MemoryFileSelector();
  init_MemoryUpdateNotification();
  init_src();
  init_claudemd();
  init_envUtils();
  init_errors();
  init_log();
  init_promptEditor();
  React = __toESM(require_react(), 1);
  jsx_dev_runtime3 = __toESM(require_jsx_dev_runtime(), 1);
});
init_memory();

export {
  call
};
