import { $t as getVerboseFlag, Qt as getPrimaryCommand, Xt as getFlagValue, Yt as getCommandPath, Zt as getPositiveIntFlagValue, _ as defaultRuntime, c as enableConsoleCapture, en as hasFlag, i as normalizeEnv, n as isTruthyEnvValue, qt as normalizeWindowsArgv, tn as hasHelpOrVersion } from "./entry.js";
import "./auth-profiles-D11Xw15i.js";
import "./exec-CzwIUObA.js";
import "./agent-scope-C-Jte08L.js";
import "./model-selection-CMx1evaF.js";
import "./file-lock-DrmXX3vL.js";
import "./agent-paths-DryQawbH.js";
import "./pi-auth-json-mn8xSJKs.js";
import "./model-B4Btg-Q6.js";
import "./pi-model-discovery-EgBaDO8n.js";
import "./frontmatter-PrEWR41G.js";
import "./skills-cLBEdkqu.js";
import "./manifest-registry-CVLmi8rz.js";
import { F as loadDotEnv, N as VERSION } from "./config-D7TcU4qN.js";
import "./shell-env-CTYaxUs_.js";
import "./client-BOd5o3Kp.js";
import "./call-DTshgdlW.js";
import "./message-channel-DXToSaWK.js";
import "./pairing-token-B-OTYROz.js";
import { Wt as installUnhandledRejectionHandler } from "./subagent-registry-CVhLz4p3.js";
import "./sessions-Dn6VXn4p.js";
import "./plugins-BsEhWvLn.js";
import "./send-Dq252-bi.js";
import "./with-timeout-B9GM8DPj.js";
import "./deliver-DIK2emIV.js";
import "./diagnostic-IdKKvrDQ.js";
import "./diagnostic-session-state-CIjIGxEE.js";
import "./pi-embedded-helpers-BQjRftRI.js";
import "./sandbox-DjKcZavm.js";
import "./chrome-D1eO2jfe.js";
import "./tailscale-FeJ1M0mP.js";
import "./auth-pHRwjgkx.js";
import "./server-context-DrAh6Cgw.js";
import "./routes-wLkmjLj9.js";
import "./redact-Dj3r1_tS.js";
import { r as formatUncaughtError } from "./errors-BmdGLmRC.js";
import "./fs-safe-D0xrTzGw.js";
import "./paths-8yCI1Car.js";
import "./ssrf-BZFvPKEu.js";
import "./image-ops-FPBHTBd0.js";
import "./ports-uA7P2qIK.js";
import "./trash-Bx4LIudf.js";
import "./dock-DZ6SgvTh.js";
import "./paths-DtiEyjsC.js";
import "./thinking-BZDIJMl_.js";
import "./model-auth-Byr7Gic_.js";
import "./github-copilot-token-B5y4__YM.js";
import "./models-config-CiR_RUxw.js";
import "./reply-prefix-DV3KhOhL.js";
import "./memory-C02Znuee.js";
import "./manager-DH00nlW8.js";
import "./sqlite-9jF_eajd.js";
import "./chunk-B2lBXhR0.js";
import "./markdown-tables-BEdkErjm.js";
import "./fetch-guard-3_W2W6u_.js";
import "./local-roots-Bm30yHHs.js";
import "./commands-BiW8npr7.js";
import "./commands-registry-D8LQ9fss.js";
import "./tool-display-DxbOx1Kx.js";
import "./tokens-CC6jvm1-.js";
import "./skills-remote-DSGpkPJE.js";
import "./redact-identifier-BOxAUdff.js";
import "./workspace-dirs-wlRR65M3.js";
import "./model-catalog-CzKsiNZA.js";
import "./session-utils-Zpe3t68b.js";
import "./skill-commands-BXP2zJNy.js";
import "./pairing-store-C4KBIVqJ.js";
import "./exec-approvals-DEjIocmZ.js";
import "./nodes-screen-_JvT4DjZ.js";
import "./session-cost-usage-CJWHHY-C.js";
import "./breakdown-Cszrv-Lf.js";
import "./control-service-CG6l_Yap.js";
import "./stagger-DUVGiPYV.js";
import "./channel-selection-CmU8iVio.js";
import "./delivery-queue-B2oigbh4.js";
import "./bindings-BRZBH7eX.js";
import "./resolve-route-BVJ4-d9c.js";
import "./links-Dnmd-RS-.js";
import "./cli-utils-DXfA5936.js";
import "./help-format-Dbp8yEhl.js";
import "./progress-CI19Xh3z.js";
import "./memory-cli-083UJtVJ.js";
import "./logging-UO6tk8Em.js";
import "./replies-CLREUzzB.js";
import "./pi-tools.policy-06k__URR.js";
import "./catalog-BQgWCFTH.js";
import "./prompt-style-CZGg35Py.js";
import "./note-BIAQpZxi.js";
import "./plugin-auto-enable-DaR6Z6BC.js";
import { t as ensurePluginRegistryLoaded } from "./plugin-registry-B74FBx4U.js";
import { t as assertSupportedRuntime } from "./runtime-guard-LRRZ73eX.js";
import { t as ensureSymiCliOnPath } from "./path-env-SUrcTSJ-.js";
import { t as emitCliBanner } from "./banner-B_P_FrmA.js";
import "./doctor-config-flow-BIBJeoRl.js";
import { n as ensureConfigReady } from "./config-guard-CCLLHbZ3.js";
import process$1 from "node:process";
import { fileURLToPath } from "node:url";

