UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

871 lines (870 loc) • 30.8 kB
import "./redact-BDinS1q9.js"; import "./errors-BxyFnvP3.js"; import "./unhandled-rejections-CDJ8dOVP.js"; import "./logger-kwZIqwuw.js"; import "./paths-ViKUYWUK.js"; import "./tmp-openclaw-dir-idKIOMmb.js"; import "./theme-CdOoMzRk.js"; import "./globals-DBUMOBZ8.js"; import "./subsystem-DISldKSB.js"; import "./ansi-BEJF8NKS.js"; import "./boolean-C3GkJetE.js"; import "./env-Dnra1IpT.js"; import "./warning-filter-CBhOcgHd.js"; import "./utils-CS0Ikux6.js"; import "./links-8xRhWBQL.js"; import "./paths-C4Oy7wjk.js"; import "./auth-profiles-DRuJBw5y.js"; import "./agent-scope-bjWqU22i.js"; import "./boundary-path-Dm0QJ7-y.js"; import "./boundary-file-read-DcZxlWD8.js"; import "./logger-BmpSCz93.js"; import "./exec-B5_AYfQG.js"; import "./workspace-D4K6QX9X.js"; import "./model-selection-BnFtDmP7.js"; import "./io-y3Az_Onx.js"; import "./shell-env-BOu7XeT_.js"; import "./safe-text-yavot2qw.js"; import "./version-CD3oP1-d.js"; import "./env-substitution-O6uabUmO.js"; import "./includes-Bj3eLUWH.js"; import "./zod-schema.providers-core-COy5nBQ0.js"; import "./legacy-web-search-BB-ZHEhz.js"; import "./registry-C5UkPpaO.js"; import "./config-state-Br0ucqMb.js"; import "./min-host-version-RMBWtIAR.js"; import "./manifest-registry-B5JNQdOM.js"; import "./runtime-guard-PhQ6PwQa.js"; import "./avatar-policy-B5nOfso_.js"; import "./ip-Ce8EDTBZ.js"; import "./zod-schema.agent-runtime-Dtg4Jy6G.js"; import "./zod-schema.core-BuVz8Rk7.js"; import "./config-D4zN4BRl.js"; import "./file-lock-DEiVq2ow.js"; import "./audit-fs-DTQIjp2r.js"; import "./resolve-B7S4PlnO.js"; import "./profiles-COPO-hHI.js"; import "./tailscale-CxY-91GZ.js"; import "./tailnet-DHiKSG7V.js"; import { u as resolveClientIp } from "./net-JAg9zL0G.js"; import "./auth-Buq0Niri.js"; import "./credentials-D8pfRimu.js"; import "./message-channel-BliByQBl.js"; import "./store-C5UK26Ce.js"; import "./runtime-Iz8uZ7EU.js"; import "./plugins-B09-vgme.js"; import "./sessions-D9ZgHCHb.js"; import "./paths-rhN9LKM_.js"; import "./session-write-lock-va3qZE6f.js"; import "./method-scopes-BiEi0X2g.js"; import "./call-CQbSO4Fr.js"; import "./prompt-style-C4CV4Y_p.js"; import "./ports-lsof-BLEgL_Gn.js"; import "./restart-stale-pids-BsPvlGJd.js"; import "./ports-FldL_Lhq.js"; import "./logging-CznuqaMu.js"; import "./commands-C6oAw_H-.js"; import "./issue-format-BtLIwOtN.js"; import "./identity-Dp-UIak4.js"; import "./heartbeat-Bdfr_onc.js"; import { Ab as isNormalizedSenderAllowed, So as resolveSenderCommandAuthorizationWithRuntime, Zv as resolveInboundRouteEnvelopeBuilderWithRuntime, bo as resolveDirectDmAuthorizationOutcome } from "./pi-embedded-CbCYZxIb.js"; import "./internal-hooks-CIUghoK4.js"; import "./multimodal-B8yEZcl5.js"; import "./memory-search-B_aq08y5.js"; import "./provider-catalog-rVN7ZbR5.js"; import "./secret-input-DXoOLNgb.js"; import "./bindings-CFudGB9Z.js"; import "./resolve-route-DwFWP4JW.js"; import "./routing-zOQ0wwtV.js"; import "./identity-file-DVLib087.js"; import "./outbound-runtime-m-y0nd6F.js"; import "./provider-env-vars-CpUJqT5v.js"; import "./provider-auth-input-Bus9W_qh.js"; import "./provider-model-minimax-DSmX4BNO.js"; import "./provider-models-BKjzpTsb.js"; import "./anthropic-vertex-provider-B2x4YywE.js"; import "./provider-catalog-BTgF8VyO.js"; import "./provider-catalog-D0IlX18O.js"; import "./provider-catalog-BTmUX0Mp.js"; import "./provider-catalog-sph_Rl63.js"; import "./provider-catalog-C7tUyBwV.js"; import "./provider-catalog-C8dPZpHW.js"; import "./provider-catalog-BJNff1VI.js"; import "./provider-catalog-IAdymoqT.js"; import "./provider-catalog-Bjc7evzh.js"; import "./models-config.providers.discovery-CjkO08q6.js"; import "./text-runtime-DVXt5xhi.js"; import "./tool-catalog-BjSY4C4F.js"; import "./docker-Bhjg8g2t.js"; import "./sandbox-DTlKNieF.js"; import "./common-zReYuoMM.js"; import "./image-ops-By4YfyWa.js"; import "./thinking-CJoSRIGR.js"; import "./path-alias-guards-CwRM04O1.js"; import "./sandbox-paths-Cn8i8Jxm.js"; import "./channel-actions-fV93bLjV.js"; import "./mime-CsUtzcn2.js"; import "./ssrf-0bPJMoZR.js"; import "./fetch-guard-CYl1q2XH.js"; import "./provider-web-search-COZNygbd.js"; import "./manager-Bw8JrihM.js"; import "./config-schema-CPzP2Ds6.js"; import "./channel-plugin-common-ClptUZHU.js"; import { a as warnMissingProviderGroupPolicyFallbackOnce, r as resolveDefaultGroupPolicy } from "./runtime-group-policy-D8ugNNDZ.js"; import "./status-helpers-Cflmo90d.js"; import "./conversation-runtime-nmWgJSXS.js"; import "./runtime-whatsapp-boundary-XjdkYMz_.js"; import "./pairing-store-BGKLrjo6.js"; import "./json-store--JDX3zNL.js"; import { n as createChannelPairingController } from "./channel-pairing-BrG9NqjP.js"; import "./secret-file-Bif7RlZ-.js"; import "./channel-config-schema-CgpS17zB.js"; import "./setup-binary-C2MYZTCc.js"; import "./archive-pOxyr9r4.js"; import "./fs-safe-DZyOgpPN.js"; import "./signal-cli-install-fVOL9FvX.js"; import "./setup-wizard-proxy-DoOpOF8S.js"; import "./setup-BI3ohdrT.js"; import "./dm-policy-shared-DtcQProI.js"; import { t as waitForAbortSignal } from "./abort-signal-DhpD4wkb.js"; import "./runtime-env-DQOYrXVl.js"; import "./temp-path-B91lt0LF.js"; import "./diagnostic-CDTtMQBT.js"; import "./logging-CCTKg_fh.js"; import "./config-runtime-BYNizC50.js"; import "./level-overrides-DzIzQ3ZY.js"; import { t as createDedupeCache } from "./dedupe-DML1ACVm.js"; import { l as logTypingFailure } from "./channel-feedback-BSaFwmB3.js"; import "./exec-approvals-BF_Qfdq8.js"; import { C as WEBHOOK_ANOMALY_COUNTER_DEFAULTS, D as createFixedWindowRateLimiter, O as createWebhookAnomalyTracker, T as WEBHOOK_RATE_LIMIT_DEFAULTS, _ as applyBasicWebhookRequestGuards, c as withResolvedWebhookRequestPipeline, n as registerWebhookTargetWithPluginRoute, o as resolveWebhookTargetWithAuthOrRejectSync, t as registerWebhookTarget, x as readJsonWebhookBodyOrReject } from "./webhook-ingress-D-H5frou.js"; import "./system-events-BU_NYynX.js"; import "./ssrf-policy-DYINyIKC.js"; import { r as evaluateSenderGroupAccess } from "./group-access-BlqfIxg6.js"; import { i as deliverTextOrMediaReply, p as resolveSendableOutboundReplyParts } from "./reply-payload-CiQ7TPgp.js"; import "./hook-runtime-BUYmDbaA.js"; import "./templating-BDXRiJUh.js"; import { t as createChannelReplyPipeline } from "./channel-reply-pipeline-BxH4-AP2.js"; import "./reply-history-n7nOPLta.js"; import "./commands-registry.data-BFXJWoqi.js"; import "./commands-registry-Bh9pJ817.js"; import "./frontmatter-CP5371Rm.js"; import "./env-overrides-BNSo89u5.js"; import "./skills-M0AZJeXx.js"; import "./skills-remote-BHxDA4Jw.js"; import "./workspace-dirs-DqDLiRvZ.js"; import "./pairing-token-DAszGmwD.js"; import "./skill-commands-D73dGR_l.js"; import "./config-CLRQPUSt.js"; import "./routes-XT2JfvT-.js"; import "./ssh-tunnel-LM52qY6N.js"; import "./server-middleware-BP59C6FL.js"; import "./provider-auth-ref-CQEp9sp3.js"; import "./provider-auth-helpers-Do3RFvdi.js"; import "./provider-api-key-auth-BEeRW3dq.js"; import "./pairing-labels-D27Y4Vv6.js"; import "./directory-runtime-D9Y42mW-.js"; import "./read-only-account-inspect-CJPRBFj7.js"; import "./src-BoNU6eQs.js"; import "./web-media-PKy3RbRG.js"; import "./media-understanding-BDOSvuM9.js"; import "./web-media-CiSbdGPs.js"; import "./state-paths-Dvb3Mfl3.js"; import "./llm-task-Br6Ixjlh.js"; import "./pi-model-discovery-DO3tFksS.js"; import "./exec-inline-eval-CpmxWJsW.js"; import "./target-registry-9OUOvlxj.js"; import "./external-content-DZI9vlJn.js"; import "./brave-onFD06fq.js"; import "./duckduckgo-CZuAOfiQ.js"; import "./exa-5bwgY04k.js"; import "./security-runtime-xlw0Fxx2.js"; import "./provider-usage-ClxTGn5c.js"; import "./provider-models-Bjv0V4OP.js"; import "./media-understanding-provider-DllGbg-v.js"; import "./media-understanding-provider-BDq4rFL-.js"; import "./provider-onboard-CSnPvkMM.js"; import "./onboard-BU8aRvq7.js"; import "./perplexity-web-search-provider-CI38RNUU.js"; import "./perplexity-CMZbsreI.js"; import "./model-definitions-CLagLj0g.js"; import "./onboard-0P7GBI2D.js"; import "./provider-catalog-CKHo9CRM.js"; import "./provider-models-Dmjtw6kn.js"; import "./stream-C-KGzzT0.js"; import "./web-search-CO1hvu_l.js"; import "./stagger-CFqdtCYL.js"; import "./command-secret-targets-DLs8jC2H.js"; import "./delivery-queue-DHURMSqX.js"; import "./channel-summary-Ctrv7moa.js"; import "./follow-redirects-CVAaqIk4.js"; import "./tool-policy-match-DQWWRSN4.js"; import "./runtime-CAdCdG-M.js"; import { n as resolveWebhookPath } from "./webhook-path-BYotIM_c.js"; import "./channel-status-BfM90KqH.js"; import "./discord-core-DLbIyXWy.js"; import "./cli-runtime-Cx1v7N7v.js"; import "./config-presence-DA3j8Nmi.js"; import "./query-expansion-BOJBTXsp.js"; import "./search-manager-DNBHwaee.js"; import "./acp-runtime-BHZj-SLU.js"; import "./telegram-core-DD8gCuaX.js"; import "./audit-BI48Fi3j.js"; import "./gateway-runtime-Dn2qAGY7.js"; import "./connection-auth-Nl2a3tDb.js"; import "./mcp-config-CDIWSqVk.js"; import "./api-DlugfmwO.js"; import "./accounts-DcKwFiLd.js"; import "./zalo-6U_b4ilp.js"; import "./runtime-api-BMKyGGGe.js"; import "./runtime-api-BRYi0Pok.js"; import { t as getZaloRuntime } from "./runtime-DCO0BW-8.js"; import { a as getUpdates, c as sendMessage, l as sendPhoto, n as ZaloApiError, o as getWebhookInfo, r as deleteWebhook, s as sendChatAction, t as resolveZaloProxyFetch, u as setWebhook } from "./proxy-CqZztnNr.js"; import { timingSafeEqual } from "node:crypto"; //#region extensions/zalo/src/group-access.ts const ZALO_ALLOW_FROM_PREFIX_RE = /^(zalo|zl):/i; function isZaloSenderAllowed(senderId, allowFrom) { return isNormalizedSenderAllowed({ senderId, allowFrom, stripPrefixRe: ZALO_ALLOW_FROM_PREFIX_RE }); } function evaluateZaloGroupAccess(params) { return evaluateSenderGroupAccess({ providerConfigPresent: params.providerConfigPresent, configuredGroupPolicy: params.configuredGroupPolicy, defaultGroupPolicy: params.defaultGroupPolicy, groupAllowFrom: params.groupAllowFrom, senderId: params.senderId, isSenderAllowed: isZaloSenderAllowed }); } //#endregion //#region extensions/zalo/src/monitor.webhook.ts const ZALO_WEBHOOK_REPLAY_WINDOW_MS = 5 * 6e4; const webhookTargets = /* @__PURE__ */ new Map(); const webhookRateLimiter = createFixedWindowRateLimiter({ windowMs: WEBHOOK_RATE_LIMIT_DEFAULTS.windowMs, maxRequests: WEBHOOK_RATE_LIMIT_DEFAULTS.maxRequests, maxTrackedKeys: WEBHOOK_RATE_LIMIT_DEFAULTS.maxTrackedKeys }); const recentWebhookEvents = createDedupeCache({ ttlMs: ZALO_WEBHOOK_REPLAY_WINDOW_MS, maxSize: 5e3 }); const webhookAnomalyTracker = createWebhookAnomalyTracker({ maxTrackedKeys: WEBHOOK_ANOMALY_COUNTER_DEFAULTS.maxTrackedKeys, ttlMs: WEBHOOK_ANOMALY_COUNTER_DEFAULTS.ttlMs, logEvery: WEBHOOK_ANOMALY_COUNTER_DEFAULTS.logEvery }); function timingSafeEquals(left, right) { const leftBuffer = Buffer.from(left); const rightBuffer = Buffer.from(right); if (leftBuffer.length !== rightBuffer.length) { const length = Math.max(1, leftBuffer.length, rightBuffer.length); const paddedLeft = Buffer.alloc(length); const paddedRight = Buffer.alloc(length); leftBuffer.copy(paddedLeft); rightBuffer.copy(paddedRight); timingSafeEqual(paddedLeft, paddedRight); return false; } return timingSafeEqual(leftBuffer, rightBuffer); } function isReplayEvent(update, nowMs) { const messageId = update.message?.message_id; if (!messageId) return false; const key = `${update.event_name}:${messageId}`; return recentWebhookEvents.check(key, nowMs); } function recordWebhookStatus(runtime, path, statusCode) { webhookAnomalyTracker.record({ key: `${path}:${statusCode}`, statusCode, log: runtime?.log, message: (count) => `[zalo] webhook anomaly path=${path} status=${statusCode} count=${String(count)}` }); } function headerValue(value) { return Array.isArray(value) ? value[0] : value; } function registerZaloWebhookTarget$1(target, opts) { if (opts?.route) return registerWebhookTargetWithPluginRoute({ targetsByPath: webhookTargets, target, route: opts.route, onLastPathTargetRemoved: opts.onLastPathTargetRemoved }).unregister; return registerWebhookTarget(webhookTargets, target, opts).unregister; } async function handleZaloWebhookRequest$1(req, res, processUpdate) { return await withResolvedWebhookRequestPipeline({ req, res, targetsByPath: webhookTargets, allowMethods: ["POST"], handle: async ({ targets, path }) => { const trustedProxies = targets[0]?.config.gateway?.trustedProxies; const allowRealIpFallback = targets[0]?.config.gateway?.allowRealIpFallback === true; const rateLimitKey = `${path}:${resolveClientIp({ remoteAddr: req.socket.remoteAddress, forwardedFor: headerValue(req.headers["x-forwarded-for"]), realIp: headerValue(req.headers["x-real-ip"]), trustedProxies, allowRealIpFallback }) ?? req.socket.remoteAddress ?? "unknown"}`; const nowMs = Date.now(); if (!applyBasicWebhookRequestGuards({ req, res, rateLimiter: webhookRateLimiter, rateLimitKey, nowMs })) { recordWebhookStatus(targets[0]?.runtime, path, res.statusCode); return true; } const headerToken = String(req.headers["x-bot-api-secret-token"] ?? ""); const target = resolveWebhookTargetWithAuthOrRejectSync({ targets, res, isMatch: (entry) => timingSafeEquals(entry.secret, headerToken) }); if (!target) { recordWebhookStatus(targets[0]?.runtime, path, res.statusCode); return true; } if (!applyBasicWebhookRequestGuards({ req, res, requireJsonContentType: true })) { recordWebhookStatus(target.runtime, path, res.statusCode); return true; } const body = await readJsonWebhookBodyOrReject({ req, res, maxBytes: 1024 * 1024, timeoutMs: 3e4, emptyObjectOnEmpty: false, invalidJsonMessage: "Bad Request" }); if (!body.ok) { recordWebhookStatus(target.runtime, path, res.statusCode); return true; } const raw = body.value; const record = raw && typeof raw === "object" ? raw : null; const update = record && record.ok === true && record.result ? record.result : record ?? void 0; if (!update?.event_name) { res.statusCode = 400; res.end("Bad Request"); recordWebhookStatus(target.runtime, path, res.statusCode); return true; } if (isReplayEvent(update, nowMs)) { res.statusCode = 200; res.end("ok"); return true; } target.statusSink?.({ lastInboundAt: Date.now() }); processUpdate({ update, target }).catch((err) => { target.runtime.error?.(`[${target.account.accountId}] Zalo webhook failed: ${String(err)}`); }); res.statusCode = 200; res.end("ok"); return true; } }); } //#endregion //#region extensions/zalo/src/monitor.ts const ZALO_TEXT_LIMIT = 2e3; const DEFAULT_MEDIA_MAX_MB = 5; const WEBHOOK_CLEANUP_TIMEOUT_MS = 5e3; const ZALO_TYPING_TIMEOUT_MS = 5e3; function formatZaloError(error) { if (error instanceof Error) return error.stack ?? `${error.name}: ${error.message}`; return String(error); } function describeWebhookTarget(rawUrl) { try { const parsed = new URL(rawUrl); return `${parsed.origin}${parsed.pathname}`; } catch { return rawUrl; } } function normalizeWebhookUrl(url) { const trimmed = url?.trim(); return trimmed ? trimmed : void 0; } function logVerbose(core, runtime, message) { if (core.logging.shouldLogVerbose()) runtime.log?.(`[zalo] ${message}`); } function registerZaloWebhookTarget(target) { return registerZaloWebhookTarget$1(target, { route: { auth: "plugin", match: "exact", pluginId: "zalo", source: "zalo-webhook", accountId: target.account.accountId, log: target.runtime.log, handler: async (req, res) => { if (!await handleZaloWebhookRequest(req, res) && !res.headersSent) { res.statusCode = 404; res.setHeader("Content-Type", "text/plain; charset=utf-8"); res.end("Not Found"); } } } }); } async function handleZaloWebhookRequest(req, res) { return handleZaloWebhookRequest$1(req, res, async ({ update, target }) => { await processUpdate({ update, token: target.token, account: target.account, config: target.config, runtime: target.runtime, core: target.core, mediaMaxMb: target.mediaMaxMb, statusSink: target.statusSink, fetcher: target.fetcher }); }); } function startPollingLoop(params) { const { token, account, config, runtime, core, abortSignal, isStopped, mediaMaxMb, statusSink, fetcher } = params; const pollTimeout = 30; const processingContext = { token, account, config, runtime, core, mediaMaxMb, statusSink, fetcher }; runtime.log?.(`[${account.accountId}] Zalo polling loop started timeout=${String(pollTimeout)}s`); const poll = async () => { if (isStopped() || abortSignal.aborted) return; try { const response = await getUpdates(token, { timeout: pollTimeout }, fetcher); if (response.ok && response.result) { statusSink?.({ lastInboundAt: Date.now() }); await processUpdate({ update: response.result, ...processingContext }); } } catch (err) { if (err instanceof ZaloApiError && err.isPollingTimeout) {} else if (!isStopped() && !abortSignal.aborted) { runtime.error?.(`[${account.accountId}] Zalo polling error: ${formatZaloError(err)}`); await new Promise((resolve) => setTimeout(resolve, 5e3)); } } if (!isStopped() && !abortSignal.aborted) setImmediate(poll); }; poll(); } async function processUpdate(params) { const { update, token, account, config, runtime, core, mediaMaxMb, statusSink, fetcher } = params; const { event_name, message } = update; const sharedContext = { token, account, config, runtime, core, statusSink, fetcher }; if (!message) return; switch (event_name) { case "message.text.received": await handleTextMessage({ message, ...sharedContext }); break; case "message.image.received": await handleImageMessage({ message, ...sharedContext, mediaMaxMb }); break; case "message.sticker.received": logVerbose(core, runtime, `[${account.accountId}] Received sticker from ${message.from.id}`); break; case "message.unsupported.received": logVerbose(core, runtime, `[${account.accountId}] Received unsupported message type from ${message.from.id}`); break; } } async function handleTextMessage(params) { const { message } = params; const { text } = message; if (!text?.trim()) return; await processMessageWithPipeline({ ...params, text, mediaPath: void 0, mediaType: void 0 }); } async function handleImageMessage(params) { const { message, mediaMaxMb, account, core, runtime } = params; const { photo_url, caption } = message; let mediaPath; let mediaType; if (photo_url) try { const maxBytes = mediaMaxMb * 1024 * 1024; const fetched = await core.channel.media.fetchRemoteMedia({ url: photo_url, maxBytes }); const saved = await core.channel.media.saveMediaBuffer(fetched.buffer, fetched.contentType, "inbound", maxBytes); mediaPath = saved.path; mediaType = saved.contentType; } catch (err) { runtime.error?.(`[${account.accountId}] Failed to download Zalo image: ${String(err)}`); } await processMessageWithPipeline({ ...params, text: caption, mediaPath, mediaType }); } async function processMessageWithPipeline(params) { const { message, token, account, config, runtime, core, text, mediaPath, mediaType, statusSink, fetcher } = params; const pairing = createChannelPairingController({ core, channel: "zalo", accountId: account.accountId }); const { from, chat, message_id, date } = message; const isGroup = chat.chat_type === "GROUP"; const chatId = chat.id; const senderId = from.id; const senderName = from.display_name ?? from.name; const dmPolicy = account.config.dmPolicy ?? "pairing"; const configAllowFrom = (account.config.allowFrom ?? []).map((v) => String(v)); const configuredGroupAllowFrom = (account.config.groupAllowFrom ?? []).map((v) => String(v)); const groupAllowFrom = configuredGroupAllowFrom.length > 0 ? configuredGroupAllowFrom : configAllowFrom; const defaultGroupPolicy = resolveDefaultGroupPolicy(config); const groupAccess = isGroup ? evaluateZaloGroupAccess({ providerConfigPresent: config.channels?.zalo !== void 0, configuredGroupPolicy: account.config.groupPolicy, defaultGroupPolicy, groupAllowFrom, senderId }) : void 0; if (groupAccess) { warnMissingProviderGroupPolicyFallbackOnce({ providerMissingFallbackApplied: groupAccess.providerMissingFallbackApplied, providerKey: "zalo", accountId: account.accountId, log: (message) => logVerbose(core, runtime, message) }); if (!groupAccess.allowed) { if (groupAccess.reason === "disabled") logVerbose(core, runtime, `zalo: drop group ${chatId} (groupPolicy=disabled)`); else if (groupAccess.reason === "empty_allowlist") logVerbose(core, runtime, `zalo: drop group ${chatId} (groupPolicy=allowlist, no groupAllowFrom)`); else if (groupAccess.reason === "sender_not_allowlisted") logVerbose(core, runtime, `zalo: drop group sender ${senderId} (groupPolicy=allowlist)`); return; } } const rawBody = text?.trim() || (mediaPath ? "<media:image>" : ""); const { senderAllowedForCommands, commandAuthorized } = await resolveSenderCommandAuthorizationWithRuntime({ cfg: config, rawBody, isGroup, dmPolicy, configuredAllowFrom: configAllowFrom, configuredGroupAllowFrom: groupAllowFrom, senderId, isSenderAllowed: isZaloSenderAllowed, readAllowFromStore: pairing.readAllowFromStore, runtime: core.channel.commands }); const directDmOutcome = resolveDirectDmAuthorizationOutcome({ isGroup, dmPolicy, senderAllowedForCommands }); if (directDmOutcome === "disabled") { logVerbose(core, runtime, `Blocked zalo DM from ${senderId} (dmPolicy=disabled)`); return; } if (directDmOutcome === "unauthorized") { if (dmPolicy === "pairing") await pairing.issueChallenge({ senderId, senderIdLine: `Your Zalo user id: ${senderId}`, meta: { name: senderName ?? void 0 }, onCreated: () => { logVerbose(core, runtime, `zalo pairing request sender=${senderId}`); }, sendPairingReply: async (text) => { await sendMessage(token, { chat_id: chatId, text }, fetcher); statusSink?.({ lastOutboundAt: Date.now() }); }, onReplyError: (err) => { logVerbose(core, runtime, `zalo pairing reply failed for ${senderId}: ${String(err)}`); } }); else logVerbose(core, runtime, `Blocked unauthorized zalo sender ${senderId} (dmPolicy=${dmPolicy})`); return; } const { route, buildEnvelope } = resolveInboundRouteEnvelopeBuilderWithRuntime({ cfg: config, channel: "zalo", accountId: account.accountId, peer: { kind: isGroup ? "group" : "direct", id: chatId }, runtime: core.channel, sessionStore: config.session?.store }); if (isGroup && core.channel.commands.isControlCommandMessage(rawBody, config) && commandAuthorized !== true) { logVerbose(core, runtime, `zalo: drop control command from unauthorized sender ${senderId}`); return; } const fromLabel = isGroup ? `group:${chatId}` : senderName || `user:${senderId}`; const { storePath, body } = buildEnvelope({ channel: "Zalo", from: fromLabel, timestamp: date ? date * 1e3 : void 0, body: rawBody }); const ctxPayload = core.channel.reply.finalizeInboundContext({ Body: body, BodyForAgent: rawBody, RawBody: rawBody, CommandBody: rawBody, From: isGroup ? `zalo:group:${chatId}` : `zalo:${senderId}`, To: `zalo:${chatId}`, SessionKey: route.sessionKey, AccountId: route.accountId, ChatType: isGroup ? "group" : "direct", ConversationLabel: fromLabel, SenderName: senderName || void 0, SenderId: senderId, CommandAuthorized: commandAuthorized, Provider: "zalo", Surface: "zalo", MessageSid: message_id, MediaPath: mediaPath, MediaType: mediaType, MediaUrl: mediaPath, OriginatingChannel: "zalo", OriginatingTo: `zalo:${chatId}` }); await core.channel.session.recordInboundSession({ storePath, sessionKey: ctxPayload.SessionKey ?? route.sessionKey, ctx: ctxPayload, onRecordError: (err) => { runtime.error?.(`zalo: failed updating session meta: ${String(err)}`); } }); const tableMode = core.channel.text.resolveMarkdownTableMode({ cfg: config, channel: "zalo", accountId: account.accountId }); const { onModelSelected, ...replyPipeline } = createChannelReplyPipeline({ cfg: config, agentId: route.agentId, channel: "zalo", accountId: account.accountId, typing: { start: async () => { await sendChatAction(token, { chat_id: chatId, action: "typing" }, fetcher, ZALO_TYPING_TIMEOUT_MS); }, onStartError: (err) => { logTypingFailure({ log: (message) => logVerbose(core, runtime, message), channel: "zalo", action: "start", target: chatId, error: err }); } } }); await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({ ctx: ctxPayload, cfg: config, dispatcherOptions: { ...replyPipeline, deliver: async (payload) => { await deliverZaloReply({ payload, token, chatId, runtime, core, config, accountId: account.accountId, statusSink, fetcher, tableMode }); }, onError: (err, info) => { runtime.error?.(`[${account.accountId}] Zalo ${info.kind} reply failed: ${String(err)}`); } }, replyOptions: { onModelSelected } }); } async function deliverZaloReply(params) { const { payload, token, chatId, runtime, core, config, accountId, statusSink, fetcher } = params; const tableMode = params.tableMode ?? "code"; const reply = resolveSendableOutboundReplyParts(payload, { text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode) }); const chunkMode = core.channel.text.resolveChunkMode(config, "zalo", accountId); await deliverTextOrMediaReply({ payload, text: reply.text, chunkText: (value) => core.channel.text.chunkMarkdownTextWithMode(value, ZALO_TEXT_LIMIT, chunkMode), sendText: async (chunk) => { try { await sendMessage(token, { chat_id: chatId, text: chunk }, fetcher); statusSink?.({ lastOutboundAt: Date.now() }); } catch (err) { runtime.error?.(`Zalo message send failed: ${String(err)}`); } }, sendMedia: async ({ mediaUrl, caption }) => { await sendPhoto(token, { chat_id: chatId, photo: mediaUrl, caption }, fetcher); statusSink?.({ lastOutboundAt: Date.now() }); }, onMediaError: (error) => { runtime.error?.(`Zalo photo send failed: ${String(error)}`); } }); } async function monitorZaloProvider(options) { const { token, account, config, runtime, abortSignal, useWebhook, webhookUrl, webhookSecret, webhookPath, statusSink, fetcher: fetcherOverride } = options; const core = getZaloRuntime(); const effectiveMediaMaxMb = account.config.mediaMaxMb ?? DEFAULT_MEDIA_MAX_MB; const fetcher = fetcherOverride ?? resolveZaloProxyFetch(account.config.proxy); const mode = useWebhook ? "webhook" : "polling"; let stopped = false; const stopHandlers = []; let cleanupWebhook; const stop = () => { if (stopped) return; stopped = true; for (const handler of stopHandlers) handler(); }; runtime.log?.(`[${account.accountId}] Zalo provider init mode=${mode} mediaMaxMb=${String(effectiveMediaMaxMb)}`); try { if (useWebhook) { if (!webhookUrl || !webhookSecret) throw new Error("Zalo webhookUrl and webhookSecret are required for webhook mode"); if (!webhookUrl.startsWith("https://")) throw new Error("Zalo webhook URL must use HTTPS"); if (webhookSecret.length < 8 || webhookSecret.length > 256) throw new Error("Zalo webhook secret must be 8-256 characters"); const path = resolveWebhookPath({ webhookPath, webhookUrl, defaultPath: null }); if (!path) throw new Error("Zalo webhookPath could not be derived"); runtime.log?.(`[${account.accountId}] Zalo configuring webhook path=${path} target=${describeWebhookTarget(webhookUrl)}`); await setWebhook(token, { url: webhookUrl, secret_token: webhookSecret }, fetcher); let webhookCleanupPromise; cleanupWebhook = async () => { if (!webhookCleanupPromise) webhookCleanupPromise = (async () => { runtime.log?.(`[${account.accountId}] Zalo stopping; deleting webhook`); try { await deleteWebhook(token, fetcher, WEBHOOK_CLEANUP_TIMEOUT_MS); runtime.log?.(`[${account.accountId}] Zalo webhook deleted`); } catch (err) { const detail = err instanceof Error && err.name === "AbortError" ? `timed out after ${String(WEBHOOK_CLEANUP_TIMEOUT_MS)}ms` : formatZaloError(err); runtime.error?.(`[${account.accountId}] Zalo webhook delete failed: ${detail}`); } })(); await webhookCleanupPromise; }; runtime.log?.(`[${account.accountId}] Zalo webhook registered path=${path}`); const unregister = registerZaloWebhookTarget({ token, account, config, runtime, core, path, secret: webhookSecret, statusSink: (patch) => statusSink?.(patch), mediaMaxMb: effectiveMediaMaxMb, fetcher }); stopHandlers.push(unregister); await waitForAbortSignal(abortSignal); return; } runtime.log?.(`[${account.accountId}] Zalo polling mode: clearing webhook before startup`); try { try { const currentWebhookUrl = normalizeWebhookUrl((await getWebhookInfo(token, fetcher)).result?.url); if (!currentWebhookUrl) runtime.log?.(`[${account.accountId}] Zalo polling mode ready (no webhook configured)`); else { runtime.log?.(`[${account.accountId}] Zalo polling mode disabling existing webhook ${describeWebhookTarget(currentWebhookUrl)}`); await deleteWebhook(token, fetcher); runtime.log?.(`[${account.accountId}] Zalo polling mode ready (webhook disabled)`); } } catch (err) { if (err instanceof ZaloApiError && err.errorCode === 404) runtime.log?.(`[${account.accountId}] Zalo polling mode webhook inspection unavailable; continuing without webhook cleanup`); else throw err; } } catch (err) { runtime.error?.(`[${account.accountId}] Zalo polling startup could not clear webhook: ${formatZaloError(err)}`); } startPollingLoop({ token, account, config, runtime, core, abortSignal, isStopped: () => stopped, mediaMaxMb: effectiveMediaMaxMb, statusSink, fetcher }); await waitForAbortSignal(abortSignal); } catch (err) { runtime.error?.(`[${account.accountId}] Zalo provider startup failed mode=${mode}: ${formatZaloError(err)}`); throw err; } finally { await cleanupWebhook?.(); stop(); runtime.log?.(`[${account.accountId}] Zalo provider stopped mode=${mode}`); } } //#endregion export { monitorZaloProvider };