import { Tu as resolveCliName, Yc as VERSION, t as isTruthyEnvValue, wu as replaceCliName } from "./env-Dlz8aQHP.js";
import { $ as tryParseLogLevel, H as theme, I as setVerbose, V as isRich, X as ALLOWED_LOG_LEVELS, d as escapeRegExp } from "./agent-paths-DUHGyU1s.js";
import "./send-Ditv1VfR.js";
import "./send-CWM2yWF6.js";
import { I as emitCliBanner, L as formatCliBannerLine, R as hasEmittedCliBanner } from "./model-catalog-B2mRe6cZ.js";
import "./github-copilot-token-A9DiaCB0.js";
import { A as defaultRuntime, At as getVerboseFlag, Et as getCommandPath, Mt as hasHelpOrVersion, Nt as hasRootVersionAlias, jt as hasFlag } from "./entry.js";
import "./reply-prefix-CCp0C8w4.js";
import "./memory-BpNgGSAl.js";
import "./memory-search-Bm46LIUQ.js";
import "./manager-DTf-5dRo.js";
import "./fetch-guard-DkRm4Ip1.js";
import "./ip-CLwwPh25.js";
import "./ssrf-CqV2hisj.js";
import "./query-expansion-CfOgA1KD.js";
import "./memory-cli-B7kMyaVL.js";
import "./ir-r4mczNAR.js";
import "./target-errors-CWVZTpXS.js";
import "./chunk-D9NQZPPD.js";
import "./markdown-tables-ylpJUTGZ.js";
import "./path-alias-guards-BerTsE5c.js";
import "./fs-safe-BrR3_fH1.js";
import "./render-BDQg502o.js";
import "./commands-registry-DQLLJg_T.js";
import "./diagnostic-BGFH8MIa.js";
import "./diagnostic-session-state-HO94DMou.js";
import "./send-C4oPrvgH.js";
import "./model-bpjlPTsB.js";
import "./pi-model-discovery-Do4Oa02J.js";
import "./dangerous-tools-CusV9bcr.js";
import "./chrome-CUkBgrOC.js";
import "./pairing-token-C2iKEhFc.js";
import "./ws-DiFJ3zRB.js";
import "./onboarding.wallet-CcoV0W6U.js";
import "./wallet-runtime-config-TjiNNY9x.js";
import "./wallet-provider-registry-CFNtQ2ZR.js";
import "./wallet-W8qsxi6H.js";
import "./wallet-approval-auth-BaVTLG5r.js";
import "./runtime-DXHXAPJA.js";
import "./device-identity-ZHUQ6a8N.js";
import "./solana-bond-signing-D9-GtRIf.js";
import "./federation-8sW60I4p.js";
import "./call-CjHZhgQk.js";
import "./send-Dlj2DghK.js";
import "./outbound-attachment-D2ImFzcm.js";
import "./fetch-BqA-KBI4.js";
import "./delivery-queue-CMGPhIoF.js";
import "./deps-4rCQ5SBd.js";
import "./frontmatter-DTw-J9er.js";
import "./skills-CzDvK09q.js";
import "./skills-remote-CM9uNuu4.js";
import "./dangerous-name-matching-ob0tR02Y.js";
import "./channel-selection-BSwWHrf5.js";
import "./session-cost-usage-Dzc2RiRn.js";
import "./trash--uInT2PE.js";
import "./paths-rsh1tVGc.js";
import "./exec-approvals-aJApzFwx.js";
import "./node-shell-CpYc0oKF.js";
import "./task-planner-CkWt6WhX.js";
import "./send-CekwB5g1.js";
import "./resolve-route-y4Ol4Qmc.js";
import "./pairing-store-qjH5R_BQ.js";
import "./skills-clawhub-CBB2AUv6.js";
import "./exec-approvals-allowlist-BZoClZ91.js";
import "./skill-commands-Cx0nCzUv.js";
import "./channel-activity-DrrSLe52.js";
import "./tables-8heM_uJo.js";
import "./proxy-mdETjik4.js";
import "./config-DfviqDy5.js";
import { t as formatDocsLink } from "./links-CPltkiov.js";
import "./cli-utils-XevKf-tr.js";
import "./help-format-D7mxVfC9.js";
import "./progress-BhMUiH4f.js";
import "./replies-BFsEK9FQ.js";
import "./prompt-style-CWdNyu_Q.js";
import "./pairing-labels-DBt_OA8C.js";
import "./plugin-registry-C7oTQytM.js";
import { i as resolveCliChannelOptions, n as isParentDefaultHelpAction } from "./parent-default-help-CpfuGajV.js";
import { t as getSubCliCommandsWithSubcommands } from "./register.subclis-Bj8pFyAT.js";
import { a as registerProgramCommands, r as getCoreCliCommandsWithSubcommands } from "./command-registry-fqlYdOTI.js";
import { r as setProgramContext } from "./program-context-CDFrVtWb.js";
import { t as forceFreePort } from "./ports-f4mmzwW4.js";
import { Command, InvalidArgumentError } 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/log-level-option.ts
const CLI_LOG_LEVEL_VALUES = ALLOWED_LOG_LEVELS.join("|");
function parseCliLogLevelOption(value) {
	const parsed = tryParseLogLevel(value);
	if (!parsed) throw new InvalidArgumentError(`Invalid --log-level (use ${CLI_LOG_LEVEL_VALUES})`);
	return parsed;
}

