import { Pl as loadDotEnv, Yc as VERSION, hu as enableConsoleCapture, ka as assertSupportedRuntime, r as normalizeEnv, t as isTruthyEnvValue } from "./env-Dlz8aQHP.js";
import "./agent-paths-DUHGyU1s.js";
import "./send-Ditv1VfR.js";
import "./send-CWM2yWF6.js";
import { I as emitCliBanner, Tn as installUnhandledRejectionHandler } from "./model-catalog-B2mRe6cZ.js";
import "./github-copilot-token-A9DiaCB0.js";
import { A as defaultRuntime, At as getVerboseFlag, Dt as getFlagValue, Et as getCommandPath, Mt as hasHelpOrVersion, Ot as getPositiveIntFlagValue, S as formatUncaughtError, jt as hasFlag, kt as getPrimaryCommand, wt as normalizeWindowsArgv } 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 "./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 "./links-CPltkiov.js";
import "./cli-utils-XevKf-tr.js";
import "./help-format-D7mxVfC9.js";
import "./progress-BhMUiH4f.js";
import "./replies-BFsEK9FQ.js";
import "./prompt-style-CWdNyu_Q.js";
import "./pairing-labels-DBt_OA8C.js";
import { t as ensureFasedAgentCliOnPath } from "./path-env-De4mtnzH.js";
import { t as ensurePluginRegistryLoaded } from "./plugin-registry-C7oTQytM.js";
import "./note-_SCwut0b.js";
import "./doctor-config-flow-Vb1Ywbek.js";
import { n as ensureConfigReady } from "./config-guard-TwBaDdU-.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-C_g99tp_.js").then((n) => n.a);
		await healthCommand({
			json,
			timeoutMs,
			verbose,
			gatewayFailureMode: "log-and-exit"
		}, 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-DIkbKBxH.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-C4xyi9TX.js");
		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-CsxQP5xg.js");
		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;
		if (hasUnexpectedTrailingPositionals(argv, ["memory", "status"], [agent])) 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-B7kMyaVL.js").then((n) => n.t);
		await runMemoryStatus({
			agent,
			json,
			deep,
			index,
			verbose
		});
		return true;
	}
};
const routeMemoryDoctor = {
	match: (path) => path[0] === "memory" && path[1] === "doctor",
	run: async (argv) => {
		const agent = getFlagValue(argv, "--agent");
		if (agent === null) return false;
		if (hasUnexpectedTrailingPositionals(argv, ["memory", "doctor"], [agent])) return false;
		const json = hasFlag(argv, "--json");
		const { runMemoryDoctorStatus } = await import("./memory-cli-B7kMyaVL.js").then((n) => n.t);
		await runMemoryDoctorStatus({
			agent,
			json
		});
		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 hasUnexpectedTrailingPositionals(argv, commandPath, allowedTrailingValues = []) {
	const allowed = new Set(allowedTrailingValues.filter((value) => typeof value === "string"));
	return getCommandPositionals(argv).slice(commandPath.length).some((value) => !allowed.has(value));
}
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,
	routeMemoryDoctor,
	{
		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-CQpqSVFS.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-CQpqSVFS.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-D8MTK6SG.js");
			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-D8MTK6SG.js");
			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.FASED_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;
}
function pauseNonTtyStdinForCliExit(stdin = process$1.stdin) {
	if (stdin.isTTY) return;
	stdin.pause();
}
async function runCli(argv = process$1.argv) {
	const normalizedArgv = normalizeWindowsArgv(argv);
	try {
		loadDotEnv({ quiet: true });
		normalizeEnv();
		if (shouldEnsureCliPath(normalizedArgv)) ensureFasedAgentCliOnPath();
		assertSupportedRuntime();
		if (await tryRouteCli(normalizedArgv)) return;
		enableConsoleCapture();
		const { buildProgram } = await import("./program-B3cXsVO0.js");
		const program = buildProgram();
		installUnhandledRejectionHandler();
		process$1.on("uncaughtException", (error) => {
			console.error("[fased] Uncaught exception:", formatUncaughtError(error));
			process$1.exit(1);
		});
		const parseArgv = rewriteUpdateFlagArgv(normalizedArgv);
		const primary = getPrimaryCommand(parseArgv);
		if (primary) {
			const { getProgramContext } = await import("./program-context-CDFrVtWb.js").then((n) => n.n);
			const ctx = getProgramContext(program);
			if (ctx) {
				const { registerCoreCliByName } = await import("./command-registry-fqlYdOTI.js").then((n) => n.t);
				await registerCoreCliByName(program, ctx, primary, parseArgv);
			}
			const { registerSubCliByName } = await import("./register.subclis-Bj8pFyAT.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-CE8pVYeA.js");
			const { loadConfig } = await import("./env-Dlz8aQHP.js").then((n) => n.qt);
			registerPluginCliCommands(program, loadConfig());
		}
		await program.parseAsync(parseArgv);
	} finally {
		pauseNonTtyStdinForCliExit();
	}
}

//#endregion
export { runCli };