import { Ct as hasHelpOrVersion, Ot as isValueToken, St as hasFlag, _ as defaultRuntime, _t as getCommandPositionalsWithRootOptions, a as normalizeEnv, bt as getPrimaryCommand, ct as normalizeWindowsArgv, gt as getCommandPathWithRootOptions, l as enableConsoleCapture, lt as applyCliProfileEnv, r as isTruthyEnvValue, ut as parseCliProfileArgs, vt as getFlagValue, xt as getVerboseFlag, yt as getPositiveIntFlagValue } from "./entry.js";
import { Kn as loadDotEnv } from "./auth-profiles-CgnoZiYS.js";
import "./agent-scope-Cezno7_M.js";
import "./utils-CD6tCvSG.js";
import "./core-root-CmA71BTT.js";
import "./logger-BcqRk323.js";
import "./exec-CaapFZaD.js";
import "./registry-CBFkaKwt.js";
import "./github-copilot-token-DHTToceK.js";
import "./manifest-registry-DdFBL-mx.js";
import { t as VERSION } from "./version-sf9dgjHP.js";
import "./dock-MGfYkqVd.js";
import "./tokens-RCFQ-amj.js";
import "./compact-DGr2hadh.js";
import "./accounts-DQj4GURA.js";
import "./plugins-D7VGnP8X.js";
import "./logging-JZEg5nDp.js";
import "./send-CVUi_VO-.js";
import "./send-B_LE3LuQ.js";
import "./with-timeout-B6VGlljS.js";
import "./deliver-DmWt0aVn.js";
import "./diagnostic-D0TTrgNC.js";
import "./accounts-F1jmiu3k.js";
import "./image-ops-DxLQocoR.js";
import "./send-DZcZ8m6m.js";
import "./pi-model-discovery-BMNFsJrD.js";
import "./message-channel-DelDwlJy.js";
import "./pi-embedded-helpers-Jygiu_rm.js";
import "./sandbox-DapwL3Y3.js";
import "./tool-catalog-DwAGTRaX.js";
import "./chrome-CNj5RXTP.js";
import "./tailscale-5K9XNlhO.js";
import "./tailnet-mjXbAxqf.js";
import "./ws-GlDBWD0H.js";
import "./auth-V2FS08vr.js";
import "./server-context-BF4RP1eP.js";
import "./frontmatter-B5GM2mXS.js";
import "./skills-CE-unP39.js";
import "./path-alias-guards-CNxRjVah.js";
import "./paths-BDDFj5Fw.js";
import "./redact-CC_d52A1.js";
import { i as formatUncaughtError } from "./errors-DAcI6n_m.js";
import "./fs-safe-qdP8sV7U.js";
import "./proxy-env-B6UxsfXo.js";
import "./store-B5eeaWQa.js";
import "./ports-D8nInYfq.js";
import "./trash-CrF5N5Zh.js";
import "./server-middleware-BniDse6Q.js";
import "./sessions-CSzvEM0w.js";
import "./accounts-BMuunqOS.js";
import "./paths-COzEpwhO.js";
import "./chat-envelope-BUdriZB0.js";
import "./tool-images-Dtu-s5JK.js";
import "./thinking-BYXvmTqG.js";
import "./models-config-BVwpS5BT.js";
import "./exec-approvals-allowlist-DLolanQl.js";
import "./exec-safe-bin-runtime-policy-yz_-h-RQ.js";
import "./model-catalog-BqfN8gX9.js";
import "./fetch-syFYVRt3.js";
import { h as installUnhandledRejectionHandler } from "./audio-transcription-runner-BVW6o6TV.js";
import "./fetch-guard-CcDaj5My.js";
import "./image-D4aFv0X1.js";
import "./tool-display-B_FNOYTS.js";
import "./api-key-rotation-DLAEpbFc.js";
import "./proxy-fetch-TWpl-yhl.js";
import "./ir-BCFPWtL_.js";
import "./render-C9LkRUhd.js";
import "./target-errors-Ci3M951J.js";
import "./commands-CmZqo7n4.js";
import "./commands-registry-CaALqeCJ.js";
import "./session-cost-usage-WqkA7nWJ.js";
import "./sqlite-BkaDx2XJ.js";
import "./client-B8ehJjd1.js";
import "./call-BAwuZELF.js";
import "./pairing-token-01jjmach.js";
import "./fetch-1d1K1Sbw.js";
import "./pairing-store-Da6gxB-g.js";
import "./exec-approvals-B2nfDOCa.js";
import "./nodes-screen-D9eByp18.js";
import "./system-run-command-C9eoW3Ze.js";
import "./session-utils-CfyCGZX2.js";
import "./skill-commands-B4itYgGX.js";
import "./pi-tools.policy-vXZNXpv0.js";
import "./workspace-dirs-CEAXZCb7.js";
import "./channel-activity-CtGt6xvS.js";
import "./tables-gNfYyl-h.js";
import "./server-lifecycle-BH1bn6N4.js";
import "./stagger-C4U8O7GM.js";
import "./channel-selection-CccMG0Tp.js";
import "./plugin-auto-enable-BG8smK-4.js";
import "./send-CipSFPME.js";
import "./outbound-attachment-Bx3xWzM0.js";
import "./delivery-queue-BU5OeQMD.js";
import "./send-Dp0h-d5B.js";
import "./proxy-Dgwoliym.js";
import "./timeouts-3s3tygPw.js";
import "./runtime-config-collectors-C7Cs7evp.js";
import "./command-secret-targets-AV-RDTsr.js";
import "./onboard-helpers-DePmX0qT.js";
import "./prompt-style-Bi8LEJM5.js";
import "./pairing-labels-DL4tko6o.js";
import "./memory-cli-BEJgeUeO.js";
import "./manager-C7W4Rpg2.js";
import "./links-C87Xouo6.js";
import "./cli-utils-DWSfnwCw.js";
import "./help-format-Cwn7EEhh.js";
import "./progress-DiO7soys.js";
import { t as ensureGensparxCliOnPath } from "./path-env-BV14fVCJ.js";
import "./note-BUcnHAZz.js";
import "./issue-format-CGfT34Dm.js";
import { t as ensurePluginRegistryLoaded } from "./plugin-registry-C--83pMj.js";
import { t as assertSupportedRuntime } from "./runtime-guard-kCSrmbox.js";
import { t as emitCliBanner } from "./banner-BlaUvZIp.js";
import "./doctor-config-flow-BWvDFOZ6.js";
import { n as ensureConfigReady } from "./config-guard-BxYTCiEp.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: (argv) => !hasFlag(argv, "--json"),
	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-DhLRfOA0.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-DSRMolpy.js").then((n) => n.t);
		await statusCommand({
			json,
			deep,
			all,
			usage,
			timeoutMs,
			verbose
		}, defaultRuntime);
		return true;
	}
};
const routeSessions = {
	match: (path) => path[0] === "sessions" && !path[1],
	run: async (argv) => {
		const json = hasFlag(argv, "--json");
		const allAgents = hasFlag(argv, "--all-agents");
		const agent = getFlagValue(argv, "--agent");
		if (agent === null) return false;
		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-o_2uQkZb.js").then((n) => n.n);
		await sessionsCommand({
			json,
			store,
			agent,
			allAgents,
			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-6u4GyrAC.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-BEJgeUeO.js").then((n) => n.t);
		await runMemoryStatus({
			agent,
			json,
			deep,
			index,
			verbose
		});
		return true;
	}
};
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 (!isValueToken(next)) 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 positionals = getCommandPositionalsWithRootOptions(argv, {
				commandPath: ["config", "get"],
				booleanFlags: ["--json"]
			});
			if (!positionals || positionals.length !== 1) return false;
			const pathArg = positionals[0];
			if (!pathArg) return false;
			const json = hasFlag(argv, "--json");
			const { runConfigGet } = await import("./config-cli-DOZqEvcp.js");
			await runConfigGet({
				path: pathArg,
				json
			});
			return true;
		}
	},
	{
		match: (path) => path[0] === "config" && path[1] === "unset",
		run: async (argv) => {
			const positionals = getCommandPositionalsWithRootOptions(argv, { commandPath: ["config", "unset"] });
			if (!positionals || positionals.length !== 1) return false;
			const pathArg = positionals[0];
			if (!pathArg) return false;
			const { runConfigUnset } = await import("./config-cli-DOZqEvcp.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-Dzw_LpBR.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-Dzw_LpBR.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) {
	const suppressDoctorStdout = hasFlag(params.argv, "--json");
	emitCliBanner(VERSION, { argv: params.argv });
	await ensureConfigReady({
		runtime: defaultRuntime,
		commandPath: params.commandPath,
		...suppressDoctorStdout ? { suppressDoctorStdout: true } : {}
	});
	if (typeof params.loadPlugins === "function" ? params.loadPlugins(params.argv) : params.loadPlugins) ensurePluginRegistryLoaded();
}
async function tryRouteCli(argv) {
	if (isTruthyEnvValue(process.env.GENSPARX_DISABLE_ROUTE_FIRST)) return false;
	if (hasHelpOrVersion(argv)) return false;
	const path = getCommandPathWithRootOptions(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] = getCommandPathWithRootOptions(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) {
	let normalizedArgv = normalizeWindowsArgv(argv);
	const parsedProfile = parseCliProfileArgs(normalizedArgv);
	if (!parsedProfile.ok) throw new Error(parsedProfile.error);
	if (parsedProfile.profile) applyCliProfileEnv({ profile: parsedProfile.profile });
	normalizedArgv = parsedProfile.argv;
	loadDotEnv({ quiet: true });
	normalizeEnv();
	if (shouldEnsureCliPath(normalizedArgv)) ensureGensparxCliOnPath();
	assertSupportedRuntime();
	if (await tryRouteCli(normalizedArgv)) return;
	enableConsoleCapture();
	const { buildProgram } = await import("./program-gioaN2B7.js");
	const program = buildProgram();
	installUnhandledRejectionHandler();
	process$1.on("uncaughtException", (error) => {
		console.error("[gensparx] Uncaught exception:", formatUncaughtError(error));
		process$1.exit(1);
	});
	const parseArgv = rewriteUpdateFlagArgv(normalizedArgv);
	const primary = getPrimaryCommand(parseArgv);
	if (primary) {
		const { getProgramContext } = await import("./program-context-COiVfSLD.js").then((n) => n.n);
		const ctx = getProgramContext(program);
		if (ctx) {
			const { registerCoreCliByName } = await import("./command-registry-DVdwLzHN.js").then((n) => n.t);
			await registerCoreCliByName(program, ctx, primary, parseArgv);
		}
		const { registerSubCliByName } = await import("./register.subclis-CDvfGbJM.js").then((n) => n.a);
		await registerSubCliByName(program, primary);
	}
	if (!shouldSkipPluginCommandRegistration({
		argv: parseArgv,
		primary,
		hasBuiltinPrimary: primary !== null && program.commands.some((command) => command.name() === primary)
	})) {
		const { registerPluginCliCommands } = await import("./cli-nnHf7oTi.js");
		const { loadConfig } = await import("./auth-profiles-CgnoZiYS.js").then((n) => n.F);
		registerPluginCliCommands(program, loadConfig());
	}
	await program.parseAsync(parseArgv);
}

//#endregion
export { runCli };