import { Cu as formatCliCommand, Qt as readConfigFileSnapshot, Xt as loadConfig, _n as parseDurationMs, hd as runExec } from "./env-Dlz8aQHP.js";
import { H as theme, y as resolveHomeDir } from "./agent-paths-DUHGyU1s.js";
import "./send-Ditv1VfR.js";
import "./send-CWM2yWF6.js";
import { Ba as normalizePublicHost, E as resolveControlUiLinks, F as removeWorkspaceDirs, La as CONTROL_UI_LOGIN_DEFAULT_GRANT_TTL_MS, M as listAgentSessionDirs, N as removePath, P as removeStateAndLinkedPaths, S as openUrl, So as getTailnetHostname, Ua as resolveControlUiBootCheck, Wa as normalizeControlUiBasePath, g as formatControlUiSshHint, j as buildCleanupPlan, m as detectBrowserOpenSupport, za as createLoginGrant } from "./model-catalog-B2mRe6cZ.js";
import "./github-copilot-token-A9DiaCB0.js";
import { A as defaultRuntime, Ct as resolveStateDir, ft as resolveConfigPath, gt as resolveGatewayPort, ut as isNixMode, xt as resolveOAuthDir } from "./entry.js";
import "./reply-prefix-CCp0C8w4.js";
import "./memory-BpNgGSAl.js";
import "./memory-search-Bm46LIUQ.js";
import "./manager-DTf-5dRo.js";
import "./fetch-guard-DkRm4Ip1.js";
import "./ip-CLwwPh25.js";
import "./ssrf-CqV2hisj.js";
import "./query-expansion-CfOgA1KD.js";
import "./memory-cli-B7kMyaVL.js";
import "./ir-r4mczNAR.js";
import "./target-errors-CWVZTpXS.js";
import "./chunk-D9NQZPPD.js";
import "./markdown-tables-ylpJUTGZ.js";
import "./path-alias-guards-BerTsE5c.js";
import "./fs-safe-BrR3_fH1.js";
import "./render-BDQg502o.js";
import "./commands-registry-DQLLJg_T.js";
import "./diagnostic-BGFH8MIa.js";
import "./diagnostic-session-state-HO94DMou.js";
import "./send-C4oPrvgH.js";
import "./model-bpjlPTsB.js";
import "./pi-model-discovery-Do4Oa02J.js";
import "./dangerous-tools-CusV9bcr.js";
import "./chrome-CUkBgrOC.js";
import "./pairing-token-C2iKEhFc.js";
import "./ws-DiFJ3zRB.js";
import "./onboarding.wallet-CcoV0W6U.js";
import "./wallet-runtime-config-TjiNNY9x.js";
import "./wallet-provider-registry-CFNtQ2ZR.js";
import "./wallet-W8qsxi6H.js";
import "./wallet-approval-auth-BaVTLG5r.js";
import "./runtime-DXHXAPJA.js";
import "./device-identity-ZHUQ6a8N.js";
import "./solana-bond-signing-D9-GtRIf.js";
import "./federation-8sW60I4p.js";
import { n as callGateway } from "./call-CjHZhgQk.js";
import "./send-Dlj2DghK.js";
import "./outbound-attachment-D2ImFzcm.js";
import "./fetch-BqA-KBI4.js";
import "./delivery-queue-CMGPhIoF.js";
import "./deps-4rCQ5SBd.js";
import "./frontmatter-DTw-J9er.js";
import "./skills-CzDvK09q.js";
import "./skills-remote-CM9uNuu4.js";
import "./dangerous-name-matching-ob0tR02Y.js";
import "./channel-selection-BSwWHrf5.js";
import "./session-cost-usage-Dzc2RiRn.js";
import "./trash--uInT2PE.js";
import "./paths-rsh1tVGc.js";
import "./exec-approvals-aJApzFwx.js";
import "./node-shell-CpYc0oKF.js";
import "./task-planner-CkWt6WhX.js";
import "./send-CekwB5g1.js";
import "./resolve-route-y4Ol4Qmc.js";
import "./pairing-store-qjH5R_BQ.js";
import "./skills-clawhub-CBB2AUv6.js";
import "./exec-approvals-allowlist-BZoClZ91.js";
import "./skill-commands-Cx0nCzUv.js";
import "./channel-activity-DrrSLe52.js";
import "./tables-8heM_uJo.js";
import "./proxy-mdETjik4.js";
import "./config-DfviqDy5.js";
import { t as formatDocsLink } from "./links-CPltkiov.js";
import { n as runCommandWithRuntime } from "./cli-utils-XevKf-tr.js";
import "./help-format-D7mxVfC9.js";
import "./progress-BhMUiH4f.js";
import "./replies-BFsEK9FQ.js";
import { a as stylePromptTitle, i as stylePromptMessage, r as stylePromptHint } from "./prompt-style-CWdNyu_Q.js";
import "./pairing-labels-DBt_OA8C.js";
import "./skills-status-Br9ZUEnO.js";
import { t as copyToClipboard } from "./clipboard-iThpANIo.js";
import "./completion-cli-CKzB1lB1.js";
import "./register.subclis-Bj8pFyAT.js";
import "./command-registry-fqlYdOTI.js";
import "./program-context-CDFrVtWb.js";
import "./managed-up-DhYefvn4.js";
import "./daemon-install-helpers-CzpeF_Bc.js";
import "./systemd-7bMkfZjg.js";
import { t as resolveGatewayService } from "./service-CnO5S7Pz.js";
import "./service-audit-B92T2Wk3.js";
import "./diagnostics-6nlk67JR.js";
import { o as probeHostedDashboardBrowserPath } from "./health-C_g99tp_.js";
import "./heartbeat-runner-D04n14H-.js";
import "./update-check-YNg-n29D.js";
import "./logging-B1pB3RkW.js";
import "./installs-PYgg3AvN.js";
import "./channels-status-issues-BiWUewGU.js";
import "./update-runner-BnRMhKva.js";
import "./note-_SCwut0b.js";
import "./doctor-config-flow-Vb1Ywbek.js";
import "./systemd-linger-CAPmfIid.js";
import "./health-format-CFeARHgA.js";
import { n as doctorCommand, t as selectStyled } from "./prompt-select-styled-C5o0Ff06.js";
import path from "node:path";
import fs from "node:fs";
import { cancel, confirm, isCancel, multiselect } from "@clack/prompts";

