import { g as resolveStateDir, i as isNixMode, m as resolveOAuthDir, o as resolveConfigPath, u as resolveGatewayPort } from "./paths-CutK9mvd.js";
import "./registry-DScA7GM7.js";
import { _ as resolveHomeDir, x as shortenHomeInString, y as resolveUserPath, z as theme } from "./utils-BXq128Ep.js";
import { f as defaultRuntime } from "./subsystem-C0jWWDsO.js";
import "./boolean-DtWR5bt3.js";
import "./auth-profiles-Ci0m1nDj.js";
import { t as formatCliCommand } from "./command-format-DXX8mw-3.js";
import "./exec-BfxXkFYo.js";
import { D as resolveDefaultAgentWorkspaceDir } from "./agent-scope-C9lu5zYP.js";
import "./frontmatter-B3s_6fwe.js";
import "./skills-CXwgvGur.js";
import "./manifest-registry-CLylU6AG.js";
import "./skills-status-C_4ZtMSQ.js";
import { a as readConfigFileSnapshot, r as loadConfig } from "./io-CD_zuK0D.js";
import "./config-DiWsrVKe.js";
import "./client-DcGx78uR.js";
import "./call-DfwL1J3H.js";
import "./message-channel-f25bXyKM.js";
import "./subagent-registry-C2sM5Cyw.js";
import "./sessions-Mt8f23sr.js";
import "./tokens-D7kBZYPD.js";
import "./plugins-CiXA7mtz.js";
import "./accounts-DlyBFGv4.js";
import "./bindings-DjR4yXgA.js";
import "./logging-pqyrk15z.js";
import "./send-BSyWSMGa.js";
import "./send-Bv-Ugxhn.js";
import "./with-timeout-CMUEB0p-.js";
import "./deliver-CkqGoWHC.js";
import "./accounts-DNDn42nY.js";
import "./send-Dbw-1Nv6.js";
import "./image-ops-DX6lds-i.js";
import "./models-config-6QdRrV1c.js";
import "./pi-embedded-helpers-_sjZz5r6.js";
import "./sandbox-Cgi5GRjr.js";
import "./chrome-CCvAKFA-.js";
import "./tailscale-BrDWEIwI.js";
import "./auth-B80pI0Uh.js";
import "./server-context-CPsi2755.js";
import "./routes-MRFMs3Hh.js";
import "./redact-CFj039qF.js";
import "./errors-8VQXhB4u.js";
import "./paths-BKv1HwMq.js";
import "./ssrf-weuQnXiO.js";
import "./store-BgSeZwv0.js";
import "./ports-BTCCmBPN.js";
import "./trash-RPQQ3ep-.js";
import "./accounts-IQLo28rM.js";
import "./paths-mQAx86lp.js";
import "./tool-images-BtNaJzDf.js";
import "./reply-prefix-CTkJoXqQ.js";
import "./memory-cli-DhQ3BMgb.js";
import "./manager-BUwPVwMU.js";
import "./gemini-auth-D_WaKG1u.js";
import "./sqlite-B6wrIncg.js";
import "./retry-eZfsfPJw.js";
import "./common-Cb-qblwg.js";
import "./chunk-CCkvwRI1.js";
import "./markdown-tables-BmPL6gxD.js";
import "./fetch-guard-DgkwAf8y.js";
import "./fetch-Cyj7bUtQ.js";
import "./ir-Zi6SqHuv.js";
import "./render-lL152pED.js";
import "./commands-registry-Bb7wps-U.js";
import "./runner-Dq5pUJw7.js";
import "./tool-display-C_2MZJqm.js";
import "./model-catalog-I10Mw32M.js";
import "./session-utils-rRgbDHdn.js";
import "./pi-tools.policy-Dl38gqLG.js";
import "./pairing-store-BFjZsQfU.js";
import "./fetch-FKiEPHsu.js";
import "./nodes-screen-aqjJyJKK.js";
import "./session-cost-usage-CFkSIl99.js";
import "./send-Dm5td_ud.js";
import "./outbound-attachment-DbnUFGg7.js";
import "./delivery-queue-CrM_98Zj.js";
import "./project-context-CDgzGX_i.js";
import "./control-service-Da4pvhRF.js";
import "./stagger-vDSk1wpM.js";
import "./channel-selection-C9HQldEr.js";
import "./send-DVTkNDIS.js";
import "./resolve-route-DfP8shJU.js";
import "./channel-activity-CjNqpxzA.js";
import "./tables-D0RFg7_p.js";
import { t as formatDocsLink } from "./links-Crq8FXFM.js";
import { n as runCommandWithRuntime } from "./cli-utils-m10N0YX2.js";
import "./help-format-xwRPMYQn.js";
import "./progress-Czj96fRf.js";
import "./replies-D7zeCuNw.js";
import { f as openUrl, g as resolveControlUiLinks, i as detectBrowserOpenSupport, o as formatControlUiSshHint } from "./onboard-helpers-BfUVfjJm.js";
import { n as stylePromptMessage, r as stylePromptTitle, t as stylePromptHint } from "./prompt-style-gyFdZw9z.js";
import "./pairing-labels-DcHuGxfy.js";
import { t as copyToClipboard } from "./clipboard-BFhwU-Qo.js";
import "./catalog-C5-j4Yr-.js";
import "./note-DBwiNGlo.js";
import "./plugin-auto-enable-D5QkbU5E.js";
import "./channels-status-issues-DtrUrEfm.js";
import "./register.subclis-IgsiQxg3.js";
import "./command-registry-5cbxhiw-.js";
import "./program-context-DtYiUT5k.js";
import "./completion-cli-wI_Pplip.js";
import "./daemon-runtime-CZOtxU0-.js";
import "./runtime-guard-CV_MGdwf.js";
import "./systemd-DJnyEJey.js";
import { t as resolveGatewayService } from "./service-B4bQU0ni.js";
import "./lifecycle-core-B5bqzlly.js";
import { o as runDaemonStop } from "./daemon-cli-cI1GSscx.js";
import "./diagnostics-ks9adiD4.js";
import "./health-DSAmjFa7.js";
import "./control-ui-assets-DWW83OaY.js";
import "./update-check-WiRoNCAg.js";
import "./dm-policy-shared-BQQ5gTsK.js";
import "./session-dirs-C6hJZt4b.js";
import "./logging-D0STCWnR.js";
import "./doctor-config-flow-UlrbUY4t.js";
import "./systemd-linger-DkqrShRC.js";
import "./health-format-C9GZy4gZ.js";
import { n as doctorCommand, t as selectStyled } from "./prompt-select-styled-BdngRkzw.js";
import "./doctor-completion-HoFRO5vx.js";
import path from "node:path";
import fs from "node:fs/promises";
import { cancel, confirm, isCancel, multiselect } from "@clack/prompts";

