import { Kl as normalizeChannelId, Wl as getChannelPlugin, Xt as loadConfig } from "./env-Dlz8aQHP.js";
import { A as danger, H as theme, I as setVerbose } from "./agent-paths-DUHGyU1s.js";
import "./send-Ditv1VfR.js";
import "./send-CWM2yWF6.js";
import "./model-catalog-B2mRe6cZ.js";
import "./github-copilot-token-A9DiaCB0.js";
import { A as defaultRuntime } 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 { n as resolveMessageChannelSelection } from "./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 { n as runCommandWithRuntime } from "./cli-utils-XevKf-tr.js";
import { t as formatHelpExamples } from "./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 { t as hasExplicitOptions } from "./command-options-j8s8APBQ.js";
import { t as resolveChannelDefaultAccountId } from "./helpers-BfdkoReO.js";
import "./plugin-registry-C7oTQytM.js";
import { r as formatCliChannelOptions, t as applyParentDefaultHelpAction } from "./parent-default-help-CpfuGajV.js";

//#region src/cli/channel-auth.ts
async function resolveChannelPluginForMode(opts, mode, cfg) {
	const explicitChannel = opts.channel?.trim();
	const channelInput = explicitChannel ? explicitChannel : (await resolveMessageChannelSelection({ cfg })).channel;
	const channelId = normalizeChannelId(channelInput);
	if (!channelId) throw new Error(`Unsupported channel: ${channelInput}`);
	const plugin = getChannelPlugin(channelId);
	if (!(mode === "login" ? Boolean(plugin?.auth?.login) : Boolean(plugin?.gateway?.logoutAccount))) throw new Error(`Channel ${channelId} does not support ${mode}`);
	return {
		channelInput,
		channelId,
		plugin
	};
}
function resolveAccountContext(plugin, opts, cfg) {
	return { accountId: opts.account?.trim() || resolveChannelDefaultAccountId({
		plugin,
		cfg
	}) };
}
async function runChannelLogin(opts, runtime = defaultRuntime) {
	const cfg = loadConfig();
	const { channelInput, plugin } = await resolveChannelPluginForMode(opts, "login", cfg);
	const login = plugin.auth?.login;
	if (!login) throw new Error(`Channel ${channelInput} does not support login`);
	setVerbose(Boolean(opts.verbose));
	const { accountId } = resolveAccountContext(plugin, opts, cfg);
	await login({
		cfg,
		accountId,
		runtime,
		verbose: Boolean(opts.verbose),
		channelInput
	});
}
async function runChannelLogout(opts, runtime = defaultRuntime) {
	const cfg = loadConfig();
	const { channelInput, plugin } = await resolveChannelPluginForMode(opts, "logout", cfg);
	const logoutAccount = plugin.gateway?.logoutAccount;
	if (!logoutAccount) throw new Error(`Channel ${channelInput} does not support logout`);
	const { accountId } = resolveAccountContext(plugin, opts, cfg);
	await logoutAccount({
		cfg,
		accountId,
		account: plugin.config.resolveAccount(cfg, accountId),
		runtime
	});
}

