import "./pi-embedded-helpers-Df7l-4vq.js";
import { en as installUnhandledRejectionHandler, et as loadDotEnv } from "./reply-CZUaueaY.js";
import { r as enableConsoleCapture, s as defaultRuntime } from "./subsystem-hATE68va.js";
import "./paths-VdmjGGyc.js";
import "./theme-C5EwWDWE.js";
import "./ansi-By7x1TI7.js";
import "./utils-D019Z2NU.js";
import "./logger-BKidfKRU.js";
import "./exec-BBWSxSu-.js";
import "./koi-scope-BeICsBhH.js";
import "./model-selection-DvQd6xjM.js";
import "./dist-Czg7dzzf.js";
import "./dist-cjs-CtVce_lP.js";
import "./boolean-D-3joTkO.js";
import { r as normalizeEnv, t as isTruthyEnvValue } from "./env-ChCKTuXK.js";
import "./github-copilot-token-BqhLBQWA.js";
import { N as VERSION } from "./config-BOTdzMIB.js";
import "./manifest-registry-D7MfBQxU.js";
import "./plugins-dW6cc0qG.js";
import "./sessions-DyqGkYWU.js";
import "./image-CUVl1Hhm.js";
import "./dist-iFsGHQA2.js";
import "./lib-C-WEldjv.js";
import "./src-CiVOi-Ma.js";
import "./core-DrwlWTgS.js";
import "./pi-model-discovery-E8vIYAbb.js";
import "./sandbox-CDOYKOkn.js";
import { E as formatUncaughtError } from "./chrome-CTicuLaA.js";
import "./skills-DHpPesfZ.js";
import "./routes-C952rvWJ.js";
import "./server-context-Cs8Yx5qf.js";
import "./image-ops-B6MN1Uli.js";
import "./message-channel-B-LM-U45.js";
import "./logging-Dn5qdhsZ.js";
import "./accounts-B8F2xBS8.js";
import "./paths-DSzdyYR5.js";
import "./tool-images-DOYdkgEG.js";
import "./redact-Db6nXe_o.js";
import "./tool-display-CGLMse-l.js";
import "./deliver-BU-ss2iZ.js";
import "./dispatcher-Da_eDTB8.js";
import "./dist-JRNJAZWM.js";
import "./pi-tool-definition-adapter-DZBstpDD.js";
import "./manager-CvGvPIqL.js";
import "./sqlite-CbC9FUO2.js";
import "./warnings-D1qUihoO.js";
import "./proxy-from-env-BBdtl5-Y.js";
import "./login-qr-BDJgj3j2.js";
import "./channel-summary-DZinsO88.js";
import "./device-identity-CBC9Fa-4.js";
import "./client-CnWPlz1L.js";
import "./call-By5olg7I.js";
import "./koi-events-CVGX2xkt.js";
import "./pairing-store-DnxZNJ-U.js";
import "./links-DlFnXfJ_.js";
import "./progress-X-YSIEVf.js";
import "./node-pairing-ClP_ps1x.js";
import "./pi-tools.policy-CA2hGIde.js";
import "./onboard-helpers-DXmuVr9a.js";
import "./prompt-style-ko1k1LE0.js";
import "./pairing-labels-CNooTiAc.js";
import "./satisfies-D4f4jwpc.js";
import "./session-cost-usage-BiwFgQ3E.js";
import "./control-service-CamrxDfq.js";
import "./channel-selection-BTYECKhQ.js";
import "./event-log-DMRSRkMD.js";
import "./deps-BkqEahC_.js";
import "./tailscale-C88PrOS1.js";
import { t as ensureSKYKOICliOnPath } from "./path-env-B9AK_97y.js";
import { g as assertSupportedRuntime } from "./daemon-runtime-EHtDn8NC.js";
import { n as findRoutedCommand, t as ensureConfigReady } from "./config-guard-GucPWd71.js";
import "./logging-D-QZpI1i.js";
import "./note-D68Wd3Zr.js";
import "./clack-prompter-DF6HE5p6.js";
import "./onboarding-HT8NN42O.js";
import "./onboard-skills-YZFGxDZB.js";
import "./github-copilot-auth-BDRjMk4p.js";
import "./onboard-channels-BqKUp6cL.js";
import "./plugin-auto-enable-BIRsItbt.js";
import "./archive-BrDQDedR.js";
import "./skill-scanner-BSxHCT2R.js";
import "./installs-D-K256Jd.js";
import "./health-format-CW12kvrh.js";
import "./update-runner-D7y7t7Dm.js";
import "./auth-tu2F7_70.js";
import "./audit-D_KuVAWW.js";
import "./table-Bu1gPkD7.js";
import "./skills-status-CrL8zDk3.js";
import "./service-C6lyBW0F.js";
import "./systemd-C7TaOB0r.js";
import "./diagnostics-B6_fjn4Z.js";
import "./node-service-CtGQ_WCB.js";
import "./channels-status-issues-CNNkv5DB.js";
import { a as getCommandPath, c as getPrimaryCommand, d as hasHelpOrVersion } from "./register.subclis-DU1_EbNo.js";
import "./gateway-rpc-FMQ_vIWH.js";
import "./help-format-CN9mmVLD.js";
import "./admin-unlock-DfFhvRis.js";
import "./koi-B9sw4JKe.js";
import { t as ensurePluginRegistryLoaded } from "./plugin-registry-BQc-z1Y2.js";
import "./configure-BGddNvFM.js";
import "./systemd-linger-DFrKH2dP.js";
import "./widearea-dns-nPnswBoX.js";
import "./bonjour-discovery-D3DvZVgk.js";
import "./ensure-local-gateway-CwgaMY79.js";
import "./login-A_sTANpw.js";
import "./auth-health-Dbdl2a43.js";
import "./doctor-gZ7cszFo.js";
import "./completion-cli-B06sgaew.js";
import "./service-audit-Bqgp6PlY.js";
import "./hooks-status-CV-O6Xro.js";
import { r as emitCliBanner } from "./tui-QrrdMeaH.js";
import process$1 from "node:process";
import { fileURLToPath } from "node:url";
import fs from "node:fs";
import path from "node:path";

