import { c as normalizeWindowsArgv, f as hasHelpOrVersion, l as getCommandPath, n as normalizeEnv, t as isTruthyEnvValue, u as getPrimaryCommand } from "./entry.js";
import "./theme-DrO_HVcw.js";
import { t as VERSION } from "./version-BcB7HG3l.js";
import { n as resolveCliName, r as emitCliBanner } from "./cli-name-Ba7MOCpZ.js";
import { spawn } from "node:child_process";
import process$1 from "node:process";
import fs from "node:fs";
import os, { homedir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";

//#region src/infra/brew.ts
function normalizePathValue(value) {
	if (typeof value !== "string") return;
	const trimmed = value.trim();
	return trimmed ? trimmed : void 0;
}
function resolveBrewPathDirs(opts) {
	const homeDir = opts?.homeDir ?? os.homedir();
	const env = opts?.env ?? process.env;
	const dirs = [];
	const prefix = normalizePathValue(env.HOMEBREW_PREFIX);
	if (prefix) dirs.push(path.join(prefix, "bin"), path.join(prefix, "sbin"));
	dirs.push(path.join(homeDir, ".linuxbrew", "bin"));
	dirs.push(path.join(homeDir, ".linuxbrew", "sbin"));
	dirs.push("/home/linuxbrew/.linuxbrew/bin", "/home/linuxbrew/.linuxbrew/sbin");
	dirs.push("/opt/homebrew/bin", "/usr/local/bin");
	return dirs;
}

//#endregion
//#region src/infra/path-env.ts
function isExecutable(filePath) {
	try {
		fs.accessSync(filePath, fs.constants.X_OK);
		return true;
	} catch {
		return false;
	}
}
function isDirectory(dirPath) {
	try {
		return fs.statSync(dirPath).isDirectory();
	} catch {
		return false;
	}
}
function mergePath(params) {
	const partsExisting = params.existing.split(path.delimiter).map((part) => part.trim()).filter(Boolean);
	const partsPrepend = (params.prepend ?? []).map((part) => part.trim()).filter(Boolean);
	const partsAppend = (params.append ?? []).map((part) => part.trim()).filter(Boolean);
	const seen = /* @__PURE__ */ new Set();
	const merged = [];
	for (const part of [
		...partsPrepend,
		...partsExisting,
		...partsAppend
	]) if (!seen.has(part)) {
		seen.add(part);
		merged.push(part);
	}
	return merged.join(path.delimiter);
}
function candidateBinDirs(opts) {
	const execPath = opts.execPath ?? process.execPath;
	const cwd = opts.cwd ?? process.cwd();
	const homeDir = opts.homeDir ?? os.homedir();
	const platform = opts.platform ?? process.platform;
	const prepend = [];
	const append = [];
	try {
		const execDir = path.dirname(execPath);
		if (isExecutable(path.join(execDir, "openclaw"))) prepend.push(execDir);
	} catch {}
	if (opts.allowProjectLocalBin === true || isTruthyEnvValue(process.env.OPENCLAW_ALLOW_PROJECT_LOCAL_BIN)) {
		const localBinDir = path.join(cwd, "node_modules", ".bin");
		if (isExecutable(path.join(localBinDir, "openclaw"))) append.push(localBinDir);
	}
	const miseDataDir = process.env.MISE_DATA_DIR ?? path.join(homeDir, ".local", "share", "mise");
	const miseShims = path.join(miseDataDir, "shims");
	if (isDirectory(miseShims)) prepend.push(miseShims);
	prepend.push(...resolveBrewPathDirs({ homeDir }));
	if (platform === "darwin") prepend.push(path.join(homeDir, "Library", "pnpm"));
	if (process.env.XDG_BIN_HOME) prepend.push(process.env.XDG_BIN_HOME);
	prepend.push(path.join(homeDir, ".local", "bin"));
	prepend.push(path.join(homeDir, ".local", "share", "pnpm"));
	prepend.push(path.join(homeDir, ".bun", "bin"));
	prepend.push(path.join(homeDir, ".yarn", "bin"));
	prepend.push("/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin");
	return {
		prepend: prepend.filter(isDirectory),
		append: append.filter(isDirectory)
	};
}
/**
* Best-effort PATH bootstrap so skills that require the `openclaw` CLI can run
* under launchd/minimal environments (and inside the macOS app bundle).
*/
function ensureOpenClawCliOnPath(opts = {}) {
	if (isTruthyEnvValue(process.env.OPENCLAW_PATH_BOOTSTRAPPED)) return;
	process.env.OPENCLAW_PATH_BOOTSTRAPPED = "1";
	const existing = opts.pathEnv ?? process.env.PATH ?? "";
	const { prepend, append } = candidateBinDirs(opts);
	if (prepend.length === 0 && append.length === 0) return;
	const merged = mergePath({
		existing,
		prepend,
		append
	});
	if (merged) process.env.PATH = merged;
}

//#endregion
//#region src/infra/runtime-guard.ts
const MIN_NODE_MAJOR = 22;
const MIN_NODE_MINOR = 12;
function parseNodeVersion(version) {
	const [majorRaw = "0", minorRaw = "0"] = version.split(".");
	return {
		major: Number.parseInt(majorRaw, 10) || 0,
		minor: Number.parseInt(minorRaw, 10) || 0
	};
}
function assertSupportedRuntime() {
	const { major, minor } = parseNodeVersion(process.versions.node);
	if (major < MIN_NODE_MAJOR || major === MIN_NODE_MAJOR && minor < MIN_NODE_MINOR) throw new Error(`DenchClaw requires Node ${MIN_NODE_MAJOR}.${MIN_NODE_MINOR}+ (current: ${process.versions.node}).`);
}

//#endregion
//#region src/cli/run-main.ts
/**
* Returns a guaranteed-valid working directory for the spawned child. When the
* current process's cwd has been deleted (tmp dirs, deleted project folders),
* `process.cwd()` throws ENOENT and the spawned Node.js child crashes before
* it can do anything useful. Falling back to the user's home dir prevents that.
*/
function safeChildCwd() {
	try {
		return process$1.cwd();
	} catch {
		return homedir();
	}
}
function rewriteUpdateFlagArgv(argv) {
	const index = argv.indexOf("--update");
	if (index === -1) return argv;
	const next = [...argv];
	next.splice(index, 1, "update");
	return next;
}
function shouldEnsureCliPath(argv) {
	if (hasHelpOrVersion(argv)) return false;
	const [primary, secondary] = getCommandPath(argv, 2);
	if (!primary) return true;
	if (primary === "status" || primary === "health" || primary === "sessions") return false;
	if (primary === "config" && (secondary === "get" || secondary === "unset")) return false;
	if (primary === "models" && (secondary === "list" || secondary === "status")) return false;
	return true;
}
function isBareDenchclawInvocation(argv) {
	if (hasHelpOrVersion(argv)) return false;
	if (getPrimaryCommand(argv)) return false;
	return resolveCliName(argv) === "denchclaw";
}
function isDelegationDisabled(env = process$1.env) {
	return isTruthyEnvValue(env.DENCHCLAW_DISABLE_OPENCLAW_DELEGATION) || isTruthyEnvValue(env.OPENCLAW_DISABLE_OPENCLAW_DELEGATION);
}
function shouldDelegateToGlobalOpenClaw(argv, env = process$1.env) {
	if (isDelegationDisabled(env)) return false;
	const primary = getPrimaryCommand(argv);
	if (!primary) return false;
	return primary !== "bootstrap" && primary !== "update" && primary !== "stop" && primary !== "start" && primary !== "restart" && primary !== "telemetry";
}
function shouldHideCliBanner(argv, env = process$1.env) {
	const commandPath = getCommandPath(argv, 2);
	return isTruthyEnvValue(env.DENCHCLAW_HIDE_BANNER) || isTruthyEnvValue(env.OPENCLAW_HIDE_BANNER) || commandPath[0] === "completion" || commandPath[0] === "plugins" && commandPath[1] === "update";
}
async function delegateToGlobalOpenClaw(argv) {
	if (isTruthyEnvValue(process$1.env.DENCHCLAW_DELEGATED) || isTruthyEnvValue(process$1.env.OPENCLAW_DELEGATED)) throw new Error("OpenClaw delegation loop detected. Check PATH so `openclaw` resolves to the global OpenClaw CLI.");
	const delegatedArgv = argv.slice(2);
	return await new Promise((resolve, reject) => {
		const child = spawn("openclaw", delegatedArgv, {
			stdio: "inherit",
			cwd: safeChildCwd(),
			env: {
				...process$1.env,
				DENCHCLAW_DELEGATED: "1",
				OPENCLAW_DELEGATED: "1"
			},
			...process$1.platform === "win32" ? {
				shell: true,
				windowsHide: true
			} : {}
		});
		child.once("error", (error) => {
			if (error?.code === "ENOENT") {
				reject(new Error(["Global `openclaw` CLI was not found on PATH.", "Install it once with: npm install -g openclaw"].join("\n")));
				return;
			}
			reject(error);
		});
		child.once("exit", (code, signal) => {
			if (signal) {
				resolve(1);
				return;
			}
			resolve(code ?? 1);
		});
	});
}
async function runCli(argv = process$1.argv) {
	const normalizedArgv = normalizeWindowsArgv(argv);
	normalizeEnv();
	if (shouldEnsureCliPath(normalizedArgv)) ensureOpenClawCliOnPath();
	assertSupportedRuntime();
	if (!shouldHideCliBanner(normalizedArgv, process$1.env)) await emitCliBanner(VERSION, { argv: normalizedArgv });
	if (isBareDenchclawInvocation(normalizedArgv)) {
		const { runDenchCloudWelcome } = await import("./dench-cloud-welcome-DNcvMuhx.js");
		await runDenchCloudWelcome();
		return;
	}
	const parseArgv = rewriteUpdateFlagArgv(normalizedArgv);
	if (shouldDelegateToGlobalOpenClaw(parseArgv)) {
		process$1.exitCode = await delegateToGlobalOpenClaw(parseArgv);
		return;
	}
	const { buildProgram } = await import("./program-yr1JFZ6t.js");
	await buildProgram().parseAsync(parseArgv);
}

//#endregion
export { runCli };