UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,667 lines • 70.3 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { E as parseStrictNonNegativeInteger, s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { l as isRecord, r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { b as resolveGatewayPort } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { n as normalizeAccountId, r as normalizeOptionalAccountId, t as DEFAULT_ACCOUNT_ID } from "./account-id-BqKT3GuY.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { t as createPermitPool } from "./permit-pool-DR3Z0pxU.mjs";
import { a as buildChannelGroupsScopeTree, l as resolveScopeRequireMention, n as resolveChannelGroupRequireMention, u as resolveScopeToolsPolicy } from "./group-policy-ChfL4Y9r.mjs";
import { i as readResponseWithLimit } from "./http-response-body-B-i_0116.mjs";
import { n as buildTimeoutAbortSignal } from "./fetch-timeout-D62KciOm.mjs";
import { _ as createChannelMessageAdapterFromOutbound, b as createAccountStatusSink, y as resolveOutboundSendDep } from "./channel-outbound-DQFse8vD.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./extension-shared-CJ4teJ7p.mjs";
import "./gateway-config-runtime-B8ERw-mA.mjs";
import { t as collectChannelAccountScopes } from "./runtime-doctor-migrations-YTlcIEpR.mjs";
import "./number-runtime-W4chuk8B.mjs";
import "./error-runtime-BM740gJj.mjs";
import "./concurrency-runtime-CY4L3doa.mjs";
import { n as makeProxyFetch } from "./proxy-fetch-DVhncUsK.mjs";
import "./fetch-runtime-Dz-KqFMb.mjs";
import "./response-limit-runtime-DkiFHsEX.mjs";
import { A as resolveTelegramRequestTimeoutMs, F as normalizeTelegramApiRoot, P as hasTelegramBotEndpointApiRoot, j as resolveTelegramStartupProbeTimeoutMs, n as resolveTelegramTransport, t as resolveTelegramFetch } from "./fetch-Credn4zH.mjs";
import { o as resolveAgentRoute } from "./resolve-route-DBnTWpM6.mjs";
import { T as resolveChannelStreamingPreviewToolProgress, x as resolveChannelStreamingBlockEnabled } from "./streaming-DsQF8isK.mjs";
import { n as collectTelegramUnmentionedGroupIds, t as auditTelegramGroupMembership } from "./audit-Bbc2wnd6.mjs";
import "./routing-DmgGYTrU.mjs";
import { a as mergeTelegramAccountConfig, n as listTelegramAccountIds, o as resolveTelegramAccountConfig, r as resolveDefaultTelegramAccountId, s as resolveTelegramLegacyWebhookListener, t as hasTelegramAccountConfig } from "./account-selection-CGYGB8bX.mjs";
import { n as resolveTelegramToken } from "./token-Dmy_LoAW.mjs";
import { n as createPairingPrefixStripper } from "./pairing-adapters-BBSggHHk.mjs";
import { n as clearAccountFieldsFromConfigSection } from "./config-helpers-DUK5R_HK.mjs";
import { i as createChatChannelPlugin, n as buildThreadAwareOutboundSessionRoute, t as buildChannelOutboundSessionRoute } from "./core-D4CovhmH.mjs";
import { d as resolveApprovalRequestChannelAccountIdAsync } from "./approval-request-account-binding-DOCAr58L.mjs";
import { d as createChannelNativeOriginTargetResolverAsync, l as createChannelApproverDmTargetResolverAsync } from "./approval-native-helpers-BnPamoUJ.mjs";
import { r as createApproverRestrictedNativeApprovalCapabilityAsync } from "./approval-delivery-helpers-ia79shuh.mjs";
import "./approval-delivery-runtime-DSuuyPvu.mjs";
import { r as createLazyChannelApprovalNativeRuntimeAdapterAsync } from "./approval-handler-adapter-runtime-DvlOtmD7.mjs";
import "./approval-handler-adapter-runtime-CvRkdXdX.mjs";
import "./approval-native-runtime-DBG67Vog.mjs";
import { a as projectCredentialSnapshotFields } from "./account-snapshot-fields-B0Zypjh2.mjs";
import { _ as appendMatchMetadata, d as createDefaultChannelRuntimeState, o as buildTokenChannelStatusSummary, p as readAccountStatusSnapshot, u as createComputedAccountStatusAdapter, v as collectIssuesForEnabledAccounts } from "./status-helpers-DArJIcrA.mjs";
import { s as createScopedDmSecurityResolver } from "./channel-config-helpers-ByHw7EOT.mjs";
import "./conversation-runtime-CefOz30L.mjs";
import { c as resolveThreadBindingSpawnPolicy } from "./thread-bindings-policy-Ty7ueYar.mjs";
import { t as channelBlockedPatch } from "./channel-status-patches-Dd7V0RTf.mjs";
import "./gateway-runtime-Du0olVch.mjs";
import "./cli-runtime-DeVPX2l7.mjs";
import { c as createNestedAllowlistOverrideResolver, n as buildDmGroupAccountAllowlistAdapter } from "./allowlist-config-edit-DJnqvYSN.mjs";
import { t as PAIRING_APPROVED_MESSAGE } from "./pairing-message-C9w9gv4K.mjs";
import "./channel-core-irqoURKA.mjs";
import "./channel-pairing-R9ineSO_.mjs";
import { T as createConditionalWarningCollector, w as createAllowlistProviderRouteAllowlistWarningCollector } from "./channel-policy-Br2lSetS.mjs";
import { t as createChannelDirectoryAdapter } from "./directory-adapters-12LLH43Y.mjs";
import "./directory-runtime-CruGq--z.mjs";
import "./channel-status-BH3icrlK.mjs";
import { i as resolveTelegramAccount, r as resolveDefaultTelegramAccountId$1 } from "./accounts-C26vVqsr.mjs";
import { r as normalizeTelegramAllowFromEntry, t as isNumericTelegramSenderUserId } from "./allow-from-9eXjPa0a.mjs";
import { l as parseTelegramTarget, n as parseTelegramTopicConversation, o as normalizeTelegramChatId, t as buildTelegramConversationId } from "./topic-conversation-CDf2PinB.mjs";
import { d as telegramMessagingTargetsMatch, l as looksLikeTelegramTargetId, p as releaseAccountThrottler, r as isTelegramTextOnlyChannelData, u as normalizeTelegramMessagingTarget } from "./prompt-context-projection-CoqAV_fc.mjs";
import { T as resolveTelegramPreviewStreamMode, s as buildTelegramRoutingTarget, w as parseTelegramThreadId } from "./helpers-CoGccTxe.mjs";
import { n as getTelegramRuntime, t as getOptionalTelegramRuntime } from "./runtime-Gy4vBjmB.mjs";
import { t as fingerprintOptionalTelegramBotToken } from "./token-fingerprint-aykBVd26.mjs";
import { n as formatDuplicateTelegramTokenReason, r as inspectTelegramAccount, t as findTelegramTokenOwnerAccountId } from "./account-inspect-C24-1-jt.mjs";
import { a as normalizeTelegramBotInfo, c as releaseStoppedTelegramPollingLease, n as monitorTelegramProvider, o as telegramMessageActions, r as buildTelegramExecApprovalPendingPayload, s as telegramMessageToolHints, t as probeTelegram } from "./probe-VYdCAZiU.mjs";
import { r as resolveTelegramInlineButtonsScope } from "./inline-buttons-uex3aS7P.mjs";
import { t as resolveTelegramReactionLevel } from "./reaction-level-Bqy9u5yv.mjs";
import { A as resolveTelegramScopedGroupConfig, D as resolveTelegramDirectToolPolicy, j as resolveTelegramRichMessages } from "./text-chunk-limit-DTiKmKhG.mjs";
import { c as resolveTelegramExecApprovalTarget, d as shouldSuppressLocalTelegramExecApprovalPrompt, i as isTelegramExecApprovalClientEnabled, l as shouldHandleTelegramExecApprovalRequest, n as isTelegramExecApprovalApprover, o as isTelegramExecApprovalTargetRecipient, r as isTelegramExecApprovalAuthorizedSender, t as getTelegramExecApprovalApprovers } from "./exec-approvals-Crn--YHh.mjs";
import { t as normalizeTelegramStateAccountId } from "./state-account-id-BXoQeOII.mjs";
import { a as buildTelegramModelsListChannelData, i as buildTelegramModelsAddProviderChannelData, n as buildTelegramCommandsListChannelData, o as buildTelegramModelsProviderChannelData, r as buildTelegramModelBrowseChannelData } from "./command-ui-CY93vhxr.mjs";
import { a as resolveTelegramConfigAccessorAccount, i as telegramSetupContract, n as telegramSetupWizard, o as telegramConfigAdapter, r as createTelegramSetupPluginBase } from "./channel.setup-p38JB_yC.mjs";
import { l as resolveTelegramOutboundDirectBaseSessionKey, p as resolveTelegramSecurityDmRoute, s as prepareTelegramConversationRouteInspection, t as createTelegramOutboundAdapter } from "./outbound-adapter-xqQwShsd.mjs";
import { n as listTelegramDirectoryPeersFromConfig, t as listTelegramDirectoryGroupsFromConfig } from "./directory-config-C1O3xIq5.mjs";
import { r as resolveTelegramWebhookPathConflict, t as DEFAULT_TELEGRAM_WEBHOOK_PATH } from "./webhook-route-uIeBtETz.mjs";
import { n as legacyConfigRules, r as normalizeCompatibilityConfig } from "./doctor-contract-BLPeSdfU.mjs";
import { t as loadTelegramSendModule } from "./send-runtime-CZEXtMaJ.mjs";
import { t as collectTelegramSecurityAuditFindings } from "./security-audit-DIa6ygCn.mjs";
import { n as resolveTelegramSessionTarget, t as resolveTelegramSessionConversation } from "./session-conversation-BuRv40n7.mjs";
import { a as setTelegramThreadBindingMaxAgeBySessionKey, i as setTelegramThreadBindingIdleTimeoutBySessionKeyAsync, o as setTelegramThreadBindingMaxAgeBySessionKeyAsync, r as setTelegramThreadBindingIdleTimeoutBySessionKey, t as createTelegramThreadBindingManager } from "./thread-bindings-DUItHFpF.mjs";
//#region extensions/telegram/src/account-throttler-lifecycle.ts
function telegramTokenStillInUse(e, t, n) {
	const r = n === void 0 ? void 0 : normalizeOptionalAccountId(n);
	return listTelegramAccountIds(e).some((n) => n !== r && resolveTelegramAccount({
		cfg: e,
		accountId: n
	}).token.trim() === t);
}
/**
* Releases the throttler of a retired bot token once no configured account
* still uses it. The caller (config reload, account removal, manual stop) has
* already excluded the affected account; the token stays cached when a sibling
* account shares it, so penalty state survives.
*/
async function releaseRetiredTelegramAccountThrottler(e, t, n) {
	const r = t ?? getOptionalTelegramRuntime()?.config.current?.();
	if (!e || !r) return false;
	if (telegramTokenStillInUse(r, e, n)) return false;
	return releaseAccountThrottler(e);
}
/**
* Releases the throttler of a rotated-out bot token and reports whether the
* account's token actually changed. `nextCfg` no longer configures the old
* token for this account, so the shared-token check covers sibling accounts.
*/
async function releaseRotatedTelegramAccountThrottler(e, t, n) {
	const r = resolveTelegramAccount({
		cfg: e,
		accountId: n
	}).token.trim();
	if (r === resolveTelegramAccount({
		cfg: t,
		accountId: n
	}).token.trim()) return false;
	await releaseRetiredTelegramAccountThrottler(r, t);
	return true;
}
/**
* Releases the throttler of a removed account's bot token once no remaining
* configured account still uses it. `prevCfg` is the config before removal, so
* it still contains the removed account; that account is excluded from the
* still-in-use check while a shared sibling token keeps its limiter alive.
*/
async function releaseRemovedTelegramAccountThrottler(e, t) {
	return releaseRetiredTelegramAccountThrottler(resolveTelegramAccount({
		cfg: e,
		accountId: t
	}).token.trim(), e, t);
}
/**
* Releases a stopped account's polling lease and, once the token is no longer
* configured anywhere (unchanged reloads and manual stops keep the limiter),
* its account throttler.
*/
async function releaseStoppedTelegramAccountResources(e) {
	if (await releaseStoppedTelegramPollingLease({
		token: e.token,
		accountId: e.accountId
	})) e.log?.info?.(`[${e.accountId}] released stopped Telegram polling lease`);
	if (await releaseRetiredTelegramAccountThrottler(e.token)) e.log?.info?.(`[${e.accountId}] released retired Telegram account throttler`);
}
//#endregion
//#region extensions/telegram/src/action-threading.ts
function resolveTelegramAutoThreadId(e) {
	const t = e.toolContext;
	if (!t?.currentThreadTs || !t.currentChannelId) return;
	const n = parseTelegramTarget(e.to);
	if (n.messageThreadId != null) return;
	const r = parseTelegramTarget(t.currentChannelId);
	return normalizeLowercaseStringOrEmpty(n.chatId) === normalizeLowercaseStringOrEmpty(r.chatId) ? t.currentThreadTs : void 0;
}
//#endregion
//#region extensions/telegram/src/agent-prompt.ts
const telegramAgentPrompt = {
	questionInputMode: "buttons",
	messageToolHints: telegramMessageToolHints,
	messageToolCapabilities: (e) => resolveTelegramInlineButtonsScope(e) === "off" ? [] : ["inlineButtons"],
	inboundFormattingHints: ({ cfg: e, accountId: t }) => {
		if (resolveTelegramRichMessages({
			cfg: e,
			accountId: t
		})) return {
			text_markup: "markdown_telegram_rich",
			rules: [
				"Telegram rich ON (Bot API 10.3 blocks; OpenClaw maps markdown + these HTML islands to typed blocks).",
				"Supported: headings, tables (markdown, or `<table>` HTML for caption/colspan/rowspan/align), block/pull quotes (`<aside>` + `<cite>`), `<details><summary>` (+`open`), dividers `<hr/>`, sup/sub/mark/spoilers, `<ul>`/`<ol>` + `<input type=\"checkbox\" checked/>` tasks, code, anchors `<a name=\"x\"></a>` + `<a href=\"#x\">label</a>`, custom emoji `<tg-emoji emoji-id=\"...\">`, maps `<tg-map lat=\"\" long=\"\" zoom=\"\"/>`, collages/slideshows `<tg-collage>`/`<tg-slideshow>`, block media e.g. `<img src=\"https://...\"/>` (+`<figure>`/`<figcaption>`).",
				"Math: `<tg-math>` inline, `<tg-math-block>` block; never `$...$`/`\\(...\\)`.",
				"Not MarkdownV2/parse_mode.",
				"Collapse=`<details>` (not expandable blockquote); structured bullets=`<ul><li>` (not literal bullets).",
				"Media https URLs only, block-level only, captions/credits when useful; buttons plain text; normal files via attachments."
			]
		};
		return {
			text_markup: "markdown",
			rules: ["Telegram rich OFF. Standard Telegram formatting only; no rich tables/details/block media/formulas.", "Owner can enable `richMessages` for this Telegram account."]
		};
	},
	reactionGuidance: ({ cfg: e, accountId: t }) => {
		const n = resolveTelegramReactionLevel({
			cfg: e,
			accountId: t ?? void 0
		}).agentReactionGuidance;
		return n ? {
			level: n,
			channelLabel: "Telegram"
		} : void 0;
	}
};
//#endregion
//#region extensions/telegram/src/api-fetch.ts
const TELEGRAM_BOT_API_MAX_RESPONSE_BYTES = 4194304;
function resolveTelegramChatLookupFetch(e) {
	const t = e?.proxyUrl?.trim();
	const n = t ? makeProxyFetch(t) : void 0;
	return resolveTelegramFetch(n, { network: e?.network });
}
async function lookupTelegramChatId(e) {
	const t = e.proxyUrl?.trim();
	const n = t ? makeProxyFetch(t) : void 0;
	const r = resolveTelegramTransport(n, { network: e.network });
	try {
		return await fetchTelegramChatId({
			...e,
			fetchImpl: r.fetch
		});
	} finally {
		await r.close();
	}
}
async function fetchTelegramChatId(e) {
	const t = `${normalizeTelegramApiRoot(e.apiRoot)}/bot${e.token}/getChat?chat_id=${encodeURIComponent(e.chatId)}`;
	const n = e.fetchImpl ?? fetch;
	const r = new AbortController();
	const i = e.signal ? AbortSignal.any([e.signal, r.signal]) : r.signal;
	const a = buildTimeoutAbortSignal({
		signal: i,
		timeoutMs: resolveTelegramRequestTimeoutMs("getchat", e.timeoutSeconds),
		operation: "telegram-getchat-lookup",
		url: t
	});
	try {
		const e = await n(t, a.signal ? { signal: a.signal } : void 0);
		if (!e.ok) {
			r.abort(/* @__PURE__ */ new Error(`Telegram getChat failed with HTTP ${e.status}`));
			e.body?.cancel().catch(() => void 0);
			return null;
		}
		const i = JSON.parse((await readResponseWithLimit(e, TELEGRAM_BOT_API_MAX_RESPONSE_BYTES)).toString("utf8"));
		const o = i?.ok ? i?.result?.id : void 0;
		if (typeof o === "number" || typeof o === "string") return String(o);
		return null;
	} catch {
		return null;
	} finally {
		a.cleanup();
	}
}
//#endregion
//#region extensions/telegram/src/approval-native.ts
function toTelegramOriginTarget(e, t) {
	const n = normalizeOptionalString(e);
	if (!n) return null;
	const r = parseTelegramTarget(n);
	const i = normalizeTelegramChatId(r.chatId);
	if (!i) return null;
	if (r.directMessagesTopicId != null) return { to: `${i}:direct-topic:${r.directMessagesTopicId}` };
	return {
		to: i,
		threadId: parseTelegramThreadId(t ?? r.messageThreadId)
	};
}
function resolveTurnSourceTelegramOriginTarget(e) {
	if (normalizeLowercaseStringOrEmpty(e.request.turnSourceChannel) !== "telegram") return null;
	return toTelegramOriginTarget(e.request.turnSourceTo, e.request.turnSourceThreadId);
}
const resolveTelegramOriginTarget = createChannelNativeOriginTargetResolverAsync({
	channel: "telegram",
	shouldHandleRequest: shouldHandleTelegramExecApprovalRequest,
	resolveTurnSourceTarget: resolveTurnSourceTelegramOriginTarget,
	resolveSessionTarget: (e) => toTelegramOriginTarget(e.to, e.threadId) ?? {
		to: e.to,
		threadId: parseTelegramThreadId(e.threadId)
	}
});
const resolveConfiguredTelegramApproverDmTargets = createChannelApproverDmTargetResolverAsync({
	shouldHandleRequest: shouldHandleTelegramExecApprovalRequest,
	resolveApprovers: getTelegramExecApprovalApprovers,
	mapApprover: (e) => ({ to: e })
});
const resolveTelegramApproverDmTargets = async (e) => {
	const t = await resolveConfiguredTelegramApproverDmTargets(e);
	const n = await resolveApprovalRequestChannelAccountIdAsync({
		cfg: e.cfg,
		request: e.request,
		channel: "telegram"
	});
	const r = normalizeOptionalString(e.accountId) ?? resolveDefaultTelegramAccountId$1(e.cfg);
	if (!n || n !== r) return t;
	const i = await resolveTelegramOriginTarget(e);
	if (!i) return t;
	const a = parseTelegramTarget(i.to);
	const o = normalizeTelegramChatId(a.chatId);
	if (a.chatType !== "direct" || !o || o.startsWith("-") || a.directMessagesTopicId != null && i.threadId != null) return t;
	return t.map((e) => {
		const t = parseTelegramTarget(e.to);
		const n = normalizeTelegramChatId(t.chatId);
		if (t.chatType !== "direct" || n !== o || t.messageThreadId != null || t.directMessagesTopicId != null || e.threadId != null && e.threadId !== i.threadId) return e;
		if (a.directMessagesTopicId != null) return Object.assign({}, e, { to: `${o}:direct-topic:${a.directMessagesTopicId}` });
		return i.threadId == null ? e : Object.assign({}, e, { threadId: i.threadId });
	});
};
function describeTelegramApprovalSetup({ accountId: e }, t) {
	const n = e && e !== "default" ? `channels.telegram.accounts.${e}` : "channels.telegram";
	return `Approve it from the ${t === "plugin" ? "Web UI or terminal UI" : "Web UI"} for now. Telegram supports native ${t} approvals for this account. Configure \`${n}.execApprovals.approvers\` or \`commands.ownerAllowFrom\`; leave \`${n}.execApprovals.enabled\` unset/\`auto\` or set it to \`true\`.`;
}
const telegramApprovalCapability = {
	...createApproverRestrictedNativeApprovalCapabilityAsync({
		channel: "telegram",
		channelLabel: "Telegram",
		describeExecApprovalSetup: (e) => describeTelegramApprovalSetup(e, "exec"),
		describePluginApprovalSetup: (e) => describeTelegramApprovalSetup(e, "plugin"),
		listAccountIds: listTelegramAccountIds,
		hasApprovers: ({ cfg: e, accountId: t }) => getTelegramExecApprovalApprovers({
			cfg: e,
			accountId: t
		}).length > 0,
		isExecAuthorizedSender: isTelegramExecApprovalAuthorizedSender,
		isPluginAuthorizedSender: isTelegramExecApprovalApprover,
		isNativeDeliveryEnabled: async (e) => isTelegramExecApprovalClientEnabled(e),
		resolveNativeDeliveryMode: resolveTelegramExecApprovalTarget,
		requireMatchingTurnSourceChannel: true,
		resolveSuppressionAccountId: ({ target: e, request: t }) => normalizeOptionalString(e.accountId) ?? normalizeOptionalString(t.request.turnSourceAccountId),
		resolveOriginTarget: resolveTelegramOriginTarget,
		resolveApproverDmTargets: resolveTelegramApproverDmTargets,
		notifyOriginWhenDmOnly: true,
		nativeRuntimeAsync: createLazyChannelApprovalNativeRuntimeAdapterAsync({
			capabilityBoundary: true,
			eventKinds: [
				"exec",
				"plugin",
				"system-agent"
			],
			isConfigured: isTelegramExecApprovalClientEnabled,
			shouldHandle: shouldHandleTelegramExecApprovalRequest,
			load: async () => (await import("./approval-handler.runtime.js")).telegramApprovalNativeRuntime
		})
	}),
	resolveApproveCommandBehavior: (e) => {
		if (e.approvalKind !== "exec" || isTelegramExecApprovalClientEnabled(e) || isTelegramExecApprovalTargetRecipient(e) || isTelegramExecApprovalAuthorizedSender(e) && !isTelegramExecApprovalApprover(e)) return;
		return {
			kind: "reply",
			text: "❌ Telegram exec approvals are not enabled for this bot account."
		};
	}
};
//#endregion
//#region extensions/telegram/src/bot-info-cache.ts
const TELEGRAM_BOT_INFO_CACHE_NAMESPACE = "telegram.bot-info-cache";
const TELEGRAM_BOT_INFO_CACHE_MAX_ENTRIES = 128;
const TELEGRAM_BOT_INFO_CACHE_MAX_AGE_MS = 864e5;
function openBotInfoCacheStore() {
	return getTelegramRuntime().state.openKeyedStore({
		namespace: TELEGRAM_BOT_INFO_CACHE_NAMESPACE,
		maxEntries: TELEGRAM_BOT_INFO_CACHE_MAX_ENTRIES,
		defaultTtlMs: TELEGRAM_BOT_INFO_CACHE_MAX_AGE_MS
	});
}
async function readCachedTelegramBotInfo(e) {
	const t = fingerprintOptionalTelegramBotToken(e.botToken);
	if (!t) return null;
	const n = await openBotInfoCacheStore().lookup(normalizeTelegramStateAccountId(e.accountId));
	if (!n || typeof n !== "object") return null;
	const r = n;
	if (typeof r.tokenFingerprint !== "string" || typeof r.fetchedAt !== "string" || Number.isNaN(Date.parse(r.fetchedAt))) return null;
	const i = normalizeTelegramBotInfo(r.botInfo);
	if (!i) return null;
	const a = r.tokenFingerprint;
	const o = r.fetchedAt;
	if (a !== t) return null;
	const s = Date.parse(o);
	if (Date.now() - s > TELEGRAM_BOT_INFO_CACHE_MAX_AGE_MS) return null;
	return {
		botInfo: i,
		fetchedAt: o
	};
}
async function writeCachedTelegramBotInfo(e) {
	const t = fingerprintOptionalTelegramBotToken(e.botToken);
	if (!t) return;
	const n = normalizeTelegramBotInfo(e.botInfo);
	if (!n) return;
	await openBotInfoCacheStore().register(normalizeTelegramStateAccountId(e.accountId), {
		tokenFingerprint: t,
		fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
		botInfo: n
	});
}
async function deleteCachedTelegramBotInfo(e) {
	await openBotInfoCacheStore().delete(normalizeTelegramStateAccountId(e.accountId));
}
//#endregion
//#region extensions/telegram/src/conversation-route-owner.ts
async function prepareTelegramConversationRouteOwnersAsync(e, t) {
	const n = e.map((e) => {
		const t = e.conversation;
		const n = parseTelegramTarget(t.target?.trim() || t.peerId);
		const r = n.chatId.trim();
		if (!r) return null;
		let i;
		if (n.directMessagesTopicId != null) i = {
			id: n.directMessagesTopicId,
			scope: "direct-messages"
		};
		else if (n.messageThreadId != null) i = {
			id: n.messageThreadId,
			scope: "forum"
		};
		else {
			const e = parseStrictNonNegativeInteger(t.threadId);
			i = e == null ? { scope: "none" } : {
				id: e,
				scope: t.kind === "direct" ? "dm" : "forum"
			};
		}
		const a = normalizeAccountId(e.accountId);
		const o = mergeTelegramAccountConfig(e.cfg, a);
		if (e.cfg.channels?.telegram?.enabled === false || o.enabled === false || !hasTelegramAccountConfig(e.cfg, a)) return null;
		const { topicConfig: s } = resolveTelegramScopedGroupConfig(o, r, i.id);
		const c = prepareTelegramConversationRouteInspection({
			cfg: e.cfg,
			accountId: a,
			chatId: r,
			isGroup: t.kind !== "direct",
			threadSpec: i,
			senderId: t.kind === "direct" ? t.peerId : void 0,
			topicAgentId: s?.agentId
		});
		return {
			conversation: c.conversation,
			resolve(t) {
				const n = c.resolve(t);
				if (!n.bindingOwnerAvailable && resolveThreadBindingSpawnPolicy({
					cfg: e.cfg,
					channel: "telegram",
					accountId: a,
					kind: "subagent"
				}).enabled) return { kind: "unavailable" };
				if (n.bindingMode.kind !== "plugin-owned-runtime") return {
					kind: "agent",
					agentId: n.route.agentId
				};
				return n.bindingMode.pluginId ? {
					kind: "plugin",
					pluginId: n.bindingMode.pluginId,
					fallbackAgentId: n.route.agentId
				} : null;
			}
		};
	});
	const r = await t(n.flatMap((e) => e ? [e.conversation] : []));
	let i = 0;
	return n.map((e) => {
		if (!e) return () => null;
		const t = i++;
		return () => e.resolve(r()[t]);
	});
}
//#endregion
//#region extensions/telegram/src/doctor.ts
function sanitizeForLog(e) {
	return e.replace(/\p{Cc}+/gu, " ").trim();
}
function hasAllowFromEntries(e) {
	return Array.isArray(e) && e.some((e) => normalizeOptionalString(String(e)));
}
function collectTelegramAllowFromLists(e, t) {
	const n = [{
		pathLabel: `${e}.allowFrom`,
		holder: t,
		key: "allowFrom"
	}, {
		pathLabel: `${e}.groupAllowFrom`,
		holder: t,
		key: "groupAllowFrom"
	}];
	const collect = (e, t, r) => {
		for (const [i, a] of Object.entries(asNullableRecord(e[r]) ?? {})) {
			const e = asNullableRecord(a);
			if (!e) continue;
			const o = `${t}.${r}.${i}`;
			n.push({
				pathLabel: `${o}.allowFrom`,
				holder: e,
				key: "allowFrom"
			});
			if (r === "groups") collect(e, o, "topics");
		}
	};
	collect(t, e, "groups");
	return n;
}
function describeConfigValueType(e) {
	if (Array.isArray(e)) return "array";
	if (e === null) return "null";
	return typeof e;
}
function collectTelegramMalformedGroupsWarnings(e) {
	const t = collectChannelAccountScopes({
		cfg: e.cfg,
		channelId: "telegram"
	}).find(({ account: e }) => Object.hasOwn(e, "groups") && !asNullableRecord(e.groups));
	if (!t) return [];
	return [`- ${sanitizeForLog(`${t.prefix}.groups`)} has invalid Telegram groups shape (${describeConfigValueType(t.account.groups)}); expected an object map keyed by Telegram group/chat id, not an array, string, or null.`, `- Example shape: channels.telegram.groups."-1001234567890".topics."99" = { agentId: "support" }. Use topics for forum-topic routing, then rerun ${e.doctorFixCommand} for any remaining Telegram config cleanup.`];
}
function scanTelegramInvalidAllowFromEntries(e) {
	const t = [];
	for (const n of collectChannelAccountScopes({
		cfg: e,
		channelId: "telegram"
	})) for (const { pathLabel: e, holder: r, key: i } of collectTelegramAllowFromLists(n.prefix, n.account)) {
		const n = r[i];
		if (!Array.isArray(n)) continue;
		for (const r of n) {
			const n = normalizeTelegramAllowFromEntry(r);
			if (!n || n === "*" || isNumericTelegramSenderUserId(n)) continue;
			t.push({
				path: e,
				entry: normalizeOptionalString(String(r)) ?? ""
			});
		}
	}
	return t;
}
function collectTelegramInvalidAllowFromWarnings(e) {
	if (e.hits.length === 0) return [];
	const t = sanitizeForLog(e.hits[0]?.entry ?? "@");
	return [`- Telegram allowFrom contains ${e.hits.length} invalid sender entries (e.g. ${t}); Telegram authorization requires positive numeric sender user IDs.`, `- Run "${e.doctorFixCommand}" to auto-resolve @username entries to numeric IDs (requires a Telegram bot token). Move negative chat IDs under channels.telegram.groups instead of allowFrom.`];
}
function scanTelegramBotEndpointApiRoots(e) {
	const t = [];
	for (const n of collectChannelAccountScopes({
		cfg: e,
		channelId: "telegram"
	})) {
		const e = n.account.apiRoot;
		if (typeof e !== "string" || !hasTelegramBotEndpointApiRoot(e)) continue;
		const r = new URL(e.trim());
		const i = r.pathname.split("/").filter(Boolean);
		i.pop();
		r.pathname = i.length > 0 ? `/${i.join("/")}` : "/";
		r.search = "";
		r.hash = "";
		t.push({
			path: `${n.prefix}.apiRoot`,
			pathSegments: [...n.pathSegments, "apiRoot"],
			normalized: r.toString().replace(/\/+$/u, "")
		});
	}
	return t;
}
function collectTelegramApiRootWarnings(e) {
	if (e.hits.length === 0) return [];
	return [`- ${sanitizeForLog(e.hits[0]?.path ?? "channels.telegram.apiRoot")} points at a full Telegram bot endpoint; apiRoot must be the Bot API root only. Telegram refuses this value until it is repaired.`, `- Run "${e.doctorFixCommand}" to remove the trailing /bot<TOKEN> path from Telegram apiRoot.`];
}
function formatTelegramAccountConfigPath(e, t) {
	const n = asNullableRecord(e.channels?.telegram);
	const r = asNullableRecord(n?.accounts);
	if (!r || Object.keys(r).length === 0) return "channels.telegram";
	return t === "default" ? "channels.telegram" : `channels.telegram.accounts.${t}`;
}
function collectTelegramSelectedQuoteToolProgressWarnings(e) {
	if (!asNullableRecord(e.channels?.telegram)) return [];
	for (const t of listTelegramAccountIds(e)) {
		const n = mergeTelegramAccountConfig(e, t);
		const r = n.replyToMode ?? "off";
		if (r === "off") continue;
		const i = resolveTelegramPreviewStreamMode(n);
		if (i === "off") continue;
		if (resolveChannelStreamingBlockEnabled(n, {
			previewAvailable: true,
			blockStreamingDefault: e.agents?.defaults?.blockStreamingDefault
		}) || !resolveChannelStreamingPreviewToolProgress(n, i !== "progress", i)) continue;
		const a = formatTelegramAccountConfigPath(e, t);
		const o = i === "progress" ? "progress" : "preview";
		return [`- ${sanitizeForLog(a)} has replyToMode: "${sanitizeForLog(r)}" while Telegram preview tool-progress is enabled. Telegram selected quote replies must send the final answer through the native quote-reply path, so those turns skip the short "Working" tool-progress preview. Current-message replies without selected quote text still keep preview streaming.`, `- Set replyToMode: "off" when tool-progress preview matters more than native quote replies, or set streaming.${o}.toolProgress: false to keep quote replies and silence this warning.`];
	}
	return [];
}
function maybeRepairTelegramApiRoots(e) {
	const t = scanTelegramBotEndpointApiRoots(e);
	if (t.length === 0) return {
		config: e,
		changes: []
	};
	const n = structuredClone(e);
	for (const { pathSegments: e, normalized: r } of t) {
		let t = n;
		for (const n of e.slice(0, -1)) {
			t = asNullableRecord(t?.[n]);
			if (!t) break;
		}
		if (t) t[e[e.length - 1] ?? "apiRoot"] = r;
	}
	return {
		config: n,
		changes: t.map((e) => `- ${sanitizeForLog(e.path)}: removed trailing /bot<TOKEN> from Telegram apiRoot.`)
	};
}
function collectTelegramMissingEnvTokenWarnings(e) {
	if (resolveDefaultTelegramAccountId$1(e.cfg) !== "default") return [];
	const t = inspectTelegramAccount({
		cfg: e.cfg,
		accountId: "default",
		envToken: e.env?.TELEGRAM_BOT_TOKEN ?? ""
	});
	if (!t.enabled || t.tokenStatus !== "missing" || t.tokenSource !== "none") return [];
	return ["- channels.telegram: default account has no available bot token, and TELEGRAM_BOT_TOKEN is absent in this doctor environment. After migration, verify TELEGRAM_BOT_TOKEN is present in the state-dir .env or configure channels.telegram.botToken / channels.telegram.accounts.default.botToken as a SecretRef."];
}
async function repairTelegramConfig(e) {
	const t = maybeRepairTelegramApiRoots(e.cfg);
	const n = await maybeRepairTelegramAllowFromUsernames(t.config);
	return {
		config: n.config,
		changes: [...t.changes, ...n.changes]
	};
}
async function maybeRepairTelegramAllowFromUsernames(e) {
	const t = scanTelegramInvalidAllowFromEntries(e);
	if (t.length === 0) return {
		config: e,
		changes: []
	};
	if (t.filter((e) => {
		const t = normalizeTelegramAllowFromEntry(e.entry);
		return t.length > 0 && !/\s/.test(t) && !t.startsWith("-");
	}).length === 0) return {
		config: e,
		changes: t.slice(0, 5).map((e) => `- ${sanitizeForLog(e.path)}: invalid sender entry ${sanitizeForLog(e.entry)}; allowFrom requires positive numeric Telegram user IDs. Move group chat IDs under channels.telegram.groups.`)
	};
	const { getChannelsCommandSecretTargetIds: n, resolveCommandSecretRefsViaGateway: r } = await import("./plugin-sdk/runtime.js");
	const { resolvedConfig: i } = await r({
		config: e,
		commandName: "doctor --fix",
		targetIds: n(),
		mode: "read_only_status"
	});
	const a = [];
	const o = [];
	let s = false;
	for (const e of listTelegramAccountIds(i)) {
		let t;
		try {
			t = inspectTelegramAccount({
				cfg: i,
				accountId: e
			});
		} catch (t) {
			a.push(`- Telegram account ${e}: failed to inspect bot token (${formatErrorMessage(t)}).`);
			continue;
		}
		if (t.tokenStatus === "configured_unavailable") {
			s = true;
			a.push(`- Telegram account ${e}: failed to inspect bot token (configured but unavailable in this command path).`);
		}
		if (t.tokenSource === "none" ? "" : normalizeOptionalString(t.token) ?? "") o.push(e);
	}
	if (o.length === 0) return {
		config: e,
		changes: [...a, s ? "- Telegram allowFrom contains @username entries, but configured Telegram bot credentials are unavailable in this command path; cannot auto-resolve." : "- Telegram allowFrom contains @username entries, but no Telegram bot token is available in this command path; cannot auto-resolve."]
	};
	const resolveUserId = async (e) => {
		if (/\s/.test(e)) return null;
		const t = e.startsWith("@") ? e : `@${e}`;
		for (const e of o) try {
			const n = resolveTelegramAccount({
				cfg: i,
				accountId: e
			});
			const r = n.token.trim();
			if (!r) continue;
			const a = await lookupTelegramChatId({
				token: r,
				chatId: t,
				network: n.config.network,
				signal: void 0
			});
			if (a) return a;
		} catch {}
		return null;
	};
	const c = structuredClone(e);
	const l = [];
	const repairList = async (e, t, n) => {
		const r = t[n];
		if (!Array.isArray(r)) return;
		const i = /* @__PURE__ */ new Map();
		const a = [];
		for (const e of r) {
			const t = normalizeTelegramAllowFromEntry(e);
			if (!t) continue;
			let n = t;
			if (t !== "*" && !isNumericTelegramSenderUserId(t)) {
				const r = await resolveUserId(t);
				n = r || (normalizeOptionalString(String(e)) ?? "");
				if (r) a.push({
					from: normalizeOptionalString(String(e)) ?? "",
					to: r
				});
			}
			const r = normalizeOptionalString(n) ?? "";
			if (r && !i.has(r)) i.set(r, n);
		}
		t[n] = [...i.values()];
		for (const t of a.slice(0, 5)) l.push(`- ${sanitizeForLog(e)}: resolved ${sanitizeForLog(t.from)} -> ${sanitizeForLog(t.to)}`);
		if (a.length > 5) l.push(`- ${sanitizeForLog(e)}: resolved ${a.length - 5} more @username entries`);
	};
	for (const e of collectChannelAccountScopes({
		cfg: c,
		channelId: "telegram"
	})) for (const t of collectTelegramAllowFromLists(e.prefix, e.account)) await repairList(t.pathLabel, t.holder, t.key);
	if (l.length === 0) return {
		config: e,
		changes: []
	};
	return {
		config: c,
		changes: l
	};
}
function hasConfiguredGroups(e, t) {
	const n = asNullableRecord(e.groups) ?? asNullableRecord(t?.groups);
	return Boolean(n) && Object.keys(n ?? {}).length > 0;
}
function collectTelegramGroupPolicyWarnings(e) {
	if (!hasConfiguredGroups(e.account, e.parent)) {
		const t = e.dmPolicy ?? "pairing";
		const n = t === "pairing" ? "DMs use pairing mode, so new senders must start a chat and be approved before regular messages are accepted." : t === "allowlist" ? `DMs use allowlist mode, so only sender IDs in ${e.prefix}.allowFrom are accepted.` : t === "open" ? "DMs are open." : "DMs are disabled.";
		return [`- ${e.prefix}: Telegram is in first-time setup mode. ${n} Group messages stay blocked until you add allowed chats under ${e.prefix}.groups (and optional sender IDs under ${e.prefix}.groupAllowFrom), or set ${e.prefix}.groupPolicy to "open" if you want broad group access.`];
	}
	const t = e.account.groupAllowFrom ?? e.parent?.groupAllowFrom;
	if (hasAllowFromEntries((hasAllowFromEntries(t) ? t : void 0) ?? e.effectiveAllowFrom)) return [];
	return [`- ${e.prefix}.groupPolicy is "allowlist" but groupAllowFrom (and allowFrom) is empty — all group messages will be silently dropped. Add sender IDs to ${e.prefix}.groupAllowFrom or ${e.prefix}.allowFrom, or set ${e.prefix}.groupPolicy to "open".`];
}
function collectTelegramEmptyAllowlistExtraWarnings(e) {
	const t = e.account;
	const n = e.parent;
	return e.channelName === "telegram" && (t.groupPolicy ?? n?.groupPolicy ?? void 0) === "allowlist" ? collectTelegramGroupPolicyWarnings({
		account: t,
		dmPolicy: e.dmPolicy,
		effectiveAllowFrom: e.effectiveAllowFrom,
		parent: n,
		prefix: e.prefix
	}) : [];
}
const telegramDoctor = {
	legacyConfigRules,
	normalizeCompatibilityConfig,
	collectPreviewWarnings: ({ cfg: e, doctorFixCommand: t, env: n }) => [
		...collectTelegramMissingEnvTokenWarnings({
			cfg: e,
			env: n
		}),
		...collectTelegramMalformedGroupsWarnings({
			cfg: e,
			doctorFixCommand: t
		}),
		...collectTelegramInvalidAllowFromWarnings({
			hits: scanTelegramInvalidAllowFromEntries(e),
			doctorFixCommand: t
		}),
		...collectTelegramApiRootWarnings({
			hits: scanTelegramBotEndpointApiRoots(e),
			doctorFixCommand: t
		}),
		...collectTelegramSelectedQuoteToolProgressWarnings(e)
	],
	runConfigSequence: ({ cfg: e, env: t }) => {
		const n = [];
		const r = [];
		const i = e.channels?.telegram?.enabled === false ? [] : listTelegramAccountIds(e);
		for (const a of i) {
			const i = mergeTelegramAccountConfig(e, a);
			if (i.enabled === false || !i.webhookUrl) continue;
			const o = resolveTelegramLegacyWebhookListener(i.legacyWebhook);
			const s = i.webhookPath ?? "/telegram-webhook";
			const c = resolveTelegramWebhookPathConflict(s);
			if (c) {
				r.push(`Telegram account "${a}" resolves webhookPath to ${s}, which ${c.message}. Set webhookPath to /telegram-webhook and update webhookUrl or its reverse-proxy mapping. ${o && c.kind !== "health" ? "The legacy listener remains available; verify delivery on the new route before setting legacyWebhook: false." : "This account cannot start until its webhook path is changed."}`);
				continue;
			}
			const l = `Gateway port ${resolveGatewayPort(e, t)}${s}`;
			n.push(o ? `Telegram account "${a}": legacy listener ${o.host}:${o.port} forwards to ${l}. Move the reverse proxy for ${i.webhookUrl} to that Gateway route, verify delivery, then set legacyWebhook: false to disable legacy forwarding for this account.` : `Telegram account "${a}": no legacy listener is configured. The advertised webhook URL must reach ${l}.`);
		}
		return {
			changeNotes: [],
			infoNotes: n,
			warningNotes: r
		};
	},
	repairConfig: repairTelegramConfig,
	collectEmptyAllowlistExtraWarnings: collectTelegramEmptyAllowlistExtraWarnings,
	shouldSkipDefaultEmptyGroupAllowlistWarning: (e) => e.channelName === "telegram"
};
//#endregion
//#region extensions/telegram/src/group-policy.ts
function parseTelegramGroupId(e) {
	const t = e?.trim() ?? "";
	if (!t) return {
		chatId: void 0,
		topicId: void 0
	};
	const [n, r, i] = t.split(":").filter(Boolean);
	const a = r === "topic" ? i : r;
	if (n !== void 0 && /^-?\d+$/.test(n) && a !== void 0 && /^\d+$/.test(a)) return {
		chatId: n,
		topicId: a
	};
	return {
		chatId: t,
		topicId: void 0
	};
}
function resolveTelegramGroupRequireMention(e) {
	const { chatId: t, topicId: n } = parseTelegramGroupId(e.groupId);
	if (t) {
		const r = (e.accountId ? resolveTelegramAccountConfig(e.cfg, e.accountId)?.groups : void 0) ?? e.cfg.channels?.telegram?.groups;
		const i = r?.[t];
		const a = r?.["*"];
		const o = [a, i];
		if (n) o.push(a?.topics?.["*"], a?.topics?.[n], i?.topics?.["*"], i?.topics?.[n]);
		const s = {};
		for (const [e, t] of o.entries()) if (t) s[e] = { requireMention: t.requireMention };
		const c = Object.keys(s);
		if (c.some((e) => typeof s[e]?.requireMention === "boolean")) return resolveScopeRequireMention({
			tree: { scopes: s },
			path: c
		});
	}
	return resolveChannelGroupRequireMention({
		cfg: e.cfg,
		channel: "telegram",
		groupId: t ?? e.groupId,
		accountId: e.accountId
	});
}
function resolveTelegramGroupToolPolicy(e) {
	const { chatId: t } = parseTelegramGroupId(e.groupId);
	const n = t ?? e.groupId?.trim();
	return resolveScopeToolsPolicy({
		tree: buildChannelGroupsScopeTree(e.cfg, "telegram", e.accountId),
		path: n ? [n] : [],
		senderPolicyMode: e.senderPolicyMode,
		senderId: e.senderId,
		senderName: e.senderName,
		senderUsername: e.senderUsername,
		senderE164: e.senderE164,
		messageProvider: "telegram"
	});
}
//#endregion
//#region extensions/telegram/src/security.ts
const resolveTelegramDmPolicy = createScopedDmSecurityResolver({
	channelKey: "telegram",
	resolvePolicy: (e) => e.config.dmPolicy,
	resolveAllowFrom: (e) => e.config.allowFrom,
	policyPathSuffix: "dmPolicy",
	normalizeEntry: (e) => e.replace(/^(telegram|tg):/i, "")
});
const collectTelegramSecurityWarnings = createAllowlistProviderRouteAllowlistWarningCollector({
	providerConfigPresent: (e) => e.channels?.telegram !== void 0,
	resolveGroupPolicy: (e) => e.config.groupPolicy,
	resolveRouteAllowlistConfigured: (e) => Boolean(e.config.groups) && Object.keys(e.config.groups ?? {}).length > 0,
	restrictSenders: {
		surface: "Telegram groups",
		openScope: "any member in allowed groups",
		groupPolicyPath: "channels.telegram.groupPolicy",
		groupAllowFromPath: "channels.telegram.groupAllowFrom"
	},
	noRouteAllowlist: {
		surface: "Telegram groups",
		routeAllowlistPath: "channels.telegram.groups",
		routeScope: "group",
		groupPolicyPath: "channels.telegram.groupPolicy",
		groupAllowFromPath: "channels.telegram.groupAllowFrom"
	}
});
const collectTelegramOpenGroupFindings = createConditionalWarningCollector.findings({
	collectWarnings: collectTelegramSecurityWarnings,
	checkId: "channels.telegram.groups.open",
	severity: "warn",
	title: "Telegram security warning"
});
const telegramSecurityAdapter = {
	resolveDirectToolPolicy(e) {
		const t = e.accountId ?? resolveDefaultTelegramAccountId(e.cfg);
		const n = mergeTelegramAccountConfig(e.cfg, t);
		const { groupConfig: r } = resolveTelegramScopedGroupConfig(n, e.conversationId);
		return resolveTelegramDirectToolPolicy({
			...e,
			directConfig: r
		});
	},
	resolveDmPolicy: resolveTelegramDmPolicy,
	dmRouting: { resolveDmRoute: (e) => resolveTelegramSecurityDmRoute(resolveDefaultTelegramAccountId(e.cfg), e) },
	collectWarnings: collectTelegramOpenGroupFindings,
	collectAuditFindings: collectTelegramSecurityAuditFindings
};
//#endregion
//#region extensions/telegram/src/startup-probe-limiter.ts
const startupProbePermits = createPermitPool(2);
async function withTelegramStartupProbeSlot(e, t) {
	const n = await startupProbePermits.acquire({ signal: e });
	try {
		if (!n || e?.aborted) throw new Error("telegram startup check wait aborted");
		return await t();
	} finally {
		n?.();
	}
}
//#endregion
//#region extensions/telegram/src/status-issues.ts
const TELEGRAM_CONNECT_GRACE_MS = 12e4;
const TELEGRAM_POLLING_STALE_TRANSPORT_MS = 18e5;
const TELEGRAM_ACCOUNT_STATUS_FIELDS = [
	"mode",
	"lastStartAt",
	"lastTransportActivityAt",
	"lastError",
	"allowUnmentionedGroups",
	"audit"
];
function appendTelegramRuntimeError(e, t) {
	const n = normalizeOptionalString(t);
	return n ? `${e}: ${n}` : e;
}
function collectTelegramStatusIssues(e) {
	return collectIssuesForEnabledAccounts({
		accounts: e,
		readAccount: (e) => readAccountStatusSnapshot(e, TELEGRAM_ACCOUNT_STATUS_FIELDS),
		collectIssues: ({ account: e, accountId: t, issues: n }) => {
			if (e.configured !== true) return;
			const r = Date.now();
			const addIssue = (e, r, i) => {
				n.push({
					channel: "telegram",
					accountId: t,
					kind: e,
					message: r,
					fix: i
				});
			};
			const i = normalizeOptionalString(e.mode);
			if (e.running === true && (i === "polling" || i === "webhook")) {
				const t = asFiniteNumber(e.lastStartAt) ?? null;
				const n = i === "polling" ? `Run: ${formatCliCommand("openclaw channels status --probe")} (or restart the gateway). Check the bot token, proxy/network settings, and logs if it persists.` : `Run: ${formatCliCommand("openclaw channels status --probe")} (or restart the gateway). Check the webhook URL, secret, TLS/proxy reachability, and Telegram setWebhook logs if it persists.`;
				if (e.connected === false) {
					if (!(t != null && r - t < TELEGRAM_CONNECT_GRACE_MS)) addIssue("runtime", appendTelegramRuntimeError(i === "webhook" ? "Telegram webhook listener is running but setWebhook has not completed since startup" : /isolated polling spool (?:backlog stalled|handler timed out)/.test(normalizeOptionalString(e.lastError) ?? "") ? "Telegram isolated polling spool backlog is stalled while Bot API polling is still succeeding" : "Telegram polling is running but has not completed a successful getUpdates call since startup", e.lastError), n);
				} else {
					const a = asFiniteNumber(e.lastTransportActivityAt) ?? null;
					if (i === "polling" && e.connected === true && a != null && (t == null || a >= t || Math.max(0, r - t) > TELEGRAM_POLLING_STALE_TRANSPORT_MS)) {
						const t = r - a;
						if (t > TELEGRAM_POLLING_STALE_TRANSPORT_MS) addIssue("runtime", appendTelegramRuntimeError(`Telegram polling transport is stale (last successful getUpdates ${Math.max(0, Math.floor(t / 6e4))}m ago)`, e.lastError), n);
					}
				}
			}
			if (e.allowUnmentionedGroups === true) addIssue("config", "Config allows unmentioned group messages (requireMention=false). Telegram Bot API privacy mode will block most group messages unless disabled.", "In BotFather run /setprivacy → Disable for this bot (then restart the gateway).");
			const a = e.audit;
			if (!isRecord(a)) return;
			if (a.hasWildcardUnmentionedGroups === true) addIssue("config", "Telegram groups config uses \"*\" with requireMention=false; membership checking is not possible without explicit group IDs.", "Add explicit numeric group ids under channels.telegram.groups (or per-account groups) to enable checking.");
			const o = asFiniteNumber(a.unresolvedGroups);
			if (o && o > 0) addIssue("config", `Some configured Telegram groups are not numeric IDs (unresolvedGroups=${o}). Membership checks require numeric group IDs.`, "Use numeric chat IDs (e.g. -100...) as keys in channels.telegram.groups for requireMention=false groups.");
			for (const e of Array.isArray(a.groups) ? a.groups : []) {
				if (!isRecord(e)) continue;
				const t = normalizeOptionalString(e.chatId);
				if (!t || e.ok === true) continue;
				const n = normalizeOptionalString(e.status);
				const r = normalizeOptionalString(e.error);
				const i = `Group ${t} not reachable by bot.${n ? ` status=${n}` : ""}${r ? `: ${r}` : ""}`;
				addIssue("runtime", appendMatchMetadata(i, {
					matchKey: normalizeOptionalString(e.matchKey),
					matchSource: normalizeOptionalString(e.matchSource)
				}), "Invite the bot to the group, then DM the bot once (/start) and restart the gateway.");
			}
		}
	});
}
//#endregion
//#region extensions/telegram/src/thread-bindings-channel.ts
function withOptionalAccountId(e) {
	return {
		...e,
		accountId: e.accountId ?? void 0
	};
}
const telegramThreadBindingLifecycle = {
	createManager: ({ cfg: e, accountId: t }) => createTelegramThreadBindingManager({
		cfg: e,
		accountId: t ?? void 0,
		persist: false,
		enableSweeper: false
	}),
	setIdleTimeoutBySessionKey: (e) => setTelegramThreadBindingIdleTimeoutBySessionKey(withOptionalAccountId(e)),
	setMaxAgeBySessionKey: (e) => setTelegramThreadBindingMaxAgeBySessionKey(withOptionalAccountId(e)),
	setIdleTimeoutBySessionKeyAsync: (e) => setTelegramThreadBindingIdleTimeoutBySessionKeyAsync(withOptionalAccountId(e)),
	setMaxAgeBySessionKeyAsync: (e) => setTelegramThreadBindingMaxAgeBySessionKeyAsync(withOptionalAccountId(e))
};
//#endregion
//#region extensions/telegram/src/threading-tool-context.ts
function buildTelegramThreadingToolContext(e) {
	const t = normalizeOptionalString(e.context.To);
	const n = e.context.MessageThreadId ?? (t ? parseTelegramTarget(t).messageThreadId : void 0);
	return {
		currentChannelId: t,
		currentThreadTs: n != null ? String(n) : void 0,
		hasRepliedRef: e.hasRepliedRef
	};
}
//#endregion
//#region extensions/telegram/src/channel.ts
const loadTelegramUpdateOffsetRuntime = createLazyRuntimeModule(() => import("./extensions/telegram/update-offset-runtime-api.js"));
async function deleteStartupBotInfoCache(e) {
	await deleteCachedTelegramBotInfo({ accountId: e }).catch(() => void 0);
}
function formatTelegramUnauthorizedTokenError(e, t) {
	const n = e.tokenSource === "none" ? "no configured token" : `${e.tokenSource} token`;
	const r = e.accountId === "default" ? "channels.telegram.botToken, channels.telegram.tokenFile, or TELEGRAM_BOT_TOKEN" : `channels.telegram.accounts.${e.accountId}.botToken/tokenFile`;
	return `Telegram bot token unauthorized for account "${e.accountId}" (getMe returned ${t} from Telegram; source: ${n}). Update ${r} with the current BotFather token.`;
}
async function resolveTelegramSend(e) {
	return resolveOutboundSendDep(e, "telegram") ?? (await loadTelegramSendModule()).sendMessageTelegram;
}
async function sendTelegramHeartbeatTyping({ cfg: e, to: t, accountId: n, threadId: r }, i) {
	const { sendTypingTelegram: a } = await loadTelegramSendModule();
	await a(t, {
		cfg: e,
		...n ? { accountId: n } : {},
		messageThreadId: parseTelegramThreadId(r),
		...i
	});
}
const telegramChannelOutbound = createTelegramOutboundAdapter({
	resolveSend: resolveTelegramSend,
	loadSendModule: loadTelegramSendModule,
	shouldSuppressLocalPayloadPrompt: shouldSuppressLocalTelegramExecApprovalPrompt,
	beforeDeliverPayload: async ({ cfg: e, target: t, hint: n }) => {
		if (n?.kind !== "approval-pending" || n.approvalKind !== "exec") return;
		const r = typeof t.threadId === "number" ? t.threadId : typeof t.threadId === "string" ? parseTelegramThreadId(t.threadId) : void 0;
		const { sendTypingTelegram: i } = await loadTelegramSendModule();
		await i(t.to, {
			cfg: e,
			accountId: t.accountId ?? void 0,
			...r !== void 0 ? { messageThreadId: r } : {}
		}).catch(() => {});
	},
	shouldTreatDeliveredTextAsVisible: ({ kind: e }) => e !== "final",
	targetsMatchForReplySuppression: targetsMatchTelegramReplySuppression,
	preferFinalAssistantVisibleText: true
});
const telegramMessageAdapter = createChannelMessageAdapterFromOutbound({
	id: "telegram",
	live: {
		capabilities: {
			draftPreview: true,
			previewFinalization: true,
			progressUpdates: true
		},
		finalizer: { capabilities: {
			finalEdit: true,
			normalFallback: true,
			previewReceipt: true,
			retainOnAmbiguousFailure: true
		} }
	},
	receive: {
		defaultAckPolicy: "after_agent_dispatch",
		supportedAckPolicies: ["after_receive_record", "after_agent_dispatch"]
	},
	outbound: telegramChannelOutbound
});
telegramMessageAdapter.durableFinal = {
	...telegramMessageAdapter.durableFinal,
	isTextOnlyChannelData: isTelegramTextOnlyChannelData
};
function normalizeTelegramAcpConversationId(e, t) {
	const n = parseTelegramTopicConversation({
		conversationId: e,
		parentConversationId: t
	});
	if (!n || !n.chatId.startsWith("-")) return null;
	return {
		conversationId: n.canonicalConversationId,
		parentConversationId: n.chatId
	};
}
function targetsMatchTelegramReplySuppression(e) {
	const t = parseTelegramTarget(e.originTarget);
	const n = parseTelegramTarget(e.targetKey);
	const r = buildTelegramConversationId({
		chatId: t.chatId,
		thread: resolveTelegramTargetThread(t)
	});
	const i = buildTelegramConversationId({
		chatId: n.chatId,
		thread: resolveTelegramTargetThread(n, normalizeOptionalString(e.targetThreadId))
	});
	return normalizeOptionalLowercaseString(r) === normalizeOptionalLowercaseString(i);
}
function resolveTelegramTargetThread(e, t) {
	if (e.directMessagesTopicId != null) return {
		id: e.directMessagesTopicId,
		scope: "direct-messages"
	};
	const n = e.messageThreadId ?? t;
	if (n == null) return { scope: "none" };
	const r = Number(n);
	return Number.isFinite(r) ? {
		id: r,
		scope: "forum"
	} : { scope: "none" };
}
function resolveTelegramInboundConversation(e) {
	const t = e.conversationId && parseTelegramTopicConversation({
		conversationId: e.conversationId,
		parentConversationId: e.parentConversationId
	});
	if (t) return {
		conversationId: t.canonicalConversationId,
		parentConversationId: t.chatId
	};
	const n = e.to || e.parentConversationId || e.conversationId || "";
	if (!n) return null;
	const r = parseTelegramTarget(n);
	const i = normalizeOptionalString(r.chatId) ?? "";
	if (!i) return null;
	return {
		conversationId: buildTelegramConversationId({
			chatId: i,
			thread: resolveTelegramTargetThread(r, e.threadId)
		}),
		parentConversationId: i
	};
}
function resolveTelegramNativeTopicThreadId(e, t) {
	if (t !== void 0) return t;
	if (e === void 0) return;
	const n = parseTelegramThreadId(e);
	if (n !== void 0) return n;
	if (typeof e === "string") {
		const t = /:(\d+)$/.exec(e.trim());
		if (t?.[1]) return Number(t[1]);
	}
	return e;
}
const resolveTelegramAllowlistGroupOverrides = createNestedAllowlistOverrideResolver({
	resolveRecord: (e) => e.config.groups,
	outerLabel: (e) => e,
	resolveOuterEntries: (e) => e?.allowFrom,
	resolveChildren: (e) => e?.topics,
	innerLabel: (e, t) => `${e} topic ${t}`,
	resolveInnerEntries: (e) => e?.allowFrom
});
const telegramPlugin = createChatChannelPlugin({
	base: {
		...createTelegramSetupPluginBase({
			setupWizard: telegramSetupWizard,
			setupContract: telegramSetupContract
		}),
		commands: {
			nativeCommandsAutoEnabled: true,
			nativeSkillsAutoEnabled: true,
			buildCommandsListChannelData: buildTelegramCommandsListChannelData,
			buildModelsMenuChannelData: buildTelegramModelsProviderChannelData,
			buildModelsProviderChannelData: buildTelegramModelsProviderChannelData,
			buildModelsAddProviderChannelData: buildTelegramModelsAddProviderChannelData,
			buildModelsListChannelData: buildTelegramModelsListChannelData,
			buildModelBrowseChannelData: buildTelegramModelBrowseChannelData
		},
		doctor: telegramDoctor,
		security: telegramSecurityAdapter,
		allowlist: buildDmGroupAccountAllowlistAdapter({
			channelId: "telegram",
			resolveAccount: resolveTelegramAccount,
			normalize: ({ cfg: e, accountId: t, values: n }) => telegramConfigAdapter.formatAllowFrom({
				cfg: e,
				accountId: t,
				allowFrom: n
			}),
			resolveDmAllowFrom: (e) => e.config.allowFrom,
			resolveGroupAllowFrom: (e) => e.config.groupAllowFrom,
			resolveDmPolicy: (e) => e.config.dmPolicy,
			resolveGroupPolicy: (e) => e.config.groupPolicy,
			resolveGroupOverrides: resolveTelegramAllowlistGroupOverrides
		}),
		bindings: {
			selfParentConversationByDefault: true,
			compileConfiguredBinding: ({ conversationId: e }) => normalizeTelegramAcpConversationId(e),
			matchInboundConversation: ({ compiledBinding: e, conversationId: t, parentConversationId: n }) => {
				const r = normalizeTelegramAcpConversationId(e.conversationId);
				if (!r) return null;
				const i = normalizeTelegramAcpConversationId(t, n);
				return i && r.conversationId === i.conversationId ? {
					...i,
					matchPriority: 2
				} : null;
			},
			resolveCommandConversation: (e) => {
				for (const t of [
					e.originatingTo,
					e.commandTo,
					e.fallbackTo
				]) {
					if (!t) continue;
					const n = parseTelegramTarget(t);
					const r = normalizeTelegramChatId(n.chatId);
					if (!r) continue;
					const i = resolveTelegramTargetThread(n, e.threadId);
					const a = buildTelegramConversationId({
						chatId: r,
						thread: i
					});
					if (a !== r || !r.startsWith("-")) return {
						conversationId: a,
						parentConversationId: r
					};
				}
				return null;
			}
		},
		conversationBindings: {
			supportsCurrentConversationBinding: true,
			bindingStore: "adapter",
			defaultTopLevelPlacement: "current",
			resolveConversationRef: ({ conversationId: e, parentConversationId: t, threadId: n }) => resolveTelegramInboundConversation({
				to: e,
				conversationId: e,
				parentConversationId: t,
				threadId: n ?? void 0
			}),
			buildBoundReplyPayload: ({ operation: e, conversation: t }) => e === "acp-spawn" && t.conversationId.includes(":topic:") ? { delivery: { pin: {
				enabled: true,
				notify: false
			} } } : null,
			shouldStripThreadFromAnnounceOrigin: (e) => {
				const t = normalizeOptionalLowercaseString(e.requester.channel);
				if (t && t !== "telegram") return true;
				const n = e.requester.to?.trim();
				if (!n) return false;
				if (!t && !n.startsWith("telegram:")) return true;
				const r = parseTelegramTarget(n);
				if (r.chatType !== "group") return true;
				const i = e.entry.to?.trim();
				if (!i) return false;
				return parseTelegramTarget(i).chatId !== r.chatId;
			},
			...telegramThreadBindingLifecycle
		},
		groups: {
			resolveRequireMention: resolveTelegramGroupRequireMention,
			resolveToolPolicy: resolveTelegramGroupToolPolicy
		},
		agentPrompt: telegramAgentPrompt,
		messaging: {
			defaultMarkdownTableMode: "block",
			targetPrefixes: ["telegram", "tg"],
			prepareConversationRouteOwnersAsync: prepareTelegramConversationRouteOwnersAsync,
			numericTopicShorthand: true,
			normalizeTarget: normalizeTelegramMessagingTarget,
			resolveInboundConversation: ({ to: e, conversationId: t, threadId: n }) => resolveTelegramInboundConversation({
				to: e,
				conversationId: t,
				threadId: n
			}),
			resolveDeliveryTarget: (e) => {
				const t = parseTelegramTopicConversation({
					conversationId: e.conversationId,
					parentConversationId: e.parentConversationId
				});
				if (t) return {
					to: t.canonicalConversationId,
					threadId: t.thread.id == null ? void 0 : String(t.thread.id)
				};
				const n = parseTelegramTarget(e.conversationId.trim() || e.parentConversationId?.trim() || "");
				if (!n.chatId.trim()) return null;
				return {
					to: n.chatId,
					...n.messageThreadId != null ? { threadId: String(n.messageThreadId) } : {}
				};
			},
			resolveSessionConversation: resolveTelegramSessionConversation,
			resolveSessionTarget: resolveTelegramSessionTarget,
			inferTargetChatType: ({ to: e }) => {
				const { chatType: t } = parseTelegramTarget(e);
				return t === "unknown" ? void 0 : t;
			},
			preserveHeartbeatThreadIdForGroupRoute: true,
			formatTargetDisplay: ({ target: e, display: t, kind: n }) => {
				const r = t?.trim();
				if (r) return r;
				const i = e.trim();
				if (!i) return i;
				const a = i.replace(/^(telegram|tg):/i, "");
				if (n === "user" || /^user:/i.test(a)) return `@${a.replace(/^user:/i, "")}`;
				if (/^channel:/i.test(a)) return `#${a.replace(/^channel:/i, "")}`;
				return a;
			},
			resolveOutboundSessionRoute: (e) => {
				const t = parseTelegramTarget(e.target);
				const n = t.chatId.trim();
				if (!n) return null;
				const r = resolveTelegramTargetThread(t, parseTelegramThreadId(e.threadId));
				const i = r.id;
				const a = r.scope === "none" ? "forum" : r.scope;
				const o = buildTelegramConversationId({
					chatId: n,
					thread: r
				});
				const s = e.resolvedTarget?.kind;
				const c = t.chatType === "group" || t.chatType === "unknown" && s !== void 0 && s !== "user";
				const l = /^-?\d+$/.test(n);
				const u = c && i ? o : n;
				const d = {
					kind: c ? "group" : "direct",
					id: u
				};
				const f = e.accountId ?? resolveDefaultTelegramAccountId$1(e.cfg);
				const p = buildChannelOutboundSessionRoute({
					cfg: e.cfg,
					agentId: e.agentId,
					channel: "telegram",
					accountId: f,
					recipientSessionExact: l,
					peer: d,
					chatType: c ? "group" : "direct",
					from: c ? `telegram:group:${u}` : i ? `telegram:${o}` : `telegram:${n}`,
					to: `telegram:${o}`,
					...c && i !== void 0 ? { threadId: i } : {}
				});
				if (c) return p;
				const m = resolveTelegramOutboundDirectBaseSessionKey({
					cfg: e.cfg,
					route: {
						agentId: e.agentId,
						accountId: f,
						sessionKey: p.sessionKey
					},
					chatId: n
				});
				const h = {
					...p,
					sessionKey: m,
					baseSessionKey: m
				};
				const g = i !== void 0 ? a === "direct-messages" ? buildTelegramConversationId({
					chatId: n,
					thread: {
						id: i,
						scope: a
					}
				}) : `${n}:${i}` : void 0;
				const _ = buildThreadAwareOutboundSessionRoute({
					route: h,
					threadId: g,
					currentSessionKey: e.currentSessionKey,
					precedence: ["threadId", "currentSession"],
					canRecoverCurrentThread: ({ route: t }) => t.chatType !== "direct" || (e.cfg.session?.dmScope ?? "main") !== "main"
				});
				const v = resolveTelegramNativeTopicThreadId(_.threadId, i);
				return {
					..._,
					...v !== void 0 ? { threadId: v } : {},
					from: v !== void 0 ? buildTelegramRoutingTarget(n, {
						id: Number(v),
						scope: a
					}) : `telegram:${n}`
				};
			},
			targetResolver: {
				looksLikeId: looksLikeTelegramTargetId,
				hint: "<chatId>",
				reservedLiterals: [
					"current",
					"self",
					"this",
					"me"
				]
			}
		},
		resolver: { resolveTargets: async (e) => {
			const unresolved = (e, t) => ({
				input: e,
				resolved: false,
				note: t
			});
			if (e.kind !== "user") return e.inputs.map((e) => unresolved(e, "Telegram runtime target resolution only supports usernames for direct-message lookups."));
			const t = resolveTelegramAccount({
				cfg: e.cfg,
				accountId: e.accountId
			});
			const n = t.token.trim();
			if (!n) return e.inputs.map((e) => unresolved(e, "Telegram bot token is required to resolve @username targets."));
			return await Promise.all(e.inputs.map(async (e) => {
				const r = e.trim();
				if (!r) return unresolved(e, "Telegram target is required.");
				const i = r.startsWith("@") ? r : `@${r}`;
				try {
					const r = await lookupTelegramChatId({
						token: n,
						chatId: i,
						proxyUrl: t.config.proxy,
						apiRoot: t.config.apiRoot,
						network: t.config.network
					});
					if (!r) return unresolved(e, "Telegram username could not be resolved by the configured bot.");
					return {
						input: e,
						resolved: true,
						id: r,
						name: i
					};
				} catch (t) {
					return unresolved(e, formatErrorMessage(t));
				}
			}));
		} },
		lifecycle: {
			onAccountConfigChanged: async ({ prevCfg: e, nextCfg: t, accountId: n }) => {
				if (await releaseRotatedTelegramAccountThrottler(e, t, n)) await deleteStartupBotInfoCache(n);
			},
			onAccountRemoved: async ({ accountId: e, prevCfg: t }) => {
				const { deleteTelegramUpdateOffset: n } = await loadTelegramUpdateOffsetRuntime();
				await Promise.all([n({ accountId: e }), deleteStartupBotInfoCache(e)]);
				await releaseRemovedTelegramAccountThrottler(t, e);
			}
		},
		heartbeat: {
			sendTypingGuarded: ({ signal: e, assertPlatformSendAuthorized: t, ...n }) => sendTelegramHeartbeatTyping(n, {
				signal: e,
				assertPlatformSendAuthorized: t
			}),
			sendTyping: sendTelegramHeartbeatTyping
		},
		approvalCapability: {
			...telegramApprovalCapability,
			render: { exec: { buildPendingPayload: buildTelegramExecApprovalPendingPayload } }
		},
		directory: createChannelDirectoryAdapter({
			listPeers: async (e) => listTelegramDirectoryPeersFromConfig(e),
			listGroups: async (e) => listTelegramDirectoryGroupsFromConfig(e)
		}),
		actions: telegramMessageActions,
		message: telegramMessageAdapter,
		status: createComputedAccountStatusAdapter({
			defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID),
			collectStatusIssues: collectTelegramStatusIssues,
			buildChannelSummary: ({ snapshot: e }) => buildTokenChannelStatusSummary(e),
			probeAccount: async ({ account: e, timeoutMs: t }) => probeTelegram(e.token, t, {
				accountId: e.accountId,
				proxyUrl: e.config.proxy,
				network: e.config.network,
				apiRoot: e.config.apiRoot,
				includeWebhookInfo: Boolean(e.config.webhookUrl)
			}),
			formatCapabilitiesProbe: ({ probe: e }) => {
				const t = [];
				if (e?.bot?.username) {
					const n = e.bot.id ? ` (${e.bot.id})` : "";
					t.push({ text: `Bot: @${e.bot.username}${n}` });
				}
				const n = Object.entries({
					joinGroups: e?.bot?.canJoinGroups,
					readAllGroupMessages: e?.bot?.canReadAllGroupMessages,
					inlineQueries: e?.bot?.supportsInlineQueries
				}).flatMap(([e, t]) => typeof t === "boolean" ? [`${e}=${t}`] : []);
				if (n.length > 0) t.push({ text: `Flags: ${n.join(" ")}` });
				if (e?.webhook?.url !== void 0) t.push({ text: `Webhook: ${e.webhook.url || "none"}` });
				return t;
			},
			auditAccount: async ({ account: e, timeoutMs: t, probe: n, cfg: r }) => {
				const i = resolveTelegramAccountConfig(r, e.accountId)?.groups ?? r.channels?.telegram?.groups;
				const { groupIds: a, unresolvedGroups: o, hasWildcardUnmentionedGroups: s } = collectTelegramUnmentionedGroupIds(i);
				if (!a.length && o === 0 && !s) return;
				const c = n?.ok && n.bot?.id != null ? n.bot.id : null;
				if (!c) return {
					ok: o === 0 && !s,
					checkedGroups: 0,
					unresolvedGroups: o,
					hasWildcardUnmentionedGroups: s,
					groups: [],
					elapsedMs: 0
				};
				return {
					...await auditTelegramGroupMembership({
						token: e.token,
						botId: c,
						groupIds: a,
						proxyUrl: e.config.proxy,
						network: e.config.network,
						apiRoot: e.config.apiRoot,
						timeoutMs: t
					}),
					unresolvedGroups: o,
					hasWildcardUnmentionedGroups: s
				};
			},
			resolveAccountSnapshot: ({ account: e, cfg: t, runtime: n, audit: r }) => {
				const i = inspectTelegramAccount({
					cfg: t,
					accountId: e.accountId
				});
				return {
					accountId: e.accountId,
					name: e.name,
					enabled: e.enabled,
					configured: i.configured,
					extra: {
						...projectCredentialSnapshotFields(e),
						lastError: n?.lastError ?? i.stateReason ?? null,
						mode: n?.mode ?? i.mode,
						audit: r,
						allowUnmentionedGroups: i.allowUnmentionedGroups
					}
				};
			}
		}),
		gateway: {
			startAccount: async (e) => {
				const t = e.account;
				const n = resolveAgentRoute({
					cfg: e.cfg,
					channel: "telegram",
					accountId: t.accountId
				}).agentId;
				const r = createAccountStatusSink({
					accountId: t.accountId,
					setStatus: e.setStatus
				});
				const i = findTelegramTokenOwnerAccountId({
					cfg: e.cfg,
					accountId: t.accountId
				});
				if (i) {
					const n = formatDuplicateTelegramTokenReason({
						accountId: t.accountId,
						ownerAccountId: i
					});
					e.log?.error?.(`[${t.accountId}] ${n}`);
					throw new Error(n);
				}
				const a = (t.token ?? "").trim();
				let o = "";
				let s = null;
				let c;
				const accessBotInfoCache = async (n, r) => {
					try {
						return await r();
					} catch (r) {
						if (getTelegramRuntime().logging.shouldLogVerbose()) e.log?.debug?.(`[${t.accountId}] bot info cache ${n} failed: ${String(r)}`);
						return;
					}
				};
				const restoreCachedBotInfo = async () => {
					c = await accessBotInfoCache("read", async () => (await readCachedTelegramBotInfo({
						accountId: t.accountId,
						botToken: a
					}))?.botInfo);
					if (c) o = ` (@${c.username})`;
				};
				try {
					const n = await withTelegramStartupProbeSlot(e.abortSignal, () => probeTelegram(a, resolveTelegramStartupProbeTimeoutMs(void 0), {
						accountId: t.accountId,
						proxyUrl: t.config.proxy,
						network: t.config.network,
						apiRoot: t.config.apiRoot,
						includeWebhookInfo: false,
						abortSignal: e.abortSignal
					}));
					const r = n.ok ? n.bot?.username?.trim() : null;
					if (r) o = ` (@${r})`;
					const i = n.ok ? n.botInfo : void 0;
					c = i;
					if (i) await accessBotInfoCache("write", () => writeCachedTelegramBotInfo({
						accountId: t.accountId,
						botToken: a,
						botInfo: i
					}));
					if (!n.ok && (n.status === 401 || n.status === 404)) {
						await deleteStartupBotInfoCache(t.accountId);
						s = formatTelegramUnauthorizedTokenError(t, n.status);
					} else if (!n.ok) await restoreCachedBotInfo();
				} catch (n) {
					if (e.abortSignal.aborted) return;
					if (getTelegramRuntime().logging.shouldLogVerbose()) e.log?.debug?.(`[${t.accountId}] bot check failed: ${String(n)}`);
					await restoreCachedBotInfo();
				}
				if (s) {
					e.log?.error?.(`[${t.accountId}] ${s}`);
					r(channelBlockedPatch(s));
					throw new Error(s);
				}
				e.log?.info(`[${t.accountId}] starting provider${o}`);
				await monitorTelegramProvider({
					token: a,
					accountId: t.accountId,
					ownerAgentId: n,
					config: e.cfg,
					runtime: e.runtime,
					channelRuntime: e.channelRuntime,
					abortSignal: e.abortSignal,
					useWebhook: Boolean(t.config.webhookUrl),
					webhookUrl: t.config.webhookUrl,
					webhookSecret: t.config.webhookSecret,
					webhookPath: t.config.webhookPath,
					legacyWebhook: t.config.legacyWebhook,
					webhookCertPath: t.config.webhookCertPath,
					botInfo: c,
					setStatus: r
				});
			},
			stopAccount: async ({ account: e, accountId: t, log: n }) => {
				const r = (e.token ?? "").trim();
				if (r) await releaseStoppedTelegramAccountResources({
					token: r,
					accountId: t,
					log: n
				});
			},
			logoutAccount: async ({ accountId: e, cfg: t }) => {
				const n = process.env.TELEGRAM_BOT_TOKEN?.trim() ?? "";
				const { nextConfig: r, changed: i, cleared: a } = clearAccountFieldsFromConfigSection({
					cfg: t,
					sectionKey: "telegram",
					accountId: e,
					fields: ["botToken"]
				});
				const o = resolveTelegramAccount({
					cfg: r,
					accountId: e
				}).tokenSource === "none";
				if (i) await getTelegramRuntime().config.replaceConfigFile({
					nextConfig: r,
					afterWrite: { mode: "auto" }
				});
				if (a || o) await deleteStartupBotInfoCache(e);
				return {
					cleared: a,
					envToken: Boolean(n),
					loggedOut: o
				};
			}
		}
	},
	pairing: { text: {
		idLabel: "telegramUserId",
		message: PAIRING_APPROVED_MESSAGE,
		normalizeAllowEntry: createPairingPrefixStripper(/^(telegram|tg):/i),
		notify: async ({ cfg: e, id: t, message: n, accountId: r }) => {
			const { token: i } = resolveTelegramToken(e, { accountId: r });
			if (!i) throw new Error("telegram token not configured");
			await (await resolveTelegramSend())(t, n, {
				cfg: e,
				token: i,
				accountId: r
			});
		}
	} },
	security: telegramSecurityAdapter,
	threading: {
		matchesToolContextTarget: ({ target: e, toolContext: t }) => {
			return [t.currentMessagingTarget, t.currentChannelId].some((t) => t != null && telegramMessagingTargetsMatch(e, t));
		},
		resolveReplyToMode: ({ cfg: e, accountId: t }) => resolveTelegramConfigAccessorAccount({
			cfg: e,
			accountId: t
		}).config.replyToMode ?? "off",
		buildToolContext: buildTelegramThreadingToolContext,
		resolveAutoThreadId: resolveTelegramAutoThreadId,
		resolveCurrentChannelId: ({ to: e, threadId: t }) => {
			if (t == null) return e;
			const n = parseTelegramTarget(e);
			return n.messageThreadId != null || n.directMessagesTopicId != null ? e : `${e}:topic:${t}`;
		}
	},
	outbound: telegramChannelOutbound
});
//#endregion
export { fetchTelegramChatId as a, resolveTelegramAutoThreadId as c, resolveTelegramGroupToolPolicy as i, collectTelegramStatusIssues as n, lookupTelegramChatId as o, resolveTelegramGroupRequireMention as r, resolveTelegramChatLookupFetch as s, telegramPlugin as t };