UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,536 lines • 52.3 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import "./session-key-CqAyZeVk.mjs";
import { n as normalizeAccountId, t as DEFAULT_ACCOUNT_ID } from "./account-id-BqKT3GuY.mjs";
import { f as resolveAgentWorkspaceDir, m as resolveAmbientOwnerAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { a as getPluginCache, w as withPluginCache } from "./plugin-cache-B_eRuqTM.mjs";
import { n as resolveChannelSetupExecutionAdapter } from "./setup-contract-hyC_qGOR.mjs";
import { r as formatConfigIssueSummary } from "./issue-format-WaYQX-7p.mjs";
import { i as resolveChannelConfigRecord } from "./channel-config-activation-BzEa8FnN.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { r as enablePluginWithCapabilityConsent } from "./enable-BY2SJL8Z.mjs";
import { i as getBundledChannelSetupPlugin } from "./bundled-BnH1gY8j.mjs";
import { t as isChannelConfigured } from "./channel-configured-3z7rRlJy.mjs";
import { r as listChatChannels } from "./chat-meta-CsbrDHrF.mjs";
import { a as createManagedRuntimeEnvBase, t as createConfigIO } from "./io.factory-DEa_bi2j.mjs";
import { n as formatChannelSelectionLine, t as formatChannelPrimerLine } from "./registry-BB86xKJa.mjs";
import { s as withPluginLifecycleLeaseAsync } from "./plugin-lifecycle-lease-CXjHGDEI.mjs";
import { i as resolveChannelAllowFrom, r as resolveChannelAccount } from "./account-resolution-D7u1J1M0.mjs";
import { t as formatDocsLink } from "./links-41lO3DKP.mjs";
import { i as wizardT, r as t } from "./i18n-AiHKCZaZ.mjs";
import { a as resolveBundledPluginSources, n as findBundledPluginSourceInMap } from "./bundled-sources-CIS6N5EC.mjs";
import { i as hasConfiguredCommandOwners, n as formatCommandOwnerFromChannelSender } from "./doctor-command-owner-Dul2IrrD.mjs";
import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs";
import { t as createPluginCapabilityConsentPrompter } from "./plugin-capability-consent-jChdL17s.mjs";
import { s as writeChannelSection } from "./config-helpers-DUK5R_HK.mjs";
import { s as moveSingleAccountChannelSectionToDefaultAccount, u as readChannelConfigSection } from "./setup-helpers-CvNcDZst.mjs";
import { E as resolveAccountIdForConfigure, N as splitSetupEntries, k as runSingleChannelSecretStep, w as promptResolvedAllowFrom } from "./setup-wizard-helpers-BVntL4dp.mjs";
import { t as promptChannelAccessConfig } from "./setup-group-access-COpmFlCA.mjs";
import { t as isAccountEnabled } from "./account-enabled-CulIMLY0.mjs";
import { n as listActiveChannelSetupPlugins, t as getChannelSetupPlugin } from "./setup-registry-UX2m_Nsm.mjs";
import { i as listTrustedChannelPluginCatalogEntries, t as getTrustedChannelPluginCatalogEntry } from "./trusted-catalog-BsRi13Hw.mjs";
import { n as loadChannelSetupPluginRegistrySnapshotForChannel, t as ensureChannelSetupPluginInstalled } from "./plugin-install-CXJAWztN.mjs";
import { i as withCommandPluginMetadata } from "./config-validation-Cy6dkTWs.mjs";
import { t as normalizeExternalChannelSetupConfig } from "./config-compatibility-BpBiCOfQ.mjs";
import { n as resolveChannelSetupEntries, r as shouldShowChannelInSetup } from "./discovery-BgDDeRvz.mjs";
import { n as runWizardWithPromptNavigationScope } from "./navigation-prompter-mPz64WG4.mjs";
//#region src/channels/plugins/setup-wizard.ts
function createWizardAccountScope(e) {
	const n = normalizeAccountId(e.accountId);
	const r = readChannelConfigSection(e.cfg, e.channelKey) ?? {};
	if (n === "default" && r.accounts === void 0) return {
		cfg: e.cfg,
		restore: (e) => e
	};
	const i = moveSingleAccountChannelSectionToDefaultAccount({
		cfg: e.cfg,
		channelKey: e.channelKey,
		setupSurface: e.setupSurface
	});
	const a = readChannelConfigSection(i, e.channelKey) ?? {};
	const o = a.defaultAccount;
	return {
		cfg: writeChannelSection(i, e.channelKey, {
			...a,
			accounts: a.accounts ?? {},
			defaultAccount: n
		}),
		restore: (n) => {
			const r = readChannelConfigSection(n, e.channelKey) ?? {};
			const i = o !== void 0 ? {
				...r,
				defaultAccount: o
			} : (({ defaultAccount: e, ...n }) => n)(r);
			return writeChannelSection(n, e.channelKey, i);
		}
	};
}
async function buildStatus(e, n, r) {
	const i = r.accountOverrides[e.id];
	const a = await n.status.resolveConfigured({
		cfg: r.cfg,
		accountId: i
	});
	const statusContext = () => ({
		cfg: r.cfg,
		accountId: i,
		configured: a
	});
	const o = await n.status.resolveStatusLines?.(statusContext()) ?? [`${e.meta.label}: ${a ? n.status.configuredLabel : n.status.unconfiguredLabel}`];
	const s = await n.status.resolveSelectionHint?.(statusContext()) ?? (a ? n.status.configuredHint : n.status.unconfiguredHint);
	const c = await n.status.resolveQuickstartScore?.(statusContext()) ?? (a ? n.status.configuredScore : n.status.unconfiguredScore);
	return {
		channel: e.id,
		configured: a,
		statusLines: o,
		selectionHint: s,
		quickstartScore: c
	};
}
function resolveTextInputKeepMessage(e, n) {
	if (e.sensitive === true) return typeof e.keepPrompt === "string" ? e.keepPrompt : `${e.message} already configured. Keep it?`;
	return typeof e.keepPrompt === "function" ? e.keepPrompt(n) : e.keepPrompt ?? `${e.message} set (${n}). Keep it?`;
}
function buildChannelSetupWizardAdapterFromSetupWizard(e) {
	const { plugin: n, wizard: r } = e;
	return {
		channel: n.id,
		getStatus: async (e) => buildStatus(n, r, e),
		configure: async ({ cfg: e, runtime: i, prompter: a, options: o, accountOverrides: s, shouldPromptAccountIds: c, forceAllowFrom: l }) => {
			const u = n.config.defaultAccountId?.(e) ?? n.config.listAccountIds(e)[0] ?? "default";
			const d = r.resolveShouldPromptAccountIds?.({
				cfg: e,
				options: o,
				shouldPromptAccountIds: c
			}) ?? c;
			const f = {
				cfg: e,
				prompter: a,
				accountOverride: s[n.id],
				shouldPromptAccountIds: d,
				listAccountIds: n.config.listAccountIds,
				defaultAccountId: u
			};
			const p = await (r.resolveAccountIdForConfigure ? r.resolveAccountIdForConfigure({
				...f,
				options: o
			}) : resolveAccountIdForConfigure({
				...f,
				label: n.meta.label
			}));
			const m = readChannelConfigSection(e, n.id) ?? {};
			const h = r.resolveShouldPromptAccountIds === void 0 || d || m.accounts !== void 0 ? createWizardAccountScope({
				cfg: e,
				channelKey: n.id,
				accountId: p,
				setupSurface: resolveChannelSetupExecutionAdapter(n)
			}) : {
				cfg: e,
				restore: (e) => e
			};
			let g = h.cfg;
			const accountContext = (e = g) => ({
				cfg: e,
				accountId: p
			});
			const collectCredentialValues = () => {
				const e = {};
				for (const n of r.credentials) {
					const r = normalizeOptionalString(n.inspect(accountContext()).resolvedValue);
					if (r) e[n.inputKey] = r;
				}
				return e;
			};
			let _ = collectCredentialValues();
			const stepContext = (e = g) => ({
				...accountContext(e),
				credentialValues: _
			});
			const hookContext = () => ({
				...stepContext(),
				runtime: i,
				prompter: a,
				options: o
			});
			const applyHookResult = (e) => {
				if (e?.cfg) g = e.cfg;
				if (e?.credentialValues) _ = {
					..._,
					...e.credentialValues
				};
			};
			const setCredentialValue = (e, n) => {
				if (n) _[e] = n;
				else delete _[e];
			};
			const applyInput = (e, r = g) => {
				const i = resolveChannelSetupExecutionAdapter(n);
				if (!i?.applyAccountConfig) throw new Error(`${n.id} does not support setup`);
				let a = e;
				if (n.setupContract) {
					const e = n.setupContract.parseInput(a);
					if (!e.ok) throw new Error(e.error);
					a = e.value;
				}
				const setupParams = (e) => ({
					cfg: r,
					accountId: e,
					input: a
				});
				const o = i.resolveAccountId?.(setupParams(p)) ?? p;
				const s = i.validateInput?.(setupParams(o));
				if (s) throw new Error(s);
				let c = i.applyAccountConfig(setupParams(o));
				if (e.name?.trim() && i.applyAccountName) c = i.applyAccountName({
					cfg: c,
					accountId: o,
					name: e.name
				});
				return c;
			};
			let v = false;
			const showNote = async (e) => {
				if (e && (!e.shouldShow || await e.shouldShow(stepContext()))) await a.note(e.lines.join("\n"), e.title);
			};
			if (r.envShortcut?.isAvailable(accountContext())) {
				if (await a.confirm({
					message: r.envShortcut.prompt,
					initialValue: true
				})) {
					g = await r.envShortcut.apply(accountContext());
					_ = collectCredentialValues();
					v = true;
				}
			}
			if (!v) await showNote(r.introNote);
			if (r.prepare) applyHookResult(await r.prepare(hookContext()));
			const runCredentialSteps = async () => {
				if (v) return;
				for (const e of r.credentials) {
					let n = e.inspect(accountContext());
					let r = normalizeOptionalString(n.resolvedValue);
					if (!(e.shouldPrompt ? await e.shouldPrompt({
						...stepContext(),
						currentValue: r,
						state: n
					}) : true)) {
						setCredentialValue(e.inputKey, r);
						continue;
					}
					const i = e.allowEnv?.(accountContext()) ?? false;
					const s = await runSingleChannelSecretStep({
						cfg: g,
						prompter: a,
						providerHint: e.providerHint,
						credentialLabel: e.credentialLabel,
						secretInputMode: o?.secretInputMode,
						accountConfigured: n.accountConfigured,
						hasConfigToken: n.hasConfiguredValue,
						allowEnv: i,
						envValue: n.envValue,
						envPrompt: e.envPrompt,
						keepPrompt: e.keepPrompt,
						inputPrompt: e.inputPrompt,
						preferredEnvVar: e.preferredEnvVar,
						onMissingConfigured: e.helpLines && e.helpLines.length > 0 ? async () => {
							await a.note(e.helpLines.join("\n"), e.helpTitle ?? e.credentialLabel);
						} : void 0,
						applyUseEnv: async (n) => e.applyUseEnv ? await e.applyUseEnv(accountContext(n)) : applyInput({
							[e.inputKey]: void 0,
							useEnv: true
						}, n),
						applySet: async (n, r, i) => e.applySet ? await e.applySet({
							...stepContext(n),
							value: r,
							resolvedValue: i
						}) : applyInput({
							[e.inputKey]: r,
							useEnv: false
						}, n)
					});
					g = s.cfg;
					n = e.inspect(accountContext());
					r = normalizeOptionalString(s.resolvedValue) || normalizeOptionalString(n.resolvedValue);
					setCredentialValue(e.inputKey, r);
				}
			};
			const runTextInputSteps = async () => {
				for (const e of r.textInputs ?? []) {
					const applyValue = async (n) => {
						g = e.applySet ? await e.applySet({
							...accountContext(),
							value: n
						}) : applyInput({ [e.inputKey]: n });
					};
					let n = normalizeOptionalString(_[e.inputKey]);
					if (!n && e.currentValue) n = normalizeOptionalString(await e.currentValue(stepContext()));
					const r = e.shouldPrompt ? await e.shouldPrompt({
						...stepContext(),
						currentValue: n
					}) : true;
					let i = !r;
					if (r) {
						if (e.helpLines && e.helpLines.length > 0) await a.note(e.helpLines.join("\n"), e.helpTitle ?? e.message);
						if (n && e.confirmCurrentValue !== false) i = await a.confirm({
							message: resolveTextInputKeepMessage(e, n),
							initialValue: true
						});
					}
					if (i) {
						if (n) {
							_[e.inputKey] = n;
							if (e.applyCurrentValue) await applyValue(n);
						}
						continue;
					}
					const o = e.sensitive === true ? void 0 : normalizeOptionalString(await e.initialValue?.(stepContext()) ?? n);
					const s = (await a.text({
						message: e.message,
						placeholder: e.placeholder,
						...e.sensitive === true ? {} : { initialValue: o },
						...e.sensitive === true ? { sensitive: true } : {},
						validate: (n) => {
							const r = normalizeOptionalString(n) ?? "";
							if (!r && e.required !== false) return "Required";
							return e.validate?.({
								value: r,
								...stepContext()
							});
						}
					})).trim();
					if (!s && e.required === false) {
						if (e.applyEmptyValue) await applyValue("");
						delete _[e.inputKey];
						continue;
					}
					const c = normalizeOptionalString(e.normalizeValue?.({
						value: s,
						...stepContext()
					}) ?? s);
					if (!c) {
						delete _[e.inputKey];
						continue;
					}
					await applyValue(c);
					_[e.inputKey] = c;
				}
			};
			if (r.stepOrder === "text-first") {
				await runTextInputSteps();
				await runCredentialSteps();
			} else {
				await runCredentialSteps();
				await runTextInputSteps();
			}
			if (r.groupAccess) {
				const e = r.groupAccess;
				if (e.helpLines && e.helpLines.length > 0) await a.note(e.helpLines.join("\n"), e.helpTitle ?? e.label);
				const n = await promptChannelAccessConfig({
					prompter: a,
					label: e.label,
					currentPolicy: e.currentPolicy(accountContext()),
					currentEntries: e.currentEntries(accountContext()),
					placeholder: e.placeholder,
					updatePrompt: e.updatePrompt(accountContext()),
					skipAllowlistEntries: e.skipAllowlistEntries
				});
				if (n) {
					if (n.policy !== "allowlist" || e.skipAllowlistEntries || !e.resolveAllowlist || !e.applyAllowlist) g = e.setPolicy({
						...accountContext(),
						policy: n.policy
					});
					else {
						const r = await e.resolveAllowlist({
							...stepContext(),
							entries: n.entries,
							prompter: a
						});
						g = e.setPolicy({
							...accountContext(),
							policy: "allowlist"
						});
						g = e.applyAllowlist({
							...accountContext(),
							resolved: r
						});
					}
				}
			}
			if (l && r.allowFrom) {
				const e = r.allowFrom;
				const i = e.credentialInputKey ?? r.credentials.find((e) => normalizeOptionalString(_[e.inputKey]))?.inputKey ?? r.credentials[0]?.inputKey;
				const o = normalizeOptionalString(i === void 0 ? void 0 : _[i]);
				if (e.helpLines && e.helpLines.length > 0) await a.note(e.helpLines.join("\n"), e.helpTitle ?? `${n.meta.label} allowlist`);
				const s = await resolveChannelAllowFrom({
					plugin: n,
					...accountContext()
				}) ?? [];
				const c = await promptResolvedAllowFrom({
					prompter: a,
					existing: s,
					token: o,
					message: e.message,
					placeholder: e.placeholder,
					label: e.helpTitle ?? `${n.meta.label} allowlist`,
					parseInputs: e.parseInputs ?? splitSetupEntries,
					parseId: e.parseId,
					invalidWithoutTokenNote: e.invalidWithoutCredentialNote,
					resolveEntries: async ({ entries: n }) => e.resolveEntries({
						...stepContext(),
						entries: n
					})
				});
				g = await e.apply({
					...accountContext(),
					allowFrom: c
				});
			}
			if (r.finalize) applyHookResult(await r.finalize({
				...hookContext(),
				forceAllowFrom: l
			}));
			await showNote(r.completionNote);
			return {
				cfg: h.restore(g),
				accountId: p
			};
		},
		dmPolicy: r.dmPolicy,
		disable: r.disable,
		onAccountRecorded: r.onAccountRecorded
	};
}
//#endregion
//#region src/commands/channel-setup/registry.ts
const setupWizardAdapters = /* @__PURE__ */ new WeakMap();
/** Resolve the setup wizard adapter exposed by one channel plugin, caching declarative adapters. */
function resolveChannelSetupWizardAdapterForPlugin(e) {
	if (!e) return;
	const { setupWizard: n } = e;
	if (!n) return;
	if ("getStatus" in n) return n;
	const r = setupWizardAdapters.get(e);
	if (r) return r;
	const i = buildChannelSetupWizardAdapterFromSetupWizard({
		plugin: e,
		wizard: n
	});
	setupWizardAdapters.set(e, i);
	return i;
}
//#endregion
//#region src/flows/channel-setup-fallback.ts
/** Shows the standard "enable it before setup" note for disabled-policy guards. */
async function noteDisabledBeforeSetup(e, n, r) {
	await e.note(t("wizard.channels.disabledBeforeSetup", {
		channel: n,
		hint: r
	}), t("wizard.channels.setupTitle"));
}
//#endregion
//#region src/flows/channel-setup-navigation.ts
async function runScopedChannelStep(e) {
	return await runWizardWithPromptNavigationScope(e.prompter, async (n) => e.runner(n, {
		...e.options,
		beforePersistentEffect: async () => {
			e.onPersistentEffect?.();
			n.disableBackNavigation?.();
			await e.options?.beforePersistentEffect?.();
		}
	}));
}
async function ensureChannelSetupPluginInstalledWithNavigation(e) {
	let n = false;
	return {
		...await runScopedChannelStep({
			prompter: e.prompter,
			options: e.options,
			runner: async (n, r) => await ensureChannelSetupPluginInstalled({
				...e.install,
				prompter: n,
				beforePersistentEffect: r.beforePersistentEffect
			}),
			onPersistentEffect: () => {
				n = true;
			}
		}),
		persistentEffectStarted: n
	};
}
//#endregion
//#region src/flows/channel-setup.disabled.ts
function createChannelSetupDisabledHints(e) {
	const resolveConfigDisabledHint = (n) => {
		const r = e.getConfig();
		if (r.plugins?.enabled === false) return "plugins disabled";
		if (r.plugins?.entries?.[n]?.enabled === false) return "plugin disabled";
		return resolveChannelConfigRecord(r, n)?.enabled === false ? "disabled" : void 0;
	};
	const resolveAccountDisabledHint = async (n, r) => {
		const i = e.getPlugin(n);
		if (!i) return;
		const a = e.getConfig();
		const o = await resolveChannelAccount({
			plugin: i,
			cfg: a,
			accountId: r ?? resolveChannelDefaultAccountId({
				plugin: i,
				cfg: a
			})
		});
		return (i.config.isEnabled ? i.config.isEnabled(o, e.getConfig()) : isAccountEnabled(o)) ? void 0 : "disabled";
	};
	const resolveDisabledHint = async (n) => {
		const r = resolveConfigDisabledHint(n);
		return r || e.deferStatusUntilSelection ? r : resolveAccountDisabledHint(n);
	};
	return {
		resolveConfigDisabledHint,
		resolveAccountDisabledHint,
		resolveDisabledHint
	};
}
//#endregion
//#region src/flows/channel-setup.prompts.ts
function formatAccountLabel(e) {
	return e === "default" ? "default (primary)" : e;
}
/** Separates the operator's administrative identity from channel chat access. */
async function maybeConfigureCommandOwner(e) {
	const { cfg: n, channels: r, prompter: i } = e;
	if (hasConfiguredCommandOwners(n) || r.length === 0) return n;
	await i.note(t("wizard.channels.commandOwnerHelp"), t("wizard.channels.commandOwnerTitle"));
	if (await i.select({
		message: t("wizard.channels.commandOwnerSetup"),
		options: [{
			value: "setup",
			label: t("wizard.channels.commandOwnerOwnAccount")
		}, {
			value: "skip",
			label: t("common.skipForNow")
		}],
		initialValue: "skip"
	}) !== "setup") return n;
	const a = r.length === 1 ? r[0].id : await i.select({
		message: t("wizard.channels.commandOwnerChannel"),
		options: r.toSorted((e, n) => e.label.localeCompare(n.label)).map(({ id: e, label: n }) => ({
			value: e,
			label: n
		}))
	});
	const o = r.find(({ id: e }) => e === a);
	const s = (await i.text({
		message: t("wizard.channels.commandOwnerUserId", { label: o.label }),
		validate: (e) => !e.trim() || /[\s*]/.test(e.trim()) ? t("wizard.channels.commandOwnerInvalidId") : void 0
	})).trim();
	const c = formatCommandOwnerFromChannelSender({
		channel: o.id,
		id: s
	});
	if (!c) return n;
	if (!await i.confirm({
		message: t("wizard.channels.commandOwnerConfirm", { owner: c }),
		initialValue: false
	})) return n;
	return {
		...n,
		commands: {
			...n.commands,
			ownerAllowFrom: [c]
		}
	};
}
async function promptConfiguredAction(e) {
	const { prompter: n, label: r, supportsDisable: i, supportsDelete: a } = e;
	const o = [
		{
			value: "update",
			label: t("wizard.channels.modifySettings")
		},
		...i ? [{
			value: "disable",
			label: t("wizard.channels.disableKeepConfig")
		}] : [],
		...a ? [{
			value: "delete",
			label: t("wizard.channels.deleteConfig")
		}] : [],
		{
			value: "skip",
			label: t("wizard.channels.skipLeaveAsIs")
		}
	];
	return await n.select({
		message: t("wizard.channels.configuredAction", { label: r }),
		options: o,
		initialValue: "update"
	});
}
async function promptRemovalAccountId(e) {
	const { cfg: n, prompter: r, label: i, channel: a } = e;
	const o = e.plugin ?? getChannelSetupPlugin(a);
	if (!o) return DEFAULT_ACCOUNT_ID;
	const s = o.config.listAccountIds(n).filter(Boolean);
	const c = resolveChannelDefaultAccountId({
		plugin: o,
		cfg: n,
		accountIds: s
	});
	if (s.length <= 1) return c;
	const l = await r.select({
		message: t("wizard.channels.account", { label: i }),
		options: s.map((e) => ({
			value: e,
			label: formatAccountLabel(e)
		})),
		initialValue: c
	});
	return normalizeAccountId(l) ?? c;
}
async function maybeConfigureDmPolicies(e) {
	const { selection: n, prompter: r, accountIdsByChannel: i } = e;
	const a = n.map((n) => e.resolveAdapter(n)?.dmPolicy).filter((e) => e !== void 0);
	if (a.length === 0) return e.cfg;
	if (!await r.confirm({
		message: t("wizard.channels.configureDmPolicies"),
		initialValue: false
	})) return e.cfg;
	let o = e.cfg;
	for (const e of a) {
		const n = i?.get(e.channel);
		const { policyKey: a, allowFromKey: s } = e.resolveConfigKeys?.(o, n) ?? {
			policyKey: e.policyKey,
			allowFromKey: e.allowFromKey
		};
		await r.note([
			t("wizard.channels.dmPolicyDefault"),
			t("wizard.channels.dmPolicyApprove", { command: formatCliCommand(`openclaw pairing approve ${e.channel} <code>`) }),
			t("wizard.channels.dmPolicyAllowlist", {
				allowFromKey: s,
				policyKey: a
			}),
			t("wizard.channels.dmPolicyOpen", {
				allowFromKey: s,
				policyKey: a
			}),
			t("wizard.channels.dmPolicyMultiUser", { command: formatCliCommand("openclaw config set session.dmScope \"per-channel-peer\"") }),
			t("wizard.channels.docs", { link: formatDocsLink("/channels/pairing", "channels/pairing") })
		].join("\n"), t("wizard.channels.dmAccessTitle", { label: e.label }));
		const c = await r.select({
			message: t("wizard.channels.dmPolicy", { label: e.label }),
			options: [
				{
					value: "pairing",
					label: t("wizard.channels.dmPolicyPairing")
				},
				{
					value: "allowlist",
					label: t("wizard.channels.dmPolicyAllowlistOption")
				},
				{
					value: "open",
					label: t("wizard.channels.dmPolicyOpenOption")
				},
				{
					value: "disabled",
					label: t("wizard.channels.dmPolicyDisabledOption")
				}
			]
		});
		if (c !== e.getCurrent(o, n)) o = e.setPolicy(o, c, n);
		if (c === "allowlist" && e.promptAllowFrom) o = await e.promptAllowFrom({
			cfg: o,
			prompter: r,
			accountId: n
		});
	}
	return o;
}
//#endregion
//#region src/flows/channel-setup.status.ts
function resolveChannelSetupWorkspaceDir(e) {
	const n = resolveAmbientOwnerAgentId(e, void 0, {
		surface: "channel setup",
		hint: "Set agents.defaults.systemAgent.agentId before configuring channels."
	});
	return resolveAgentWorkspaceDir(e, n);
}
const CHANNEL_PRIMER_BLURB_KEYS = {
	clickclack: "wizard.channelsPrimer.blurbs.clickclack",
	discord: "wizard.channelsPrimer.blurbs.discord",
	feishu: "wizard.channelsPrimer.blurbs.feishu",
	googlechat: "wizard.channelsPrimer.blurbs.googlechat",
	imessage: "wizard.channelsPrimer.blurbs.imessage",
	irc: "wizard.channelsPrimer.blurbs.irc",
	line: "wizard.channelsPrimer.blurbs.line",
	mattermost: "wizard.channelsPrimer.blurbs.mattermost",
	matrix: "wizard.channelsPrimer.blurbs.matrix",
	msteams: "wizard.channelsPrimer.blurbs.msteams",
	"nextcloud-talk": "wizard.channelsPrimer.blurbs.nextcloudTalk",
	nostr: "wizard.channelsPrimer.blurbs.nostr",
	qqbot: "wizard.channelsPrimer.blurbs.qqbot",
	signal: "wizard.channelsPrimer.blurbs.signal",
	slack: "wizard.channelsPrimer.blurbs.slack",
	"synology-chat": "wizard.channelsPrimer.blurbs.synologyChat",
	telegram: "wizard.channelsPrimer.blurbs.telegram",
	tlon: "wizard.channelsPrimer.blurbs.tlon",
	twitch: "wizard.channelsPrimer.blurbs.twitch",
	wecom: "wizard.channelsPrimer.blurbs.wecom",
	whatsapp: "wizard.channelsPrimer.blurbs.whatsapp",
	yuanbao: "wizard.channelsPrimer.blurbs.yuanbao",
	zalo: "wizard.channelsPrimer.blurbs.zalo",
	zalouser: "wizard.channelsPrimer.blurbs.zalouser"
};
function formatSetupSelectionLabel(e, n = "") {
	return sanitizeTerminalText(e ?? "").trim() || sanitizeTerminalText(n).trim() || "<invalid channel>";
}
function formatSetupSelectionHint(e) {
	if (!e) return;
	return sanitizeTerminalText(e) || void 0;
}
function formatSetupFreeText(e) {
	return sanitizeTerminalText(e ?? "").trim();
}
function formatSetupOptionalDisplayText(e) {
	return formatSetupFreeText(e) || void 0;
}
function formatSetupDisplayList(e) {
	const n = (e ?? []).flatMap((e) => {
		const n = formatSetupOptionalDisplayText(e);
		return n ? [n] : [];
	});
	return n.length > 0 ? n : void 0;
}
function formatSetupDisplayMeta(e) {
	const { selectionDocsPrefix: n, ...r } = e;
	const i = formatSetupSelectionLabel(e.id, "<invalid channel>");
	const a = formatSetupSelectionLabel(e.label, i);
	const o = n === "" ? "" : formatSetupOptionalDisplayText(n?.trim());
	const s = formatSetupDisplayList(e.selectionExtras);
	return {
		...r,
		id: i,
		label: a,
		selectionLabel: formatSetupSelectionLabel(e.selectionLabel, a),
		docsPath: formatSetupSelectionLabel(e.docsPath, "/"),
		...e.docsLabel ? { docsLabel: formatSetupSelectionLabel(e.docsLabel, i) } : {},
		blurb: formatSetupFreeText(e.blurb),
		...o !== void 0 ? { selectionDocsPrefix: o } : {},
		...s ? { selectionExtras: s } : {}
	};
}
function formatChannelPrimerBlurb(e) {
	const n = CHANNEL_PRIMER_BLURB_KEYS[e.id];
	if (!n) return e.blurb;
	const r = wizardT(n, void 0, { locale: "en" });
	return e.blurb === r ? t(n) : e.blurb;
}
function formatChannelSelectionMeta(e) {
	const n = formatSetupDisplayMeta({
		...e,
		blurb: formatChannelPrimerBlurb(e)
	});
	n.selectionDocsPrefix ??= t("common.docs");
	return n;
}
const CHANNEL_STATUS_LABEL_KEYS = /* @__PURE__ */ new Map([
	["configured", "wizard.channels.statusConfigured"],
	["not configured", "wizard.channels.statusNotConfigured"],
	["configured (plugin disabled)", "wizard.channels.statusConfiguredPluginDisabled"],
	["installed", "wizard.channels.statusInstalled"],
	["installed (plugin disabled)", "wizard.channels.statusInstalledPluginDisabled"],
	["bundled · enable to use", "wizard.channels.statusBundledEnable"],
	["install plugin to enable", "wizard.channels.statusInstallPluginEnable"],
	["needs app credentials", "wizard.channels.statusNeedsAppCredentials"],
	["needs app creds", "wizard.channels.statusNeedsAppCreds"],
	["needs auth", "wizard.channels.statusNeedsAuth"],
	["needs host + nick", "wizard.channels.statusNeedsHostNick"],
	["needs private key", "wizard.channels.statusNeedsPrivateKey"],
	["needs QR login", "wizard.channels.statusNeedsQrLogin"],
	["needs service account", "wizard.channels.statusNeedsServiceAccount"],
	["needs setup", "wizard.channels.statusNeedsSetup"],
	["needs token", "wizard.channels.statusNeedsToken"],
	["needs tokens", "wizard.channels.statusNeedsTokens"],
	["needs token + incoming webhook", "wizard.channels.statusNeedsTokenIncomingWebhook"],
	["needs token + secret", "wizard.channels.statusNeedsTokenSecret"],
	["needs token + url", "wizard.channels.statusNeedsTokenUrl"],
	["needs username, token, and clientId", "wizard.channels.statusNeedsUsernameTokenClientId"],
	["linked", "wizard.channels.statusLinked"],
	["logged in", "wizard.channels.statusLoggedIn"],
	["not linked", "wizard.channels.statusNotLinked"],
	["recommended · configured", "wizard.channels.statusRecommendedConfigured"],
	["recommended · logged in", "wizard.channels.statusRecommendedLoggedIn"],
	["recommended · newcomer-friendly", "wizard.channels.statusRecommendedNewcomerFriendly"],
	["recommended · QR login", "wizard.channels.statusRecommendedQrLogin"],
	["self-hosted chat", "wizard.channels.statusSelfHostedChat"],
	["signal-cli found", "wizard.channels.statusSignalCliFound"],
	["signal-cli missing", "wizard.channels.statusSignalCliMissing"],
	["urbit messenger", "wizard.channels.statusUrbitMessenger"],
	["configured (connection not verified)", "wizard.channels.statusConfiguredConnectionNotVerified"]
]);
function localizeChannelStatusLabel(e) {
	const n = CHANNEL_STATUS_LABEL_KEYS.get(e);
	if (n) return t(n);
	if (e.startsWith("connected as ")) return t("wizard.channels.statusConnectedAs", { name: e.slice(13) });
	return e;
}
function localizeChannelStatusLine(e) {
	const n = e.lastIndexOf(": ");
	if (n < 0) return localizeChannelStatusLabel(e);
	return `${e.slice(0, n + 2)}${localizeChannelStatusLabel(e.slice(n + 2))}`;
}
function localizeChannelSetupStatus(e) {
	return {
		...e,
		statusLines: e.statusLines.map(localizeChannelStatusLine),
		...e.selectionHint ? { selectionHint: localizeChannelStatusLabel(e.selectionHint) } : {}
	};
}
function resolveCatalogChannelSelectionHint(e, n) {
	const r = e.install?.npmSpec?.trim();
	if (r && !n?.bundledLocalPath) return `download from ${formatSetupSelectionLabel(r, r)}`;
	return "";
}
function findBundledSourceForCatalogChannel(e) {
	const n = e.entry.pluginId?.trim() || e.entry.id.trim();
	if (n) {
		const r = findBundledPluginSourceInMap({
			bundled: e.bundled,
			lookup: {
				kind: "pluginId",
				value: n
			}
		});
		if (r) return r;
	}
	const r = e.entry.install?.npmSpec?.trim();
	if (r) return findBundledPluginSourceInMap({
		bundled: e.bundled,
		lookup: {
			kind: "npmSpec",
			value: r
		}
	});
}
async function collectChannelStatus(e) {
	const { installedPlugins: n, resolveAdapter: r } = e;
	const i = e.workspaceDir ?? resolveChannelSetupWorkspaceDir(e.cfg);
	const { installedCatalogEntries: a, installableCatalogEntries: o } = resolveChannelSetupEntries({
		cfg: e.cfg,
		installedPlugins: n,
		workspaceDir: i
	});
	const s = resolveBundledPluginSources({ workspaceDir: i });
	const c = (await Promise.all(n.filter((e) => shouldShowChannelInSetup(e.meta)).map(async (n) => {
		try {
			const i = r(n.id);
			if (!i) return;
			return await i.getStatus({
				cfg: e.cfg,
				options: e.options,
				accountOverrides: e.accountOverrides
			});
		} catch (r) {
			const i = formatSetupFreeText(formatErrorMessage(r));
			return {
				channel: n.id,
				configured: isChannelConfigured(e.cfg, n.id),
				statusLines: [`${formatSetupSelectionLabel(n.meta.label, n.id)}: status unavailable (${i})`],
				selectionHint: "status unavailable"
			};
		}
	}))).filter((e) => e !== void 0);
	const l = new Set(c.map((e) => e.channel));
	const u = listChatChannels().filter((e) => shouldShowChannelInSetup(e)).filter((e) => !l.has(e.id)).map((n) => {
		const r = isChannelConfigured(e.cfg, n.id);
		const i = r ? "configured (plugin disabled)" : "not configured";
		return {
			channel: n.id,
			configured: r,
			statusLines: [`${formatSetupSelectionLabel(n.label, n.id)}: ${i}`],
			selectionHint: r ? "configured · plugin disabled" : "not configured",
			quickstartScore: 0
		};
	});
	const d = a.filter((e) => !l.has(e.id)).map((n) => {
		const r = isChannelConfigured(e.cfg, n.id);
		const i = e.cfg.plugins?.entries?.[n.pluginId ?? n.id]?.enabled !== false;
		const a = r ? i ? "configured" : "configured (plugin disabled)" : i ? "installed" : "installed (plugin disabled)";
		return {
			channel: n.id,
			configured: r,
			statusLines: [`${formatSetupSelectionLabel(n.meta.label, n.id)}: ${a}`],
			selectionHint: a,
			quickstartScore: 0
		};
	});
	const f = o.map((e) => {
		const n = findBundledSourceForCatalogChannel({
			bundled: s,
			entry: e
		})?.localPath ?? null;
		const r = Boolean(n) ? "bundled · enable to use" : "install plugin to enable";
		return {
			channel: e.id,
			configured: false,
			statusLines: [`${formatSetupSelectionLabel(e.meta.label, e.id)}: ${r}`],
			selectionHint: resolveCatalogChannelSelectionHint(e, { bundledLocalPath: n }),
			quickstartScore: 0
		};
	});
	const p = [
		...c,
		...u,
		...d,
		...f
	].map(localizeChannelSetupStatus);
	return {
		statusByChannel: new Map(p.map((e) => [e.channel, e])),
		statusLines: p.flatMap((e) => e.statusLines)
	};
}
async function noteChannelPrimer(e, n) {
	const r = n.map((e) => formatChannelPrimerLine(formatSetupDisplayMeta({
		id: e.id,
		label: e.label,
		selectionLabel: e.label,
		docsPath: "/",
		blurb: formatChannelPrimerBlurb(e)
	})));
	await e.note([
		t("wizard.channelsPrimer.inboundSafety"),
		t("wizard.channelsPrimer.approveWith", { command: formatCliCommand("openclaw pairing approve <channel> <code>") }),
		t("wizard.channelsPrimer.openDm"),
		t("wizard.channelsPrimer.multiUserDm", { command: formatCliCommand("openclaw config set session.dmScope \"per-channel-peer\"") }),
		t("wizard.channelsPrimer.docs", { link: formatDocsLink("/channels/pairing", "channels/pairing") }),
		"",
		...r
	].join("\n"), t("wizard.channelsPrimer.title"));
}
function resolveQuickstartDefault(e) {
	let n = null;
	for (const [r, i] of e) {
		if (i.quickstartScore == null) continue;
		if (!n || i.quickstartScore > n.score) n = {
			channel: r,
			score: i.quickstartScore
		};
	}
	return n?.channel;
}
function resolveChannelSelectionNoteLines(e) {
	const { entries: n } = resolveChannelSetupEntries({
		cfg: e.cfg,
		installedPlugins: e.installedPlugins,
		workspaceDir: e.workspaceDir ?? resolveChannelSetupWorkspaceDir(e.cfg)
	});
	const r = /* @__PURE__ */ new Map();
	for (const e of n) r.set(e.id, formatChannelSelectionLine(formatChannelSelectionMeta(e.meta), formatDocsLink));
	return e.selection.map((e) => r.get(e)).filter((e) => Boolean(e));
}
function resolveChannelSetupSelectionOptions(e) {
	return e.entries.filter((e) => shouldShowChannelInSetup(e.meta)).toSorted((e, n) => compareChannelSetupSelectionEntries(e, n)).map((n) => {
		const r = e.resolveDisabledHint(n.id);
		const i = e.statusByChannel.get(n.id)?.selectionHint;
		const a = formatSetupSelectionHint([i, r].filter(Boolean).join(" · ") || void 0);
		return Object.assign({
			value: n.id,
			label: formatSetupSelectionLabel(n.meta.selectionLabel ?? n.meta.label, n.id)
		}, a ? { hint: a } : void 0);
	});
}
function compareChannelSetupSelectionEntries(e, n) {
	const r = e.meta.selectionLabel ?? e.meta.label;
	const i = n.meta.selectionLabel ?? n.meta.label;
	return r.localeCompare(i, void 0, {
		numeric: true,
		sensitivity: "base"
	}) || e.id.localeCompare(n.id, void 0, {
		numeric: true,
		sensitivity: "base"
	});
}
//#endregion
//#region src/flows/channel-setup.ts
function createChannelSetupHooks(e) {
	const n = /* @__PURE__ */ new Map();
	return {
		onPostWriteHook: (e) => {
			n.set(`${e.channel}:${e.accountId}`, e);
		},
		async runPostWriteHooks(r) {
			await runCollectedChannelOnboardingPostWriteHooks({
				hooks: [...n.values()],
				configPath: r,
				runtime: e.runtime,
				...e.beforePersistentEffect ? { beforePersistentEffect: e.beforePersistentEffect } : {}
			});
			n.clear();
		}
	};
}
async function runCollectedChannelOnboardingPostWriteHooks(e) {
	if (e.hooks.length === 0) return;
	const { snapshot: n, pluginMetadataSnapshot: r } = await createConfigIO({
		configPath: e.configPath,
		env: createManagedRuntimeEnvBase(),
		observe: false
	}).readConfigFileSnapshotWithPluginMetadata({ allowCurrentPluginMetadata: false });
	await withCommandPluginMetadata({
		config: n.runtimeConfig,
		snapshot: r
	}, async () => {
		for (const r of e.hooks) {
			await e.beforePersistentEffect?.();
			try {
				if (!n.exists || !n.valid) {
					const e = n.exists ? formatConfigIssueSummary(n.issues) : "file not found";
					throw new Error(`Saved config is unavailable: ${e}. Run openclaw doctor --fix, then retry setup.`);
				}
				await r.run({
					cfg: n.runtimeConfig,
					runtime: e.runtime
				});
			} catch (n) {
				const i = formatErrorMessage(n);
				e.runtime.error(`Channel ${r.channel} post-setup warning for "${r.accountId}": ${i}`);
			}
		}
	});
}
function createChannelOnboardingPostWriteHook(e) {
	if (!e.accountId || !e.adapter?.afterConfigWritten) return;
	return {
		channel: e.channel,
		accountId: e.accountId,
		run: async ({ cfg: n, runtime: r }) => await e.adapter?.afterConfigWritten?.({
			previousCfg: e.previousCfg,
			cfg: n,
			accountId: e.accountId,
			runtime: r
		})
	};
}
async function setupChannels(e, n, r, i) {
	let a = e;
	const o = i?.deferStatusUntilSelection === true;
	const s = new Set(i?.forceAllowFromChannels ?? []);
	const c = { ...i?.accountIds };
	const l = /* @__PURE__ */ new Map();
	let u = i?.workspaceDir;
	const resolveWorkspaceDir = () => u ??= resolveChannelSetupWorkspaceDir(a);
	const d = /* @__PURE__ */ new Map();
	const rememberActivePlugin = (e) => {
		d.set(e.id, e);
		return e;
	};
	const getVisibleChannelPlugin = (e) => l.get(e) ?? d.get(e);
	const listVisibleInstalledPlugins = () => {
		const e = /* @__PURE__ */ new Map();
		for (const n of [...listActiveChannelSetupPlugins().map(rememberActivePlugin), ...l.values()]) if (shouldShowChannelInSetup(n.meta)) e.set(n.id, n);
		return Array.from(e.values());
	};
	const resolveVisibleChannelEntries = () => resolveChannelSetupEntries({
		cfg: a,
		installedPlugins: listVisibleInstalledPlugins(),
		workspaceDir: resolveWorkspaceDir()
	});
	const loadScopedChannelPlugin = async (e, r, i = false) => {
		const o = getVisibleChannelPlugin(e);
		if (o && !i) return o;
		const s = await loadChannelSetupPluginRegistrySnapshotForChannel({
			cfg: a,
			runtime: n,
			channel: e,
			...r ? { pluginId: r } : {},
			workspaceDir: resolveWorkspaceDir(),
			forceSetupOnlyChannelPlugins: true
		});
		const c = s.channelSetups.find((n) => n.plugin.id === e)?.plugin ?? s.channels.find((n) => n.plugin.id === e)?.plugin ?? getBundledChannelSetupPlugin(e);
		if (c) l.set(c.id, c);
		return c;
	};
	const f = getPluginCache();
	const enableChannelPluginForSetup = async (e) => {
		const n = await withPluginLifecycleLeaseAsync({}, async () => {
			const n = await enablePluginWithCapabilityConsent(a, e, {
				workspaceDir: resolveWorkspaceDir(),
				onCapabilityConsent: createPluginCapabilityConsentPrompter(r, i?.beforePersistentEffect)
			});
			a = n.config;
			if (n.enabled) await withPluginCache(f, () => loadScopedChannelPlugin(e));
			return n;
		});
		if (!n.enabled) await r.note(t("wizard.channels.pluginEnableFailed", {
			channel: e,
			reason: n.reason ?? "plugin disabled",
			command: formatCliCommand("openclaw plugins list")
		}), t("wizard.channels.setupTitle"));
		return n.enabled;
	};
	const getVisibleSetupFlowAdapter = (e) => resolveChannelSetupWizardAdapterForPlugin(getVisibleChannelPlugin(e));
	const preloadConfiguredExternalPlugins = async () => {
		listVisibleInstalledPlugins();
		const e = resolveWorkspaceDir();
		const n = [];
		for (const r of listTrustedChannelPluginCatalogEntries({
			cfg: a,
			workspaceDir: e
		})) {
			const e = r.id;
			if (getVisibleChannelPlugin(e)) continue;
			if (!(a.plugins?.entries?.[r.pluginId ?? e]?.enabled === true) && !isChannelConfigured(a, e)) continue;
			n.push(loadScopedChannelPlugin(e, r.pluginId));
		}
		await Promise.all(n);
	};
	if (!o) await preloadConfiguredExternalPlugins();
	const { statusByChannel: p, statusLines: m } = o ? {
		statusByChannel: /* @__PURE__ */ new Map(),
		statusLines: []
	} : await withCommandPluginMetadata({
		config: a,
		workspaceDir: resolveWorkspaceDir()
	}, () => collectChannelStatus({
		cfg: a,
		workspaceDir: resolveWorkspaceDir(),
		options: i,
		accountOverrides: c,
		installedPlugins: listVisibleInstalledPlugins(),
		resolveAdapter: getVisibleSetupFlowAdapter
	}));
	if (!i?.skipStatusNote && m.length > 0) await r.note(m.join("\n"), t("wizard.channels.statusTitle"));
	const h = i?.finishAfterInitialSelection && i.initialSelection?.length === 1 ? i.initialSelection[0] : void 0;
	if (!(i?.skipConfirm || h ? true : await r.confirm({
		message: t("wizard.channels.setupConfirm"),
		initialValue: true
	}))) return e;
	const g = resolveVisibleChannelEntries().entries.map((e) => ({
		id: e.id,
		label: e.meta.label,
		blurb: e.meta.blurb
	}));
	await noteChannelPrimer(r, g);
	const _ = i?.initialSelection?.[0] ?? (o ? void 0 : resolveQuickstartDefault(p));
	const v = i?.promptAccountIds === true;
	const y = /* @__PURE__ */ new Map();
	const recordAccount = (e, n) => {
		i?.onAccountId?.(e, n);
		getVisibleSetupFlowAdapter(e)?.onAccountRecorded?.(n, i);
		y.set(e, n);
	};
	const b = [];
	let x = false;
	const addSelection = (e) => {
		if (!b.includes(e)) b.push(e);
	};
	const { resolveConfigDisabledHint: S, resolveAccountDisabledHint: C, resolveDisabledHint: w } = createChannelSetupDisabledHints({
		getConfig: () => a,
		getPlugin: getVisibleChannelPlugin,
		deferStatusUntilSelection: o
	});
	const buildStatusByChannelForSelection = (e) => {
		const n = new Map(p);
		if (e.size === 0) return n;
		const r = resolveBundledPluginSources({ workspaceDir: resolveWorkspaceDir() });
		for (const [i, a] of e) {
			if (n.has(i)) continue;
			const e = findBundledSourceForCatalogChannel({
				bundled: r,
				entry: a
			})?.localPath ?? null;
			n.set(i, {
				channel: i,
				configured: false,
				statusLines: [],
				selectionHint: resolveCatalogChannelSelectionHint(a, { bundledLocalPath: e })
			});
		}
		return n;
	};
	const resolveSelectionOptions = () => withCommandPluginMetadata({
		config: a,
		workspaceDir: resolveWorkspaceDir()
	}, async () => {
		const { entries: e, installableCatalogById: n } = resolveVisibleChannelEntries();
		const r = /* @__PURE__ */ new Map();
		for (const n of e) if (shouldShowChannelInSetup(n.meta)) r.set(n.id, await w(n.id));
		return resolveChannelSetupSelectionOptions({
			entries: e,
			statusByChannel: buildStatusByChannelForSelection(n),
			resolveDisabledHint: (e) => r.get(e)
		});
	});
	const refreshStatus = async (e) => await withCommandPluginMetadata({
		config: a,
		workspaceDir: resolveWorkspaceDir()
	}, async () => {
		const n = getVisibleSetupFlowAdapter(e);
		if (!n) return;
		const r = await n.getStatus({
			cfg: a,
			options: i,
			accountOverrides: c
		});
		p.set(e, r);
		return r;
	});
	const enableBundledPluginForSetup = async (e) => {
		const n = S(e);
		if (n) {
			await r.note(t("wizard.channels.disabledDuringSetup", {
				channel: e,
				hint: n,
				command: formatCliCommand("openclaw channels add")
			}), t("wizard.channels.setupTitle"));
			return false;
		}
		if (!await enableChannelPluginForSetup(e)) return false;
		if (!getVisibleChannelPlugin(e)) {
			await r.note(t("wizard.channels.pluginNotAvailable", { channel: e }), t("wizard.channels.setupTitle"));
			return false;
		}
		await refreshStatus(e);
		return true;
	};
	const applySetupResult = async (e, n) => {
		const o = a;
		a = normalizeExternalChannelSetupConfig({
			cfg: n.cfg,
			channel: e
		});
		if (n.completion === "paused") {
			x = true;
			return;
		}
		const s = getVisibleChannelPlugin(e);
		if (s) i?.onResolvedPlugin?.(e, s);
		const c = getVisibleSetupFlowAdapter(e);
		if (n.accountId) {
			recordAccount(e, n.accountId);
			const r = createChannelOnboardingPostWriteHook({
				accountId: n.accountId,
				adapter: c,
				channel: e,
				previousCfg: o
			});
			if (r) {
				if (!i?.onPostWriteHook) throw new Error(`Channel setup internal error: ${e} produced a post-write hook without a transaction sink.`);
				i.onPostWriteHook(r);
			}
		}
		addSelection(e);
		if (e === h) x = true;
		try {
			await refreshStatus(e);
		} catch (n) {
			const i = sanitizeTerminalText(formatErrorMessage(n));
			p.set(e, {
				channel: e,
				configured: isChannelConfigured(a, e),
				statusLines: [],
				selectionHint: "status unavailable"
			});
			await r.note(`Status unavailable (${i}).\nRetry: ${formatCliCommand(`openclaw channels status --channel ${e}`)}`, t("wizard.channels.statusTitle"));
		}
	};
	const applyCustomSetupResult = async (e, n) => {
		if (n !== "skip") await applySetupResult(e, n);
	};
	const runScopedChannelStep$1 = async (e) => await runScopedChannelStep({
		prompter: r,
		options: i,
		runner: (n, r) => withCommandPluginMetadata({
			config: a,
			workspaceDir: resolveWorkspaceDir()
		}, () => e(n, r))
	});
	const channelSetupContext = (e, r, i) => ({
		cfg: a,
		runtime: n,
		prompter: r,
		options: i,
		accountOverrides: c,
		shouldPromptAccountIds: v,
		forceAllowFrom: s.has(e)
	});
	const configureChannel = async (e, n, i) => {
		if (l.has(e)) await loadScopedChannelPlugin(e, void 0, true);
		const a = getVisibleSetupFlowAdapter(e);
		if (!a) {
			await r.note(t("wizard.channels.noInteractiveSetup", {
				channel: e,
				command: formatCliCommand(`openclaw channels add --channel ${e} --help`)
			}), t("wizard.channels.setupTitle"));
			return;
		}
		const o = await a.configure(channelSetupContext(e, n, i));
		await applySetupResult(e, o);
	};
	const handleConfiguredChannel = async (e, n, r, i) => {
		const o = getVisibleChannelPlugin(e);
		const s = getVisibleSetupFlowAdapter(e);
		if (s?.configureWhenConfigured) {
			const a = await s.configureWhenConfigured({
				...channelSetupContext(e, r, i),
				configured: true,
				label: n
			});
			await applyCustomSetupResult(e, a);
			return;
		}
		const c = Boolean(i.allowDisable && (o?.config.setAccountEnabled || s?.disable));
		const l = Boolean(i.allowDisable && o?.config.deleteAccount);
		const u = await promptConfiguredAction({
			prompter: r,
			label: n,
			supportsDisable: c,
			supportsDelete: l
		});
		if (u === "skip") return;
		if (u === "update") {
			await configureChannel(e, r, i);
			return;
		}
		if (!i.allowDisable) return;
		if (u === "delete" && !l) {
			await r.note(t("wizard.channels.configuredDeleteUnsupported", { label: n }), t("wizard.channels.removeTitle"));
			return;
		}
		const d = (u === "delete" ? Boolean(o?.config.deleteAccount) : Boolean(o?.config.setAccountEnabled)) ? await promptRemovalAccountId({
			cfg: a,
			prompter: r,
			label: n,
			channel: e,
			plugin: o
		}) : DEFAULT_ACCOUNT_ID;
		const f = normalizeAccountId(d);
		const p = formatAccountLabel(f);
		if (u === "delete") {
			if (!await r.confirm({
				message: t("wizard.channels.deleteAccount", {
					label: n,
					account: p
				}),
				initialValue: false
			})) return;
			if (o?.config.deleteAccount) a = o.config.deleteAccount({
				cfg: a,
				accountId: f
			});
			await refreshStatus(e);
			return;
		}
		if (o?.config.setAccountEnabled) a = o.config.setAccountEnabled({
			cfg: a,
			accountId: f,
			enabled: false
		});
		else if (s?.disable) a = s.disable(a);
		await refreshStatus(e);
	};
	const ensureChannelSetupPluginInstalledWithNavigation$1 = async (e, n) => await withPluginLifecycleLeaseAsync({}, async () => {
		const o = await ensureChannelSetupPluginInstalledWithNavigation({
			install: n,
			prompter: r,
			options: i
		});
		if (o.status !== "back" && o.value.installed) {
			a = o.value.cfg;
			await withPluginCache(f, () => loadScopedChannelPlugin(e, o.value.pluginId ?? n.entry.pluginId));
		}
		return o;
	});
	const handleChannelChoice = async (e) => {
		let i = a;
		const s = new Map(l);
		const c = new Map(p);
		const returnToSelection = () => {
			a = i;
			l.clear();
			for (const [e, n] of s) l.set(e, n);
			p.clear();
			for (const [e, n] of c) p.set(e, n);
			return "retry_selection";
		};
		const installCatalogEntry = async (r) => {
			const o = await ensureChannelSetupPluginInstalledWithNavigation$1(e, {
				cfg: a,
				entry: r,
				runtime: n,
				workspaceDir: resolveWorkspaceDir(),
				autoConfirmSingleSource: true
			});
			if (o.status === "back") return returnToSelection();
			a = o.value.cfg;
			if (!o.value.installed) return "retry_selection";
			if (o.persistentEffectStarted) i = a;
		};
		let u = o ? S(e) : void 0;
		let d = false;
		if (u) {
			if (u !== "disabled" && u !== "plugin disabled") {
				await noteDisabledBeforeSetup(r, e, u);
				return "done";
			}
			if (e !== h && !await r.confirm({
				message: t(u === "disabled" ? "wizard.channels.resumeDisabledSetup" : "wizard.channels.resumeDisabledPluginSetup", { channel: e }),
				initialValue: true
			})) return "done";
			if (u === "disabled") {
				const n = a.channels;
				a = {
					...a,
					channels: {
						...a.channels,
						[e]: {
							...n?.[e],
							enabled: true
						}
					}
				};
			} else if (!await enableChannelPluginForSetup(e)) return "done";
			d = true;
			u = S(e);
			if (u) {
				await noteDisabledBeforeSetup(r, e, u);
				return "done";
			}
		}
		const { installableCatalogById: f, installedCatalogById: m } = resolveVisibleChannelEntries();
		const g = f.get(e);
		const _ = m.get(e);
		if (g) {
			const n = await installCatalogEntry(g);
			if (n) return n;
			await refreshStatus(e);
		} else if (_) {
			let n = await loadScopedChannelPlugin(e, _.pluginId);
			if (!n && _.install?.npmSpec) {
				const i = S(e);
				if (i) {
					await noteDisabledBeforeSetup(r, e, i);
					return "done";
				}
				const a = await installCatalogEntry(_);
				if (a) return a;
				n = getVisibleChannelPlugin(e);
			}
			if (!n) {
				await r.note(t("wizard.channels.pluginNotAvailable", { channel: e }), t("wizard.channels.setupTitle"));
				return "done";
			}
			await refreshStatus(e);
		} else {
			const n = getTrustedChannelPluginCatalogEntry(e, {
				cfg: a,
				workspaceDir: resolveWorkspaceDir()
			});
			if (n?.install?.npmSpec) {
				const i = S(e);
				if (i) {
					await noteDisabledBeforeSetup(r, e, i);
					return "done";
				}
				if (!getVisibleChannelPlugin(e)) {
					const e = await installCatalogEntry(n);
					if (e) return e;
				}
				await refreshStatus(e);
			} else if (!await enableBundledPluginForSetup(e)) return "done";
		}
		const v = getVisibleChannelPlugin(e);
		const y = getVisibleSetupFlowAdapter(e);
		const b = v?.meta.label ?? g?.meta.label ?? e;
		const x = p.get(e);
		const C = d ? false : x?.configured ?? false;
		const w = y?.configureInteractive;
		if (w) {
			const n = await runScopedChannelStep$1(async (n, r) => await w({
				...channelSetupContext(e, n, r),
				configured: C,
				label: b
			}));
			if (n.status === "back") return returnToSelection();
			const r = n.value;
			await withCommandPluginMetadata({
				config: a,
				workspaceDir: resolveWorkspaceDir()
			}, () => applyCustomSetupResult(e, r));
			return "done";
		}
		if ((await runScopedChannelStep$1(async (n, r) => C ? await handleConfiguredChannel(e, b, n, r) : await configureChannel(e, n, r))).status === "back") return returnToSelection();
		return "done";
	};
	const T = h ? await handleChannelChoice(h) === "retry_selection" : false;
	if (!h || T) {
		const e = !h && i?.quickstartDefaults;
		const n = e ? "__skip__" : "__done__";
		const a = i?.initialSelection?.[0] ?? (e ? n : _);
		while (true) {
			const i = await resolveSelectionOptions();
			const o = e ? {
				value: n,
				label: t("common.skipForNow"),
				hint: t("wizard.channels.skipLaterHint", { command: formatCliCommand("openclaw channels add") })
			} : {
				value: n,
				label: t("common.finished"),
				hint: b.length > 0 ? t("wizard.channels.doneHint") : t("common.skipForNow")
			};
			const s = await r.select({
				message: t(e ? "wizard.channels.selectQuickstart" : "wizard.channels.select"),
				options: e ? [o, ...i] : [...i, o],
				initialValue: a,
				...e ? { searchable: true } : {}
			});
			if (s === n) break;
			const c = await handleChannelChoice(s);
			if (e ? c === "done" : x) break;
		}
	}
	i?.onSelection?.(b);
	const E = resolveChannelSelectionNoteLines({
		cfg: a,
		workspaceDir: resolveWorkspaceDir(),
		installedPlugins: listVisibleInstalledPlugins(),
		selection: b
	});
	if (E.length > 0) await r.note(E.join("\n"), t("wizard.channels.selectedTitle"));
	if (!i?.skipDmPolicyPrompt) a = await withCommandPluginMetadata({
		config: a,
		workspaceDir: resolveWorkspaceDir()
	}, () => maybeConfigureDmPolicies({
		cfg: a,
		selection: b,
		prompter: r,
		accountIdsByChannel: y,
		resolveAdapter: getVisibleSetupFlowAdapter
	}));
	if (hasConfiguredCommandOwners(a)) return a;
	const D = [];
	await withCommandPluginMetadata({
		config: a,
		workspaceDir: resolveWorkspaceDir()
	}, async () => {
		for (const e of b) try {
			if (S(e) || await C(e, y.get(e))) continue;
			if ((await refreshStatus(e))?.configured) D.push({
				id: e,
				label: getVisibleChannelPlugin(e)?.meta.label ?? e
			});
		} catch (n) {
			await r.note(`Status unavailable (${sanitizeTerminalText(formatErrorMessage(n))}).\nRetry: ${formatCliCommand(`openclaw channels status --channel ${e}`)}`, t("wizard.channels.statusTitle"));
		}
	});
	return await maybeConfigureCommandOwner({
		cfg: a,
		channels: D,
		prompter: r
	});
}
//#endregion
export { setupChannels as i, createChannelSetupHooks as n, runCollectedChannelOnboardingPostWriteHooks as r, createChannelOnboardingPostWriteHook as t };