import { f as resolveSessionAgentId } from "./agent-scope-CVnlY0oG.js";
import { o as loadConfig } from "./config-DJ3A5x_1.js";
import { l as assertMediaNotDataUrl, p as resolveSandboxedMediaSource } from "./skills-CHYyY1lO.js";
import { l as extensionForMime } from "./image-ops-C0D77XHD.js";
import { r as appendAssistantMessageToSessionTranscript } from "./sessions-Ct2d_bGl.js";
import { h as GATEWAY_CLIENT_NAMES, l as normalizeMessageChannel, m as GATEWAY_CLIENT_MODES, n as isDeliverableMessageChannel } from "./message-channel-DSU96OKy.js";
import { r as parseSlackTarget } from "./client-36a9DTBg.js";
import { n as listChannelPlugins, r as normalizeChannelId, t as getChannelPlugin } from "./plugins-DYgcd4QJ.js";
import { E as parseTelegramTarget } from "./helpers-DAXsRcXO.js";
import { r as resolveOutboundTarget, y as DiscordUiContainer } from "./targets-D3Hd_LiZ.js";
import { d as normalizeTargetForProvider, f as parseReplyDirectives } from "./reply-payloads-Idpqh_HL.js";
import { c as readStringArrayParam, o as readNumberParam, u as readStringParam } from "./common-oaZdjdal.js";
import { n as loadWebMedia } from "./media-Ce9mjBUa.js";
import { i as randomIdempotencyKey, n as callGateway } from "./call-C206Z-zx.js";
import { n as normalizePollInput } from "./polls-CF33ugZi.js";
import { a as actionRequiresTarget, i as actionHasTarget, r as applyTargetToParams } from "./channel-target-Ce9GdVgj.js";
import { o as normalizeReplyPayloadsForDelivery, s as throwIfAborted, t as deliverOutboundPayloads } from "./deliver-DhB9l23e.js";
import { n as resolveMessageChannelSelection, t as listConfiguredMessageChannels } from "./channel-selection-Bfj-Ulc5.js";
import { i as lookupDirectoryDisplay, n as resolveOutboundSessionRoute, o as resolveChannelTarget, r as formatTargetDisplay, t as ensureOutboundSessionEntry } from "./outbound-session-BP4zpBio.js";
import { fileURLToPath } from "node:url";
import path from "node:path";
import fs from "node:fs/promises";
import { Separator, TextDisplay } from "@buape/carbon";

//#region src/channels/plugins/message-actions.ts
function listChannelMessageActions(cfg) {
	const actions = new Set(["send", "broadcast"]);
	for (const plugin of listChannelPlugins()) {
		const list = plugin.actions?.listActions?.({ cfg });
		if (!list) continue;
		for (const action of list) actions.add(action);
	}
	return Array.from(actions);
}
function supportsChannelMessageButtons(cfg) {
	for (const plugin of listChannelPlugins()) if (plugin.actions?.supportsButtons?.({ cfg })) return true;
	return false;
}
function supportsChannelMessageButtonsForChannel(params) {
	if (!params.channel) return false;
	return getChannelPlugin(params.channel)?.actions?.supportsButtons?.({ cfg: params.cfg }) === true;
}
function supportsChannelMessageCards(cfg) {
	for (const plugin of listChannelPlugins()) if (plugin.actions?.supportsCards?.({ cfg })) return true;
	return false;
}
function supportsChannelMessageCardsForChannel(params) {
	if (!params.channel) return false;
	return getChannelPlugin(params.channel)?.actions?.supportsCards?.({ cfg: params.cfg }) === true;
}
async function dispatchChannelMessageAction(ctx) {
	const plugin = getChannelPlugin(ctx.channel);
	if (!plugin?.actions?.handleAction) return null;
	if (plugin.actions.supportsAction && !plugin.actions.supportsAction({ action: ctx.action })) return null;
	return await plugin.actions.handleAction(ctx);
}

//#endregion
//#region src/channels/plugins/message-action-names.ts
const CHANNEL_MESSAGE_ACTION_NAMES = [
	"send",
	"broadcast",
	"poll",
	"react",
	"reactions",
	"read",
	"edit",
	"unsend",
	"reply",
	"sendWithEffect",
	"renameGroup",
	"setGroupIcon",
	"addParticipant",
	"removeParticipant",
	"leaveGroup",
	"sendAttachment",
	"delete",
	"pin",
	"unpin",
	"list-pins",
	"permissions",
	"thread-create",
	"thread-list",
	"thread-reply",
	"search",
	"sticker",
	"sticker-search",
	"member-info",
	"role-info",
	"emoji-list",
	"emoji-upload",
	"sticker-upload",
	"role-add",
	"role-remove",
	"channel-info",
	"channel-list",
	"channel-create",
	"channel-edit",
	"channel-delete",
	"channel-move",
	"category-create",
	"category-edit",
	"category-delete",
	"topic-create",
	"voice-status",
	"event-list",
	"event-create",
	"timeout",
	"kick",
	"ban",
	"set-presence"
];

