#!/usr/bin/env node
import "./paths-C9FmTW1x.js";
import { H as isRich, L as setVerbose, O as toWhatsappJid, U as theme, Z as ALLOWED_LOG_LEVELS, _ as normalizeE164, a as assertWebChannel, et as tryParseLogLevel, f as escapeRegExp } from "./agent-paths-BySKyq9I.js";
import { $l as runCommandWithTimeout, Cd as isTruthyEnvValue, Dn as loadConfig, Et as loadSessionStore, Su as loadDotEnv, Td as normalizeEnv, bl as VERSION, cn as deriveSessionKey, eu as runExec, fd as replaceCliName, jt as saveSessionStore, ln as resolveSessionKey, oo as assertSupportedRuntime, pd as resolveCliName, rd as enableConsoleCapture } from "./agent-scope-CLn_Ws3B.js";
import "./commands-registry-DfzoWf4b.js";
import { cn as emitCliBanner, ds as applyTemplate, ln as formatCliBannerLine, lr as installUnhandledRejectionHandler, ns as ensureBinary, rs as promptYesNo, t as getReplyFromConfig, un as hasEmittedCliBanner } from "./reply-DQfPM5ia.js";
import { d as defaultRuntime, r as formatUncaughtError } from "./errors-Dx3S3Nrp.js";
import "./send-DI5jsj-s.js";
import "./send-Dg2_aoK-.js";
import "./github-copilot-token-BA45-q56.js";
import { g as resolveStorePath } from "./chat-envelope-D_wSv26N.js";
import "./pi-model-discovery-BftA1L--.js";
import "./dangerous-tools-C88-uuUI.js";
import { c as PortInUseError, d as handlePortError, l as describePortOwner, u as ensurePortAvailable } from "./chrome-BFIqTpDi.js";
import "./pairing-token-BFGorDQo.js";
import "./ip-D_T5zbZS.js";
import "./ws-cvQhrVP3.js";
import "./onboarding.wallet-B12p7GUZ.js";
import "./wallet-runtime-config-BlRWvEER.js";
import "./wallet-provider-registry-ax0NJo0F.js";
import "./wallet-BPiknFdt.js";
import "./wallet-approval-auth-DT-vofLs.js";
import "./reply-prefix-BRvLVE6I.js";
import "./media-ZuS0crH3.js";
import "./path-alias-guards-DivKBvV8.js";
import "./fs-safe-Cp0MI7Oo.js";
import "./runtime-bsvPuEXH.js";
import "./device-identity-DzUZ06fL.js";
import "./solana-bond-signing-CgswTuFe.js";
import "./diagnostic-Cl18V9Cy.js";
import "./federation-BrNm7xtG.js";
import "./call-s6DNIELo.js";
import "./chunk-tBRG1JLR.js";
import "./markdown-tables-DvKl7MfL.js";
import "./send-aHqtlYYi.js";
import "./fetch-guard-hWUtz61M.js";
import "./ssrf-Blf4NrHS.js";
import "./outbound-attachment-BHTb_aF7.js";
import "./fetch-BJWQWfdf.js";
import "./delivery-queue-9lp1uujZ.js";
import { t as createDefaultDeps } from "./deps-CBapZnsi.js";
import "./memory-e9aOXNx1.js";
import "./memory-search-B8y2GTeB.js";
import "./manager-DI2w66Ae.js";
import "./query-expansion-BdzehFyx.js";
import "./memory-cli-mMVfDz8Z.js";
import "./target-errors-_IirSOQ1.js";
import "./render-C2MRWrC0.js";
import "./diagnostic-session-state-89enG0Yp.js";
import "./send-B3O8oJLA.js";
import "./model-CfutahU0.js";
import "./exec-approvals-allowlist-C5bxRc7H.js";
import "./dangerous-name-matching-B2YH8EDF.js";
import "./skills-D1Qdj69-.js";
import "./node-match-BNTZ8TY5.js";
import "./system-run-command-BvFkDQae.js";
import "./channel-selection-EDP8q9uz.js";
import "./task-planner-BW6kdamv.js";
import "./trash-BiHtb5y8.js";
import "./paths-BA7z-HF9.js";
import "./send-CKgt65ud.js";
import "./resolve-route-CbII9dNc.js";
import "./pairing-store-CUPrh2Qy.js";
import "./session-cost-usage-DQSpjhkP.js";
import "./skills-clawhub-kuGAFKgL.js";
import "./config-eval-CuVkTCse.js";
import "./channel-activity-BkfQ8RFW.js";
import "./tables-apsvCDwc.js";
import "./proxy-DU7W9XSc.js";
import "./config-BKhx4paQ.js";
import { t as formatDocsLink } from "./links-BeUKckiL.js";
import "./cli-utils-DJ7Nfw8J.js";
import "./help-format-H4GNCFCs.js";
import "./progress-CDqdg8f8.js";
import "./replies-Xddrs-mt.js";
import "./skills-remote-DkdYN-8J.js";
import "./skill-commands-CxJHp3z6.js";
import { a as hasFlag, i as getVerboseFlag, n as getCommandPath, o as hasHelpOrVersion, s as hasRootVersionAlias } from "./argv-BqQeWVYw.js";
import "./prompt-style-Db5iJoaI.js";
import "./pairing-labels-sAC1Ty3_.js";
import { r as waitForever, t as monitorWebChannel } from "./channel-web-qHKfuCHE.js";
import "./outbound-DvIMfvtY.js";
import "./session-DZkPK2HB.js";
import "./login-T8Rtml0H.js";
import { t as isMainModule } from "./is-main-CDzrraLY.js";
import { t as ensureFasedAgentCliOnPath } from "./path-env-BJKsiRNr.js";
import "./ports-CxVYOn9b.js";
import { i as getCoreCliCommandsWithSubcommands, n as setProgramContext, o as registerProgramCommands, s as getSubCliCommandsWithSubcommands } from "./program-context-Di7qiwOM.js";
import "./plugin-registry-2aqMgXpl.js";
import { i as resolveCliChannelOptions, n as isParentDefaultHelpAction } from "./parent-default-help-DbMf7NQe.js";
import process$1 from "node:process";
import { fileURLToPath } from "node:url";
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-C0LJNvn-.js");
		await ensureConfigReady({
			runtime: defaultRuntime,
			commandPath
		});
		if (PLUGIN_REQUIRED_COMMANDS.has(commandPath[0])) {
			const { ensurePluginRegistryLoaded } = await import("./plugin-registry-2aqMgXpl.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
//#region src/index.ts
loadDotEnv({ quiet: true });
normalizeEnv();
ensureFasedAgentCliOnPath();
enableConsoleCapture();
assertSupportedRuntime();
const program = buildProgram();
if (isMainModule({ currentFile: fileURLToPath(import.meta.url) })) {
	installUnhandledRejectionHandler();
	process$1.on("uncaughtException", (error) => {
		console.error("[fased] Uncaught exception:", formatUncaughtError(error));
		process$1.exit(1);
	});
	program.parseAsync(process$1.argv).catch((err) => {
		console.error("[fased] CLI failed:", formatUncaughtError(err));
		process$1.exit(1);
	});
}

//#endregion
export { PortInUseError, applyTemplate, assertWebChannel, createDefaultDeps, deriveSessionKey, describePortOwner, ensureBinary, ensurePortAvailable, getReplyFromConfig, handlePortError, loadConfig, loadSessionStore, monitorWebChannel, normalizeE164, promptYesNo, resolveSessionKey, resolveStorePath, runCommandWithTimeout, runExec, saveSessionStore, toWhatsappJid, waitForever };