import "./subagent-registry-BdCHUwJF.js";
import { _ as defaultRuntime, an as getPrimaryCommand, c as enableConsoleCapture, cn as hasHelpOrVersion, en as normalizeWindowsArgv, i as normalizeEnv, in as getPositiveIntFlagValue, n as isTruthyEnvValue, nn as getCommandPath, on as getVerboseFlag, rn as getFlagValue, sn as hasFlag } from "./entry.js";
import "./auth-profiles-BGjbqScX.js";
import "./exec-CBKBIMpA.js";
import "./agent-scope-p68ICeNQ.js";
import "./github-copilot-token-CyWpbkHJ.js";
import "./model-OTR4fRIX.js";
import "./pi-model-discovery-BDrA0RUW.js";
import "./frontmatter-DRl3Sa-X.js";
import "./skills-Ho_2X6WT.js";
import "./manifest-registry-CYUiqtAr.js";
import { L as VERSION, z as loadDotEnv } from "./config-xHYx2cij.js";
import "./client-fwA5zyHb.js";
import "./call-BOB-Te5P.js";
import "./message-channel-B9mgJ1nn.js";
import "./sessions-BwDGf9Sn.js";
import "./tokens-DNhq_l0Z.js";
import "./normalize-B8nBEyAK.js";
import "./accounts-BSDGn_Eo.js";
import "./bindings-B_ZIo7YE.js";
import "./logging-5MtSkLpb.js";
import "./send-YkSDctU7.js";
import "./plugins-B1ojCJHx.js";
import "./send-CsZYxWdf.js";
import "./with-timeout-DEXcYOPT.js";
import "./deliver-5Uvc7ymL.js";
import "./diagnostic-BrjZno3V.js";
import "./diagnostic-session-state-CAYi3DRc.js";
import "./accounts-DUB7WjhZ.js";
import "./send-33rhg_bg.js";
import "./image-ops-DGYdb3fh.js";
import "./pi-embedded-helpers-DoMXOCkN.js";
import "./sandbox-CZanUXAq.js";
import "./chrome-DfrRhznb.js";
import "./tailscale-D9FK-yno.js";
import "./auth-BFCCBoWg.js";
import "./server-context-DvoYRfwN.js";
import "./routes-ClCMoQG_.js";
import "./redact-BfDi6wIJ.js";
import { r as formatUncaughtError } from "./errors-DNW-UCMb.js";
import "./paths-DqOyyjUy.js";
import "./ssrf-B_uizFky.js";
import "./store-CORMGVx_.js";
import "./ports-LWH8Y0_f.js";
import "./trash-B891j_cA.js";
import "./dock-BPcuR3ve.js";
import "./accounts-SnH-42ge.js";
import "./paths-DT4MkPF0.js";
import "./tool-images-DLc1ZwCt.js";
import "./thinking-O_pp2Bz3.js";
import "./models-config-xKUJ-Jlr.js";
import "./reply-prefix-CrkNe8Gp.js";
import "./memory-cli-Guckbc8M.js";
import "./manager-DnbrWcSO.js";
import "./gemini-auth-BF-a5GeR.js";
import "./sqlite-DZTdGqNd.js";
import "./retry-DtzRtCu9.js";
import "./common-Bi2yGPsV.js";
import "./chunk-DkEDZgsU.js";
import "./markdown-tables-I-50wDdr.js";
import "./fetch-guard-sWUTAYEJ.js";
import "./fetch-CfzM3qfj.js";
import "./ir-WbjhHhfd.js";
import "./render-CCLsW6Lz.js";
import "./commands-registry-D8TQrvT9.js";
import "./image-CWNvCgXH.js";
import "./tool-display-Ch60dmIj.js";
import { c as installUnhandledRejectionHandler } from "./runner-BWzWj3vE.js";
import "./model-catalog-CCane-Jh.js";
import "./session-utils-BeS2v05U.js";
import "./skill-commands-DVP91_MZ.js";
import "./workspace-dirs-CpIMMjZW.js";
import "./pairing-store-DM_ihkC1.js";
import "./fetch-mirEALun.js";
import "./nodes-screen-BNyvvjYY.js";
import "./session-cost-usage-BCIITMRg.js";
import "./project-context-DhXARJNC.js";
import "./control-service-DziHPGgw.js";
import "./stagger-BCQzFuQi.js";
import "./channel-selection-DV8cpKuI.js";
import "./send-BquvUhjS.js";
import "./outbound-attachment-DAzLnDoa.js";
import "./delivery-queue-CL2en3fg.js";
import "./send-D5voy0Gs.js";
import "./resolve-route-CAxji0MH.js";
import "./channel-activity-OK2g2kgk.js";
import "./tables-7XAEudlg.js";
import "./proxy-YU8wp1-L.js";
import "./links-rnbUL9h5.js";
import "./cli-utils-f9j-_1VT.js";
import "./help-format-5GFCgEVf.js";
import "./progress-Clpi3Ckj.js";
import "./replies-B4l-Q3Tx.js";
import "./pi-tools.policy-Cadm9ZgR.js";
import "./onboard-helpers-COs8NEvA.js";
import "./prompt-style-B_yUCLn4.js";
import "./pairing-labels-H_LS1HI0.js";
import { t as ensureOpenClawCliOnPath } from "./path-env-C6L51Z2a.js";
import "./catalog-DrXj_7vG.js";
import "./note-3kkap1pu.js";
import "./plugin-auto-enable-Dv6NYkie.js";
import { t as ensurePluginRegistryLoaded } from "./plugin-registry-CYZ6YsHI.js";
import { t as assertSupportedRuntime } from "./runtime-guard-kzIyHhvr.js";
import { t as emitCliBanner } from "./banner-BheTTuTV.js";
import "./doctor-config-flow-Vzd7XYmX.js";
import { n as ensureConfigReady } from "./config-guard-Cwr6umN2.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-vdUao_La.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-aHA2QEB2.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-CIK3cg_h.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-C8qUwRUH.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-Guckbc8M.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-CbYXuowV.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-CbYXuowV.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-CQ9yxwfz.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-CQ9yxwfz.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.OPENCLAW_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)) ensureOpenClawCliOnPath();
	assertSupportedRuntime();
	if (await tryRouteCli(normalizedArgv)) return;
	enableConsoleCapture();
	const { buildProgram } = await import("./program-DxeS-PD_.js");
	const program = buildProgram();
	installUnhandledRejectionHandler();
	process$1.on("uncaughtException", (error) => {
		console.error("[openclaw] Uncaught exception:", formatUncaughtError(error));
		process$1.exit(1);
	});
	const parseArgv = rewriteUpdateFlagArgv(normalizedArgv);
	const primary = getPrimaryCommand(parseArgv);
	if (primary) {
		const { getProgramContext } = await import("./program-context-BUuYElH3.js").then((n) => n.n);
		const ctx = getProgramContext(program);
		if (ctx) {
			const { registerCoreCliByName } = await import("./command-registry-DJUPGQmQ.js").then((n) => n.t);
			await registerCoreCliByName(program, ctx, primary, parseArgv);
		}
		const { registerSubCliByName } = await import("./register.subclis-7q1zQzQK.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-W1J8kaoO.js");
		const { loadConfig } = await import("./config-xHYx2cij.js").then((n) => n.t);
		registerPluginCliCommands(program, loadConfig());
	}
	await program.parseAsync(parseArgv);
}

//#endregion
export { runCli };