//#region src/cli/route.ts
async function prepareRoutedCommand(params) {
	await emitCliBanner(VERSION, { argv: params.argv });
	await ensureConfigReady({
		runtime: defaultRuntime,
		commandPath: params.commandPath
	});
	if (params.loadPlugins) ensurePluginRegistryLoaded();
}
async function tryRouteCli(argv) {
	if (isTruthyEnvValue(process.env.SKYKOI_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
/**
* @module cli/run-main
*
* Main CLI entry point. Bootstraps the runtime environment (dotenv, PATH,
* error handlers), routes subcommands, and handles top-level lifecycle
* (fast-path routing, commander program build, uncaught error formatting).
*/
function rewriteUpdateFlagArgv(argv) {
	const index = argv.indexOf("--update");
	if (index === -1) return argv;
	const next = [...argv];
	next.splice(index, 1, "update");
	return next;
}
async function runCli(argv = process$1.argv) {
	const normalizedArgv = stripWindowsNodeExec(argv);
	loadDotEnv({ quiet: true });
	normalizeEnv();
	ensureSKYKOICliOnPath();
	assertSupportedRuntime();
	if (await tryRouteCli(normalizedArgv)) return;
	enableConsoleCapture();
	const { buildProgram } = await import("./program-B9hoSXbr.js").then((n) => n.t);
	const program = buildProgram();
	installUnhandledRejectionHandler();
	process$1.on("uncaughtException", (error) => {
		console.error("[SKYKOI] Uncaught exception:", formatUncaughtError(error));
		process$1.exit(1);
	});
	let parseArgv = rewriteUpdateFlagArgv(normalizedArgv);
	const hasAnyArg = parseArgv.slice(2).some((a) => !!a && !a.startsWith("--"));
	const wantsHelpOrVersion = hasHelpOrVersion(parseArgv);
	if (!hasAnyArg && !wantsHelpOrVersion) {
		let isLoggedIn = false;
		try {
			const { readAuthFile } = await import("./login-A_sTANpw.js").then((n) => n.n);
			isLoggedIn = !!(await readAuthFile())?.token;
		} catch {}
		let defaultCommand = "tui";
		if (!isLoggedIn) try {
			const { isFreshInstall, canPromptInteractively, runFirstRunWelcome } = await import("./first-run-C2ym7GEo.js");
			if (isFreshInstall(isLoggedIn) && canPromptInteractively()) {
				const choice = await runFirstRunWelcome();
				if (choice === null) return;
				if (choice === "admin") {
					const { adminUnlockCommand } = await import("./admin-unlock-DfFhvRis.js").then((n) => n.n);
					if (!await adminUnlockCommand({})) return;
					defaultCommand = "tui";
				} else defaultCommand = choice;
			}
		} catch {}
		parseArgv = [...parseArgv, defaultCommand];
	}
	const primary = getPrimaryCommand(parseArgv);
	if (primary) {
		const { registerSubCliByName } = await import("./register.subclis-DU1_EbNo.js").then((n) => n.i);
		await registerSubCliByName(program, primary);
	}
	if (!(!primary && hasHelpOrVersion(parseArgv))) {
		const { registerPluginCliCommands } = await import("./cli-CLRALtXM.js");
		const { loadConfig } = await import("./config-BOTdzMIB.js").then((n) => n.t);
		registerPluginCliCommands(program, loadConfig());
	}
	await program.parseAsync(parseArgv);
}
function stripWindowsNodeExec(argv) {
	if (process$1.platform !== "win32") return argv;
	const stripControlChars = (value) => {
		let out = "";
		for (let i = 0; i < value.length; i += 1) {
			const code = value.charCodeAt(i);
			if (code >= 32 && code !== 127) out += value[i];
		}
		return out;
	};
	const normalizeArg = (value) => stripControlChars(value).replace(/^['"]+|['"]+$/g, "").trim();
	const normalizeCandidate = (value) => normalizeArg(value).replace(/^\\\\\\?\\/, "");
	const execPath = normalizeCandidate(process$1.execPath);
	const execPathLower = execPath.toLowerCase();
	const execBase = path.basename(execPath).toLowerCase();
	const isExecPath = (value) => {
		if (!value) return false;
		const normalized = normalizeCandidate(value);
		if (!normalized) return false;
		const lower = normalized.toLowerCase();
		return lower === execPathLower || path.basename(lower) === execBase || lower.endsWith("\\node.exe") || lower.endsWith("/node.exe") || lower.includes("node.exe") || path.basename(lower) === "node.exe" && fs.existsSync(normalized);
	};
	const filtered = argv.filter((arg, index) => index === 0 || !isExecPath(arg));
	if (filtered.length < 3) return filtered;
	const cleaned = [...filtered];
	if (isExecPath(cleaned[1])) cleaned.splice(1, 1);
	if (isExecPath(cleaned[2])) cleaned.splice(2, 1);
	return cleaned;
}

//#endregion
export { runCli };