//#endregion
//#region src/infra/outbound/message-action-params.ts
function readBooleanParam(params, key) {
	const raw = params[key];
	if (typeof raw === "boolean") return raw;
	if (typeof raw === "string") {
		const trimmed = raw.trim().toLowerCase();
		if (trimmed === "true") return true;
		if (trimmed === "false") return false;
	}
}
function resolveSlackAutoThreadId(params) {
	const context = params.toolContext;
	if (!context?.currentThreadTs || !context.currentChannelId) return;
	if (context.replyToMode !== "all" && context.replyToMode !== "first") return;
	const parsedTarget = parseSlackTarget(params.to, { defaultKind: "channel" });
	if (!parsedTarget || parsedTarget.kind !== "channel") return;
	if (parsedTarget.id.toLowerCase() !== context.currentChannelId.toLowerCase()) return;
	if (context.replyToMode === "first" && context.hasRepliedRef?.value) return;
	return context.currentThreadTs;
}
/**
* Auto-inject Telegram forum topic thread ID when the message tool targets
* the same chat the session originated from.  Mirrors the Slack auto-threading
* pattern so media, buttons, and other tool-sent messages land in the correct
* topic instead of the General Topic.
*
* Unlike Slack, we do not gate on `replyToMode` here: Telegram forum topics
* are persistent sub-channels (not ephemeral reply threads), so auto-injection
* should always apply when the target chat matches.
*/
function resolveTelegramAutoThreadId(params) {
	const context = params.toolContext;
	if (!context?.currentThreadTs || !context.currentChannelId) return;
	const parsedTo = parseTelegramTarget(params.to);
	const parsedChannel = parseTelegramTarget(context.currentChannelId);
	if (parsedTo.chatId.toLowerCase() !== parsedChannel.chatId.toLowerCase()) return;
	return context.currentThreadTs;
}
function resolveAttachmentMaxBytes(params) {
	const accountId = typeof params.accountId === "string" ? params.accountId.trim() : "";
	const channelCfg = params.cfg.channels?.[params.channel];
	const channelObj = channelCfg && typeof channelCfg === "object" ? channelCfg : void 0;
	const channelMediaMax = typeof channelObj?.mediaMaxMb === "number" ? channelObj.mediaMaxMb : void 0;
	const accountsObj = channelObj?.accounts && typeof channelObj.accounts === "object" ? channelObj.accounts : void 0;
	const accountCfg = accountId && accountsObj ? accountsObj[accountId] : void 0;
	const accountMediaMax = accountCfg && typeof accountCfg === "object" ? accountCfg.mediaMaxMb : void 0;
	const limitMb = (typeof accountMediaMax === "number" ? accountMediaMax : void 0) ?? channelMediaMax ?? params.cfg.agents?.defaults?.mediaMaxMb;
	return typeof limitMb === "number" ? limitMb * 1024 * 1024 : void 0;
}
function inferAttachmentFilename(params) {
	const mediaHint = params.mediaHint?.trim();
	if (mediaHint) try {
		if (mediaHint.startsWith("file://")) {
			const filePath = fileURLToPath(mediaHint);
			const base = path.basename(filePath);
			if (base) return base;
		} else if (/^https?:\/\//i.test(mediaHint)) {
			const url = new URL(mediaHint);
			const base = path.basename(url.pathname);
			if (base) return base;
		} else {
			const base = path.basename(mediaHint);
			if (base) return base;
		}
	} catch {}
	const ext = params.contentType ? extensionForMime(params.contentType) : void 0;
	return ext ? `attachment${ext}` : "attachment";
}
function normalizeBase64Payload(params) {
	if (!params.base64) return {
		base64: params.base64,
		contentType: params.contentType
	};
	const match = /^data:([^;]+);base64,(.*)$/i.exec(params.base64.trim());
	if (!match) return {
		base64: params.base64,
		contentType: params.contentType
	};
	const [, mime, payload] = match;
	return {
		base64: payload,
		contentType: params.contentType ?? mime
	};
}
async function hydrateAttachmentPayload(params) {
	const contentTypeParam = params.contentTypeParam ?? void 0;
	const rawBuffer = readStringParam(params.args, "buffer", { trim: false });
	const normalized = normalizeBase64Payload({
		base64: rawBuffer,
		contentType: contentTypeParam ?? void 0
	});
	if (normalized.base64 !== rawBuffer && normalized.base64) {
		params.args.buffer = normalized.base64;
		if (normalized.contentType && !contentTypeParam) params.args.contentType = normalized.contentType;
	}
	const filename = readStringParam(params.args, "filename");
	const mediaSource = (params.mediaHint ?? void 0) || (params.fileHint ?? void 0);
	if (!params.dryRun && !readStringParam(params.args, "buffer", { trim: false }) && mediaSource) {
		const media = await loadWebMedia(mediaSource, {
			maxBytes: resolveAttachmentMaxBytes({
				cfg: params.cfg,
				channel: params.channel,
				accountId: params.accountId
			}),
			sandboxValidated: true,
			readFile: (filePath) => fs.readFile(filePath)
		});
		params.args.buffer = media.buffer.toString("base64");
		if (!contentTypeParam && media.contentType) params.args.contentType = media.contentType;
		if (!filename) params.args.filename = inferAttachmentFilename({
			mediaHint: media.fileName ?? mediaSource,
			contentType: media.contentType ?? contentTypeParam ?? void 0
		});
	} else if (!filename) params.args.filename = inferAttachmentFilename({
		mediaHint: mediaSource,
		contentType: contentTypeParam ?? void 0
	});
}
async function normalizeSandboxMediaParams(params) {
	const sandboxRoot = params.sandboxRoot?.trim();
	for (const key of [
		"media",
		"path",
		"filePath"
	]) {
		const raw = readStringParam(params.args, key, { trim: false });
		if (!raw) continue;
		assertMediaNotDataUrl(raw);
		if (!sandboxRoot) continue;
		const normalized = await resolveSandboxedMediaSource({
			media: raw,
			sandboxRoot
		});
		if (normalized !== raw) params.args[key] = normalized;
	}
}
async function normalizeSandboxMediaList(params) {
	const sandboxRoot = params.sandboxRoot?.trim();
	const normalized = [];
	const seen = /* @__PURE__ */ new Set();
	for (const value of params.values) {
		const raw = value?.trim();
		if (!raw) continue;
		assertMediaNotDataUrl(raw);
		const resolved = sandboxRoot ? await resolveSandboxedMediaSource({
			media: raw,
			sandboxRoot
		}) : raw;
		if (seen.has(resolved)) continue;
		seen.add(resolved);
		normalized.push(resolved);
	}
	return normalized;
}
async function hydrateAttachmentActionPayload(params) {
	const mediaHint = readStringParam(params.args, "media", { trim: false });
	const fileHint = readStringParam(params.args, "path", { trim: false }) ?? readStringParam(params.args, "filePath", { trim: false });
	const contentTypeParam = readStringParam(params.args, "contentType") ?? readStringParam(params.args, "mimeType");
	if (params.allowMessageCaptionFallback) {
		const caption = readStringParam(params.args, "caption", { allowEmpty: true })?.trim();
		const message = readStringParam(params.args, "message", { allowEmpty: true })?.trim();
		if (!caption && message) params.args.caption = message;
	}
	await hydrateAttachmentPayload({
		cfg: params.cfg,
		channel: params.channel,
		accountId: params.accountId,
		args: params.args,
		dryRun: params.dryRun,
		contentTypeParam,
		mediaHint,
		fileHint
	});
}
async function hydrateSetGroupIconParams(params) {
	if (params.action !== "setGroupIcon") return;
	await hydrateAttachmentActionPayload(params);
}
async function hydrateSendAttachmentParams(params) {
	if (params.action !== "sendAttachment") return;
	await hydrateAttachmentActionPayload({
		...params,
		allowMessageCaptionFallback: true
	});
}
function parseButtonsParam(params) {
	const raw = params.buttons;
	if (typeof raw !== "string") return;
	const trimmed = raw.trim();
	if (!trimmed) {
		delete params.buttons;
		return;
	}
	try {
		params.buttons = JSON.parse(trimmed);
	} catch {
		throw new Error("--buttons must be valid JSON");
	}
}
function parseCardParam(params) {
	const raw = params.card;
	if (typeof raw !== "string") return;
	const trimmed = raw.trim();
	if (!trimmed) {
		delete params.card;
		return;
	}
	try {
		params.card = JSON.parse(trimmed);
	} catch {
		throw new Error("--card must be valid JSON");
	}
}
function parseComponentsParam(params) {
	const raw = params.components;
	if (typeof raw !== "string") return;
	const trimmed = raw.trim();
	if (!trimmed) {
		delete params.components;
		return;
	}
	try {
		params.components = JSON.parse(trimmed);
	} catch {
		throw new Error("--components must be valid JSON");
	}
}

