import "./paths-CutK9mvd.js";
import "./registry-DScA7GM7.js";
import "./utils-BXq128Ep.js";
import { f as defaultRuntime, r as enableConsoleCapture } from "./subsystem-C0jWWDsO.js";
import "./boolean-DtWR5bt3.js";
import { a as normalizeWindowsArgv, c as getFlagValue, d as getVerboseFlag, f as hasFlag, i as normalizeEnv, l as getPositiveIntFlagValue, n as isTruthyEnvValue, p as hasHelpOrVersion, s as getCommandPath, u as getPrimaryCommand } from "./entry.js";
import "./auth-profiles-Ci0m1nDj.js";
import "./exec-BfxXkFYo.js";
import "./agent-scope-C9lu5zYP.js";
import "./frontmatter-B3s_6fwe.js";
import "./skills-CXwgvGur.js";
import "./manifest-registry-CLylU6AG.js";
import { L as VERSION, z as loadDotEnv } from "./io-CD_zuK0D.js";
import "./config-DiWsrVKe.js";
import "./client-DcGx78uR.js";
import "./call-DfwL1J3H.js";
import "./message-channel-f25bXyKM.js";
import "./subagent-registry-C2sM5Cyw.js";
import "./sessions-Mt8f23sr.js";
import "./tokens-D7kBZYPD.js";
import "./plugins-CiXA7mtz.js";
import "./accounts-DlyBFGv4.js";
import "./bindings-DjR4yXgA.js";
import "./logging-pqyrk15z.js";
import "./send-BSyWSMGa.js";
import "./send-Bv-Ugxhn.js";
import "./with-timeout-CMUEB0p-.js";
import "./deliver-CkqGoWHC.js";
import "./accounts-DNDn42nY.js";
import "./send-Dbw-1Nv6.js";
import "./image-ops-DX6lds-i.js";
import "./models-config-6QdRrV1c.js";
import "./pi-embedded-helpers-_sjZz5r6.js";
import "./sandbox-Cgi5GRjr.js";
import "./chrome-CCvAKFA-.js";
import "./tailscale-BrDWEIwI.js";
import "./auth-B80pI0Uh.js";
import "./server-context-CPsi2755.js";
import "./routes-MRFMs3Hh.js";
import "./redact-CFj039qF.js";
import { r as formatUncaughtError } from "./errors-8VQXhB4u.js";
import "./paths-BKv1HwMq.js";
import "./ssrf-weuQnXiO.js";
import "./store-BgSeZwv0.js";
import "./ports-BTCCmBPN.js";
import "./trash-RPQQ3ep-.js";
import "./accounts-IQLo28rM.js";
import "./paths-mQAx86lp.js";
import "./tool-images-BtNaJzDf.js";
import "./reply-prefix-CTkJoXqQ.js";
import "./memory-cli-DhQ3BMgb.js";
import "./manager-BUwPVwMU.js";
import "./gemini-auth-D_WaKG1u.js";
import "./sqlite-B6wrIncg.js";
import "./retry-eZfsfPJw.js";
import "./common-Cb-qblwg.js";
import "./chunk-CCkvwRI1.js";
import "./markdown-tables-BmPL6gxD.js";
import "./fetch-guard-DgkwAf8y.js";
import "./fetch-Cyj7bUtQ.js";
import "./ir-Zi6SqHuv.js";
import "./render-lL152pED.js";
import "./commands-registry-Bb7wps-U.js";
import { c as installUnhandledRejectionHandler } from "./runner-Dq5pUJw7.js";
import "./tool-display-C_2MZJqm.js";
import "./model-catalog-I10Mw32M.js";
import "./session-utils-rRgbDHdn.js";
import "./pi-tools.policy-Dl38gqLG.js";
import "./pairing-store-BFjZsQfU.js";
import "./fetch-FKiEPHsu.js";
import "./nodes-screen-aqjJyJKK.js";
import "./session-cost-usage-CFkSIl99.js";
import "./send-Dm5td_ud.js";
import "./outbound-attachment-DbnUFGg7.js";
import "./delivery-queue-CrM_98Zj.js";
import "./project-context-CDgzGX_i.js";
import "./control-service-Da4pvhRF.js";
import "./stagger-vDSk1wpM.js";
import "./channel-selection-C9HQldEr.js";
import "./send-DVTkNDIS.js";
import "./resolve-route-DfP8shJU.js";
import "./channel-activity-CjNqpxzA.js";
import "./tables-D0RFg7_p.js";
import "./links-Crq8FXFM.js";
import "./cli-utils-m10N0YX2.js";
import "./help-format-xwRPMYQn.js";
import "./progress-Czj96fRf.js";
import "./replies-D7zeCuNw.js";
import "./onboard-helpers-BfUVfjJm.js";
import "./prompt-style-gyFdZw9z.js";
import "./pairing-labels-DcHuGxfy.js";
import { t as ensureCoderClawCliOnPath } from "./path-env-CdEq7X1S.js";
import "./catalog-C5-j4Yr-.js";
import "./note-DBwiNGlo.js";
import "./plugin-auto-enable-D5QkbU5E.js";
import { t as ensurePluginRegistryLoaded } from "./plugin-registry-DgWOHdSi.js";
import { t as assertSupportedRuntime } from "./runtime-guard-CV_MGdwf.js";
import { t as emitCliBanner } from "./banner-DpDWt1U4.js";
import "./doctor-config-flow-UlrbUY4t.js";
import { n as ensureConfigReady } from "./config-guard-CmVMxRmP.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-DSAmjFa7.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-BP_wXBQL.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-BC_qhgxj.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-DfmD2axW.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-DhQ3BMgb.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-CCWbiZix.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-CCWbiZix.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-CaXQ34NP.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-CaXQ34NP.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.CODERCLAW_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)) ensureCoderClawCliOnPath();
	assertSupportedRuntime();
	if (await tryRouteCli(normalizedArgv)) return;
	enableConsoleCapture();
	const { buildProgram } = await import("./program-wAxEK1Bb.js");
	const program = buildProgram();
	installUnhandledRejectionHandler();
	process$1.on("uncaughtException", (error) => {
		console.error("[coderclaw] Uncaught exception:", formatUncaughtError(error));
		process$1.exit(1);
	});
	const parseArgv = rewriteUpdateFlagArgv(normalizedArgv);
	const primary = getPrimaryCommand(parseArgv);
	if (primary) {
		const { getProgramContext } = await import("./program-context-DtYiUT5k.js").then((n) => n.n);
		const ctx = getProgramContext(program);
		if (ctx) {
			const { registerCoreCliByName } = await import("./command-registry-5cbxhiw-.js").then((n) => n.t);
			await registerCoreCliByName(program, ctx, primary, parseArgv);
		}
		const { registerSubCliByName } = await import("./register.subclis-IgsiQxg3.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-DDIIFX_m.js");
		const { loadConfig } = await import("./config-DiWsrVKe.js").then((n) => n.t);
		registerPluginCliCommands(program, loadConfig());
	}
	await program.parseAsync(parseArgv);
}

//#endregion
export { runCli };