//#region src/cli/program/routes.ts
const routeHealth = {
	match: (path) => path[0] === "health",
	loadPlugins: true,
	run: async (argv) => {
		const json = hasFlag(argv, "--json");
		const verbose = getVerboseFlag(argv, { includeDebug: true });
		const timeoutMs = getPositiveIntFlagValue(argv, "--timeout");
		if (timeoutMs === null) return false;
		const { healthCommand } = await import("./health-Dkwuq8ta.js").then((n) => n.i);
		await healthCommand({
			json,
			timeoutMs,
			verbose
		}, defaultRuntime);
		return true;
	}
};
const routeStatus = {
	match: (path) => path[0] === "status",
	loadPlugins: true,
	run: async (argv) => {
		const json = hasFlag(argv, "--json");
		const deep = hasFlag(argv, "--deep");
		const all = hasFlag(argv, "--all");
		const usage = hasFlag(argv, "--usage");
		const verbose = getVerboseFlag(argv, { includeDebug: true });
		const timeoutMs = getPositiveIntFlagValue(argv, "--timeout");
		if (timeoutMs === null) return false;
		const { statusCommand } = await import("./status-BEZotN01.js").then((n) => n.t);
		await statusCommand({
			json,
			deep,
			all,
			usage,
			timeoutMs,
			verbose
		}, defaultRuntime);
		return true;
	}
};
const routeSessions = {
	match: (path) => path[0] === "sessions",
	run: async (argv) => {
		const json = hasFlag(argv, "--json");
		const store = getFlagValue(argv, "--store");
		if (store === null) return false;
		const active = getFlagValue(argv, "--active");
		if (active === null) return false;
		const { sessionsCommand } = await import("./sessions-C2vCAjTZ.js").then((n) => n.n);
		await sessionsCommand({
			json,
			store,
			active
		}, defaultRuntime);
		return true;
	}
};
const routeAgentsList = {
	match: (path) => path[0] === "agents" && path[1] === "list",
	run: async (argv) => {
		const json = hasFlag(argv, "--json");
		const bindings = hasFlag(argv, "--bindings");
		const { agentsListCommand } = await import("./agents-DtRd3yEb.js").then((n) => n.t);
		await agentsListCommand({
			json,
			bindings
		}, defaultRuntime);
		return true;
	}
};
const routeMemoryStatus = {
	match: (path) => path[0] === "memory" && path[1] === "status",
	run: async (argv) => {
		const agent = getFlagValue(argv, "--agent");
		if (agent === null) return false;
		const json = hasFlag(argv, "--json");
		const deep = hasFlag(argv, "--deep");
		const index = hasFlag(argv, "--index");
		const verbose = hasFlag(argv, "--verbose");
		const { runMemoryStatus } = await import("./memory-cli-083UJtVJ.js").then((n) => n.t);
		await runMemoryStatus({
			agent,
			json,
			deep,
			index,
			verbose
		});
		return true;
	}
};
function getCommandPositionals(argv) {
	const out = [];
	const args = argv.slice(2);
	for (const arg of args) {
		if (!arg || arg === "--") break;
		if (arg.startsWith("-")) continue;
		out.push(arg);
	}
	return out;
}
function getFlagValues(argv, name) {
	const values = [];
	const args = argv.slice(2);
	for (let i = 0; i < args.length; i += 1) {
		const arg = args[i];
		if (!arg || arg === "--") break;
		if (arg === name) {
			const next = args[i + 1];
			if (!next || next === "--" || next.startsWith("-")) return null;
			values.push(next);
			i += 1;
			continue;
		}
		if (arg.startsWith(`${name}=`)) {
			const value = arg.slice(name.length + 1).trim();
			if (!value) return null;
			values.push(value);
		}
	}
	return values;
}
const routes = [
	routeHealth,
	routeStatus,
	routeSessions,
	routeAgentsList,
	routeMemoryStatus,
	{
		match: (path) => path[0] === "config" && path[1] === "get",
		run: async (argv) => {
			const pathArg = getCommandPositionals(argv)[2];
			if (!pathArg) return false;
			const json = hasFlag(argv, "--json");
			const { runConfigGet } = await import("./config-cli-9a5qBcdo.js");
			await runConfigGet({
				path: pathArg,
				json
			});
			return true;
		}
	},
	{
		match: (path) => path[0] === "config" && path[1] === "unset",
		run: async (argv) => {
			const pathArg = getCommandPositionals(argv)[2];
			if (!pathArg) return false;
			const { runConfigUnset } = await import("./config-cli-9a5qBcdo.js");
			await runConfigUnset({ path: pathArg });
			return true;
		}
	},
	{
		match: (path) => path[0] === "models" && path[1] === "list",
		run: async (argv) => {
			const provider = getFlagValue(argv, "--provider");
			if (provider === null) return false;
			const all = hasFlag(argv, "--all");
			const local = hasFlag(argv, "--local");
			const json = hasFlag(argv, "--json");
			const plain = hasFlag(argv, "--plain");
			const { modelsListCommand } = await import("./models-Bh_frCup.js").then((n) => n.t);
			await modelsListCommand({
				all,
				local,
				provider,
				json,
				plain
			}, defaultRuntime);
			return true;
		}
	},
	{
		match: (path) => path[0] === "models" && path[1] === "status",
		run: async (argv) => {
			const probeProvider = getFlagValue(argv, "--probe-provider");
			if (probeProvider === null) return false;
			const probeTimeout = getFlagValue(argv, "--probe-timeout");
			if (probeTimeout === null) return false;
			const probeConcurrency = getFlagValue(argv, "--probe-concurrency");
			if (probeConcurrency === null) return false;
			const probeMaxTokens = getFlagValue(argv, "--probe-max-tokens");
			if (probeMaxTokens === null) return false;
			const agent = getFlagValue(argv, "--agent");
			if (agent === null) return false;
			const probeProfileValues = getFlagValues(argv, "--probe-profile");
			if (probeProfileValues === null) return false;
			const probeProfile = probeProfileValues.length === 0 ? void 0 : probeProfileValues.length === 1 ? probeProfileValues[0] : probeProfileValues;
			const json = hasFlag(argv, "--json");
			const plain = hasFlag(argv, "--plain");
			const check = hasFlag(argv, "--check");
			const probe = hasFlag(argv, "--probe");
			const { modelsStatusCommand } = await import("./models-Bh_frCup.js").then((n) => n.t);
			await modelsStatusCommand({
				json,
				plain,
				check,
				probe,
				probeProvider,
				probeProfile,
				probeTimeout,
				probeConcurrency,
				probeMaxTokens,
				agent
			}, defaultRuntime);
			return true;
		}
	}
];
function findRoutedCommand(path) {
	for (const route of routes) if (route.match(path)) return route;
	return null;
}