//#region src/commands/dashboard-link.ts
const AGENT_DOMAIN_SUFFIX = ".agents.fased.app";
function readStateGatewayToken(env = process.env) {
	try {
		const filePath = path.join(resolveStateDir(env), "gateway-secret");
		if (!fs.existsSync(filePath)) return "";
		return fs.readFileSync(filePath, "utf8").trim();
	} catch {
		return "";
	}
}
function collectGatewayTokenCandidates(snapshot, options) {
	const out = [];
	const optionToken = options.token?.trim() || "";
	if (optionToken) out.push({
		source: "option",
		token: optionToken
	});
	const envToken = process.env.FASED_GATEWAY_TOKEN?.trim() || "";
	if (envToken) out.push({
		source: "env",
		token: envToken
	});
	const stateToken = readStateGatewayToken(process.env);
	if (stateToken) out.push({
		source: "state-file",
		token: stateToken
	});
	if (snapshot.valid) {
		const configuredToken = snapshot.config?.gateway?.auth?.token?.trim();
		if (configuredToken) out.push({
			source: "config",
			token: configuredToken
		});
	}
	return out;
}
function resolveGatewayToken(snapshot, options) {
	const optionToken = options.token?.trim() || "";
	if (optionToken) return {
		token: optionToken,
		source: "option"
	};
	const candidates = collectGatewayTokenCandidates(snapshot, options);
	const distinct = /* @__PURE__ */ new Map();
	for (const candidate of candidates) {
		const list = distinct.get(candidate.token) ?? [];
		list.push(candidate.source);
		distinct.set(candidate.token, list);
	}
	if (distinct.size > 1) {
		const parts = candidates.map((candidate) => `${candidate.source}=set`).join(", ");
		throw new Error(`gateway token mismatch across sources (${parts}); align --token / FASED_GATEWAY_TOKEN / ~/.fased/gateway-secret / gateway.auth.token`);
	}
	if (candidates.length === 0) return {
		token: "",
		source: "config"
	};
	return {
		token: candidates[0].token,
		source: candidates[0].source
	};
}
async function dashboardLinkCommand(runtime = defaultRuntime, options) {
	const rawPublicUrl = options.publicUrl?.trim() || "";
	if (!rawPublicUrl) throw new Error("missing required --public-url");
	let parsed;
	try {
		parsed = new URL(rawPublicUrl);
	} catch {
		throw new Error("invalid --public-url");
	}
	if (parsed.protocol !== "https:") throw new Error("public URL must use https://");
	const host = normalizePublicHost(parsed.host);
	if (!host) throw new Error("public URL host is invalid");
	if (!options.allowCustomHost && !host.endsWith(AGENT_DOMAIN_SUFFIX)) throw new Error("public URL host must be under *.agents.fased.app (use --allow-custom-host to override)");
	const resolvedToken = resolveGatewayToken(await readConfigFileSnapshot(), options);
	const gatewayToken = resolvedToken.token;
	if (!gatewayToken) throw new Error("gateway token not configured (set --token, FASED_GATEWAY_TOKEN, ~/.fased/gateway-secret, or gateway.auth.token)");
	const ttlMs = options.ttl ? parseDurationMs(options.ttl, { defaultUnit: "m" }) : CONTROL_UI_LOGIN_DEFAULT_GRANT_TTL_MS;
	if (ttlMs <= 0) throw new Error("ttl must be greater than 0");
	const grant = createLoginGrant({
		gatewayToken,
		host,
		ttlMs
	});
	const finalUrl = new URL(parsed.toString());
	const hashParams = new URLSearchParams();
	hashParams.set("login", grant);
	if (options.onboarding) hashParams.set("onboarding", "1");
	finalUrl.hash = hashParams.toString();
	runtime.log(`Dashboard login URL: ${finalUrl.toString()}`);
	runtime.log(`Grant TTL: ${Math.ceil(ttlMs / 1e3)}s`);
	runtime.log(`Gateway token source: ${resolvedToken.source}`);
	runtime.log("This link is one-time use. If leaked, revoke by rotating gateway token.");
}