//#endregion
//#region src/infra/outbound/channel-adapters.ts
var CrossContextContainer = class extends DiscordUiContainer {
	constructor({ originLabel, message, cfg, accountId }) {
		const trimmed = message.trim();
		const components = [];
		if (trimmed) {
			components.push(new TextDisplay(message));
			components.push(new Separator({
				divider: true,
				spacing: "small"
			}));
		}
		components.push(new TextDisplay(`*From ${originLabel}*`));
		super({
			cfg,
			accountId,
			components
		});
	}
};
const DEFAULT_ADAPTER = { supportsComponentsV2: false };
const DISCORD_ADAPTER = {
	supportsComponentsV2: true,
	buildCrossContextComponents: ({ originLabel, message, cfg, accountId }) => [new CrossContextContainer({
		originLabel,
		message,
		cfg,
		accountId
	})]
};
function getChannelMessageAdapter(channel) {
	if (channel === "discord") return DISCORD_ADAPTER;
	return DEFAULT_ADAPTER;
}

//#endregion
//#region src/infra/outbound/outbound-policy.ts
const CONTEXT_GUARDED_ACTIONS = new Set([
	"send",
	"poll",
	"reply",
	"sendWithEffect",
	"sendAttachment",
	"thread-create",
	"thread-reply",
	"sticker"
]);
const CONTEXT_MARKER_ACTIONS = new Set([
	"send",
	"poll",
	"reply",
	"sendWithEffect",
	"sendAttachment",
	"thread-reply",
	"sticker"
]);
function resolveContextGuardTarget(action, params) {
	if (!CONTEXT_GUARDED_ACTIONS.has(action)) return;
	if (action === "thread-reply" || action === "thread-create") {
		if (typeof params.channelId === "string") return params.channelId;
		if (typeof params.to === "string") return params.to;
		return;
	}
	if (typeof params.to === "string") return params.to;
	if (typeof params.channelId === "string") return params.channelId;
}
function normalizeTarget(channel, raw) {
	return normalizeTargetForProvider(channel, raw) ?? raw.trim().toLowerCase();
}
function isCrossContextTarget(params) {
	const currentTarget = params.toolContext?.currentChannelId?.trim();
	if (!currentTarget) return false;
	const normalizedTarget = normalizeTarget(params.channel, params.target);
	const normalizedCurrent = normalizeTarget(params.channel, currentTarget);
	if (!normalizedTarget || !normalizedCurrent) return false;
	return normalizedTarget !== normalizedCurrent;
}
function enforceCrossContextPolicy(params) {
	const currentTarget = params.toolContext?.currentChannelId?.trim();
	if (!currentTarget) return;
	if (!CONTEXT_GUARDED_ACTIONS.has(params.action)) return;
	if (params.cfg.tools?.message?.allowCrossContextSend) return;
	const currentProvider = params.toolContext?.currentChannelProvider;
	const allowWithinProvider = params.cfg.tools?.message?.crossContext?.allowWithinProvider !== false;
	const allowAcrossProviders = params.cfg.tools?.message?.crossContext?.allowAcrossProviders === true;
	if (currentProvider && currentProvider !== params.channel) {
		if (!allowAcrossProviders) throw new Error(`Cross-context messaging denied: action=${params.action} target provider "${params.channel}" while bound to "${currentProvider}".`);
		return;
	}
	if (allowWithinProvider) return;
	const target = resolveContextGuardTarget(params.action, params.args);
	if (!target) return;
	if (!isCrossContextTarget({
		channel: params.channel,
		target,
		toolContext: params.toolContext
	})) return;
	throw new Error(`Cross-context messaging denied: action=${params.action} target="${target}" while bound to "${currentTarget}" (channel=${params.channel}).`);
}
async function buildCrossContextDecoration(params) {
	if (!params.toolContext?.currentChannelId) return null;
	if (params.toolContext.skipCrossContextDecoration) return null;
	if (!isCrossContextTarget(params)) return null;
	const markerConfig = params.cfg.tools?.message?.crossContext?.marker;
	if (markerConfig?.enabled === false) return null;
	const currentName = await lookupDirectoryDisplay({
		cfg: params.cfg,
		channel: params.channel,
		targetId: params.toolContext.currentChannelId,
		accountId: params.accountId ?? void 0
	}) ?? params.toolContext.currentChannelId;
	const originLabel = formatTargetDisplay({
		channel: params.channel,
		target: params.toolContext.currentChannelId,
		display: currentName
	});
	const prefixTemplate = markerConfig?.prefix ?? "[from {channel}] ";
	const suffixTemplate = markerConfig?.suffix ?? "";
	const prefix = prefixTemplate.replaceAll("{channel}", originLabel);
	const suffix = suffixTemplate.replaceAll("{channel}", originLabel);
	const adapter = getChannelMessageAdapter(params.channel);
	return {
		prefix,
		suffix,
		componentsBuilder: adapter.supportsComponentsV2 ? adapter.buildCrossContextComponents ? (message) => adapter.buildCrossContextComponents({
			originLabel,
			message,
			cfg: params.cfg,
			accountId: params.accountId ?? void 0
		}) : void 0 : void 0
	};
}
function shouldApplyCrossContextMarker(action) {
	return CONTEXT_MARKER_ACTIONS.has(action);
}
function applyCrossContextDecoration(params) {
	if (params.preferComponents && params.decoration.componentsBuilder) return {
		message: params.message,
		componentsBuilder: params.decoration.componentsBuilder,
		usedComponents: true
	};
	return {
		message: `${params.decoration.prefix}${params.message}${params.decoration.suffix}`,
		usedComponents: false
	};
}

