import "./tool-display-DMBmPBI-.js";
import "./paths-WcYpcMAY.js";
import { Bt as getCommandPath, Dt as theme, Et as isRich, Kt as hasHelpOrVersion, Wt as getVerboseFlag, X as escapeRegExp, _ as defaultRuntime, n as isTruthyEnvValue, xt as setVerbose } from "./entry.js";
import "./auth-profiles-CaNK0cUT.js";
import { n as replaceCliName, r as resolveCliName } from "./command-format-C8jrlG0z.js";
import "./exec-CmvuUufz.js";
import "./agent-scope-E2aR3Ci_.js";
import "./github-copilot-token-CKOQDjEZ.js";
import "./emitter-BKo8D7Oj.js";
import "./sqlite-CVrhPija.js";
import "./reliability-BnL75OlZ.js";
import "./pi-model-discovery-Cd63DV2B.js";
import "./model-nrbMzlbz.js";
import "./frontmatter-C3D7gE4Z.js";
import "./skills-UwTwDeDw.js";
import "./manifest-registry-AgGLF4V7.js";
import "./validation-B00oOkJ3.js";
import { w as VERSION } from "./config-CoCeK5B2.js";
import "./client-DtQEs2_8.js";
import "./call-CkgY6Bq7.js";
import "./message-channel-DKXbq8GH.js";
import "./subagent-registry-BSfrC7gZ.js";
import "./sessions-CFJLtXRH.js";
import "./tokens-D-4TlWcT.js";
import "./heartbeat-XNOTz34R.js";
import "./accounts-CNwod9BY.js";
import "./accounts-C3i8BBiA.js";
import "./normalize-CRf-uoB2.js";
import "./bindings-B1hNZin3.js";
import "./helpers-C1I2eYI4.js";
import "./allow-list-C1QL6XM_.js";
import "./logging-BiuZwq5D.js";
import "./client-BrCP9C3o.js";
import "./plugins-DMpYx7kb.js";
import "./targets-DvKzWjKi.js";
import "./with-timeout-xvreNRIp.js";
import "./diagnostic-CvuUUG_n.js";
import "./diagnostic-session-state-Dom6CWV9.js";
import "./lanes-6YZC1uc5.js";
import "./reply-payloads-DHkZZC3s.js";
import "./route-reply-0Dr2Q7BS.js";
import "./tts-CLI3TzKv.js";
import "./image-ops-D0pBQqKh.js";
import "./audio-xR21p4sl.js";
import "./pi-embedded-helpers-D-q9ylFX.js";
import "./sandbox-C79rEJ_w.js";
import "./chrome-BTLLz_O2.js";
import "./tailscale-V4nwZFBO.js";
import "./auth-Beo6eR0R.js";
import "./server-context-T5wFkzWi.js";
import "./routes-Ch0tqbTH.js";
import "./redact-2qrQ_uJt.js";
import "./errors-BlUw40-o.js";
import "./paths-Cb76_eC_.js";
import "./ssrf-BEPhIfOk.js";
import "./store-Bz34pm8z.js";
import "./ports-BsKQWWi9.js";
import "./trash-Cn3CsF86.js";
import "./dock-BvRrtCWj.js";
import "./accounts-CdYdWklO.js";
import "./paths-CDTtU20P.js";
import "./tool-images-B4eVOjD0.js";
import "./thinking-C03RqJxq.js";
import "./models-config-By95gdZa.js";
import "./chat-trace-C0wGIaWO.js";
import "./response-prefix-template-C1xl3U-G.js";
import "./tool-tracking-CtNygH0q.js";
import "./memory-cli-85mo64bb.js";
import "./manager-CFXUPO5v.js";
import "./gemini-auth-dH8SvNUd.js";
import "./session-files-0TqN4M7r.js";
import "./retry-Bdf0L_dZ.js";
import "./hybrid-DSp5ZIQe.js";
import "./common-CxpUJZLb.js";
import "./send-BozJfiUK.js";
import "./chunk-CNObemR3.js";
import "./markdown-tables-Cex18ib0.js";
import "./fetch-guard-BLrk92iq.js";
import "./fetch-DFo2YRBT.js";
import "./media-PPft1pQs.js";
import "./ir-CRxad2DW.js";
import "./render-JkHfM4BD.js";
import "./commands-registry-Ckq8wOdS.js";
import "./sessions-helpers-NrlH9x7w.js";
import "./pi-embedded-utils-BCSBp2bL.js";
import "./external-content-pnoCpvzd.js";
import "./runner-Dbz36vkv.js";
import "./image-tool.helpers-Bb25eyJc.js";
import "./image-DnnIE6E3.js";
import "./model-catalog-c_sp3sxR.js";
import "./session-utils-CwXLwy_N.js";
import "./workspace-dirs-Dm1vImLQ.js";
import "./skill-commands-B6qVCgej.js";
import "./fetch-CbnJhXfl.js";
import "./pairing-store-BHSQgDEs.js";
import "./exec-approvals-DGBfDg6X.js";
import "./gateway-CWnGRD4E.js";
import "./nodes-utils-DKSV6jwI.js";
import "./session-cost-usage-COXOEQzN.js";
import "./typed-schema-NhH7oBv2.js";
import "./knowledge-graph-njh3pt-F.js";
import "./model-fallback-N2p6k-x8.js";
import "./send-DpN8GxWR.js";
import "./channel-activity-Renq827a.js";
import "./tables-BD7LbCl1.js";
import "./server-startup-users-Dzui320y.js";
import "./resolve-route-CjJJ3gIl.js";
import "./replies-f6OSxuwk.js";
import "./reply-prefix-CjtRvYlq.js";
import "./pi-tools.policy-CW2flz_o.js";
import "./send-CdF3YtrB.js";
import "./onboard-helpers-HmtMUhNQ.js";
import "./prompt-style-BNQCf62G.js";
import "./onboard-helpers-CMBWpQU-.js";
import "./outbound-attachment-BhyLC0RY.js";
import "./targets-Df3HJYGb.js";
import "./pairing-labels-B7JDegCR.js";
import "./send-oTQYKgod.js";
import "./send-BxB9sGGU.js";
import "./proxy-BWmn1C2E.js";
import { t as formatDocsLink } from "./links-BcL73qkF.js";
import "./cli-utils-CpDxBFOW.js";
import "./help-format-CSTLKmFP.js";
import "./progress-Dh4aWkCA.js";
import "./active-listener-Bqb34bVB.js";
import "./catalog-Cd-lskrP.js";
import "./plugin-registry-TqWTff0U.js";
import { n as resolveCliChannelOptions } from "./channel-options-68rPNIvW.js";
import { t as getSubCliCommandsWithSubcommands } from "./register.subclis-CquYR9Fa.js";
import { a as registerProgramCommands, r as getCoreCliCommandsWithSubcommands } from "./command-registry-jhIy2Mh7.js";
import { r as setProgramContext } from "./program-context-gOe5nMsh.js";
import { t as forceFreePort } from "./ports-a82p6a66.js";
import { n as formatCliBannerLine, r as hasEmittedCliBanner, t as emitCliBanner } from "./banner-BIgZ6EqH.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.MINION_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-BtJzD7EA.js").then((n) => n.t);
		await ensureConfigReady({
			runtime: defaultRuntime,
			commandPath
		});
		if (PLUGIN_REQUIRED_COMMANDS.has(commandPath[0])) {
			const { ensurePluginRegistryLoaded } = await import("./plugin-registry-TqWTff0U.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 };