//#region src/commands/dashboard.ts
async function dashboardCommand(runtime = defaultRuntime, options = {}) {
	const snapshot = await readConfigFileSnapshot();
	const cfg = snapshot.valid ? snapshot.config : {};
	const port = resolveGatewayPort(cfg);
	const bind = cfg.gateway?.bind ?? "loopback";
	const basePath = cfg.gateway?.controlUi?.basePath;
	const customBindHost = cfg.gateway?.customBindHost;
	const token = cfg.gateway?.auth?.token ?? process.env.CODERCLAW_GATEWAY_TOKEN ?? "";
	const links = resolveControlUiLinks({
		port,
		bind: bind === "lan" ? "loopback" : bind,
		customBindHost,
		basePath
	});
	const dashboardUrl = token ? `${links.httpUrl}#token=${encodeURIComponent(token)}` : links.httpUrl;
	runtime.log(`Dashboard URL: ${dashboardUrl}`);
	const copied = await copyToClipboard(dashboardUrl).catch(() => false);
	runtime.log(copied ? "Copied to clipboard." : "Copy to clipboard unavailable.");
	let opened = false;
	let hint;
	if (!options.noOpen) {
		if ((await detectBrowserOpenSupport()).ok) opened = await openUrl(dashboardUrl);
		if (!opened) hint = formatControlUiSshHint({
			port,
			basePath,
			token: token || void 0
		});
	} else hint = "Browser launch disabled (--no-open). Use the URL above.";
	if (opened) runtime.log("Opened in your browser. Keep that tab to control CoderClaw.");
	else if (hint) runtime.log(hint);
}