//#endregion
//#region src/infra/outbound/message.ts
async function resolveRequiredChannel(params) {
	const channel = params.channel?.trim() ? normalizeChannelId(params.channel) : (await resolveMessageChannelSelection({ cfg: params.cfg })).channel;
	if (!channel) throw new Error(`Unknown channel: ${params.channel}`);
	return channel;
}
function resolveRequiredPlugin(channel) {
	const plugin = getChannelPlugin(channel);
	if (!plugin) throw new Error(`Unknown channel: ${channel}`);
	return plugin;
}
function resolveGatewayOptions(opts) {
	return {
		url: opts?.mode === GATEWAY_CLIENT_MODES.BACKEND || opts?.clientName === GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT ? void 0 : opts?.url,
		token: opts?.token,
		timeoutMs: typeof opts?.timeoutMs === "number" && Number.isFinite(opts.timeoutMs) ? Math.max(1, Math.floor(opts.timeoutMs)) : 1e4,
		clientName: opts?.clientName ?? GATEWAY_CLIENT_NAMES.CLI,
		clientDisplayName: opts?.clientDisplayName,
		mode: opts?.mode ?? GATEWAY_CLIENT_MODES.CLI
	};
}
async function callMessageGateway(params) {
	const gateway = resolveGatewayOptions(params.gateway);
	return await callGateway({
		url: gateway.url,
		token: gateway.token,
		method: params.method,
		params: params.params,
		timeoutMs: gateway.timeoutMs,
		clientName: gateway.clientName,
		clientDisplayName: gateway.clientDisplayName,
		mode: gateway.mode
	});
}
async function sendMessage(params) {
	const cfg = params.cfg ?? loadConfig();
	const channel = await resolveRequiredChannel({
		cfg,
		channel: params.channel
	});
	const deliveryMode = resolveRequiredPlugin(channel).outbound?.deliveryMode ?? "direct";
	const normalizedPayloads = normalizeReplyPayloadsForDelivery([{
		text: params.content,
		mediaUrl: params.mediaUrl,
		mediaUrls: params.mediaUrls
	}]);
	const mirrorText = normalizedPayloads.map((payload) => payload.text).filter(Boolean).join("\n");
	const mirrorMediaUrls = normalizedPayloads.flatMap((payload) => payload.mediaUrls ?? (payload.mediaUrl ? [payload.mediaUrl] : []));
	const primaryMediaUrl = mirrorMediaUrls[0] ?? params.mediaUrl ?? null;
	if (params.dryRun) return {
		channel,
		to: params.to,
		via: deliveryMode === "gateway" ? "gateway" : "direct",
		mediaUrl: primaryMediaUrl,
		mediaUrls: mirrorMediaUrls.length ? mirrorMediaUrls : void 0,
		dryRun: true
	};
	if (deliveryMode !== "gateway") {
		const outboundChannel = channel;
		const resolvedTarget = resolveOutboundTarget({
			channel: outboundChannel,
			to: params.to,
			cfg,
			accountId: params.accountId,
			mode: "explicit"
		});
		if (!resolvedTarget.ok) throw resolvedTarget.error;
		const results = await deliverOutboundPayloads({
			cfg,
			channel: outboundChannel,
			to: resolvedTarget.to,
			agentId: params.agentId,
			accountId: params.accountId,
			payloads: normalizedPayloads,
			replyToId: params.replyToId,
			threadId: params.threadId,
			gifPlayback: params.gifPlayback,
			deps: params.deps,
			bestEffort: params.bestEffort,
			abortSignal: params.abortSignal,
			silent: params.silent,
			mirror: params.mirror ? {
				...params.mirror,
				text: mirrorText || params.content,
				mediaUrls: mirrorMediaUrls.length ? mirrorMediaUrls : void 0
			} : void 0
		});
		return {
			channel,
			to: params.to,
			via: "direct",
			mediaUrl: primaryMediaUrl,
			mediaUrls: mirrorMediaUrls.length ? mirrorMediaUrls : void 0,
			result: results.at(-1)
		};
	}
	const result = await callMessageGateway({
		gateway: params.gateway,
		method: "send",
		params: {
			to: params.to,
			message: params.content,
			mediaUrl: params.mediaUrl,
			mediaUrls: mirrorMediaUrls.length ? mirrorMediaUrls : params.mediaUrls,
			gifPlayback: params.gifPlayback,
			accountId: params.accountId,
			channel,
			sessionKey: params.mirror?.sessionKey,
			idempotencyKey: params.idempotencyKey ?? randomIdempotencyKey()
		}
	});
	return {
		channel,
		to: params.to,
		via: "gateway",
		mediaUrl: primaryMediaUrl,
		mediaUrls: mirrorMediaUrls.length ? mirrorMediaUrls : void 0,
		result
	};
}
async function sendPoll(params) {
	const channel = await resolveRequiredChannel({
		cfg: params.cfg ?? loadConfig(),
		channel: params.channel
	});
	const pollInput = {
		question: params.question,
		options: params.options,
		maxSelections: params.maxSelections,
		durationSeconds: params.durationSeconds,
		durationHours: params.durationHours
	};
	const outbound = resolveRequiredPlugin(channel)?.outbound;
	if (!outbound?.sendPoll) throw new Error(`Unsupported poll channel: ${channel}`);
	const normalized = outbound.pollMaxOptions ? normalizePollInput(pollInput, { maxOptions: outbound.pollMaxOptions }) : normalizePollInput(pollInput);
	if (params.dryRun) return {
		channel,
		to: params.to,
		question: normalized.question,
		options: normalized.options,
		maxSelections: normalized.maxSelections,
		durationSeconds: normalized.durationSeconds ?? null,
		durationHours: normalized.durationHours ?? null,
		via: "gateway",
		dryRun: true
	};
	const result = await callMessageGateway({
		gateway: params.gateway,
		method: "poll",
		params: {
			to: params.to,
			question: normalized.question,
			options: normalized.options,
			maxSelections: normalized.maxSelections,
			durationSeconds: normalized.durationSeconds,
			durationHours: normalized.durationHours,
			threadId: params.threadId,
			silent: params.silent,
			isAnonymous: params.isAnonymous,
			channel,
			accountId: params.accountId,
			idempotencyKey: params.idempotencyKey ?? randomIdempotencyKey()
		}
	});
	return {
		channel,
		to: params.to,
		question: normalized.question,
		options: normalized.options,
		maxSelections: normalized.maxSelections,
		durationSeconds: normalized.durationSeconds ?? null,
		durationHours: normalized.durationHours ?? null,
		via: "gateway",
		result
	};
}

