import "./pi-embedded-helpers-C7GyAcoc.js";
import { et as loadDotEnv, qt as installUnhandledRejectionHandler } from "./reply-Bnpxcafr.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-XH65-wH1.js";
import "./koi-scope-je0O-Kk9.js";
import "./model-selection-DHqY0wuU.js";
import "./dist-CFhZJtYo.js";
import "./dist-cjs-DiQp4ztu.js";
import "./boolean-D-3joTkO.js";
import { r as normalizeEnv, t as isTruthyEnvValue } from "./env-ChCKTuXK.js";
import "./github-copilot-token-BqhLBQWA.js";
import { t as VERSION } from "./version-BKRSzdyx.js";
import "./config-ZjEd8561.js";
import "./manifest-registry-DEGu_o5t.js";
import "./plugins-Ct7Mnq1x.js";
import "./sessions-COz6-MPd.js";
import "./image-DYRH6hYg.js";
import "./dist-nhxaQYGz.js";
import "./lib-pS0Bd7GL.js";
import "./src-ByySp9O0.js";
import "./core-B7QS0Vnt.js";
import "./pi-model-discovery-Cy-rVVvR.js";
import "./sandbox-BeaBvIJZ.js";
import { E as formatUncaughtError } from "./chrome-CROsH9kD.js";
import "./skills-D0qJwRRD.js";
import "./routes-DP4mWBwK.js";
import "./server-context-0I52nf-b.js";
import "./image-ops-CQFojSu1.js";
import "./message-channel-CaDAAMe0.js";
import "./logging-ADUQX6n5.js";
import "./accounts-DFSZwaCs.js";
import "./paths-DLKQOevr.js";
import "./tool-images-DlkXfMNL.js";
import "./redact-1AXapBET.js";
import "./tool-display-DYOxwSs6.js";
import "./deliver-CkS1xVhO.js";
import "./dispatcher-CoG7Bmmx.js";
import "./dist-B556KqJe.js";
import "./pi-tool-definition-adapter-CnsO-0rY.js";
import "./manager-6pqEqm7q.js";
import "./sqlite-CYnXobrn.js";
import "./warnings-Ds_WSeah.js";
import "./proxy-from-env-DxUIcU4P.js";
import "./login-qr-ekueLD_2.js";
import "./channel-summary-1rzVva2g.js";
import "./device-identity-CpMBJtRJ.js";
import "./client-BM6xyPUD.js";
import "./call-JFo1_L0m.js";
import "./koi-events-DhwDeG-q.js";
import "./pairing-store-BrlNnaod.js";
import "./links-BupJpVpQ.js";
import "./progress-EICDZThJ.js";
import "./node-pairing-DuliQoRe.js";
import "./pi-tools.policy-XgYp6L9R.js";
import "./onboard-helpers-FO60qqTG.js";
import "./prompt-style-hXUwxLRe.js";
import "./pairing-labels-DLc3GnhN.js";
import "./satisfies-Dp_OBiSc.js";
import "./session-cost-usage-BNV86lI0.js";
import "./control-service-DQtH-td4.js";
import "./restart-sentinel-BqQzvk3k.js";
import "./channel-selection-DhBJOelv.js";
import "./event-log-CL2tmo5v.js";
import "./deps-CX3Skz28.js";
import "./tailscale-CDBmRrBH.js";
import { t as ensureSKYKOICliOnPath } from "./path-env-DLiKMTfX.js";
import { t as assertSupportedRuntime } from "./runtime-guard-Btp4Sks0.js";
import { n as findRoutedCommand, t as ensureConfigReady } from "./config-guard-CmbWsYQa.js";
import "./logging-CSvbGeqF.js";
import "./note-DdyFyHLV.js";
import "./clack-prompter-CCgKKgnN.js";
import "./onboarding-CCpP66LJ.js";
import "./onboard-skills-ChDFxeGS.js";
import "./github-copilot-auth-CRvtl8wF.js";
import "./onboard-channels-BiwGmgdU.js";
import "./plugin-auto-enable-WPZfV7Dp.js";
import "./archive-DnVN3g6v.js";
import "./skill-scanner-BCGU84pB.js";
import "./installs-BBJbDnE-.js";
import "./health-format-Cw_wWsUk.js";
import "./update-runner-BF2ZUZuV.js";
import "./auth-CeZ-Kq3Y.js";
import "./audit-B5CUzM1R.js";
import "./table-C-_kZeNX.js";
import "./skills-status-B0uJbSLd.js";
import "./service-CgbWVYSz.js";
import "./systemd-CKUsCXqF.js";
import "./diagnostics-CBJs_eaH.js";
import "./node-service-CnU49y0d.js";
import "./channels-status-issues-D_rjAibL.js";
import "./doctor-completion-CLMLUQj9.js";
import { a as getCommandPath, c as getPrimaryCommand, d as hasHelpOrVersion } from "./register.subclis-B7sqTsBj.js";
import "./gateway-rpc-BLmNrKaj.js";
import "./help-format-BgbvAVIq.js";
import "./admin-unlock--4SPdpdy.js";
import "./koi-Dv4SlCoI.js";
import { t as ensurePluginRegistryLoaded } from "./plugin-registry-Bb6CC447.js";
import "./control-ui-assets-C6cSlkkc.js";
import "./configure-BQQN1fFr.js";
import "./daemon-runtime-BTR2GDIQ.js";
import "./systemd-linger-Cu8buxAR.js";
import "./widearea-dns-BVskGRhX.js";
import "./bonjour-discovery-DjvriZpZ.js";
import "./ensure-local-gateway-CWMjpIBa.js";
import "./login-BPXcLBkt.js";
import "./auth-health-BQXG_lTS.js";
import "./doctor-Ce1sxck6.js";
import "./completion-cli-Q3xLcOzu.js";
import "./service-audit-D1ElVIM8.js";
import "./hooks-status-CxWUG7p9.js";
import { r as emitCliBanner } from "./tui-Dh1acgyz.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-DMa1pnc4.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-BPXcLBkt.js").then((n) => n.n);
			isLoggedIn = !!(await readAuthFile())?.token;
		} catch {}
		let defaultCommand = "tui";
		if (!isLoggedIn) try {
			const { isFreshInstall, canPromptInteractively, runFirstRunWelcome } = await import("./first-run-DWzQt5YX.js");
			if (isFreshInstall(isLoggedIn) && canPromptInteractively()) {
				const choice = await runFirstRunWelcome();
				if (choice === null) return;
				if (choice === "admin") {
					const { adminUnlockCommand } = await import("./admin-unlock--4SPdpdy.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-B7sqTsBj.js").then((n) => n.i);
		await registerSubCliByName(program, primary);
	}
	if (!(!primary && hasHelpOrVersion(parseArgv))) {
		const { registerPluginCliCommands } = await import("./cli-Df5Bozh9.js");
		const { loadConfig } = await import("./config-ZjEd8561.js").then((n) => n.t);
		registerPluginCliCommands(program, loadConfig());
	}
	if (!wantsHelpOrVersion && getPrimaryCommand(parseArgv) !== "update") import("./cli-auto-update-BFvdwaVA.js").then((m) => m.maybeAutoUpdateOnStartup()).catch(() => {});
	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 };