import "./subagent-registry-BdCHUwJF.js";
import { Dt as theme, Et as isRich, X as escapeRegExp, _ as defaultRuntime, cn as hasHelpOrVersion, n as isTruthyEnvValue, nn as getCommandPath, on as getVerboseFlag, xt as setVerbose } from "./entry.js";
import "./auth-profiles-BGjbqScX.js";
import { n as replaceCliName, r as resolveCliName } from "./command-format-Cutkv9UT.js";
import "./exec-CBKBIMpA.js";
import "./agent-scope-p68ICeNQ.js";
import "./github-copilot-token-CyWpbkHJ.js";
import "./model-OTR4fRIX.js";
import "./pi-model-discovery-BDrA0RUW.js";
import "./frontmatter-DRl3Sa-X.js";
import "./skills-Ho_2X6WT.js";
import "./manifest-registry-CYUiqtAr.js";
import { L as VERSION } from "./config-xHYx2cij.js";
import "./client-fwA5zyHb.js";
import "./call-BOB-Te5P.js";
import "./message-channel-B9mgJ1nn.js";
import "./sessions-BwDGf9Sn.js";
import "./tokens-DNhq_l0Z.js";
import "./normalize-B8nBEyAK.js";
import "./accounts-BSDGn_Eo.js";
import "./bindings-B_ZIo7YE.js";
import "./logging-5MtSkLpb.js";
import "./send-YkSDctU7.js";
import "./plugins-B1ojCJHx.js";
import "./send-CsZYxWdf.js";
import "./with-timeout-DEXcYOPT.js";
import "./deliver-5Uvc7ymL.js";
import "./diagnostic-BrjZno3V.js";
import "./diagnostic-session-state-CAYi3DRc.js";
import "./accounts-DUB7WjhZ.js";
import "./send-33rhg_bg.js";
import "./image-ops-DGYdb3fh.js";
import "./pi-embedded-helpers-DoMXOCkN.js";
import "./sandbox-CZanUXAq.js";
import "./chrome-DfrRhznb.js";
import "./tailscale-D9FK-yno.js";
import "./auth-BFCCBoWg.js";
import "./server-context-DvoYRfwN.js";
import "./routes-ClCMoQG_.js";
import "./redact-BfDi6wIJ.js";
import "./errors-DNW-UCMb.js";
import "./paths-DqOyyjUy.js";
import "./ssrf-B_uizFky.js";
import "./store-CORMGVx_.js";
import "./ports-LWH8Y0_f.js";
import "./trash-B891j_cA.js";
import "./dock-BPcuR3ve.js";
import "./accounts-SnH-42ge.js";
import "./paths-DT4MkPF0.js";
import "./tool-images-DLc1ZwCt.js";
import "./thinking-O_pp2Bz3.js";
import "./models-config-xKUJ-Jlr.js";
import "./reply-prefix-CrkNe8Gp.js";
import "./memory-cli-Guckbc8M.js";
import "./manager-DnbrWcSO.js";
import "./gemini-auth-BF-a5GeR.js";
import "./sqlite-DZTdGqNd.js";
import "./retry-DtzRtCu9.js";
import "./common-Bi2yGPsV.js";
import "./chunk-DkEDZgsU.js";
import "./markdown-tables-I-50wDdr.js";
import "./fetch-guard-sWUTAYEJ.js";
import "./fetch-CfzM3qfj.js";
import "./ir-WbjhHhfd.js";
import "./render-CCLsW6Lz.js";
import "./commands-registry-D8TQrvT9.js";
import "./image-CWNvCgXH.js";
import "./tool-display-Ch60dmIj.js";
import "./runner-BWzWj3vE.js";
import "./model-catalog-CCane-Jh.js";
import "./session-utils-BeS2v05U.js";
import "./skill-commands-DVP91_MZ.js";
import "./workspace-dirs-CpIMMjZW.js";
import "./pairing-store-DM_ihkC1.js";
import "./fetch-mirEALun.js";
import "./nodes-screen-BNyvvjYY.js";
import "./session-cost-usage-BCIITMRg.js";
import "./project-context-DhXARJNC.js";
import "./control-service-DziHPGgw.js";
import "./stagger-BCQzFuQi.js";
import "./channel-selection-DV8cpKuI.js";
import "./send-BquvUhjS.js";
import "./outbound-attachment-DAzLnDoa.js";
import "./delivery-queue-CL2en3fg.js";
import "./send-D5voy0Gs.js";
import "./resolve-route-CAxji0MH.js";
import "./channel-activity-OK2g2kgk.js";
import "./tables-7XAEudlg.js";
import "./proxy-YU8wp1-L.js";
import { t as formatDocsLink } from "./links-rnbUL9h5.js";
import "./cli-utils-f9j-_1VT.js";
import "./help-format-5GFCgEVf.js";
import "./progress-Clpi3Ckj.js";
import "./replies-B4l-Q3Tx.js";
import "./pi-tools.policy-Cadm9ZgR.js";
import "./onboard-helpers-COs8NEvA.js";
import "./prompt-style-B_yUCLn4.js";
import "./pairing-labels-H_LS1HI0.js";
import "./catalog-DrXj_7vG.js";
import "./plugin-registry-CYZ6YsHI.js";
import { n as resolveCliChannelOptions } from "./channel-options-CwkpNCEg.js";
import { t as getSubCliCommandsWithSubcommands } from "./register.subclis-7q1zQzQK.js";
import { a as registerProgramCommands, r as getCoreCliCommandsWithSubcommands } from "./command-registry-DJUPGQmQ.js";
import { r as setProgramContext } from "./program-context-BUuYElH3.js";
import { t as forceFreePort } from "./ports-xVpf3c8Y.js";
import { n as formatCliBannerLine, r as hasEmittedCliBanner, t as emitCliBanner } from "./banner-BheTTuTV.js";
import { Command } from "commander";