//#endregion
//#region src/infra/outbound/tool-payload.ts
function extractToolPayload(result) {
	if (result.details !== void 0) return result.details;
	const text = (Array.isArray(result.content) ? result.content.find((block) => block && typeof block === "object" && block.type === "text" && typeof block.text === "string") : void 0)?.text;
	if (text) try {
		return JSON.parse(text);
	} catch {
		return text;
	}
	return result.content ?? result;
}

//#endregion
//#region src/infra/outbound/outbound-send-service.ts
async function tryHandleWithPluginAction(params) {
	if (params.ctx.dryRun) return null;
	const handled = await dispatchChannelMessageAction({
		channel: params.ctx.channel,
		action: params.action,
		cfg: params.ctx.cfg,
		params: params.ctx.params,
		accountId: params.ctx.accountId ?? void 0,
		gateway: params.ctx.gateway,
		toolContext: params.ctx.toolContext,
		dryRun: params.ctx.dryRun
	});
	if (!handled) return null;
	await params.onHandled?.();
	return {
		handledBy: "plugin",
		payload: extractToolPayload(handled),
		toolResult: handled
	};
}
async function executeSendAction(params) {
	throwIfAborted(params.ctx.abortSignal);
	const pluginHandled = await tryHandleWithPluginAction({
		ctx: params.ctx,
		action: "send",
		onHandled: async () => {
			if (!params.ctx.mirror) return;
			const mirrorText = params.ctx.mirror.text ?? params.message;
			const mirrorMediaUrls = params.ctx.mirror.mediaUrls ?? params.mediaUrls ?? (params.mediaUrl ? [params.mediaUrl] : void 0);
			await appendAssistantMessageToSessionTranscript({
				agentId: params.ctx.mirror.agentId,
				sessionKey: params.ctx.mirror.sessionKey,
				text: mirrorText,
				mediaUrls: mirrorMediaUrls
			});
		}
	});
	if (pluginHandled) return pluginHandled;
	throwIfAborted(params.ctx.abortSignal);
	const result = await sendMessage({
		cfg: params.ctx.cfg,
		to: params.to,
		content: params.message,
		agentId: params.ctx.agentId,
		mediaUrl: params.mediaUrl || void 0,
		mediaUrls: params.mediaUrls,
		channel: params.ctx.channel || void 0,
		accountId: params.ctx.accountId ?? void 0,
		replyToId: params.replyToId,
		threadId: params.threadId,
		gifPlayback: params.gifPlayback,
		dryRun: params.ctx.dryRun,
		bestEffort: params.bestEffort ?? void 0,
		deps: params.ctx.deps,
		gateway: params.ctx.gateway,
		mirror: params.ctx.mirror,
		abortSignal: params.ctx.abortSignal,
		silent: params.ctx.silent
	});
	return {
		handledBy: "core",
		payload: result,
		sendResult: result
	};
}
async function executePollAction(params) {
	const pluginHandled = await tryHandleWithPluginAction({
		ctx: params.ctx,
		action: "poll"
	});
	if (pluginHandled) return pluginHandled;
	const result = await sendPoll({
		cfg: params.ctx.cfg,
		to: params.to,
		question: params.question,
		options: params.options,
		maxSelections: params.maxSelections,
		durationSeconds: params.durationSeconds ?? void 0,
		durationHours: params.durationHours ?? void 0,
		channel: params.ctx.channel,
		accountId: params.ctx.accountId ?? void 0,
		threadId: params.threadId ?? void 0,
		silent: params.ctx.silent ?? void 0,
		isAnonymous: params.isAnonymous ?? void 0,
		dryRun: params.ctx.dryRun,
		gateway: params.ctx.gateway
	});
	return {
		handledBy: "core",
		payload: result,
		pollResult: result
	};
}

