UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

820 lines (819 loc) • 32.2 kB
import { c as normalizeOptionalLowercaseString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { A as resolveExpiresAtMsFromDurationMs, E as parseStrictNonNegativeInteger, _ as finiteSecondsToTimerSafeMilliseconds, n as MAX_TIMER_TIMEOUT_MS, y as isFutureDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs"; import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { a as extractErrorCode, d as readErrorName, p as toErrorObject, r as collectErrorGraphCandidates } from "./error-coercion-hDrHOSGy.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { t as captureEffectAuthority } from "./effect-authority-nglmRKHz.mjs"; import { a as createPinnedLookup } from "./ssrf-DHBNJw0c.mjs"; import { a as matchesNoProxy, n as hasEnvHttpProxyAgentConfigured, o as resolveEnvHttpProxyAgentOptions } from "./proxy-env-CZP0dXDG.mjs"; import { n as createHttp1EnvHttpProxyAgent, r as createHttp1ProxyAgent } from "./undici-runtime-ByR6iuTV.mjs"; import { n as isWSL2Sync } from "./wsl-I_VtUW9p.mjs"; import { o as resolveEffectiveDebugProxyUrl } from "./env-Dhl2_42G.mjs"; import { n as captureHttpExchangeAsync } from "./runtime-D7l8z_nQ.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import { t as classifyTransientNetworkErrorCode } from "./retry-runtime-DOUvdfOa.mjs"; import "./number-runtime-W4chuk8B.mjs"; import { r as PlatformMessageNotDispatchedError } from "./deliver-types-BnSKrpHG.mjs"; import "./error-runtime-BM740gJj.mjs"; import { t as resolveFetch } from "./fetch-DGeDtKVy.mjs"; import { n as makeProxyFetch, t as getProxyUrlFromFetch } from "./proxy-fetch-DVhncUsK.mjs"; import "./fetch-runtime-Dz-KqFMb.mjs"; import "./runtime-env-D-Pa5lD6.mjs"; import { t as expectDefined } from "./expect-runtime-DT3P17Ul.mjs"; import "./proxy-capture-Dge29mWm.mjs"; import { t as resolveRequestUrl } from "./request-url-D1UP4HaS.mjs"; import process$1 from "node:process"; import { randomUUID } from "node:crypto"; import { AsyncLocalStorage } from "node:async_hooks"; import * as dns$1 from "node:dns"; import { Agent, fetch } from "undici/index.js"; //#region extensions/telegram/src/api-root.ts const DEFAULT_TELEGRAM_API_ROOT = "https://api.telegram.org"; const TELEGRAM_BOT_ENDPOINT_SEGMENT_RE = /^bot\d+:[^/]+$/u; function isTelegramBotEndpointSegment(e) { try { return TELEGRAM_BOT_ENDPOINT_SEGMENT_RE.test(decodeURIComponent(e)); } catch { return TELEGRAM_BOT_ENDPOINT_SEGMENT_RE.test(e); } } function normalizeTelegramApiRoot(e) { const t = e?.trim(); if (!t) return DEFAULT_TELEGRAM_API_ROOT; if (hasTelegramBotEndpointApiRoot(t)) throw new Error("Telegram apiRoot must be the Bot API root without /bot<TOKEN>. Run openclaw doctor --fix to repair stored config."); return t.replace(/\/+$/u, ""); } function hasTelegramBotEndpointApiRoot(e) { if (typeof e !== "string" || !e.trim()) return false; const t = (URL.parse(e.trim())?.pathname.split("/").filter(Boolean))?.at(-1); return Boolean(t && isTelegramBotEndpointSegment(t)); } function extractTelegramApiMethod(e) { const t = typeof e === "string" ? e : e instanceof URL ? e.toString() : e instanceof Request ? e.url : null; return (URL.parse(t ?? "")?.pathname.split("/").filter(Boolean))?.at(-1)?.toLowerCase() ?? null; } //#endregion //#region extensions/telegram/src/request-timeouts.ts const TELEGRAM_GET_UPDATES_REQUEST_TIMEOUT_MS = 45e3; const TELEGRAM_DEFAULT_REQUEST_TIMEOUT_MS = 6e4; const TELEGRAM_DEFAULT_LONG_POLL_TIMEOUT_SECONDS = 30; const TELEGRAM_LONG_POLL_ABORT_MARGIN_SECONDS = 5; const TELEGRAM_UPLOAD_ASSUMED_BYTES_PER_SECOND = 2097152; const TELEGRAM_UPLOAD_RESPONSE_MARGIN_MS = 15e3; const TELEGRAM_UPLOAD_MAX_TIMEOUT_MS = 18e5; const TELEGRAM_CLIENT_TIMEOUT_BACKSTOP_SECONDS = 1860; const TELEGRAM_REQUEST_TIMEOUTS_MS = { deletemycommands: 15e3, deletewebhook: 15e3, deletemessage: 15e3, editforumtopic: 15e3, editmessagetext: 15e3, getchat: 15e3, getfile: 3e4, getme: 15e3, getupdates: TELEGRAM_GET_UPDATES_REQUEST_TIMEOUT_MS, pinchatmessage: 15e3, sendanimation: 3e4, sendaudio: 3e4, sendchataction: TELEGRAM_DEFAULT_REQUEST_TIMEOUT_MS, senddocument: 3e4, sendmessage: TELEGRAM_DEFAULT_REQUEST_TIMEOUT_MS, sendmessagedraft: TELEGRAM_DEFAULT_REQUEST_TIMEOUT_MS, sendphoto: 3e4, sendvideo: 3e4, sendvoice: 3e4, setmessagereaction: 1e4, setmycommands: 15e3, setwebhook: 15e3 }; function resolveConfiguredTimeoutMs(e, t) { if (typeof e !== "number" || !Number.isFinite(e)) return Math.max(t, 0); return Math.max(t, finiteSecondsToTimerSafeMilliseconds(Math.max(1, e), { floorSeconds: true }) ?? 2147e6); } function resolveTelegramUploadTimeoutMs(e) { if (typeof e !== "number" || !Number.isFinite(e) || e <= 0) return 0; const t = Math.ceil(e / TELEGRAM_UPLOAD_ASSUMED_BYTES_PER_SECOND) * 1e3; return Math.min(t + TELEGRAM_UPLOAD_RESPONSE_MARGIN_MS, TELEGRAM_UPLOAD_MAX_TIMEOUT_MS); } function resolveTelegramRequestTimeoutMs(e, t, n) { if (!e) return; if (e === "getupdates") return TELEGRAM_REQUEST_TIMEOUTS_MS.getupdates; const r = TELEGRAM_REQUEST_TIMEOUTS_MS[e] ?? TELEGRAM_DEFAULT_REQUEST_TIMEOUT_MS; return resolveConfiguredTimeoutMs(t, Math.max(r, resolveTelegramUploadTimeoutMs(n))); } const telegramUploadBytesByFile = /* @__PURE__ */ new WeakMap(); const telegramUploadBytesStore = new AsyncLocalStorage(); /** Remember how many bytes an outgoing InputFile carries. */ function recordTelegramUploadBytes(e, t) { telegramUploadBytesByFile.set(e, t); return e; } function readRecordedUploadBytes(e) { return typeof e === "object" && e !== null && telegramUploadBytesByFile.get(e) || 0; } function readTelegramPayloadUploadBytes(e) { let t = 0; for (const n of Object.values(e ?? {})) if (Array.isArray(n)) { for (const e of n) if (typeof e === "object" && e !== null && "media" in e) t += readRecordedUploadBytes(e.media); } else t += readRecordedUploadBytes(n); return t; } /** * Carry a request's upload size to the client fetch guard. Install inside the * account throttler: its queue runs requests from its own drain loop, so a size * taken from the caller's async context would be lost or cross-attributed. */ const telegramUploadTimeoutTransformer = (e, t, n, r) => { const i = readTelegramPayloadUploadBytes(n); return i > 0 ? telegramUploadBytesStore.run(i, () => e(t, n, r)) : e(t, n, r); }; function getTelegramUploadBytes() { return telegramUploadBytesStore.getStore(); } function resolveTelegramLongPollTimeoutSeconds(e) { const t = Math.max(1, Math.floor(TELEGRAM_GET_UPDATES_REQUEST_TIMEOUT_MS / 1e3) - TELEGRAM_LONG_POLL_ABORT_MARGIN_SECONDS); return Math.min(typeof e === "number" && Number.isFinite(e) ? Math.max(1, Math.floor(e)) : TELEGRAM_DEFAULT_LONG_POLL_TIMEOUT_SECONDS, t); } function resolveTelegramStartupProbeTimeoutMs(e) { return resolveConfiguredTimeoutMs(e, TELEGRAM_REQUEST_TIMEOUTS_MS.getme); } //#endregion //#region extensions/telegram/src/dispatcher-pool-options.ts const TELEGRAM_DISPATCHER_KEEP_ALIVE_TIMEOUT_MS = 3e4; const TELEGRAM_DISPATCHER_KEEP_ALIVE_MAX_TIMEOUT_MS = 6e5; const TELEGRAM_DISPATCHER_CONNECTIONS_PER_ORIGIN = 10; function telegramAgentPoolOptions(e) { return { allowH2: false, keepAliveTimeout: TELEGRAM_DISPATCHER_KEEP_ALIVE_TIMEOUT_MS, keepAliveMaxTimeout: TELEGRAM_DISPATCHER_KEEP_ALIVE_MAX_TIMEOUT_MS, connections: TELEGRAM_DISPATCHER_CONNECTIONS_PER_ORIGIN, pipelining: e, headersTimeout: TELEGRAM_CLIENT_TIMEOUT_BACKSTOP_SECONDS * 1e3 }; } //#endregion //#region extensions/telegram/src/network-config.ts const TELEGRAM_DISABLE_AUTO_SELECT_FAMILY_ENV = "OPENCLAW_TELEGRAM_DISABLE_AUTO_SELECT_FAMILY"; const TELEGRAM_ENABLE_AUTO_SELECT_FAMILY_ENV = "OPENCLAW_TELEGRAM_ENABLE_AUTO_SELECT_FAMILY"; const TELEGRAM_DNS_RESULT_ORDER_ENV = "OPENCLAW_TELEGRAM_DNS_RESULT_ORDER"; let wsl2SyncCache; function resolveTelegramAutoSelectFamilyDecision(e) { if (isTruthyEnvValue(process$1.env[TELEGRAM_ENABLE_AUTO_SELECT_FAMILY_ENV])) return true; if (isTruthyEnvValue(process$1.env[TELEGRAM_DISABLE_AUTO_SELECT_FAMILY_ENV])) return false; if (typeof e?.network?.autoSelectFamily === "boolean") return e.network.autoSelectFamily; if (wsl2SyncCache ??= isWSL2Sync()) return false; return resolveTelegramDnsResultOrderDecision(e).value !== "ipv4first"; } function resolveTelegramDnsResultOrderDecision(e) { for (const [t, n] of [ [`env:${TELEGRAM_DNS_RESULT_ORDER_ENV}`, () => process$1.env[TELEGRAM_DNS_RESULT_ORDER_ENV]], ["config", () => e?.network?.dnsResultOrder], ["process-default", () => dns$1.getDefaultResultOrder()] ]) { const e = normalizeOptionalLowercaseString(n()); if (e === "ipv4first" || e === "verbatim" || t === "process-default" && e === "ipv6first") return { value: e, source: t }; } return { value: "ipv4first", source: "default-node22" }; } //#endregion //#region extensions/telegram/src/network-errors.ts const TELEGRAM_SUPERGROUP_MIGRATION_DESCRIPTION = "Bad Request: group chat was upgraded to a supergroup chat"; var TelegramRequestNotStartedError = class extends Error { constructor(e = "Telegram request did not start", t) { super(e, t); this.name = "TelegramRequestNotStartedError"; } }; function isTelegramRequestNotStartedError(e) { return e instanceof TelegramRequestNotStartedError || readErrorName(e) === "HttpError" && e.error instanceof TelegramRequestNotStartedError; } function rethrowTelegramSendError(e) { if (isTelegramRequestNotStartedError(e)) throw new PlatformMessageNotDispatchedError("Telegram request not started", { cause: e }); const t = describeTelegramSupergroupMigration(e); if (t !== void 0) throw new PlatformMessageNotDispatchedError(t, { cause: e, retryable: false }); if (isRecord(e) && e.error_code === 400 && (e.description === "Bad Request: chat not found" || e.description === "Bad Request: message thread not found")) throw new PlatformMessageNotDispatchedError(formatErrorMessage(e), { cause: e }); throw e; } const TELEGRAM_ADDITIONAL_TRANSIENT_ERROR_CODES = /* @__PURE__ */ new Set([ "ENETDOWN", "ESOCKETTIMEDOUT", "EHOSTUNREACH", "UND_ERR_ABORTED", "ECONNABORTED", "ERR_NETWORK" ]); const TELEGRAM_ADDITIONAL_PRE_CONNECT_ERROR_CODES = /* @__PURE__ */ new Set(["ENETDOWN", "EHOSTUNREACH"]); const RECOVERABLE_ERROR_NAMES = /* @__PURE__ */ new Set([ "AbortError", "TimeoutError", "ConnectTimeoutError", "HeadersTimeoutError", "BodyTimeoutError" ]); const ALWAYS_RECOVERABLE_MESSAGES = /* @__PURE__ */ new Set(["fetch failed", "typeerror: fetch failed"]); const RECOVERABLE_MESSAGE_SNIPPETS = [ "undici", "network error", "network request", "client network socket disconnected", "socket hang up", "getaddrinfo", "timeout", "timed out" ]; function collectTelegramErrorCandidates(e) { return collectErrorGraphCandidates(e, (e) => { const t = [e.cause, e.reason]; if (Array.isArray(e.errors)) t.push(...e.errors); if (readErrorName(e) === "HttpError") t.push(e.error); return t; }); } function normalizedErrorCode(e) { let t = extractErrorCode(e); if (!t && e && typeof e === "object") { const n = e.errno; if (typeof n === "string" || typeof n === "number") t = String(n); } return t?.trim().toUpperCase() ?? ""; } function classifyTelegramTransientNetworkError(e) { const t = normalizedErrorCode(e); return classifyTransientNetworkErrorCode(t) ?? (TELEGRAM_ADDITIONAL_PRE_CONNECT_ERROR_CODES.has(t) ? "pre-connect" : TELEGRAM_ADDITIONAL_TRANSIENT_ERROR_CODES.has(t) ? "ambiguous" : void 0); } function hasTelegramNetworkErrorCode(e) { return collectTelegramErrorCandidates(e).some((e) => classifyTelegramTransientNetworkError(e) !== void 0); } function getNumericHttpStatus(e) { if (!e || typeof e !== "object") return; const t = e; for (const e of [ t.error_code, t.status, t.statusCode ]) { if (typeof e === "number" && Number.isFinite(e)) return e; if (typeof e === "string") { const t = e.trim(); if (/^\d+$/.test(t)) return parseStrictNonNegativeInteger(t); } } } function describeTelegramSupergroupMigration(e) { for (const t of collectTelegramErrorCandidates(e)) { if (!isRecord(t) || t.error_code !== 400 || t.description !== TELEGRAM_SUPERGROUP_MIGRATION_DESCRIPTION) continue; const e = isRecord(t.parameters) ? t.parameters.migrate_to_chat_id : void 0; return typeof e === "number" && Number.isSafeInteger(e) ? `Telegram rejected send: group migrated to supergroup ${e}` : "Telegram rejected send: group migrated to a supergroup"; } } function isTelegramMisdirectedRequestError(e) { for (const t of collectTelegramErrorCandidates(e)) { if (normalizedErrorCode(t) === "421" || getNumericHttpStatus(t) === 421) return true; const e = normalizeLowercaseStringOrEmpty(formatErrorMessage(t)); if (/\b421\b/.test(e) && e.includes("misdirected request")) return true; } return false; } /** True only for channel-owned no-send proof or proven pre-connect failures. */ function isSafeToRetrySendError(e) { if (!e) return false; if (e instanceof PlatformMessageNotDispatchedError) return e.retryable; if (isTelegramRequestNotStartedError(e)) return true; return collectTelegramErrorCandidates(e).some((e) => classifyTelegramTransientNetworkError(e) === "pre-connect"); } function hasTelegramErrorCode(e, t) { return collectTelegramErrorCandidates(e).some((e) => { if (!e || typeof e !== "object" || !("error_code" in e)) return false; const n = e.error_code; return typeof n === "number" && t(n); }); } function isTelegramAuthenticationError(e) { return hasTelegramErrorCode(e, (e) => e === 401 || e === 404); } /** Reads Telegram's flood-control retry_after hint (in ms) from any error nesting shape. */ function readTelegramRetryAfterMs(e) { for (const t of collectTelegramErrorCandidates(e)) { if (!t || typeof t !== "object") continue; const e = "parameters" in t && t.parameters && typeof t.parameters === "object" ? t.parameters.retry_after : "response" in t && t.response && typeof t.response === "object" && "parameters" in t.response ? t.response.parameters?.retry_after : "error" in t && t.error && typeof t.error === "object" && "parameters" in t.error ? t.error.parameters?.retry_after : void 0; if (typeof e === "number" && Number.isFinite(e)) return e * 1e3; } } /** Returns true for HTTP 5xx server errors (error may have been processed). */ function isTelegramServerError(e) { return hasTelegramErrorCode(e, (e) => e >= 500); } function isTelegramRateLimitError(e) { return hasTelegramErrorCode(e, (e) => e === 429) || readTelegramRetryAfterMs(e) !== void 0 && /(?:^|\b)429\b|too many requests/i.test(formatErrorMessage(e)); } const MESSAGE_NOT_MODIFIED_RE = /400:\s*Bad Request:\s*message is not modified|MESSAGE_NOT_MODIFIED/i; const MESSAGE_HAS_NO_TEXT_RE = /400:\s*Bad Request:\s*there is no text in the message to edit/i; const EDIT_TARGET_MISSING_RE = /400:\s*Bad Request:\s*message to edit not found|400:\s*Bad Request:\s*message can't be edited|MESSAGE_ID_INVALID/i; /** True when Telegram rejected an edit because the content is unchanged; the message already shows the requested text. */ function isTelegramMessageNotModifiedError(e) { return MESSAGE_NOT_MODIFIED_RE.test(formatErrorMessage(e)); } /** True when the edit target has no text body (e.g. media message needing a caption edit). */ function isTelegramMessageHasNoTextError(e) { return MESSAGE_HAS_NO_TEXT_RE.test(formatErrorMessage(e)); } /** True when the edit target is gone or locked (deleted message, invalid id); retrying the same edit cannot succeed. */ function isTelegramEditTargetMissingError(e) { return EDIT_TARGET_MISSING_RE.test(formatErrorMessage(e)); } /** Returns true for HTTP 4xx client errors (Telegram explicitly rejected, not applied). */ function isTelegramClientRejection(e) { return hasTelegramErrorCode(e, (e) => e >= 400 && e < 500); } function isTelegramBadRequestError(e) { return hasTelegramErrorCode(e, (e) => e === 400); } function isRecoverableTelegramNetworkError(e) { if (!e) return false; if (isTelegramRequestNotStartedError(e)) return true; for (const t of collectTelegramErrorCandidates(e)) { if (classifyTelegramTransientNetworkError(t)) return true; const e = readErrorName(t); if (e && RECOVERABLE_ERROR_NAMES.has(e)) return true; const n = normalizeLowercaseStringOrEmpty(formatErrorMessage(t)); if (n && (ALWAYS_RECOVERABLE_MESSAGES.has(n) || RECOVERABLE_MESSAGE_SNIPPETS.some((e) => n.includes(e)))) return true; } return false; } function isRetryableTelegramApiError(e) { return isRecoverableTelegramNetworkError(e) || isTelegramServerError(e) || isTelegramRateLimitError(e); } //#endregion //#region extensions/telegram/src/request-authority.ts const requestAuthority = Symbol("telegram.requestAuthority"); /** Distinguish a local rejection from a network error wrapped by grammY. */ var TelegramRequestAuthorityError = class extends Error { constructor(e) { super("Telegram request authority rejected"); this.originalError = e; } }; function findTelegramRequestAuthorityError(e) { return collectErrorGraphCandidates(e, (e) => [e.cause, e.error]).find((e) => e instanceof TelegramRequestAuthorityError); } function assertTelegramRequestAuthority(e) { try { e?.(); } catch (e) { throw new TelegramRequestAuthorityError(e); } } /** Keep the selected transport and guard every request, including Undici's HTTP 421 retry. */ function bindTelegramTransportAuthority(e, t) { const n = captureEffectAuthority(); return (r, i, a) => { const o = i?.dispatcher; let s = withoutTelegramRequestAuthority(i); if (!o && a) s = { ...s, dispatcher: a }; if (!t && !n.active) return e(r, s); assertTelegramRequestAuthority(t); const c = o ?? a; if (c) { const e = new AbortController(); const a = i?.signal === void 0 && r instanceof Request ? r.signal : i?.signal; const o = a ? AbortSignal.any([a, e.signal]) : e.signal; s = { ...s, signal: o, dispatcher: c.compose((r) => (i, a) => { let s = false; n.initiate(() => { o.throwIfAborted(); assertTelegramRequestAuthority(t); s = true; return r(i, a); }).catch((t) => { const n = s ? toErrorObject(t, "Telegram dispatch failed") : findTelegramRequestAuthorityError(t) ?? new TelegramRequestAuthorityError(t); e.abort(n); }); return true; }) }; } const request = () => { assertTelegramRequestAuthority(t); return e(r, s); }; return (c ? n.run(request) : n.initiate(request)).catch((e) => { throw findTelegramRequestAuthorityError(e) ?? e; }); }; } /** Keep operation authority off the shared client's cached fetch options. */ function bindTelegramRequestAuthority(e, t) { const n = captureEffectAuthority(); const guardedFetch = (r, i) => { const a = { ...i, [requestAuthority]: t }; return n.run(() => e(r, a)); }; return Object.assign(guardedFetch, e); } function getTelegramRequestAuthority(e) { return e?.[requestAuthority]; } /** The private callback travels between our retry layers, never to the HTTP client. */ function withoutTelegramRequestAuthority(e) { if (!e || !(requestAuthority in e)) return e; const t = { ...e }; delete t[requestAuthority]; return t; } //#endregion //#region extensions/telegram/src/fetch.ts const log = createSubsystemLogger("telegram/network"); const TELEGRAM_AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_MS = 300; const TELEGRAM_API_HOSTNAME = "api.telegram.org"; const TELEGRAM_FALLBACK_IPS = ["149.154.167.220"]; const TELEGRAM_STICKY_FALLBACK_PRIMARY_PROBE_SUCCESS_THRESHOLD = 5; const TELEGRAM_TRANSPORT_ATTEMPT_FAILURE_THRESHOLD = 5; const TELEGRAM_TRANSPORT_ATTEMPT_INITIAL_COOLDOWN_MS = 1e4; const TELEGRAM_TRANSPORT_ATTEMPT_MAX_COOLDOWN_MS = 6e4; const FALLBACK_RETRY_ERROR_CODES = [ "ETIMEDOUT", "ENETDOWN", "ENETUNREACH", "EHOSTUNREACH", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET" ]; function createDnsResultOrderLookup(e) { const t = dns$1.lookup; return (n, r, i) => { t(n, { ...typeof r === "number" ? { family: r } : r, order: e, verbatim: e === "verbatim" }, i); }; } const TELEGRAM_KEEPALIVE_INITIAL_DELAY_MS = 3e4; function resolveTelegramDispatcherPolicy(e) { const t = { keepAlive: true, keepAliveInitialDelay: TELEGRAM_KEEPALIVE_INITIAL_DELAY_MS, ...e.forceIpv4 ? { family: 4, autoSelectFamily: false } : { autoSelectFamily: e.autoSelectFamily, autoSelectFamilyAttemptTimeout: TELEGRAM_AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_MS }, lookup: createDnsResultOrderLookup(e.dnsResultOrder) }; const n = e.proxyUrl?.trim(); if (n) return { mode: "explicit-proxy", proxyUrl: n, allowPrivateProxy: true, proxyTls: t }; return { mode: e.useEnvProxy ? "env-proxy" : "direct", connect: t }; } function withPinnedLookup(e, t) { if (!t) return e ? { ...e } : void 0; const n = createPinnedLookup({ hostname: t.hostname, addresses: [...t.addresses], fallback: dns$1.lookup }); return { ...e, lookup: n }; } function createTelegramDispatcher(e, t = 1) { const n = telegramAgentPoolOptions(t); let r; if (e.mode === "explicit-proxy") { const t = withPinnedLookup(e.proxyTls, e.pinnedHostname); const i = { uri: e.proxyUrl, ...n, ...t ? { requestTls: t } : {} }; try { r = createHttp1ProxyAgent(i); } catch (e) { const t = formatErrorMessage(e); throw new Error(`explicit proxy dispatcher init failed: ${t}`, { cause: e }); } } else { const i = withPinnedLookup(e.connect, e.pinnedHostname); const a = { ...n, ...i ? { connect: i } : {} }; if (e.mode === "direct") { r = new Agent(a); return { dispatcher: r, mode: e.mode, effectivePolicy: e }; } const o = withPinnedLookup(e.proxyTls, e.pinnedHostname); const s = { ...a, ...resolveEnvHttpProxyAgentOptions(), ...o ? { proxyTls: o } : {} }; try { r = createHttp1EnvHttpProxyAgent(s); } catch (e) { log.warn(`env proxy dispatcher init failed; falling back to direct dispatcher: ${formatErrorMessage(e)}`); return createTelegramDispatcher({ mode: "direct", ...i ? { connect: i } : {} }, t); } } return { dispatcher: r, mode: e.mode, effectivePolicy: e }; } function resolveWrappedFetch(e) { return resolveFetch(e) ?? e; } function collectErrorCodes(e) { const t = /* @__PURE__ */ new Set(); for (const n of collectErrorGraphCandidates(e, (e) => [e.cause, ...Array.isArray(e.errors) ? e.errors : []])) if (n && typeof n === "object") { const e = n.code; if (typeof e === "string" && e.trim()) t.add(e.trim().toUpperCase()); } return t; } function formatErrorCodes(e) { const t = [...collectErrorCodes(e)]; return t.length > 0 ? t.join(",") : "none"; } function shouldRetryTelegramTransportFallback(e) { if (findTelegramRequestAuthorityError(e)) return false; const t = e && typeof e === "object" && "message" in e ? normalizeLowercaseStringOrEmpty(String(e.message)) : ""; const n = collectErrorCodes(e); return FALLBACK_RETRY_ERROR_CODES.some((e) => n.has(e)) || t.includes("fetch failed") && n.size === 0; } const UNDICI_PROXY_TUNNEL_REJECTED_RE = /^Proxy response \((\d{3})\) !== 200 when HTTP Tunneling$/; const UNDICI_PROXY_CONNECTION_ERROR_CODE = "UND_ERR_PRX_CONN"; function describeProxyTunnelFailure(e, t) { if (e !== "explicit-proxy" && e !== "env-proxy") return; for (const e of collectErrorGraphCandidates(t, (e) => [e.cause, ...Array.isArray(e.errors) ? e.errors : []])) { const t = extractErrorCode(e); if (t === UNDICI_PROXY_CONNECTION_ERROR_CODE) return "proxy connection failed while opening the tunnel"; if (t !== "UND_ERR_ABORTED" || !e || typeof e !== "object") continue; const n = "message" in e ? e.message : void 0; const r = typeof n === "string" ? UNDICI_PROXY_TUNNEL_REJECTED_RE.exec(n) : null; if (r) return `proxy answered CONNECT with ${r[1]}`; } } function resolveTelegramTransport(e, t) { const n = resolveTelegramAutoSelectFamilyDecision({ network: t?.network }); const r = resolveTelegramDnsResultOrderDecision({ network: t?.network }); const i = e ?? (() => { const e = resolveEffectiveDebugProxyUrl(void 0); return e ? makeProxyFetch(e) : void 0; })(); const a = i ? getProxyUrlFromFetch(i) : void 0; const o = !a && hasEnvHttpProxyAgentConfigured(); const s = !i && !o ? process.env.OPENCLAW_PROXY_URL?.trim() || void 0 : void 0; const c = a ?? s; const l = resolveWrappedFetch(fetch); const u = !c && i ? resolveWrappedFetch(i) : l; if (i && !a) return { fetch: u, sourceFetch: u, close: async () => {} }; const d = !c && o; const f = createTelegramDispatcher(resolveTelegramDispatcherPolicy({ autoSelectFamily: n, dnsResultOrder: r.value, useEnvProxy: d, forceIpv4: false, proxyUrl: c })); const p = matchesNoProxy(`https://${TELEGRAM_API_HOSTNAME}`); const m = !((r.source === "config" || r.source === `env:${"OPENCLAW_TELEGRAM_DNS_RESULT_ORDER"}`) && r.value !== "ipv4first") && (f.mode === "direct" || f.mode === "env-proxy" && p) ? resolveTelegramDispatcherPolicy({ autoSelectFamily: false, dnsResultOrder: "ipv4first", useEnvProxy: f.mode === "env-proxy", forceIpv4: true, proxyUrl: c }) : void 0; const h = /* @__PURE__ */ new Set(); const createAttempt = (e, t) => { const n = /* @__PURE__ */ new Map(); if (t) { n.set(false, t); h.add(t); } return { exportAttempt: { dispatcherPolicy: e }, createDispatcher: (t = false) => { let r = n.get(t); if (!r) { r = createTelegramDispatcher(e, t ? 0 : 1).dispatcher; n.set(t, r); h.add(r); } return r; } }; }; const g = [createAttempt(f.effectivePolicy, f.dispatcher)]; if (m) { g.push({ ...createAttempt(m), logLevel: "debug", logMessage: "fetch fallback: enabling sticky IPv4-only dispatcher" }); g.push({ ...createAttempt({ ...m, pinnedHostname: { hostname: TELEGRAM_API_HOSTNAME, addresses: [...TELEGRAM_FALLBACK_IPS] } }), logLevel: "warn", logMessage: "fetch fallback: primary connection path failed; trying alternative Telegram API IP" }); } let _ = 0; let v = 0; let y = false; const b = g.map(() => ({ consecutiveFailures: 0, cooldownMs: TELEGRAM_TRANSPORT_ATTEMPT_INITIAL_COOLDOWN_MS, unhealthyUntilMs: 0 })); const resetStickyRecoveryProbe = () => { v = 0; y = false; }; const getAttemptCooldownError = (e) => { const t = expectDefined(b[e], "transport attempt health index"); if (!isFutureDateTimestampMs(t.unhealthyUntilMs)) return null; const n = Math.max(0, t.unhealthyUntilMs - Date.now()); return new TelegramRequestNotStartedError(`Telegram transport attempts are cooling down; retry after ${n}ms`); }; const recordAttemptFailure = (e, t) => { if (!shouldRetryTelegramTransportFallback(t)) return; const n = expectDefined(b[e], "transport attempt health index"); n.consecutiveFailures += 1; if (n.consecutiveFailures < TELEGRAM_TRANSPORT_ATTEMPT_FAILURE_THRESHOLD) return; const r = Math.min(TELEGRAM_TRANSPORT_ATTEMPT_MAX_COOLDOWN_MS, Math.max(TELEGRAM_TRANSPORT_ATTEMPT_INITIAL_COOLDOWN_MS, n.cooldownMs)); n.consecutiveFailures = 0; n.cooldownMs = Math.min(TELEGRAM_TRANSPORT_ATTEMPT_MAX_COOLDOWN_MS, r * 2); const i = resolveExpiresAtMsFromDurationMs(r); if (i === void 0) { n.unhealthyUntilMs = 0; return; } n.unhealthyUntilMs = i; log.warn(`telegram transport attempt marked temporarily unhealthy for ${r}ms (codes=${formatErrorCodes(t)})`); }; const promoteStickyAttempt = (e, t, n) => { if (e <= _ || e >= g.length) return false; const r = expectDefined(g[e], "validated fallback attempt index"); if (r.logMessage) { const e = n ? `, reason=${n}` : ""; const i = `${r.logMessage} (codes=${formatErrorCodes(t)}${e})`; log[r.logLevel ?? "warn"](i); } _ = e; resetStickyRecoveryProbe(); return true; }; const recordSuccessfulAttempt = (e) => { const t = expectDefined(b[e], "transport attempt health index"); t.consecutiveFailures = 0; t.cooldownMs = TELEGRAM_TRANSPORT_ATTEMPT_INITIAL_COOLDOWN_MS; t.unhealthyUntilMs = 0; if (_ === 0) { resetStickyRecoveryProbe(); return; } if (e < _) { _ = e; resetStickyRecoveryProbe(); return; } if (e !== _) return; v += 1; if (v >= TELEGRAM_STICKY_FALLBACK_PRIMARY_PROBE_SUCCESS_THRESHOLD) { v = 0; y = true; } }; let x = false; const resolvedFetch = (async (e, t) => { if (x) throw new TelegramRequestNotStartedError("Telegram transport is closed"); const n = extractTelegramApiMethod(e); const r = n === "sendmessage" || n === "sendrichmessage"; const shouldRetryRequest = (e) => !x && shouldRetryTelegramTransportFallback(e) && (!r || isSafeToRetrySendError(e)); const i = bindTelegramTransportAuthority(u, getTelegramRequestAuthority(t)); const a = t?.signal ?? (e instanceof Request ? e.signal : void 0); const o = Boolean(t?.dispatcher); const s = Math.min(_, g.length - 1); const c = o ? null : getAttemptCooldownError(s); const l = !o && s > 0 && (y || c !== null); const d = l ? 0 : s; if (l) y = false; let f; const captureResponse = (n, r) => { captureHttpExchangeAsync({ url: resolveRequestUrl(e), method: t?.method ?? "GET", requestHeaders: t?.headers, requestBody: t?.body ?? null, response: n, flowId: randomUUID(), meta: { subsystem: "telegram-fetch", ...r === void 0 ? {} : { fallbackAttempt: r } } }).catch(() => {}); }; if (o) try { const n = await i(e, t); a?.throwIfAborted(); captureResponse(n); return n; } catch (n) { a?.throwIfAborted(); if (!shouldRetryRequest(n)) throw n; const r = await i(e, t ?? {}); a?.throwIfAborted(); return r; } for (let n = d; n < g.length; n += 1) { const o = expectDefined(g[n], "transport attempt loop index"); if (n > d) promoteStickyAttempt(n, f); const s = getAttemptCooldownError(n); if (s) { f = s; continue; } try { const s = await i(e, t, o.createDispatcher(r)); a?.throwIfAborted(); captureResponse(s, n === d ? void 0 : n); recordSuccessfulAttempt(n); return s; } catch (e) { a?.throwIfAborted(); const t = describeProxyTunnelFailure(o.exportAttempt.dispatcherPolicy?.mode, e); if (t) throw new TelegramRequestNotStartedError(`Telegram proxy tunnel did not open: ${t}`, { cause: e }); f = e; recordAttemptFailure(n, f); if (!shouldRetryRequest(f)) throw f; } } throw f; }); return { fetch: resolvedFetch, sourceFetch: u, dispatcherAttempts: g.map((e) => e.exportAttempt), forceFallback: (e, t) => promoteStickyAttempt(_ + 1, t ?? /* @__PURE__ */ new Error("forced fallback"), e), close: async () => { x = true; const e = [...h]; h.clear(); await Promise.allSettled(e.map(async (e) => e.destroy())); } }; } function resolveTelegramFetch(e, t) { return resolveTelegramTransport(e, t).fetch; } //#endregion export { resolveTelegramRequestTimeoutMs as A, readTelegramRetryAfterMs as C, getTelegramUploadBytes as D, TELEGRAM_GET_UPDATES_REQUEST_TIMEOUT_MS as E, normalizeTelegramApiRoot as F, telegramUploadTimeoutTransformer as M, extractTelegramApiMethod as N, recordTelegramUploadBytes as O, hasTelegramBotEndpointApiRoot as P, isTelegramServerError as S, TELEGRAM_CLIENT_TIMEOUT_BACKSTOP_SECONDS as T, isTelegramEditTargetMissingError as _, bindTelegramRequestAuthority as a, isTelegramMisdirectedRequestError as b, withoutTelegramRequestAuthority as c, isRecoverableTelegramNetworkError as d, isRetryableTelegramApiError as f, isTelegramClientRejection as g, isTelegramBadRequestError as h, assertTelegramRequestAuthority as i, resolveTelegramStartupProbeTimeoutMs as j, resolveTelegramLongPollTimeoutSeconds as k, TelegramRequestNotStartedError as l, isTelegramAuthenticationError as m, resolveTelegramTransport as n, findTelegramRequestAuthorityError as o, isSafeToRetrySendError as p, shouldRetryTelegramTransportFallback as r, getTelegramRequestAuthority as s, resolveTelegramFetch as t, hasTelegramNetworkErrorCode as u, isTelegramMessageHasNoTextError as v, rethrowTelegramSendError as w, isTelegramRateLimitError as x, isTelegramMessageNotModifiedError as y };