//#endregion
//#region src/cli/channels-cli.ts
const optionNamesAdd = [
	"channel",
	"account",
	"name",
	"token",
	"tokenFile",
	"botToken",
	"appToken",
	"signalNumber",
	"cliPath",
	"dbPath",
	"service",
	"region",
	"authDir",
	"httpUrl",
	"httpHost",
	"httpPort",
	"webhookPath",
	"webhookUrl",
	"audienceType",
	"audience",
	"useEnv",
	"homeserver",
	"userId",
	"accessToken",
	"password",
	"deviceName",
	"initialSyncLimit",
	"ship",
	"url",
	"code",
	"groupChannels",
	"dmAllowlist",
	"autoDiscoverChannels"
];
const optionNamesRemove = [
	"channel",
	"account",
	"delete"
];
let channelsCommandsPromise;
function loadChannelsCommands() {
	channelsCommandsPromise ??= import("./channels-BoOF2dAy.js");
	return channelsCommandsPromise;
}
function runChannelsCommand(action) {
	return runCommandWithRuntime(defaultRuntime, action);
}
function runChannelsCommandWithDanger(action, label) {
	return runCommandWithRuntime(defaultRuntime, action, (err) => {
		defaultRuntime.error(danger(`${label}: ${String(err)}`));
		defaultRuntime.exit(1);
	});
}
function registerChannelsCli(program) {
	const channelNames = formatCliChannelOptions();
	const channels = program.command("channels").description("Manage connected chat channels and accounts").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
		["fased channels list", "List configured channels and auth profiles."],
		["fased channels status --probe", "Run channel status checks and probes."],
		["fased channels add --channel telegram --token <token>", "Add or update a channel account non-interactively."],
		["fased channels login --channel whatsapp", "Link a WhatsApp Web account."]
	])}\n\n${theme.muted("Docs:")} ${formatDocsLink("/cli/channels", "docs.fased.ai/cli/channels")}\n`);
	channels.command("list").description("List configured channels + auth profiles").option("--no-usage", "Skip model provider usage/quota snapshots").option("--json", "Output JSON", false).action(async (opts) => {
		await runChannelsCommand(async () => {
			const { channelsListCommand } = await loadChannelsCommands();
			await channelsListCommand(opts, defaultRuntime);
		});
	});
	channels.command("status").description("Show gateway channel status (use status --deep for local)").option("--probe", "Probe channel credentials", false).option("--timeout <ms>", "Timeout in ms", "10000").option("--json", "Output JSON", false).action(async (opts) => {
		await runChannelsCommand(async () => {
			const { channelsStatusCommand } = await loadChannelsCommands();
			await channelsStatusCommand(opts, defaultRuntime);
		});
	});
	channels.command("capabilities").description("Show provider capabilities (intents/scopes + supported features)").option("--channel <name>", `Channel (${formatCliChannelOptions(["all"])})`).option("--account <id>", "Account id (only with --channel)").option("--target <dest>", "Channel target for permission audit (Discord channel:<id>)").option("--timeout <ms>", "Timeout in ms", "10000").option("--json", "Output JSON", false).action(async (opts) => {
		await runChannelsCommand(async () => {
			const { channelsCapabilitiesCommand } = await loadChannelsCommands();
			await channelsCapabilitiesCommand(opts, defaultRuntime);
		});
	});
	channels.command("resolve").description("Resolve channel/user names to IDs").argument("<entries...>", "Entries to resolve (names or ids)").option("--channel <name>", `Channel (${channelNames})`).option("--account <id>", "Account id (accountId)").option("--kind <kind>", "Target kind (auto|user|group)", "auto").option("--json", "Output JSON", false).action(async (entries, opts) => {
		await runChannelsCommand(async () => {
			const { channelsResolveCommand } = await loadChannelsCommands();
			await channelsResolveCommand({
				channel: opts.channel,
				account: opts.account,
				kind: opts.kind,
				json: Boolean(opts.json),
				entries: Array.isArray(entries) ? entries : [String(entries)]
			}, defaultRuntime);
		});
	});
	channels.command("logs").description("Show recent channel logs from the gateway log file").option("--channel <name>", `Channel (${formatCliChannelOptions(["all"])})`, "all").option("--lines <n>", "Number of lines (default: 200)", "200").option("--json", "Output JSON", false).action(async (opts) => {
		await runChannelsCommand(async () => {
			const { channelsLogsCommand } = await loadChannelsCommands();
			await channelsLogsCommand(opts, defaultRuntime);
		});
	});
	channels.command("add").description("Add or update a channel account").option("--channel <name>", `Channel (${channelNames})`).option("--account <id>", "Account id (default when omitted)").option("--name <name>", "Display name for this account").option("--token <token>", "Bot token (Telegram/Discord)").option("--token-file <path>", "Bot token file (Telegram)").option("--bot-token <token>", "Slack bot token (xoxb-...)").option("--app-token <token>", "Slack app token (xapp-...)").option("--signal-number <e164>", "Signal account number (E.164)").option("--cli-path <path>", "CLI path (signal-cli or imsg)").option("--db-path <path>", "iMessage database path").option("--service <service>", "iMessage service (imessage|sms|auto)").option("--region <region>", "iMessage region (for SMS)").option("--auth-dir <path>", "WhatsApp auth directory override").option("--http-url <url>", "Signal HTTP daemon base URL").option("--http-host <host>", "Signal HTTP host").option("--http-port <port>", "Signal HTTP port").option("--webhook-path <path>", "Webhook path (Google Chat/BlueBubbles)").option("--webhook-url <url>", "Google Chat webhook URL").option("--audience-type <type>", "Google Chat audience type (app-url|project-number)").option("--audience <value>", "Google Chat audience value (app URL or project number)").option("--homeserver <url>", "Matrix homeserver URL").option("--user-id <id>", "Matrix user ID").option("--access-token <token>", "Matrix access token").option("--password <password>", "Matrix password").option("--device-name <name>", "Matrix device name").option("--initial-sync-limit <n>", "Matrix initial sync limit").option("--ship <ship>", "Tlon ship name (~sampel-palnet)").option("--url <url>", "Tlon ship URL").option("--code <code>", "Tlon login code").option("--group-channels <list>", "Tlon group channels (comma-separated)").option("--dm-allowlist <list>", "Tlon DM allowlist (comma-separated ships)").option("--auto-discover-channels", "Tlon auto-discover group channels").option("--no-auto-discover-channels", "Disable Tlon auto-discovery").option("--use-env", "Use env token (default account only)", false).action(async (opts, command) => {
		await runChannelsCommand(async () => {
			const { channelsAddCommand } = await loadChannelsCommands();
			await channelsAddCommand(opts, defaultRuntime, { hasFlags: hasExplicitOptions(command, optionNamesAdd) });
		});
	});
	channels.command("remove").description("Disable or delete a channel account").option("--channel <name>", `Channel (${channelNames})`).option("--account <id>", "Account id (default when omitted)").option("--delete", "Delete config entries (no prompt)", false).action(async (opts, command) => {
		await runChannelsCommand(async () => {
			const { channelsRemoveCommand } = await loadChannelsCommands();
			await channelsRemoveCommand(opts, defaultRuntime, { hasFlags: hasExplicitOptions(command, optionNamesRemove) });
		});
	});
	channels.command("login").description("Link a channel account (if supported)").option("--channel <channel>", "Channel alias (auto when only one is configured)").option("--account <id>", "Account id (accountId)").option("--verbose", "Verbose connection logs", false).action(async (opts) => {
		await runChannelsCommandWithDanger(async () => {
			await runChannelLogin({
				channel: opts.channel,
				account: opts.account,
				verbose: Boolean(opts.verbose)
			}, defaultRuntime);
		}, "Channel login failed");
	});
	channels.command("logout").description("Log out of a channel session (if supported)").option("--channel <channel>", "Channel alias (auto when only one is configured)").option("--account <id>", "Account id (accountId)").action(async (opts) => {
		await runChannelsCommandWithDanger(async () => {
			await runChannelLogout({
				channel: opts.channel,
				account: opts.account
			}, defaultRuntime);
		}, "Channel logout failed");
	});
	applyParentDefaultHelpAction(channels);
}

//#endregion
export { registerChannelsCli };