//#endregion
//#region src/commands/cleanup-utils.ts
function collectWorkspaceDirs(cfg) {
	const dirs = /* @__PURE__ */ new Set();
	const defaults = cfg?.agents?.defaults;
	if (typeof defaults?.workspace === "string" && defaults.workspace.trim()) dirs.add(resolveUserPath(defaults.workspace));
	const list = Array.isArray(cfg?.agents?.list) ? cfg?.agents?.list : [];
	for (const agent of list) {
		const workspace = agent.workspace;
		if (typeof workspace === "string" && workspace.trim()) dirs.add(resolveUserPath(workspace));
	}
	if (dirs.size === 0) dirs.add(resolveDefaultAgentWorkspaceDir());
	return [...dirs];
}
function buildCleanupPlan(params) {
	return {
		configInsideState: isPathWithin(params.configPath, params.stateDir),
		oauthInsideState: isPathWithin(params.oauthDir, params.stateDir),
		workspaceDirs: collectWorkspaceDirs(params.cfg)
	};
}
function isPathWithin(child, parent) {
	const relative = path.relative(parent, child);
	return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
}
function isUnsafeRemovalTarget(target) {
	if (!target.trim()) return true;
	const resolved = path.resolve(target);
	if (resolved === path.parse(resolved).root) return true;
	const home = resolveHomeDir();
	if (home && resolved === path.resolve(home)) return true;
	return false;
}
async function removePath(target, runtime, opts) {
	if (!target?.trim()) return {
		ok: false,
		skipped: true
	};
	const resolved = path.resolve(target);
	const displayLabel = shortenHomeInString(opts?.label ?? resolved);
	if (isUnsafeRemovalTarget(resolved)) {
		runtime.error(`Refusing to remove unsafe path: ${displayLabel}`);
		return { ok: false };
	}
	if (opts?.dryRun) {
		runtime.log(`[dry-run] remove ${displayLabel}`);
		return {
			ok: true,
			skipped: true
		};
	}
	try {
		await fs.rm(resolved, {
			recursive: true,
			force: true
		});
		runtime.log(`Removed ${displayLabel}`);
		return { ok: true };
	} catch (err) {
		runtime.error(`Failed to remove ${displayLabel}: ${String(err)}`);
		return { ok: false };
	}
}
async function listAgentSessionDirs(stateDir) {
	const root = path.join(stateDir, "agents");
	try {
		return (await fs.readdir(root, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => path.join(root, entry.name, "sessions"));
	} catch {
		return [];
	}
}

//#endregion
//#region src/commands/cleanup-plan.ts
function resolveCleanupPlanFromDisk() {
	const cfg = loadConfig();
	const stateDir = resolveStateDir();
	const configPath = resolveConfigPath();
	const oauthDir = resolveOAuthDir();
	return {
		cfg,
		stateDir,
		configPath,
		oauthDir,
		...buildCleanupPlan({
			cfg,
			stateDir,
			configPath,
			oauthDir
		})
	};
}

//#endregion
//#region src/commands/reset.ts
async function stopGatewayIfRunning(runtime) {
	if (isNixMode) return;
	const service = resolveGatewayService();
	let loaded = false;
	try {
		loaded = await service.isLoaded({ env: process.env });
	} catch (err) {
		runtime.error(`Gateway service check failed: ${String(err)}`);
		return;
	}
	if (!loaded) return;
	try {
		await service.stop({
			env: process.env,
			stdout: process.stdout
		});
	} catch (err) {
		runtime.error(`Gateway stop failed: ${String(err)}`);
	}
}
async function resetCommand(runtime, opts) {
	const interactive = !opts.nonInteractive;
	if (!interactive && !opts.yes) {
		runtime.error("Non-interactive mode requires --yes.");
		runtime.exit(1);
		return;
	}
	let scope = opts.scope;
	if (!scope) {
		if (!interactive) {
			runtime.error("Non-interactive mode requires --scope.");
			runtime.exit(1);
			return;
		}
		const selection = await selectStyled({
			message: "Reset scope",
			options: [
				{
					value: "config",
					label: "Config only",
					hint: "coderclaw.json"
				},
				{
					value: "config+creds+sessions",
					label: "Config + credentials + sessions",
					hint: "keeps workspace + auth profiles"
				},
				{
					value: "full",
					label: "Full reset",
					hint: "state dir + workspace"
				}
			],
			initialValue: "config+creds+sessions"
		});
		if (isCancel(selection)) {
			cancel(stylePromptTitle("Reset cancelled.") ?? "Reset cancelled.");
			runtime.exit(0);
			return;
		}
		scope = selection;
	}
	if (![
		"config",
		"config+creds+sessions",
		"full"
	].includes(scope)) {
		runtime.error("Invalid --scope. Expected \"config\", \"config+creds+sessions\", or \"full\".");
		runtime.exit(1);
		return;
	}
	if (interactive && !opts.yes) {
		const ok = await confirm({ message: stylePromptMessage(`Proceed with ${scope} reset?`) });
		if (isCancel(ok) || !ok) {
			cancel(stylePromptTitle("Reset cancelled.") ?? "Reset cancelled.");
			runtime.exit(0);
			return;
		}
	}
	const dryRun = Boolean(opts.dryRun);
	const { stateDir, configPath, oauthDir, configInsideState, oauthInsideState, workspaceDirs } = resolveCleanupPlanFromDisk();
	if (scope !== "config") if (dryRun) runtime.log("[dry-run] stop gateway service");
	else await stopGatewayIfRunning(runtime);
	if (scope === "config") {
		await removePath(configPath, runtime, {
			dryRun,
			label: configPath
		});
		return;
	}
	if (scope === "config+creds+sessions") {
		await removePath(configPath, runtime, {
			dryRun,
			label: configPath
		});
		await removePath(oauthDir, runtime, {
			dryRun,
			label: oauthDir
		});
		const sessionDirs = await listAgentSessionDirs(stateDir);
		for (const dir of sessionDirs) await removePath(dir, runtime, {
			dryRun,
			label: dir
		});
		runtime.log(`Next: ${formatCliCommand("coderclaw onboard --install-daemon")}`);
		return;
	}
	if (scope === "full") {
		await removePath(stateDir, runtime, {
			dryRun,
			label: stateDir
		});
		if (!configInsideState) await removePath(configPath, runtime, {
			dryRun,
			label: configPath
		});
		if (!oauthInsideState) await removePath(oauthDir, runtime, {
			dryRun,
			label: oauthDir
		});
		for (const workspace of workspaceDirs) await removePath(workspace, runtime, {
			dryRun,
			label: workspace
		});
		runtime.log(`Next: ${formatCliCommand("coderclaw onboard --install-daemon")}`);
		return;
	}
}

//#endregion
//#region src/commands/uninstall.ts
const multiselectStyled = (params) => multiselect({
	...params,
	message: stylePromptMessage(params.message),
	options: params.options.map((opt) => opt.hint === void 0 ? opt : {
		...opt,
		hint: stylePromptHint(opt.hint)
	})
});
function buildScopeSelection(opts) {
	const hadExplicit = Boolean(opts.all || opts.service || opts.state || opts.workspace || opts.app);
	const scopes = /* @__PURE__ */ new Set();
	if (opts.all || opts.service) scopes.add("service");
	if (opts.all || opts.state) scopes.add("state");
	if (opts.all || opts.workspace) scopes.add("workspace");
	if (opts.all || opts.app) scopes.add("app");
	return {
		scopes,
		hadExplicit
	};
}
async function stopAndUninstallService(runtime) {
	if (isNixMode) {
		runtime.error("Nix mode detected; service uninstall is disabled.");
		return false;
	}
	const service = resolveGatewayService();
	let loaded = false;
	try {
		loaded = await service.isLoaded({ env: process.env });
	} catch (err) {
		runtime.error(`Gateway service check failed: ${String(err)}`);
		return false;
	}
	if (!loaded) {
		runtime.log(`Gateway service ${service.notLoadedText}.`);
		return true;
	}
	try {
		await service.stop({
			env: process.env,
			stdout: process.stdout
		});
	} catch (err) {
		runtime.error(`Gateway stop failed: ${String(err)}`);
	}
	try {
		await service.uninstall({
			env: process.env,
			stdout: process.stdout
		});
		return true;
	} catch (err) {
		runtime.error(`Gateway uninstall failed: ${String(err)}`);
		return false;
	}
}
async function removeMacApp(runtime, dryRun) {
	if (process.platform !== "darwin") return;
	await removePath("/Applications/CoderClaw.app", runtime, {
		dryRun,
		label: "/Applications/CoderClaw.app"
	});
}
async function uninstallCommand(runtime, opts) {
	const { scopes, hadExplicit } = buildScopeSelection(opts);
	const interactive = !opts.nonInteractive;
	if (!interactive && !opts.yes) {
		runtime.error("Non-interactive mode requires --yes.");
		runtime.exit(1);
		return;
	}
	if (!hadExplicit) {
		if (!interactive) {
			runtime.error("Non-interactive mode requires explicit scopes (use --all).");
			runtime.exit(1);
			return;
		}
		const selection = await multiselectStyled({
			message: "Uninstall which components?",
			options: [
				{
					value: "service",
					label: "Gateway service",
					hint: "launchd / systemd / schtasks"
				},
				{
					value: "state",
					label: "State + config",
					hint: "~/.coderclaw"
				},
				{
					value: "workspace",
					label: "Workspace",
					hint: "agent files"
				},
				{
					value: "app",
					label: "macOS app",
					hint: "/Applications/CoderClaw.app"
				}
			],
			initialValues: [
				"service",
				"state",
				"workspace"
			]
		});
		if (isCancel(selection)) {
			cancel(stylePromptTitle("Uninstall cancelled.") ?? "Uninstall cancelled.");
			runtime.exit(0);
			return;
		}
		for (const value of selection) scopes.add(value);
	}
	if (scopes.size === 0) {
		runtime.log("Nothing selected.");
		return;
	}
	if (interactive && !opts.yes) {
		const ok = await confirm({ message: stylePromptMessage("Proceed with uninstall?") });
		if (isCancel(ok) || !ok) {
			cancel(stylePromptTitle("Uninstall cancelled.") ?? "Uninstall cancelled.");
			runtime.exit(0);
			return;
		}
	}
	const dryRun = Boolean(opts.dryRun);
	const { stateDir, configPath, oauthDir, configInsideState, oauthInsideState, workspaceDirs } = resolveCleanupPlanFromDisk();
	if (scopes.has("service")) if (dryRun) runtime.log("[dry-run] remove gateway service");
	else await stopAndUninstallService(runtime);
	if (scopes.has("state")) {
		await removePath(stateDir, runtime, {
			dryRun,
			label: stateDir
		});
		if (!configInsideState) await removePath(configPath, runtime, {
			dryRun,
			label: configPath
		});
		if (!oauthInsideState) await removePath(oauthDir, runtime, {
			dryRun,
			label: oauthDir
		});
	}
	if (scopes.has("workspace")) for (const workspace of workspaceDirs) await removePath(workspace, runtime, {
		dryRun,
		label: workspace
	});
	if (scopes.has("app")) await removeMacApp(runtime, dryRun);
	runtime.log("CLI still installed. Remove via npm/pnpm if desired.");
	if (scopes.has("state") && !scopes.has("workspace")) {
		const home = resolveHomeDir();
		if (home && workspaceDirs.some((dir) => dir.startsWith(path.resolve(home)))) runtime.log("Tip: workspaces were preserved. Re-run with --workspace to remove them.");
	}
}

//#endregion
//#region src/cli/program/register.maintenance.ts
function registerMaintenanceCommands(program) {
	program.command("doctor").description("Health checks + quick fixes for the gateway and channels").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/doctor", "docs.coderclaw.ai/cli/doctor")}\n`).option("--no-workspace-suggestions", "Disable workspace memory system suggestions", false).option("--yes", "Accept defaults without prompting", false).option("--repair", "Apply recommended repairs without prompting", false).option("--fix", "Apply recommended repairs (alias for --repair)", false).option("--force", "Apply aggressive repairs (overwrites custom service config)", false).option("--non-interactive", "Run without prompts (safe migrations only)", false).option("--generate-gateway-token", "Generate and configure a gateway token", false).option("--deep", "Scan system services for extra gateway installs", false).action(async (opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await doctorCommand(defaultRuntime, {
				workspaceSuggestions: opts.workspaceSuggestions,
				yes: Boolean(opts.yes),
				repair: Boolean(opts.repair) || Boolean(opts.fix),
				force: Boolean(opts.force),
				nonInteractive: Boolean(opts.nonInteractive),
				generateGatewayToken: Boolean(opts.generateGatewayToken),
				deep: Boolean(opts.deep)
			});
			defaultRuntime.exit(0);
		});
	});
	program.command("dashboard").description("Open the Control UI with your current token").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/dashboard", "docs.coderclaw.ai/cli/dashboard")}\n`).option("--no-open", "Print URL but do not launch a browser", false).action(async (opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await dashboardCommand(defaultRuntime, { noOpen: Boolean(opts.noOpen) });
		});
	});
	program.command("reset").description("Reset local config/state (keeps the CLI installed)").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/reset", "docs.coderclaw.ai/cli/reset")}\n`).option("--scope <scope>", "config|config+creds+sessions|full (default: interactive prompt)").option("--yes", "Skip confirmation prompts", false).option("--non-interactive", "Disable prompts (requires --scope + --yes)", false).option("--dry-run", "Print actions without removing files", false).action(async (opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await resetCommand(defaultRuntime, {
				scope: opts.scope,
				yes: Boolean(opts.yes),
				nonInteractive: Boolean(opts.nonInteractive),
				dryRun: Boolean(opts.dryRun)
			});
		});
	});
	program.command("uninstall").description("Uninstall the gateway service + local data (CLI remains)").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/uninstall", "docs.coderclaw.ai/cli/uninstall")}\n`).option("--service", "Remove the gateway service", false).option("--state", "Remove state + config", false).option("--workspace", "Remove workspace dirs", false).option("--app", "Remove the macOS app", false).option("--all", "Remove service + state + workspace + app", false).option("--yes", "Skip confirmation prompts", false).option("--non-interactive", "Disable prompts (requires --yes)", false).option("--dry-run", "Print actions without removing files", false).action(async (opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await uninstallCommand(defaultRuntime, {
				service: Boolean(opts.service),
				state: Boolean(opts.state),
				workspace: Boolean(opts.workspace),
				app: Boolean(opts.app),
				all: Boolean(opts.all),
				yes: Boolean(opts.yes),
				nonInteractive: Boolean(opts.nonInteractive),
				dryRun: Boolean(opts.dryRun)
			});
		});
	});
	program.command("stop").description("Stop the running gateway service (launchd/systemd/schtasks)").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/gateway", "docs.coderclaw.ai/cli/gateway")}\n`).option("--json", "Output JSON", false).action(async (opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await runDaemonStop({ json: Boolean(opts.json) });
		});
	});
}

//#endregion
export { registerMaintenanceCommands };