import { t as __exportAll } from "./rolldown-runtime-twds-ZHy.mjs";
import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { homedir, platform } from "node:os";
import * as p from "@clack/prompts";
//#region src/cli/connect/util.ts
const AGENTMEMORY_MCP_BLOCK = {
	command: "npx",
	args: ["-y", "@agentmemory/mcp"],
	env: {
		AGENTMEMORY_URL: "${AGENTMEMORY_URL:-http://localhost:3111}",
		AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}",
		AGENTMEMORY_TOOLS: "${AGENTMEMORY_TOOLS:-all}"
	}
};
const AGENTMEMORY_COPILOT_MCP_BLOCK = {
	type: "local",
	...process.platform === "win32" ? {
		command: process.env["ComSpec"] || process.env["COMSPEC"] || "cmd.exe",
		args: [
			"/d",
			"/s",
			"/c",
			"npx",
			"-y",
			"@agentmemory/mcp"
		]
	} : {
		command: "npx",
		args: ["-y", "@agentmemory/mcp"]
	},
	env: {
		AGENTMEMORY_URL: "${AGENTMEMORY_URL:-http://localhost:3111}",
		AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}",
		AGENTMEMORY_TOOLS: "${AGENTMEMORY_TOOLS:-all}"
	},
	tools: ["*"]
};
function backupsDir() {
	return join(homedir(), ".agentmemory", "backups");
}
function ensureBackupsDir() {
	const dir = backupsDir();
	mkdirSync(dir, { recursive: true });
	return dir;
}
function timestampSlug() {
	return (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
}
function backupFile(sourcePath, agent, ext = "json") {
	ensureBackupsDir();
	const stamp = timestampSlug();
	const target = join(backupsDir(), `${agent}-${stamp}.${ext}`);
	copyFileSync(sourcePath, target);
	return target;
}
function readJsonSafe(path) {
	if (!existsSync(path)) return null;
	try {
		return JSON.parse(readFileSync(path, "utf-8"));
	} catch {
		return null;
	}
}
function writeJsonAtomic(path, value) {
	mkdirSync(dirname(path), { recursive: true });
	const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
	writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, "utf-8");
	renameSync(tmp, path);
}
function logInstalled(label, target) {
	p.log.success(`${label} → wired into ${target}`);
}
function logAlreadyWired(label, target) {
	p.log.info(`${label} already wired in ${target} (use --force to re-install)`);
}
function logBackup(target) {
	p.log.info(`Backup: ${target}`);
}
//#endregion
//#region src/cli/connect/json-mcp-adapter.ts
function entryMatches$2(entry) {
	if (!entry || typeof entry !== "object") return false;
	const e = entry;
	if (e["command"] !== "npx") return false;
	return (Array.isArray(e["args"]) ? e["args"] : []).includes("@agentmemory/mcp");
}
function createJsonMcpAdapter(config) {
	const wrapperKey = config.wrapperKey ?? "mcpServers";
	return {
		name: config.name,
		displayName: config.displayName,
		...config.docs !== void 0 && { docs: config.docs },
		...config.protocolNote !== void 0 && { protocolNote: config.protocolNote },
		detect() {
			return existsSync(config.detectDir);
		},
		async install(opts) {
			const existing = readJsonSafe(config.configPath);
			const next = existing ? { ...existing } : {};
			const servers = { ...next[wrapperKey] ?? {} };
			const alreadyHas = entryMatches$2(servers["agentmemory"]);
			if (alreadyHas && !opts.force) {
				logAlreadyWired(config.displayName, config.configPath);
				return {
					kind: "already-wired",
					mutatedPath: config.configPath
				};
			}
			if (opts.dryRun) {
				p.log.info(`[dry-run] Would ${alreadyHas ? "overwrite" : "add"} ${wrapperKey}.agentmemory in ${config.configPath}`);
				return {
					kind: "installed",
					mutatedPath: config.configPath
				};
			}
			let backupPath;
			if (existsSync(config.configPath)) {
				backupPath = backupFile(config.configPath, config.name);
				logBackup(backupPath);
			} else mkdirSync(dirname(config.configPath), { recursive: true });
			servers["agentmemory"] = {
				...AGENTMEMORY_MCP_BLOCK,
				...config.extraEntryFields ?? {}
			};
			next[wrapperKey] = servers;
			writeJsonAtomic(config.configPath, next);
			const verifyServers = readJsonSafe(config.configPath)?.[wrapperKey];
			if (!entryMatches$2(verifyServers?.["agentmemory"])) {
				p.log.error(`Verification failed: ${config.configPath} did not contain ${wrapperKey}.agentmemory after write.`);
				return {
					kind: "skipped",
					reason: "verification-failed"
				};
			}
			logInstalled(config.displayName, config.configPath);
			return {
				kind: "installed",
				mutatedPath: config.configPath,
				...backupPath !== void 0 && { backupPath }
			};
		}
	};
}
//#endregion
//#region src/cli/connect/antigravity.ts
const ANTIGRAVITY_DIR = platform() === "darwin" ? join(homedir(), "Library", "Application Support", "Antigravity", "User") : join(homedir(), ".config", "Antigravity", "User");
const adapter$16 = createJsonMcpAdapter({
	name: "antigravity",
	displayName: "Antigravity",
	detectDir: ANTIGRAVITY_DIR,
	configPath: join(ANTIGRAVITY_DIR, "mcp_config.json"),
	docs: "https://github.com/rohitg00/agentmemory#other-agents",
	protocolNote: "→ Using MCP via mcp_config.json. Antigravity replaces Gemini CLI (sunset 2026-06-18)."
});
//#endregion
//#region src/cli/connect/codex-hooks.ts
/**
* Locate the bundled `plugin/` directory at runtime. Walks up from the
* module's own location looking for `plugin/scripts/` + `plugin/hooks/`,
* both shipped via the npm `files` field. Works for both `dist/cli.mjs`
* (bundled) and `src/cli/connect/codex-hooks.ts` (dev) layouts.
*/
function findPluginRoot(startUrl = import.meta.url) {
	const here = dirname(fileURLToPath(startUrl));
	let dir = here;
	for (let i = 0; i < 12; i++) {
		if (existsSync(join(dir, "plugin", "scripts")) && existsSync(join(dir, "plugin", "hooks"))) return resolve(join(dir, "plugin"));
		const parent = dirname(dir);
		if (parent === dir) break;
		dir = parent;
	}
	throw new Error(`agentmemory: could not locate bundled plugin/ directory (searched up from ${here})`);
}
/**
* Build the merged hooks.json content.
*
*   1. Strip any entry from `existing` whose first hook command points
*      under `<pluginRoot>/scripts/`. This lets us re-install idempotently
*      without leaving stale references.
*   2. Append fresh entries from the bundled Codex manifest with
*      `${CLAUDE_PLUGIN_ROOT}` rewritten to the absolute plugin path.
*      Matcher values from the bundled manifest are preserved so PreToolUse
*      event routing keeps working.
*/
function buildMergedHooks(existing, pluginRoot, manifestFile = "hooks.codex.json") {
	const bundledManifestPath = join(pluginRoot, "hooks", manifestFile);
	const ours = JSON.parse(readFileSync(bundledManifestPath, "utf-8"));
	const scriptsDir = join(pluginRoot, "scripts");
	const out = { hooks: {} };
	if (existing?.hooks) for (const [event, entries] of Object.entries(existing.hooks)) {
		const kept = entries.filter((entry) => !isAgentmemoryEntry(entry, scriptsDir));
		if (kept.length > 0) out.hooks[event] = kept;
	}
	for (const [event, entries] of Object.entries(ours.hooks)) {
		const resolvedEntries = entries.map((entry) => {
			const next = { hooks: entry.hooks.map((handler) => ({
				type: handler.type,
				command: handler.command.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, pluginRoot)
			})) };
			if (entry.matcher !== void 0) next.matcher = entry.matcher;
			return next;
		});
		out.hooks[event] = [...out.hooks[event] ?? [], ...resolvedEntries];
	}
	return out;
}
function isAgentmemoryEntry(entry, scriptsDir) {
	const normalizedScriptsDir = normalizePathForCommandMatch(scriptsDir);
	return entry.hooks.some((handler) => normalizePathForCommandMatch(handler.command).includes(normalizedScriptsDir));
}
function normalizePathForCommandMatch(value) {
	return value.replace(/\\/g, "/");
}
//#endregion
//#region src/cli/connect/claude-code.ts
const CLAUDE_DIR = join(homedir(), ".claude");
const CLAUDE_JSON = join(homedir(), ".claude.json");
const CLAUDE_SETTINGS = join(CLAUDE_DIR, "settings.json");
function entryMatches$1(entry) {
	if (!entry || typeof entry !== "object") return false;
	const e = entry;
	if (e["command"] !== "npx") return false;
	return (Array.isArray(e["args"]) ? e["args"] : []).includes("@agentmemory/mcp");
}
const adapter$15 = {
	name: "claude-code",
	displayName: "Claude Code",
	docs: "https://github.com/rohitg00/agentmemory#claude-code-one-block-paste-it",
	protocolNote: "→ Using MCP. Hooks are also available — see docs/claude-code.md.",
	detect() {
		return existsSync(CLAUDE_DIR);
	},
	async install(opts) {
		const existing = readJsonSafe(CLAUDE_JSON);
		const next = existing ? { ...existing } : {};
		const servers = { ...next.mcpServers ?? {} };
		const alreadyHas = entryMatches$1(servers["agentmemory"]);
		if (alreadyHas && !opts.force) {
			logAlreadyWired("Claude Code", CLAUDE_JSON);
			if (opts.withHooks) {
				const hookResult = installClaudeHooks(opts);
				if (hookResult.kind === "skipped") p.log.warn(`Claude Code hooks fallback skipped: ${hookResult.reason}.`);
			}
			return {
				kind: "already-wired",
				mutatedPath: CLAUDE_JSON
			};
		}
		if (opts.dryRun) {
			p.log.info(`[dry-run] Would ${alreadyHas ? "overwrite" : "add"} mcpServers.agentmemory in ${CLAUDE_JSON}`);
			return {
				kind: "installed",
				mutatedPath: CLAUDE_JSON
			};
		}
		let backupPath;
		if (existsSync(CLAUDE_JSON)) {
			backupPath = backupFile(CLAUDE_JSON, "claude-code");
			logBackup(backupPath);
		} else {
			mkdirSync(CLAUDE_DIR, { recursive: true });
			writeFileSync(CLAUDE_JSON, "{}\n", "utf-8");
		}
		servers["agentmemory"] = AGENTMEMORY_MCP_BLOCK;
		next.mcpServers = servers;
		writeJsonAtomic(CLAUDE_JSON, next);
		if (!entryMatches$1(readJsonSafe(CLAUDE_JSON)?.mcpServers?.["agentmemory"])) {
			p.log.error(`Verification failed: ${CLAUDE_JSON} did not contain mcpServers.agentmemory after write.`);
			return {
				kind: "skipped",
				reason: "verification-failed"
			};
		}
		logInstalled("Claude Code", CLAUDE_JSON);
		p.log.info("Restart Claude Code (or run `/mcp` inside a session) to pick up the new server.");
		if (opts.withHooks) {
			const hookResult = installClaudeHooks(opts);
			if (hookResult.kind === "skipped") p.log.warn(`Claude Code hooks fallback skipped: ${hookResult.reason}. MCP wiring still applied.`);
		}
		return {
			kind: "installed",
			mutatedPath: CLAUDE_JSON,
			backupPath
		};
	}
};
/**
* Merge the bundled `plugin/hooks/hooks.json` into
* `~/.claude/settings.json`'s top-level `hooks` field with absolute
* script paths. Use this when agentmemory is NOT installed through
* `/plugin marketplace add` (e.g. MCP standalone wiring), so the
* hook scripts survive version bumps without `${CLAUDE_PLUGIN_ROOT}`
* expansion (issue #508).
*
* Re-install strips entries whose command points under
* `<pluginRoot>/scripts/`; unrelated user hook entries survive.
*/
function installClaudeHooks(opts) {
	let pluginRoot;
	try {
		pluginRoot = findPluginRoot();
	} catch (err) {
		return {
			kind: "skipped",
			reason: err instanceof Error ? err.message : String(err)
		};
	}
	const existing = readJsonSafe(CLAUDE_SETTINGS) ?? {};
	const merged = buildMergedHooks(existing.hooks ? { hooks: existing.hooks } : null, pluginRoot, "hooks.json");
	if (opts.dryRun) {
		p.log.info(`[dry-run] Would merge agentmemory hook entries into ${CLAUDE_SETTINGS} (${Object.keys(merged.hooks).length} event(s))`);
		return {
			kind: "installed",
			mutatedPath: CLAUDE_SETTINGS
		};
	}
	let backupPath;
	if (existsSync(CLAUDE_SETTINGS)) {
		backupPath = backupFile(CLAUDE_SETTINGS, "claude-settings", "json");
		logBackup(backupPath);
	} else mkdirSync(CLAUDE_DIR, { recursive: true });
	writeJsonAtomic(CLAUDE_SETTINGS, {
		...existing,
		hooks: merged.hooks
	});
	logInstalled("Claude Code hooks (workaround for #508)", CLAUDE_SETTINGS);
	p.log.info("User-scope hook entries reference absolute paths under the bundled plugin/ dir. Re-run `agentmemory connect claude-code --with-hooks` after upgrading agentmemory to refresh them.");
	return {
		kind: "installed",
		mutatedPath: CLAUDE_SETTINGS,
		...backupPath !== void 0 && { backupPath }
	};
}
//#endregion
//#region src/cli/connect/cline.ts
const adapter$14 = createJsonMcpAdapter({
	name: "cline",
	displayName: "Cline",
	detectDir: join(homedir(), ".cline"),
	configPath: join(homedir(), ".cline", "mcp.json"),
	docs: "https://github.com/rohitg00/agentmemory#other-agents",
	protocolNote: "→ Using MCP via ~/.cline/mcp.json (CLI). VS Code users: add the same block via Cline Settings → MCP Servers → Edit JSON."
});
//#endregion
//#region src/cli/connect/copilot-cli.ts
const COPILOT_DIR = process.env["COPILOT_HOME"] || join(homedir(), ".copilot");
const COPILOT_MCP_JSON = join(COPILOT_DIR, "mcp-config.json");
function entryMatches(entry) {
	if (!entry || typeof entry !== "object") return false;
	return JSON.stringify(entry) === JSON.stringify(AGENTMEMORY_COPILOT_MCP_BLOCK);
}
const adapter$13 = {
	name: "copilot-cli",
	displayName: "GitHub Copilot CLI",
	docs: "https://github.com/rohitg00/agentmemory#github-copilot-cli",
	protocolNote: "→ Using MCP. Install the plugin too for full hooks/skills coverage.",
	detect() {
		return existsSync(COPILOT_DIR);
	},
	async install(opts) {
		const existing = readJsonSafe(COPILOT_MCP_JSON);
		const next = existing ? { ...existing } : {};
		const servers = { ...next.mcpServers ?? {} };
		const alreadyHas = entryMatches(servers["agentmemory"]);
		if (alreadyHas && !opts.force) {
			logAlreadyWired("GitHub Copilot CLI", COPILOT_MCP_JSON);
			return {
				kind: "already-wired",
				mutatedPath: COPILOT_MCP_JSON
			};
		}
		if (opts.dryRun) {
			p.log.info(`[dry-run] Would ${alreadyHas ? "overwrite" : "add"} mcpServers.agentmemory in ${COPILOT_MCP_JSON}`);
			return {
				kind: "installed",
				mutatedPath: COPILOT_MCP_JSON
			};
		}
		let backupPath;
		if (existsSync(COPILOT_MCP_JSON)) {
			backupPath = backupFile(COPILOT_MCP_JSON, "copilot-cli");
			logBackup(backupPath);
		} else mkdirSync(dirname(COPILOT_MCP_JSON), { recursive: true });
		servers["agentmemory"] = AGENTMEMORY_COPILOT_MCP_BLOCK;
		next.mcpServers = servers;
		writeJsonAtomic(COPILOT_MCP_JSON, next);
		if (!entryMatches(readJsonSafe(COPILOT_MCP_JSON)?.mcpServers?.["agentmemory"])) {
			p.log.error(`Verification failed: ${COPILOT_MCP_JSON} did not contain mcpServers.agentmemory after write.`);
			return {
				kind: "skipped",
				reason: "verification-failed"
			};
		}
		logInstalled("GitHub Copilot CLI", COPILOT_MCP_JSON);
		p.log.info("Copilot picks up MCP servers on next launch or after `/mcp`. Install the plugin too for full hooks/skills.");
		return {
			kind: "installed",
			mutatedPath: COPILOT_MCP_JSON,
			...backupPath !== void 0 && { backupPath }
		};
	}
};
//#endregion
//#region src/cli/connect/codex.ts
const CODEX_DIR = join(homedir(), ".codex");
const CODEX_TOML = join(CODEX_DIR, "config.toml");
const CODEX_HOOKS = join(CODEX_DIR, "hooks.json");
const TOML_BLOCK = `[mcp_servers.agentmemory]
command = "npx"
args = ["-y", "@agentmemory/mcp"]

[mcp_servers.agentmemory.env]
AGENTMEMORY_URL = "http://localhost:3111"
`;
const SECTION_HEADER = "[mcp_servers.agentmemory]";
function isWiredText(toml) {
	return toml.includes(SECTION_HEADER);
}
function stripExistingBlock(toml) {
	const lines = toml.split(/\r?\n/);
	const out = [];
	let skipping = false;
	for (const line of lines) {
		const trimmed = line.trim();
		if (trimmed === SECTION_HEADER || trimmed === "[mcp_servers.agentmemory.env]") {
			skipping = true;
			continue;
		}
		if (skipping && trimmed.startsWith("[") && trimmed !== "[mcp_servers.agentmemory.env]") skipping = false;
		if (!skipping) out.push(line);
	}
	return out.join("\n").replace(/\n{3,}$/, "\n\n").trimEnd() + "\n";
}
const adapter$12 = {
	name: "codex",
	displayName: "Codex CLI",
	docs: "https://github.com/rohitg00/agentmemory#codex-cli-codex-plugin-platform",
	protocolNote: "→ Using MCP. Hooks ship via the Codex plugin; on Codex Desktop, also pass --with-hooks to install the global hooks.json workaround for openai/codex#16430.",
	detect() {
		return existsSync(CODEX_DIR);
	},
	async install(opts) {
		const exists = existsSync(CODEX_TOML);
		const current = exists ? readFileSync(CODEX_TOML, "utf-8") : "";
		const wired = isWiredText(current);
		if (wired && !opts.force) {
			logAlreadyWired("Codex CLI", CODEX_TOML);
			return {
				kind: "already-wired",
				mutatedPath: CODEX_TOML
			};
		}
		if (opts.dryRun) {
			p.log.info(`[dry-run] Would ${wired ? "rewrite" : "append"} [mcp_servers.agentmemory] in ${CODEX_TOML}`);
			if (opts.withHooks) installCodexHooks(opts);
			return {
				kind: "installed",
				mutatedPath: CODEX_TOML
			};
		}
		let backupPath;
		if (exists) {
			backupPath = backupFile(CODEX_TOML, "codex", "toml");
			logBackup(backupPath);
		} else mkdirSync(dirname(CODEX_TOML), { recursive: true });
		const cleaned = wired ? stripExistingBlock(current) : current;
		writeFileSync(CODEX_TOML, `${cleaned}${cleaned.length === 0 || cleaned.endsWith("\n") ? "" : "\n"}${cleaned.length > 0 ? "\n" : ""}${TOML_BLOCK}`, "utf-8");
		if (!isWiredText(readFileSync(CODEX_TOML, "utf-8"))) {
			p.log.error(`Verification failed: ${CODEX_TOML} did not contain ${SECTION_HEADER} after write.`);
			return {
				kind: "skipped",
				reason: "verification-failed"
			};
		}
		logInstalled("Codex CLI", CODEX_TOML);
		p.log.info("Codex picks up MCP servers on next launch. For the deeper plugin install, run: codex plugin marketplace add rohitg00/agentmemory && codex plugin add agentmemory@agentmemory");
		if (opts.withHooks) {
			const hookResult = installCodexHooks(opts);
			if (hookResult.kind === "skipped") p.log.warn(`Codex hooks fallback skipped: ${hookResult.reason}. MCP wiring still applied.`);
		}
		return {
			kind: "installed",
			mutatedPath: CODEX_TOML,
			...backupPath !== void 0 && { backupPath }
		};
	}
};
/**
* Install the global `~/.codex/hooks.json` fallback. See
* `codex-hooks.ts` for context (openai/codex#16430). Returns a result
* describing the side effect for the caller's summary; failures here do
* not roll back the MCP wiring.
*/
function installCodexHooks(opts) {
	let pluginRoot;
	try {
		pluginRoot = findPluginRoot();
	} catch (err) {
		return {
			kind: "skipped",
			reason: err instanceof Error ? err.message : String(err)
		};
	}
	const existing = readJsonSafe(CODEX_HOOKS);
	const merged = buildMergedHooks(existing, pluginRoot);
	if (opts.dryRun) {
		p.log.info(`[dry-run] Would ${existing ? "merge" : "create"} ${CODEX_HOOKS} with ${Object.keys(merged.hooks).length} event(s)`);
		return {
			kind: "installed",
			mutatedPath: CODEX_HOOKS
		};
	}
	let backupPath;
	if (existsSync(CODEX_HOOKS)) {
		backupPath = backupFile(CODEX_HOOKS, "codex-hooks", "json");
		logBackup(backupPath);
	}
	writeJsonAtomic(CODEX_HOOKS, merged);
	logInstalled("Codex hooks (workaround for openai/codex#16430)", CODEX_HOOKS);
	p.log.info("User-scope hooks reference absolute paths under the bundled plugin/ dir. Re-run `agentmemory connect codex --with-hooks` after upgrading agentmemory to refresh them.");
	return {
		kind: "installed",
		mutatedPath: CODEX_HOOKS,
		...backupPath !== void 0 && { backupPath }
	};
}
//#endregion
//#region src/cli/connect/continue.ts
const CONTINUE_DIR = join(homedir(), ".continue");
const YAML_PATH = join(CONTINUE_DIR, "config.yaml");
const JSON_PATH = join(CONTINUE_DIR, "config.json");
function buildEntry() {
	return {
		name: "agentmemory",
		command: AGENTMEMORY_MCP_BLOCK.command,
		args: [...AGENTMEMORY_MCP_BLOCK.args],
		env: { ...AGENTMEMORY_MCP_BLOCK.env }
	};
}
function entryIsAgentmemory(entry) {
	if (!entry) return false;
	return entry.name === "agentmemory" && entry.args.includes("@agentmemory/mcp");
}
function renderFreshYaml() {
	const e = buildEntry();
	const envLines = Object.entries(e.env ?? {}).map(([k, v]) => `      ${k}: "${v}"`).join("\n");
	return [
		"mcpServers:",
		`  - name: ${e.name}`,
		`    command: ${e.command}`,
		"    args:",
		...e.args.map((a) => `      - "${a}"`),
		"    env:",
		envLines,
		""
	].join("\n");
}
const adapter$11 = {
	name: "continue",
	displayName: "Continue",
	docs: "https://github.com/rohitg00/agentmemory#other-agents",
	protocolNote: "→ Using MCP via ~/.continue/config.yaml (preferred) or config.json (legacy, only when no yaml).",
	detect() {
		return existsSync(CONTINUE_DIR);
	},
	async install(opts) {
		const yamlExists = existsSync(YAML_PATH);
		const jsonExists = existsSync(JSON_PATH);
		if (yamlExists) {
			const manual = `\nMerge this block into ~/.continue/config.yaml (the snippet already includes the top-level mcpServers key — if your config already has a mcpServers list, append the agentmemory entry to it instead of duplicating the key):\n\n${renderFreshYaml().split("\n").map((l) => l ? `  ${l}` : l).join("\n")}`;
			p.log.info(`Continue: ${YAML_PATH} already exists. Manual edit needed.${manual}`);
			return {
				kind: "stub",
				reason: "config.yaml-needs-manual-edit"
			};
		}
		if (jsonExists) {
			const existing = readJsonSafe(JSON_PATH);
			const next = existing ? { ...existing } : {};
			const servers = Array.isArray(next.mcpServers) ? [...next.mcpServers] : [];
			const idx = servers.findIndex((s) => s?.name === "agentmemory");
			const alreadyHas = idx >= 0 && entryIsAgentmemory(servers[idx]);
			if (alreadyHas && !opts.force) {
				logAlreadyWired("Continue", JSON_PATH);
				return {
					kind: "already-wired",
					mutatedPath: JSON_PATH
				};
			}
			if (opts.dryRun) {
				p.log.info(`[dry-run] Would ${alreadyHas ? "overwrite" : "add"} mcpServers[agentmemory] in ${JSON_PATH}`);
				return {
					kind: "installed",
					mutatedPath: JSON_PATH
				};
			}
			const backupPath = backupFile(JSON_PATH, "continue");
			logBackup(backupPath);
			const entry = buildEntry();
			if (idx >= 0) servers[idx] = entry;
			else servers.push(entry);
			next.mcpServers = servers;
			writeJsonAtomic(JSON_PATH, next);
			const verifyEntry = readJsonSafe(JSON_PATH)?.mcpServers?.find((s) => s?.name === "agentmemory");
			if (!entryIsAgentmemory(verifyEntry)) {
				p.log.error(`Verification failed: ${JSON_PATH} did not contain mcpServers[agentmemory] after write.`);
				return {
					kind: "skipped",
					reason: "verification-failed"
				};
			}
			logInstalled("Continue (legacy config.json)", JSON_PATH);
			return {
				kind: "installed",
				mutatedPath: JSON_PATH,
				backupPath
			};
		}
		if (opts.dryRun) {
			p.log.info(`[dry-run] Would create ${YAML_PATH} with agentmemory entry`);
			return {
				kind: "installed",
				mutatedPath: YAML_PATH
			};
		}
		mkdirSync(dirname(YAML_PATH), { recursive: true });
		writeFileSync(YAML_PATH, renderFreshYaml(), "utf-8");
		logInstalled("Continue", YAML_PATH);
		return {
			kind: "installed",
			mutatedPath: YAML_PATH
		};
	}
};
//#endregion
//#region src/cli/connect/cursor.ts
const adapter$10 = createJsonMcpAdapter({
	name: "cursor",
	displayName: "Cursor",
	detectDir: join(homedir(), ".cursor"),
	configPath: join(homedir(), ".cursor", "mcp.json"),
	docs: "https://github.com/rohitg00/agentmemory#other-agents",
	protocolNote: "→ Using MCP (the only protocol Cursor speaks). Memory bridge runs at :3111 underneath."
});
//#endregion
//#region src/cli/connect/droid.ts
const adapter$9 = createJsonMcpAdapter({
	name: "droid",
	displayName: "Droid (Factory.ai)",
	detectDir: join(homedir(), ".factory"),
	configPath: join(homedir(), ".factory", "mcp.json"),
	docs: "https://github.com/rohitg00/agentmemory#other-agents",
	protocolNote: "→ Using MCP via ~/.factory/mcp.json. The `/mcp` slash command inside droid lists configured servers.",
	extraEntryFields: { type: "stdio" }
});
//#endregion
//#region src/cli/connect/gemini-cli.ts
const adapter$8 = createJsonMcpAdapter({
	name: "gemini-cli",
	displayName: "Gemini CLI",
	detectDir: join(homedir(), ".gemini"),
	configPath: join(homedir(), ".gemini", "settings.json"),
	docs: "https://github.com/rohitg00/agentmemory#other-agents",
	protocolNote: "→ Using MCP (the only protocol Gemini CLI speaks). Memory bridge runs at :3111 underneath."
});
//#endregion
//#region src/cli/connect/hermes.ts
const HERMES_DIR = join(homedir(), ".hermes");
const HERMES_CONFIG = join(HERMES_DIR, "config.yaml");
const DOCS$2 = "https://github.com/rohitg00/agentmemory/tree/main/integrations/hermes";
const adapter$7 = {
	name: "hermes",
	displayName: "Hermes Agent",
	docs: DOCS$2,
	protocolNote: "→ Using MCP. Hooks are also available — see docs/hermes.md.",
	detect() {
		return existsSync(HERMES_DIR);
	},
	async install(_opts) {
		p.log.warn("Hermes uses YAML config. Automated merge isn't implemented yet — manual install required.");
		p.note([
			`Add to ${HERMES_CONFIG}:`,
			"",
			"  mcp_servers:",
			"    agentmemory:",
			"      command: npx",
			"      args: [\"-y\", \"@agentmemory/mcp\"]",
			"",
			"  memory:",
			"    provider: agentmemory",
			"",
			`Full guide: ${DOCS$2}`
		].join("\n"), "Hermes manual install");
		return {
			kind: "stub",
			reason: "yaml-merge-not-implemented"
		};
	}
};
//#endregion
//#region src/cli/connect/kiro.ts
const adapter$6 = createJsonMcpAdapter({
	name: "kiro",
	displayName: "Kiro",
	detectDir: join(homedir(), ".kiro"),
	configPath: join(homedir(), ".kiro", "settings", "mcp.json"),
	docs: "https://github.com/rohitg00/agentmemory#other-agents",
	protocolNote: "→ Using MCP via ~/.kiro/settings/mcp.json (user-level). Workspace overrides live in .kiro/settings/mcp.json."
});
//#endregion
//#region src/cli/connect/openclaw.ts
const adapter$5 = createJsonMcpAdapter({
	name: "openclaw",
	displayName: "OpenClaw",
	detectDir: join(homedir(), ".openclaw"),
	configPath: join(homedir(), ".openclaw", "openclaw.json"),
	docs: "https://github.com/rohitg00/agentmemory/tree/main/integrations/openclaw",
	protocolNote: "→ Using MCP. Hooks are also available — see docs/openclaw.md."
});
//#endregion
//#region src/cli/connect/openhuman.ts
const OPENHUMAN_DIR = join(homedir(), ".openhuman");
const DOCS$1 = "https://github.com/tinyhumansai/openhuman";
const adapter$4 = {
	name: "openhuman",
	displayName: "OpenHuman",
	docs: DOCS$1,
	protocolNote: "→ Using native hooks (REST API at :3111). MCP not required.",
	detect() {
		return existsSync(OPENHUMAN_DIR);
	},
	async install(_opts) {
		p.log.warn("OpenHuman integration is not yet automated. No `integrations/openhuman/` folder exists in the agentmemory repo today.");
		p.note([
			"OpenHuman is a Memory-trait host. The expected wiring is the REST",
			"proxy at http://localhost:3111 plus an OpenHuman-side Memory trait",
			"impl. Once integrations/openhuman/ lands in agentmemory we'll wire",
			"this up automatically.",
			"",
			`Tracking: ${DOCS$1}`
		].join("\n"), "OpenHuman manual install");
		return {
			kind: "stub",
			reason: "no-integration-folder-yet"
		};
	}
};
//#endregion
//#region src/cli/connect/pi.ts
const PI_DIR = join(homedir(), ".pi");
const PI_EXT_DIR = join(PI_DIR, "agent", "extensions", "agentmemory");
const DOCS = "https://github.com/rohitg00/agentmemory/tree/main/integrations/pi";
const adapter$3 = {
	name: "pi",
	displayName: "pi",
	docs: DOCS,
	protocolNote: "→ Using native hooks (REST API at :3111). MCP not required.",
	detect() {
		return existsSync(PI_DIR);
	},
	async install(_opts) {
		p.log.warn("pi uses a TypeScript extension file. Automated copy + register isn't implemented yet — manual install required.");
		p.note([
			"Run these from the agentmemory repo root:",
			"",
			`  mkdir -p ${PI_EXT_DIR}`,
			`  cp integrations/pi/index.ts ${PI_EXT_DIR}/index.ts`,
			`  cp integrations/pi/security.ts ${PI_EXT_DIR}/security.ts`,
			"",
			"Then add to ~/.pi/agent/settings.json:",
			"  { \"extensions\": [\"~/.pi/agent/extensions/agentmemory\"] }",
			"",
			`Full guide: ${DOCS}`
		].join("\n"), "pi manual install");
		return {
			kind: "stub",
			reason: "ts-extension-copy-not-implemented"
		};
	}
};
//#endregion
//#region src/cli/connect/qwen.ts
const adapter$2 = createJsonMcpAdapter({
	name: "qwen",
	displayName: "Qwen Code",
	detectDir: join(homedir(), ".qwen"),
	configPath: join(homedir(), ".qwen", "settings.json"),
	docs: "https://github.com/rohitg00/agentmemory#other-agents",
	protocolNote: "→ Using MCP via ~/.qwen/settings.json. Qwen Code's hook system can also be wired separately — see docs."
});
//#endregion
//#region src/cli/connect/warp.ts
const adapter$1 = createJsonMcpAdapter({
	name: "warp",
	displayName: "Warp",
	detectDir: join(homedir(), ".warp"),
	configPath: join(homedir(), ".warp", ".mcp.json"),
	docs: "https://github.com/rohitg00/agentmemory#other-agents",
	protocolNote: "→ Using MCP via ~/.warp/.mcp.json. Skills auto-discover from .claude/skills/ if the Claude Code plugin is also installed."
});
//#endregion
//#region src/cli/connect/zed.ts
const zedConfigDir = join(homedir(), ".config", "zed");
const adapter = createJsonMcpAdapter({
	name: "zed",
	displayName: "Zed",
	detectDir: zedConfigDir,
	configPath: join(zedConfigDir, "settings.json"),
	wrapperKey: "context_servers",
	docs: "https://github.com/rohitg00/agentmemory#other-agents",
	protocolNote: "→ Using MCP via ~/.config/zed/settings.json (key: context_servers)."
});
//#endregion
//#region src/cli/connect/index.ts
var connect_exports = /* @__PURE__ */ __exportAll({
	ADAPTERS: () => ADAPTERS,
	knownAgents: () => knownAgents,
	resolveAdapter: () => resolveAdapter,
	runAdapter: () => runAdapter,
	runConnect: () => runConnect
});
const ADAPTERS = [
	adapter$15,
	adapter$13,
	adapter$12,
	adapter$10,
	adapter$8,
	adapter$2,
	adapter$16,
	adapter$6,
	adapter$1,
	adapter$14,
	adapter$11,
	adapter,
	adapter$9,
	adapter$5,
	adapter$7,
	adapter$3,
	adapter$4
];
function resolveAdapter(name) {
	const lower = name.toLowerCase();
	return ADAPTERS.find((a) => a.name === lower) ?? null;
}
function knownAgents() {
	return ADAPTERS.map((a) => a.name);
}
function parseFlags(args) {
	const positional = [];
	let dryRun = false;
	let force = false;
	let all = false;
	let withHooks = false;
	for (const a of args) if (a === "--dry-run") dryRun = true;
	else if (a === "--force") force = true;
	else if (a === "--all") all = true;
	else if (a === "--with-hooks") withHooks = true;
	else if (!a.startsWith("-")) positional.push(a);
	return {
		dryRun,
		force,
		all,
		withHooks,
		positional
	};
}
async function runAdapter(adapter, opts) {
	if (!adapter.detect()) {
		p.log.warn(`${adapter.displayName}: not detected on this machine (skipping).${adapter.docs ? ` Docs: ${adapter.docs}` : ""}`);
		return {
			kind: "skipped",
			reason: "not-detected"
		};
	}
	p.log.step(`Wiring ${adapter.displayName}…`);
	if (adapter.protocolNote) p.log.message(adapter.protocolNote);
	try {
		return await adapter.install(opts);
	} catch (err) {
		p.log.error(`${adapter.displayName}: ${err instanceof Error ? err.message : String(err)}`);
		return {
			kind: "skipped",
			reason: "exception"
		};
	}
}
async function runConnect(args) {
	const { dryRun, force, all, withHooks, positional } = parseFlags(args);
	const allowWindowsAdapter = positional.length === 1 && positional[0]?.toLowerCase() === "copilot-cli";
	if (platform() === "win32" && !allowWindowsAdapter) {
		p.intro("agentmemory connect");
		p.log.warn("Windows: automated `connect` is not supported yet. See https://github.com/rohitg00/agentmemory#other-agents for manual install steps.");
		p.outro("Windows: manual install required — see docs");
		return;
	}
	const opts = {
		dryRun,
		force,
		withHooks
	};
	p.intro("agentmemory connect");
	if (positional.length === 0 && !all) {
		const detected = ADAPTERS.filter((a) => a.detect());
		if (detected.length === 0) {
			p.log.error("No supported agents detected on this machine.");
			p.outro(`Supported: ${knownAgents().join(", ")}`);
			process.exit(1);
		}
		const picked = await p.multiselect({
			message: "Wire agentmemory into which agents?",
			options: detected.map((a) => ({
				value: a.name,
				label: a.displayName
			})),
			required: true
		});
		if (p.isCancel(picked)) {
			p.cancel("Cancelled.");
			return;
		}
		const results = [];
		for (const name of picked) {
			const adapter = resolveAdapter(name);
			if (!adapter) continue;
			results.push({
				name,
				result: await runAdapter(adapter, opts)
			});
		}
		summarize(results);
		return;
	}
	if (all) {
		const detected = ADAPTERS.filter((a) => a.detect());
		if (detected.length === 0) {
			p.log.error("No supported agents detected on this machine.");
			process.exit(1);
		}
		const results = [];
		for (const adapter of detected) results.push({
			name: adapter.name,
			result: await runAdapter(adapter, opts)
		});
		summarize(results);
		return;
	}
	const agentName = positional[0];
	const adapter = resolveAdapter(agentName);
	if (!adapter) {
		p.log.error(`Unknown agent: ${agentName}`);
		p.outro(`Supported: ${knownAgents().join(", ")}`);
		process.exit(1);
	}
	const result = await runAdapter(adapter, opts);
	summarize([{
		name: agentName,
		result
	}]);
	if (result.kind === "skipped" && result.reason !== "not-detected") process.exit(1);
}
function summarize(results) {
	const lines = results.map(({ name, result }) => {
		switch (result.kind) {
			case "installed": return `  ✓ ${name}${result.mutatedPath ? ` → ${result.mutatedPath}` : ""}`;
			case "already-wired": return `  ✓ ${name} (already wired)`;
			case "stub": return `  ⚠ ${name} (manual install required: ${result.reason})`;
			case "skipped": return `  ✗ ${name} (skipped: ${result.reason})`;
		}
	});
	p.note(lines.join("\n"), "summary");
	const stubs = results.filter((r) => r.result.kind === "stub");
	if (stubs.length > 0) p.log.info(`${stubs.length} agent(s) require manual install — see docs links above.`);
	if (results.some((r) => r.result.kind === "installed" || r.result.kind === "already-wired")) p.log.info("Next: install agentmemory's 8 skills into the same agent(s) so they know when to call the tools:\n  npx skills add rohitg00/agentmemory -y");
	p.outro("Restart any wired agent (or open a new session) to pick up agentmemory.");
}
//#endregion
export { resolveAdapter as n, runAdapter as r, connect_exports as t };

//# sourceMappingURL=connect-bmZ5eqYN.mjs.map