//#endregion
//#region src/infra/outbound/message-action-runner.ts
function resolveAndApplyOutboundThreadId(params, ctx) {
	const threadId = readStringParam(params, "threadId");
	const slackAutoThreadId = ctx.allowSlackAutoThread && ctx.channel === "slack" && !threadId ? resolveSlackAutoThreadId({
		to: ctx.to,
		toolContext: ctx.toolContext
	}) : void 0;
	const telegramAutoThreadId = ctx.channel === "telegram" && !threadId ? resolveTelegramAutoThreadId({
		to: ctx.to,
		toolContext: ctx.toolContext
	}) : void 0;
	const resolved = threadId ?? slackAutoThreadId ?? telegramAutoThreadId;
	if (resolved && !params.threadId) params.threadId = resolved;
	return resolved ?? void 0;
}
function getToolResult(result) {
	return "toolResult" in result ? result.toolResult : void 0;
}
function applyCrossContextMessageDecoration({ params, message, decoration, preferComponents }) {
	const applied = applyCrossContextDecoration({
		message,
		decoration,
		preferComponents
	});
	params.message = applied.message;
	if (applied.componentsBuilder) params.components = applied.componentsBuilder;
	return applied.message;
}
async function maybeApplyCrossContextMarker(params) {
	if (!shouldApplyCrossContextMarker(params.action) || !params.toolContext) return params.message;
	const decoration = await buildCrossContextDecoration({
		cfg: params.cfg,
		channel: params.channel,
		target: params.target,
		toolContext: params.toolContext,
		accountId: params.accountId ?? void 0
	});
	if (!decoration) return params.message;
	return applyCrossContextMessageDecoration({
		params: params.args,
		message: params.message,
		decoration,
		preferComponents: params.preferComponents
	});
}
async function resolveChannel(cfg, params) {
	return (await resolveMessageChannelSelection({
		cfg,
		channel: readStringParam(params, "channel")
	})).channel;
}
async function resolveActionTarget(params) {
	let resolvedTarget;
	const toRaw = typeof params.args.to === "string" ? params.args.to.trim() : "";
	if (toRaw) {
		const resolved = await resolveChannelTarget({
			cfg: params.cfg,
			channel: params.channel,
			input: toRaw,
			accountId: params.accountId ?? void 0
		});
		if (resolved.ok) {
			params.args.to = resolved.target.to;
			resolvedTarget = resolved.target;
		} else throw resolved.error;
	}
	const channelIdRaw = typeof params.args.channelId === "string" ? params.args.channelId.trim() : "";
	if (channelIdRaw) {
		const resolved = await resolveChannelTarget({
			cfg: params.cfg,
			channel: params.channel,
			input: channelIdRaw,
			accountId: params.accountId ?? void 0,
			preferredKind: "group"
		});
		if (resolved.ok) {
			if (resolved.target.kind === "user") throw new Error(`Channel id "${channelIdRaw}" resolved to a user target.`);
			params.args.channelId = resolved.target.to.replace(/^(channel|group):/i, "");
		} else throw resolved.error;
	}
	return resolvedTarget;
}
function resolveGateway(input) {
	if (!input.gateway) return;
	return {
		url: input.gateway.url,
		token: input.gateway.token,
		timeoutMs: input.gateway.timeoutMs,
		clientName: input.gateway.clientName,
		clientDisplayName: input.gateway.clientDisplayName,
		mode: input.gateway.mode
	};
}
async function handleBroadcastAction(input, params) {
	throwIfAborted(input.abortSignal);
	if (!(input.cfg.tools?.message?.broadcast?.enabled !== false)) throw new Error("Broadcast is disabled. Set tools.message.broadcast.enabled to true.");
	const rawTargets = readStringArrayParam(params, "targets", { required: true }) ?? [];
	if (rawTargets.length === 0) throw new Error("Broadcast requires at least one target in --targets.");
	const channelHint = readStringParam(params, "channel");
	const configured = await listConfiguredMessageChannels(input.cfg);
	if (configured.length === 0) throw new Error("Broadcast requires at least one configured channel.");
	const targetChannels = channelHint && channelHint.trim().toLowerCase() !== "all" ? [await resolveChannel(input.cfg, { channel: channelHint })] : configured;
	const results = [];
	const isAbortError = (err) => err instanceof Error && err.name === "AbortError";
	for (const targetChannel of targetChannels) {
		throwIfAborted(input.abortSignal);
		for (const target of rawTargets) {
			throwIfAborted(input.abortSignal);
			try {
				const resolved = await resolveChannelTarget({
					cfg: input.cfg,
					channel: targetChannel,
					input: target
				});
				if (!resolved.ok) throw resolved.error;
				const sendResult = await runMessageAction({
					...input,
					action: "send",
					params: {
						...params,
						channel: targetChannel,
						target: resolved.target.to
					}
				});
				results.push({
					channel: targetChannel,
					to: resolved.target.to,
					ok: true,
					result: sendResult.kind === "send" ? sendResult.sendResult : void 0
				});
			} catch (err) {
				if (isAbortError(err)) throw err;
				results.push({
					channel: targetChannel,
					to: target,
					ok: false,
					error: err instanceof Error ? err.message : String(err)
				});
			}
		}
	}
	return {
		kind: "broadcast",
		channel: targetChannels[0] ?? "discord",
		action: "broadcast",
		handledBy: input.dryRun ? "dry-run" : "core",
		payload: { results },
		dryRun: Boolean(input.dryRun)
	};
}
async function handleSendAction(ctx) {
	const { cfg, params, channel, accountId, dryRun, gateway, input, agentId, resolvedTarget, abortSignal } = ctx;
	throwIfAborted(abortSignal);
	const action = "send";
	const to = readStringParam(params, "to", { required: true });
	const mediaHint = readStringParam(params, "media", { trim: false }) ?? readStringParam(params, "path", { trim: false }) ?? readStringParam(params, "filePath", { trim: false });
	const hasCard = params.card != null && typeof params.card === "object";
	const hasComponents = params.components != null && typeof params.components === "object";
	const caption = readStringParam(params, "caption", { allowEmpty: true }) ?? "";
	let message = readStringParam(params, "message", {
		required: !mediaHint && !hasCard && !hasComponents,
		allowEmpty: true
	}) ?? "";
	if (message.includes("\\n")) message = message.replaceAll("\\n", "\n");
	if (!message.trim() && caption.trim()) message = caption;
	const parsed = parseReplyDirectives(message);
	const mergedMediaUrls = [];
	const seenMedia = /* @__PURE__ */ new Set();
	const pushMedia = (value) => {
		const trimmed = value?.trim();
		if (!trimmed) return;
		if (seenMedia.has(trimmed)) return;
		seenMedia.add(trimmed);
		mergedMediaUrls.push(trimmed);
	};
	pushMedia(mediaHint);
	for (const url of parsed.mediaUrls ?? []) pushMedia(url);
	pushMedia(parsed.mediaUrl);
	const normalizedMediaUrls = await normalizeSandboxMediaList({
		values: mergedMediaUrls,
		sandboxRoot: input.sandboxRoot
	});
	mergedMediaUrls.length = 0;
	mergedMediaUrls.push(...normalizedMediaUrls);
	message = parsed.text;
	params.message = message;
	if (!params.replyTo && parsed.replyToId) params.replyTo = parsed.replyToId;
	if (!params.media) params.media = mergedMediaUrls[0] || void 0;
	message = await maybeApplyCrossContextMarker({
		cfg,
		channel,
		action,
		target: to,
		toolContext: input.toolContext,
		accountId,
		args: params,
		message,
		preferComponents: true
	});
	const mediaUrl = readStringParam(params, "media", { trim: false });
	if (channel === "whatsapp") {
		message = message.replace(/^(?:[ \t]*\r?\n)+/, "");
		if (!message.trim()) message = "";
	}
	if (!message.trim() && !mediaUrl && mergedMediaUrls.length === 0 && !hasCard && !hasComponents) throw new Error("send requires text or media");
	params.message = message;
	const gifPlayback = readBooleanParam(params, "gifPlayback") ?? false;
	const bestEffort = readBooleanParam(params, "bestEffort");
	const silent = readBooleanParam(params, "silent");
	const replyToId = readStringParam(params, "replyTo");
	const resolvedThreadId = resolveAndApplyOutboundThreadId(params, {
		channel,
		to,
		toolContext: input.toolContext,
		allowSlackAutoThread: channel === "slack" && !replyToId
	});
	const outboundRoute = agentId && !dryRun ? await resolveOutboundSessionRoute({
		cfg,
		channel,
		agentId,
		accountId,
		target: to,
		resolvedTarget,
		replyToId,
		threadId: resolvedThreadId
	}) : null;
	if (outboundRoute && agentId && !dryRun) await ensureOutboundSessionEntry({
		cfg,
		agentId,
		channel,
		accountId,
		route: outboundRoute
	});
	if (outboundRoute && !dryRun) params.__sessionKey = outboundRoute.sessionKey;
	if (agentId) params.__agentId = agentId;
	const mirrorMediaUrls = mergedMediaUrls.length > 0 ? mergedMediaUrls : mediaUrl ? [mediaUrl] : void 0;
	throwIfAborted(abortSignal);
	const send = await executeSendAction({
		ctx: {
			cfg,
			channel,
			params,
			agentId,
			accountId: accountId ?? void 0,
			gateway,
			toolContext: input.toolContext,
			deps: input.deps,
			dryRun,
			mirror: outboundRoute && !dryRun ? {
				sessionKey: outboundRoute.sessionKey,
				agentId,
				text: message,
				mediaUrls: mirrorMediaUrls
			} : void 0,
			abortSignal,
			silent: silent ?? void 0
		},
		to,
		message,
		mediaUrl: mediaUrl || void 0,
		mediaUrls: mergedMediaUrls.length ? mergedMediaUrls : void 0,
		gifPlayback,
		bestEffort: bestEffort ?? void 0,
		replyToId: replyToId ?? void 0,
		threadId: resolvedThreadId ?? void 0
	});
	return {
		kind: "send",
		channel,
		action,
		to,
		handledBy: send.handledBy,
		payload: send.payload,
		toolResult: send.toolResult,
		sendResult: send.sendResult,
		dryRun
	};
}
async function handlePollAction(ctx) {
	const { cfg, params, channel, accountId, dryRun, gateway, input, abortSignal } = ctx;
	throwIfAborted(abortSignal);
	const action = "poll";
	const to = readStringParam(params, "to", { required: true });
	const question = readStringParam(params, "pollQuestion", { required: true });
	const options = readStringArrayParam(params, "pollOption", { required: true }) ?? [];
	if (options.length < 2) throw new Error("pollOption requires at least two values");
	const silent = readBooleanParam(params, "silent");
	const allowMultiselect = readBooleanParam(params, "pollMulti") ?? false;
	const pollAnonymous = readBooleanParam(params, "pollAnonymous");
	const pollPublic = readBooleanParam(params, "pollPublic");
	if (pollAnonymous && pollPublic) throw new Error("pollAnonymous and pollPublic are mutually exclusive");
	const isAnonymous = pollAnonymous ? true : pollPublic ? false : void 0;
	const durationHours = readNumberParam(params, "pollDurationHours", { integer: true });
	const durationSeconds = readNumberParam(params, "pollDurationSeconds", { integer: true });
	const maxSelections = allowMultiselect ? Math.max(2, options.length) : 1;
	if (durationSeconds !== void 0 && channel !== "telegram") throw new Error("pollDurationSeconds is only supported for Telegram polls");
	if (isAnonymous !== void 0 && channel !== "telegram") throw new Error("pollAnonymous/pollPublic are only supported for Telegram polls");
	const resolvedThreadId = resolveAndApplyOutboundThreadId(params, {
		channel,
		to,
		toolContext: input.toolContext,
		allowSlackAutoThread: channel === "slack"
	});
	const base = typeof params.message === "string" ? params.message : "";
	await maybeApplyCrossContextMarker({
		cfg,
		channel,
		action,
		target: to,
		toolContext: input.toolContext,
		accountId,
		args: params,
		message: base,
		preferComponents: false
	});
	const poll = await executePollAction({
		ctx: {
			cfg,
			channel,
			params,
			accountId: accountId ?? void 0,
			gateway,
			toolContext: input.toolContext,
			dryRun,
			silent: silent ?? void 0
		},
		to,
		question,
		options,
		maxSelections,
		durationSeconds: durationSeconds ?? void 0,
		durationHours: durationHours ?? void 0,
		threadId: resolvedThreadId ?? void 0,
		isAnonymous
	});
	return {
		kind: "poll",
		channel,
		action,
		to,
		handledBy: poll.handledBy,
		payload: poll.payload,
		toolResult: poll.toolResult,
		pollResult: poll.pollResult,
		dryRun
	};
}
async function handlePluginAction(ctx) {
	const { cfg, params, channel, accountId, dryRun, gateway, input, abortSignal } = ctx;
	throwIfAborted(abortSignal);
	const action = input.action;
	if (dryRun) return {
		kind: "action",
		channel,
		action,
		handledBy: "dry-run",
		payload: {
			ok: true,
			dryRun: true,
			channel,
			action
		},
		dryRun: true
	};
	const handled = await dispatchChannelMessageAction({
		channel,
		action,
		cfg,
		params,
		accountId: accountId ?? void 0,
		gateway,
		toolContext: input.toolContext,
		dryRun
	});
	if (!handled) throw new Error(`Message action ${action} not supported for channel ${channel}.`);
	return {
		kind: "action",
		channel,
		action,
		handledBy: "plugin",
		payload: extractToolPayload(handled),
		toolResult: handled,
		dryRun
	};
}
async function runMessageAction(input) {
	const cfg = input.cfg;
	const params = { ...input.params };
	const resolvedAgentId = input.agentId ?? (input.sessionKey ? resolveSessionAgentId({
		sessionKey: input.sessionKey,
		config: cfg
	}) : void 0);
	parseButtonsParam(params);
	parseCardParam(params);
	parseComponentsParam(params);
	const action = input.action;
	if (action === "broadcast") return handleBroadcastAction(input, params);
	const explicitTarget = typeof params.target === "string" ? params.target.trim() : "";
	const hasLegacyTarget = typeof params.to === "string" && params.to.trim().length > 0 || typeof params.channelId === "string" && params.channelId.trim().length > 0;
	if (explicitTarget && hasLegacyTarget) {
		delete params.to;
		delete params.channelId;
	}
	if (!explicitTarget && !hasLegacyTarget && actionRequiresTarget(action) && !actionHasTarget(action, params)) {
		const inferredTarget = input.toolContext?.currentChannelId?.trim();
		if (inferredTarget) params.target = inferredTarget;
	}
	if (!explicitTarget && actionRequiresTarget(action) && hasLegacyTarget) {
		const legacyTo = typeof params.to === "string" ? params.to.trim() : "";
		const legacyChannelId = typeof params.channelId === "string" ? params.channelId.trim() : "";
		const legacyTarget = legacyTo || legacyChannelId;
		if (legacyTarget) {
			params.target = legacyTarget;
			delete params.to;
			delete params.channelId;
		}
	}
	if (!(typeof params.channel === "string" ? params.channel.trim() : "")) {
		const inferredChannel = normalizeMessageChannel(input.toolContext?.currentChannelProvider);
		if (inferredChannel && isDeliverableMessageChannel(inferredChannel)) params.channel = inferredChannel;
	}
	applyTargetToParams({
		action,
		args: params
	});
	if (actionRequiresTarget(action)) {
		if (!actionHasTarget(action, params)) throw new Error(`Action ${action} requires a target.`);
	}
	const channel = await resolveChannel(cfg, params);
	const accountId = readStringParam(params, "accountId") ?? input.defaultAccountId;
	if (accountId) params.accountId = accountId;
	const dryRun = Boolean(input.dryRun ?? readBooleanParam(params, "dryRun"));
	await normalizeSandboxMediaParams({
		args: params,
		sandboxRoot: input.sandboxRoot
	});
	await hydrateSendAttachmentParams({
		cfg,
		channel,
		accountId,
		args: params,
		action,
		dryRun
	});
	await hydrateSetGroupIconParams({
		cfg,
		channel,
		accountId,
		args: params,
		action,
		dryRun
	});
	const resolvedTarget = await resolveActionTarget({
		cfg,
		channel,
		action,
		args: params,
		accountId
	});
	enforceCrossContextPolicy({
		channel,
		action,
		args: params,
		toolContext: input.toolContext,
		cfg
	});
	const gateway = resolveGateway(input);
	if (action === "send") return handleSendAction({
		cfg,
		params,
		channel,
		accountId,
		dryRun,
		gateway,
		input,
		agentId: resolvedAgentId,
		resolvedTarget,
		abortSignal: input.abortSignal
	});
	if (action === "poll") return handlePollAction({
		cfg,
		params,
		channel,
		accountId,
		dryRun,
		gateway,
		input,
		abortSignal: input.abortSignal
	});
	return handlePluginAction({
		cfg,
		params,
		channel,
		accountId,
		dryRun,
		gateway,
		input,
		abortSignal: input.abortSignal
	});
}

//#endregion
export { supportsChannelMessageButtons as a, supportsChannelMessageCardsForChannel as c, listChannelMessageActions as i, runMessageAction as n, supportsChannelMessageButtonsForChannel as o, CHANNEL_MESSAGE_ACTION_NAMES as r, supportsChannelMessageCards as s, getToolResult as t };