//#endregion
//#region src/commands/dashboard.ts
const LOCAL_DASHBOARD_GATEWAY_TIMEOUT_MS = 3e4;
const HOSTED_DASHBOARD_GATEWAY_TIMEOUT_MS = 12e4;
const HOSTED_DASHBOARD_BROWSER_TIMEOUT_MS = 12e4;
function buildDashboardUrl(params) {
	const url = new URL(params.httpUrl);
	const hashParams = new URLSearchParams();
	const token = params.token?.trim();
	if (token) hashParams.set("token", token);
	const hash = hashParams.toString();
	url.hash = hash ? `#${hash}` : "";
	return url.toString();
}
async function resolveHostedDashboardHttpUrl(params) {
	if (!params.tailscaleMode || params.tailscaleMode === "off") return null;
	const dns = await getTailnetHostname((cmd, args) => runExec(cmd, args, {
		timeoutMs: 1200,
		maxBuffer: 2e5
	})).catch(() => null);
	if (!dns) return null;
	const basePath = normalizeControlUiBasePath(params.basePath);
	return `https://${dns}${basePath ? `${basePath}/` : "/"}`;
}
async function probeDashboardGateway(cfg, timeoutMs = 5e3) {
	try {
		const summary = await callGateway({
			method: "health",
			timeoutMs,
			config: cfg
		});
		return {
			ok: true,
			durationMs: typeof summary.durationMs === "number" ? summary.durationMs : null
		};
	} catch (err) {
		const message = err instanceof Error ? err.message : String(err);
		return {
			ok: false,
			message: message.split("\n")[0] ?? message
		};
	}
}
function isHostedDashboardUrl(httpUrl, localHttpUrl) {
	try {
		const hosted = new URL(httpUrl);
		const local = new URL(localHttpUrl);
		return hosted.origin !== local.origin && hosted.protocol === "https:";
	} catch {
		return false;
	}
}
function isGatewayWarmupTimeout(message) {
	return /gateway timeout|operation was aborted|aborted due to timeout/i.test(message);
}
function buildDashboardWsUrl(httpUrl) {
	try {
		const url = new URL(httpUrl);
		url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
		url.search = "";
		url.hash = "";
		return url.toString();
	} catch {
		return null;
	}
}
function formatBootAssetLine(label, asset) {
	if (!asset) return `Dashboard ${label}: not referenced`;
	const status = typeof asset.status === "number" ? String(asset.status) : "fetch failed";
	const contentType = asset.contentType?.trim() || "missing content-type";
	const suffix = asset.ok ? "" : ` (${asset.message ?? "failed"})`;
	return `Dashboard ${label}: ${asset.url} [${status}, ${contentType}]${suffix}`;
}
function logHostedDashboardBootCheck(runtime, bootCheck) {
	const indexStatus = typeof bootCheck.indexResponse.status === "number" ? String(bootCheck.indexResponse.status) : "fetch failed";
	const indexType = bootCheck.indexResponse.contentType?.trim() || "missing content-type";
	const indexSuffix = bootCheck.indexResponse.ok ? "" : ` (${bootCheck.indexResponse.message ?? "failed"})`;
	runtime.log(`Dashboard boot check: ${bootCheck.index} via ${bootCheck.serve}`);
	runtime.log(`Dashboard index: ${bootCheck.indexResponse.url} [${indexStatus}, ${indexType}]${indexSuffix}`);
	runtime.log(formatBootAssetLine("entry JS", bootCheck.entryJs));
	runtime.log(formatBootAssetLine("app JS", bootCheck.appJs));
}
function resolveLocalDashboardBootCheck(params) {
	const origin = (() => {
		try {
			return new URL(params.httpUrl).origin;
		} catch {
			return "http://localhost";
		}
	})();
	return resolveControlUiBootCheck({
		basePath: params.basePath,
		origin,
		serve: "direct"
	});
}
function logLocalDashboardBootCheck(runtime, bootCheck) {
	const indexStatus = typeof bootCheck.indexResponse.status === "number" ? String(bootCheck.indexResponse.status) : "fetch failed";
	const indexType = bootCheck.indexResponse.contentType?.trim() || "missing content-type";
	const indexSuffix = bootCheck.indexResponse.ok ? "" : ` (${bootCheck.indexResponse.message ?? "failed"})`;
	runtime.log(`Dashboard boot check: ${bootCheck.index} via ${bootCheck.serve}`);
	runtime.log(`Dashboard index: ${bootCheck.indexResponse.url} [${indexStatus}, ${indexType}]${indexSuffix}`);
	runtime.log(formatBootAssetLine("entry JS", bootCheck.entryJs));
	runtime.log(formatBootAssetLine("app JS", bootCheck.appJs));
}
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.FASED_GATEWAY_TOKEN ?? "";
	const links = resolveControlUiLinks({
		port,
		bind: bind === "lan" ? "loopback" : bind,
		customBindHost,
		basePath
	});
	const hostedHttpUrl = await resolveHostedDashboardHttpUrl({
		tailscaleMode: cfg.gateway?.tailscale?.mode ?? "off",
		basePath
	}) ?? links.httpUrl;
	const hostedDashboard = isHostedDashboardUrl(hostedHttpUrl, links.httpUrl);
	const dashboardUrl = buildDashboardUrl({
		httpUrl: hostedHttpUrl,
		token
	});
	const gatewayProbe = await probeDashboardGateway(cfg, hostedDashboard ? HOSTED_DASHBOARD_GATEWAY_TIMEOUT_MS : LOCAL_DASHBOARD_GATEWAY_TIMEOUT_MS);
	if (gatewayProbe.ok) {
		const suffix = gatewayProbe.durationMs != null ? ` (${Math.max(0, Math.round(gatewayProbe.durationMs))}ms)` : "";
		runtime.log(`Gateway: online${suffix}`);
	} else {
		const warming = hostedDashboard && isGatewayWarmupTimeout(gatewayProbe.message);
		runtime.log(`Gateway: ${warming ? "warming" : "offline"} (${gatewayProbe.message})`);
		runtime.log(warming ? "Hosted Gateway is still warming after restart; retry dashboard after it settles." : "The dashboard page may load, but it will stay offline until the Gateway is healthy.");
		runtime.log("Run: fased health");
	}
	if (hostedDashboard) if (!gatewayProbe.ok) {
		const warming = isGatewayWarmupTimeout(gatewayProbe.message);
		runtime.log(`Dashboard browser path: not checked via Tailscale (gateway ${warming ? "warming" : "offline"})`);
		const wsUrl = buildDashboardWsUrl(hostedHttpUrl);
		if (wsUrl) runtime.log(`Dashboard websocket: ${wsUrl}`);
	} else if (token.trim()) {
		const hostedProbe = await probeHostedDashboardBrowserPath({
			httpUrl: hostedHttpUrl,
			token,
			timeoutMs: HOSTED_DASHBOARD_BROWSER_TIMEOUT_MS
		});
		if (hostedProbe.ok) {
			runtime.log(`Dashboard browser path: online via Tailscale (${Math.max(0, Math.round(hostedProbe.durationMs))}ms)`);
			if (options.noOpen) logHostedDashboardBootCheck(runtime, hostedProbe.bootCheck);
		} else {
			runtime.log(`Dashboard browser path: offline via Tailscale (${hostedProbe.stage}: ${hostedProbe.message})`);
			if (hostedProbe.bootCheck) logHostedDashboardBootCheck(runtime, hostedProbe.bootCheck);
			if (hostedProbe.wsUrl) runtime.log(`Dashboard websocket: ${hostedProbe.wsUrl}`);
		}
	} else runtime.log("Dashboard browser path: not checked (missing gateway token)");
	else if (options.noOpen) {
		logLocalDashboardBootCheck(runtime, resolveLocalDashboardBootCheck({
			httpUrl: links.httpUrl,
			basePath
		}));
		runtime.log(`Dashboard websocket: ${links.wsUrl}`);
	}
	runtime.log(`Dashboard URL: ${dashboardUrl}`);
	if (!options.noOpen) {
		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 Fased Agent.");
	else if (hint) runtime.log(hint);
}

