#!/usr/bin/env node
import { m as readNonBlankString } from "./string-coerce-CIXf7egm.js";
import { i as normalizeEnv, n as isTruthyEnvValue } from "./env-DDC-EStD.js";
import { r as getCommandPositionalsWithRootOptions } from "./cli-root-options-CpQG4BXe.js";
import { n as getCommandPathWithRootOptions, u as isRootHelpInvocation } from "./argv-DpiTmsER.js";
import { t as resolveCliArgvInvocation } from "./argv-invocation-CDnnGWCE.js";
import { r as defaultRuntime } from "./runtime-LRpY2Icg.js";
import { n as requestExitAfterOneShotOutput, r as runCliWithExitFinalization } from "./one-shot-exit-IDgc-qbq.js";
import { n as installDistEsmResolveFastPath, t as tryHandleRootVersionFastPath } from "./entry.version-fast-path-DQ-a0W-X.js";
import { n as parseCliContainerArgs, r as resolveCliContainerTarget } from "./container-target-CGwc-Jul.js";
import { t as isMainModule } from "./is-main-CH4EEB_R.js";
import { a as tryOutputPrecomputedCommandHelp, i as parseCliProfileArgs, n as createGatewayDispatchStartupTrace, r as applyCliProfileEnv, t as configureGatewayStartupTraceConsoleFormatting } from "./startup-trace-BzUI7Tyz.js";
import { t as normalizeWindowsArgv } from "./windows-argv-Dl7Refj1.js";
import { t as attachChildProcessBridge } from "./child-process-bridge-CFJsa4sQ.js";
import { n as signalProcessTree } from "./kill-tree-CR2oLt9D.js";
import { t as resolveNodeStartupTlsEnvironment } from "./node-startup-env-C5ZHYlJG.js";
import { n as ensureOpenClawExecMarkerOnProcess } from "./openclaw-exec-env-BmbZ1aqS.js";
import { t as installProcessWarningFilter } from "./warning-filter-z3hZGeVP.js";
import { enableCompileCache, getCompileCacheDir } from "node:module";
import process$1 from "node:process";
import { fileURLToPath } from "node:url";
import { existsSync, readFileSync, statSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { format as format$1 } from "node:util";
//#region src/cli/respawn-policy.ts
const GATEWAY_RUN_BOOLEAN_FLAGS = [
	"--allow-unconfigured",
	"--claude-cli-logs",
	"--cli-backend-logs",
	"--compact",
	"--dev",
	"--force",
	"--raw-stream",
	"--reset",
	"--tailscale-reset-on-exit",
	"--verbose"
];
const GATEWAY_RUN_VALUE_FLAGS = [
	"--auth",
	"--bind",
	"--password",
	"--password-file",
	"--port",
	"--raw-stream-path",
	"--tailscale",
	"--token",
	"--ws-log"
];
const INTERACTIVE_TTY_COMMANDS = /* @__PURE__ */ new Set([
	"tui",
	"terminal",
	"chat"
]);
/** Gmail owns a shutdown grace period longer than the generic respawn wrapper allows. */
function isForegroundGmailRunArgv(argv) {
	return getCommandPathWithRootOptions(argv, 3).join(" ") === "webhooks gmail run";
}
function isNativeHookRelayArgv(argv) {
	const { commandPath } = resolveCliArgvInvocation(argv);
	return commandPath[0] === "hooks" && commandPath[1] === "relay";
}
function shouldKeepNativeHookRelayInProcess(argv, platform) {
	return platform !== "win32" && isNativeHookRelayArgv(argv);
}
function isInteractiveTtyCommandArgv(argv) {
	const invocation = resolveCliArgvInvocation(argv);
	return invocation.primary !== null && INTERACTIVE_TTY_COMMANDS.has(invocation.primary);
}
function isTerminalInteractiveRespawnArgv(argv) {
	const invocation = resolveCliArgvInvocation(argv);
	if (invocation.hasHelpOrVersion) return false;
	return invocation.primary === null || INTERACTIVE_TTY_COMMANDS.has(invocation.primary);
}
function isForegroundGatewayRunArgv(argv) {
	const positionals = getCommandPositionalsWithRootOptions(argv, {
		commandPath: ["gateway"],
		booleanFlags: GATEWAY_RUN_BOOLEAN_FLAGS,
		valueFlags: GATEWAY_RUN_VALUE_FLAGS
	});
	if (!positionals) return false;
	return positionals.length === 0 || positionals.length === 1 && positionals[0] === "run";
}
/** Returns whether CLI startup should avoid the general respawn wrapper for this argv. */
function shouldSkipRespawnForArgv(argv, platform = process.platform) {
	const invocation = resolveCliArgvInvocation(argv);
	const isGatewayStatus = invocation.commandPath.length === 2 && invocation.commandPath[0] === "gateway" && invocation.commandPath[1] === "status";
	return invocation.hasHelpOrVersion || isInteractiveTtyCommandArgv(argv) || isForegroundGmailRunArgv(argv) || shouldKeepNativeHookRelayInProcess(argv, platform) || isGatewayStatus || invocation.primary === "gateway" && isForegroundGatewayRunArgv(argv);
}
/** Returns whether startup-environment respawn should be skipped without suppressing TUI respawn policy. */
function shouldSkipStartupEnvironmentRespawnForArgv(argv, platform = process.platform) {
	const invocation = resolveCliArgvInvocation(argv);
	return invocation.hasHelpOrVersion || isForegroundGmailRunArgv(argv) || shouldKeepNativeHookRelayInProcess(argv, platform) || invocation.primary === "gateway" && isForegroundGatewayRunArgv(argv);
}
//#endregion
//#region src/process/respawn-child-runner.ts
const RESPAWN_SIGNAL_EXIT_GRACE_MS = 1e3;
const RESPAWN_SIGNAL_FORCE_KILL_GRACE_MS = 1e3;
const RESPAWN_SIGNAL_HARD_EXIT_GRACE_MS = 1e3;
function runRespawnChildWithSignalBridge(params) {
	const { command, args, env, runtime, onError } = params;
	const stdioIsTerminal = params.stdioIsTerminal ?? (process.stdin.isTTY || process.stdout.isTTY);
	const detachForProcessTree = params.detachForProcessTree === true && process.platform !== "win32" && !stdioIsTerminal;
	const child = runtime.spawn(command, args, {
		stdio: "inherit",
		env,
		detached: detachForProcessTree
	});
	let signalExitTimer;
	let signalForceKillTimer;
	let signalHardExitTimer;
	let parentSignalReceived = false;
	let firstForwardedSignal;
	let hardKillBackstopStarted = false;
	const clearSignalTimers = () => {
		if (signalExitTimer) {
			clearTimeout(signalExitTimer);
			signalExitTimer = void 0;
		}
		if (signalForceKillTimer) {
			clearTimeout(signalForceKillTimer);
			signalForceKillTimer = void 0;
		}
		if (signalHardExitTimer) {
			clearTimeout(signalHardExitTimer);
			signalHardExitTimer = void 0;
		}
	};
	const signalChild = (signal) => {
		if (detachForProcessTree && typeof child.pid === "number" && child.pid > 0) {
			signalProcessTree(child.pid, signal, { detached: true });
			return;
		}
		child.kill(signal === "SIGKILL" && process.platform === "win32" ? "SIGTERM" : signal);
	};
	const forceKillChild = () => {
		try {
			signalChild("SIGKILL");
		} catch {}
	};
	const requestChildTermination = () => {
		try {
			signalChild("SIGTERM");
		} catch {}
		signalForceKillTimer = setTimeout(() => {
			hardKillBackstopStarted = true;
			forceKillChild();
			signalHardExitTimer = setTimeout(() => {
				runtime.exit(1);
			}, RESPAWN_SIGNAL_HARD_EXIT_GRACE_MS);
			signalHardExitTimer.unref?.();
		}, RESPAWN_SIGNAL_FORCE_KILL_GRACE_MS);
		signalForceKillTimer.unref?.();
	};
	const scheduleParentExit = (signal) => {
		parentSignalReceived = true;
		firstForwardedSignal ??= signal;
		if (signalExitTimer) return;
		signalExitTimer = setTimeout(() => {
			requestChildTermination();
		}, RESPAWN_SIGNAL_EXIT_GRACE_MS);
		signalExitTimer.unref?.();
	};
	runtime.attachChildProcessBridge(child, { onSignal: scheduleParentExit });
	child.once("exit", (code, signal) => {
		if (parentSignalReceived && detachForProcessTree) forceKillChild();
		clearSignalTimers();
		if (signal) {
			const forwardedSignalExitCode = !hardKillBackstopStarted && signal === firstForwardedSignal ? signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : void 0 : void 0;
			runtime.exit(forwardedSignalExitCode ?? 1);
			return;
		}
		runtime.exit(code ?? 1);
	});
	child.on("error", (error) => {
		if (child.pid !== void 0) return;
		clearSignalTimers();
		onError(error);
		runtime.exit(1);
	});
	return child;
}
//#endregion
//#region src/entry.compile-cache.ts
const COMPILE_CACHE_DISABLED_RESPAWNED_ENV = "OPENCLAW_COMPILE_CACHE_DISABLED_RESPAWNED";
function resolveEntryInstallRoot(entryFile) {
	const entryDir = path.dirname(entryFile);
	const entryParent = path.basename(entryDir);
	return entryParent === "dist" || entryParent === "src" ? path.dirname(entryDir) : entryDir;
}
function isSourceCheckoutInstallRoot(installRoot) {
	return existsSync(path.join(installRoot, ".git")) || existsSync(path.join(installRoot, "src", "entry.ts"));
}
function isNodeCompileCacheDisabled(env) {
	return env?.NODE_DISABLE_COMPILE_CACHE !== void 0;
}
function isNodeCompileCacheRequested(env) {
	return env?.NODE_COMPILE_CACHE !== void 0 && !isNodeCompileCacheDisabled(env);
}
function shouldEnableOpenClawCompileCache(params) {
	return !isNodeCompileCacheDisabled(params.env) && !isSourceCheckoutInstallRoot(params.installRoot);
}
function sanitizeCompileCachePathSegment(value) {
	const normalized = value.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
	return normalized.length > 0 ? normalized : "unknown";
}
function readPackageVersion(packageJsonPath) {
	try {
		const parsed = JSON.parse(readFileSync(packageJsonPath, "utf8"));
		if (parsed && typeof parsed === "object" && "version" in parsed && typeof parsed.version === "string" && parsed.version.trim().length > 0) return parsed.version;
	} catch {}
	return "unknown";
}
function resolveOpenClawCompileCacheDirectory(params) {
	const env = params.env ?? process$1.env;
	const packageJsonPath = path.join(params.installRoot, "package.json");
	const version = sanitizeCompileCachePathSegment(readPackageVersion(packageJsonPath));
	let installMarker = "no-package-json";
	try {
		const stat = statSync(packageJsonPath);
		installMarker = `${Math.trunc(stat.mtimeMs)}-${stat.size}`;
	} catch {}
	const baseDirectory = env.NODE_COMPILE_CACHE && !isNodeCompileCacheDisabled(env) ? env.NODE_COMPILE_CACHE : path.join(os.tmpdir(), "node-compile-cache");
	return path.join(baseDirectory, "openclaw", version, sanitizeCompileCachePathSegment(installMarker));
}
function buildOpenClawCompileCacheRespawnPlan(params) {
	const env = params.env ?? process$1.env;
	const argv = params.argv ?? process$1.argv;
	const platform = params.platform ?? process$1.platform;
	if (isForegroundGmailRunArgv(argv) || shouldKeepNativeHookRelayInProcess(argv, platform)) return;
	if (!isSourceCheckoutInstallRoot(params.installRoot)) return;
	if (env[COMPILE_CACHE_DISABLED_RESPAWNED_ENV] === "1") return;
	if (!params.compileCacheDir && !isNodeCompileCacheRequested(env)) return;
	const nextEnv = {
		...env,
		NODE_DISABLE_COMPILE_CACHE: "1",
		[COMPILE_CACHE_DISABLED_RESPAWNED_ENV]: "1"
	};
	delete nextEnv.NODE_COMPILE_CACHE;
	return {
		command: params.execPath ?? process$1.execPath,
		args: [
			...params.execArgv ?? process$1.execArgv,
			params.currentFile,
			...argv.slice(2)
		],
		env: nextEnv,
		detachForProcessTree: platform !== "win32" && !isTerminalInteractiveRespawnArgv(argv)
	};
}
async function respawnWithoutOpenClawCompileCacheIfNeeded(params) {
	const plan = buildOpenClawCompileCacheRespawnPlan({
		currentFile: params.currentFile,
		installRoot: params.installRoot,
		compileCacheDir: getCompileCacheDir?.()
	});
	if (!plan) return false;
	const writeError = await params.prepareWriteError?.();
	runOpenClawCompileCacheRespawnPlan(plan, writeError ? {
		spawn,
		attachChildProcessBridge,
		exit: process$1.exit.bind(process$1),
		writeError
	} : void 0);
	return true;
}
function runOpenClawCompileCacheRespawnPlan(plan, runtime = {
	spawn,
	attachChildProcessBridge,
	exit: process$1.exit.bind(process$1),
	writeError: (message) => process$1.stderr.write(message)
}) {
	return runRespawnChildWithSignalBridge({
		command: plan.command,
		args: plan.args,
		env: plan.env,
		detachForProcessTree: plan.detachForProcessTree,
		runtime,
		onError: (error) => {
			runtime.writeError(`[openclaw] Failed to respawn CLI without compile cache: ${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
		}
	});
}
function enableOpenClawCompileCache(params) {
	if (!shouldEnableOpenClawCompileCache(params)) return;
	try {
		enableCompileCache(resolveOpenClawCompileCacheDirectory(params));
	} catch {}
}
if (process$1.env.VITEST || process$1.env.NODE_ENV === "test") globalThis[Symbol.for("openclaw.entryCompileCacheTestApi")] = {
	buildOpenClawCompileCacheRespawnPlan,
	isSourceCheckoutInstallRoot,
	resolveOpenClawCompileCacheDirectory,
	runOpenClawCompileCacheRespawnPlan,
	shouldEnableOpenClawCompileCache
};
//#endregion
//#region src/entry.respawn.ts
const EXPERIMENTAL_WARNING_FLAG = "--disable-warning=ExperimentalWarning";
const OPENCLAW_NODE_OPTIONS_READY = "OPENCLAW_NODE_OPTIONS_READY";
const OPENCLAW_NODE_EXTRA_CA_CERTS_READY = "OPENCLAW_NODE_EXTRA_CA_CERTS_READY";
const WINDOWS_STACK_SIZE_FLAG = "--stack-size=8192";
function pathModuleForPlatform(platform) {
	return platform === "win32" ? path.win32 : path.posix;
}
function resolveCliRespawnCommand(params) {
	const basename = pathModuleForPlatform(params.platform ?? process.platform).basename(params.execPath).toLowerCase();
	if (basename === "volta-shim" || basename === "volta-shim.exe") return "node";
	return params.execPath;
}
function hasExperimentalWarningSuppressed(params = {}) {
	const env = params.env ?? process.env;
	const execArgv = params.execArgv ?? process.execArgv;
	const nodeOptions = env.NODE_OPTIONS ?? "";
	if (nodeOptions.includes(EXPERIMENTAL_WARNING_FLAG) || nodeOptions.includes("--no-warnings")) return true;
	return execArgv.some((arg) => arg === EXPERIMENTAL_WARNING_FLAG || arg === "--no-warnings");
}
function hasStackSizeConfigured(execArgv) {
	return execArgv.some((arg) => arg === "--stack-size" || arg.startsWith("--stack-size=") || arg === "--stack_size" || arg.startsWith("--stack_size="));
}
function buildCliRespawnPlan(params = {}) {
	const argv = params.argv ?? process.argv;
	const env = params.env ?? process.env;
	const execArgv = params.execArgv ?? process.execArgv;
	const execPath = params.execPath ?? process.execPath;
	const platform = params.platform ?? process.platform;
	const normalizedArgv = platform === "win32" ? normalizeWindowsArgv(argv, {
		platform,
		execPath
	}) : argv;
	if (shouldSkipStartupEnvironmentRespawnForArgv(normalizedArgv, platform) || isTruthyEnvValue(env.OPENCLAW_NO_RESPAWN)) return null;
	const childEnv = { ...env };
	if (!readNonBlankString(childEnv.NODE_EXTRA_CA_CERTS)) delete childEnv.NODE_EXTRA_CA_CERTS;
	const childExecArgv = [...execArgv];
	let needsRespawn = false;
	if (platform === "win32") {
		if (!hasStackSizeConfigured(childExecArgv)) {
			childExecArgv.unshift(WINDOWS_STACK_SIZE_FLAG);
			needsRespawn = true;
		}
		if (!needsRespawn) return null;
		return {
			command: resolveCliRespawnCommand({
				execPath,
				platform
			}),
			argv: [...childExecArgv, ...normalizedArgv.slice(1)],
			env: childEnv,
			detachForProcessTree: false
		};
	}
	const autoNodeExtraCaCerts = params.autoNodeExtraCaCerts ?? resolveNodeStartupTlsEnvironment({
		env,
		execPath,
		includeDarwinDefaults: false
	}).NODE_EXTRA_CA_CERTS;
	if (autoNodeExtraCaCerts && !isTruthyEnvValue(env[OPENCLAW_NODE_EXTRA_CA_CERTS_READY]) && !childEnv.NODE_EXTRA_CA_CERTS) {
		childEnv.NODE_EXTRA_CA_CERTS = autoNodeExtraCaCerts;
		childEnv[OPENCLAW_NODE_EXTRA_CA_CERTS_READY] = "1";
		needsRespawn = true;
	}
	if (!shouldSkipRespawnForArgv(argv, platform) && !isTruthyEnvValue(env[OPENCLAW_NODE_OPTIONS_READY]) && !hasExperimentalWarningSuppressed({
		env,
		execArgv
	})) {
		childEnv[OPENCLAW_NODE_OPTIONS_READY] = "1";
		childExecArgv.unshift(EXPERIMENTAL_WARNING_FLAG);
		needsRespawn = true;
	}
	if (!needsRespawn) return null;
	return {
		command: resolveCliRespawnCommand({
			execPath,
			platform
		}),
		argv: [...childExecArgv, ...argv.slice(1)],
		env: childEnv,
		detachForProcessTree: !isTerminalInteractiveRespawnArgv(argv)
	};
}
function runCliRespawnPlan(plan, runtime, writeError = (message, error) => console.error(message, error)) {
	const resolvedRuntime = runtime ?? {
		spawn,
		attachChildProcessBridge,
		exit: process.exit.bind(process),
		writeError
	};
	return runRespawnChildWithSignalBridge({
		command: plan.command,
		args: plan.argv,
		env: plan.env,
		detachForProcessTree: plan.detachForProcessTree,
		runtime: resolvedRuntime,
		onError: (error) => {
			resolvedRuntime.writeError("[openclaw] Failed to respawn CLI:", error instanceof Error ? error.stack ?? error.message : error);
		}
	});
}
//#endregion
//#region src/entry.ts
const ENTRY_WRAPPER_PAIRS = [
	{
		wrapperBasename: "openclaw.mjs",
		entryBasename: "entry.js"
	},
	{
		wrapperBasename: "openclaw.mjs",
		entryBasename: "entry.mjs"
	},
	{
		wrapperBasename: "openclaw.js",
		entryBasename: "entry.js"
	}
];
const loadRootHelpLiveConfigModule = async () => await import("./root-help-live-config-DLFpCf-w.js");
const loadRootHelpMetadataModule = async () => await import("./root-help-metadata-BzTFoMx_.js");
async function writeCapturedCliArgumentError(message) {
	const { loadCliDotEnv } = await import("./dotenv-C1BZ8F4P.js");
	loadCliDotEnv({ quiet: true });
	await configureGatewayStartupTraceConsoleFormatting(gatewayEntryStartupTrace);
	const { enableConsoleCapture } = await import("./logging-CjOAus1j.js");
	enableConsoleCapture();
	const [{ formatCliJsonFailure }, { isJsonOutputModeActive }] = await Promise.all([import("./failure-output-UIlyogfI.js"), import("./json-output-mode-DCwXIqlL.js")]);
	if (isJsonOutputModeActive(process$1.argv)) defaultRuntime.writeJson(formatCliJsonFailure(message));
	console.error(`[openclaw] ${message}`);
}
async function writeCliDiagnosticBlock(message) {
	const { loadCliDotEnv } = await import("./dotenv-C1BZ8F4P.js");
	loadCliDotEnv({ quiet: true });
	await configureGatewayStartupTraceConsoleFormatting(gatewayEntryStartupTrace);
	const { formatConsoleDiagnosticBlock } = await import("./json-console-line-CNFnCOoI.js");
	process$1.stderr.write(formatConsoleDiagnosticBlock({
		level: "error",
		message: `${message}\n`
	}));
}
async function prepareCliDiagnosticBlockWriter() {
	const { loadCliDotEnv } = await import("./dotenv-C1BZ8F4P.js");
	loadCliDotEnv({ quiet: true });
	await configureGatewayStartupTraceConsoleFormatting(gatewayEntryStartupTrace);
	const { formatConsoleDiagnosticBlock } = await import("./json-console-line-CNFnCOoI.js");
	return (message, error) => {
		const formatted = error === void 0 ? message : format$1(message, error);
		process$1.stderr.write(formatConsoleDiagnosticBlock({
			level: "error",
			message: formatted.endsWith("\n") ? formatted : `${formatted}\n`
		}));
	};
}
async function flushEntryStartupTraceForEarlyReturn(argv) {
	if (!gatewayEntryStartupTrace.enabled) return;
	const { loadCliDotEnvForEarlyDiagnostic } = await import("./dotenv-C1BZ8F4P.js");
	await loadCliDotEnvForEarlyDiagnostic(argv);
	await configureGatewayStartupTraceConsoleFormatting(gatewayEntryStartupTrace);
}
function shouldForceReadOnlyAuthStore(argv) {
	const tokens = argv.slice(2).filter((token) => token.length > 0 && !token.startsWith("-"));
	for (let index = 0; index < tokens.length - 1; index += 1) if (tokens[index] === "secrets" && tokens[index + 1] === "audit") return true;
	return false;
}
const gatewayEntryStartupTrace = createGatewayDispatchStartupTrace(process$1.argv, "entry");
if (!isMainModule({
	currentFile: fileURLToPath(import.meta.url),
	wrapperEntryPairs: [...ENTRY_WRAPPER_PAIRS]
})) {} else {
	const entryFile = fileURLToPath(import.meta.url);
	const installRoot = resolveEntryInstallRoot(entryFile);
	installDistEsmResolveFastPath(import.meta.url);
	process$1.title = "openclaw";
	ensureOpenClawExecMarkerOnProcess();
	installProcessWarningFilter();
	normalizeEnv();
	process$1.argv = normalizeWindowsArgv(process$1.argv);
	const earlyProfile = parseCliProfileArgs(process$1.argv);
	if (earlyProfile.ok && earlyProfile.profile) applyCliProfileEnv({ profile: earlyProfile.profile });
	const { assertSupportedRuntime, isCurrentRuntimeSupported } = await import("./runtime-guard-DDcD1U2U.js");
	if (!isCurrentRuntimeSupported()) {
		const { loadCliDotEnv } = await import("./dotenv-C1BZ8F4P.js");
		loadCliDotEnv({ quiet: true });
		await configureGatewayStartupTraceConsoleFormatting(gatewayEntryStartupTrace);
	}
	assertSupportedRuntime();
	gatewayEntryStartupTrace.mark("bootstrap");
	if (!await respawnWithoutOpenClawCompileCacheIfNeeded({
		currentFile: entryFile,
		installRoot,
		prepareWriteError: async () => {
			const writeError = await prepareCliDiagnosticBlockWriter();
			return (message) => writeError(message);
		}
	})) {
		enableOpenClawCompileCache({ installRoot });
		if (shouldForceReadOnlyAuthStore(process$1.argv)) process$1.env.OPENCLAW_AUTH_STORE_READONLY = "1";
		if (process$1.argv.includes("--no-color")) {
			process$1.env.NO_COLOR = "1";
			process$1.env.FORCE_COLOR = "0";
		}
		async function ensureCliRespawnReady() {
			const plan = buildCliRespawnPlan();
			if (!plan) return false;
			runCliRespawnPlan(plan, void 0, await prepareCliDiagnosticBlockWriter());
			return true;
		}
		if (!await ensureCliRespawnReady()) {
			const parsedContainer = parseCliContainerArgs(process$1.argv);
			if (!parsedContainer.ok) {
				await writeCapturedCliArgumentError(parsedContainer.error);
				process$1.exit(2);
			}
			const parsed = parseCliProfileArgs(parsedContainer.argv);
			if (!parsed.ok) {
				await writeCapturedCliArgumentError(parsed.error);
				process$1.exit(2);
			}
			const containerTargetName = resolveCliContainerTarget(process$1.argv);
			if (parsed.profile) {
				applyCliProfileEnv({ profile: parsed.profile });
				process$1.argv = parsed.argv;
			}
			if (containerTargetName && parsed.profile) {
				await writeCapturedCliArgumentError("--container cannot be combined with --profile/--dev");
				process$1.exit(2);
			}
			gatewayEntryStartupTrace.mark("argv");
			if (!tryHandleRootVersionFastPath(process$1.argv)) await runMainOrRootHelp(process$1.argv);
		}
	}
}
async function tryHandleRootHelpFastPath(argv, deps = {}) {
	const env = deps.env ?? process$1.env;
	if (env.OPENCLAW_DISABLE_CLI_STARTUP_HELP_FAST_PATH === "1" || resolveCliContainerTarget(argv, env)) return false;
	if (!isRootHelpInvocation(argv)) return false;
	const handleError = deps.onError ?? (async (error) => {
		await writeCliDiagnosticBlock(`[openclaw] Failed to display help: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
		process$1.exit(1);
	});
	try {
		const liveRootHelpOptions = await (deps.loadRootHelpRenderOptionsForConfigSensitivePlugins ?? (await loadRootHelpLiveConfigModule()).loadRootHelpRenderOptionsForConfigSensitivePlugins)(env);
		if (!liveRootHelpOptions) {
			if ((deps.outputPrecomputedRootHelpText ?? (await loadRootHelpMetadataModule()).outputPrecomputedRootHelpText)()) return true;
		}
		await (deps.outputRootHelp ?? (await import("./root-help-BJCQqSPf.js")).outputRootHelp)(liveRootHelpOptions ?? void 0);
		return true;
	} catch (error) {
		await handleError(error);
		return true;
	}
}
async function tryHandlePrecomputedCommandHelpFastPath(argv, deps = {}) {
	const env = deps.env ?? process$1.env;
	if (resolveCliContainerTarget(argv, env)) return false;
	try {
		return await tryOutputPrecomputedCommandHelp(argv, {
			...deps,
			env
		});
	} catch {
		return false;
	}
}
async function runMainOrRootHelp(argv, deps = {}) {
	await runCliWithExitFinalization({
		run: async () => {
			if (isNativeHookRelayArgv(argv) && !argv.includes("--help") && !argv.includes("-h")) {
				const { runNativeHookRelayCliFromArgv } = await import("./native-hook-relay-cli-DZ_U0OH5.js");
				const exitCode = await runNativeHookRelayCliFromArgv(argv);
				process$1.exitCode = exitCode;
				requestExitAfterOneShotOutput(defaultRuntime, exitCode);
				return;
			}
			if (await tryHandleRootHelpFastPath(argv)) {
				await flushEntryStartupTraceForEarlyReturn(argv);
				return;
			}
			if (await tryHandlePrecomputedCommandHelpFastPath(argv)) {
				await flushEntryStartupTraceForEarlyReturn(argv);
				return;
			}
			const { runCli } = await gatewayEntryStartupTrace.measure("run-main-import", deps.loadRunCli ?? (() => import("./cli/run-main.js")));
			await runCli(argv, {
				additionalStartupTrace: gatewayEntryStartupTrace,
				retainConsoleRoutingUntilProcessExit: true
			});
		},
		onError: async (error) => {
			const { loadCliDotEnvForEarlyDiagnostic } = await import("./dotenv-C1BZ8F4P.js");
			await loadCliDotEnvForEarlyDiagnostic(argv);
			await configureGatewayStartupTraceConsoleFormatting(gatewayEntryStartupTrace);
			const { enableConsoleCapture } = await import("./logging-CjOAus1j.js");
			enableConsoleCapture();
			const [{ formatCliFailureLines, formatCliJsonFailure }, { isJsonOutputModeActive }] = await Promise.all([import("./failure-output-UIlyogfI.js"), import("./json-output-mode-DCwXIqlL.js")]);
			if (isJsonOutputModeActive(argv)) defaultRuntime.writeJson(formatCliJsonFailure(error));
			for (const line of formatCliFailureLines({
				title: "Could not start the CLI.",
				error,
				argv
			})) console.error(line);
			process$1.exitCode = 1;
		}
	});
}
//#endregion
export { runMainOrRootHelp, tryHandlePrecomputedCommandHelpFastPath, tryHandleRootHelpFastPath };
