import "./pi-embedded-helpers-Ny2JybJV.js";
import { Xt as installUnhandledRejectionHandler } from "./reply-CL83zh9t.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 "./exec-xrC0ejqg.js";
import "./koi-scope-D8R_V4oO.js";
import "./model-selection-Bue40sP3.js";
import "./dist-CUiRTtgg.js";
import "./dist-cjs-DKbiqPag.js";
import "./boolean-CBeSt-pi.js";
import { r as normalizeEnv, t as isTruthyEnvValue } from "./env-Dliiu-O6.js";
import "./github-copilot-token-CNBLk7kR.js";
import { N as VERSION } from "./config-CJCyYQfd.js";
import "./manifest-registry-oBOOUSYE.js";
import "./plugins-4Dg2aV3Z.js";
import "./sessions-p608GJQF.js";
import "./image-Cm8pagSS.js";
import "./dist-qohLth5U.js";
import "./lib-DySFL26z.js";
import "./src-CuBVmkDD.js";
import "./core-CYIM8X9C.js";
import "./pi-model-discovery-BJB6xKfm.js";
import "./sandbox-CH6Z4NF9.js";
import { E as formatUncaughtError } from "./chrome-qnrH3SE9.js";
import "./skills-belB1fF2.js";
import "./routes-B_ID_OU2.js";
import "./server-context-BfQWGTuX.js";
import "./image-ops-D4trOw4b.js";
import "./message-channel-DFpLxeOe.js";
import "./logging-DbUpYaKc.js";
import "./accounts-Grk0tpBF.js";
import "./paths-DeB-Vw2o.js";
import "./tool-images-BotO6WKu.js";
import "./redact-AS2CBwfj.js";
import "./tool-display-DcE_Uu-6.js";
import "./deliver-DaqlX5n9.js";
import "./dispatcher-CvOxCTiO.js";
import "./dist-Cldz93r6.js";
import "./pi-tool-definition-adapter-Bm-MOj6J.js";
import "./manager-M02jv6fr.js";
import "./sqlite-ciTubP4r.js";
import "./warnings-WXNLPyeJ.js";
import "./proxy-from-env-CZI-BeJ4.js";
import "./login-qr-jct4RHB3.js";
import "./channel-summary-CaRm5ceF.js";
import "./device-identity-Bb4mQJBL.js";
import "./net-CgTtDqcj.js";
import "./call-CJHT-9_x.js";
import "./koi-events-mTBifGCl.js";
import "./pairing-store-C3Jk-2f9.js";
import "./links-RRRDj3kH.js";
import "./progress-DpXGZ7eP.js";
import "./node-pairing-C8IUm3Xm.js";
import "./pi-tools.policy-C2-uMacJ.js";
import "./onboard-helpers-BfbPZ2qa.js";
import "./prompt-style-VlLGOsyw.js";
import "./pairing-labels-gxX2Garz.js";
import "./satisfies-Bvl3f_kk.js";
import "./session-cost-usage-C1dZUsv0.js";
import "./control-service-Deb7vSlB.js";
import "./channel-selection-C4X4L8u3.js";
import "./event-log-Bp_kcsW9.js";
import "./deps-C09ak7pX.js";
import "./tailscale-B9nalljD.js";
import { t as loadDotEnv } from "./dotenv-2TPorV-O.js";
import { t as ensureSKYKOICliOnPath } from "./path-env-DGypuWGK.js";
import { g as assertSupportedRuntime } from "./daemon-runtime-DUaeQ1rH.js";
import { n as findRoutedCommand, t as ensureConfigReady } from "./config-guard-CgPeENat.js";
import "./logging-C1O4qtJt.js";
import "./note-DGDjXGAF.js";
import "./clack-prompter-CjPgjdmC.js";
import "./onboarding-Dze4vcK5.js";
import "./onboard-skills-D-hnEsDf.js";
import "./github-copilot-auth-CGviv7_I.js";
import "./onboard-channels-2nIi5fQi.js";
import "./plugin-auto-enable-CAaRgRRA.js";
import "./archive-DfyrMWmh.js";
import "./skill-scanner-oZNfZVUO.js";
import "./installs-zbov_HlD.js";
import "./health-format-wLPqgHrB.js";
import "./update-runner-B6m4iwFl.js";
import "./auth-oGq4xOCr.js";
import "./audit-CfOfhgP7.js";
import "./table-3qkY6e1T.js";
import "./skills-status-DuDN8c7D.js";
import "./service-CYp-ZMZO.js";
import "./systemd-BwrS2WmZ.js";
import "./service-audit-CtA-SSNX.js";
import "./node-service-CMlPSxKk.js";
import "./channels-status-issues-DBv-Cc4W.js";
import { a as getCommandPath, c as getPrimaryCommand, d as hasHelpOrVersion } from "./register.subclis-DG_bEdS6.js";
import "./gateway-rpc-CyFabm9F.js";
import "./help-format-lN5-Ns06.js";
import "./admin-unlock-kahk3vPh.js";
import "./koi-C6i0qbe-.js";
import { t as ensurePluginRegistryLoaded } from "./plugin-registry-ChZmVClb.js";
import "./configure-DUPDTU69.js";
import "./systemd-linger-Dppl0X6M.js";
import "./widearea-dns-BV1FENWO.js";
import "./bonjour-discovery-BSmdJTHl.js";
import "./auth-health-B3BNAX3f.js";
import "./doctor-ujPSl1VX.js";
import "./completion-cli-CmOg_YSa.js";
import "./hooks-status-BeE0Lo6_.js";
import { n as emitCliBanner } from "./tui-BPKuWU22.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-Bl7ooJiH.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-CmBbN0eq.js").then((n) => n.n);
			isLoggedIn = !!(await readAuthFile())?.token;
		} catch {}
		let defaultCommand = isLoggedIn ? "chat" : "tui";
		if (!isLoggedIn) try {
			const { isFreshInstall, canPromptInteractively, runFirstRunWelcome } = await import("./first-run-ELkFSgtJ.js");
			if (isFreshInstall(isLoggedIn) && canPromptInteractively()) {
				const choice = await runFirstRunWelcome();
				if (choice === null) return;
				if (choice === "admin") {
					const { adminUnlockCommand } = await import("./admin-unlock-kahk3vPh.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-DG_bEdS6.js").then((n) => n.i);
		await registerSubCliByName(program, primary);
	}
	if (!(!primary && hasHelpOrVersion(parseArgv))) {
		const { registerPluginCliCommands } = await import("./cli-S5Qe17qA.js");
		const { loadConfig } = await import("./config-CJCyYQfd.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 };