import { g as resolveStateDir, i as isNixMode, m as resolveOAuthDir, o as resolveConfigPath, u as resolveGatewayPort } from "./paths-Ci0O5IXU.js";
import { p as theme } from "./globals-o4Hkf2nH.js";
import { _ as resolveHomeDir, x as shortenHomeInString, y as resolveUserPath } from "./utils-DXDZXfi2.js";
import "./thinking-Fqckw03T.js";
import "./reply-CHHLWXTP.js";
import { A as resolveDefaultAgentWorkspaceDir } from "./agent-scope-BUcFoOez.js";
import { d as defaultRuntime } from "./subsystem-CocLsF9M.js";
import "./core-root-D_XTmw6_.js";
import "./logger-B4_TThxB.js";
import "./exec-Bvzmovpq.js";
import { Dn as secretRefKey, an as readConfigFileSnapshot, rn as loadConfig, zt as resolveSecretRefValues } from "./model-selection-YEFtLNSF.js";
import { V as resolveSecretInputRef } from "./registry-CZfQ-snX.js";
import "./github-copilot-token-DqwKrrmK.js";
import { t as formatCliCommand } from "./command-format-BUhchepc.js";
import "./boolean-C6Pbt2Ue.js";
import "./env-D3eA4r2n.js";
import "./manifest-registry-CqRtX07d.js";
import "./dock-B9SrGH_K.js";
import "./message-channel-B7if8_Ss.js";
import "./send-D4IPI7DA.js";
import "./plugins-DPuCvyAr.js";
import "./sessions-CxtmRBrc.js";
import "./audio-transcription-runner-BmYM79ae.js";
import "./image-C5KyeETN.js";
import "./models-config-B8Hasdzn.js";
import "./pi-embedded-helpers-M3RkS711.js";
import "./sandbox-C1_DWCsa.js";
import "./tool-catalog-7XRC3klR.js";
import "./chrome-BBVmc3Se.js";
import "./tailscale-BxdRBeK_.js";
import "./tailnet-DONkFGUG.js";
import "./ws-DQm2qOSB.js";
import "./auth-BfvQ8QYP.js";
import "./server-context-Ba0Dvxyt.js";
import "./frontmatter-wvk5Gwyc.js";
import "./skills-BgSP_JFk.js";
import "./path-alias-guards-Cjml85oF.js";
import "./paths-CI0-x9aa.js";
import "./redact-Nl4LWTUL.js";
import "./errors-D2aogITB.js";
import "./fs-safe-4KkU2jy0.js";
import "./proxy-env-QR3xvEvF.js";
import "./image-ops-BMK3YDnH.js";
import "./store-wnkoDS0q.js";
import "./ports-BJ314ngw.js";
import "./trash-C57Djqhz.js";
import "./server-middleware-Db5VJPvz.js";
import "./accounts--YCaC3h2.js";
import "./accounts-DIXxXacs.js";
import "./logging-w5jq5901.js";
import "./accounts-Cy5Z48cS.js";
import "./send-BftGPeDi.js";
import "./paths-DyjDYWsu.js";
import "./chat-envelope-DjXKeY_Z.js";
import "./tool-images-BdgJAeDm.js";
import "./tool-display-DtW9AC9y.js";
import "./fetch-guard-BXj181Wi.js";
import "./api-key-rotation-kSZ_8x6S.js";
import "./local-roots-lI8oP7YT.js";
import "./model-catalog-CrylEG4v.js";
import "./proxy-fetch-1Erku4sd.js";
import "./tokens-CQyDX0_9.js";
import "./deliver-CjvogG-h.js";
import "./commands-CjCZ7VFi.js";
import "./commands-registry-Bjrh-xTL.js";
import "./client-DoEmtGyQ.js";
import "./call-CGx2d27E.js";
import "./pairing-token-BbiCPOiP.js";
import "./with-timeout-Z1s9Diet.js";
import "./diagnostic-dPBPmwAh.js";
import "./send-NUo-HdLp.js";
import "./pi-model-discovery-BYAKdd2d.js";
import "./exec-approvals-allowlist-DC_4Tf0s.js";
import "./exec-safe-bin-runtime-policy-bh7vljJv.js";
import "./ir-BjgRIHDw.js";
import "./render-CUAKPmvZ.js";
import "./target-errors-CbVI6ds_.js";
import "./channel-selection-aHawixyC.js";
import "./plugin-auto-enable-DRWWaZkx.js";
import "./send-DAtCjd-s.js";
import "./outbound-attachment-C2bCVbHg.js";
import "./fetch-MguOSqpo.js";
import "./delivery-queue-BEhfSqnG.js";
import "./send-eLzaCOuF.js";
import "./pairing-store-CbJHk_de.js";
import "./read-only-account-inspect-Qmimgb8a.js";
import "./channel-activity-Cx5Unx4s.js";
import "./tables-BhHaE0Wa.js";
import "./proxy-j8BltAEx.js";
import "./timeouts-BNjB4b5v.js";
import "./skill-commands-BZahRPvp.js";
import "./workspace-dirs-BU0q6mL7.js";
import "./runtime-config-collectors-CW2xlUjz.js";
import "./command-secret-targets-B0--_778.js";
import "./session-cost-usage-qv_Px0s6.js";
import { _ as resolveControlUiLinks, f as openUrl, i as detectBrowserOpenSupport, o as formatControlUiSshHint } from "./onboard-helpers-CgBGHcnn.js";
import { n as stylePromptMessage, r as stylePromptTitle, t as stylePromptHint } from "./prompt-style-C3CFmIhm.js";
import "./pairing-labels-DgY7LhGG.js";
import "./memory-cli-DnOu7SX5.js";
import "./manager-DPAW8PRF.js";
import "./query-expansion-D5WNngl2.js";
import { t as formatDocsLink } from "./links-DRjWcKgy.js";
import { n as runCommandWithRuntime } from "./cli-utils-CuyGL3rq.js";
import "./help-format-BuSfnjUn.js";
import "./progress-CSvLovC9.js";
import "./exec-approvals-C8Ra1A3C.js";
import "./nodes-screen-CWe-prHK.js";
import "./system-run-command-DopVO6dk.js";
import "./server-lifecycle-ChsLH-5K.js";
import "./stagger-F4n43mMH.js";
import "./runtime-guard-DRPIdCHk.js";
import "./program-context-DzWr37kA.js";
import "./skills-status-DIRU8plG.js";
import { t as copyToClipboard } from "./clipboard-isJYshqH.js";
import "./note-BxgUVS4k.js";
import "./issue-format-B5EOFmBa.js";
import "./channels-status-issues-D1CmgD0J.js";
import "./completion-cli-BfbVdas-.js";
import "./daemon-install-helpers-BaAKOoka.js";
import "./gateway-install-token-Con7-XZK.js";
import "./systemd-Coag6AD6.js";
import { t as resolveGatewayService } from "./service-BuILYYFR.js";
import "./systemd-hints-CcVW-pl9.js";
import "./diagnostics-Dj8I6sv_.js";
import "./health-B8CcGS1a.js";
import "./control-ui-assets-C-kGFLbW.js";
import "./channel-account-context-DMN4F0HY.js";
import "./update-runner-GSKG7w_C.js";
import "./logging-DUBdyhZC.js";
import "./oauth-tls-preflight-BPApzpql.js";
import "./doctor-config-flow-SpvMiSkP.js";
import "./systemd-linger-DIcLDkk6.js";
import "./health-format-DxMIKtVr.js";
import { n as doctorCommand, t as selectStyled } from "./prompt-select-styled-_D4igwUE.js";
import "./doctor-completion-Cu6sbF0T.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
function readGatewayTokenEnv(env) {
	const primary = env.GENSPARX_GATEWAY_TOKEN?.trim();
	if (primary) return primary;
	return env.CLAWDBOT_GATEWAY_TOKEN?.trim() || void 0;
}
async function resolveDashboardToken(cfg, env = process.env) {
	const { ref } = resolveSecretInputRef({
		value: cfg.gateway?.auth?.token,
		defaults: cfg.secrets?.defaults
	});
	const configToken = ref || typeof cfg.gateway?.auth?.token !== "string" ? void 0 : cfg.gateway.auth.token.trim() || void 0;
	if (configToken) return {
		token: configToken,
		source: "config",
		tokenSecretRefConfigured: false
	};
	if (!ref) {
		const envToken = readGatewayTokenEnv(env);
		return envToken ? {
			token: envToken,
			source: "env",
			tokenSecretRefConfigured: false
		} : { tokenSecretRefConfigured: false };
	}
	const refLabel = `${ref.source}:${ref.provider}:${ref.id}`;
	try {
		const value = (await resolveSecretRefValues([ref], {
			config: cfg,
			env
		})).get(secretRefKey(ref));
		if (typeof value === "string" && value.trim().length > 0) return {
			token: value.trim(),
			source: "secretRef",
			tokenSecretRefConfigured: true
		};
		const envToken = readGatewayTokenEnv(env);
		return envToken ? {
			token: envToken,
			source: "env",
			tokenSecretRefConfigured: true
		} : {
			unresolvedRefReason: `gateway.auth.token SecretRef is unresolved (${refLabel}).`,
			tokenSecretRefConfigured: true
		};
	} catch {
		const envToken = readGatewayTokenEnv(env);
		return envToken ? {
			token: envToken,
			source: "env",
			tokenSecretRefConfigured: true
		} : {
			unresolvedRefReason: `gateway.auth.token SecretRef is unresolved (${refLabel}).`,
			tokenSecretRefConfigured: true
		};
	}
}
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 resolvedToken = await resolveDashboardToken(cfg, process.env);
	const token = resolvedToken.token ?? "";
	const links = resolveControlUiLinks({
		port,
		bind: bind === "lan" ? "loopback" : bind,
		customBindHost,
		basePath
	});
	const includeTokenInUrl = token.length > 0 && !resolvedToken.tokenSecretRefConfigured;
	const dashboardUrl = includeTokenInUrl ? `${links.httpUrl}#token=${encodeURIComponent(token)}` : links.httpUrl;
	runtime.log(`Dashboard URL: ${dashboardUrl}`);
	if (resolvedToken.tokenSecretRefConfigured && token) runtime.log("Token auto-auth is disabled for SecretRef-managed gateway.auth.token; use your external token source if prompted.");
	if (resolvedToken.unresolvedRefReason) {
		runtime.log(`Token auto-auth unavailable: ${resolvedToken.unresolvedRefReason}`);
		runtime.log("Set GENSPARX_GATEWAY_TOKEN in this shell or resolve your secret provider, then rerun `gensparx dashboard`.");
	}
	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: includeTokenInUrl ? token || void 0 : 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 Gensparx.");
	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 removeStateAndLinkedPaths(cleanup, runtime, opts) {
	await removePath(cleanup.stateDir, runtime, {
		dryRun: opts?.dryRun,
		label: cleanup.stateDir
	});
	if (!cleanup.configInsideState) await removePath(cleanup.configPath, runtime, {
		dryRun: opts?.dryRun,
		label: cleanup.configPath
	});
	if (!cleanup.oauthInsideState) await removePath(cleanup.oauthDir, runtime, {
		dryRun: opts?.dryRun,
		label: cleanup.oauthDir
	});
}
async function removeWorkspaceDirs(workspaceDirs, runtime, opts) {
	for (const workspace of workspaceDirs) await removePath(workspace, runtime, {
		dryRun: opts?.dryRun,
		label: workspace
	});
}
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: "gensparx.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("gensparx onboard --install-daemon")}`);
		return;
	}
	if (scope === "full") {
		await removeStateAndLinkedPaths({
			stateDir,
			configPath,
			oauthDir,
			configInsideState,
			oauthInsideState
		}, runtime, { dryRun });
		await removeWorkspaceDirs(workspaceDirs, runtime, { dryRun });
		runtime.log(`Next: ${formatCliCommand("gensparx 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/Gensparx.app", runtime, {
		dryRun,
		label: "/Applications/Gensparx.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: "~/.gensparx"
				},
				{
					value: "workspace",
					label: "Workspace",
					hint: "agent files"
				},
				{
					value: "app",
					label: "macOS app",
					hint: "/Applications/Gensparx.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.gensparx.com/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.gensparx.com/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.gensparx.com/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.gensparx.com/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 };