openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5,380 lines • 202 kB
JavaScript
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs";
import { D as parseStrictPositiveInteger, T as parseStrictInteger, V as timestampMsToIsoString, s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs";
import { d as sleepWithAbort, n as computeBackoff } from "./src-BPmQBLJp.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { w as root } from "./fs-safe-BbWvmdVn.mjs";
import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { a as resolveAgentDir, r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { n as resolveDefaultModelForAgent } from "./model-selection-config-Bvf5WqHo.mjs";
import { f as normalizeMessagePresentation } from "./payload-Cab4FCxl.mjs";
import { N as stripReplyPayloadResponsePrefix, a as buildTtsSupplementMediaPayload, f as isFastModeAutoProgressPayload, h as isReplyPayloadNonTerminalToolErrorWarning, l as getReplyPayloadTtsSupplement, o as copyReplyPayloadMetadata, y as isReplyPayloadTerminalContent } from "./reply-payload-k5WsQWxi.mjs";
import { r as isInsideCode } from "./code-ranges-2XaqsF-S.mjs";
import { n as findMarkdownCodeRegions } from "./reasoning-tags-DL3sP_9k.mjs";
import { m as stripReasoningTagsFromText } from "./assistant-visible-text-fPqh5m9O.mjs";
import { n as resolvePromptHistoryLimit } from "./history-limit-D9prPWZZ.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { o as getGroupThreadDeliverySession } from "./group-thread-context-DFimpu_J.mjs";
import { o as warn, r as logVerbose, t as danger } from "./globals-CgepmiqE.mjs";
import { p as fireAndForgetHook } from "./hooks-BiZpB_10.mjs";
import { t as collectReplyMediaEntries } from "./reply-media-entries-BE-R1jqq.mjs";
import { c as triggerInternalHook, n as createInternalHookEvent } from "./internal-hooks-D6nf-Q3g.mjs";
import { r as resolveStoredModelOverrideAsync } from "./stored-model-overrides-CyqayMPa.mjs";
import { M as takeMessageIdAfterStop, T as resolveChannelDraftStreamingChunking, c as resolveTranscriptBackedChannelFinalText, j as createFinalizableDraftStreamControlsForState, l as selectLongerFinalText, n as deliverStructuredInboundReplyWithMessageSendContext, r as preserveReplyPayloadMediaSelection, s as isPotentialTruncatedFinal } from "./channel-outbound-DQFse8vD.mjs";
import { i as resolveInboundMentionDecision, n as implicitMentionKindWhen, r as resolveBotThreadMentionPolicy } from "./mention-gating-BBO25eef.mjs";
import { n as firstDefined, r as isSenderIdAllowed } from "./allow-from-BGE4RL6B.mjs";
import { i as resolveHumanDelayConfig, t as resolveAckReaction } from "./identity-Cd2mxvzm.mjs";
import { r as toLocationContext } from "./location-oMDzIggt.mjs";
import { d as resolveAskUserQuestionOptionIndices, o as hasReplyPayloadFinalDeliveryCapture } from "./reply-payload-CwASJYas.mjs";
import { a as resolveSendableOutboundReplyParts } from "./reply-payload-parts-0Tn7wkpR.mjs";
import { n as isSingleUseReplyToMode } from "./reply-reference-DrrH-Rw0.mjs";
import "./file-access-runtime-BD2Fjfbw.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import { a as createDeferred } from "./extension-shared-CJ4teJ7p.mjs";
import "./security-runtime-C-zE_Zy_.mjs";
import { t as evaluateSupplementalContextVisibility } from "./context-visibility-DKa41bxb.mjs";
import { i as resolvePinnedMainDmOwnerFromAllowlist } from "./dm-policy-shared-DYfj6q8U.mjs";
import "./ssrf-runtime-B6q6NM4E.mjs";
import "./text-utility-runtime-Ds8jsG0J.mjs";
import { l as runDetachedWebhookWork } from "./webhook-request-guards-Br7AftEb.mjs";
import "./number-runtime-W4chuk8B.mjs";
import { r as PlatformMessageNotDispatchedError } from "./deliver-types-BnSKrpHG.mjs";
import "./error-runtime-BM740gJj.mjs";
import "./concurrency-runtime-CY4L3doa.mjs";
import "./runtime-env-D-Pa5lD6.mjs";
import { C as readTelegramRetryAfterMs, F as normalizeTelegramApiRoot, f as isRetryableTelegramApiError, g as isTelegramClientRejection, l as TelegramRequestNotStartedError, p as isSafeToRetrySendError, r as shouldRetryTelegramTransportFallback, u as hasTelegramNetworkErrorCode, x as isTelegramRateLimitError, y as isTelegramMessageNotModifiedError } from "./fetch-Credn4zH.mjs";
import { r as createStructuredOutboundPayloadPlan, t as createOutboundPayloadPlan } from "./payloads-CQvywZOF.mjs";
import { a as toInternalMessageReceivedContext } from "./message-hook-mappers-BCrhfgqk.mjs";
import { n as getAgentScopedMediaLocalRoots } from "./local-roots-BTz6ULME.mjs";
import { d as saveMediaBuffer } from "./store-zsTAVy24.mjs";
import { n as normalizeCommandBody } from "./commands-registry-normalize-dI3NYF5y.mjs";
import { n as readAgentRunTerminalOutcome } from "./agent-run-terminal-outcome-BQoZ_25h.mjs";
import { s as resolveInboundLastRouteSessionKey } from "./resolve-route-DBnTWpM6.mjs";
import { r as matchesMentionWithExplicit, t as buildMentionRegexes } from "./mentions-CACvAvae.mjs";
import { l as resolveGroupThreadMentionFacts } from "./dispatch-vEUtrodM.mjs";
import { T as resolveChannelStreamingPreviewToolProgress, u as isChannelProgressDraftWorkToolName, v as resolveChannelProgressDraftMaxLineChars, x as resolveChannelStreamingBlockEnabled, y as resolveChannelProgressDraftMaxLines } from "./streaming-DsQF8isK.mjs";
import { t as hasControlCommand } from "./command-detection-BdYTt9PO.mjs";
import { t as PLUGIN_COMMAND_DISPATCH } from "./plugin-command-dispatch-contract-4LAPWU0e.mjs";
import { n as formatAudioTranscriptForAgent } from "./echo-transcript-C-BDqHL2.mjs";
import { a as saveRemoteMedia, t as MediaFetchError } from "./fetch-CpjnlJme.mjs";
import { n as loadWebMedia } from "./web-media-CX3Hvr6c.mjs";
import "./routing-DmgGYTrU.mjs";
import "./agent-scope-runtime-CDpr-vor.mjs";
import { o as resolveTelegramAccountConfig } from "./account-selection-CGYGB8bX.mjs";
import { n as getSessionEntryAsync } from "./session-store-runtime-internal-DEwSyDjM.mjs";
import { t as resolveAmbientTranscriptWatermarkKey } from "./ambient-transcript-watermark-DudVwq95.mjs";
import { _ as readSessionUpdatedAtAsync, m as readAmbientTranscriptWatermarkAsync } from "./session-store-runtime-D5peOAR8.mjs";
import { c as resolveTextChunkLimit, s as resolveChunkMode } from "./chunk-D9JRZpRm.mjs";
import { a as resolveEnvelopeFormatOptions, r as formatInboundEnvelope } from "./envelope-C1e0Wmhj.mjs";
import { i as shouldAckReaction } from "./ack-reactions-wVmQEGsP.mjs";
import { n as formatInboundMediaUnavailableText, r as formatMediaPlaceholderText } from "./media-C-9Rs9OV.mjs";
import { t as buildChannelInboundEventContext } from "./context-BpxG76OD.mjs";
import { t as recordInboundSession } from "./session-DoRia6Kc.mjs";
import { n as recordChannelActivity } from "./channel-activity-elw91nA1.mjs";
import { c as upsertChannelPairingRequest } from "./pairing-store-Dwflz9v8.mjs";
import { n as isAbortRequestText } from "./abort-primitives-Bk9blQey.mjs";
import { d as formatReasoningMessage } from "./embedded-agent-utils-CRYA6mcb.mjs";
import { t as deriveDurableFinalDeliveryRequirements } from "./capabilities-Cm5mmzL6.mjs";
import { d as createChannelPartialDeliveryError, f as isChannelPartialDeliveryError, n as createLivePreviewLifecycle, r as createPreviewMessageReceipt, s as createAcceptedChannelDeliveryResult } from "./live-DOXDs-ke.mjs";
import { n as createChannelProgressDraftCompositor } from "./progress-draft-compositor-ClWAxBC_.mjs";
import { t as generateConversationLabel } from "./conversation-label-generator-DNK7CHE6.mjs";
import "./reply-dispatch-runtime-WQNxMuuK.mjs";
import "./reply-reference-CxilHBpH.mjs";
import "./reply-chunking-DEcptSL-.mjs";
import { t as createChannelReplyPipeline } from "./reply-pipeline-BLDOfhMa.mjs";
import { a as runChannelInboundEvent, d as resolveUnmentionedGroupInboundPolicy, u as classifyChannelInboundEvent } from "./channel-inbound-DA48LBlQ.mjs";
import { n as logInboundDrop, r as logTypingFailure } from "./logging-DyCvEa9E.mjs";
import "./interactive-runtime-sv_-VQ8S.mjs";
import "./web-media-aVGyt4Jk.mjs";
import "./media-runtime-B-kyz_D7.mjs";
import "./conversation-runtime-CefOz30L.mjs";
import "./text-chunking-B9FpckXY.mjs";
import "./agent-runtime-DA4W1L0G.mjs";
import "./plugin-command-runtime-CITBoUQv.mjs";
import "./plugin-runtime-z_iV2vts.mjs";
import "./hook-runtime-BncR_mRz.mjs";
import "./allow-from-KJPYRCAd.mjs";
import "./command-auth-native-DT07BMZD.mjs";
import "./command-primitives-runtime-BdQPnatN.mjs";
import "./command-detection-DsN8r3t3.mjs";
import "./command-surface-CQH79919.mjs";
import "./channel-feedback-ux7aYycZ.mjs";
import "./channel-mention-gating-Bq50i0VG.mjs";
import { t as createChannelPairingChallengeIssuer } from "./channel-pairing-R9ineSO_.mjs";
import { t as resolveChannelContextVisibilityMode } from "./context-visibility-runtime-A6y83BUa.mjs";
import { c as readLatestAssistantTextByIdentity, t as appendAssistantMirrorMessageByIdentity } from "./session-transcript-runtime-Bmol1TH_.mjs";
import "./media-understanding-runtime-BCwEOrrt.mjs";
import { i as resolveTelegramAccount, o as resolveTelegramMediaRuntimeOptions, r as resolveDefaultTelegramAccountId } from "./accounts-C26vVqsr.mjs";
import { t as buildTelegramConversationId, u as resolveTelegramTargetChatType } from "./topic-conversation-CDf2PinB.mjs";
import { a as resolveCompleteTelegramPromptContextProjectionIds, c as withTelegramPromptContextSource, g as TELEGRAM_CHAT_ACTION_INTERVAL_MS, h as runReplaceableTelegramRequest, m as runAuthorizedTelegramRequest, n as createTelegramPromptContextProjectionSequence, o as resolveTelegramPromptContextDeliverySignature, v as resolveTelegramAccountOwnerAgentId } from "./prompt-context-projection-CoqAV_fc.mjs";
import { n as withTelegramApiErrorLogging } from "./api-logging-D-u3hsql.mjs";
import { I as withTelegramNativeQuoteFallback, M as buildTelegramThreadReplyParams, S as telegramPromptContextHistory, _ as buildTelegramSelfSenderName, b as isTelegramSelfSenderName, c as recordOutboundMessageForPromptContext, d as createTelegramMessageCache, g as resolveTelegramMessageCacheScope, h as isTelegramMediaKind, i as reportTelegramProviderDelivery, l as buildTelegramConversationContext, m as resolveProviderObservedTelegramThreadSpec, o as recordSentMessage, u as buildTelegramReplyChain, v as isTelegramChatWindowPromptContext, x as selectTelegramGroupPromptContext, y as isTelegramHistoryEntryAfterAmbientWatermark } from "./send-outbound-8-7P0nHN.mjs";
import { A as hasBotMention, B as resolveTelegramDmAllow, D as buildSenderName, E as buildSenderLabel, F as resolveTelegramNonTextBody, I as resolveTelegramPrimaryMedia, L as resolveTelegramRichMessagePlaceholder, N as joinTelegramTextParts, P as normalizeForwardedContext, R as renderTelegramTextEntities, T as resolveTelegramPreviewStreamMode, U as resolveTelegramEffectiveDmPolicy, V as normalizeAllowFrom, a as buildTelegramInboundOriginTarget, c as buildTelegramThreadParams, d as extractTelegramForumFlag, h as resolveTelegramForumFlag, i as buildTelegramGroupPeerId, j as hasLeadingBotCommandAddressedToOtherBot, k as getTelegramTextParts, l as buildTypingThreadParams, m as resolveTelegramBotHasTopicsEnabled, n as buildGroupLabel, o as buildTelegramParentPeer, r as buildTelegramGroupFrom, u as describeReplyTarget, y as resolveTelegramMessageThreadSpec, z as expandTelegramAllowFromWithAccessGroups } from "./helpers-CoGccTxe.mjs";
import { n as getTelegramRuntime } from "./runtime-Gy4vBjmB.mjs";
import { C as renderTelegramHtmlText, E as escapeTelegramHtml, M as resolveTelegramTableMode, O as resolveTelegramGroupIngestEnabled, T as telegramHtmlToPlainTextFallback, a as buildTelegramRichMarkdownPlan, j as resolveTelegramRichMessages, k as resolveTelegramGroupPromptSettings, o as removeTelegramRichNativeQuoteParam, p as warnTelegramRichBlocksDegradations, r as TELEGRAM_RICH_TEXT_LIMIT, t as TELEGRAM_TEXT_CHUNK_LIMIT } from "./text-chunk-limit-DTiKmKhG.mjs";
import { d as shouldSuppressLocalTelegramExecApprovalPrompt } from "./exec-approvals-Crn--YHh.mjs";
import { t as normalizeTelegramStateAccountId } from "./state-account-id-BXoQeOII.mjs";
import { a as applyTelegramTargetSession, c as resolveTelegramConversationRoute, f as resolveTelegramDirectPeerId, i as registerTelegramQuestionDelivery, u as resolveTelegramTargetSession } from "./outbound-adapter-xqQwShsd.mjs";
import { o as resolveTelegramInlineButtons, t as appendTelegramDroppedControlFallback } from "./button-types-D-RCz2yJ.mjs";
import { a as resolveFinalTelegramPresentationText, i as markTelegramDroppedControlFallback, n as canonicalizeTelegramPresentationPayload, r as copyTelegramDroppedControlFallback, t as applyTextToPayload } from "./interactive-fallback-CGI6v8n_.mjs";
import { a as getCachedSticker, n as cacheSticker, t as describeStickerImage } from "./sticker-cache-By7J2yVe.mjs";
import { A as getTopicName, C as editMessageTelegram, G as resolveTelegramStatusReactionEmojis, H as resolveTelegramAllowedReactions, K as require_abort_controller, M as resolveTelegramDirectTopicNameCacheScope, N as updateTopicName, S as editMessageReplyMarkupTelegram, T as planTelegramTextDeliveryPages, U as resolveTelegramReactionEmoji, V as buildTelegramStatusReactionVariants, W as resolveTelegramReactionVariant, j as recordTopicCreation, k as getTopicCreatorUserId, m as mergeTelegramPartialDeliveryError, p as failPromptContextSequence, q as evaluateTelegramGroupBaseAccess, w as deliverTelegramTextPage } from "./send-CkT6jkYo.mjs";
import { c as createTelegramIngressResolver, d as resolveTelegramNativeCommandAdmission, f as resolveTelegramNativeCommandBody, i as isTelegramHistoryNodeAllowed, l as resolveTelegramCommandIngressAuthorization, n as renderTelegramProgressDraftPreview, p as telegramAllowEntries, r as telegramInboundEventDelivery, s as readTelegramHistoryWindow } from "./progress-draft-preview-CFzpew0W.mjs";
import { a as emitTelegramMessageSentHooks, i as buildTelegramNativeQuoteCandidate, n as deliverStructuredReplies, r as addTelegramNativeQuoteCandidate, t as deliverReplies } from "./delivery-kknhgdQm.mjs";
import path from "node:path";
import { AsyncLocalStorage } from "node:async_hooks";
import { GrammyError } from "grammy";
//#region extensions/telegram/src/bot-handlers.media.ts
var import_abort_controller = require_abort_controller();
const TELEGRAM_BOT_API_FILE_DOWNLOAD_LIMIT_MB = 20;
var TelegramBotApiFileTooLargeError = class extends MediaFetchError {
constructor(e) {
super("max_bytes", `Telegram Bot API cannot download files larger than ${TELEGRAM_BOT_API_FILE_DOWNLOAD_LIMIT_MB} MB`, {
cause: e,
status: 400
});
this.limitMb = TELEGRAM_BOT_API_FILE_DOWNLOAD_LIMIT_MB;
this.name = "TelegramBotApiFileTooLargeError";
}
};
function isMediaSizeLimitError(e) {
if (e instanceof MediaFetchError) return e.code === "max_bytes";
const t = String(e);
return t.includes("exceeds") && t.includes("MB limit");
}
function hasInboundMedia(e) {
return Boolean(e.media_group_id) || Array.isArray(e.photo) && e.photo.length > 0 || Boolean(e.video ?? e.video_note ?? e.animation ?? e.document ?? e.audio ?? e.voice ?? e.sticker);
}
//#endregion
//#region extensions/telegram/src/bot/delivery.resolve-media.ts
const FILE_TOO_BIG_RE = /file is too big/i;
const TELEGRAM_GET_FILE_RETRY_ATTEMPTS = 3;
function buildTelegramMediaSsrfPolicy(e, t) {
const n = ["api.telegram.org"];
let r;
if (e) try {
const t = new URL(e).hostname;
if (t && !n.includes(t)) {
n.push(t);
r = [t];
}
} catch (t) {
logVerbose(`telegram: invalid apiRoot URL "${e}": ${String(t)}`);
}
return {
hostnameAllowlist: n,
...r ? { allowedHostnames: r } : {},
...t ? { allowPrivateNetwork: true } : {},
allowRfc2544BenchmarkRange: true
};
}
function isFileTooBigError(e) {
return FILE_TOO_BIG_RE.test(e instanceof GrammyError ? e.description : formatErrorMessage(e));
}
function isRetryableGetFileError(e) {
if (isFileTooBigError(e)) return false;
if (isRetryableTelegramApiError(e)) return true;
return e instanceof GrammyError && e.method === "getFile" && e.error_code === 400 && /\bfile is temporarily unavailable\b/i.test(e.description);
}
function resolveMediaMetadata(e) {
return {
fileRef: e.photo?.[e.photo.length - 1] ?? e.video ?? e.video_note ?? e.animation ?? e.document ?? e.audio ?? e.voice,
fileName: e.animation?.file_name ?? e.document?.file_name ?? e.audio?.file_name ?? e.video?.file_name,
mimeType: e.audio?.mime_type ?? e.voice?.mime_type ?? e.video?.mime_type ?? e.animation?.mime_type ?? e.document?.mime_type
};
}
async function resolveTelegramFileWithRetry(e, t) {
const n = t;
try {
for (let r = 1;; r += 1) try {
return await e.getFile(n);
} catch (e) {
if (r >= TELEGRAM_GET_FILE_RETRY_ATTEMPTS || !isRetryableGetFileError(e)) throw e;
logVerbose(`telegram: getFile retry ${r}/${TELEGRAM_GET_FILE_RETRY_ATTEMPTS}`);
try {
await sleepWithAbort(readTelegramRetryAfterMs(e) ?? 1e3 * 2 ** (r - 1), t);
} catch {
throw e;
}
}
} catch (e) {
if (isFileTooBigError(e)) throw new TelegramBotApiFileTooLargeError(e);
const t = e instanceof GrammyError ? e.error_code : void 0;
throw new MediaFetchError(t ? "http_error" : "fetch_failed", `Telegram getFile failed after retries: ${formatErrorMessage(e)}`, {
cause: e,
status: t
});
}
}
const TELEGRAM_DOWNLOAD_IDLE_TIMEOUT_MS = 3e4;
const TELEGRAM_DOWNLOAD_RESPONSE_HEADER_TIMEOUT_MS = 12e4;
function resolveTrustedLocalTelegramRoot(e, t) {
if (!path.isAbsolute(e)) return null;
for (const n of t ?? []) {
const t = path.relative(n, e);
if (t === "" || t === ".." || t.startsWith(`..${path.sep}`) || path.isAbsolute(t)) continue;
return {
rootDir: n,
relativePath: t
};
}
return null;
}
const TELEGRAM_BOT_API_CONTAINER_DATA_ROOT = "/var/lib/telegram-bot-api";
function normalizeTrustedTelegramRelativeFilePath(e) {
const t = e.replace(/\\/g, "/").replace(/^\/+/, "");
if (!t || t.includes("\0")) return null;
if (t.split("/").some((e) => !e || e === "." || e === "..")) return null;
return t;
}
function resolveTelegramBotApiContainerRelativePaths(e, t) {
if (!path.isAbsolute(e)) return [];
const n = e.replace(/\\/g, "/");
const r = `${TELEGRAM_BOT_API_CONTAINER_DATA_ROOT}/`;
if (!n.startsWith(r)) return [];
const i = normalizeTrustedTelegramRelativeFilePath(n.slice(r.length));
if (!i) return [];
const a = [i];
for (const e of [t, t.replaceAll(":", "~")]) {
const t = `${e}/`;
if (e && i.startsWith(t)) a.push(i.slice(t.length));
}
return [...new Set(a)];
}
function isTrustedLocalTelegramFileMissing(e) {
return e instanceof Error && "code" in e && (e.code === "not-found" || e.code === "ENOENT" || e.code === "ENOTDIR");
}
async function resolveMedia(e) {
const { ctx: t, ...n } = e;
const r = t.message;
const i = r.sticker;
if (i?.is_animated || i?.is_video) {
logVerbose("telegram: skipping animated/video sticker (only static stickers supported)");
return null;
}
const a = i ? {
fileRef: i,
fileName: void 0,
mimeType: void 0
} : resolveMediaMetadata(r);
if (!a.fileRef?.file_id) return null;
const o = e.abortSignal ? AbortSignal.any([e.abortSignal, e.budget]) : e.budget;
const s = a.fileName;
const c = a.mimeType;
const l = await (async () => {
const e = await resolveTelegramFileWithRetry(t, o);
if (!e.file_path) throw new Error(`Telegram getFile returned no file_path${i ? " for sticker" : ""}`);
const r = e.file_path;
const a = resolveTrustedLocalTelegramRoot(r, n.trustedLocalFileRoots);
const l = a ? [] : resolveTelegramBotApiContainerRelativePaths(r, n.token);
const u = a ? [a] : (n.trustedLocalFileRoots ?? []).flatMap((e) => l.map((t) => ({
rootDir: e,
relativePath: t
})));
for (const { rootDir: e, relativePath: t } of u) {
let i;
try {
i = await (await root(e)).read(t, { maxBytes: n.maxBytes });
} catch (e) {
if (!a && isTrustedLocalTelegramFileMissing(e)) continue;
throw new MediaFetchError("fetch_failed", `Failed to read ${a ? `local Telegram Bot API media from ${r}` : "mapped local Telegram Bot API media"}: ${formatErrorMessage(e)}`, { cause: e });
}
return await saveMediaBuffer(i.buffer, c, "inbound", n.maxBytes, s ?? path.basename(i.realPath));
}
if (path.isAbsolute(r)) throw new MediaFetchError("fetch_failed", `Telegram Bot API returned absolute file path ${r} outside trustedLocalFileRoots`);
const d = n.transport;
const f = d ? d.sourceFetch : globalThis.fetch;
if (!d && !f) throw new Error("fetch is not available; set channels.telegram.proxy in config");
const p = `${normalizeTelegramApiRoot(n.apiRoot)}/file/bot${n.token}/${r}`;
return await saveRemoteMedia({
url: p,
fetchImpl: f,
dispatcherAttempts: d?.dispatcherAttempts,
trustExplicitProxyDns: d?.dispatcherAttempts?.some((e) => e.dispatcherPolicy?.mode === "explicit-proxy") ?? false,
shouldRetryFetchError: shouldRetryTelegramTransportFallback,
requestInit: { signal: o },
filePathHint: r,
maxBytes: n.maxBytes,
responseHeaderTimeoutMs: TELEGRAM_DOWNLOAD_RESPONSE_HEADER_TIMEOUT_MS,
readIdleTimeoutMs: TELEGRAM_DOWNLOAD_IDLE_TIMEOUT_MS,
ssrfPolicy: buildTelegramMediaSsrfPolicy(n.apiRoot, n.dangerouslyAllowPrivateNetwork),
fallbackContentType: c,
originalFilename: s
});
})();
let u;
if (i) {
const e = i.file_unique_id ? await getCachedSticker(i.file_unique_id) : null;
const t = i.file_id ?? e?.fileId;
const n = i.emoji ?? e?.emoji;
const r = i.set_name ?? e?.setName;
if (e) {
if (t !== e.fileId || n !== e.emoji || r !== e.setName) await cacheSticker({
...e,
fileId: t,
emoji: n,
setName: r
});
}
u = {
emoji: n,
setName: r,
fileId: t,
fileUniqueId: i.file_unique_id,
...e ? { cachedDescription: e.description } : {}
};
}
const d = i ? "sticker" : resolveTelegramPrimaryMedia(r)?.kind ?? "document";
return {
id: l.id,
path: l.path,
size: l.size,
contentType: l.contentType,
...a.fileName ? { fileName: a.fileName } : {},
kind: d !== "sticker" && l.contentType?.startsWith("audio/") ? "audio" : d === "document" && l.contentType?.startsWith("image/") ? "image" : d,
fileUniqueId: a.fileRef.file_unique_id,
savedAt: Date.now(),
...u ? { stickerMetadata: u } : {}
};
}
//#endregion
//#region extensions/telegram/src/bot-message-avatar.ts
const AVATAR_TTL_MS = 3e5;
const AVATAR_MAX_ENTRIES = 128;
const AVATAR_MAX_BYTES = 262144;
/** One resolver belongs to one bot account, never to the viewer's profile. */
function createTelegramDirectAvatarResolver(e) {
const t = /* @__PURE__ */ new Map();
const n = /* @__PURE__ */ new Set();
return (r, i) => {
const a = r.message;
const o = a.from?.id;
if (e.abortSignal?.aborted || a.chat.type !== "private" || !o || a.from?.is_bot || a.chat.id !== o) return;
const s = t.get(o);
if (s && s.expiresAt > Date.now()) return s.path;
if (n.has(o) || n.size >= AVATAR_MAX_ENTRIES) return s?.path;
const load = async () => {
const t = [AbortSignal.timeout(4e3), e.abortSignal].filter((e) => e !== void 0);
const n = AbortSignal.any(t);
const a = new import_abort_controller.AbortController();
const abort = () => a.abort();
if (n.aborted) abort();
else n.addEventListener("abort", abort, { once: true });
try {
const t = await e.api.getUserProfilePhotos(o, {
offset: 0,
limit: 1
}, a.signal);
if (n.aborted) return;
const s = t.photos[0]?.[0];
if (!s) return "";
const c = await resolveMedia({
...resolveTelegramMediaRuntimeOptions({
cfg: i,
accountId: e.accountId,
token: e.token,
transport: e.transport
}),
ctx: {
message: { photo: [s] },
me: r.me,
getFile: (t) => e.api.getFile(s.file_id, t)
},
maxBytes: AVATAR_MAX_BYTES,
budget: n
});
return n.aborted ? void 0 : c?.path;
} catch {
return;
} finally {
n.removeEventListener("abort", abort);
}
};
n.add(o);
load().then((n) => {
if (e.abortSignal?.aborted) return;
t.delete(o);
t.set(o, {
path: n ?? s?.path,
expiresAt: Date.now() + AVATAR_TTL_MS
});
pruneMapToMaxSize(t, AVATAR_MAX_ENTRIES);
}).finally(() => n.delete(o));
return s?.path;
};
}
//#endregion
//#region extensions/telegram/src/forum-service-message.ts
const TELEGRAM_FORUM_SERVICE_FIELDS = [
"forum_topic_created",
"forum_topic_edited",
"forum_topic_closed",
"forum_topic_reopened",
"general_forum_topic_hidden",
"general_forum_topic_unhidden"
];
function isTelegramForumServiceMessage(e) {
if (!e || typeof e !== "object") return false;
const t = e;
return TELEGRAM_FORUM_SERVICE_FIELDS.some((e) => e in t && t[e] != null);
}
/** Returns true only for title-bearing forum-topic service updates. */
function isTelegramForumTopicTitleUpdate(e) {
if (!e || typeof e !== "object") return false;
return ["forum_topic_created" in e ? e.forum_topic_created : void 0, "forum_topic_edited" in e ? e.forum_topic_edited : void 0].some((e) => e != null && typeof e === "object" && "name" in e && typeof e.name === "string" && Boolean(e.name.trim()));
}
//#endregion
//#region extensions/telegram/src/sticker-vision.ts
const loadStickerVisionRuntime = createLazyRuntimeModule(() => import("./sticker-vision.runtime.js"));
async function resolveStickerVisionSupport(e) {
try {
return await (await loadStickerVisionRuntime()).resolveStickerVisionSupportRuntime(e);
} catch {
return false;
}
}
//#endregion
//#region extensions/telegram/src/bot-message-context.body.ts
const loadMediaUnderstandingRuntime = createLazyRuntimeModule(() => import("./plugin-sdk/media-runtime.js"));
async function resolveTelegramInboundBody(e) {
const { cfg: t, primaryCtx: n, msg: r, allMedia: i, isGroup: a, chatId: o, accountId: s, senderId: c, senderUsername: l, sessionKey: u, resolvedThreadId: d, threadSpec: f, routeAgentId: p, effectiveGroupAllow: m, effectiveDmAllow: h, groupConfig: g, topicConfig: _, providerMentionPatterns: v, requireMention: y, options: b, logger: x } = e;
const S = buildTelegramInboundOriginTarget(o, f);
const C = f.id;
const w = normalizeOptionalLowercaseString(n.me?.username);
const T = buildMentionRegexes(t, p, {
provider: "telegram",
conversationId: a ? buildTelegramGroupPeerId(o, f) : String(o),
providerPolicy: v
});
const E = getTelegramTextParts(r);
if (w && hasLeadingBotCommandAddressedToOtherBot(r, w)) {
logInboundDrop({
log: logVerbose,
channel: "telegram",
reason: "command addressed to another bot",
target: c ?? "unknown"
});
return null;
}
const D = a ? m : h;
const O = hasControlCommand(E.text, t, { botUsername: w });
const k = await resolveTelegramCommandIngressAuthorization({
accountId: s ?? "default",
cfg: t,
dmPolicy: "pairing",
isGroup: a,
chatId: o,
resolvedThreadId: d,
senderId: c,
effectiveDmAllow: h,
effectiveGroupAllow: m,
eventKind: "message",
allowTextCommands: true,
hasControlCommand: O,
modeWhenAccessGroupsOff: "allow",
includeDmAllowForGroupCommands: false
});
const A = k.authorized;
const j = resolveTelegramNativeCommandBody({
msg: r,
nativeCommandNames: e.nativeCommandNames,
botUsername: w
});
const M = b?.commandSource ?? (j !== void 0 ? "native" : A && O ? "text" : void 0);
const N = a ? buildTelegramGroupPeerId(o, f) : void 0;
const P = resolveTelegramPrimaryMedia(r);
const F = i.length > 0 ? i : P ? [{ kind: P.kind }] : [];
const I = i[0]?.stickerMetadata?.cachedDescription;
const ee = Boolean(r.sticker) && i.some((e) => e.kind === "sticker" && e.path);
const L = ee ? await resolveStickerVisionSupport({
cfg: t,
agentId: p
}) : false;
const R = Boolean(I) && !L;
let z;
if (R) {
const e = i[0]?.stickerMetadata?.emoji;
const t = i[0]?.stickerMetadata?.setName;
const n = [e, t ? `from "${t}"` : null].filter(Boolean).join(" ");
z = `[Sticker${n ? ` ${n}` : ""}] ${I}`;
}
const B = resolveTelegramNonTextBody(r);
const te = renderTelegramTextEntities(E.text, E.entities).trim();
const V = Boolean(te || B?.kind === "location");
let H = [te, B?.text].filter(Boolean).join("\n").trim();
if (!H) H = resolveTelegramRichMessagePlaceholder(r) ?? "";
if (!H && r.sticker && !ee && !z) H = r.sticker.emoji?.trim() || formatMediaPlaceholderText(F);
const U = r.chat.type === "private" && r.message_thread_id != null && isTelegramForumTopicTitleUpdate(r);
if (!H && F.length === 0 && !U) return null;
let ne = z ? [z, H].filter(Boolean).join("\n") : H;
const isAudioMedia = (e) => e.kind === "audio" || e.contentType?.startsWith("audio/") === true;
const W = i.filter((e) => Boolean(e.path));
const G = i.findIndex((e) => Boolean(e.path) && isAudioMedia(e));
const K = (_?.disableAudioPreflight ?? g?.disableAudioPreflight) === true;
const re = !D.hasEntries || A;
let q;
if (G >= 0 && !V && (!a || y && T.length > 0 && !K && re)) try {
const { transcribeFirstAudio: e } = await loadMediaUnderstandingRuntime();
q = await e({
ctx: {
Provider: "telegram",
Surface: "telegram",
OriginatingChannel: "telegram",
OriginatingTo: S,
AccountId: s,
MessageSid: String(r.message_id),
ChatType: a ? "group" : "direct",
MessageThreadId: C,
media: W
},
cfg: t,
agentDir: void 0
});
} catch (e) {
logVerbose(`telegram: audio preflight transcription failed: ${String(e)}`);
}
const ie = q === void 0 ? void 0 : G;
if (!H && q) ne = formatAudioTranscriptForAgent(q);
const J = H || z || formatMediaPlaceholderText(F);
const ae = b?.bufferedMessages?.some((e) => e.contact) ? b.bufferedMessages : void 0;
const oe = ae ? joinTelegramTextParts(ae.filter((e) => !e.contact), "\n") : E;
const se = oe.entities.some((e) => e.type === "mention");
const ce = w ? ae ? ae.some((e) => hasBotMention(e, w, n.me?.id)) : hasBotMention(r, w, n.me?.id) : false;
const le = ae || !r.contact ? oe.text : "";
const ue = resolveGroupThreadMentionFacts({
cfg: t,
channel: "telegram",
peerId: a ? String(o) : resolveTelegramDirectPeerId({
chatId: o,
senderId: c
}),
text: [le, q].filter(Boolean).join("\n"),
sessionKey: e.sessionKey,
acpBinding: e.acpBinding
});
const de = Boolean(ue?.mentionedAgentIds.length) || matchesMentionWithExplicit({
text: le,
mentionRegexes: T,
explicit: {
hasAnyMention: se,
isExplicitlyMentioned: ce,
canResolveExplicit: Boolean(w)
},
transcript: q
});
const Y = b?.forceWasMentioned === true || M === "native" && A || de;
if (a && (k.shouldBlockControlCommand || M === "native" && !A)) {
logInboundDrop({
log: logVerbose,
channel: "telegram",
reason: "control command (unauthorized)",
target: c ?? "unknown"
});
return null;
}
const fe = n.me?.id;
const pe = r.reply_to_message?.from?.id;
const X = fe != null && pe === fe;
const { implicitMentionKinds: Z } = resolveBotThreadMentionPolicy({
isBotOwnedThread: e.isBotOwnedThread === true,
requireMentionInBotThreads: e.requireMentionInBotThreads,
requireMention: Boolean(y),
implicitMentionKinds: implicitMentionKindWhen("reply_to_bot", X && !isTelegramForumServiceMessage(r.reply_to_message))
});
const me = Boolean(ue) || Boolean(w) || T.length > 0;
const he = resolveInboundMentionDecision({
facts: {
canDetectMention: me,
wasMentioned: Y,
hasAnyMention: se,
implicitMentionKinds: a ? Z : []
},
policy: {
isGroup: a,
requireMention: Boolean(y),
allowTextCommands: true,
hasControlCommand: O,
commandAuthorized: A
}
});
const Q = he.effectiveWasMentioned;
const ge = classifyChannelInboundEvent({
conversation: { kind: a ? "group" : "direct" },
unmentionedGroupPolicy: resolveUnmentionedGroupInboundPolicy({
cfg: t,
agentId: p
}),
wasMentioned: Q,
hasControlCommand: O,
hasAbortRequest: isAbortRequestText(H, { botUsername: w }),
commandSource: M
});
if (a && y && me && he.shouldSkip) {
x.info({
chatId: o,
reason: "no-mention"
}, "skipping group message");
if (u && resolveTelegramGroupIngestEnabled({
cfg: t,
chatId: o,
accountId: s,
topicConfig: _
})) fireAndForgetHook(triggerInternalHook(createInternalHookEvent("message", "received", u, toInternalMessageReceivedContext({
from: `telegram:group:${N ?? o}`,
to: S,
content: J,
timestamp: r.date ? r.date * 1e3 : void 0,
channelId: "telegram",
accountId: s,
conversationId: S,
messageId: typeof r.message_id === "number" ? String(r.message_id) : void 0,
senderId: c || void 0,
senderName: buildSenderName(r),
senderUsername: l || void 0,
provider: "telegram",
surface: "telegram",
threadId: d,
originatingChannel: "telegram",
originatingTo: S,
isGroup: true,
groupId: `telegram:${o}`,
media: W.map(({ path: e, contentType: t, kind: n, sourceMessageId: i }) => ({
path: e,
contentType: t,
kind: n,
messageId: i ?? String(r.message_id)
}))
}))), "telegram: mention-skip message hook failed");
return null;
}
return {
originatingTo: S,
bodyText: ne,
rawBody: H,
historyKey: N,
commandAuthorized: A,
effectiveWasMentioned: Q,
inboundEventKind: U ? "room_event" : ge,
groupThread: ue,
mentionFacts: {
canDetectMention: me,
wasMentioned: Q,
explicitlyMentionedBot: ce,
mentionSource: ce ? "explicit_bot" : de ? "mention_pattern" : Z && Z.length > 0 ? "implicit_thread" : he.shouldBypassMention ? "command_bypass" : void 0,
implicitMentionKinds: Z,
effectiveWasMentioned: Q,
requireMention: Boolean(y)
},
canDetectMention: me,
shouldBypassMention: he.shouldBypassMention,
commandSource: M,
nativeCommandBody: j,
...ie !== void 0 ? { audioTranscribedMediaIndex: ie } : {},
stickerCacheHit: R,
locationData: B?.kind === "location" ? B.location : void 0
};
}
//#endregion
//#region extensions/telegram/src/prompt-media-path.ts
function resolveTelegramInboundMediaUri(e) {
if (!e || e === "." || e === ".." || e.includes("/") || e.includes("\\") || e.includes("\0")) return;
return `media://inbound/${encodeURIComponent(e)}`;
}
function resolveTelegramPromptMediaPath(e) {
const t = /^media:\/\/inbound\/([^/\\]+)$/i.exec(e);
if (t?.[1]) try {
return resolveTelegramInboundMediaUri(decodeURIComponent(t[1]));
} catch {
return;
}
const n = e.replace(/\\/g, "/");
if (!n.includes("/media/inbound/")) return;
return resolveTelegramInboundMediaUri(path.posix.basename(n));
}
//#endregion
//#region extensions/telegram/src/bot-message-context.session.ts
async function loadTelegramMessageContextSessionRuntime(e) {
return e ?? import("./bot-message-context.session.runtime.js");
}
function replyTargetToChainEntry(e, t) {
const { forwardedFrom: n } = e;
return {
...e.id ? { messageId: e.id } : {},
sender: e.sender,
...e.senderId ? { senderId: e.senderId } : {},
...e.senderUsername ? { senderUsername: e.senderUsername } : {},
...e.body ? { body: e.body } : {},
...e.mediaType ? {
mediaKind: e.mediaType,
mediaType: e.mediaType
} : {},
...t?.path ? {
mediaPath: t.path,
mediaKind: t.kind,
...t.contentType ? { mediaType: t.contentType } : {}
} : {},
...e.kind === "quote" ? { isQuote: true } : {},
...n?.from ? { forwardedFrom: n.from } : {},
...n?.fromId ? { forwardedFromId: n.fromId } : {},
...n?.fromUsername ? { forwardedFromUsername: n.fromUsername } : {},
...n?.date ? { forwardedDate: n.date * 1e3 } : {}
};
}
function formatTelegramForwardedMessageBody(e) {
const t = timestampMsToIsoString(e.forwardedDate);
return [e.forwardedFrom ? `[Forwarded from ${e.forwardedFrom}${t ? ` at ${t}` : ""}]` : void 0, e.body].filter(Boolean).join("\n");
}
function formatReplyChainEntry(e, t) {
const n = e.mediaPath ? resolveTelegramPromptMediaPath(e.mediaPath) : void 0;
const r = [
`${t + 1}. ${e.sender ?? "unknown sender"}`,
e.messageId ? `id:${e.messageId}` : void 0,
e.replyToId ? `reply_to:${e.replyToId}` : void 0,
e.timestamp ? timestampMsToIsoString(e.timestamp) : void 0
].filter(Boolean);
const i = [
formatTelegramForwardedMessageBody({
body: e.isQuote && e.body ? `"${e.body}"` : e.body ?? "",
forwardedFrom: e.forwardedFrom,
forwardedDate: e.forwardedDate
}),
e.mediaKind || e.mediaType ? formatMediaPlaceholderText([resolveReplyChainMediaType(e)]) : void 0,
n ? `[media_path:${n}]` : void 0,
e.mediaRef ? `[media_ref:${e.mediaRef}]` : void 0
].filter(Boolean);
return `[${r.join(" ")}]\n${i.join("\n")}`;
}
function resolveReplyChainMediaType(e) {
const t = e.mediaType;
const n = isTelegramMediaKind(t) ? t : void 0;
const r = e.mediaKind || n;
return {
...r ? { kind: r } : {},
...t && !n ? { contentType: t } : {}
};
}
async function buildTelegramInboundContextPayload(e) {
const { cfg: t, primaryCtx: n, msg: r, allMedia: i, replyMedia: a, replyChain: o, promptContext: s, isGroup: c, isForum: l, chatId: u, senderId: d, senderUsername: f, resolvedThreadId: p, dmThreadId: m, threadSpec: h, route: g, historyLimit: _, dmHistoryLimit: v, groupConfig: y, topicConfig: b, groupRequireMention: x, options: S, dmAllowFrom: C, effectiveGroupAllow: w, topicName: T, sessionRuntime: E } = e;
const { rawBody: D, bodyText: O, historyKey: k = "", effectiveWasMentioned: A, inboundEventKind: j, mentionFacts: M, groupThread: N, commandSource: P, nativeCommandBody: F, stickerCacheHit: I, audioTranscribedMediaIndex: ee, commandAuthorized: L, locationData: R, originatingTo: z } = e.bodyResult;
const B = r.date ? r.date * 1e3 : void 0;
const te = describeReplyTarget(r);
const V = S?.bufferedMessages ?? [];
const H = V.length > 1 && S?.ingressBuffer !== "text-batch";
const U = H ? null : normalizeForwardedContext(r);
const ne = resolveChannelContextVisibilityMode({
cfg: t,
channel: "telegram",
accountId: g.accountId
});
const shouldIncludeGroupSupplementalContext = (e, t) => {
if (!c) return true;
const n = w?.hasEntries ? isSenderIdAllowed(w, t, true) : true;
return evaluateSupplementalContextVisibility({
mode: ne,
kind: e,
senderAllowed: n
}).include;
};
const resolveVisibleForwardOrigin = (e) => e && shouldIncludeGroupSupplementalContext("forwarded", e.fromId) ? e : void 0;
const resolveVisibleReplyTarget = (e) => {
if (!e || !shouldIncludeGroupSupplementalContext("quote", e.senderId)) return null;
return {
...e,
forwardedFrom: resolveVisibleForwardOrigin(e.forwardedFrom)
};
};
const W = resolveVisibleForwardOrigin(U);
const G = resolveVisibleReplyTarget(te);
const K = G ? replyTargetToChainEntry(G, o.length === 0 ? a[0] : void 0) : void 0;
const re = o.length > 0 ? o : K ? [K] : [];
const q = /* @__PURE__ */ new Set();
const ie = [];
const appendReplyChainEntry = (e) => {
if (!e || ie.length >= 4) return;
if (e.messageId !== void 0) {
if (q.has(e.messageId)) return;
q.add(e.messageId);
}
ie.push(e);
};
for (let e = V.length - 1; e >= 1 && ie.length < 4; e -= 1) {
const t = V[e];
if (!t) continue;
const n = resolveVisibleReplyTarget(describeReplyTarget(t));
appendReplyChainEntry(n ? replyTargetToChainEntry(n) : void 0);
}
for (const e of re) {
if (ie.length >= 4) break;
appendReplyChainEntry(e);
}
const J = ie.flatMap((e) => {
const t = e.messageId === K?.messageId ? K : void 0;
const n = {
...e,
...t,
...e.mediaPath ? {
mediaKind: e.mediaKind,
mediaType: e.mediaType
} : {},
sender: e.sender,
senderId: e.senderId,
senderUsername: e.senderUsername
};
if (!shouldIncludeGroupSupplementalContext("quote", n.senderId)) return [];
if (!(n.forwardedFrom && shouldIncludeGroupSupplementalContext("forwarded", n.forwardedFromId))) {
delete n.forwardedFrom;
delete n.forwardedFromId;
delete n.forwardedFromUsername;
delete n.forwardedDate;
}
return [n];
});
const ae = H ? V.flatMap((e) => {
const t = resolveTelegramPrimaryMedia(e);
const n = getTelegramTextParts(e);
const r = renderTelegramTextEntities(n.text, n.entities) || formatMediaPlaceholderText(t ? [{ kind: t.kind }] : []);
if (!r) return [];
const i = resolveVisibleForwardOrigin(normalizeForwardedContext(e));
return [formatTelegramForwardedMessageBody({
body: r,
forwardedFrom: i?.from,
forwardedDate: i?.date ? i.date * 1e3 : void 0
})];
}) : void 0;
const oe = ae?.length ? ae.join("\n") : formatTelegramForwardedMessageBody({
body: O,
forwardedFrom: W?.from,
forwardedDate: W?.date ? W.date * 1e3 : void 0
});
const se = i.flatMap((e) => e.unavailable ? [e.unavailable] : []);
const ce = i.length > 1 ? `${se.length} of ${i.length} attachments could not be downloaded` : se[0]?.reason === "oversize" ? `file exceeds ${se[0].limit} limit` : "download failed";
const appendMediaUnavailableNotice = (e) => se.length > 0 ? formatInboundMediaUnavailableText({
body: e,
notice: `[media unavailable: ${ce}]`
}) : e;
const le = J.length > 0 ? `\n\n[Reply chain - nearest first]\n${J.map(formatReplyChainEntry).join("\n")}\n[/Reply chain]` : "";
const ue = buildSenderName(r);
const de = c ? buildGroupLabel(r, u, p) : buildSenderLabel(r, d || u);
const Y = await loadTelegramMessageContextSessionRuntime(E);
const fe = Y.resolveStorePath(t.session?.store, { agentId: g.agentId });
const pe = resolveEnvelopeFormatOptions(t);
const X = await Y.readSessionUpdatedAtAsync({
storePath: fe,
sessionKey: g.sessionKey
});
const Z = c && k ? Y.resolveAmbientTranscriptWatermarkKey({
channel: "telegram",
accountId: g.accountId,
conversationId: String(u),
...p !== void 0 ? { threadId: p } : {}
}) : void 0;
const me = Z ? await Y.readAmbientTranscriptWatermarkAsync({
storePath: fe,
sessionKey: g.sessionKey,
key: Z
}) : void 0;
const he = !c && X !== void 0 && m == null && J.length === 0 && !G ? s.filter((e) => !isTelegramChatWindowPromptContext(e)) : s;
const Q = formatInboundEnvelope({
channel: "Telegram",
from: de,
timestamp: B,
body: `${appendMediaUnavailableNotice(oe)}${le}`,
chatType: c ? "group" : "direct",
sender: {
name: ue,
username: f || void 0,
id: d || void 0
},
previousTimestamp: X,
envelope: pe
});
const ge = normalizeCommandBody(F ?? D, {
botUsername: normalizeOptionalLowercaseString(n.me?.username),
preserveArguments: true
});
const _e = c ? "group" : "direct";
const ve = c ? selectTelegramGroupPromptContext({
promptContext: he,
historyLimit: _,
ambientWatermark: me,
includeBeforeSelf: j === "room_event"
}) : he;
const ye = telegramPromptContextHistory(ve);
const { skillFilter: be, groupSystemPrompt: xe } = resolveTelegramGroupPromptSettings({
groupConfig: y,
topicConfig: b
});
const $ = J[0];
const toInboundMedia = (e, t) => ({
...e.path ? {
path: e.path,
url: e.path
} : {},
contentType: e.contentType,
...e.fileName ? { fileName: e.fileName } : {},
kind: e.kind,
transcribed: t !== void 0 && ee === t
});
const Se = i.map(toInboundMedia);
const toReplyChainMediaFact = (e) => e.mediaPath || e.mediaKind || e.mediaType ? {
...e.mediaPath ? {
path: e.mediaPath,
url: e.mediaPath
} : {},
...resolveReplyChainMediaType(e)
} : void 0;
const Ce = J.length > 0 ? J.flatMap((e) => {
const t = toReplyChainMediaFact(e);
return t ? [t] : [];
}) : G ? a.length > 0 ? a.map((e) => toInboundMedia(e)) : G.mediaType ? [{ kind: G.mediaType }] : [] : [];
const we = ($ ? toReplyChainMediaFact($) : void 0) ?? (G?.mediaType ? { kind: G.mediaType } : void 0);
const Te = $?.body ?? G?.body ?? (we ? formatMediaPlaceholderText([we]) : void 0);
const Ee = c ? buildTelegramGroupFrom(u, h) : `telegram:${u}`;
const De = R ? toLocationContext(R) : void 0;
const Oe = n.update;
const ke = Oe ? [
"edited_message",
"message",
"edited_channel_post",
"channel_post"
].find((e) => e in Oe) : void 0;
const Ae = c && k && _ > 0 && ye.length > 0 ? ye : void 0;
const je = S?.messageIdOverride ?? String(r.message_id);
const Me = Object.freeze({
agentId: g.agentId,
sessionKey: g.sessionKey,
messageId: je,
inboundEventKind: j
});
const Ne = S?.channelIngressResolvers ? await Promise.all(S.channelIngressResolvers.map((e) => e(Me))) : void 0;
const Pe = await Y.buildChannelInboundEventContext({
channel: "telegram",
channelIngress: Ne,
resolveSupplementalMedia: true,
accountId: g.accountId,
messageId: je,
timestamp: B,
from: Ee,
sender: {
...d ? { id: d } : {},
name: ue,
username: f || void 0,
isBot: r.from?.is_bot
},
conversation: {
avatar: e.conversationAvatar,
kind: _e,
id: String(u),
routePeer: {
kind: _e,
id: c ? buildTelegramConversationId({
chatId: u,
thread: h
}) : resolveTelegramDirectPeerId({
chatId: u,
senderId: d
})
},
label: de,
parentId: buildTelegramParentPeer({
isGroup: c,
resolvedThreadId: h.id,
chatId: u
})?.id,
threadId: h.id != null ? String(h.id) : void 0
},
route: {
...g,
routeSessionKey: g.sessionKey,
mainSessionKey: g.mainSessionKey
},
reply: {
to: z,
replyToId: $?.messageId ?? G?.id,
messageThreadId: h.id
},
message: {
inboundEventKind: j,
body: Q,
rawBody: D,
bodyForAgent: appendMediaUnavailableNotice(H ? oe : O),
commandBody: ge,
inboundHistory: Ae,
sourceModality: r.voice ? "voice" : void 0
},
sessionTranscript: {
chatWindow: true,
historyLimit: c ? _ : v,
beforeTimestampMs: S?.receivedAtMs ?? B,
minTimestampMs: S?.promptContextMinTimestampMs,
senderLabels: {
assistant: "OpenClaw",
user: "User"
}
},
access: {
commands: { authorized: L },
mentions: M
},
command: P === "native" || P === "text" ? {
kind: P === "native" ? "native" : "text-slash",
authorized: L,
body: ge
} : void 0,
media: Se,
supplemental: {
quote: $ || G ? {
id: $?.messageId ?? G?.id,
body: Te,
sender: $?.sender ?? G?.sender,
senderAllowed: true,
isQuote: $?.isQuote ?? (G?.kind === "quote" ? true : void 0),
media: Ce
} : void 0,
forwarded: W ? {
from: W.from,
fromType: W.fromType,
fromId: W.fromId,
date: W.date ? W.date * 1e3 : void 0,
senderAllowed: true
} : void 0,
groupSystemPrompt: c || !c && y ? xe : void 0,
channelStructuredContext: ve.length > 0 ? ve : void 0
},
contextVisibility: ne,
extra: {
GroupThread: N,
BotUsername: n.me?.username ?? void 0,
AmbientTranscriptWatermarkKey: Z,
AmbientTranscriptBody: S?.ambientTranscriptBody,
AmbientTranscriptMessageId: Z ? S?.messageIdOverride ?? String(r.message_id) : void 0,
AmbientTranscriptTimestampMs: Z ? B : void 0,
AmbientTranscriptPreviousMessageId: me?.messageId,
AmbientTranscriptPreviousTimestampMs: me?.timestampMs,
GroupSubject: c ? r.chat.title ?? void 0 : void 0,
GroupRequireMention: c ? x : void 0,
ReplyChain: J.length > 0 ? J : void 0,
ReplyToIsExternal: G?.source === "external_reply" ? true : void 0,
ReplyToQuoteText: G?.quoteText,
ReplyToQuotePosition: G?.quotePosition,
ReplyToQuoteEntities: G?.quoteEntities,
ReplyToQuoteSourceText: G?.quoteSourceText,
ReplyToQuoteSourceEntities: G?.quoteSourceEntities,
ReplyToForwardedFrom: G?.forwardedFrom?.from,
ReplyToForwardedFromType: G?.forwardedFrom?.fromType,
ReplyToForwardedFromId: G?.forwardedFrom?.fromId,
ReplyToForwardedFromUsername: G?.forwardedFrom?.fromUsername,
ReplyToForwardedFromTitle: G?.forwardedFrom?.fromTitle,
ReplyToForwardedDate: G?.forwardedFrom?.date ? G.forwardedFrom.date * 1e3 : void 0,
ForwardedFromUsername: W?.fromUsername,
ForwardedFromTitle: W?.fromTitle,
ForwardedFromSignature: W?.fromSignature,
ForwardedFromChatType: W?.fromChatType,
ForwardedFromMessageId: W?.fromMessageId,
WasMentioned: c ? A : void 0,
Sticker: i[0]?.stickerMetadata,
StickerMediaIncluded: i[0]?.stickerMetadata ? Se.length > 0 : void 0,
SkipStickerMediaUnderstanding: I ? true : void 0,
...De,
ProviderUpdateId: typeof Oe?.update_id === "number" ? String(Oe.update_id) : void 0,
ProviderUpdateKind: ke,
ProviderMessageTimestamp: n.message?.date ? n.message.date * 1e3 : void 0,
ProviderEditTimestamp: n.message?.edit_date ? n.message.edit_date * 1e3 : void 0,
LocationLivePeriodSeconds: n.message?.location?.live_period,
IsForum: l,
TopicName: l && T ? T : void 0,
ThreadLabel: !c && h.scope === "dm" ? T : void 0
}
});
const Fe = !c ? Y.resolvePinnedMainDmOwnerFromAllowlist({
dmScope: t.session?.dmScope,
allowFrom: C,
normalizeEntry: (e) => normalizeAllowFrom([e]).entries[0]
}) : null;
const Ie = Y.resolveInboundLastRouteSessionKey({
route: g,
sessionKey: g.sessionKey
});
const Le = c && g.matchedBy !== "binding.channel";
const Re = c ? Le && p != null ? String(p) : void 0 : m != null ? String(m) : void 0;
const ze = !c || Re != null ? {
sessionKey: Ie,
channel: "telegram",
to: z,
accountId: g.accountId,
threadId: Re,
mainDmOwnerPin: !c && Ie === g.mainSessionKey && Fe && d ? {
ownerRecipient: Fe,
senderRecipient: d,
onSkip: (e) => {
logVerbose(`telegram: skip main-session last route for ${e.senderRecipient} (pinned owner ${e.ownerRecipient})`);
}
} : void 0
} : void 0;
return {
ctxPayload: Pe,
skillFilter: be,
turn: {
storePath: fe,
recordInboundSession: Y.recordInboundSession,
record: {
updateLastRoute: ze,
onRecordError: (e) => {
logVerbose(`telegram: failed updating session meta: ${String(e)}`);
}
}
}
};
}
//#endregion
//#region extensions/telegram/src/dm-access.ts
function resolveTelegramSenderIdentity(e, t) {
const n = e.from;
const r = n?.id != null ? String(n.id) : null;
return {
username: n?.username ?? "",
userId: r,
candidateId: r ?? String(t),
firstName: n?.first_name,
lastName: n?.last_name
};
}
async function decideTelegramDmAccess(e, t) {
return (await createTelegramIngressResolver({ accountId: e.accountId }).message({
subject: { stableId: t },
conversation: {
kind: "direct",
id: t
},
dmPolicy: e.dmPolicy,
groupPolicy: "disabled",
allowFrom: telegramAllowEntries(e.effectiveDmAllow)
})).ingress;
}
async function isTelegramDmAccessAllowed(e) {
if (e.dmPolicy === "disabled") return false;
return (await decideTelegramDmAccess(e, resolveTelegramSenderIdentity(e.msg, e.chatId).candidateId)).decision === "allow";
}
async function enforceTelegramDmAccess(e) {
const { isGroup: t, dmPolicy: n, msg: r, chatId: i, accountId: a, bot: o, logger: s, upsertPairingRequest: c } = e;
if (t) return true;
if (n === "disabled") return false;
const l = resolveTelegramSenderIdentity(r, i);
const u = await decideTelegramDmAccess(e, l.candidateId);
if (u.decision === "allow") return true;
if (n === "open") {
logVerbose(`Blocked unauthorized telegram sender ${l.candidateId} (dmPolicy=open)`);
return false;
}
if (u.decision === "pairing") {
try {
await createChannelPairingChallengeIssuer({
channel: "telegram",
accountId: a,
upsertPairingRequest: async ({ id: e, meta: t }) => await (c ?? upsertChannelPairingRequest)({
channel: "telegram",
id: e,
accountId: a,
meta: t
})
})({
senderId: l.candidateId,
senderIdLine: `Your Telegram user id: ${l.candidateId}`,
meta: {
username: l.username || void 0,
firstName: l.firstName,
lastName: l.lastName
},
onCreated: () => {
s.info({
chatId: String(i),
senderUserId: l.userId ?? void 0,
username: l.username || void 0,
firstName: l.firstName,
lastName: l.lastName
}, "telegram pairing request");
},
sendPairingReply: async (e) => {
const t = renderTelegramHtmlText(e);
await withTelegramApiErrorLogging({
operation: "sendMessage",
fn: () => o.api.sendMessage(i, t, { parse_mode: "HTML" })
});
},
onReplyError: (e) => {
logVerbose(`telegram pairing reply failed for chat ${i}: ${String(e)}`);
}
});
} catch (e) {
logVerbose(`telegram pairing reply failed for chat ${i}: ${String(e)}`);
}
return false;
}
logVerbose(`Blocked unauthorized telegram sender ${l.candidateId} (dmPolicy=${n})`);
return false;
}
//#endregion
//#region extensions/telegram/src/forum-topic-metadata.ts
async function resolveTelegramForumTopicMetadata(e) {
const { msg: t, threadId: n, scope: r } = e;
const i = t.chat.id;
const recordCreation = (e, t) => recordTopicCreation(i, n, {
name: e.name,
creatorUserId: t,
iconColor: e.icon_color,
iconCustomEmojiId: e.icon_custom_emoji_id
}, r);
const a = t.forum_topic_created;
if (a?.name) await recordCreation(a, t.from?.id);
const o = t.forum_topic_edited;
const s = o?.name ? {
name: o.name,
iconCustomEmojiId: o.icon_custom_emoji_id
} : t.forum_topic_closed || t.forum_topic_reopened ? { closed: Boolean(t.forum_topic_closed) } : void 0;
if (s) await updateTopicName(i, n, s, r);
let c = await getTopicName(i, n, r);
let l = await getTopicCreatorUserId(i, n, r);
const u = t.reply_to_message;
const d = u?.forum_topic_created;
if (u && d?.name) {
const e = u.message_id === n ? u.from?.id : void 0;
if (!c || l === void 0 && e !== void 0) {
await recordCreation(d, e);
c ??= d.name;
l ??= e;
}
}
return {
topicName: c,
creatorUserId: l
};
}
//#endregion
//#region extensions/telegram/src/bot-message-context.ts
const loadTelegramMessageContextRuntime = createLazyRuntimeModule(() => import("./bot-message-context.runtime.js"));
const buildTelegramMessageContext = async ({ nativeCommandNames: e, primaryCtx: t, resolveDirectAvatar: n, allMedia: r, replyMedia: i = [], replyChain: a = [], promptContext: o = [], storeAllowFrom: s, options: c, bot: l, cfg: u, account: d, ownerAgentId: f, historyLimit: p, dmHistoryLimit: m, dmPolicy: h, allowFrom: g, groupAllowFrom: _, ackReactionScope: v, logger: y, resolveGroupActivation: b, resolveGroupRequireMention: x, resolveTelegramGroupConfig: S, runtime: C, sessionRuntime: w, upsertPairingRequest: T, sendChatActionHandler: E }) => {
const D = t.message;
const O = D.chat.id;
const k = D.chat.type === "group" || D.chat.type === "supergroup";
const A = D.from?.id ? String(D.from.id) : "";
const j = D.chat.is_direct_messages === true ? false : await resolveTelegramForumFlag({
chatId: O,
chatType: D.chat.type,
isGroup: k,
isForum: extractTelegramForumFlag(D.chat),
isTopicMessage: D.is_topic_message,
getChat: (e) => l.api.getChat(e)
});
const M = c?.threadSpec ?? resolveTelegramMessageThreadSpec(D, j);
const N = M.scope === "forum" || M.scope === "direct-messages" ? M.id : void 0;
const P = M.id;
const F = M.scope === "dm" ? M.id : void 0;
const resolveTopicMetadata = async (e, t = false) => {
let n = (await loadTelegramMessageContextSessionRuntime(w)).resolveStorePath(u.session?.store, { agentId: f?.trim() || resolveTelegramAccountOwnerAgentId({
cfg: u,
accountId: d.accountId
}) });
if (t) n = resolveTelegramDirectTopicNameCacheScope(n, d.accountId);
return resolveTelegramForumTopicMetadata({
msg: D,
threadId: e,
scope: n
});
};
let I;
let ee = false;
if (j && N != null) {
const e = await resolveTopicMetadata(N);
I = e.topicName;
ee = t.me?.id !== void 0 && e.creatorUserId === t.me.id;
}
const { groupConfig: L, topicConfig: R } = S(O, N ?? F, u);
const z = !k ? L : void 0;
const B = k ? L : void 0;
const te = resolveTelegramEffectiveDmPolicy({
isGroup: k,
groupConfig: L,
dmPolicy: h
});
const V = await resolveTelegramConversationRoute({
cfg: u,
accountId: d.accountId,
chatId: O,
isGroup: k,
threadSpec: M,
senderId: A,
topicAgentId: R?.agentId
});
const { bindingMode: H } = V;
let { route: U } = V;
const ne = normalizeAccountId(U.accountId) !== normalizeAccountId(resolveDefaultTelegramAccountId(u)) && U.matchedBy === "default";
const W = k && Boolean(R?.agentId?.trim());
if (ne && k && !W) {
logInboundDrop({
log: logVerbose,
channel: "telegram",
reason: "non-default account requires explicit binding",
target: U.accountId
});
return null;
}
const G = firstDefined(R?.allowFrom, L?.allowFrom);
const K = await resolveTelegramDmAllow({
cfg: u,
groupAllowOverride: G,
allowFrom: g,
accountId: d.accountId,
senderId: A,
storeAllowFrom: s,
dmPolicy: te
});
const re = await expandTelegramAllowFromWithAccessGroups({
cfg: u,
allowFrom: G ?? _,
accountId: d.accountId,
senderId: A
});
const q = normalizeAllowFrom(re);
const ie = G !== void 0;
const J = D.from?.username ?? "";
const ae = await resolveTelegramNativeCommandAdmission({
msg: D,
nativeCommandNames: e,
botUsername: t.me?.username,
cfg: u,
accountId: d.accountId,
dmPolicy: te,
isGroup: k,
chatId: O,
senderId: A
});
const oe = evaluateTelegramGroupBaseAccess({
groupConfig: L,
topicConfig: R,
hasGroupAllowOverride: ie,
effectiveGroupAllow: q,
senderId: A,
enforceAllowOverride: true,
requireSenderForAllowOverride: false
});
if (!oe.allowed) {
logVerbose({
"group-disabled": `Blocked telegram group ${O} (group disabled)`,
"topic-disabled": `Blocked telegram topic ${O} (${N ?? "unknown"}) (topic disabled)`,
"group-override-unauthorized": k ? `Blocked telegram group sender ${A || "unknown"} (group allowFrom override)` : `Blocked telegram DM sender ${A || "unknown"} (DM allowFrom override)`
}[oe.reason]);
return null;
}
if (!k && z?.requireTopic === true && F == null) {
logVerbose(`Blocked telegram DM ${O}: requireTopic=true but no topic present`);
return null;
}
const sendChatAction = async (e) => {
if (M.scope === "direct-messages") return;
await withTelegramApiErrorLogging({
operation: "sendChatAction",
fn: () => E.sendChatAction(O, e, buildTypingThreadParams(P))
});
};
const sendTyping = () => sendChatAction("typing");
const sendRecordVoice = async () => {
try {
await sendChatAction("record_voice");
} catch (e) {
logVerbose(`telegram record_voice cue failed for chat ${O}: ${String(e)}`);
}
};
if (!ae && !await enforceTelegramDmAccess({
isGroup: k,
dmPolicy: te,
msg: D,
chatId: O,
effectiveDmAllow: K.effectiveAllow,
accountId: d.accountId,
bot: l,
logger: y,
upsertPairingRequest: T
})) return null;
if (!k && M.scope === "dm" && F != null && (D.is_topic_message === true || isTelegramForumTopicTitleUpdate(D))) I = (await resolveTopicMetadata(F, true)).topicName;
U = applyTelegramTargetSession({
cfg: u,
route: U,
bindingMode: H,
chatId: O,
isGroup: k,
senderId: A,
dmThreadId: F,
botHasTopicsEnabled: M.scope === "dm" && (D.is_topic_message === true || isTelegramForumTopicTitleUpdate(D)) || resolveTelegramBotHasTopicsEnabled(t.me)
});
const { sessionKey: se } = U;
const ce = await b({
sessionKey: se,
agentId: U.agentId,
cfg: u
});
const le = x(O, u);
const ue = firstDefined(R?.requireMention, ce, B?.requireMention, le);
const de = firstDefined(R?.requireMentionInBotThreads, B?.requireMentionInBotThreads);
const { requireMention: Y } = resolveBotThreadMentionPolicy({
isBotOwnedThread: ee,
requireMentionInBotThreads: de,
requireMention: Boolean(ue)
});
const fe = k && H.kind === "plugin-owned-runtime" ? false : Y;
(C?.recordChannelActivity ?? (await loadTelegramMessageContextRuntime()).recordChannelActivity)({
channel: "telegram",
accountId: d.accountId,
direction: "inbound"
});
const pe = {
cfg: u,
primaryCtx: t,
msg: D,
allMedia: r,
isGroup: k,
chatId: O,
senderId: A,
senderUsername: J,
resolvedThreadId: N,
threadSpec: M,
effectiveGroupAllow: q,
groupConfig: L,
topicConfig: R,
options: c
};
const X = await resolveTelegramInboundBody({
...pe,
nativeCommandNames: e,
accountId: d.accountId,
routeAgentId: U.agentId,
sessionKey: se,
acpBinding: H.kind === "configured",
effectiveDmAllow: K.effectiveAllow,
providerMentionPatterns: resolveTelegramAccountConfig(u, d.accountId)?.mentionPatterns,
requireMention: fe,
isBotOwnedThread: ee,
requireMentionInBotThreads: de,
logger: y
});
if (!X) return null;
if (H.kind === "configured") {
const e = await (C?.ensureConfiguredBindingRouteReady ?? (await loadTelegramMessageContextRuntime()).ensureConfiguredBindingRouteReady)({
cfg: u,
bindingResolution: H.binding
});
if (!e.ok) {
logVerbose(`telegram: configured ACP binding unavailable for ${H.binding.record.conversation.conversationId}: ${e.error}`);
logInboundDrop({
log: logVerbose,
channel: "telegram",
reason: "configured ACP binding unavailable",
target: H.binding.record.conversation.conversationId
});
return null;
}
}
const { ctxPayload: Z, skillFilter: me, turn: he } = await buildTelegramInboundContextPayload({
...pe,
conversationAvatar: n?.(t, u),
replyMedia: i,
replyChain: a,
promptContext: o,
isForum: j,
dmThreadId: F,
route: U,
bodyResult: X,
historyLimit: p,
dmHistoryLimit: m,
groupRequireMention: Y,
dmAllowFrom: K.allowFrom,
topicName: I,
sessionRuntime: w
});
const Q = resolveAckReaction(u, U.agentId, {
channel: "telegram",
accountId: d.accountId
});
const ge = Q ? resolveTelegramReactionEmoji(Q) : void 0;
const _e = Boolean(Q && shouldAckReaction({
scope: v,
inboundEventKind: Z.InboundEventKind,
isDirect: !k,
isGroup: k,
isMentionableGroup: k,
canDetectMention: X.canDetectMention,
effectiveWasMentioned: X.effectiveWasMentioned,
shouldBypassMention: X.shouldBypassMention
}));
const ve = u.messages?.statusReactions;
const ye = Z.InboundEventKind !== "room_event" && ve?.enabled === true && _e;
const be = ye ? resolveTelegramStatusReactionEmojis(Q) : null;
const xe = be ? buildTelegramStatusReactionVariants(be) : /* @__PURE__ */ new Map();
let $ = null;
const Se = ye && be && D.message_id ? (C?.createStatusReactionController ?? (await loadTelegramMessageContextRuntime()).createStatusReactionController)({
enabled: true,
adapter: { setReaction: async (e) => {
if (!$) $ = resolveTelegramAllowedReactions({
chat: D.chat,
chatId: O,
getChat: (e) => l.api.getChat(e)
}).then((e) => e ? new Set(e.flatMap((e) => e.type === "emoji" ? [e.emoji] : [])) : null).catch((e) => {
logVerbose(`telegram status-reaction available_reactions lookup failed for chat ${O}: ${String(e)}`);
return null;
});
const t = await $;
const n = resolveTelegramReactionVariant({
requestedEmoji: e,
variantsByRequestedEmoji: xe,
allowedEmojiReactions: t
});
if (!n) return;
await l.api.setMessageReaction(O, D.message_id, [{
type: "emoji",
emoji: n
}]);
} },
initialEmoji: Q,
emojis: be,
onError: (e) => {
logVerbose(`telegram status-reaction error for chat ${O}: ${String(e)}`);
}
}) : null;
const Ce = Se ? Promise.resolve(Se.setQueued()).then(() => true, () => false) : _e && D.message_id && ge ? withTelegramApiErrorLogging({
operation: "setMessageReaction",
fn: () => l.api.setMessageReaction(O, D.message_id, [{
type: "emoji",
emoji: ge
}])
}).then(() => true, (e) => {
logVerbose(`telegram react failed for chat ${O}: ${String(e)}`);
return false;
}) : null;
return {
cfg: u,
ctxPayload: Z,
turn: he,
primaryCtx: t,
msg: D,
chatId: O,
isGroup: k,
groupConfig: L,
topicConfig: R,
resolvedThreadId: N,
threadSpec: M,
replyThreadId: P,
isForum: j,
historyKey: X.historyKey ?? "",
historyLimit: p,
route: U,
skillFilter: me,
sendTyping,
sendRecordVoice,
sendChatActionHandler: E,
ackReactionPromise: Ce,
statusReactionController: Se,
accountId: d.accountId
};
};
//#endregion
//#region extensions/telegram/src/auto-topic-label-config.ts
const AUTO_TOPIC_LABEL_DEFAULT_PROMPT = "Generate a very short topic label (2-4 words, max 25 chars) for a chat conversation based on the supplied source message. No emoji. Use the same language as the message, in sentence case: capitalize only the first word and words that language always capitalizes. Be concise and descriptive. Return ONLY the topic name, nothing else.";
function resolveAutoTopicLabelConfig(e, t) {
const n = e ?? t;
if (n === void 0 || n === true) return {
enabled: true,
prompt: AUTO_TOPIC_LABEL_DEFAULT_PROMPT
};
if (n === false || n.enabled === false) return null;
return {
enabled: true,
prompt: n.prompt?.trim() || AUTO_TOPIC_LABEL_DEFAULT_PROMPT
};
}
//#endregion
//#region extensions/telegram/src/dm-history.ts
const DEFAULT_TELEGRAM_DM_HISTORY_LIMIT = 10;
function resolveTelegramDmHistoryLimit(e) {
const t = e.senderId === void 0 ? void 0 : String(e.senderId);
const n = t ? e.config.dms?.[t]?.historyLimit : void 0;
return resolvePromptHistoryLimit(n ?? e.config.dmHistoryLimit, DEFAULT_TELEGRAM_DM_HISTORY_LIMIT);
}
//#endregion
//#region extensions/telegram/src/bot-handlers.message-context.ts
function promptContextBoundaryOptions(e, t) {
const n = asFiniteNumber(e);
return {
...n === void 0 ? {} : { promptContextMinTimestampMs: n },
...t === void 0 ? {} : { promptContextAmbientWatermark: t }
};
}
function latestPromptContextMinTimestampMs(...e) {
const t = e.map(asFiniteNumber).filter((e) => e !== void 0);
return t.length > 0 ? Math.max(...t) : void 0;
}
const latestPromptContextAmbientWatermark = (...e) => e.findLast((e) => e !== void 0);
function buildSyntheticTextMessage(e) {
const t = {
...e.base,
...e.from ? { from: e.from } : {},
text: e.text,
...e.date != null ? { date: e.date } : {}
};
delete t.caption;
delete t.caption_entities;
if (e.entities?.length) t.entities = e.entities;
else delete t.entities;
return t;
}
const buildSyntheticContext = (e, t) => ({
message: t,
update: e.update,
me: e.me,
getFile: e.getFile.bind(e)
});
function formatTelegramAmbientTranscriptBody(e) {
const t = e.map((e) => {
const t = getTelegramTextParts(e).text.trim();
const n = resolveTelegramPrimaryMedia(e);
const r = t || formatMediaPlaceholderText(n ? [{ kind: n.kind }] : [{}]);
const i = [e.message_id ? `#${e.message_id}` : void 0, buildSenderName(e)].filter(Boolean).join(" ");
return i ? `${i}: ${r}` : r;
});
return t.length > 0 ? t.join("\n") : void 0;
}
function createTelegramMessageSessionRuntime({ accountId: e, resolveTelegramGroupConfig: t }) {
const n = getSessionEntryAsync;
const resolveTelegramSessionState = async (r) => {
const i = r.threadSpec.scope === "dm" ? r.threadSpec.id : void 0;
const { topicConfig: a } = t(r.chatId, r.threadSpec.id, r.runtimeCfg);
const { route: o, bindingMode: s } = await resolveTelegramConversationRoute({
...r,
cfg: r.runtimeCfg,
accountId: e,
topicAgentId: a?.agentId
});
const c = resolveTelegramTargetSession({
...r,
cfg: r.runtimeCfg,
route: o,
bindingMode: s,
dmThreadId: i
});
const l = resolveSessionStorePathCore(r.runtimeCfg.session?.store, { agentId: o.agentId });
const u = await n({
agentId: o.agentId,
storePath: l,
sessionKey: c
});
const d = await resolveStoredModelOverrideAsync({
sessionEntry: u,
loadSessionEntry: (e) => n({
agentId: o.agentId,
storePath: l,
sessionKey: e
}),
sessionKey: c,
defaultProvider: resolveDefaultModelForAgent({
cfg: r.runtimeCfg,
agentId: o.agentId
}).provider
});
const f = u?.modelProvider?.trim();
const p = u?.model?.trim();
const m = r.runtimeCfg.agents?.defaults?.model;
return {
agentId: o.agentId,
bindingMode: s,
sessionEntry: u,
sessionKey: c,
storePath: l,
model: d ? d.provider ? `${d.provider}/${d.model}` : d.model : f && p ? `${f}/${p}` : typeof m === "string" ? m : m?.primary
};
};
const resolvePromptContextAmbientWatermark = async (t) => {
if (!t.isGroup) return;
const n = resolveAmbientTranscriptWatermarkKey({
channel: "telegram",
accountId: e,
conversationId: String(t.chatId),
...t.resolvedThreadId !== void 0 ? { threadId: t.resolvedThreadId } : {}
});
return await readAmbientTranscriptWatermarkAsync({
storePath: t.storePath,
sessionKey: t.sessionKey,
key: n
});
};
return {
resolveTelegramSessionState,
resolvePromptContextAmbientWatermark
};
}
function createTelegramMessageContextRuntime({ cfg: e, accountId: t, ownerAgentId: n, opts: r, telegramCfg: i }) {
const a = createTelegramMessageCache({ scope: resolveTelegramMessageCacheScope(resolveSessionStorePathCore(e.session?.store, { agentId: n })) });
const resolvePromptSender = (e, t) => {
const n = t.me ?? r.botInfo;
if (n?.id != null && (e.senderId === String(n.id) || e.sourceMessage.sender_business_bot?.id === n.id)) return buildTelegramSelfSenderName(i.name, n);
if (e.senderId === "0" && e.sourceMessage.from?.is_bot === true) return e.sender;
return isTelegramSelfSenderName(e.sender) ? `${e.sender} (Telegram sender)` : e.sender;
};
const recordMessageForReplyChain = (e, n, r) => a.record({
accountId: t,
chatId: e.chat.id,
msg: e,
historyEligible: true,
...r !== void 0 ? { botUserId: r } : {},
...n ? { providerObservedThread: n } : {},
...n?.id != null ? { threadId: n.id } : {}
});
const recordMessageResolvedMedia = (e) => a.recordResolvedMedia({
accountId: t,
chatId: e.msg.chat.id,
messageId: String(e.msg.message_id),
media: e.media,
...e.botUserId !== void 0 ? { botUserId: e.botUserId } : {}
});
const recordReplyMessageResolvedMedia = async (e) => {
const n = {
accountId: t,
chatId: e.chatId,
messageId: e.messageId,
media: e.media,
...e.botUserId !== void 0 ? { botUserId: e.botUserId } : {}
};
if (await a.get(n)) await a.recordResolvedMedia(n);
};
const resolveCachedMessageThreadSpec = async (e) => {
const n = await a.get({
accountId: t,
chatId: e.chatId,
messageId: String(e.messageId)
});
const r = resolveProviderObservedTelegramThreadSpec(n);
return r ? {
threadSpec: r,
isTopicMessage: n?.sourceMessage?.is_topic_message === true
} : void 0;
};
const buildReplyChainForMessage = (e) => buildTelegramReplyChain({
cache: a,
accountId: t,
chatId: e.chat.id,
msg: e
});
const toReplyChainEntry = (e, t, n) => {
const { sourceMessage: r, resolvedMedia: i, promptContextProjectionMarker: a, threadBinding: o, ...s } = e;
const c = {
...s,
sender: resolvePromptSender(e, t)
};
if (!n?.path) return c;
const { mediaRef: l, ...u } = c;
return {
...u,
mediaPath: n.path,
mediaKind: n.kind,
...n.contentType ? { mediaType: n.contentType } : {}
};
};
const buildPromptContextForMessage = async (e, n, i, o, s, c, l, u) => {
const d = getTelegramTextParts(n).text.trim();
if (/^\/(?:new|reset)(?:@[A-Za-z0-9_]+)?(?:\s|$)/i.test(d) && !/^\/reset(?:@[A-Za-z0-9_]+)?\s+soft(?:\s|$)/i.test(d)) return [];
const f = n.chat.type === "group" || n.chat.type === "supergroup";
const p = resolvePromptHistoryLimit(s.historyLimit ?? o.messages?.groupChat?.historyLimit);
const m = resolveTelegramDmHistoryLimit({
config: s,
senderId: n.from?.id
});
if ((f ? p : m) === 0 && i.length === 0 && !u?.size) return [];
const h = typeof n.message_id === "number" ? String(n.message_id) : void 0;
const g = await a.get({
accountId: t,
chatId: n.chat.id,
messageId: h
});
const _ = c?.threadSpec?.id ?? (g?.threadId ? Number(g.threadId) : void 0);
const v = {
cache: a,
cfg: o,
accountId: t,
chatId: n.chat.id,
...Number.isFinite(_) ? { threadId: _ } : {},
botUserId: e.me?.id ?? r.botInfo?.id
};
const y = await buildTelegramConversationContext({
...v,
messageId: h,
replyChainNodes: i,
recentLimit: f ? 0 : m,
replyTargetWindowSize: f ? 0 : m > 0 ? 2 : 0,
...c?.promptContextMinTimestampMs !== void 0 ? { minTimestampMs: c.promptContextMinTimestampMs } : {}
});
const b = new Map(y.flatMap((e) => e.node.messageId ? [[e.node.messageId, e]] : []));
if (f && p > 0) {
const e = await readTelegramHistoryWindow({
...v,
before: h,
limit: p
});
for (const t of e) {
if (c?.promptContextMinTimestampMs !== void 0 && t.timestamp !== void 0 && t.timestamp < c.promptContextMinTimestampMs || !isTelegramHistoryEntryAfterAmbientWatermark(t, c?.promptContextAmbientWatermark)) continue;
if (t.messageId && !b.has(t.messageId)) b.set(t.messageId, { node: t });
}
}
for (const [e, r] of u ?? []) {
if (r === "exclude") {
b.delete(e);
continue;
}
if (e === h || b.has(e)) continue;
const i = await a.get({
accountId: t,
chatId: n.chat.id,
messageId: e
});
if (i?.messageId && (!f || await isTelegramHistoryNodeAllowed({
...v,
node: i
}))) b.set(i.messageId, { node: i });
}
const x = Array.from(b.values()).toSorted((e, t) => Number(e.node.messageId) - Number(t.node.messageId)).map(({ node: t, isReplyTarget: n }) => {
const r = t.messageId ? l?.get(t.messageId) : void 0;
return {
node: t,
message: {
message_id: t.messageId,
thread_id: t.threadId,
sender: resolvePromptSender(t, e),
sender_id: t.senderId,
sender_username: t.senderUsername,
timestamp_ms: t.timestamp,
body: t.body,
media_type: r?.contentType ?? r?.kind ?? t.mediaType,
media_path: r?.path,
media_ref: r?.path ? void 0 : t.mediaRef,
reply_to_id: t.replyToId,
is_reply_target: n === true ? true : void 0
}
};
});
const S = resolveCompleteTelegramPromptContextProjectionIds(x.map((e) => e.node.promptContextProjectionMarker));
const C = x.map((e) => e.message);
return C.length > 0 ? [{
label: "Conversation context",
source: "telegram",
type: "chat_window",
...S.size > 0 ? { sessionTranscriptDedupeMessageIds: [...S] } : {},
payload: {
order: "chronological",
relation: "selected_for_current_message",
messages: C
}
}] : [];
};
return {
recordMessageForReplyChain,
recordMessageResolvedMedia,
recordReplyMessageResolvedMedia,
resolveCachedMessageThreadSpec,
buildReplyChainForMessage,
toReplyChainEntry,
buildPromptContextForMessage
};
}
//#endregion
//#region extensions/telegram/src/bot-message-dispatch-context.ts
const TELEGRAM_GENERAL_TOPIC_ID = 1;
function resolveTelegramForumThreadScopeFromSessionKey(e) {
if (typeof e !== "string") return;
const t = /:telegram:group:(-?\d+):topic:(\d+)(?::|$)/.exec(e);
const n = parseStrictPositiveInteger(t?.[2]);
if (!t?.[1] || n == null) return;
return {
chatId: t[1],
threadId: n
};
}
function resolveDispatchTelegramThreadSpec(e) {
if (e.threadSpec.scope !== "forum" || e.threadSpec.id != null && e.threadSpec.id !== TELEGRAM_GENERAL_TOPIC_ID) return e.threadSpec;
const t = resolveTelegramForumThreadScopeFromSessionKey(e.ctxPayload.SessionKey);
const n = t?.chatId === String(e.chatId) ? t.threadId : void 0;
const r = parseStrictPositiveInteger(e.ctxPayload.MessageThreadId) ?? parseStrictPositiveInteger(e.ctxPayload.TransportThreadId);
const i = n ?? r;
return i == null || i === e.threadSpec.id ? e.threadSpec : {
...e.threadSpec,
id: i
};
}
function buildRecoveredTelegramChatActionSender(e) {
return async () => {
try {
await withTelegramApiErrorLogging({
operation: "sendChatAction",
fn: () => e.context.sendChatActionHandler.sendChatAction(e.context.chatId, e.action, buildTypingThreadParams(e.threadId))
});
} catch (t) {
if (e.action !== "record_voice") throw t;
logVerbose(`telegram record_voice cue failed for chat ${e.context.chatId}: ${String(t)}`);
}
};
}
async function resolveDispatchTelegramContext(e) {
const t = resolveDispatchTelegramThreadSpec(e.context);
if (t === e.context.threadSpec || t.scope !== "forum") {
if (t.scope !== "forum" || t.id == null) return e.context;
const n = parseStrictPositiveInteger(e.context.ctxPayload.MessageThreadId);
const r = parseStrictPositiveInteger(e.context.ctxPayload.TransportThreadId);
if (n === t.id && r === t.id) return e.context;
Object.assign(e.context.ctxPayload, {
MessageThreadId: t.id,
TransportThreadId: t.id
});
return e.context;
}
const n = buildTelegramInboundOriginTarget(e.context.chatId, t);
const r = e.context.isGroup ? buildTelegramGroupFrom(e.context.chatId, t) : e.context.ctxPayload.From;
const i = e.context.turn.record.updateLastRoute && t.id != null ? {
...e.context.turn.record.updateLastRoute,
to: `telegram:${e.context.chatId}:topic:${t.id}`,
threadId: String(t.id)
} : e.context.turn.record.updateLastRoute;
const a = e.context.isGroup ? buildTelegramGroupPeerId(e.context.chatId, t) : e.context.historyKey;
const o = e.context.ctxPayload.ChannelStructuredContext ?? [];
let s = e.context.historyLimit > 0 ? o.filter((e) => !isTelegramChatWindowPromptContext(e)) : selectTelegramGroupPromptContext({
promptContext: o,
historyLimit: 0,
includeBeforeSelf: false
});
if (e.context.isGroup && e.context.historyLimit > 0) {
const n = resolveTelegramAccount({
cfg: e.context.cfg,
accountId: e.context.accountId
}).config;
const r = createTelegramMessageContextRuntime({
cfg: e.context.cfg,
accountId: e.context.accountId,
ownerAgentId: resolveTelegramAccountOwnerAgentId({
cfg: e.context.cfg,
accountId: e.context.accountId
}),
telegramCfg: n,
opts: { botInfo: e.context.primaryCtx.me }
});
const i = e.context.ctxPayload.AmbientTranscriptPreviousMessageId ? {
messageId: e.context.ctxPayload.AmbientTranscriptPreviousMessageId,
timestampMs: e.context.ctxPayload.AmbientTranscriptPreviousTimestampMs
} : void 0;
const a = await r.buildReplyChainForMessage(e.context.msg);
s = selectTelegramGroupPromptContext({
promptContext: [...s, ...await r.buildPromptContextForMessage(e.context.primaryCtx, e.context.msg, a, e.context.cfg, {
...n,
historyLimit: e.context.historyLimit
}, {
threadSpec: t,
promptContextMinTimestampMs: e.context.ctxPayload.SessionTranscriptContext?.minTimestampMs,
promptContextAmbientWatermark: i
})],
historyLimit: e.context.historyLimit,
ambientWatermark: i,
includeBeforeSelf: e.context.ctxPayload.InboundEventKind === "room_event"
});
}
const c = telegramPromptContextHistory(s);
const l = c.length > 0 ? c : void 0;
const u = buildRecoveredTelegramChatActionSender({
context: e.context,
threadId: t.id,
action: "typing"
});
const d = buildRecoveredTelegramChatActionSender({
context: e.context,
threadId: t.id,
action: "record_voice"
});
if (t.id != null) Object.assign(e.context.ctxPayload, {
From: r,
InboundHistory: l,
MessageThreadId: t.id,
OriginatingTo: n,
To: n,
TransportThreadId: t.id,
ChannelStructuredContext: s.length > 0 ? s : void 0
});
return {
...e.context,
historyKey: a,
threadSpec: t,
resolvedThreadId: t.id,
replyThreadId: t.id,
sendTyping: u,
sendRecordVoice: d,
turn: {
...e.context.turn,
record: {
...e.context.turn.record,
updateLastRoute: i
}
},
ctxPayload: e.context.ctxPayload
};
}
//#endregion
//#region extensions/telegram/src/draft-stream-message.ts
function toDraftSnapshot(e) {
return {
text: e.plainText,
sourceText: e.sourceText,
sourceTextMode: e.sourceTextMode
};
}
async function deliverDraftPage(e) {
const { page: t } = e;
if (t.richMessage) warnTelegramRichBlocksDegradations({
context: e.context,
reasons: t.degradationReasons ?? [],
warn: (t) => e.warn?.(t)
});
const send = async () => {
const [n] = await deliverTelegramTextPage({
page: {
...t,
degradationReasons: void 0
},
html: t.sourceTextMode === "html",
context: e.context,
warn: (t) => e.warn?.(t),
fallbackLimit: Number.MAX_SAFE_INTEGER,
sender: {
sendPlain: (t) => e.send({ text: t }),
sendHtml: (t) => e.send({
text: t,
parseMode: "HTML"
}),
sendRich: (n) => e.send({
text: t.plainText,
richMessage: n
})
}
});
return {
message: n.result,
snapshot: toDraftSnapshot(n.page)
};
};
return await (e.request ? e.request(send) : send());
}
async function editTelegramDraftMessage(e) {
return (await deliverDraftPage({
page: e.page,
context: "stream preview edit",
warn: e.warn,
request: e.request,
send: ({ text: t, parseMode: n, richMessage: r }) => {
if (r) return e.api.raw.editMessageText({
chat_id: e.chatId,
message_id: e.messageId,
rich_message: r
});
const i = n ? {
parse_mode: n,
...e.linkPreviewParams
} : e.linkPreviewParams;
return Object.keys(i).length > 0 ? e.api.editMessageText(e.chatId, e.messageId, t, i) : e.api.editMessageText(e.chatId, e.messageId, t);
}
})).snapshot;
}
async function sendTelegramDraftMessage(e) {
const { chatId: t, linkPreviewParams: n, page: r, assertCurrentSend: i } = e;
const sendPlannedMessage = (a) => deliverDraftPage({
page: r,
context: "stream preview",
warn: e.warn,
send: ({ text: r, parseMode: o, richMessage: s }) => {
i();
return s ? e.api.raw.sendRichMessage({
chat_id: t,
rich_message: s,
...a
}) : e.api.sendMessage(t, r, {
...o ? { parse_mode: o } : {},
...a,
...n
});
}
});
return (await withTelegramNativeQuoteFallback({
label: "stream-preview",
requestParams: e.sendMessageParams,
...e.page.richMessage ? { removeNativeQuoteParam: removeTelegramRichNativeQuoteParam } : {},
request: sendPlannedMessage
})).result;
}
//#endregion
//#region extensions/telegram/src/draft-stream.ts
const DEFAULT_THROTTLE_MS = 1e3;
const MAX_CONSECUTIVE_PREVIEW_FAILURES = 3;
const MIN_PREVIEW_DWELL_MS = 4e3;
function createTelegramDraftStream(e) {
const t = e.richMessages === true;
const n = t ? TELEGRAM_RICH_TEXT_LIMIT : TELEGRAM_TEXT_CHUNK_LIMIT;
const r = Math.min(e.maxChars ?? n, n);
const i = Math.max(250, e.throttleMs ?? DEFAULT_THROTTLE_MS);
const a = e.minInitialChars;
const o = e.chatId;
const s = buildTelegramThreadParams(e.thread);
const c = parseStrictInteger(e.replyToMessageId);
const l = {
...s,
...buildTelegramThreadReplyParams({
replyToMessageId: c,
replyQuoteMessageId: c,
replyQuoteText: e.replyQuote?.text,
replyQuotePosition: e.replyQuote?.position,
replyQuoteEntities: e.replyQuote?.entities,
nativeReply: true
})
};
const u = c != null && e.replyToMode !== void 0 && isSingleUseReplyToMode(e.replyToMode);
let d = { kind: "available" };
const reserveReplyTargetForSend = () => {
if (!u) return l;
if (d.kind !== "available") return s ?? {};
d = { kind: "pending" };
return l;
};
const settlePendingReplyTarget = (e) => {
if (d.kind === "pending") d = e === void 0 ? { kind: "available" } : {
kind: "retained",
messageId: e
};
};
const f = {
stopped: false,
final: false
};
let p = false;
let m = 0;
let h;
let g;
let _;
let v;
const y = /* @__PURE__ */ new Set();
let b;
let x = "";
let S = "";
let C = "";
let w = "";
let T;
let E;
let D;
let O = 0;
let k;
let A = [];
const previewRequest = (e, t) => runAuthorizedTelegramRequest(e, () => f.final ? t() : runReplaceableTelegramRequest(t));
const scheduleProviderMessageObservation = (t) => {
if (!t) return;
const n = (async () => {
try {
await e.onProviderMessage?.(t);
} catch (t) {
try {
e.warn?.(`telegram stream preview observation failed: ${formatErrorMessage(t)}`);
} catch {}
}
})();
y.add(n);
n.then(() => {
y.delete(n);
});
};
const observeCurrentProviderMessage = () => {
const e = _;
_ = void 0;
scheduleProviderMessageObservation(e);
};
const sendMessageTransportPreview = async (t, n) => {
const r = n ? { link_preview_options: { is_disabled: true } } : {};
if (E) {
await E();
E = void 0;
}
const i = D;
i?.();
const a = h;
if (typeof a === "number") {
g = await editTelegramDraftMessage({
api: e.api,
chatId: o,
messageId: a,
page: t,
linkPreviewParams: r,
warn: e.warn,
request: (e) => previewRequest(i, e)
});
return true;
}
p = true;
const s = reserveReplyTargetForSend();
let c;
try {
c = await previewRequest(i, () => sendTelegramDraftMessage({
api: e.api,
chatId: o,
page: t,
sendMessageParams: s,
linkPreviewParams: r,
warn: e.warn,
assertCurrentSend: () => {
if (f.stopped) throw new TelegramRequestNotStartedError("Telegram preview stopped");
i?.();
}
}));
} catch (e) {
if (isSafeToRetrySendError(e) || isTelegramClientRejection(e)) {
p = false;
settlePendingReplyTarget();
}
throw e;
}
const l = c.message?.message_id;
const u = typeof l === "number" && Number.isFinite(l) ? Math.trunc(l) : void 0;
if (u === void 0) {
f.stopped = true;
e.warn?.("telegram stream preview stopped (missing message id from sendMessage)");
return false;
}
settlePendingReplyTarget(u);
const adoptSentMessage = () => {
h = u;
g = c.snapshot;
_ = c.message;
b = Date.now();
};
try {
if (e.validateProviderMessage) await e.validateProviderMessage(c.message);
} catch (e) {
v ??= e instanceof Error ? e : new Error(formatErrorMessage(e));
f.stopped = true;
adoptSentMessage();
return false;
}
adoptSentMessage();
retireSupersededPreviews();
return true;
};
const sendOrEditPlannedPage = async (t, n = false, r = e.linkPreview === false) => {
const i = JSON.stringify([
t.sourceTextMode,
t.sourceText,
t.richMessage?.skip_entity_detection === true,
r
]);
if (i === x) return true;
if (typeof h !== "number" && a != null && !f.final && !n && t.plainText.length < a) return false;
const o = x;
x = i;
const s = O;
const settleAuthorization = () => {
if (O === s) D = void 0;
};
try {
const e = await sendMessageTransportPreview(t, r);
if (e) settleAuthorization();
if (e) m = 0;
return e;
} catch (n) {
const r = typeof h === "number";
if (r && isTelegramMessageNotModifiedError(n)) {
settleAuthorization();
m = 0;
g = toDraftSnapshot(t);
return true;
}
x = o;
if (!f.final && isTelegramRateLimitError(n)) return false;
const i = isTelegramRateLimitError(n) || (r ? isRetryableTelegramApiError(n) : isSafeToRetrySendError(n));
m += 1;
if (i && m <= MAX_CONSECUTIVE_PREVIEW_FAILURES) {
e.warn?.(`telegram stream preview ${r ? "edit" : "send"} failed (retrying): ${formatErrorMessage(n)}`);
return false;
}
f.stopped = true;
e.warn?.(`telegram stream preview failed: ${formatErrorMessage(n)}`);
return false;
}
};
const retainCurrentPage = () => {
if (typeof h !== "number" || !g?.text) return;
e.onRetainedPage?.({
messageId: h,
textSnapshot: g.text,
visibleSinceMs: b
});
observeCurrentProviderMessage();
};
const resolveExactRemainingPage = (e) => {
if (e.nextPageIndex <= 0 || e.nextPageIndex >= e.pages.length) return;
const t = e.pages[0]?.fullSourceText;
if (t === void 0) return;
const n = e.pages.slice(0, e.nextPageIndex).map((e) => e.sourceText).join("");
if (!t?.startsWith(n)) return;
const i = t.slice(n.length);
const a = telegramHtmlToPlainTextFallback(i);
return a.length <= r ? {
plainText: a,
sourceText: i,
sourceTextMode: "html",
fullSourceText: t,
htmlText: i
} : void 0;
};
const sendOrEditStreamMessage = async (n) => {
const i = typeof n !== "string";
const a = i ? n.resolveText() : n;
if (a === void 0) return true;
if (i) {
T = void 0;
C = a;
}
if (f.stopped && !f.final) return false;
const o = a.trimEnd();
if (!o) return false;
w = o;
const s = T?.text === o ? T : e.renderText?.(o) ?? { text: o };
const c = f.final && k ? k.pages : planTelegramTextDeliveryPages({
text: s.markdownSource?.text ?? s.text,
maxChars: r,
richMessages: t,
richMessage: s.richMessage,
tableMode: s.markdownSource?.tableMode,
...t || s.markdownSource ? {} : { textMode: s.parseMode === "HTML" ? "html" : "plain" }
});
const l = c[0];
if (!l) return false;
const u = s.linkPreview === false || e.linkPreview === false;
if (!f.final) {
k = void 0;
const e = await sendOrEditPlannedPage(l, s.complete, u);
if (e) S = c.length === 1 ? o : l.plainText.trimEnd();
return e;
}
const d = k ??= {
pages: c,
nextPageIndex: 0
};
for (let e = d.nextPageIndex; e < c.length; e += 1) {
const t = resolveExactRemainingPage(d);
const n = t ?? c[e];
if (e > 0 && typeof h === "number") {
retainCurrentPage();
resetStreamToNewMessage("page");
}
if (!await sendOrEditPlannedPage(n, false, u)) return false;
if (k !== d) return true;
d.nextPageIndex = t ? c.length : e + 1;
if (t) break;
}
k = void 0;
S = o;
return true;
};
const { loop: j, update: M, stopForClear: N } = createFinalizableDraftStreamControlsForState({
throttleMs: i,
state: f,
sendOrEditStreamMessage
});
const throwTerminalDeliveryError = () => {
if (v !== void 0) throw v;
};
const waitForInFlight = async () => {
await j.waitForInFlight();
throwTerminalDeliveryError();
};
const flush = async () => {
await waitForInFlight();
if (!f.stopped) await j.flush();
throwTerminalDeliveryError();
};
const requestDraftUpdate = (e, t, n, r) => {
if (f.stopped || f.final) return;
if (typeof e === "string") {
T = t;
C = e;
E = n;
}
D = r;
O += 1;
M(e);
};
const stop = async () => {
f.final = true;
j.resetThrottleWindow();
await j.waitForInFlight();
throwTerminalDeliveryError();
if (f.stopped) return;
await flush();
if (f.stopped) return;
const e = C.trimEnd();
if (e && e !== S.trimEnd()) for (let t = 0; t < 2; t += 1) {
const t = await sendOrEditStreamMessage(e);
throwTerminalDeliveryError();
if (t) {
j.resetPending();
break;
}
if (!k || f.stopped) break;
}
f.final = true;
observeCurrentProviderMessage();
await Promise.all(y);
E = void 0;
D = void 0;
};
/** Prepared final content not yet accepted after retained pagination pages. */
const remainingFinalContent = () => {
const e = k;
if (!e || e.nextPageIndex <= 0 || e.nextPageIndex >= e.pages.length) return;
const t = e.pages.slice(e.nextPageIndex);
const n = resolveExactRemainingPage(e);
const r = n?.sourceText || t.map((e) => e.sourceTextMode === "html" ? e.sourceText : escapeTelegramHtml(e.plainText)).join("");
return {
text: n?.plainText ?? t.map((e) => e.plainText).join(""),
sourceText: r,
sourceTextMode: "html"
};
};
const resetStreamToNewMessage = (e) => {
const t = e === "page";
if (e === "retain") observeCurrentProviderMessage();
f.stopped = false;
f.final = t;
p = false;
h = void 0;
g = void 0;
_ = void 0;
b = void 0;
x = "";
if (!t) {
k = void 0;
C = "";
S = "";
j.resetPending();
T = void 0;
D = void 0;
O += 1;
}
j.resetThrottleWindow();
};
const scheduleDetachedDelete = (t, n, r = 0) => {
const runDelete = async () => {
try {
if (!await e.api.deleteMessage(o, t)) {
e.warn?.(`telegram stream preview cleanup was not confirmed (chat=${o}, message=${t})`);
return;
}
if (d.kind === "retained" && d.messageId === t) d = { kind: "available" };
} catch (t) {
e.warn?.(`telegram stream preview cleanup failed: ${formatErrorMessage(t)}`);
}
};
const i = typeof n === "number" ? Date.now() - n : MIN_PREVIEW_DWELL_MS;
const a = Math.max(0, MIN_PREVIEW_DWELL_MS - i);
const s = Math.max(a, r);
if (s <= 0) runDelete();
else setTimeout(() => {
runDelete();
}, s);
};
const retireSupersededPreviews = () => {
const e = A;
A = [];
for (const { messageId: t, visibleSinceMs: n } of e) scheduleDetachedDelete(t, n, P);
};
const retireWhenReplaced = (e, t) => {
A.push({
messageId: e,
visibleSinceMs: t
});
if (typeof h === "number") retireSupersededPreviews();
};
const clear = async () => {
retireSupersededPreviews();
const e = b;
const t = await takeMessageIdAfterStop({
stopForClear: N,
readMessageId: () => h,
clearMessageId: () => {
h = void 0;
g = void 0;
_ = void 0;
}
});
retireSupersededPreviews();
if (typeof t === "number" && Number.isFinite(t)) scheduleDetachedDelete(t, e);
await Promise.all(y);
};
const P = 1500;
/** Rewind and delete the superseded preview only after its replacement lands. */
const rotateToNewMessageDeferringDelete = () => {
const e = h;
const t = b;
resetStreamToNewMessage("replace");
if (typeof e === "number" && Number.isFinite(e)) retireWhenReplaced(e, t);
};
return {
update: (e, t) => requestDraftUpdate(e, void 0, t?.onPlatformSendDispatch, t?.assertPlatformSendAuthorized),
updateLazy: (e) => requestDraftUpdate({ resolveText: e }),
updatePreview: (e, t) => {
const n = e.text.trimEnd();
if (!n) return;
requestDraftUpdate(n, {
...e,
text: n
}, void 0, t);
},
flush,
waitForInFlight,
messageId: () => h,
lastDeliveredText: () => S,
/** A failed preview stops editing for good; it can no longer carry live progress. */
isStopped: () => f.stopped,
currentMessageSnapshot: () => {
const e = !u || d.kind === "retained" && d.messageId === h;
return g && e && c !== void 0 ? {
...g,
replyToMessageId: c
} : g;
},
clear,
stop,
/** Stop without a final flush or delete. */
discard: async () => {
await N();
observeCurrentProviderMessage();
await Promise.all(y);
},
remainingFinalContent,
/** True while a pending or visible draft owns a first/batched reply target. */
hasConsumedReplyTarget: () => d.kind !== "available",
/** Reset internal state so the next update creates a new message instead of editing. */
forceNewMessage: () => resetStreamToNewMessage("retain"),
rotateToNewMessageDeferringDelete,
/** True when a lost sendMessage response may have delivered exactly this text. */
sendMayHaveLanded: (e) => p && typeof h !== "number" && w === e.trimEnd()
};
}
//#endregion
//#region extensions/telegram/src/reasoning-lane-coordinator.ts
const REASONING_MESSAGE_RE = /^🧠\s+_/u;
const CORE_THINKING_HEADER_RE = /^Thinking\.{0,3}\s*\n+/u;
function markReasoningMessage(e) {
return e.replace(CORE_THINKING_HEADER_RE, "").replace(/^_/u, "🧠 _");
}
const REASONING_TAG_PREFIXES = [
"think",
"thinking",
"thought",
"internal",
"antthinking",
"mm:think"
].flatMap((e) => [`<${e}`, `</${e}`]);
const THINKING_TAG_RE = /<\s*(\/?)\s*(?:(?:antml:|mm:)?(?:think(?:ing)?|thought)|antthinking)\b[^<>]*>/gi;
function extractThinkingFromTaggedStreamOutsideCode(e) {
const t = findMarkdownCodeRegions(e);
let n = "";
let r = 0;
let i = false;
for (const a of e.matchAll(THINKING_TAG_RE)) {
const o = a.index ?? 0;
if (isInsideCode(o, t)) continue;
if (i) n += e.slice(r, o);
i = a[1] !== "/";
r = o + a[0].length;
}
if (i) n += e.slice(r);
return n.trim();
}
function isPartialReasoningTagPrefix(e) {
const t = e.trim().replace(/^<\s*(\/?)\s+/u, "<$1").toLowerCase();
return t.startsWith("<") && REASONING_TAG_PREFIXES.some((e) => e.startsWith(t));
}
function splitTelegramReasoningText(e, t) {
if (typeof e !== "string") return {};
if (t !== true) return { answerText: e };
const n = e.trim();
if (isPartialReasoningTagPrefix(n)) return {};
if (REASONING_MESSAGE_RE.test(n)) return { reasoningText: n };
if (CORE_THINKING_HEADER_RE.test(n)) return { reasoningText: markReasoningMessage(n) };
const r = extractThinkingFromTaggedStreamOutsideCode(e);
const i = stripReasoningTagsFromText(e, {
mode: "strict",
trim: "both"
});
const a = r || i;
if (!a) return {};
return { reasoningText: markReasoningMessage(formatReasoningMessage(a)) };
}
function createTelegramReasoningStepState() {
let e = "none";
let t;
return {
noteReasoningHint() {
if (e === "none") e = "hinted";
},
noteReasoningDelivered() {
e = "delivered";
},
shouldBufferFinalAnswer: () => e === "hinted" && !t,
bufferFinalAnswer(e) {
t = e;
},
takeBufferedFinalAnswer() {
const e = t;
t = void 0;
return e;
},
resetForNextStep() {
e = "none";
t = void 0;
}
};
}
//#endregion
//#region extensions/telegram/src/bot-message-dispatch-draft.ts
const draftLogger = createSubsystemLogger("telegram/draft-stream");
const DRAFT_MIN_INITIAL_CHARS = 30;
function createDraftState(e) {
const t = e.context.ctxPayload.InboundEventKind === "room_event";
const n = e.resolvedReasoningLevel === "on" && e.streamMode !== "progress";
const r = !t && e.streamMode !== "off";
const i = e.allowProviderPreview && r && !(e.replyToMode !== "off" && e.replyQuoteText != null) && !n;
const a = resolveChannelStreamingBlockEnabled(e.telegramCfg, {
previewAvailable: i,
blockStreamingDefault: e.cfg.agents?.defaults?.blockStreamingDefault
});
const o = i && !a;
const s = e.resolvedReasoningLevel === "stream";
const c = s && e.streamMode === "progress" && o;
const l = e.allowProviderPreview && !t && s && !c;
const u = e.streamMode === "block" ? Math.min(resolveChannelDraftStreamingChunking(e.cfg, "telegram", e.context.route.accountId, { fallbackLimit: TELEGRAM_TEXT_CHUNK_LIMIT }).maxChars, e.textLimit) : Math.min(e.textLimit, e.richMessages ? TELEGRAM_RICH_TEXT_LIMIT : TELEGRAM_TEXT_CHUNK_LIMIT);
const renderDraftText = (t) => e.richMessages ? {
text: t,
richMessage: buildTelegramRichMarkdownPlan(t, {
tableMode: e.tableMode,
skipEntityDetection: e.telegramCfg.linkPreview === false
}).richMessage
} : {
text: t,
markdownSource: {
text: t,
tableMode: e.tableMode
}
};
const createLaneStream = (t) => createTelegramDraftStream({
api: e.bot.api,
chatId: e.context.chatId,
maxChars: u,
thread: e.context.threadSpec,
replyToMessageId: e.draftReplyToMessageId,
replyToMode: e.replyToMode,
replyQuote: e.draftReplyToMessageId != null ? e.replyQuoteByMessageId[String(e.draftReplyToMessageId)] : void 0,
richMessages: e.richMessages,
linkPreview: e.telegramCfg.linkPreview,
minInitialChars: DRAFT_MIN_INITIAL_CHARS,
renderText: renderDraftText,
onRetainedPage: (e) => {
d[t].retainedPromptContextPages.push({
messageId: e.messageId,
text: e.textSnapshot
});
},
...e.context.threadSpec.id !== void 0 ? { validateProviderMessage: async (t) => {
await reportTelegramProviderDelivery({
message: t,
messageId: t.message_id,
fallbackChatId: e.context.chatId,
successfulSendThread: e.context.threadSpec
});
} } : {},
onProviderMessage: async (t) => {
await recordSentMessage(e.context.chatId, t.message_id, e.cfg, {
accountId: e.context.route.accountId,
agentId: e.opts.ownerAgentId
});
await recordOutboundMessageForPromptContext({
cfg: e.cfg,
ownerAgentId: e.opts.ownerAgentId,
account: {
accountId: e.context.route.accountId,
...e.telegramCfg.name !== void 0 ? { name: e.telegramCfg.name } : {}
},
chatId: e.context.chatId,
message: t,
messageId: t.message_id,
...e.context.threadSpec.id !== void 0 ? { messageThreadId: e.context.threadSpec.id } : {},
successfulSendThread: e.context.threadSpec
});
},
warn: (n) => draftLogger.warn(n, {
lane: t,
chatId: e.context.chatId,
threadId: e.context.threadSpec.id
})
});
const createDraftLane = (e, t) => ({
stream: t ? createLaneStream(e) : void 0,
lastPartialText: "",
hasStreamedMessage: false,
finalized: false,
retainedPromptContextPages: []
});
const d = {
answer: createDraftLane("answer", o),
reasoning: createDraftLane("reasoning", l)
};
const f = resolveChannelStreamingBlockEnabled(e.telegramCfg);
const p = !r ? true : n ? false : typeof f === "boolean" ? !f : !e.allowProviderPreview && !e.context.ctxPayload.GroupThread ? e.cfg.agents?.defaults?.blockStreamingDefault === "off" : o ? true : void 0;
return {
answerLane: d.answer,
reasoningLane: d.reasoning,
lanes: d,
createAnswerStream: () => createLaneStream("answer"),
streamDeliveryEnabled: r,
streamReasoningInProgressDraft: c,
disableBlockStreaming: p,
durableReasoningPayloadsEnabled: e.resolvedReasoningLevel === "on" || Boolean(d.reasoning.stream),
lastAnswerPartialText: "",
activeAnswerDraftIsToolProgressOnly: false,
activeAnswerBlockAssistantMessageIndex: void 0,
activeAnswerBlockDelivery: void 0,
queuedAnswerBlockRotations: [],
pendingAnswerBlockAssistantMessageIndex: void 0,
rotateAnswerLaneWhenQueuedBlocksSettle: false,
draftEventQueue: Promise.resolve()
};
}
function resetLaneState(e, t) {
t.lastPartialText = "";
t.hasStreamedMessage = false;
t.finalized = false;
t.retainedPromptContextPages = [];
if (t === e.answerLane) {
e.lastAnswerPartialText = "";
e.activeAnswerDraftIsToolProgressOnly = false;
e.pendingAnswerBlockAssistantMessageIndex = void 0;
e.activeAnswerBlockDelivery = void 0;
}
}
function repositionLaneForNewMessage(e, t) {
t.stream?.rotateToNewMessageDeferringDelete();
resetLaneState(e, t);
}
async function rotateLaneForNewMessage(e, t) {
if (t.hasStreamedMessage || typeof t.stream?.messageId() === "number") {
await t.stream?.stop();
t.stream?.forceNewMessage();
}
resetLaneState(e, t);
}
async function retireAnswerLane(e, t = "defer") {
const n = e.answerLane;
if (n.finalized) await rotateLaneForNewMessage(e, n);
else if (t === "defer") repositionLaneForNewMessage(e, n);
else {
await n.stream?.clear();
n.stream?.forceNewMessage();
resetLaneState(e, n);
}
}
async function rotateAnswerLaneForNewMessage(e) {
await e.materializeAnswerLaneBeforeRotation();
await retireAnswerLane(e);
}
async function rotateAnswerLaneAfterToolProgress(e) {
if (!e.activeAnswerDraftIsToolProgressOnly) return false;
await retireAnswerLane(e);
e.progressCompositor.resetActivity({ suppressed: true });
e.rotateAnswerLaneWhenQueuedBlocksSettle = false;
return true;
}
async function rotateAnswerLaneAfterQueuedBlocksSettle(e) {
if (!e.rotateAnswerLaneWhenQueuedBlocksSettle || e.queuedAnswerBlockRotations.length > 0) return false;
e.rotateAnswerLaneWhenQueuedBlocksSettle = false;
if (!e.answerLane.hasStreamedMessage || e.activeAnswerDraftIsToolProgressOnly) return false;
await rotateAnswerLaneForNewMessage(e);
return true;
}
async function prepareAnswerLaneForText(e) {
if (e.streamMode === "progress") return false;
if (await rotateAnswerLaneAfterToolProgress(e) || await rotateAnswerLaneAfterQueuedBlocksSettle(e)) return true;
if (!e.answerLane.finalized) return false;
e.answerLane.stream?.forceNewMessage();
resetLaneState(e, e.answerLane);
e.rotateAnswerLaneWhenQueuedBlocksSettle = false;
return true;
}
async function prepareAnswerLaneForToolProgress(e) {
if (e.answerLane.finalized) {
e.answerLane.stream?.forceNewMessage();
resetLaneState(e, e.answerLane);
}
if (e.activeAnswerDraftIsToolProgressOnly) return;
if (e.streamMode !== "progress" && e.answerLane.hasStreamedMessage) await rotateAnswerLaneForNewMessage(e);
e.activeAnswerDraftIsToolProgressOnly = true;
}
function splitTextIntoLaneSegments(e, t, n) {
const r = splitTelegramReasoningText(t, n);
const i = n === true ? "reasoning" : "answer";
const a = i === "reasoning" ? r.reasoningText : r.answerText;
const o = e.resolvedReasoningLevel === "off";
return {
segment: a && (i === "answer" || !o) ? {
lane: i,
text: a
} : void 0,
suppressedReasoningOnly: n === true && (o || !a)
};
}
function updateTelegramDraftFromPartial(e, t, n, r = true) {
if (!t.stream || !n) return;
if (n === (t === e.answerLane ? e.lastAnswerPartialText : t.lastPartialText) || t === e.answerLane && e.streamMode === "progress") return;
if (t === e.answerLane) {
e.activeAnswerDraftIsToolProgressOnly = false;
e.progressCompositor.resetActivity({ suppressed: true });
e.lastAnswerPartialText = n;
}
t.hasStreamedMessage = true;
t.finalized = false;
t.lastPartialText = n;
if (r) t.stream.update(n);
return n;
}
async function ingestDraftLaneSegments(e, t, n) {
if (n !== true) {
const n = e.answerLane.stream;
if (!n) return;
if (e.streamMode !== "progress" && (e.activeAnswerDraftIsToolProgressOnly || e.answerLane.finalized || e.rotateAnswerLaneWhenQueuedBlocksSettle && e.queuedAnswerBlockRotations.length === 0 && e.answerLane.hasStreamedMessage)) {
const n = t.text;
if (!n) return;
await prepareAnswerLaneForText(e);
updateTelegramDraftFromPartial(e, e.answerLane, n);
return;
}
let r = false;
let i;
n.updateLazy(() => {
if (!r) {
const n = t.text;
i = n ? updateTelegramDraftFromPartial(e, e.answerLane, n, false) : void 0;
r = true;
}
return i;
});
return;
}
const r = splitTextIntoLaneSegments(e, t.text, true).segment;
if (r) {
e.reasoningStepState.noteReasoningHint();
e.reasoningStepState.noteReasoningDelivered();
updateTelegramDraftFromPartial(e, e.reasoningLane, r.text);
}
}
function enqueueDraftEvent(e, t, n = "progress") {
const r = e.draftEventQueue.then(() => n === "progress" && e.isSuperseded() ? void 0 : t());
const i = r.catch((e) => {
logVerbose(`telegram: draft lane callback failed: ${String(e)}`);
});
e.draftEventQueue = i.then(() => {});
return n === "delivery" ? r : i;
}
function recomputeTelegramQueuedAnswerBlockRotations(e) {
let t = e.activeAnswerBlockAssistantMessageIndex ?? e.pendingAnswerBlockAssistantMessageIndex;
for (const n of e.queuedAnswerBlockRotations) {
if (n.assistantMessageIndex === void 0) continue;
n.shouldRotateBeforeDelivery = t !== void 0 && n.assistantMessageIndex !== t;
t = n.assistantMessageIndex;
}
}
function telegramQueuedRotationMatches(e, t, n) {
return n !== void 0 && e.assistantMessageIndex !== void 0 ? n === e.assistantMessageIndex : e.text !== void 0 && t.text !== void 0 && e.text === t.text;
}
async function prepareQueuedAnswerBlock(e, t, n) {
if (splitTextIntoLaneSegments(e, t.text, t.isReasoning).segment?.lane !== "answer") return;
if (e.streamMode !== "progress") e.progressCompositor.resetActivity();
const r = n?.assistantMessageIndex;
const i = r === void 0 ? void 0 : e.queuedAnswerBlockRotations.findLast((e) => e.assistantMessageIndex !== void 0)?.assistantMessageIndex ?? e.activeAnswerBlockAssistantMessageIndex ?? e.pendingAnswerBlockAssistantMessageIndex;
e.queuedAnswerBlockRotations.push({
...r !== void 0 ? { assistantMessageIndex: r } : {},
text: t.text,
shouldRotateBeforeDelivery: i !== void 0 && r !== i
});
}
function takeQueuedAnswerBlockRotation(e, t, n) {
if (e.queuedAnswerBlockRotations.length === 0) return false;
const r = e.queuedAnswerBlockRotations.findIndex((e) => telegramQueuedRotationMatches(e, t, n));
const i = e.queuedAnswerBlockRotations.splice(0, Math.max(r, 0) + 1).at(-1);
if (i?.assistantMessageIndex !== void 0) {
e.activeAnswerBlockAssistantMessageIndex = i.assistantMessageIndex;
e.pendingAnswerBlockAssistantMessageIndex = void 0;
}
recomputeTelegramQueuedAnswerBlockRotations(e);
return i?.shouldRotateBeforeDelivery ?? false;
}
function dropQueuedAnswerBlockRotation(e, t, n) {
let r = e.queuedAnswerBlockRotations.findIndex((e) => telegramQueuedRotationMatches(e, t, n));
if (r < 0 && n === void 0) r = e.queuedAnswerBlockRotations.findIndex((e) => e.assistantMessageIndex === void 0);
if (r < 0) return;
const [i] = e.queuedAnswerBlockRotations.splice(r, 1);
if (r === 0 && i?.assistantMessageIndex !== void 0 && e.rotateAnswerLaneWhenQueuedBlocksSettle && e.activeAnswerBlockAssistantMessageIndex === void 0 && e.answerLane.hasStreamedMessage) e.pendingAnswerBlockAssistantMessageIndex = i.assistantMessageIndex;
recomputeTelegramQueuedAnswerBlockRotations(e);
}
function isQueuedAnswerBlock(e, t, n) {
return e.queuedAnswerBlockRotations.some((e) => telegramQueuedRotationMatches(e, t, n));
}
function beginDraftQueuedFollowup(e) {
if (e.progressContinuationAdopted) e.answerLane.stream = e.createAnswerStream();
e.progressContinuationAdopted = false;
for (const t of [e.answerLane, e.reasoningLane]) {
if (!t.stream) continue;
t.stream.forceNewMessage();
resetLaneState(e, t);
}
}
async function cleanupDrafts(e, t) {
await e.previewLifecycle.cleanup({ failed: t || e.dispatchError != null || e.agentRunFailed });
}
//#endregion
//#region extensions/telegram/src/bot-message-dispatch-payload.ts
const projectPayloadForDelivery = (e, t, n) => {
const r = createOutboundPayloadPlan([t])[0]?.payload;
if (r && n) {
if (t.replyToId !== void 0 || t.replyToCurrent === true) {
r.replyToId = t.replyToId;
r.replyToCurrent = t.replyToCurrent;
r.replyToTag = t.replyToTag || t.replyToCurrent === true;
} else if (n.replyToId !== void 0 || n.replyToCurrent === true) {
r.replyToId = n.replyToId;
r.replyToCurrent = n.replyToCurrent;
r.replyToTag = true;
}
r.audioAsVoice = t.audioAsVoice ?? n.audioAsVoice ?? r.audioAsVoice;
if (n.mediaUrls?.length) r.mediaUrls = [...r.mediaUrls ?? [], ...n.mediaUrls];
}
if (r?.replyToCurrent && r.replyToId === void 0) r.replyToId = e.context.ctxPayload.MessageSidFull ?? e.context.ctxPayload.MessageSid;
return r ? createStructuredOutboundPayloadPlan([r])[0]?.payload : void 0;
};
function normalizeDeliveryPayload(e, t) {
const n = t.isReasoning === true && e.durableReasoningPayloadsEnabled;
const r = n ? copyReplyPayloadMetadata(t, { ...t }) : t;
if (n) delete r.isReasoning;
const i = projectPayloadForDelivery(e, r);
return i ? normalizePreparedDeliveryPayload(e, i) : void 0;
}
function normalizePreparedDeliveryPayload(e, t) {
if (e.richMessages && t.presentation) return t;
return canonicalizeTelegramPresentationPayload(t, {
allowWebAppButtons: resolveTelegramTargetChatType(String(e.context.chatId)) === "direct",
richTables: false
});
}
const usesNativeTelegramQuote = (e, t) => (e.replyToMode !== "off" || t.replyToTag === true || t.replyToCurrent === true) && (e.replyQuoteText != null || t.replyToId != null && e.replyQuoteByMessageId[t.replyToId] != null);
function applyQuoteReplyTarget(e, t) {
if (!e.implicitQuoteReplyTargetId || !e.currentMessageIdForQuoteReply || t.replyToId !== e.currentMessageIdForQuoteReply || t.replyToTag || t.replyToCurrent) return t;
return copyReplyPayloadMetadata(t, {
...t,
replyToId: e.implicitQuoteReplyTargetId
});
}
function formatTelegramGroupThreadReply(e, t) {
return `**${t.name.replace(/[\\`*_{}[\]()<>#!|]/g, "\\$&").replace(/\s+/g, " ")}**\n${e}`;
}
//#endregion
//#region extensions/telegram/src/bot-message-dispatch-session.ts
function createFreshTelegramSessionEntryLoader(e) {
const t = /* @__PURE__ */ new Map();
const load = async (n, r) => {
const i = resolveSessionStorePathCore(e.cfg.session?.store, { agentId: n });
const a = `${i}\0${r}`;
const o = t.get(a);
if (o) return {
storePath: i,
entry: await o
};
const s = getSessionEntryAsync({
storePath: i,
sessionKey: r,
readConsistency: "latest"
});
t.set(a, s);
return {
storePath: i,
entry: await s
};
};
return Object.assign(load, { clear: () => t.clear() });
}
async function resolveTelegramReasoningLevel(e) {
const t = resolveAgentConfig(e.cfg, e.agentId)?.reasoningDefault ?? e.cfg.agents?.defaults?.reasoningDefault ?? "off";
if (!e.sessionKey) return t;
try {
const { entry: n } = await e.loadFreshSessionEntry(e.agentId, e.sessionKey);
const r = n?.reasoningLevel;
return r === "on" || r === "stream" || r === "off" ? r : t;
} catch {
return "off";
}
}
function resolveTelegramMirroredTranscriptText(e) {
const t = e.mediaUrls?.filter((e) => e.trim()) ?? [];
if (t.length > 0) return t.map((e) => {
const t = e.split("#")[0]?.split("?")[0] ?? e;
const n = path.basename(t);
return n && n !== "." && n !== "/" ? n : "media";
}).join(", ");
return e.text?.trim() || null;
}
function createTelegramTranscriptMirror(e, t = e) {
const n = e.context.ctxPayload.SessionKey;
if (!n) return;
return async (r) => {
const i = `telegram-final:${n}:${e.transcriptMirrorTurnId}:${t.transcriptMirrorSequence++}`;
const a = resolveTelegramMirroredTranscriptText(r);
if (!a) return;
const o = e.context.route.agentId;
const { entry: s, storePath: c } = await e.loadFreshSessionEntry(o, n);
const l = s?.sessionId?.trim();
if (!l) return;
const u = await appendAssistantMirrorMessageByIdentity({
agentId: o,
config: e.cfg,
idempotencyKey: i,
...e.transcriptMirrorRunId ? { sourceRunId: e.transcriptMirrorRunId } : {},
deliveryMirror: {
kind: "channel-final",
sourceMessageId: i
},
sessionId: l,
sessionKey: n,
storePath: c,
text: a
});
if (!u.ok && u.code !== "session-rebound") logVerbose(`telegram transcript mirror append failed: ${u.reason}`);
};
}
function createCurrentTurnTranscriptFinalResolver(e) {
return async () => {
if (!e.sessionKey) return;
try {
const { entry: t, storePath: n } = await e.loadFreshSessionEntry(e.agentId, e.sessionKey);
if (!t?.sessionId) return;
const r = await readLatestAssistantTextByIdentity({
agentId: e.agentId,
sessionId: t.sessionId,
sessionKey: e.sessionKey,
storePath: n
});
if (!r?.timestamp || r.timestamp < e.dispatchStartedAt) return;
return {
...r.id ? { messageId: r.id } : {},
text: r.text,
...r.openclawDelivery ? { openclawDelivery: r.openclawDelivery } : {}
};
} catch (e) {
logVerbose(`telegram transcript final candidate lookup failed: ${formatErrorMessage(e)}`);
return;
}
};
}
//#endregion
//#region extensions/telegram/src/bot-message-dispatch.media-dedup.ts
function deduplicateBlockSentMedia(e, t) {
if (!e.mediaUrls?.length || t.size === 0) return e;
const n = e.mediaUrls.filter((e) => !t.has(e));
if (n.length === e.mediaUrls.length) return e;
if (n.length === 0 && !e.text) return;
const r = t.has(e.mediaUrl?.trim() ?? "") ? void 0 : e.mediaUrl;
return copyReplyPayloadMetadata(e, {
...e,
mediaUrls: n,
mediaUrl: r,
...e.attachments ? { attachments: collectReplyMediaEntries(e, [...n, ...r ? [r] : []]).map(({ attachment: e }) => e ?? {}) } : {}
});
}
function trackBlockMedia(e, t, n) {
for (const { url: r, sourceUrls: i } of collectReplyMediaEntries(t, n)) for (const t of [r, ...i ?? []]) e.add(t);
}
//#endregion
//#region extensions/telegram/src/final-delivery-config.ts
/** Preserve the inbound bot, including credentials resolved outside the config snapshot. */
function prepareTelegramFinalDeliveryConfig(e, t, n) {
const r = n.trim();
const i = resolveTelegramAccount({
cfg: e,
accountId: t
});
if (!r || !i.enabled || i.accountId !== normalizeAccountId(t) || i.token.trim() !== r) {
const e = "The Telegram reply sender changed during this turn; delivery was not started.";
throw new PlatformMessageNotDispatchedError(e, {
cause: /* @__PURE__ */ new Error(e),
retryable: false
});
}
const a = e.channels?.telegram;
const o = a?.accounts;
const s = o && Object.hasOwn(o, i.accountId) ? i.accountId : Object.keys(o ?? {}).find((e) => normalizeAccountId(e) === i.accountId) ?? i.accountId;
return {
...e,
channels: {
...e.channels,
telegram: {
...a,
accounts: {
...o,
[s]: {
...resolveTelegramAccountConfig(e, i.accountId),
tokenFile: void 0,
botToken: r
}
}
}
}
};
}
//#endregion
//#region extensions/telegram/src/lane-delivery-state.ts
function createLaneDeliveryStateTracker() {
const e = {
delivered: false,
skippedNonSilent: 0,
failedNonSilent: 0
};
return {
markDelivered: () => {
e.delivered = true;
},
markNonSilentSkip: () => {
e.skippedNonSilent += 1;
},
markNonSilentFailure: () => {
e.failedNonSilent += 1;
},
snapshot: () => ({ ...e })
};
}
//#endregion
//#region extensions/telegram/src/lane-delivery-text-deliverer.ts
function createLaneTextDeliverer(e) {
const recordRetainedPromptContextPages = async (e, t) => {
for (const n of e.retainedPromptContextPages.splice(0)) await t.accept(n);
};
return async ({ laneName: t, text: n, payload: r, infoKind: i, buttons: a, finalizePreview: o, durable: s, allowStream: c = true, promptContextSequence: l, onPlatformSendDispatch: u, assertPlatformSendAuthorized: d, bindPendingFinalDelivery: f, onMediaAccepted: p }) => {
let m = n;
let h = r;
const g = e.lanes[t];
const _ = l ?? e.createPromptContextSequence();
let v = resolveSendableOutboundReplyParts(h, { text: m });
const y = i === "final";
const b = o ?? y;
const x = s ?? y;
const S = {
durable: x,
promptContextSequence: _,
onPlatformSendDispatch: u,
assertPlatformSendAuthorized: d,
bindPendingFinalDelivery: f,
onMediaAccepted: p
};
let C;
if (c && y && h.isError === true && t === "answer" && g.stream && g.hasStreamedMessage && !g.finalized && !v.hasMedia && m.trim()) {
const e = (g.lastPartialText || g.stream.lastDeliveredText() || "").trimEnd();
const t = m.trim();
C = e && !e.endsWith(t) ? `${e}\n\n${t}` : e || t;
}
const w = C ?? m;
const T = c && !v.hasMedia && (!h.isError || C !== void 0);
const E = c && b && v.hasMedia && g.hasStreamedMessage && !g.finalized && !h.isError;
if (y && g.stream && (T || E) && isPotentialTruncatedFinal(w)) {
let n;
await resolveTranscriptBackedChannelFinalText({
payload: h,
finalText: w,
resolveCandidateText: async () => {
n = await e.resolveFinalPayloadCandidate?.({
finalText: w,
laneName: t,
payload: h,
candidateTexts: [g.stream?.lastDeliveredText(), g.lastPartialText]
});
return n?.text;
}
});
if (n) {
h = n;
m = n.text ?? "";
v = resolveSendableOutboundReplyParts(h, { text: m });
C = C === void 0 ? void 0 : m;
}
}
const D = h.replyToId === void 0 || parseStrictInteger(h.replyToId) === g.stream?.currentMessageSnapshot()?.replyToMessageId;
const O = b && g.stream && g.hasStreamedMessage && !g.finalized && m.trim().length > 0;
const streamText = async () => {
const n = C ?? m;
const r = v.hasMedia;
const i = !v.hasMedia && C !== void 0;
const o = g.stream;
if (!o || n.length === 0 || h.isError && !i) return;
if (g.finalized) {
o.forceNewMessage();
g.lastPartialText = "";
g.hasStreamedMessage = false;
g.finalized = false;
}
const s = n.trimEnd();
const c = y ? await resolveTranscriptBackedChannelFinalText({
payload: h,
finalText: s,
resolveCandidateText: async () => selectLongerFinalText({
finalText: s,
candidateTexts: [o.lastDeliveredText(), g.lastPartialText]
})
}) : s;
const l = b && h.presentation ? await e.resolveFinalPresentationText?.({
payload: h,
text: c
}) ?? c : c;
g.lastPartialText = l;
g.hasStreamedMessage = true;
g.finalized = false;
const f = o.lastDeliveredText() === l;
if (!f) {
if (b && u) o.update(l, {
onPlatformSendDispatch: u,
assertPlatformSendAuthorized: d
});
else o.update(l);
} else if (b) {
await u?.();
d?.();
}
if (b) {
if (f) await g.stream?.stop().catch(() => void 0);
else await g.stream?.stop();
} else {
await g.stream?.flush();
if (a) await o.waitForInFlight();
}
const p = o.messageId();
if (typeof p !== "number") {
if (b && o.sendMayHaveLanded(l)) {
const e = g.retainedPromptContextPages.length ? createAcceptedChannelDeliveryResult({ results: g.retainedPromptContextPages.map(({ messageId: e }) => ({ messageId: String(e) })) }) : void 0;
await recordRetainedPromptContextPages(g, _);
await _.fail();
return {
kind: "preview-retained",
deliveryResult: {
visibleReplySent: false,
...e,
suppression: { reason: "adapter_returned_no_identity" }
}
};
}
if (!b) {
const e = g.stream;
if (e) {
await e.discard();
e.forceNewMessage();
}
g.lastPartialText = "";
g.hasStreamedMessage = false;
g.finalized = false;
}
return;
}
if (b && o.lastDeliveredText() !== l) {
if (!g.retainedPromptContextPages.length || !o.remainingFinalContent()?.text.trimEnd()) _.invalidate();
return;
}
e.markDelivered();
const x = b || a ? o.currentMessageSnapshot() : void 0;
let S = false;
let w;
if (a && x) try {
await u?.();
d?.();
await e.editStreamMessage({
laneName: t,
messageId: p,
text: x.sourceText,
...x.sourceTextMode ? { textMode: x.sourceTextMode } : {},
buttons: a
});
S = true;
} catch (n) {
w = n;
e.log(`telegram: ${t} stream button edit failed: ${String(n)}`);
}
if (!b && w === void 0) return {
kind: "preview-updated",
deliveryResult: {
visibleReplySent: true,
receipt: createPreviewMessageReceipt({ id: p })
}
};
if (!x) {
if (b) _.invalidate();
return;
}
g.finalized = true;
const T = {
content: l,
messageId: p,
buttonsAttached: S,
receipt: createPreviewMessageReceipt({ id: p })
};
const E = {
visibleReplySent: true,
receipt: T.receipt,
content: l
};
try {
await recordRetainedPromptContextPages(g, _);
await _.accept({
messageId: p,
text: x.text
});
if (!r) await _.finish();
} catch (e) {
_.invalidate();
return {
kind: "preview-finalized-partial",
delivery: T,
deliveryResult: E,
error: e,
confirmedFinalContent: !w && !r ? true : void 0
};
}
return w ? {
kind: "preview-finalized-partial",
delivery: T,
deliveryResult: E,
error: w
} : {
kind: "preview-finalized",
delivery: T,
deliveryResult: E
};
};
const k = D && c && (!v.hasMedia || O) ? await streamText() : void 0;
if (k) {
if (!v.hasMedia || k.kind === "preview-finalized-partial") return k;
const t = k.kind === "preview-finalized" && k.delivery.buttonsAttached === true;
const n = k.kind === "preview-finalized" ? k.delivery.content : m;
try {
let r;
if (getReplyPayloadTtsSupplement(h)) r = buildTtsSupplementMediaPayload(applyTextToPayload(h, n));
else {
const { text: e, presentation: t, interactive: i, btw: a, ...o } = h.audioAsVoice === true ? applyTextToPayload(h, n) : h;
r = copyReplyPayloadMetadata(h, h.audioAsVoice === true ? {
...o,
spokenText: n
} : o);
}
if (t || a) {
const e = r.channelData ?? {};
const n = asOptionalRecord(e.telegram);
if (t && n && n.buttons !== void 0) {
const { buttons: t, ...i } = n;
const a = { ...e };
if (Object.keys(i).length > 0) a.telegram = i;
else delete a.telegram;
const { channelData: o, ...s } = r;
r = copyReplyPayloadMetadata(r, Object.keys(a).length > 0 ? {
...s,
channelData: a
} : s);
} else if (!t && a && !(n && "buttons" in n)) r = copyReplyPayloadMetadata(r, {
...r,
channelData: {
...e,
telegram: {
...n,
buttons: a
}
}
});
}
const i = await e.sendPayload(r, {
afterAcceptedDraft: true,
...S
});
const o = k.deliveryResult.suppression?.reason === "adapter_returned_no_identity" ? k.deliveryResult.suppression : i.suppression ?? k.deliveryResult.suppression;
return {
...k,
deliveryResult: {
...i.visibleReplySent ? createAcceptedChannelDeliveryResult({ deliveryResults: [k.deliveryResult, i] }) : k.deliveryResult,
...o ? { suppression: o } : {},
...i.deliveryIntent ? { deliveryIntent: i.deliveryIntent } : {}
}
};
} catch (e) {
if (x && k.kind === "preview-finalized") return {
...k,
kind: "preview-finalized-partial",
error: e
};
throw e;
}
}
const A = D && b && g.retainedPromptContextPages.length > 0 ? g.stream?.remainingFinalContent() : void 0;
const j = A !== void 0 || g.stream?.hasConsumedReplyTarget() === true;
if (b) {
await recordRetainedPromptContextPages(g, _);
await g.stream?.discard().catch((n) => {
e.log(`telegram: ${t} draft discard failed: ${String(n)}`);
});
}
const M = await e.sendPayload(applyTextToPayload(h, A?.sourceText ?? m), {
afterAcceptedDraft: j,
...S,
...A?.sourceTextMode === "html" ? { textMode: "html" } : {}
});
if (M.visibleReplySent && b && !y && g.stream && !g.finalized) {
await g.stream.clear();
g.lastPartialText = "";
g.hasStreamedMessage = false;
}
return {
kind: M.visibleReplySent ? "sent" : "skipped",
deliveryResult: M
};
};
}
//#endregion
//#region extensions/telegram/src/bot-message-dispatch-delivery.ts
const promptContextDeliverySignature = (e) => {
const t = createStructuredOutboundPayloadPlan([e])[0]?.payload;
return t ? resolveTelegramPromptContextDeliverySignature(t) : void 0;
};
function resolvePromptContextSource(e, t, ...n) {
const r = t ? projectPayloadForDelivery(e, { text: t.text }, t.openclawDelivery) : void 0;
const i = r ? promptContextDeliverySignature(r) : void 0;
if (!t?.messageId || !i) return;
return n.some((e) => promptContextDeliverySignature(e) === i) ? { transcriptMessageId: t.messageId } : void 0;
}
const createPromptContextSequence = (e, t) => createTelegramPromptContextProjectionSequence({
...t ? { source: t } : {},
record: async (t) => {
const { context: n } = e;
return await recordOutboundMessageForPromptContext({
cfg: e.cfg,
ownerAgentId: e.opts.ownerAgentId,
account: {
accountId: n.route.accountId,
...e.telegramCfg.name !== void 0 ? { name: e.telegramCfg.name } : {},
...n.primaryCtx.me ? { bot: n.primaryCtx.me } : {}
},
...n.primaryCtx.me?.id !== void 0 ? { botUserId: n.primaryCtx.me.id } : {},
chatId: String(n.chatId),
message: t.message ?? { message_id: t.messageId },
messageId: t.messageId,
...t.text ? { text: t.text } : {},
...t.projection ? { promptContextProjection: t.projection } : {},
...e.context.threadSpec.id !== void 0 ? { messageThreadId: e.context.threadSpec.id } : {},
successfulSendThread: e.context.threadSpec
});
}
});
function createDeliveryBaseOptions(e) {
const { context: t } = e;
return {
cfg: e.cfg,
ownerAgentId: e.opts.ownerAgentId,
chatId: String(t.chatId),
accountId: t.route.accountId,
sessionKeyForInternalHooks: t.ctxPayload.SessionKey,
mirrorIsGroup: t.isGroup,
mirrorGroupId: t.isGroup ? String(t.chatId) : void 0,
token: e.opts.token,
runtime: e.runtime,
bot: e.bot,
mediaLocalRoots: e.mediaLocalRoots,
mediaMaxBytes: (e.opts.mediaMaxMb ?? e.telegramCfg.mediaMaxMb ?? 100) * 1024 * 1024,
replyToMode: e.replyToMode,
textLimit: e.textLimit,
thread: e.context.threadSpec,
tableMode: e.tableMode,
chunkMode: e.chunkMode,
richMessages: e.richMessages,
linkPreview: e.telegramCfg.linkPreview,
replyQuoteMessageId: e.replyQuoteMessageId,
replyQuoteText: e.replyQuoteText,
replyQuotePosition: e.replyQuotePosition,
replyQuoteEntities: e.replyQuoteEntities,
replyQuoteByMessageId: e.replyQuoteByMessageId,
transcriptMirror: createTelegramTranscriptMirror(e)
};
}
async function sendPayload(e, t, n) {
if (n?.durable) e.finalDeliveryError = void 0;
if (e.isSuperseded()) {
await n?.promptContextSequence?.fail();
return {
visibleReplySent: false,
suppression: { reason: "channel_transform" }
};
}
const r = getGroupThreadDeliverySession();
const i = r ? {
...e,
context: {
...e.context,
route: {
...e.context.route,
...r
},
ctxPayload: {
...e.context.ctxPayload,
AgentId: r.agentId,
SessionKey: r.sessionKey,
RuntimePolicySessionKey: r.sessionKey
}
},
mediaLocalRoots: getAgentScopedMediaLocalRoots(e.cfg, r.agentId)
} : e;
const a = applyQuoteReplyTarget(i, t);
const o = parseStrictInteger(a.replyToId);
const s = o != null && o !== i.draftReplyToMessageId;
const c = n?.afterAcceptedDraft === true && isSingleUseReplyToMode(i.replyToMode) && !s;
const l = c ? copyReplyPayloadMetadata(a, (({ replyToId: e, replyToTag: t, replyToCurrent: n, ...r }) => r)(a)) : a;
const u = c ? "off" : i.replyToMode;
const d = n?.promptContextSequence ?? createPromptContextSequence(i, n?.durable ? resolvePromptContextSource(i, await i.resolveCurrentTurnTranscriptFinal(), l) : void 0);
const f = withTelegramPromptContextSource(l, d.source);
const p = n?.bindPendingFinalDelivery ? n.bindPendingFinalDelivery(f) : f;
const m = n?.silent ?? (i.telegramCfg.silentErrorReplies === true && t.isError === true);
if (n?.durable && d.isFresh()) {
const t = createStructuredOutboundPayloadPlan([p])[0];
if (!t) {
await d.fail();
return {
visibleReplySent: false,
suppression: { reason: "no_visible_payload" }
};
}
const r = await deliverStructuredInboundReplyWithMessageSendContext({
cfg: i.cfg,
prepareRuntimeHandoff: (e) => prepareTelegramFinalDeliveryConfig(e, i.context.route.accountId, i.opts.token),
channel: "telegram",
to: i.context.ctxPayload.OriginatingTo ?? i.context.ctxPayload.To ?? `telegram:${i.context.chatId}`,
accountId: i.context.route.accountId,
agentId: i.context.route.agentId,
ctxPayload: i.context.ctxPayload,
plan: t,
info: { kind: "final" },
retryAmbiguousFinalText: true,
replyToMode: u,
replyToId: p.replyToId ?? (i.draftReplyToMessageId !== void 0 ? String(i.draftReplyToMessageId) : null),
threadId: i.context.threadSpec.id,
formatting: {
textLimit: i.textLimit,
tableMode: i.tableMode,
chunkMode: i.chunkMode,
...n?.textMode === "html" ? { parseMode: "HTML" } : {}
},
silent: m,
requiredCapabilities: deriveDurableFinalDeliveryRequirements({
payload: p,
replyToId: p.replyToId,
threadId: i.context.threadSpec.id,
silent: m,
payloadTransport: true,
extraCapabilities: { nativeQuote: !c && usesNativeTelegramQuote(i, p) }
})
});
if (r.status === "failed") {
e.finalDeliveryError = r.error;
return await failPromptContextSequence(d, r.error);
}
if (r.status === "handled_visible") {
i.deliveryState.markDelivered();
return {
...r.delivery,
visibleReplySent: true
};
}
if (r.status === "handled_no_send") {
await d.fail();
return {
...r.delivery,
visibleReplySent: false
};
}
}
try {
const r = hasReplyPayloadFinalDeliveryCapture(t) ? void 0 : createTelegramTranscriptMirror(i, e);
const a = await deliverStructuredReplies({
...createDeliveryBaseOptions(i),
replyToMode: u,
transcriptMirror: n?.durable ? r : void 0,
replies: [p],
onMediaAccepted: n?.onMediaAccepted,
onVoiceRecording: i.context.sendRecordVoice,
silent: m,
mediaLoader: loadWebMedia,
promptContextSequence: d,
onPlatformSendDispatch: n?.onPlatformSendDispatch,
assertPlatformSendAuthorized: n?.assertPlatformSendAuthorized,
...n?.textMode ? { textMode: n.textMode } : {}
});
if (!a.delivered) {
await d.fail();
return {
visibleReplySent: false,
suppression: { reason: "no_visible_result" }
};
}
try {
await d.finish();
} catch (e) {
if (!a.receipt?.platformMessageIds.length) throw e;
if (n?.durable) await observeFinalDelivery(i, {
visibleReplySent: true,
receipt: a.receipt
});
throw mergeTelegramPartialDeliveryError(e, {
receipt: a.receipt,
messageIds: a.receipt.platformMessageIds,
visibleReplySent: true
});
}
i.deliveryState.markDelivered();
return {
visibleReplySent: true,
receipt: a.receipt
};
} catch (e) {
return await failPromptContextSequence(d, e);
}
}
async function handlePreviewFinalizedResult(e, t, n) {
if (t.kind !== "preview-finalized" && t.kind !== "preview-finalized-partial") return;
if (!e.isSuperseded()) {
emitTelegramMessageSentHooks({
sessionKeyForInternalHooks: e.context.ctxPayload.SessionKey,
chatId: String(e.context.chatId),
accountId: e.context.route.accountId,
content: t.delivery.content,
success: t.kind === "preview-finalized",
messageId: t.delivery.messageId,
isGroup: e.context.isGroup,
groupId: e.context.isGroup ? String(e.context.chatId) : void 0
});
const r = hasReplyPayloadFinalDeliveryCapture(n) ? void 0 : createTelegramTranscriptMirror(e);
if (r && t.delivery.content) r({ text: t.delivery.content }).catch((e) => {
logVerbose(`telegram preview-finalized transcriptMirror failed: ${formatErrorMessage(e)}`);
});
}
if (t.kind === "preview-finalized-partial") throw mergeTelegramPartialDeliveryError(t.error, {
...t.deliveryResult,
visibleReplySent: true
});
}
function registerTelegramQuestionDeliveryForMessage(e, t, n) {
const { chatId: r } = e.context;
const i = e.context.route.accountId;
const a = e.bot.api;
const o = e.cfg;
const s = e.telegramCfg.linkPreview;
const c = editMessageTelegram;
const { messageId: l, text: u } = n;
registerTelegramQuestionDelivery({
accountId: i,
chatId: String(r),
messageId: l,
payload: t,
text: u,
textLimit: e.textLimit,
clearButtons: async () => {
await editMessageReplyMarkupTelegram(r, l, [], {
api: a,
cfg: o,
accountId: i
});
},
annotate: async (e) => {
await c(r, l, e, {
api: a,
cfg: o,
accountId: i,
linkPreview: s
});
}
});
}
function recoverFinalPayload(e, t, n, r) {
const i = projectPayloadForDelivery(e, applyTextToPayload(t, n), r?.openclawDelivery);
return i ? copyTelegramDroppedControlFallback(t, deduplicateBlockSentMedia(preserveReplyPayloadMediaSelection(t, i), e.sentBlockMediaUrls)) : void 0;
}
async function observeFinalDelivery(e, t, n = false) {
if (t.visibleReplySent) e.deliveryState.markDelivered();
const r = t.suppression?.reason;
if (t.deliveryIntent || r === "adapter_returned_no_identity") e.finalDispatchClaimed = true;
if (r === "adapter_returned_no_identity" || r === "no_visible_result") e.previewLifecycle.observeFailure(t);
else if (t.visibleReplySent) await e.previewLifecycle.observeDelivery(t, { isError: n });
else if (t.suppression) e.previewLifecycle.observeSuppression();
else e.previewLifecycle.observeFailure(t);
}
async function deliverFinalAnswerText(e, t, n, r, i, a, o) {
e.previewLifecycle.beginFinalDelivery();
const s = await e.resolveCurrentTurnTranscriptFinal();
const c = await resolveTranscriptBackedChannelFinalText({
payload: t,
finalText: n,
resolveCandidateText: async () => s?.text
});
const l = c === n ? t : recoverFinalPayload(e, t, c, s);
if (!l) {
const t = {
visibleReplySent: false,
suppression: { reason: "channel_transform" }
};
await observeFinalDelivery(e, t);
return {
kind: "skipped",
deliveryResult: t
};
}
const u = c === n ? n : l.text ?? "";
const d = resolvePromptContextSource(e, s, t, applyTextToPayload(l, u));
const f = createPromptContextSequence(e, d);
const p = e.previewLifecycle.finalDelivered;
let m;
if (!p && e.streamMode === "progress") {
await e.answerLane.stream?.discard().catch((e) => {
logVerbose(`telegram progress discard failed: ${formatErrorMessage(e)}`);
});
const t = await sendPayload(e, applyTextToPayload(l, u), {
durable: true,
promptContextSequence: f,
onPlatformSendDispatch: i,
assertPlatformSendAuthorized: a,
bindPendingFinalDelivery: o
});
m = {
kind: t.visibleReplySent ? "sent" : "skipped",
deliveryResult: t
};
} else {
if (p) {
e.answerLane.stream?.forceNewMessage();
resetLaneState(e, e.answerLane);
} else if (!e.activeAnswerDraftIsToolProgressOnly) await rotateAnswerLaneAfterQueuedBlocksSettle(e);
m = await e.deliverLaneText({
laneName: "answer",
text: u,
payload: l,
infoKind: "final",
buttons: r,
allowStream: !e.activeAnswerDraftIsToolProgressOnly && (!usesNativeTelegramQuote(e, l) || e.replyQuoteText == null && parseStrictInteger(l.replyToId) === e.answerLane.stream?.currentMessageSnapshot()?.replyToMessageId),
promptContextSequence: f,
onPlatformSendDispatch: i,
assertPlatformSendAuthorized: a,
bindPendingFinalDelivery: o
});
}
if (m.kind === "preview-finalized-partial" && !m.confirmedFinalContent) e.previewLifecycle.observeFailure(m.deliveryResult);
else await observeFinalDelivery(e, m.deliveryResult, l.isError === true);
await handlePreviewFinalizedResult(e, m, l);
if (m.kind === "preview-finalized") registerTelegramQuestionDeliveryForMessage(e, l, {
messageId: m.delivery.messageId,
text: m.delivery.content
});
return m;
}
async function finalizePendingAnswerBlockDraft(e) {
const t = e.activeAnswerBlockDelivery;
if (!t || e.finalDispatchClaimed || e.dispatchError || e.previewLifecycle.finalStarted || e.isSuperseded() || e.answerLane.finalized) return;
const n = t.text.trimEnd();
if (!n) return;
await deliverFinalAnswerText(e, t.payload, n, t.buttons);
e.activeAnswerBlockDelivery = void 0;
}
async function deliverFallback(e, t, n) {
try {
const r = await deliverReplies({
replies: t,
...createDeliveryBaseOptions(e),
silent: n,
mediaLoader: loadWebMedia
});
if (r.delivered && !e.previewLifecycle.finalDelivered) await observeFinalDelivery(e, {
visibleReplySent: true,
receipt: r.receipt
}, true);
else if (r.delivered) e.deliveryState.markDelivered();
return r;
} catch (t) {
const n = isChannelPartialDeliveryError(t) ? t.deliveryResult : void 0;
e.previewLifecycle.observeFailure(n);
if (n) e.deliveryState.markDelivered();
e.runtime.error?.(`telegram fallback delivery failed: ${formatErrorMessage(t)}`);
return { delivered: n !== void 0 };
}
}
function createDeliveryState(e, t) {
const { context: n } = e;
const r = n.ctxPayload.SessionKey;
const i = n.ctxPayload.ReplyToIsQuote && !n.msg.reply_to_message?.from?.is_bot && e.replyQuoteMessageId != null ? String(e.replyQuoteMessageId) : void 0;
const a = i && n.ctxPayload.MessageSid ? n.ctxPayload.MessageSid : void 0;
const o = createLaneDeliveryStateTracker();
return {
deliveryState: o,
deliverLaneText: createLaneTextDeliverer({
lanes: e.lanes,
sendPayload: async (e, n) => await sendPayload(t(), e, n),
editStreamMessage: async ({ messageId: e, text: n, textMode: r, buttons: i }) => {
const a = t();
if (!a.isSuperseded()) await editMessageTelegram(a.context.chatId, e, n, {
api: a.bot.api,
cfg: a.cfg,
accountId: a.context.route.accountId,
linkPreview: a.telegramCfg.linkPreview,
textMode: r,
buttons: i
});
},
createPromptContextSequence: () => createPromptContextSequence(t()),
resolveFinalPresentationText: ({ payload: e, text: n }) => resolveFinalTelegramPresentationText({
payload: e,
text: n,
richMessages: t().richMessages,
allowWebAppButtons: resolveTelegramTargetChatType(String(t().context.chatId)) === "direct"
}),
resolveFinalPayloadCandidate: async ({ finalText: e, payload: n, candidateTexts: r }) => {
const i = t();
const a = await i.resolveCurrentTurnTranscriptFinal();
const o = selectLongerFinalText({
finalText: e,
candidateTexts: r
});
const s = await resolveTranscriptBackedChannelFinalText({
payload: n,
finalText: e,
resolveCandidateText: async () => a?.text
});
if (s === e) return;
const c = recoverFinalPayload(i, n, s, a);
return c && o && o.length > (c.text ?? "").trimEnd().length ? applyTextToPayload(c, o) : c;
},
log: logVerbose,
markDelivered: o.markDelivered
}),
materializeAnswerLaneBeforeRotation: async () => {
const e = t();
const n = e.activeAnswerBlockDelivery;
const r = e.answerLane;
if (!n || !r.stream || !r.hasStreamedMessage || r.finalized || e.activeAnswerDraftIsToolProgressOnly) return;
const i = r.lastPartialText || e.lastAnswerPartialText || n.text;
if (!i?.trim()) return;
const a = await e.deliverLaneText({
laneName: "answer",
text: i,
payload: n.payload,
infoKind: "block",
buttons: n.buttons,
finalizePreview: true,
durable: false
});
e.activeAnswerBlockDelivery = void 0;
await handlePreviewFinalizedResult(e, a, n.payload);
},
resolveCurrentTurnTranscriptFinal: n.ctxPayload.GroupThread ? async () => void 0 : createCurrentTurnTranscriptFinalResolver({
agentId: n.route.agentId,
dispatchStartedAt: e.dispatchStartedAt,
loadFreshSessionEntry: e.loadFreshSessionEntry,
sessionKey: r
}),
transcriptMirrorSequence: 0,
transcriptMirrorTurnId: `${n.chatId}:${n.ctxPayload.MessageSid ?? n.msg.message_id ?? e.dispatchStartedAt}`,
implicitQuoteReplyTargetId: i,
currentMessageIdForQuoteReply: a
};
}
//#endregion
//#region extensions/telegram/src/bot-message-dispatch-progress.ts
function buildTelegramProgressLine(e, t, n) {
return {
id: e,
kind: "item",
icon: t,
label: n,
text: `${t} ${n}`,
prefix: false
};
}
function buildTelegramTextToolProgressLine(e, t) {
return {
...t ? { id: t } : {},
kind: "item",
label: "",
text: e,
prefix: false
};
}
function createProgressState(e, t, n) {
const r = createChannelProgressDraftCompositor({
preparedItems: true,
showWorkStatus: true,
entry: e.telegramCfg,
mode: e.streamMode,
active: Boolean(t.answerLane.stream),
seed: `${e.context.route.accountId}:${e.context.chatId}:${e.context.threadSpec.id ?? ""}`,
reasoningGate: t.streamReasoningInProgressDraft,
reasoningLinePrefix: "🧠 ",
commentaryLinePrefix: "💬 ",
toolIcons: true,
compactToolRuns: true,
commentaryItalics: false,
updateOnLineChange: true,
shouldStartNow: (e) => typeof e !== "string" && Boolean(e?.toolName),
update: async (i, a) => {
if (e.streamMode === "progress" && !a.snapshot.statusHeadline && a.snapshot.lines.length === 0 && !a.snapshot.plan?.length && await n().verboseProgressActive()) return false;
await prepareAnswerLaneForToolProgress(n());
t.answerLane.lastPartialText = i;
t.answerLane.hasStreamedMessage = true;
t.answerLane.finalized = false;
t.answerLane.stream?.updatePreview(renderTelegramProgressDraftPreview(a.snapshot, {
toolProgress: r.previewToolProgressEnabled,
richMessages: e.richMessages,
maxLines: resolveChannelProgressDraftMaxLines(e.telegramCfg),
maxLineChars: resolveChannelProgressDraftMaxLineChars(e.telegramCfg)
}));
if (a.flush) await t.answerLane.stream?.flush();
},
deleteCurrent: async () => await retireAnswerLane(n(), "clear")
});
const i = [t.answerLane, t.reasoningLane];
const settleDraftLanes = async (e) => {
for (const t of i) if (e !== "clear" || !t.finalized) await t.stream?.[e]();
};
return {
verboseProgressActive: async () => false,
progressCompositor: r,
previewLifecycle: createLivePreviewLifecycle({
draft: i.some((e) => e.stream) ? {
flush: () => settleDraftLanes("flush"),
id: () => t.answerLane.stream?.messageId() ?? t.reasoningLane.stream?.messageId(),
discardPending: () => settleDraftLanes("discard"),
clear: () => settleDraftLanes("clear")
} : void 0,
cleanupUndelivered: true,
onFinalStarted: () => r.markFinalReplyStarted(),
onFinalDelivered: () => r.markFinalReplyDelivered(),
onCleanupFailure: (t) => e.runtime.error?.(`telegram preview cleanup failed: ${formatErrorMessage(t)}`)
}),
commentaryProgressEnabled: r.commentaryProgressEnabled,
progressPreambleEnabled: e.streamMode === "progress" && t.answerLane.stream ? true : void 0
};
}
async function settleFailedFinalDelivery(e) {
if (e.isSuperseded() || e.previewLifecycle.finalSucceeded || e.progressContinuationAdopted || e.context.ctxPayload.InboundEventKind === "room_event" || !e.previewLifecycle.finalFailed) return;
const t = hasTelegramNetworkErrorCode(e.finalDeliveryError) ? "I couldn't deliver my reply because of a network problem. Please ask again." : "I couldn't deliver my reply. Please ask again.";
const n = e.answerLane.stream;
const r = n?.messageId();
if (e.previewLifecycle.finalDelivered || !n || typeof r !== "number" || !Number.isFinite(r) || e.answerLane.finalized) {
await deliverFallback(e, [{
text: t,
isError: true
}], e.telegramCfg.silentErrorReplies === true);
return;
}
try {
await n.discard();
if (e.isSuperseded()) return;
await editMessageTelegram(e.context.chatId, r, t, {
api: e.bot.api,
cfg: e.cfg,
accountId: e.context.route.accountId,
linkPreview: e.telegramCfg.linkPreview
});
e.answerLane.finalized = true;
e.deliveryState.markDelivered();
await e.previewLifecycle.observeDelivery({
visibleReplySent: true,
receipt: createPreviewMessageReceipt({ id: r }),
content: t
}, { isError: true });
} catch (t) {
e.runtime.error?.(`telegram failed preview settlement: ${formatErrorMessage(t)}`);
}
}
/**
* Keeps a confirmed progress card after its turn for the owner that adopted it.
* The card keeps Telegram's rendering, throttling and deletion; only the
* adopting owner's prepared items reach it.
*/
function retainProgressDraft(e, t) {
let n = false;
const assertNotRetired = () => {
if (n) throw new TelegramRequestNotStartedError("Telegram retained progress retired");
};
const r = createChannelProgressDraftCompositor({
preparedItems: true,
showWorkStatus: true,
entry: e.telegramCfg,
mode: "progress",
active: true,
seed: `${e.context.route.accountId}:${e.context.chatId}:${e.context.threadSpec.id ?? ""}`,
reasoningGate: false,
toolIcons: true,
compactToolRuns: true,
updateOnLineChange: true,
initialSnapshot: e.progressCompositor.getSnapshot(),
update: (i, a) => {
if (n) return;
t.updatePreview(renderTelegramProgressDraftPreview(a.snapshot, {
toolProgress: r.previewToolProgressEnabled,
richMessages: e.richMessages,
maxLines: resolveChannelProgressDraftMaxLines(e.telegramCfg),
maxLineChars: resolveChannelProgressDraftMaxLineChars(e.telegramCfg)
}), assertNotRetired);
}
});
let i;
const enqueue = (t) => {
i = (i ?? r.start()).then(t).catch((t) => {
e.runtime.error?.(`telegram retained progress failed: ${formatErrorMessage(t)}`);
});
};
return {
push: (e) => enqueue(() => r.pushItemEvent(e)),
retire: () => {
n = true;
enqueue(async () => {
r.cancel();
await t.clear();
});
}
};
}
function canPushProgress(e) {
return Boolean(e.answerLane.stream && !e.isSuperseded() && !e.answerLane.finalized && !e.previewLifecycle.finalStarted);
}
async function canPushToolProgress(e) {
return !await e.verboseProgressActive() && canPushProgress(e);
}
function pushCompactionProgress(e, t) {
if (!e.answerLane.stream || e.answerLane.finalized || e.previewLifecycle.finalStarted) return Promise.resolve(false);
const n = {
start: "Compacting context...",
complete: "Compaction complete",
incomplete: "Compaction incomplete"
}[t];
return e.progressCompositor.pushToolProgress(buildTelegramProgressLine("context-compaction", "🧹", n), {
startImmediately: true,
flush: true
});
}
async function pushToolProgress(e, t, n) {
if (!await canPushToolProgress(e)) return false;
if (n?.id && e.progressCompositor.getSnapshot().lines.some((e) => typeof e === "object" && e.id === n.id)) return true;
return await e.progressCompositor.pushToolProgress(typeof t === "string" ? buildTelegramTextToolProgressLine(t, n?.id) : t, n);
}
async function pushThinkingTokenProgress(e, t) {
return await pushToolProgress(e, buildTelegramProgressLine("reasoning:token-progress", "🧠", `Thinking… (~${Math.round(t)} tokens)`), { startImmediately: true });
}
async function handleToolStart(e, t) {
const n = t.name?.trim();
const r = await e.verboseProgressActive();
let i;
if (canPushProgress(e)) {
if (!r) i = e.progressCompositor.pushToolEvent(t);
else if (e.streamMode === "progress" && isChannelProgressDraftWorkToolName(n)) i = e.progressCompositor.noteActivity();
}
if (e.statusReactionController && n) await e.statusReactionController.setTool(n);
return await i ?? false;
}
async function handleCompactionStart(e) {
const t = pushCompactionProgress(e, "start");
await e.statusReactionController?.setCompacting();
return await t;
}
async function handleCompactionEnd(e, t) {
const n = pushCompactionProgress(e, t?.completed === false ? "incomplete" : "complete");
e.statusReactionController?.cancelPending();
await e.statusReactionController?.setThinking();
return await n;
}
async function handleItemEvent(e, t) {
let n = false;
await enqueueDraftEvent(e, async () => {
if (e.previewLifecycle.finalStarted) return;
if (t.phase === "start" && t.kind === "tool" && e.answerLane.stream && e.streamMode !== "progress" && !e.activeAnswerDraftIsToolProgressOnly) {
await rotateAnswerLaneForNewMessage(e);
e.progressCompositor.resetActivity();
}
n = (t.kind === "preamble" || t.kind === "model-wait" || await canPushToolProgress(e)) && await e.progressCompositor.pushItemEvent(t);
});
return n;
}
async function handlePlanUpdate(e, t) {
return t.phase === "update" && await canPushToolProgress(e) ? await e.progressCompositor.pushPlanProgress(t.steps, {
explanation: t.explanation,
explanationFormat: t.explanationFormat
}) : false;
}
//#endregion
//#region extensions/telegram/src/error-policy.ts
const errorCooldownStore = /* @__PURE__ */ new Map();
const DEFAULT_ERROR_COOLDOWN_MS = 144e5;
function pruneExpiredCooldowns(e, t, n) {
for (const [e, r] of t) if (r <= n) t.delete(e);
if (t.size === 0) errorCooldownStore.delete(e);
}
function resolveTelegramErrorPolicy(e) {
return {
policy: e.topicConfig?.errorPolicy || e.groupConfig?.errorPolicy || e.accountConfig?.errorPolicy || "always",
cooldownMs: DEFAULT_ERROR_COOLDOWN_MS
};
}
function buildTelegramErrorScopeKey(e) {
return `${e.accountId}:${buildTelegramGroupPeerId(e.chatId, e.threadSpec ?? { scope: "none" })}`;
}
function shouldSuppressTelegramError(e) {
const { scopeKey: t, cooldownMs: n, errorMessage: r } = e;
const i = Date.now();
const a = r ?? "";
const o = errorCooldownStore.get(t);
if (o) pruneExpiredCooldowns(t, o, i);
if (errorCooldownStore.size > 100) for (const [e, t] of errorCooldownStore) pruneExpiredCooldowns(e, t, i);
const s = o?.get(a);
if (s !== void 0 && s > i) return true;
const c = o ?? /* @__PURE__ */ new Map();
c.set(a, i + n);
errorCooldownStore.set(t, c);
return false;
}
//#endregion
//#region extensions/telegram/src/bot-message-dispatch-reply.ts
function toTelegramReplyDeliveryResult(e, t, n, r) {
const i = {
...r,
visibleReplySent: t || (r?.visibleReplySent ?? false),
...n ? { finalization: n } : {}
};
if (!r && !n && !t) i.suppression = { reason: e.previewLifecycle.finalSuppressed ? "channel_transform" : "no_visible_result" };
return i;
}
function toTelegramVisiblePartialDeliveryError(e) {
return isChannelPartialDeliveryError(e) ? e : createChannelPartialDeliveryError(e, { visibleReplySent: true });
}
function resolvePayloadTelegramControls(e, t) {
const n = t.channelData?.telegram;
const r = [];
const i = resolveTelegramInlineButtons({
buttons: n?.buttons,
presentation: normalizeMessagePresentation(t.presentation),
interactive: t.interactive
}, {
allowWebAppButtons: resolveTelegramTargetChatType(String(e.context.chatId)) === "direct",
supportsDisabled: e.richMessages,
onDroppedControl: (e) => r.push(e),
questionOptionIndices: resolveAskUserQuestionOptionIndices(t)
});
const a = appendTelegramDroppedControlFallback(t.text ?? "", r);
const o = appendTelegramDroppedControlFallback("", r);
const s = a === (t.text ?? "") ? t : applyTextToPayload(t, a);
return {
payload: o ? markTelegramDroppedControlFallback(s, a === o ? "" : a.slice(0, -o.length - 2), a) : s,
buttons: i
};
}
function createReplyState() {
return {
reasoningStepState: createTelegramReasoningStepState(),
bufferedFinalSettlement: void 0,
sentBlockMediaUrls: /* @__PURE__ */ new Set(),
splitReasoningOnNextStream: false
};
}
function settleBufferedFinalAsNotVisible(e) {
if (e.bufferedFinalSettlement) e.bufferedFinalSettlement.resolve({ visibleReplySent: e.bufferedFinalSettlement.visibleReplySent });
e.bufferedFinalSettlement = void 0;
}
function resetReasoningStepState(e) {
settleBufferedFinalAsNotVisible(e);
e.reasoningStepState.resetForNextStep();
}
async function flushBufferedFinalAnswer(e, t = false) {
const n = e.bufferedFinalSettlement;
const r = e.reasoningStepState.takeBufferedFinalAnswer();
e.bufferedFinalSettlement = void 0;
if (!r) {
n?.resolve({ visibleReplySent: n.visibleReplySent });
e.reasoningStepState.resetForNextStep();
return;
}
try {
const t = resolvePayloadTelegramControls(e, r);
const i = await deliverFinalAnswerText(e, t.payload, t.payload.text ?? "", t.buttons, n?.onPlatformSendDispatch, n?.assertPlatformSendAuthorized, n?.bindPendingFinalDelivery);
if (n) n.resolve({
...i.deliveryResult,
visibleReplySent: n.visibleReplySent || i.deliveryResult.visibleReplySent
});
resetReasoningStepState(e);
} catch (e) {
if (n) n.reject(n.visibleReplySent ? toTelegramVisiblePartialDeliveryError(e) : e);
throw t ? toTelegramVisiblePartialDeliveryError(e) : e;
}
}
async function settleTerminalNoVisibleDelivery(e, t, n) {
if (n?.abandonBufferedFinal) resetReasoningStepState(e);
else if (t.kind === "final") await flushBufferedFinalAnswer(e);
return toTelegramReplyDeliveryResult(e, false);
}
async function adoptProgressDraft(e, t, n) {
if (n.kind !== "final" || t.isError === true || typeof n.adoptProgressDraft !== "function") return false;
const r = n.adoptProgressDraft;
const i = e.answerLane.stream;
if (!i || e.answerLane.finalized || e.isSuperseded()) return false;
await n.onPlatformSendDispatch?.();
if (!e.progressCompositor.isVisible && !e.progressCompositor.hasStarted && (e.progressCompositor.hasStatusHeadline || e.progressCompositor.hasPlanProgress || e.progressCompositor.getSnapshot().lines.length > 0)) {
n.assertPlatformSendAuthorized?.();
await e.progressCompositor.start();
}
if (!e.progressCompositor.isVisible || e.isSuperseded()) return false;
e.progressCompositor.cancel();
n.assertPlatformSendAuthorized?.();
await i.flush();
const a = i.messageId();
const o = i.lastDeliveredText();
if (typeof a !== "number" || !Number.isFinite(a) || !o || i.isStopped() || e.isSuperseded()) return false;
n.assertPlatformSendAuthorized?.();
if (!r(retainProgressDraft(e, i))) return false;
e.answerLane.stream = void 0;
e.progressContinuationAdopted = true;
resetLaneState(e, e.answerLane);
resetReasoningStepState(e);
e.deliveryState.markDelivered();
return true;
}
async function deliverReply(e, t, n) {
return deliverReplyWithNormalization(e, t, n, normalizeDeliveryPayload);
}
async function deliverPreparedReply(e, t, n) {
return deliverReplyWithNormalization(e, t.payload, n, normalizePreparedDeliveryPayload);
}
async function deliverReplyWithNormalization(e, t, n, r) {
if (e.isSuperseded()) return await settleTerminalNoVisibleDelivery(e, n, { abandonBufferedFinal: true });
let i = t;
if (n.participant && (i.text || i.mediaUrl || i.mediaUrls?.length)) i = applyTextToPayload(i, formatTelegramGroupThreadReply(i.text ?? "", n.participant));
const a = r(e, i);
if (!a) return await settleTerminalNoVisibleDelivery(e, n);
const o = n.kind === "final" ? deduplicateBlockSentMedia(a, e.sentBlockMediaUrls) : a;
if (!o) return await settleTerminalNoVisibleDelivery(e, n);
const s = resolvePayloadTelegramControls(e, o);
const c = s.payload;
const l = n.kind === "block" ? (t) => trackBlockMedia(e.sentBlockMediaUrls, c, t) : void 0;
if (shouldSuppressLocalTelegramExecApprovalPrompt({
cfg: e.cfg,
accountId: e.context.route.accountId,
payload: c
})) {
e.suppressSilentReplyFallback = true;
return await settleTerminalNoVisibleDelivery(e, n);
}
const u = s.buttons;
const d = resolveSendableOutboundReplyParts(c);
const f = c.channelData?.execApproval !== void 0;
const p = d.hasMedia || u !== void 0 || f;
if (!p && c.interactive === void 0 && c.presentation === void 0 && c.channelData?.askUser === void 0 && await adoptProgressDraft(e, t, n)) return toTelegramReplyDeliveryResult(e, true);
const m = n.kind === "block" && typeof i.text === "string" && typeof c.text === "string" && i.text !== c.text && i.text.trimEnd() === c.text && !c.mediaUrl && !c.mediaUrls?.length ? applyTextToPayload(c, i.text) : c;
const h = splitTextIntoLaneSegments(e, m.text, i.isReasoning);
const { segment: g } = h;
if (n.kind === "final" && (d.text.length > 0 || d.hasMedia)) e.previewLifecycle.beginFinalDelivery();
if (n.kind === "final" && c.isStatusNotice === true) {
await e.materializeAnswerLaneBeforeRotation();
const t = await sendPayload(e, c, {
durable: true,
onPlatformSendDispatch: n.onPlatformSendDispatch,
assertPlatformSendAuthorized: n.assertPlatformSendAuthorized,
bindPendingFinalDelivery: n.bindPendingFinalDelivery
});
await observeFinalDelivery(e, t, c.isError === true);
return toTelegramReplyDeliveryResult(e, t.visibleReplySent, void 0, t);
}
const _ = n.kind === "tool" && e.previewLifecycle.finalStarted;
const v = isReplyPayloadNonTerminalToolErrorWarning(i) && e.previewLifecycle.finalDelivered;
if ((_ || v) && !d.hasMedia && !f) return await settleTerminalNoVisibleDelivery(e, n);
if (i.isError === true) e.hadErrorReplyFailureOrSkip = true;
if (n.kind === "block" && g?.lane !== "answer") dropQueuedAnswerBlockRotation(e, c, n.assistantMessageIndex);
if (g) {
if (g.lane === "answer" && n.kind === "final" && e.reasoningStepState.shouldBufferFinalAnswer()) {
const t = createDeferred();
settleBufferedFinalAsNotVisible(e);
e.bufferedFinalSettlement = {
visibleReplySent: false,
onPlatformSendDispatch: n.onPlatformSendDispatch,
assertPlatformSendAuthorized: n.assertPlatformSendAuthorized,
bindPendingFinalDelivery: n.bindPendingFinalDelivery,
resolve: t.resolve,
reject: t.reject
};
e.reasoningStepState.bufferFinalAnswer(applyTextToPayload(c, g.text));
return toTelegramReplyDeliveryResult(e, false, t.promise);
}
if (g.lane === "reasoning") e.reasoningStepState.noteReasoningHint();
if (g.lane === "answer" && n.kind === "tool") {
const t = await e.verboseProgressActive();
if (e.isSuperseded()) return await settleTerminalNoVisibleDelivery(e, n, { abandonBufferedFinal: true });
if (t) return toTelegramReplyDeliveryResult(e, (await sendPayload(e, applyTextToPayload(c, g.text))).visibleReplySent);
const r = !p && c.channelData?.askUser === void 0;
const i = isFastModeAutoProgressPayload(c);
if (e.streamMode === "progress") {
if (r && e.answerLane.stream && !i) return toTelegramReplyDeliveryResult(e, false);
if ((r || i) && await pushToolProgress(e, g.text, { startImmediately: true })) return toTelegramReplyDeliveryResult(e, true);
}
await prepareAnswerLaneForToolProgress(e);
}
const t = isQueuedAnswerBlock(e, m, n.assistantMessageIndex);
const r = e.streamMode === "partial" && n.kind === "block" && i.textMode !== "delta" && g.lane === "answer" && !p && e.answerLane.hasStreamedMessage && !e.activeAnswerDraftIsToolProgressOnly && !t && g.text.trimEnd() === e.answerLane.lastPartialText.trimEnd();
const a = e.streamMode === "progress" && Boolean(e.answerLane.stream) && n.kind === "block" && g.lane === "answer" && !p;
if (r || a) {
e.activeAnswerBlockDelivery = {
payload: c,
text: i.textMode === "delta" ? (e.activeAnswerBlockDelivery?.text ?? "") + (e.activeAnswerBlockDelivery?.text ? stripReplyPayloadResponsePrefix(c, g.text) : g.text) : g.text,
buttons: u
};
e.activeAnswerDraftIsToolProgressOnly = false;
if (!a) e.progressCompositor.resetActivity();
return toTelegramReplyDeliveryResult(e, !a);
}
if (g.lane === "answer" && n.kind === "block") {
const t = await prepareAnswerLaneForText(e);
const r = takeQueuedAnswerBlockRotation(e, m, n.assistantMessageIndex);
if (e.streamMode !== "progress" && r && !t) {
await rotateAnswerLaneForNewMessage(e);
e.rotateAnswerLaneWhenQueuedBlocksSettle = false;
}
e.activeAnswerDraftIsToolProgressOnly = false;
e.progressCompositor.resetActivity();
}
const o = c.channelData?.askUser !== void 0;
const s = n.kind === "block" && g.lane === "answer" && Boolean(e.answerLane.stream) && !p && !c.isError && !c.presentation && !c.interactive && !o && isReplyPayloadTerminalContent(c);
const d = s && c.textMode === "delta" ? e.lastAnswerPartialText + (e.lastAnswerPartialText ? stripReplyPayloadResponsePrefix(c, g.text) : g.text) : g.text;
if (s) e.lastAnswerPartialText = d;
const f = g.lane === "answer" && n.kind === "final" ? await deliverFinalAnswerText(e, c, g.text, u, n.onPlatformSendDispatch, n.assertPlatformSendAuthorized, n.bindPendingFinalDelivery) : await e.deliverLaneText({
laneName: g.lane,
text: d,
payload: m,
infoKind: n.kind,
buttons: u,
...o ? { finalizePreview: true } : {},
onPlatformSendDispatch: n.onPlatformSendDispatch,
assertPlatformSendAuthorized: n.assertPlatformSendAuthorized,
bindPendingFinalDelivery: n.bindPendingFinalDelivery,
onMediaAccepted: l
});
if (g.lane === "answer" && n.kind !== "final" && (f.kind === "preview-finalized" || f.kind === "preview-finalized-partial")) {
await handlePreviewFinalizedResult(e, f, m);
if (o && f.kind === "preview-finalized") registerTelegramQuestionDeliveryForMessage(e, c, {
messageId: f.delivery.messageId,
text: f.delivery.content
});
}
if (g.lane === "answer" && n.kind === "block" && f.kind === "preview-updated") e.activeAnswerBlockDelivery = {
payload: m,
text: d,
buttons: u
};
if (g.lane === "reasoning") {
if (f.deliveryResult.visibleReplySent) {
e.reasoningStepState.noteReasoningDelivered();
await flushBufferedFinalAnswer(e, true);
}
} else if (n.kind === "final") resetReasoningStepState(e);
return toTelegramReplyDeliveryResult(e, f.deliveryResult.visibleReplySent, void 0, n.kind === "final" && g.lane === "answer" ? f.deliveryResult : void 0);
}
if (n.kind === "final") {
await e.answerLane.stream?.stop();
await e.reasoningLane.stream?.stop();
await flushBufferedFinalAnswer(e);
}
if (h.suppressedReasoningOnly && !d.hasMedia) return toTelegramReplyDeliveryResult(e, false, void 0, { visibleReplySent: false });
if (!d.hasMedia && d.text.length === 0) {
if (n.kind === "final") await flushBufferedFinalAnswer(e);
return toTelegramReplyDeliveryResult(e, false);
}
const y = h.suppressedReasoningOnly && typeof c.text === "string" ? applyTextToPayload(c, "") : c;
const b = await sendPayload(e, y, {
durable: n.kind === "final",
onPlatformSendDispatch: n.onPlatformSendDispatch,
assertPlatformSendAuthorized: n.assertPlatformSendAuthorized,
bindPendingFinalDelivery: n.bindPendingFinalDelivery,
onMediaAccepted: l
});
if (n.kind === "final") await observeFinalDelivery(e, b, c.isError === true);
return toTelegramReplyDeliveryResult(e, b.visibleReplySent, void 0, b);
}
function handleReplySkip(e, t, n) {
if (n.kind === "final" && n.reason === "silent") e.previewLifecycle.observeSuppression();
if (n.kind === "block") enqueueDraftEvent(e, async () => {
dropQueuedAnswerBlockRotation(e, t, n.assistantMessageIndex);
});
if (t.isError === true) e.hadErrorReplyFailureOrSkip = true;
if (n.reason !== "silent") e.deliveryState.markNonSilentSkip();
}
function handleReplyError(e, t, n) {
if (n.kind === "final") {
e.finalDeliveryError = t;
e.previewLifecycle.observeFailure(isChannelPartialDeliveryError(t) ? t.deliveryResult : void 0);
if (isChannelPartialDeliveryError(t)) e.deliveryState.markDelivered();
}
const r = resolveTelegramErrorPolicy({
accountConfig: e.telegramCfg,
groupConfig: e.context.groupConfig,
topicConfig: e.context.topicConfig
});
if (r.policy === "silent") return;
if (r.policy === "once" && shouldSuppressTelegramError({
scopeKey: buildTelegramErrorScopeKey({
accountId: e.context.route.accountId,
chatId: e.context.chatId,
threadSpec: e.context.threadSpec
}),
cooldownMs: r.cooldownMs,
errorMessage: String(t)
})) return;
e.deliveryState.markNonSilentFailure();
e.runtime.error?.(danger(`telegram ${n.kind} reply failed: ${String(t)}`));
}
//#endregion
//#region extensions/telegram/src/bot-loop-protection.ts
/**
* Whether a bot wrote this message as itself. The Bot API marks a message sent on behalf of
* a chat with `sender_chat`; in a group its `from` is then a backward-compatibility
* placeholder, and a channel post may have no `from` at all, in which case the channel_post
* pipeline stamps the channel itself. Neither names the author, so anonymous admins,
* linked-channel forwards and unattributed channel posts never count, and two bots that
* only post as a channel are not bounded here. A channel post that does carry a bot `from`
* still counts.
*/
function isOtherBotAuthor(e, t) {
const n = e.from;
if (n?.is_bot !== true || n.id === t) return false;
const r = e.sender_chat;
if (n.id === r?.id || e.chat.type !== "private" && n.id === e.chat.id) return false;
return !r || r.type === "channel" && r.id === e.chat.id;
}
/**
* Bot-pair facts for the core turn runner, or undefined when this turn is not another
* bot's message. Core records the pair and drops the turn before session record and
* dispatch once the pair exceeds its budget; Telegram only identifies the two bots.
*
* Telegram declares no channel or account override, so only
* `channels.defaults.botLoopProtection` applies, as for Feishu.
*/
function resolveTelegramBotLoopProtection(e) {
const t = e.msg.from;
if (!t || e.botUserId == null || !isOtherBotAuthor(e.msg, e.botUserId)) return;
return {
scopeId: e.accountId,
conversationId: String(e.msg.chat.id),
senderId: String(t.id),
receiverId: String(e.botUserId),
eventId: String(e.msg.message_id),
defaultsConfig: e.cfg.channels?.defaults?.botLoopProtection,
defaultEnabled: true,
nowMs: e.msg.date * 1e3
};
}
//#endregion
//#region extensions/telegram/src/bot-message-dispatch-turn.ts
const TELEGRAM_MAX_CONSECUTIVE_TYPING_FAILURES = 5;
async function runTelegramDispatchTurn(e) {
const { context: t } = e;
const n = { value: false };
const r = t.ctxPayload.InboundEventKind === "room_event";
const i = e.streamMode !== "off" && resolveChannelStreamingPreviewToolProgress(e.telegramCfg, true, e.streamMode);
const beginDeliveryCorrelation = () => telegramInboundEventDelivery.begin(t.ctxPayload.SessionKey, {
outboundTo: t.historyKey || String(t.chatId),
outboundAccountId: t.route.accountId,
markInboundEventDelivered: e.deliveryState.markDelivered
}, { inboundEventKind: t.ctxPayload.InboundEventKind });
const a = beginDeliveryCorrelation();
const queueDraftProgress = (t) => enqueueDraftEvent(e, t).then(() => false);
try {
const { onModelSelected: a, ...o } = createChannelReplyPipeline({
cfg: e.cfg,
agentId: t.route.agentId,
channel: "telegram",
accountId: t.route.accountId,
typing: {
start: t.sendTyping,
keepaliveIntervalMs: TELEGRAM_CHAT_ACTION_INTERVAL_MS,
maxDurationMs: 0,
maxConsecutiveFailures: TELEGRAM_MAX_CONSECUTIVE_TYPING_FAILURES,
onStartError: (e) => {
logTypingFailure({
log: logVerbose,
channel: "telegram",
target: String(t.chatId),
error: e
});
}
}
});
const s = await runChannelInboundEvent({
channel: "telegram",
accountId: t.route.accountId,
raw: t,
adapter: {
ingest: () => ({
id: t.ctxPayload.MessageSid ?? `${t.chatId}:${Date.now()}`,
timestamp: typeof t.ctxPayload.Timestamp === "number" ? t.ctxPayload.Timestamp : void 0,
rawText: t.ctxPayload.RawBody ?? "",
textForAgent: t.ctxPayload.BodyForAgent,
textForCommands: t.ctxPayload.CommandBody,
raw: t
}),
resolveTurn: () => ({
cfg: e.cfg,
channel: "telegram",
accountId: t.route.accountId,
route: {
agentId: t.route.agentId,
sessionKey: t.route.sessionKey
},
ctxPayload: t.ctxPayload,
record: t.turn.record,
botLoopProtection: resolveTelegramBotLoopProtection({
cfg: e.cfg,
accountId: t.route.accountId,
msg: t.msg,
botUserId: t.primaryCtx.me?.id
}),
dispatchReplyFromConfig: e.opts.dispatchReplyFromConfig,
delivery: {
deliverWithProviderMessageSending: (t, n) => enqueueDraftEvent(e, () => deliverReply(e, t, n), "delivery"),
deliverPreparedWithProviderMessageSending: (t, n) => enqueueDraftEvent(e, () => deliverPreparedReply(e, t, n), "delivery"),
onError: (t, n) => handleReplyError(e, t, n),
onDelivered: (t, n, r) => {
const i = r?.suppression?.reason;
if (n.kind === "final" && !e.previewLifecycle.finalFailed && (i === "cancelled_by_reply_payload_sending_hook" || i === "empty_after_reply_payload_sending_hook")) e.previewLifecycle.observeSuppression();
}
},
dispatcherOptions: {
...o,
humanDelay: resolveHumanDelayConfig(e.cfg, t.route.agentId),
beforeDeliver: async (e) => e,
onBeforeDeliverCancelled: (t, n) => n.kind === "block" ? enqueueDraftEvent(e, async () => {
dropQueuedAnswerBlockRotation(e, t, n.assistantMessageIndex);
}) : void 0,
onSkip: (t, n) => handleReplySkip(e, t, n)
},
replyOptions: {
hasRepliedRef: n,
onPreparedAgentRunStart: ({ runId: t }) => {
e.transcriptMirrorRunId = t;
},
...t.ctxPayload.CommandSource === "native" ? { [PLUGIN_COMMAND_DISPATCH]: { kind: "non-plugin" } } : {},
groupThreadReplyFormatter: formatTelegramGroupThreadReply,
skillFilter: t.skillFilter,
disableBlockStreaming: e.disableBlockStreaming,
preserveProgressCallbackStartOrder: true,
abortSignal: e.turnAdoptionLifecycle?.abortSignal,
turnAdoptionLifecycle: e.turnAdoptionLifecycle ? {
...e.turnAdoptionLifecycle,
admission: e.turnAdoptionLifecycle.admission ?? "exclusive"
} : void 0,
sourceReplyDeliveryMode: r ? "message_tool_only" : void 0,
queuedDeliveryCorrelations: r ? [{ begin: beginDeliveryCorrelation }] : void 0,
suppressTyping: r,
onObservedReplyDelivery: async () => {
e.previewLifecycle.beginFinalDelivery();
await e.draftEventQueue;
e.deliveryState.markDelivered();
await e.previewLifecycle.observeDelivery({ visibleReplySent: true });
},
onPartialReply: e.answerLane.stream || e.reasoningLane.stream ? (t) => {
return enqueueDraftEvent(e, async () => {
await ingestDraftLaneSegments(e, t);
}).then(async () => {
const t = e.answerLane.stream;
await t?.waitForInFlight();
const n = t?.messageId();
return typeof n === "number" && Number.isFinite(n);
});
} : void 0,
onBlockReplyQueued: e.answerLane.stream ? (t, n) => queueDraftProgress(() => prepareQueuedAnswerBlock(e, t, n)) : void 0,
onReasoningStream: e.reasoningLane.stream ? (t) => queueDraftProgress(async () => {
if (e.splitReasoningOnNextStream) {
repositionLaneForNewMessage(e, e.reasoningLane);
e.splitReasoningOnNextStream = false;
}
await ingestDraftLaneSegments(e, t, true);
}) : e.streamReasoningInProgressDraft ? (t) => queueDraftProgress(async () => {
await e.progressCompositor.pushReasoningProgress(t.text, { snapshot: t.isReasoningSnapshot === true });
}) : void 0,
onReasoningProgress: e.answerLane.stream ? (t) => enqueueDraftEvent(e, async () => {
await pushThinkingTokenProgress(e, t.progressTokens);
}) : void 0,
onAssistantMessageStart: e.answerLane.stream ? () => queueDraftProgress(async () => {
resetReasoningStepState(e);
const t = e.previewLifecycle.finalDelivered;
e.previewLifecycle.reset();
e.finalDispatchClaimed = false;
e.progressCompositor.beginAssistantMessage();
if (e.answerLane.finalized) {
await rotateLaneForNewMessage(e, e.answerLane);
e.rotateAnswerLaneWhenQueuedBlocksSettle = false;
} else if (t) {
e.answerLane.stream?.forceNewMessage();
resetLaneState(e, e.answerLane);
e.rotateAnswerLaneWhenQueuedBlocksSettle = false;
} else if (e.answerLane.hasStreamedMessage && !e.activeAnswerDraftIsToolProgressOnly && (e.activeAnswerBlockDelivery || e.queuedAnswerBlockRotations.length > 0)) e.rotateAnswerLaneWhenQueuedBlocksSettle = true;
}) : void 0,
onReasoningEnd: e.reasoningLane.stream ? () => queueDraftProgress(async () => {
e.splitReasoningOnNextStream = e.reasoningLane.hasStreamedMessage;
e.progressCompositor.resetReasoningProgress();
}) : () => false,
onQueuedFollowupAdmitted: () => {
n.value = false;
beginDraftQueuedFollowup(e);
e.previewLifecycle.reset();
e.finalDispatchClaimed = false;
e.progressCompositor.beginNewTurn({ force: true });
},
onQueuedFollowupSettled: async () => {
e.progressCompositor.cancel();
await e.draftEventQueue;
await cleanupDrafts(e, e.isSuperseded());
},
suppressDefaultToolProgressMessages: !e.streamDeliveryEnabled || Boolean(e.answerLane.stream),
progressRequiresReply: e.streamMode === "progress" ? true : void 0,
suppressToolProgressMessages: !i,
allowProgressCallbacksWhenSourceDeliverySuppressed: !r && Boolean(e.answerLane.stream),
onVerboseProgressVisibilityAsync: (t) => {
e.verboseProgressActive = t;
},
commentaryProgressEnabled: e.streamMode === "progress" ? e.commentaryProgressEnabled : void 0,
progressPreambleEnabled: e.progressPreambleEnabled,
commentaryPayloadsEnabled: e.progressPreambleEnabled,
shouldDeliverCommentaryPayloads: e.progressPreambleEnabled === true ? () => false : void 0,
reasoningPayloadsEnabled: e.durableReasoningPayloadsEnabled,
onToolStart: (t) => enqueueDraftEvent(e, () => handleToolStart(e, t)),
onItemEvent: (t) => handleItemEvent(e, t),
onPlanUpdate: (t) => enqueueDraftEvent(e, () => handlePlanUpdate(e, t)),
onApprovalEvent: (t) => enqueueDraftEvent(e, async () => await canPushToolProgress(e) ? await e.progressCompositor.pushApprovalEvent(t) : false),
onToolResult: (t) => enqueueDraftEvent(e, async () => {
const n = t.text?.trim();
if (!n) return false;
const r = t.channelData?.openclawToolProgressId;
if (await pushToolProgress(e, n, {
startImmediately: true,
id: typeof r === "string" ? r : void 0
})) return true;
if (isFastModeAutoProgressPayload(t) && !await canPushToolProgress(e)) return (await sendPayload(e, t)).visibleReplySent;
return false;
}),
onCompactionStart: r ? void 0 : () => enqueueDraftEvent(e, () => handleCompactionStart(e)),
onCompactionEnd: r ? void 0 : (t) => enqueueDraftEvent(e, () => handleCompactionEnd(e, t)),
onModelSelected: a
}
})
}
});
if (!s.dispatched) {
if (s.admission.kind === "drop" && s.admission.reason === "bot-loop-protection") e.runtime.log?.(warn(`telegram: bot-loop protection dropped message ${t.msg.message_id} from bot ${t.msg.from?.id} in chat ${t.chatId} (account ${t.route.accountId})`));
return false;
}
e.finalDispatchClaimed ||= s.dispatchResult.queuedFinal || (s.dispatchResult.settledReceipt?.counts.final.failedAfterSend ?? 0) > 0;
e.agentRunFailed = readAgentRunTerminalOutcome(s.dispatchResult) === "failed";
e.sendPolicyDenied = s.dispatchResult.sendPolicyDenied === true;
e.noVisibleReplyFallbackEligible = s.dispatchResult.noVisibleReplyFallbackEligible === true;
e.suppressSilentReplyFallback ||= s.dispatchResult.sourceReplyDeliveryMode === "message_tool_only";
if (s.dispatchResult.deliberateSilentTerminalReply) e.previewLifecycle.observeSuppression();
return true;
} finally {
a();
}
}
//#endregion
//#region extensions/telegram/src/bot-message-dispatch.ts
const EMPTY_RESPONSE_FALLBACK = "No response generated. Please try again.";
const silentReplyDispatchLogger = createSubsystemLogger("telegram/silent-reply-dispatch");
function includeStickerDescription(e) {
if (!e.body?.trim()) return e.formattedDescription;
if (e.body.includes(e.formattedDescription)) return e.body;
return `${e.formattedDescription}\n${e.body}`;
}
async function prepareTelegramSticker(e) {
const { context: t } = e;
const n = t.ctxPayload.Sticker;
const r = t.ctxPayload.media?.find((e) => e.kind === "sticker");
const i = r?.path ?? (!r && t.ctxPayload.StickerMediaIncluded ? t.ctxPayload.media?.[0]?.path : void 0);
if (!n?.fileId || !n.fileUniqueId || !i) return;
const a = resolveAgentDir(e.cfg, t.route.agentId);
const o = await resolveStickerVisionSupport({
cfg: e.cfg,
agentId: t.route.agentId
});
const s = n.cachedDescription || await describeStickerImage({
imagePath: i,
cfg: e.cfg,
agentDir: a,
agentId: t.route.agentId
});
if (!s) return;
const c = [n.emoji, n.setName ? `from "${n.setName}"` : null].filter(Boolean).join(" ");
const l = `[Sticker${c ? ` ${c}` : ""}] ${s}`;
n.cachedDescription = s;
if (!o) {
t.ctxPayload.Body = includeStickerDescription({
body: t.ctxPayload.Body,
formattedDescription: l
});
t.ctxPayload.agentText = includeStickerDescription({
body: t.ctxPayload.agentText ?? t.ctxPayload.BodyForAgent,
formattedDescription: l
});
t.ctxPayload.BodyForAgent = t.ctxPayload.agentText;
t.ctxPayload.SkipStickerMediaUnderstanding = true;
}
await cacheSticker({
fileId: n.fileId,
fileUniqueId: n.fileUniqueId,
emoji: n.emoji,
setName: n.setName,
description: s,
cachedAt: (/* @__PURE__ */ new Date()).toISOString(),
receivedFrom: t.ctxPayload.From
});
logVerbose(`telegram: cached sticker description for ${n.fileUniqueId}`);
}
const dispatchTelegramMessage = async (e) => {
const { context: t, bot: n, cfg: r, runtime: i, replyToMode: a, telegramCfg: o, retryDispatchErrors: s = false, suppressFailureFallback: c = false, turnAdoptionLifecycle: l } = e;
const u = Date.now();
const d = await resolveDispatchTelegramContext({ context: t });
const f = createFreshTelegramSessionEntryLoader({ cfg: r });
const p = d.ctxPayload.InboundEventKind === "room_event";
const m = p ? null : d.statusReactionController;
const finalizeStatus = async (e) => {
if (!m) return;
if (e === "done") await m.setDone();
else if (e === "error") await m.setError();
await m.restoreInitial();
};
const finalizeStatusInBackground = (e, t) => {
finalizeStatus(e).catch((e) => {
logVerbose(`telegram: status reaction ${t} failed: ${String(e)}`);
});
};
const h = {
cfg: r,
accountId: d.route.accountId,
accountConfig: o
};
const g = resolveTelegramRichMessages(h);
const _ = resolveTelegramTableMode(h);
const v = await resolveTelegramReasoningLevel({
cfg: r,
sessionKey: d.ctxPayload.SessionKey,
agentId: d.route.agentId,
loadFreshSessionEntry: f
});
const y = d.ctxPayload.ReplyToIsQuote && typeof d.ctxPayload.ReplyToQuoteText === "string" ? d.ctxPayload.ReplyToQuoteText : void 0;
const b = d.ctxPayload.ReplyToIsQuote ? y?.trim() ? y : d.ctxPayload.ReplyToBody?.trim() || void 0 : void 0;
const x = b && !d.ctxPayload.ReplyToIsExternal ? parseStrictInteger(d.ctxPayload.ReplyToId) : void 0;
const S = typeof d.ctxPayload.ReplyToQuotePosition === "number" ? d.ctxPayload.ReplyToQuotePosition : void 0;
const C = Array.isArray(d.ctxPayload.ReplyToQuoteEntities) ? d.ctxPayload.ReplyToQuoteEntities : void 0;
const w = d.msg.reply_to_message?.from?.is_bot === true;
const T = {};
if (a !== "off") {
if (b && x != null) addTelegramNativeQuoteCandidate(T, x, {
text: b,
...S !== void 0 ? { position: S } : {},
...C ? { entities: C } : {}
});
addTelegramNativeQuoteCandidate(T, d.ctxPayload.MessageSid ?? d.msg.message_id, buildTelegramNativeQuoteCandidate(getTelegramTextParts(d.msg)));
if (!d.ctxPayload.ReplyToIsExternal && typeof d.ctxPayload.ReplyToQuoteSourceText === "string") addTelegramNativeQuoteCandidate(T, d.ctxPayload.ReplyToId, buildTelegramNativeQuoteCandidate({
text: d.ctxPayload.ReplyToQuoteSourceText,
entities: Array.isArray(d.ctxPayload.ReplyToQuoteSourceEntities) ? d.ctxPayload.ReplyToQuoteSourceEntities : void 0
}));
}
const E = a !== "off" && typeof d.msg.message_id === "number" ? w ? d.msg.message_id : x ?? d.msg.message_id : void 0;
const D = getGlobalHookRunner();
const O = !d.ctxPayload.GroupThread && !((D?.hasHooks("reply_payload_sending") ?? false) || (D?.hasHooks("message_sending") ?? false));
const isDispatchSuperseded = () => l?.abortSignal?.aborted === true;
const k = {
...e,
draftReplyToMessageId: E,
replyQuoteByMessageId: T,
replyQuoteEntities: C,
replyQuoteMessageId: x,
replyQuotePosition: S,
replyQuoteText: b,
allowProviderPreview: O,
chunkMode: resolveChunkMode(r, "telegram", d.route.accountId),
context: d,
dispatchStartedAt: u,
isSuperseded: isDispatchSuperseded,
loadFreshSessionEntry: f,
mediaLocalRoots: getAgentScopedMediaLocalRoots(r, d.route.agentId),
resolvedReasoningLevel: v,
richMessages: g,
statusReactionController: m,
tableMode: _
};
const A = createDraftState(k);
const j = createProgressState(k, A, () => N);
const M = createDeliveryState({
...k,
lanes: A.lanes
}, () => N);
const N = {
...k,
...A,
...j,
...M,
...createReplyState(),
finalDispatchClaimed: false,
noVisibleReplyFallbackEligible: false,
suppressSilentReplyFallback: false,
hadErrorReplyFailureOrSkip: false
};
let P = false;
let F;
const I = !d.isGroup && d.threadSpec.scope === "dm" && d.threadSpec.id != null;
await prepareTelegramSticker({
cfg: r,
context: d
});
if (I) try {
const e = d.ctxPayload.SessionKey;
if (e) P = !(await f(d.route.agentId, e)).entry?.systemSent;
else logVerbose("auto-topic-label: SessionKey is absent, skipping first-turn detection");
} catch (e) {
logVerbose(`auto-topic-label: session store error: ${String(e)}`);
}
f.clear();
if (isDispatchSuperseded()) {
finalizeStatusInBackground("cancelled", "cancelled finalize");
return { kind: "completed" };
}
if (m && !p) m.setThinking();
try {
F = await runTelegramDispatchTurn(N);
} catch (e) {
N.dispatchError = e;
N.previewLifecycle.observeFailure(isChannelPartialDeliveryError(e) ? e.deliveryResult : void 0);
i.error?.(danger(`telegram dispatch failed: ${String(e)}`));
} finally {
N.progressCompositor.cancel();
await N.draftEventQueue;
try {
await finalizePendingAnswerBlockDraft(N);
} catch (e) {
N.dispatchError ??= e;
N.previewLifecycle.observeFailure(isChannelPartialDeliveryError(e) ? e.deliveryResult : void 0);
i.error?.(danger(`telegram terminal block delivery failed: ${String(e)}`));
}
await cleanupDrafts(N, isDispatchSuperseded());
}
const ee = isDispatchSuperseded();
if (F === false) {
finalizeStatusInBackground("cancelled", "skipped finalize");
return { kind: "completed" };
}
if (ee) {
if (m) finalizeStatusInBackground("done", "finalize");
return { kind: "completed" };
}
let L = N.deliveryState.snapshot();
if (!N.sendPolicyDenied && L.failedNonSilent > 0) {
await settleFailedFinalDelivery(N);
L = N.deliveryState.snapshot();
}
let R = false;
const z = N.dispatchError || N.agentRunFailed;
if (!p && !N.previewLifecycle.finalSuppressed && !N.sendPolicyDenied && !N.finalDispatchClaimed && (!c || N.agentRunFailed) && !N.previewLifecycle.finalDelivered && (z || !N.progressContinuationAdopted && (L.failedNonSilent > 0 || L.skippedNonSilent > 0 && !N.suppressSilentReplyFallback))) R = (await deliverFallback(N, [{ text: z ? "Something went wrong while processing your request. Please try again." : EMPTY_RESPONSE_FALLBACK }], o.silentErrorReplies === true && Boolean(z || N.hadErrorReplyFailureOrSkip))).delivered;
if (!R && !N.previewLifecycle.finalSuppressed && !N.sendPolicyDenied && !N.dispatchError && !L.delivered && !N.suppressSilentReplyFallback && !N.finalDispatchClaimed && N.noVisibleReplyFallbackEligible) {
R = (await deliverFallback(N, [{ text: EMPTY_RESPONSE_FALLBACK }], false)).delivered;
silentReplyDispatchLogger.debug("telegram recovered eligible turn without visible response", {
hasSessionKey: Boolean(d.ctxPayload.SessionKey),
hasChatId: d.chatId != null,
finalDispatchClaimed: N.finalDispatchClaimed,
sentFallback: R
});
}
const B = N.previewLifecycle.finalSuppressed || N.sendPolicyDenied || N.suppressSilentReplyFallback;
const te = B || N.previewLifecycle.finalDelivered || N.progressContinuationAdopted || R;
const V = L.delivered || R;
const H = !B && !N.previewLifecycle.finalDelivered && !N.progressContinuationAdopted && (N.previewLifecycle.finalFailed || L.skippedNonSilent > 0 || L.failedNonSilent > 0);
const U = N.dispatchError ?? (H ? /* @__PURE__ */ new Error(`Telegram reply delivery failed without a final response (failed=${L.failedNonSilent}, skipped=${L.skippedNonSilent})`) : null);
if (m && !V && !B) finalizeStatusInBackground("error", "error finalize");
const ne = s && !N.finalDispatchClaimed && (N.dispatchError != null && !te || N.dispatchError == null && H && !V);
if (U && ne) return {
kind: "failed-retryable",
error: U
};
if (!V && !B) return { kind: "completed" };
const scheduleDmTopicLabel = () => {
if (!I || !P) return;
const e = truncateUtf16Safe(d.ctxPayload.RawBody ?? d.ctxPayload.Body ?? "", 500);
if (!e.trim()) return;
const t = d.groupConfig && "autoTopicLabel" in d.groupConfig ? d.groupConfig.autoTopicLabel : void 0;
const i = resolveAutoTopicLabelConfig(t, o.autoTopicLabel);
if (!i) return;
const a = d.threadSpec.id;
(async () => {
try {
const t = await generateConversationLabel({
userMessage: e,
prompt: i.prompt,
maxLength: 128,
cfg: r,
agentId: d.route.agentId,
agentDir: resolveAgentDir(r, d.route.agentId)
});
if (!t) {
logVerbose("auto-topic-label: LLM returned empty label");
return;
}
logVerbose(`auto-topic-label: generated label (len=${t.length})`);
await n.api.editForumTopic(d.chatId, a, { name: t });
logVerbose(`auto-topic-label: renamed topic ${d.chatId}/${a}`);
} catch (e) {
logVerbose(`auto-topic-label: failed: ${String(e)}`);
}
})();
};
scheduleDmTopicLabel();
if (m) finalizeStatusInBackground(N.agentRunFailed || N.dispatchError != null || N.previewLifecycle.finalFailed || N.previewLifecycle.finalDelivered && !N.previewLifecycle.finalSucceeded || R ? "error" : "done", "finalize");
return { kind: "completed" };
};
//#endregion
//#region extensions/telegram/src/bot-processing-outcome.ts
const telegramUpdateProcessingFrames = new AsyncLocalStorage();
const telegramSpooledReplayFrames = new AsyncLocalStorage();
const telegramSpooledReplayUpdates = /* @__PURE__ */ new WeakSet();
const telegramUpdateReceivedAtMs = /* @__PURE__ */ new WeakMap();
/** Records the durable spool receipt time so replayed updates keep their original arrival time. */
function recordTelegramUpdateReceivedAt(e, t) {
telegramUpdateReceivedAtMs.set(e, t);
}
/**
* Unix seconds when OpenClaw received the update. Telegram callback queries carry no
* timestamp of their own, so this approximates the tap time for callback-built messages.
*/
function resolveTelegramUpdateReceivedAtSeconds(e) {
const t = typeof e === "object" && e !== null ? telegramUpdateReceivedAtMs.get(e) : void 0;
return Math.floor((t ?? Date.now()) / 1e3);
}
var TelegramSpooledReplayProcessingError = class extends Error {
constructor(e) {
super(`telegram spooled update processing failed: ${String(e)}`);
this.name = "TelegramSpooledReplayProcessingError";
this.cause = e;
}
};
async function runWithTelegramUpdateProcessingFrame(e) {
const t = telegramUpdateProcessingFrames.getStore();
const n = t ?? {};
const r = t ? await e() : await telegramUpdateProcessingFrames.run(n, e);
return n.result ? {
value: r,
result: n.result
} : { value: r };
}
/** Records a default only when a handler has not already chosen its terminal disposition. */
function ensureTelegramMessageProcessingResult(e) {
const t = telegramUpdateProcessingFrames.getStore();
if (t && !t.result) t.result = e;
}
function recordTelegramMessageProcessingResult(e) {
const t = telegramUpdateProcessingFrames.getStore();
if (t && (e.kind === "failed-retryable" || !t.result || t.result.kind === "skipped")) t.result = e;
}
function resolveTelegramSpooledReplayHeartbeatIntervalMs(e) {
const t = e.map((e) => e.heartbeatIntervalMs).filter((e) => typeof e === "number" && Number.isFinite(e) && e > 0);
return t.length > 0 ? Math.min(...t) : void 0;
}
function createTelegramSpooledReplayParticipant(e, t) {
const n = new AbortController();
const r = telegramSpooledReplayFrames.getStore()?.lifecycle;
const i = r?.abortSignal;
const a = i ? AbortSignal.any([n.signal, i]) : n.signal;
let o = false;
let s = i?.aborted === true;
let c = false;
let l;
const { promise: u, resolve: d } = createDeferredCore();
const onOwnerAbort = () => {
if (!o) {
s = true;
if (!c) settleNow({
kind: "failed-retryable",
error: i?.reason ?? /* @__PURE__ */ new Error("telegram spooled replay owner aborted")
});
}
};
i?.addEventListener("abort", onOwnerAbort, { once: true });
const settleNow = (e) => {
if (o) return;
o = true;
i?.removeEventListener("abort", onOwnerAbort);
if (e.kind !== "completed") n.abort(e.kind === "failed-retryable" ? e.error : e.kind);
d(e);
};
if (i?.aborted) onOwnerAbort();
return {
key: e,
abortSignal: a,
task: u,
readLaneBacklogUpdates: async () => {
return (await r?.readLaneBacklog?.() ?? []).flatMap(({ payload: e }) => isRecord(e) && "update" in e ? [e.update] : []);
},
isSettled: () => o,
heartbeat: () => {
if (o) return;
if (t) for (const e of t) e.heartbeat();
else r?.onDeferredHeartbeat?.();
},
heartbeatIntervalMs: resolveTelegramSpooledReplayHeartbeatIntervalMs(t ?? [{ heartbeatIntervalMs: r?.deferredHeartbeatIntervalMs }]),
wasOwnerAbortedWhilePending: () => s,
beginSettlementHold: () => {
if (o || c) return;
c = true;
r?.onAdoptionFinalizing?.();
let e = false;
return { release: (t) => {
if (e) return;
e = true;
c = false;
const n = l;
l = void 0;
if (t === "replay-pending" && n) settleNow(n);
} };
},
settle: (e) => {
if (o) return;
if (c) {
l ??= e;
return;
}
settleNow(e);
}
};
}
function createTelegramSpooledReplayDeferredParticipant(e) {
const t = telegramSpooledReplayFrames.getStore();
if (!t) return null;
const n = createTelegramSpooledReplayParticipant(e);
t.deferredWork = n;
return n;
}
function getTelegramSpooledReplayDeferredParticipant() {
return telegramSpooledReplayFrames.getStore()?.deferredWork;
}
async function runWithTelegramSpooledReplayUpdate(e, t, n) {
const r = n ? { lifecycle: n } : {};
telegramSpooledReplayUpdates.add(e);
try {
const e = await telegramSpooledReplayFrames.run(r, t);
return r.deferredWork ? {
value: e,
deferredWork: r.deferredWork
} : { value: e };
} finally {
telegramSpooledReplayUpdates.delete(e);
}
}
/** Drain lifecycle for the active spooled-replay ALS frame, if any. */
function getTelegramSpooledReplayLifecycle() {
return telegramSpooledReplayFrames.getStore()?.lifecycle;
}
function isTelegramSpooledReplayUpdate(e) {
return telegramSpooledReplayFrames.getStore() !== void 0 || typeof e === "object" && e !== null && telegramSpooledReplayUpdates.has(e);
}
//#endregion
//#region extensions/telegram/src/telegram-ingress-spool.ts
const TELEGRAM_SPOOLED_COMPLETION_RETRY_POLICY = {
initialMs: 250,
maxMs: 5e3,
factor: 2,
jitter: .2
};
function resolveTelegramUpdateId(e) {
if (!e || typeof e !== "object") return null;
const t = e.update_id;
return typeof t === "number" && Number.isSafeInteger(t) && t >= 0 ? t : null;
}
function telegramQueueEventId(e) {
return String(e).padStart(16, "0");
}
function openTelegramIngressQueue(e) {
return getTelegramRuntime().state.openChannelIngressQueue({
accountId: normalizeTelegramStateAccountId(e.accountId),
stateDir: e.stateDir
});
}
/** Backoff for irrevocable-adoption completion retries (bot-message only). */
function resolveSpooledUpdatePersistenceRetryDelayMs(e) {
return computeBackoff(TELEGRAM_SPOOLED_COMPLETION_RETRY_POLICY, e);
}
//#endregion
//#region extensions/telegram/src/bot-message.ts
function abortedProcessingResult(e, t) {
return e.reason === "skipped" ? { kind: "skipped" } : {
kind: "failed-retryable",
error: e.reason ?? new Error(t)
};
}
function resolveTelegramMessageTurnSettings(e) {
const t = e.opts.allowFrom ?? e.telegramCfg.allowFrom;
const n = resolveTelegramRichMessages({
cfg: e.cfg,
accountId: e.accountId,
accountConfig: e.telegramCfg
}) ? TELEGRAM_RICH_TEXT_LIMIT : TELEGRAM_TEXT_CHUNK_LIMIT;
return {
ackReactionScope: e.cfg.messages?.ackReactionScope ?? "group-mentions",
allowFrom: t,
dmPolicy: e.telegramCfg.dmPolicy ?? "pairing",
dmHistoryLimit: resolveTelegramDmHistoryLimit({
config: e.telegramCfg,
senderId: e.senderId
}),
groupAllowFrom: e.opts.groupAllowFrom ?? e.telegramCfg.groupAllowFrom ?? e.telegramCfg.allowFrom ?? t,
historyLimit: resolvePromptHistoryLimit(e.telegramCfg.historyLimit ?? e.cfg.messages?.groupChat?.historyLimit),
replyToMode: e.opts.replyToMode ?? e.telegramCfg.replyToMode ?? "off",
streamMode: resolveTelegramPreviewStreamMode(e.telegramCfg),
textLimit: Math.min(resolveTextChunkLimit(e.cfg, "telegram", e.accountId, { fallbackLimit: n }), n)
};
}
const createTelegramMessageProcessor = (e) => {
const { runtime: t, buildContext: n, opts: r, ...i } = e;
const { bot: a, account: o } = i;
const s = {
buildChannelInboundEventContext: n ?? buildChannelInboundEventContext,
readSessionUpdatedAtAsync,
readAmbientTranscriptWatermarkAsync,
recordInboundSession,
resolveAmbientTranscriptWatermarkKey,
resolveInboundLastRouteSessionKey,
resolvePinnedMainDmOwnerFromAllowlist,
resolveStorePath: resolveSessionStorePathCore
};
const c = createTelegramDirectAvatarResolver({
api: a.api,
abortSignal: r.fetchAbortSignal,
accountId: o.accountId,
token: r.token,
transport: e.telegramTransport
});
const l = { recordChannelActivity };
return async ({ ctx: n, allMedia: u, storeAllowFrom: d, turnContext: f, options: p, replyMedia: m, replyChain: h, promptContext: g }) => {
const _ = f.cfg;
const v = f.telegramCfg;
const y = resolveTelegramMessageTurnSettings({
accountId: o.accountId,
senderId: n.message.from?.id,
cfg: _,
telegramCfg: v,
opts: r
});
const b = await buildTelegramMessageContext({
...i,
resolveDirectAvatar: c,
nativeCommandNames: e.nativeCommandNames,
primaryCtx: n,
allMedia: u,
replyMedia: m,
replyChain: h,
promptContext: g,
storeAllowFrom: d,
options: p,
cfg: _,
ownerAgentId: r.ownerAgentId,
...y,
runtime: l,
sessionRuntime: s,
upsertPairingRequest: upsertChannelPairingRequest
});
if (!b) return { kind: "skipped" };
if (isTelegramForumTopicTitleUpdate(b.primaryCtx.message) && !b.isGroup && b.threadSpec.scope === "dm") {
if (b.threadSpec.id == null) return { kind: "completed" };
let e;
let t;
await b.turn.recordInboundSession({
storePath: b.turn.storePath,
sessionKey: b.ctxPayload.SessionKey,
ctx: b.ctxPayload,
createIfMissing: false,
onRecordError: (e) => {
t = e;
},
trackSessionMetaTask: (t) => {
e = t;
}
});
await e;
if (t !== void 0) throw t instanceof Error ? t : new Error("Telegram topic metadata update failed", { cause: t });
return { kind: "completed" };
}
const x = p?.spooledReplay === true || isTelegramSpooledReplayUpdate(n.update);
if (!x) await f.onDispatchStart?.();
const runTelegramDispatch = async (e) => {
try {
const n = await dispatchTelegramMessage({
context: b,
bot: a,
cfg: b.cfg,
runtime: t,
replyToMode: y.replyToMode,
streamMode: y.streamMode,
textLimit: y.textLimit,
telegramCfg: v,
opts: r,
retryDispatchErrors: x,
suppressFailureFallback: x,
turnAdoptionLifecycle: e
});
if (n?.kind === "failed-retryable") return {
kind: "failed-retryable",
error: n.error
};
return { kind: "completed" };
} catch (e) {
t.error?.(danger(`telegram message processing failed: ${String(e)}`));
if (!x) try {
await a.api.sendMessage(b.chatId, "Something went wrong while processing your request. Please try again.", buildTelegramThreadParams(b.threadSpec));
} catch {}
return {
kind: "failed-retryable",
error: e
};
}
};
if (x) {
const e = f.spooledReplayParticipant ?? (p?.isolateSpooledReplaySettlement ? void 0 : getTelegramSpooledReplayDeferredParticipant()) ?? (p?.isolateSpooledReplaySettlement ? void 0 : createTelegramSpooledReplayDeferredParticipant(`agent-turn:${b.chatId}:${b.ctxPayload.MessageSid ?? Date.now()}`)) ?? createTelegramSpooledReplayParticipant(`agent-turn:${b.chatId}:${b.ctxPayload.MessageSid ?? Date.now()}`);
let n = false;
let r = false;
let i;
let a = false;
let o;
let s;
const settle = async (t, r) => {
if (o) return o;
if (s) return await s;
s = (async () => {
let i;
try {
i = f.finalizeSpooledReplayResult ? await f.finalizeSpooledReplayResult(t, r) : t;
} catch (e) {
i = {
kind: "failed-retryable",
error: e
};
}
if (r === "adopted" && i.kind !== "completed") return i;
if (r === "adopted" && i.kind === "completed") n = true;
o = i;
e.settle(i);
return i;
})();
try {
return await s;
} finally {
if (!o) s = void 0;
}
};
const run = async () => {
const s = getTelegramSpooledReplayLifecycle();
const c = [
e.abortSignal,
f.spooledReplayAbortSignal,
s?.abortSignal
].filter((e) => e !== void 0);
const l = c.length === 1 ? e.abortSignal : AbortSignal.any(c);
const u = await runTelegramDispatch({
admission: "exclusive",
abortSignal: l,
onAdopted: async () => {
if (n) return;
r = true;
const e = await settle({ kind: "completed" }, "adopted");
if (e.kind !== "completed") {
i = e.kind === "failed-retryable" ? e.error : /* @__PURE__ */ new Error("telegram spooled turn adoption was not completed");
throw i;
}
await s?.onAdopted();
},
onDeferred: () => {
a = true;
s?.onDeferred();
f.onTurnDeferred?.();
},
onDeferredHeartbeat: () => e.heartbeat(),
deferredHeartbeatIntervalMs: e.heartbeatIntervalMs,
onAbandoned: () => {
if (!n) settle({
kind: "failed-retryable",
error: "turn-abandoned"
}, "terminal");
s?.onAbandoned();
}
});
if (n) return { kind: "completed" };
if (o) return o;
if (l.aborted) return await settle(abortedProcessingResult(l, "telegram spooled replay owner cancelled before adoption"), "terminal");
if (r && !a && u.kind === "completed") {
t.error?.(danger(`telegram spooled turn adoption finalization failed after active steer commit: ${String(i)}`));
let r = i;
let a = 0;
while (!l.aborted) {
a += 1;
try {
const t = await f.completeSpooledReplayAfterIrrevocableAdoption?.(r) ?? { kind: "completed" };
if (t.kind === "completed") {
n = true;
o = t;
e.settle(t);
return t;
}
r = t.kind === "failed-retryable" ? t.error : /* @__PURE__ */ new Error("telegram spooled turn adoption was not completed");
} catch (e) {
r = e;
}
const i = resolveSpooledUpdatePersistenceRetryDelayMs(a);
t.error?.(danger(`telegram spooled turn durable replay protection retry ${a} failed after active steer commit; retrying in ${i}ms: ${String(r)}`));
try {
await sleepWithAbort(i, l);
} catch {
break;
}
}
if (l.aborted && !e.abortSignal.aborted) e.settle(abortedProcessingResult(l, "telegram spooled replay owner cancelled"));
return await e.task;
}
if (a) return await e.task;
return await settle(u, "terminal");
};
runDetachedWebhookWork(run).catch((e) => settle({
kind: "failed-retryable",
error: e
}, "terminal"));
return await e.task;
}
return await runTelegramDispatch();
};
};
//#endregion
export { resolveTelegramInboundMediaUri as A, formatTelegramAmbientTranscriptBody as C, resolveTelegramForumTopicMetadata as D, promptContextBoundaryOptions as E, hasInboundMedia as F, isMediaSizeLimitError as I, isTelegramForumServiceMessage as M, resolveMedia as N, enforceTelegramDmAccess as O, TelegramBotApiFileTooLargeError as P, createTelegramMessageSessionRuntime as S, latestPromptContextMinTimestampMs as T, runWithTelegramSpooledReplayUpdate as _, telegramQueueEventId as a, buildSyntheticTextMessage as b, createTelegramSpooledReplayParticipant as c, getTelegramSpooledReplayLifecycle as d, isTelegramSpooledReplayUpdate as f, resolveTelegramUpdateReceivedAtSeconds as g, resolveTelegramSpooledReplayHeartbeatIntervalMs as h, resolveTelegramUpdateId as i, resolveTelegramPromptMediaPath as j, isTelegramDmAccessAllowed as k, ensureTelegramMessageProcessingResult as l, recordTelegramUpdateReceivedAt as m, resolveTelegramMessageTurnSettings as n, TelegramSpooledReplayProcessingError as o, recordTelegramMessageProcessingResult as p, openTelegramIngressQueue as r, createTelegramSpooledReplayDeferredParticipant as s, createTelegramMessageProcessor as t, getTelegramSpooledReplayDeferredParticipant as u, runWithTelegramUpdateProcessingFrame as v, latestPromptContextAmbientWatermark as w, createTelegramMessageContextRuntime as x, buildSyntheticContext as y };