//#endregion
//#region src/cli/route.ts
async function prepareRoutedCommand(params) {
	emitCliBanner(VERSION, { argv: params.argv });
	await ensureConfigReady({
		runtime: defaultRuntime,
		commandPath: params.commandPath
	});
	if (params.loadPlugins) ensurePluginRegistryLoaded();
}
async function tryRouteCli(argv) {
	if (isTruthyEnvValue(process.env.SYMI_DISABLE_ROUTE_FIRST)) return false;
	if (hasHelpOrVersion(argv)) return false;
	const path = getCommandPath(argv, 2);
	if (!path[0]) return false;
	const route = findRoutedCommand(path);
	if (!route) return false;
	await prepareRoutedCommand({
		argv,
		commandPath: path,
		loadPlugins: route.loadPlugins
	});
	return route.run(argv);
}

//#endregion
//#region src/cli/run-main.ts
function rewriteUpdateFlagArgv(argv) {
	const index = argv.indexOf("--update");
	if (index === -1) return argv;
	const next = [...argv];
	next.splice(index, 1, "update");
	return next;
}
function shouldSkipPluginCommandRegistration(params) {
	if (params.hasBuiltinPrimary) return true;
	if (!params.primary) return hasHelpOrVersion(params.argv);
	return false;
}
function shouldEnsureCliPath(argv) {
	if (hasHelpOrVersion(argv)) return false;
	const [primary, secondary] = getCommandPath(argv, 2);
	if (!primary) return true;
	if (primary === "status" || primary === "health" || primary === "sessions") return false;
	if (primary === "config" && (secondary === "get" || secondary === "unset")) return false;
	if (primary === "models" && (secondary === "list" || secondary === "status")) return false;
	return true;
}
async function runCli(argv = process$1.argv) {
	const normalizedArgv = normalizeWindowsArgv(argv);
	loadDotEnv({ quiet: true });
	normalizeEnv();
	if (shouldEnsureCliPath(normalizedArgv)) ensureSymiCliOnPath();
	assertSupportedRuntime();
	if (await tryRouteCli(normalizedArgv)) return;
	enableConsoleCapture();
	const { buildProgram } = await import("./program-CGuYYumL.js");
	const program = buildProgram();
	installUnhandledRejectionHandler();
	process$1.on("uncaughtException", (error) => {
		console.error("[symi] Uncaught exception:", formatUncaughtError(error));
		process$1.exit(1);
	});
	let parseArgv = rewriteUpdateFlagArgv(normalizedArgv);
	if (!getPrimaryCommand(parseArgv) && !hasHelpOrVersion(parseArgv) && process$1.stdout.isTTY) {
		const fs = await import("node:fs");
		const os = await import("node:os");
		const path = await import("node:path");
		const home = os.homedir();
		const stateDir = process$1.env.SYMI_STATE_DIR?.trim() || path.join(home, ".symi");
		if (![
			path.join(stateDir, "config.yaml"),
			path.join(stateDir, "config.yml"),
			path.join(stateDir, "config.json5"),
			path.join(stateDir, "config.json")
		].some((p) => {
			try {
				return fs.existsSync(p);
			} catch {
				return false;
			}
		})) parseArgv = [...parseArgv.slice(0, 2), "onboard"];
	}
	const primary = getPrimaryCommand(parseArgv);
	if (primary) {
		const { getProgramContext } = await import("./program-context-B_0V80zV.js").then((n) => n.n);
		const ctx = getProgramContext(program);
		if (ctx) {
			const { registerCoreCliByName } = await import("./command-registry-DBbzZvh6.js").then((n) => n.t);
			await registerCoreCliByName(program, ctx, primary, parseArgv);
		}
		const { registerSubCliByName } = await import("./register.subclis-QXO75pUm.js").then((n) => n.a);
		await registerSubCliByName(program, primary);
	}
	const hasBuiltinPrimary = primary !== null && program.commands.some((command) => command.name() === primary);
	if (!shouldSkipPluginCommandRegistration({
		argv: parseArgv,
		primary,
		hasBuiltinPrimary
	})) {
		const { registerPluginCliCommands } = await import("./cli-DHG9iZJi.js");
		const { loadConfig } = await import("./config-D7TcU4qN.js").then((n) => n.t);
		registerPluginCliCommands(program, loadConfig());
	}
	await program.parseAsync(parseArgv);
}

//#endregion
export { runCli };