//#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 = [
	["fased models --help", "Show detailed help for the models command."],
	["fased channels login --verbose", "Link personal WhatsApp Web and show QR + connection logs."],
	["fased message send --target +15555550123 --message \"Hi\" --json", "Send via your web session and print JSON result."],
	["fased gateway run --port 18789", "Run the WebSocket Gateway locally."],
	["fased --dev gateway run", "Run a dev Gateway (isolated state/config) on ws://127.0.0.1:19001."],
	["fased gateway run --force", "Kill anything bound to the default gateway port, then start it."],
	["fased gateway ...", "Gateway control via WebSocket."],
	["fased agent --to +15555550123 --message \"Run summary\" --deliver", "Talk directly to the agent using the Gateway; optionally send the WhatsApp reply."],
	["fased 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 ~/.fased-dev, default gateway port 19001, and shift derived ports (browser/canvas)").option("--profile <name>", "Use a named profile (isolates FASED_STATE_DIR/FASED_CONFIG_PATH under ~/.fased-<name>)").option("--log-level <level>", `Global log level override for file + console (${CLI_LOG_LEVEL_VALUES})`, parseCliLogLevelOption);
	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 (hasFlag(process.argv, "-V") || hasFlag(process.argv, "--version") || hasRootVersionAlias(process.argv)) {
		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.fased.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",
	"agents",
	"configure",
	"onboard"
]);
const CONFIG_GUARD_BYPASS_COMMANDS = new Set([
	"doctor",
	"completion",
	"secrets"
]);
function getRootCommand(command) {
	let current = command;
	while (current.parent) current = current.parent;
	return current;
}
function getCliLogLevel(actionCommand) {
	const root = getRootCommand(actionCommand);
	if (typeof root.getOptionValueSource !== "function") return;
	if (root.getOptionValueSource("logLevel") !== "cli") return;
	const logLevel = root.opts().logLevel;
	return typeof logLevel === "string" ? logLevel : void 0;
}
function isBareParentDefaultHelpInvocation(actionCommand, argv) {
	if (!isParentDefaultHelpAction(actionCommand)) return false;
	const [primary, extra] = getCommandPath(argv, 2);
	if (!primary || extra !== void 0) return false;
	return primary === actionCommand.name() || actionCommand.aliases().includes(primary);
}
function registerPreActionHooks(program, programVersion) {
	program.hook("preAction", async (_thisCommand, actionCommand) => {
		setProcessTitleForCommand(actionCommand);
		const argv = process.argv;
		if (hasHelpOrVersion(argv) || isBareParentDefaultHelpInvocation(actionCommand, argv)) return;
		const commandPath = getCommandPath(argv, 2);
		if (!(isTruthyEnvValue(process.env.FASED_HIDE_BANNER) || process.env.FASED_INSTALLER_ONBOARD === "1" || commandPath[0] === "update" || commandPath[0] === "completion" || commandPath[0] === "plugins" && commandPath[1] === "update")) emitCliBanner(programVersion);
		const verbose = getVerboseFlag(argv, { includeDebug: true });
		setVerbose(verbose);
		const cliLogLevel = getCliLogLevel(actionCommand);
		if (cliLogLevel) process.env.FASED_LOG_LEVEL = cliLogLevel;
		if (!verbose) process.env.NODE_NO_WARNINGS ??= "1";
		if (CONFIG_GUARD_BYPASS_COMMANDS.has(commandPath[0])) return;
		const { ensureConfigReady } = await import("./config-guard-TwBaDdU-.js").then((n) => n.t);
		await ensureConfigReady({
			runtime: defaultRuntime,
			commandPath
		});
		if (PLUGIN_REQUIRED_COMMANDS.has(commandPath[0])) {
			const { ensurePluginRegistryLoaded } = await import("./plugin-registry-C7oTQytM.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 };