import "./paths-mmi2xb99.js";
import { c as defaultRuntime, r as enableConsoleCapture } from "./subsystem-D4e4nOE7.js";
import { d as resolveConfigDir } from "./utils-DLd4fFd2.js";
import "./boolean-Djq1Hgv8.js";
import { r as normalizeEnv, t as isTruthyEnvValue } from "./env-Bdq5Y-tD.js";
import { D as formatUncaughtError } from "./chrome-CpAaM-7H.js";
import "./is-main-BM4C4Apw.js";
import "./brew-Ds23pxcL.js";
import { t as ensureEdwinPAICliOnPath } from "./path-env-CRhwhQ1c.js";
import { t as assertSupportedRuntime } from "./runtime-guard-DD5U3rmV.js";
import { br as installUnhandledRejectionHandler } from "./loader-nlcizznp.js";
import "./logging-BdXz5wtj.js";
import { i as getCommandPath, s as getPrimaryCommand, u as hasHelpOrVersion } from "./register.subclis-D7CAc31a.js";
import { I as VERSION } from "./config-C9wUwpYY.js";
import { i as emitCliBanner, n as findRoutedCommand, t as ensureConfigReady } from "./config-guard-czS2xVVk.js";
import "./agent-scope-BcV171ci.js";
import "./exec-B_ziy0Fn.js";
import "./edwinpai-root-BaNzp4sP.js";
import "./model-selection-ChysOie6.js";
import "./github-copilot-token-D-EydSr2.js";
import "./command-format-XQlUKdf6.js";
import "./manifest-registry-DThGPzHr.js";
import "./internal-Ft2bMMnL.js";
import "./files-C_lcxjDi.js";
import "./client-FZxVEb3g.js";
import "./tailnet-CsQPCZBE.js";
import "./call-Dm_M_SfO.js";
import "./message-channel-eeeqF-J8.js";
import "./ws-ld1ms-Ht.js";
import "./sandbox-B_7wnPz0.js";
import "./deliver-Ce4muAXi.js";
import "./plugins-D_f06tiR.js";
import "./accounts-Blm-CSIN.js";
import "./dispatcher-kTQZ3t7n.js";
import "./pi-model-discovery-DZFI_e0Z.js";
import "./routes-CHh8zZx-.js";
import "./pi-embedded-helpers-Hus0BP0L.js";
import "./skills-B9WXNmn5.js";
import "./server-context-CdZ_-Xj5.js";
import "./ports-SUg8rnQx.js";
import "./paths-1OcM9YBo.js";
import "./image-yOVg03mb.js";
import "./exec-approvals-K3ABdHGm.js";
import "./nodes-screen-24Fv30p2.js";
import "./redact-DbMu650y.js";
import "./tool-display-D8xZqYsu.js";
import "./control-service-DYqjNgPG.js";
import "./restart-sentinel-DkbwzVUl.js";
import "./channel-selection-BXORBOHN.js";
import "./channel-summary-xp5M-jlo.js";
import "./commands-Bl1f7vmP.js";
import "./pairing-store-F36xrrvf.js";
import "./login-qr-DWYOkTgz.js";
import "./links-DlcX3SnL.js";
import "./progress-D4tnjzku.js";
import { n as ensurePluginRegistryLoaded } from "./command-options-By5yFv1a.js";
import "./helpers-XH2J9KRX.js";
import "./onboard-helpers-BArU1Ks-.js";
import "./note-BmwttIJ8.js";
import "./clack-prompter-CAZu6UVa.js";
import "./onboarding-CcpOoI2d.js";
import "./onboard-skills-BqrGuDv7.js";
import "./onboard-channels-B_O2u1kZ.js";
import "./shared-DsNlV7x3.js";
import "./wsl-BxK-Spqg.js";
import "./plugin-auto-enable-CAYA2jY0.js";
import "./archive-UFoXv0sh.js";
import "./installs-C0iwT6hr.js";
import "./health-format-DTWwS6zi.js";
import "./update-runner-BCjl92Go.js";
import "./tailscale-jmgId34Y.js";
import "./net-V2OLvHbo.js";
import "./auth-CySi9sC4.js";
import "./audit-DcTWNaLK.js";
import "./table-CTqUON-t.js";
import "./skills-status-CjdifZyI.js";
import "./service-BXV5WdCs.js";
import "./systemd-B3oVOU-l.js";
import "./service-audit-taH0ebK-.js";
import "./node-service-DnDJ49mK.js";
import "./channels-status-issues-DgPHxqCU.js";
import "./status.update-D9eAu2de.js";
import "./gateway-rpc-Dw0OsDV7.js";
import "./help-format-ph1z7eHo.js";
import "./deps-BygaPoRm.js";
import "./agent-yboWdGCD.js";
import "./configure-Trjv6X0t.js";
import "./daemon-runtime-C0L3ZZ7l.js";
import "./service-env-BwW73jih.js";
import "./systemd-linger-CeRc1hOc.js";
import "./widearea-dns-BvuXu7AL.js";
import "./auth-health-D7TxGNjl.js";
import "./doctor-DvQlQAjz.js";
import "./completion-cli-nlw31mEs.js";
import "./systemd-hints-uRWaROC9.js";
import "./hooks-status-BnBA7R7I.js";
import "./tui-BeUMXiYC.js";
import "./auth-token-DMp3C907.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-GsUoS2Sf.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-E_Nqy5cF.js");
		await registerSubCliByName(program, primary);
	}
	if (!(!primary && hasHelpOrVersion(parseArgv))) {
		const { registerPluginCliCommands } = await import("./cli-BcHbu45b.js");
		const { loadConfig } = await import("./config-DpZUcn1-.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 };