//#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: "fased.json; preserves wallets and Tailscale access"
				},
				{
					value: "config+creds+sessions",
					label: "Config + credentials + sessions",
					hint: "preserves wallets, workspace, and Tailscale access"
				},
				{
					value: "full",
					label: "Full reset",
					hint: "state dir + workspace, but preserves wallet material"
				}
			],
			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? Wallet material and Tailscale device access are preserved.`) });
		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("fased onboard --install-daemon")}`);
		return;
	}
	if (scope === "full") {
		await removeStateAndLinkedPaths({
			stateDir,
			configPath,
			oauthDir,
			configInsideState,
			oauthInsideState
		}, runtime, {
			dryRun,
			preserveWalletDir: true
		});
		await removeWorkspaceDirs(workspaceDirs, runtime, { dryRun });
		runtime.log(`Next: ${formatCliCommand("fased 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/FasedAgent.app", runtime, {
		dryRun,
		label: "/Applications/FasedAgent.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: "~/.fased"
				},
				{
					value: "workspace",
					label: "Workspace",
					hint: "agent files"
				},
				{
					value: "app",
					label: "macOS app",
					hint: "/Applications/FasedAgent.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 removeStateAndLinkedPaths({
		stateDir,
		configPath,
		oauthDir,
		configInsideState,
		oauthInsideState
	}, runtime, { dryRun });
	if (scopes.has("workspace")) await removeWorkspaceDirs(workspaceDirs, runtime, { dryRun });
	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.fased.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-link").description("Generate a one-time public Control UI login link").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/web/public-ui-login", "docs.fased.ai/web/public-ui-login")}\n`).requiredOption("--public-url <url>", "Public Control UI URL (https://<slug>.agents.fased.app)").option("--token <token>", "Gateway token override for grant signing").option("--ttl <duration>", "Grant TTL (e.g. 10m, 1h)", "10m").option("--onboarding", "Append onboarding=1 in link hash", false).option("--allow-custom-host", "Allow non-*.agents.fased.app host", false).action(async (opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await dashboardLinkCommand(defaultRuntime, {
				publicUrl: String(opts.publicUrl ?? ""),
				token: String(opts.token ?? ""),
				ttl: String(opts.ttl ?? ""),
				onboarding: Boolean(opts.onboarding),
				allowCustomHost: Boolean(opts.allowCustomHost)
			});
		});
	});
	program.command("dashboard").description("Open the Control UI with your current token").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/dashboard", "docs.fased.ai/cli/dashboard")}\n`).option("--no-open", "Print URL but do not launch a browser").action(async (opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await dashboardCommand(defaultRuntime, { noOpen: opts.open === false });
		});
	});
	program.command("reset").description("Reset local config/state (keeps the CLI installed)").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/reset", "docs.fased.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.fased.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)
			});
		});
	});
}

//#endregion
export { registerMaintenanceCommands };