UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

791 lines (790 loc) • 32.5 kB
import { D as parseStrictPositiveInteger } from "./number-coercion-D6u-4YD8.mjs"; import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { v as normalizeUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs"; import { r as normalizeOptionalAccountId } from "./account-id-BqKT3GuY.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { n as createRuntimeConfigReader } from "./runtime-snapshot-WbwbY5b7.mjs"; import { f as normalizeMessagePresentation, v as renderMessagePresentationFallbackText } from "./payload-Cab4FCxl.mjs"; import { n as jsonResult } from "./tool-results-CcV0sxnb.mjs"; import { d as readReactionParams, f as readStringArrayParam, m as readToolStringParam, p as readStringOrNumberParam, u as readPositiveIntegerParam } from "./common-njQNtpnW.mjs"; import { a as sendDurableMessageBatch } from "./channel-outbound-DQFse8vD.mjs"; import { n as normalizeOutboundLocation } from "./location-oMDzIggt.mjs"; import { t as captureChannelReadAuthority } from "./channel-read-authority-BVl4WY3A.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./runtime-config-snapshot-Dy0VFqWf.mjs"; import "./number-runtime-W4chuk8B.mjs"; import "./fetch-runtime-Dz-KqFMb.mjs"; import "./account-core-DMIDUKXd.mjs"; import { n as resolveTelegramToken } from "./token-Dmy_LoAW.mjs"; import "./session-store-runtime-D5peOAR8.mjs"; import { r as resolvePollMaxSelections } from "./polls-CTzQur-g.mjs"; import { t as buildOutboundSessionContext } from "./session-context-CCVPkFMh.mjs"; import "./channel-inbound-DA48LBlQ.mjs"; import "./interactive-runtime-sv_-VQ8S.mjs"; import { t as resolveReactionMessageId } from "./reaction-message-id-OibXGcWa.mjs"; import { t as readBooleanParam } from "./boolean-param-iT2wc5fb.mjs"; import "./channel-actions-DxuDuzvg.mjs"; import { r as resolveDefaultTelegramAccountId, s as resolveTelegramPollActionGateState, t as createTelegramActionGate } from "./accounts-C26vVqsr.mjs"; import { c as normalizeTelegramOutboundTarget, l as parseTelegramTarget, u as resolveTelegramTargetChatType } from "./topic-conversation-CDf2PinB.mjs"; import { v as resolveTelegramAccountOwnerAgentId } from "./prompt-context-projection-CoqAV_fc.mjs"; import { d as createTelegramMessageCache, f as hasProviderObservedTelegramThreadBinding, g as resolveTelegramMessageCacheScope } from "./send-outbound-8-7P0nHN.mjs"; import { r as inspectTelegramAccount } from "./account-inspect-C24-1-jt.mjs"; import { n as TELEGRAM_MESSAGE_ACTION_MAP, t as rejectTelegramNativeButtonParams } from "./native-button-params-CrIaa-o7.mjs"; import { r as resolveTelegramInlineButtonsScope } from "./inline-buttons-uex3aS7P.mjs"; import { t as resolveTelegramReactionLevel } from "./reaction-level-Bqy9u5yv.mjs"; import { j as resolveTelegramRichMessages } from "./text-chunk-limit-DTiKmKhG.mjs"; import { a as resolveTelegramButtonsFromParams, n as buildTelegramControlDegradation, t as appendTelegramDroppedControlFallback } from "./button-types-D-RCz2yJ.mjs"; import { o as resolveTelegramInteractiveTextFallback } from "./interactive-fallback-CGI6v8n_.mjs"; import { i as getCacheStats, o as searchStickers } from "./sticker-cache-By7J2yVe.mjs"; import { B as TELEGRAM_SUPPORTED_REACTION_EMOJI_LIST, C as editMessageTelegram, D as editForumTopicTelegram, E as createForumTopicTelegram, F as getTelegramAllowedReactions, L as reactMessageTelegram, N as updateTopicName, P as deleteMessageTelegram, S as editMessageReplyMarkupTelegram, n as sendStickerTelegram, t as sendPollTelegram } from "./send-CkT6jkYo.mjs"; import { t as resolveTelegramPollVisibility } from "./poll-visibility-BFqVORgv.mjs"; import { a as isTelegramHistorySenderAllowed, i as isTelegramHistoryNodeAllowed, o as readTelegramHistory, r as telegramInboundEventDelivery, t as renderTelegramAccountProgressDraftPreview } from "./progress-draft-preview-CFzpew0W.mjs"; //#region extensions/telegram/src/action-params.ts const TELEGRAM_FORUM_TOPIC_ICON_COLORS = [ 7322096, 16766590, 13338331, 9367192, 16749490, 16478047 ]; const SEND_MEDIA_FIELDS = [ "mediaUrl", "media", "path", "filePath", "fileUrl" ]; const ATTACHMENT_MEDIA_FIELDS = [ "media", "mediaUrl", "path", "filePath", "fileUrl", "url" ]; function readTelegramPositiveIntegerParam(e, t) { return readPositiveIntegerParam(e, t, { message: `${t} must be a positive integer.` }); } function readTelegramForumTopicIconColor(e) { const t = readPositiveIntegerParam(e, "iconColor", { message: "iconColor must be one of Telegram's supported forum topic colors." }); const n = TELEGRAM_FORUM_TOPIC_ICON_COLORS.find((e) => e === t); if (t != null && n === void 0) throw new Error("iconColor must be one of Telegram's supported forum topic colors."); return n; } function readTelegramChatId(e) { return readStringOrNumberParam(e, "chatId") ?? readStringOrNumberParam(e, "channelId") ?? readStringOrNumberParam(e, "to", { required: true }); } function readTelegramThreadId(e) { return readTelegramPositiveIntegerParam(e, "messageThreadId") ?? readTelegramPositiveIntegerParam(e, "threadId"); } function readTelegramReplyToMessageId(e) { return readTelegramPositiveIntegerParam(e, "replyToMessageId") ?? readTelegramPositiveIntegerParam(e, "replyTo"); } function readTelegramSendMediaUrls(e) { const t = Array.isArray(e.attachments) ? e.attachments.filter(isRecord) : []; return normalizeUniqueTrimmedStringList([ ...SEND_MEDIA_FIELDS.map((t) => e[t]), ...Array.isArray(e.mediaUrls) ? e.mediaUrls : [], ...t.flatMap((e) => ATTACHMENT_MEDIA_FIELDS.map((t) => e[t])) ]); } function normalizeTelegramDeliveryPin(e) { const t = asOptionalRecord(e.delivery); const n = t ? t.pin : e.pin === true ? true : void 0; if (n === true) return { enabled: true }; const r = asOptionalRecord(n); if (r?.enabled !== true) return; return { enabled: true, ...r.notify === true ? { notify: true } : {}, ...r.required === true ? { required: true } : {} }; } //#endregion //#region extensions/telegram/src/history-read.ts const HISTORY_SCOPE_ERROR = "Telegram history read requires the authenticated current group session, account, chat, and exact topic."; function resolveReadScope(e, t) { const n = t?.toolContext; const r = normalizeOptionalAccountId(t?.requesterAccountId); const i = normalizeOptionalAccountId(readStringOrNumberParam(e, "accountId")); const a = t?.requesterSenderId?.trim(); if (!t?.sessionKey?.trim() || !r || i !== void 0 && i !== r || !a || !/^\d+$/.test(a) || n?.currentChannelProvider?.trim().toLowerCase() !== "telegram" || n.currentChatType !== void 0 && n.currentChatType !== "group") throw new Error(HISTORY_SCOPE_ERROR); const o = [n.currentChannelId, n.currentMessagingTarget].filter((e) => typeof e === "string" && Boolean(e.trim())).map(parseTelegramTarget); const s = o[0]?.chatId; const c = parseStrictPositiveInteger(n.currentThreadTs); if (n.currentThreadTs != null && c === void 0) throw new Error(HISTORY_SCOPE_ERROR); const l = [...o.map((e) => e.messageThreadId), c].filter((e) => e !== void 0); const u = l[0]; if (!s || !/^-\d+$/.test(s) || o.some((e) => e.chatId !== s || e.directMessagesTopicId !== void 0) || l.some((e) => e !== u || e <= 0)) throw new Error(HISTORY_SCOPE_ERROR); for (const t of [ "target", "to", "chatId", "channelId" ]) { const n = readStringOrNumberParam(e, t); if (n === void 0) continue; const r = parseTelegramTarget(n); if (r.chatId !== s || r.directMessagesTopicId !== void 0 || r.messageThreadId !== void 0 && r.messageThreadId !== u) throw new Error(HISTORY_SCOPE_ERROR); } for (const t of ["threadId", "messageThreadId"]) { const n = readPositiveIntegerParam(e, t); if (n !== void 0 && n !== u) throw new Error(HISTORY_SCOPE_ERROR); } return { accountId: r, chatId: s, threadId: u, senderId: a, sessionKey: t.sessionKey, currentMessageId: parseStrictPositiveInteger(n.currentMessageId) }; } async function readTelegramHistoryAction(e, t, n) { const r = captureChannelReadAuthority(); r?.(); n?.assertDirectAdapterHandoff?.(); const i = resolveReadScope(e, n); const a = createRuntimeConfigReader(t); const o = a(); const s = { ...n?.toolContext }; const c = n?.requesterAccountId; const l = n?.requesterSenderId; const assertCurrent = () => { r?.(); n?.assertDirectAdapterHandoff?.(); const e = n?.toolContext; if (a() !== o || n?.requesterAccountId !== c || n?.requesterSenderId !== l || n?.sessionKey !== i.sessionKey || e?.currentChannelProvider !== s.currentChannelProvider || e?.currentChatType !== s.currentChatType || e?.currentChannelId !== s.currentChannelId || e?.currentMessagingTarget !== s.currentMessagingTarget || e?.currentThreadTs !== s.currentThreadTs || e?.currentMessageId !== s.currentMessageId) throw new Error(HISTORY_SCOPE_ERROR); }; const u = inspectTelegramAccount({ cfg: o, accountId: i.accountId }); if (!u.enabled || !u.configured || u.accountId !== i.accountId) throw new Error("Telegram history is unavailable for the current account."); const d = { cfg: o, accountId: i.accountId, chatId: i.chatId, threadId: i.threadId, botUserId: parseStrictPositiveInteger(u.token.split(":", 1)[0]), assertCurrent }; if (!await isTelegramHistorySenderAllowed({ ...d, senderId: i.senderId })) throw new Error("Telegram history read is not permitted by the current group policy."); const f = createTelegramMessageCache({ scope: resolveTelegramMessageCacheScope(resolveSessionStorePathCore(o.session?.store, { agentId: resolveTelegramAccountOwnerAgentId({ cfg: o, accountId: i.accountId }) })) }); const p = readPositiveIntegerParam(e, "messageId"); const m = readPositiveIntegerParam(e, "before"); const h = readPositiveIntegerParam(e, "after"); if (e.around != null) throw new Error("Telegram history supports messageId for an exact message, or before/after for paging."); if (p !== void 0 && (m !== void 0 || h !== void 0)) throw new Error("Use messageId alone for an exact Telegram history read."); const g = Math.min(readPositiveIntegerParam(e, "limit") ?? 50, 100); assertCurrent(); let _; if (p !== void 0) { const e = await f.get({ ...i, messageId: String(p) }); const t = e && await isTelegramHistoryNodeAllowed({ ...d, node: e }); _ = { messages: e && t ? [e] : [], hasMore: false }; } else { const e = m ?? (h === void 0 ? i.currentMessageId : void 0); _ = await readTelegramHistory({ ...d, cache: f, before: e === void 0 ? void 0 : String(e), after: h === void 0 ? void 0 : String(h), limit: g }); } if (!await isTelegramHistorySenderAllowed({ ...d, senderId: i.senderId })) throw new Error("Telegram history read is not permitted by the current group policy."); assertCurrent(); return jsonResult({ ok: true, chatId: i.chatId, ...i.threadId !== void 0 ? { threadId: i.threadId } : {}, messages: _.messages.map((e) => ({ messageId: e.messageId, sender: e.sender, senderId: e.senderId, senderUsername: e.senderUsername, timestamp: e.timestamp, body: e.body, mediaType: e.mediaType, mediaRef: e.mediaRef, replyToId: e.replyToId })), hasMore: _.hasMore, oldestMessageId: _.messages[0]?.messageId, newestMessageId: _.messages.at(-1)?.messageId }); } //#endregion //#region extensions/telegram/src/message-topic-binding.ts const TOPIC_BINDING_ERROR = "Delegated Telegram message mutation requires a provider-observed binding to the exact current topic and account."; const CONVERSATION_BINDING_ERROR = "Delegated Telegram conversation read requires the exact current chat and account."; function resolveCurrentTelegramConversation(e, t) { if (e?.currentChannelProvider?.trim().toLowerCase() !== "telegram") return { matchesChat: false }; const n = [e.currentChannelId, e.currentMessagingTarget].filter((e) => typeof e === "string" && Boolean(e.trim())); const r = n.map((e) => parseTelegramTarget(e)); const i = [...r.map((e) => e.messageThreadId), parseStrictPositiveInteger(e.currentThreadTs)].filter((e) => e !== void 0); const a = i[0]; return { matchesChat: n.length > 0 && r.every((e) => e.chatId === t) && (a === void 0 || i.every((e) => e === a)), threadId: a }; } function resolveMatchingTelegramRequesterAccount(e) { const t = normalizeOptionalAccountId(e.accountId ?? resolveDefaultTelegramAccountId(e.cfg)); const n = normalizeOptionalAccountId(e.context?.requesterAccountId); return t && t === n ? t : void 0; } function resolveTelegramConversationReadChatId(e) { const t = e.context?.toolContext?.currentChannelId ?? e.context?.toolContext?.currentMessagingTarget; const n = e.chatId ?? t; if (n == null || !String(n).trim()) throw new Error("Telegram emoji-list requires a chatId or current Telegram conversation."); const r = parseTelegramTarget(String(n)); if (e.context?.conversationReadOrigin === "direct-operator") return r.chatId; const i = resolveCurrentTelegramConversation(e.context?.toolContext, r.chatId); if (!resolveMatchingTelegramRequesterAccount(e) || !i.matchesChat || r.messageThreadId !== void 0 && r.messageThreadId !== i.threadId) throw new Error(CONVERSATION_BINDING_ERROR); return r.chatId; } async function resolveTelegramMessageMutationChatId(e) { const t = parseTelegramTarget(String(e.chatId)); if (e.context?.conversationReadOrigin === "direct-operator") return t.messageThreadId === void 0 ? e.chatId : t.chatId; const n = resolveCurrentTelegramConversation(e.context?.toolContext, t.chatId); const r = resolveMatchingTelegramRequesterAccount(e); if (!r || !n.matchesChat) throw new Error(TOPIC_BINDING_ERROR); const i = t.messageThreadId ?? n.threadId; if (i === void 0) return t.chatId; if (n.threadId !== i) throw new Error(TOPIC_BINDING_ERROR); if (parseStrictPositiveInteger(e.context?.toolContext?.currentMessageId) === e.messageId) return t.chatId; const a = await createTelegramMessageCache({ scope: resolveTelegramMessageCacheScope(resolveSessionStorePathCore(e.cfg.session?.store, { agentId: resolveTelegramAccountOwnerAgentId({ cfg: e.cfg, accountId: r }) })) }).get({ accountId: r, chatId: t.chatId, messageId: String(e.messageId) }); if (!hasProviderObservedTelegramThreadBinding(a, i)) throw new Error(TOPIC_BINDING_ERROR); return t.chatId; } //#endregion //#region extensions/telegram/src/action-runtime.ts const TELEGRAM_EMOJI_LIST_LIMIT = 100; const TELEGRAM_REACTION_HINT_LIMIT = 20; const TELEGRAM_DEFAULT_REACTIONS = TELEGRAM_SUPPORTED_REACTION_EMOJI_LIST.map((e) => ({ type: "emoji", emoji: e })); const TELEGRAM_ACTION_ALIASES = { ...TELEGRAM_MESSAGE_ACTION_MAP, createForumTopic: "createForumTopic", deleteMessage: "deleteMessage", editForumTopic: "editForumTopic", editMessage: "editMessage", searchSticker: "searchSticker", sendMessage: "sendMessage", sendSticker: "sendSticker", stickerCacheStats: "stickerCacheStats" }; function normalizeTelegramActionName(e) { const t = TELEGRAM_ACTION_ALIASES[e]; if (!t) throw new Error(`Unsupported Telegram action: ${e}`); return t; } function resolveActionTopicNameCacheScope(e, t) { const n = t ?? resolveDefaultTelegramAccountId(e); return resolveSessionStorePathCore(e.session?.store, { agentId: resolveTelegramAccountOwnerAgentId({ cfg: e, accountId: n }) }); } function formatTelegramDeliveryTarget(e, t) { const n = parseTelegramTarget(e); const r = n.directMessagesTopicId; if (r != null) return `${n.chatId}:direct-topic:${r}`; const i = t ?? n.messageThreadId; if (i == null) return e; return `${n.chatId}:topic:${i}`; } async function handleTelegramAction(e, t, n) { rejectTelegramNativeButtonParams(e); const r = normalizeTelegramActionName(readToolStringParam(e, "action", { required: true })); const i = readToolStringParam(e, "accountId"); const a = createTelegramActionGate({ cfg: t, accountId: i }); const o = { cfg: t, accountId: i, gatewayClientScopes: n?.gatewayClientScopes, assertPlatformSendAuthorized: n?.assertDirectAdapterHandoff }; const requireToken = () => { const e = resolveTelegramToken(t, { accountId: i }).token; if (!e) throw new Error("Telegram bot token missing. Set TELEGRAM_BOT_TOKEN or channels.telegram.botToken."); return e; }; const notifyVisibleOutboundSuccess = (e, t) => { telegramInboundEventDelivery.notify({ sessionKey: n?.sessionKey ?? void 0, to: formatTelegramDeliveryTarget(e, t), accountId: i, inboundEventKind: n?.inboundEventKind }); }; const s = []; const resolveButtons = (n, r) => resolveTelegramButtonsFromParams(e, r, { allowWebAppButtons: resolveTelegramTargetChatType(n) === "direct", supportsDisabled: resolveTelegramRichMessages({ cfg: t, accountId: i }), onDroppedControl: (e) => s.push(e) }); const requireInlineButtonsScope = () => { const e = resolveTelegramInlineButtonsScope({ cfg: t, accountId: i }); if (e === "off") throw new Error("Telegram inline buttons are disabled. Set channels.telegram.capabilities.inlineButtons to \"dm\", \"group\", \"all\", or \"allowlist\"."); return e; }; if (r === "read") return await readTelegramHistoryAction(e, t, n); if (r === "emoji-list") { if (!a("reactions")) throw new Error("Telegram reactions are disabled via actions.reactions."); const r = resolveTelegramConversationReadChatId({ chatId: readStringOrNumberParam(e, "chatId") ?? readStringOrNumberParam(e, "channelId") ?? readStringOrNumberParam(e, "to"), cfg: t, accountId: i, context: n }); const o = requireToken(); const s = Math.min(readTelegramPositiveIntegerParam(e, "limit") ?? TELEGRAM_EMOJI_LIST_LIMIT, TELEGRAM_EMOJI_LIST_LIMIT); const c = await getTelegramAllowedReactions(r, { cfg: t, token: o, accountId: i }); return jsonResult({ ok: true, emojis: (c ?? TELEGRAM_DEFAULT_REACTIONS).slice(0, s).map((e) => e.type === "emoji" ? { name: e.emoji, identifier: e.emoji } : { identifier: e.custom_emoji_id, type: "custom_emoji" }), ...c === null ? { note: "All standard Telegram reactions are allowed." } : {} }); } if (r === "react") { const rejectReaction = (e, t) => jsonResult({ ok: false, reason: e, hint: t }); const missingMessageId = () => rejectReaction("missing_message_id", "Telegram reaction requires a valid messageId (or inbound context fallback). Do not retry."); const r = resolveTelegramReactionLevel({ cfg: t, accountId: i }); if (!r.agentReactionsEnabled) return rejectReaction("disabled", `Telegram agent reactions disabled (reactionLevel="${r.level}"). Do not retry.`); if (!a("reactions")) return rejectReaction("disabled", "Telegram reactions are disabled via actions.reactions. Do not retry."); const s = readTelegramChatId(e); let c; try { c = readTelegramPositiveIntegerParam(e, "messageId"); } catch { return missingMessageId(); } const l = c ?? resolveReactionMessageId({ args: e }); if (typeof l !== "number" || !Number.isFinite(l) || l <= 0) return missingMessageId(); const { emoji: u, remove: d, isEmpty: f } = readReactionParams(e, { removeErrorMessage: "Emoji is required to remove a Telegram reaction." }); const p = resolveTelegramToken(t, { accountId: i }).token; if (!p) return rejectReaction("missing_token", "Telegram bot token missing. Do not retry."); let m; let h = s ?? ""; const describeAllowedReactions = async () => { const e = await getTelegramAllowedReactions(h, { cfg: t, token: p, accountId: i }).catch(() => void 0); if (e === void 0) return ""; const n = e ?? TELEGRAM_DEFAULT_REACTIONS; const r = n.filter((e) => e.type === "emoji").slice(0, TELEGRAM_REACTION_HINT_LIMIT).map((e) => e.emoji); const a = n.filter((e) => e.type === "custom_emoji").slice(0, TELEGRAM_REACTION_HINT_LIMIT - r.length).map((e) => e.custom_emoji_id); const o = a.length ? `numeric custom IDs ${a.join(", ")}` : ""; const s = [r.join(" "), o].filter(Boolean).join("; "); return s ? ` This chat allows: ${s}.` : ""; }; try { h = await resolveTelegramMessageMutationChatId({ chatId: s ?? "", messageId: l, cfg: t, accountId: i, context: n }); m = await reactMessageTelegram(h, l, u ?? "", { ...o, token: p, remove: d }); } catch (e) { const t = String(e).includes("REACTION_INVALID"); return jsonResult({ ok: false, reason: t ? "REACTION_INVALID" : "error", emoji: u, hint: t ? `This reaction is unavailable.${await describeAllowedReactions()}` : "Reaction failed. Do not retry." }); } const g = d || f ? { removed: true } : { added: u }; if (!m.ok) { const e = await describeAllowedReactions(); return jsonResult({ ok: false, warning: `${m.warning}${e}`, ...g }); } return jsonResult({ ok: true, ...g }); } if (r === "sendMessage") { if (!a("sendMessage")) throw new Error("Telegram sendMessage is disabled."); const r = normalizeTelegramOutboundTarget(readToolStringParam(e, "to", { required: true })); const o = readTelegramSendMediaUrls(e); const c = o[0]; const l = normalizeOutboundLocation(e.location); const u = normalizeMessagePresentation(e.presentation); const d = resolveButtons(r, u); const f = Array.isArray(d) && d.length > 0; const p = Boolean(l); const m = e.interactive; const h = readToolStringParam(e, "content", { allowEmpty: true }) ?? readToolStringParam(e, "message", { allowEmpty: true }) ?? readToolStringParam(e, "caption", { allowEmpty: true }); const g = u?.blocks.filter((e) => e.type === "chart" || e.type === "table") ?? []; const _ = h == null && u ? renderMessagePresentationFallbackText({ presentation: u }) : h != null && g.length > 0 ? renderMessagePresentationFallbackText({ text: h, presentation: { ...u, blocks: g } }) : void 0; const v = h == null && !u ? resolveTelegramInteractiveTextFallback({ interactive: m }) : void 0; const y = (_?.trim() ? _ : void 0) ?? h ?? (v?.trim() ? v : void 0); if (y == null && !c && !f && !p) throw new Error("content required."); const b = y ?? ""; const x = s.length > 0 && h != null ? appendTelegramDroppedControlFallback(b, s) : b; const S = appendTelegramDroppedControlFallback("", s); const C = h == null && S.length > 0 && x.trim() === S.trim(); const w = readBooleanParam(e, "asVideoNote") ?? false; if (l && (x.trim() && !C || o.length > 0 || w)) throw new Error("Telegram location sends cannot be combined with message text or media."); if (w && o.length !== 1) throw new Error("Telegram video notes require exactly one media attachment."); if (d) { const e = requireInlineButtonsScope(); if (e === "dm" || e === "group") { const t = resolveTelegramTargetChatType(r); if (t === "unknown") throw new Error(`Telegram inline buttons require a numeric chat id when inlineButtons="${e}".`); if (e === "dm" && t !== "direct") throw new Error("Telegram inline buttons are limited to DMs when inlineButtons=\"dm\"."); if (e === "group" && t !== "group") throw new Error("Telegram inline buttons are limited to groups when inlineButtons=\"group\"."); } } const T = readTelegramReplyToMessageId(e); const E = readTelegramThreadId(e); const D = readToolStringParam(e, "quoteText", { trim: false }); requireToken(); const O = readBooleanParam(e, "asVoice"); const k = readBooleanParam(e, "silent"); const A = readBooleanParam(e, "forceDocument") ?? readBooleanParam(e, "asDocument") ?? false; const j = normalizeTelegramDeliveryPin(e); const M = d || D ? { ...d ? { buttons: d } : {}, ...D ? { quoteText: D } : {} } : void 0; const N = { text: x, ...o.length > 0 ? { mediaUrls: o } : {}, ...O === true ? { audioAsVoice: true } : {}, ...w ? { videoAsNote: true } : {}, ...l ? { location: l } : {}, ...j ? { delivery: { pin: j } } : {}, ...M ? { channelData: { telegram: M } } : {} }; const P = n?.mediaAccess ?? (n?.mediaLocalRoots || n?.mediaReadFile ? { ...n.mediaLocalRoots ? { localRoots: n.mediaLocalRoots } : {}, ...n.mediaReadFile ? { readFile: n.mediaReadFile } : {} } : void 0); const F = buildOutboundSessionContext({ cfg: t, sessionKey: n?.sessionKey, requesterAccountId: i }); const I = await sendDurableMessageBatch({ cfg: t, channel: "telegram", to: r, accountId: i, payloads: [N], ...n?.reply ? { reply: n.reply } : { replyToId: T == null ? void 0 : String(T) }, threadId: E, forceDocument: A, silent: k, durability: "required", gatewayClientScopes: n?.gatewayClientScopes, deliveryRetryOwner: n?.deliveryRetryOwner, onPlatformSendDispatch: n?.onPlatformSendDispatch, assertDirectAdapterHandoff: n?.assertDirectAdapterHandoff, skipQueue: n?.skipQueue, ...P ? { mediaAccess: P } : {}, ...F ? { session: F } : {} }); if (I.status === "failed" || I.status === "partial_failed") throw I.error; if (I.status === "suppressed") { if (I.reason === "adapter_returned_no_identity" || I.payloadOutcomes?.some((e) => e.status === "failed" ? e.sentBeforeError : e.status === "sent" || e.reason === "adapter_returned_no_identity")) throw new Error("Telegram sendMessage was suppressed before delivery."); return jsonResult({ status: "suppressed", reason: I.reason }); } const L = I.results.at(-1); const R = I.receipt; notifyVisibleOutboundSuccess(r, E); return jsonResult({ ok: true, messageId: L?.messageId ?? R.primaryPlatformMessageId ?? R.platformMessageIds.at(-1), chatId: L?.target?.kind === "chat" ? L.target.id : void 0, receipt: { threadId: R.threadId, replyToId: R.replyToId }, ...buildTelegramControlDegradation(s, Boolean(x.trim())) }); } if (r === "poll") { const t = resolveTelegramPollActionGateState(a); if (!t.sendMessageEnabled) throw new Error("Telegram sendMessage is disabled."); if (!t.pollEnabled) throw new Error("Telegram polls are disabled."); const n = readToolStringParam(e, "to", { required: true }); const r = readToolStringParam(e, "question") ?? readToolStringParam(e, "pollQuestion", { required: true }); const i = readStringArrayParam(e, "answers") ?? readStringArrayParam(e, "pollOption", { required: true }); const s = readBooleanParam(e, "allowMultiselect") ?? readBooleanParam(e, "pollMulti"); const c = readTelegramPositiveIntegerParam(e, "durationSeconds") ?? readTelegramPositiveIntegerParam(e, "pollDurationSeconds"); const l = readTelegramPositiveIntegerParam(e, "durationHours") ?? readTelegramPositiveIntegerParam(e, "pollDurationHours"); const u = readTelegramReplyToMessageId(e); const d = readTelegramThreadId(e); const f = readBooleanParam(e, "isAnonymous") ?? resolveTelegramPollVisibility({ pollAnonymous: readBooleanParam(e, "pollAnonymous"), pollPublic: readBooleanParam(e, "pollPublic") }); const p = readBooleanParam(e, "silent"); const m = requireToken(); const h = await sendPollTelegram(n, { question: r, options: i, maxSelections: resolvePollMaxSelections(i.length, s ?? false), durationSeconds: c, durationHours: l }, { ...o, token: m, replyToMessageId: u, messageThreadId: d, isAnonymous: f, silent: p }); notifyVisibleOutboundSuccess(n, d); return jsonResult({ ok: true, messageId: h.messageId, chatId: h.chatId, pollId: h.pollId, ...h.pollAnswerRouting ? { pollAnswerRouting: h.pollAnswerRouting } : {}, ...h.warning ? { warning: h.warning } : {} }); } if (r === "deleteMessage" || r === "editMessage") { if (!a(r)) throw new Error(`Telegram ${r} is disabled.`); const c = readTelegramChatId(e); const l = readTelegramPositiveIntegerParam(e, "messageId"); if (l === void 0) throw new Error("messageId required"); const u = await resolveTelegramMessageMutationChatId({ chatId: c ?? "", messageId: l, cfg: t, accountId: i, context: n }); if (r === "deleteMessage") { const e = await deleteMessageTelegram(u, l, { ...o }); if (!e.ok) return jsonResult({ ok: false, deleted: false, warning: e.warning }); return jsonResult({ ok: true, deleted: true }); } let d = readToolStringParam(e, "content", { allowEmpty: false }) ?? readToolStringParam(e, "message", { allowEmpty: false }); let f = readToolStringParam(e, "caption", { allowEmpty: true }); let p; if (n?.progressSnapshot) { p = renderTelegramAccountProgressDraftPreview(n.progressSnapshot, { cfg: t, accountId: i }); d = p.text; } const m = resolveButtons(c ?? "") ?? (s.length > 0 && s.every((e) => e.reason === "disabled_unsupported") ? [] : void 0); if (s.length > 0) { if (f != null) f = appendTelegramDroppedControlFallback(f, s); else if (d != null) d = appendTelegramDroppedControlFallback(d, s); } if (d == null && f == null && m === void 0) { const e = buildTelegramControlDegradation(s, false); if (e) return jsonResult({ ok: false, ...e }); throw new Error("content required."); } if (m !== void 0) requireInlineButtonsScope(); const h = requireToken(); const g = d == null && f == null && m !== void 0; const _ = { ...o, token: h }; const v = g ? await editMessageReplyMarkupTelegram(u, l, m, _) : await editMessageTelegram(u, l, p?.parseMode === "HTML" ? p.text.replaceAll("<br>", "\n") : p?.text ?? f ?? d ?? "", { ..._, buttons: m, editMode: p ? "text" : f != null ? "caption" : "auto", ...p ? { textMode: p.parseMode === "HTML" ? "html" : "markdown", richMessage: p.richMessage } : {} }); return jsonResult({ ok: true, messageId: v.messageId, chatId: v.chatId, ...buildTelegramControlDegradation(s, !g) }); } if (r === "sendSticker" || r === "searchSticker") { if (!a("sticker", false)) throw new Error("Telegram sticker actions are disabled. Set channels.telegram.actions.sticker to true."); } if (r === "sendSticker") { const t = readToolStringParam(e, "to") ?? readToolStringParam(e, "target", { required: true }); const n = readToolStringParam(e, "fileId") ?? readStringArrayParam(e, "stickerId")?.[0]; if (!n) throw new Error("fileId is required."); const r = readTelegramReplyToMessageId(e); const i = readTelegramThreadId(e); const a = requireToken(); const s = await sendStickerTelegram(t, n, { ...o, token: a, replyToMessageId: r, messageThreadId: i }); notifyVisibleOutboundSuccess(t, i); return jsonResult({ ok: true, messageId: s.messageId, chatId: s.chatId }); } if (r === "searchSticker") { const t = readToolStringParam(e, "query", { required: true }); const n = readTelegramPositiveIntegerParam(e, "limit") ?? 5; const r = await searchStickers(t, n); return jsonResult({ ok: true, count: r.length, stickers: r.map((e) => ({ fileId: e.fileId, emoji: e.emoji, description: e.description, setName: e.setName })) }); } if (r === "stickerCacheStats") { const e = await getCacheStats(); return jsonResult({ ok: true, ...e }); } if (r === "createForumTopic" || r === "editForumTopic") { if (!a(r)) throw new Error(`Telegram ${r} is disabled.`); const n = readTelegramChatId(e); if (r === "createForumTopic") { const t = readToolStringParam(e, "name") ?? readToolStringParam(e, "threadName", { required: true, label: "name" }); const r = readTelegramForumTopicIconColor(e); const i = readToolStringParam(e, "iconCustomEmojiId"); const a = requireToken(); const s = await createForumTopicTelegram(n ?? "", t, { ...o, token: a, iconColor: r, iconCustomEmojiId: i }); return jsonResult({ ok: true, topicId: s.topicId, name: s.name, chatId: s.chatId }); } const s = readTelegramThreadId(e); if (typeof s !== "number") throw new Error("messageThreadId or threadId is required."); const c = readToolStringParam(e, "name") ?? readToolStringParam(e, "threadName"); const l = readToolStringParam(e, "iconCustomEmojiId"); const u = requireToken(); const d = await editForumTopicTelegram(n ?? "", s, { ...o, token: u, name: c, iconCustomEmojiId: l }); if (d.chatId) { const e = { ...c ? { name: c } : {}, ...l ? { iconCustomEmojiId: l } : {} }; if (Object.keys(e).length > 0) await updateTopicName(d.chatId, d.messageThreadId, e, resolveActionTopicNameCacheScope(t, i)).catch(() => {}); } return jsonResult(d); } throw new Error(`Unsupported Telegram action: ${String(r)}`); } //#endregion export { handleTelegramAction };