import "./paths-C9FmTW1x.js";
import { L as setVerbose, U as theme, j as danger } from "./agent-paths-BySKyq9I.js";
import { Dn as loadConfig, Mu as getChannelPlugin, Pu as normalizeChannelId } from "./agent-scope-CLn_Ws3B.js";
import "./commands-registry-DfzoWf4b.js";
import "./reply-DQfPM5ia.js";
import { d as defaultRuntime } from "./errors-Dx3S3Nrp.js";
import "./send-DI5jsj-s.js";
import "./send-Dg2_aoK-.js";
import "./github-copilot-token-BA45-q56.js";
import "./chat-envelope-D_wSv26N.js";
import "./pi-model-discovery-BftA1L--.js";
import "./dangerous-tools-C88-uuUI.js";
import "./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 "./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 { n as resolveMessageChannelSelection } from "./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 { n as runCommandWithRuntime } from "./cli-utils-DJ7Nfw8J.js";
import { t as formatHelpExamples } from "./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 "./prompt-style-Db5iJoaI.js";
import "./pairing-labels-sAC1Ty3_.js";
import "./plugin-registry-2aqMgXpl.js";
import { r as formatCliChannelOptions, t as applyParentDefaultHelpAction } from "./parent-default-help-DbMf7NQe.js";
import { t as hasExplicitOptions } from "./command-options-DEPpN8NK.js";
import { t as resolveChannelDefaultAccountId } from "./helpers-BvDnvwsE.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-DvT6s1kl.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 };