import "./paths-mmi2xb99.js";
import "./globals-D5pM_phR.js";
import { d as resolveConfigDir } from "./utils-3Lue6wVm.js";
import { c as defaultRuntime, r as enableConsoleCapture } from "./subsystem-_lp1q2Mi.js";
import "./boolean-BhvV-zDA.js";
import { r as normalizeEnv, t as isTruthyEnvValue } from "./env-aEqmsXHj.js";
import { D as formatUncaughtError } from "./chrome-7Zn7OYzP.js";
import "./is-main-DkmOEL5_.js";
import "./brew-B4JBRY5K.js";
import { t as ensureEdwinPAICliOnPath } from "./path-env-1UqReFRd.js";
import { t as assertSupportedRuntime } from "./runtime-guard-taA7D64B.js";
import { kr as installUnhandledRejectionHandler } from "./loader-364nXh92.js";
import "./logging-D4aavsm_.js";
import { i as getCommandPath, s as getPrimaryCommand, u as hasHelpOrVersion } from "./register.subclis-Dbev_opC.js";
import { I as VERSION } from "./config-VoJVjSgT.js";
import { i as emitCliBanner, n as findRoutedCommand, t as ensureConfigReady } from "./config-guard-DnQ7spuS.js";
import "./agent-scope-u760_XKU.js";
import "./exec-NeyMP-Tl.js";
import "./edwinpai-root-fGTEvnPp.js";
import "./model-selection-CMHF17-l.js";
import "./github-copilot-token-Bu-iLSUh.js";
import "./command-format-D8drL8c2.js";
import "./manifest-registry-Cobl4jxs.js";
import "./access-policy-Bz60GPHK.js";
import "./backend-config-CnwghGiS.js";
import "./public-policy-BcsEQrNF.js";
import "./internal-C9ERe0oQ.js";
import "./files-C9aOMd12.js";
import "./client-BdG39O7o.js";
import "./tailnet-D1VxJifZ.js";
import "./call-BuuyfSRn.js";
import "./message-channel-B4I_vLJb.js";
import "./ws-CvzJ5P1j.js";
import "./sandbox-Cnho92pr.js";
import "./deliver-CDl0wl5Y.js";
import "./plugins-B3jBOs5H.js";
import "./accounts-DmCFbO1K.js";
import "./dispatcher-Bo-53pRv.js";
import "./pi-model-discovery-DU5m2tTc.js";
import "./routes--IwjIOyE.js";
import "./pi-embedded-helpers-bcXOORS6.js";
import "./skills-DMXslih8.js";
import "./server-context-CysGziRI.js";
import "./ports-CgQyR_CW.js";
import "./paths-CzSw2xi4.js";
import "./image-Behi5-Q5.js";
import "./exec-approvals-HMeMyfFd.js";
import "./nodes-screen-BCmLkGEF.js";
import "./redact-DKKIzZKH.js";
import "./tool-display-CEyvKqx1.js";
import "./control-service-BCE6PKvq.js";
import "./restart-sentinel-V09ETbcM.js";
import "./channel-selection-nnjP4eS9.js";
import "./channel-summary-b-OepsoT.js";
import "./commands-CYbojHvd.js";
import "./pairing-store-BHWTx_J7.js";
import "./login-qr-C0aXNPXR.js";
import "./links-BKmnIRTU.js";
import "./progress-DIssriZ5.js";
import { n as ensurePluginRegistryLoaded } from "./command-options-r41gHMe0.js";
import "./helpers-C7AMac6B.js";
import "./onboard-helpers-CSsQgmZN.js";
import "./note-B0WhCXlw.js";
import "./clack-prompter-CwHL0EGc.js";
import "./agents.config-BoatZ0qi.js";
import "./onboard-skills-CoK0dkQn.js";
import "./onboard-channels-Del21pjv.js";
import "./shared-BKEXeTXq.js";
import "./wsl-BFoXHNBM.js";
import "./plugin-auto-enable-oOj_liKU.js";
import "./archive-wBMTPd1d.js";
import "./installs-BC5L3cvh.js";
import "./health-format-C1q5vlEI.js";
import "./update-runner-DOoc5PX2.js";
import "./onboarding-bCbVdsAe.js";
import "./tailscale-9brshfui.js";
import "./net-BImkhihx.js";
import "./auth-DQvzz4Ac.js";
import "./audit-C9c7n4Gt.js";
import "./table-tCr5riS6.js";
import "./skills-status-BdfabRbZ.js";
import "./service-BssQxmRt.js";
import "./systemd-pzbs8ZOA.js";
import "./service-audit-Dvc0hKtz.js";
import "./node-service-DanQ7J9k.js";
import "./channels-status-issues-CbhkLB9h.js";
import "./status.update-fpLgJ3ZG.js";
import "./gateway-rpc-DDaEENUI.js";
import "./help-format-BhVuFSZT.js";
import "./disciplines-9fVGWq-P.js";
import "./deps-BDkDEJDb.js";
import "./agent-AE36cAfG.js";
import "./configure-ix33PxpS.js";
import "./daemon-runtime-CEk_30Dc.js";
import "./service-env-BnMzE8Cz.js";
import "./systemd-linger-B_hlqS-Z.js";
import "./widearea-dns-BnBAD9pa.js";
import "./auth-health-953re2h8.js";
import "./doctor-BkGVznVe.js";
import "./completion-cli-B_rAu7gA.js";
import "./systemd-hints-CzgT_W5U.js";
import "./response-EhRrUCse.js";
import "./shared-CdxZFobZ.js";
import "./runners-tzpWaOR5.js";
import "./status-J7E8eYs2.js";
import "./hooks-status-TRRghkID.js";
import "./tui-N6eeHe7P.js";
import "./auth-token-DdM6zbgB.js";
import fs from "node:fs";
import path from "node:path";
import process$1 from "node:process";
import { fileURLToPath } from "node:url";
import dotenv from "dotenv";

//#region ../../src/infra/dotenv.ts
function loadDotEnv(opts) {
	const quiet = opts?.quiet ?? true;
	dotenv.config({ quiet });
	const globalEnvPath = path.join(resolveConfigDir(process.env), ".env");
	if (!fs.existsSync(globalEnvPath)) return;
	dotenv.config({
		quiet,
		path: globalEnvPath,
		override: false
	});
}

//#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.EDWINPAI_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;
}
async function runCli(argv = process$1.argv) {
	const normalizedArgv = stripWindowsNodeExec(argv);
	loadDotEnv({ quiet: true });
	normalizeEnv();
	ensureEdwinPAICliOnPath();
	assertSupportedRuntime();
	if (await tryRouteCli(normalizedArgv)) return;
	enableConsoleCapture();
	const { buildProgram } = await import("./program-Dl1xDp8M.js");
	const program = buildProgram();
	installUnhandledRejectionHandler();
	process$1.on("uncaughtException", (error) => {
		console.error("[edwinpai] Uncaught exception:", formatUncaughtError(error));
		process$1.exit(1);
	});
	const parseArgv = rewriteUpdateFlagArgv(normalizedArgv);
	const primary = getPrimaryCommand(parseArgv);
	if (primary) {
		const { registerSubCliByName } = await import("./register.subclis-D3bL53hf.js");
		await registerSubCliByName(program, primary);
	}
	if (!(!primary && hasHelpOrVersion(parseArgv))) {
		const { registerPluginCliCommands } = await import("./cli-dWFsXn1M.js");
		const { loadConfig } = await import("./config-BBUIIDK-.js");
		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 };