//#region src/cli/program/context.ts
function createProgramContext() {
	const channelOptions = resolveCliChannelOptions();
	return {
		programVersion: VERSION,
		channelOptions,
		messageChannelOptions: channelOptions.join("|"),
		agentChannelOptions: ["last", ...channelOptions].join("|")
	};
}

//#endregion
//#region src/cli/program/help.ts
const CLI_NAME = resolveCliName();
const CLI_NAME_PATTERN = escapeRegExp(CLI_NAME);
const ROOT_COMMANDS_WITH_SUBCOMMANDS = new Set([...getCoreCliCommandsWithSubcommands(), ...getSubCliCommandsWithSubcommands()]);
const ROOT_COMMANDS_HINT = "Hint: commands suffixed with * have subcommands. Run <command> --help for details.";
const EXAMPLES = [
	["openclaw models --help", "Show detailed help for the models command."],
	["openclaw channels login --verbose", "Link personal WhatsApp Web and show QR + connection logs."],
	["openclaw message send --target +15555550123 --message \"Hi\" --json", "Send via your web session and print JSON result."],
	["openclaw gateway --port 18789", "Run the WebSocket Gateway locally."],
	["openclaw --dev gateway", "Run a dev Gateway (isolated state/config) on ws://127.0.0.1:19001."],
	["openclaw gateway --force", "Kill anything bound to the default gateway port, then start it."],
	["openclaw gateway ...", "Gateway control via WebSocket."],
	["openclaw agent --to +15555550123 --message \"Run summary\" --deliver", "Talk directly to the agent using the Gateway; optionally send the WhatsApp reply."],
	["openclaw message send --channel telegram --target @mychat --message \"Hi\"", "Send via your Telegram bot."]
];
function configureProgramHelp(program, ctx) {
	program.name(CLI_NAME).description("").version(ctx.programVersion).option("--dev", "Dev profile: isolate state under ~/.openclaw-dev, default gateway port 19001, and shift derived ports (browser/canvas)").option("--profile <name>", "Use a named profile (isolates OPENCLAW_STATE_DIR/OPENCLAW_CONFIG_PATH under ~/.openclaw-<name>)");
	program.option("--no-color", "Disable ANSI colors", false);
	program.helpOption("-h, --help", "Display help for command");
	program.helpCommand("help [command]", "Display help for command");
	program.configureHelp({
		sortSubcommands: true,
		sortOptions: true,
		optionTerm: (option) => theme.option(option.flags),
		subcommandTerm: (cmd) => {
			const hasSubcommands = cmd.parent === program && ROOT_COMMANDS_WITH_SUBCOMMANDS.has(cmd.name());
			return theme.command(hasSubcommands ? `${cmd.name()} *` : cmd.name());
		}
	});
	const formatHelpOutput = (str) => {
		let output = str;
		if (new RegExp(`^Usage:\\s+${CLI_NAME_PATTERN}\\s+\\[options\\]\\s+\\[command\\]\\s*$`, "m").test(output) && /^Commands:/m.test(output)) output = output.replace(/^Commands:/m, `Commands:\n  ${theme.muted(ROOT_COMMANDS_HINT)}`);
		return output.replace(/^Usage:/gm, theme.heading("Usage:")).replace(/^Options:/gm, theme.heading("Options:")).replace(/^Commands:/gm, theme.heading("Commands:"));
	};
	program.configureOutput({
		writeOut: (str) => {
			process.stdout.write(formatHelpOutput(str));
		},
		writeErr: (str) => {
			process.stderr.write(formatHelpOutput(str));
		},
		outputError: (str, write) => write(theme.error(str))
	});
	if (process.argv.includes("-V") || process.argv.includes("--version") || process.argv.includes("-v")) {
		console.log(ctx.programVersion);
		process.exit(0);
	}
	program.addHelpText("beforeAll", () => {
		if (hasEmittedCliBanner()) return "";
		const rich = isRich();
		return `\n${formatCliBannerLine(ctx.programVersion, { richTty: rich })}\n`;
	});
	const fmtExamples = EXAMPLES.map(([cmd, desc]) => `  ${theme.command(replaceCliName(cmd, CLI_NAME))}\n    ${theme.muted(desc)}`).join("\n");
	program.addHelpText("afterAll", ({ command }) => {
		if (command !== program) return "";
		const docs = formatDocsLink("/cli", "docs.openclaw.ai/cli");
		return `\n${theme.heading("Examples:")}\n${fmtExamples}\n\n${theme.muted("Docs:")} ${docs}\n`;
	});
}

//#endregion
//#region src/cli/program/preaction.ts
function setProcessTitleForCommand(actionCommand) {
	let current = actionCommand;
	while (current.parent && current.parent.parent) current = current.parent;
	const name = current.name();
	const cliName = resolveCliName();
	if (!name || name === cliName) return;
	process.title = `${cliName}-${name}`;
}
const PLUGIN_REQUIRED_COMMANDS = new Set([
	"message",
	"channels",
	"directory"
]);
function registerPreActionHooks(program, programVersion) {
	program.hook("preAction", async (_thisCommand, actionCommand) => {
		setProcessTitleForCommand(actionCommand);
		const argv = process.argv;
		if (hasHelpOrVersion(argv)) return;
		const commandPath = getCommandPath(argv, 2);
		if (!(isTruthyEnvValue(process.env.OPENCLAW_HIDE_BANNER) || commandPath[0] === "update" || commandPath[0] === "completion" || commandPath[0] === "plugins" && commandPath[1] === "update")) emitCliBanner(programVersion);
		const verbose = getVerboseFlag(argv, { includeDebug: true });
		setVerbose(verbose);
		if (!verbose) process.env.NODE_NO_WARNINGS ??= "1";
		if (commandPath[0] === "doctor" || commandPath[0] === "completion") return;
		const { ensureConfigReady } = await import("./config-guard-Cwr6umN2.js").then((n) => n.t);
		await ensureConfigReady({
			runtime: defaultRuntime,
			commandPath
		});
		if (PLUGIN_REQUIRED_COMMANDS.has(commandPath[0])) {
			const { ensurePluginRegistryLoaded } = await import("./plugin-registry-CYZ6YsHI.js").then((n) => n.n);
			ensurePluginRegistryLoaded();
		}
	});
}

//#endregion
//#region src/cli/program/build-program.ts
function buildProgram() {
	const program = new Command();
	const ctx = createProgramContext();
	const argv = process.argv;
	setProgramContext(program, ctx);
	configureProgramHelp(program, ctx);
	registerPreActionHooks(program, ctx.programVersion);
	registerProgramCommands(program, ctx, argv);
	return program;
}

//#endregion
export { buildProgram };