UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

867 lines (866 loc) • 32.2 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 "./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 { Ib as mergeAllowlist, Rb as summarizeMapping, mv as resolveMentionGatingWithBypass, xo as resolveSenderCommandAuthorization } 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 { t as KeyedAsyncQueue } from "./keyed-async-queue-Bj6YmEFK.js"; import "./config-schema-CPzP2Ds6.js"; import "./channel-plugin-common-ClptUZHU.js"; import { a as warnMissingProviderGroupPolicyFallbackOnce, i as resolveOpenProviderRuntimeGroupPolicy, 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 { o as resolveDmGroupAccessWithLists, t as DM_GROUP_ACCESS_REASON } from "./dm-policy-shared-DtcQProI.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 { n as isDangerousNameMatchingEnabled } from "./dangerous-name-matching-BQW4HoPt.js"; import "./level-overrides-DzIzQ3ZY.js"; import "./exec-approvals-BF_Qfdq8.js"; import "./webhook-ingress-D-H5frou.js"; import "./system-events-BU_NYynX.js"; import "./ssrf-policy-DYINyIKC.js"; import { a as resolveSenderScopedGroupPolicy, t as evaluateGroupRouteAccessForPolicy } 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 { a as buildPendingHistoryContextFromMap, s as clearHistoryEntriesIfEnabled, u as recordPendingHistoryEntryIfEnabled } from "./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 "./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 "./channel-setup-C5JbULY6.js"; import { a as createDeferred } from "./extension-shared-B8dMu-tU.js"; import "./outbound-media-CVWWX2Ba.js"; import "./semver-DgFx6ze4.js"; import "./zalouser-BPCNqkr-.js"; import "./json-bigint-CbAcNBLP.js"; import "./runtime-api-DyobrjkL.js"; import { o as listZaloGroups, r as listZaloFriends, u as resolveZaloGroupContext, v as startZaloListener } from "./zalo-js-HULxcu6w.js"; import { c as getZalouserRuntime, d as resolveZalouserMessageSid, h as isZalouserGroupEntryAllowed, i as sendMessageZalouser, m as findZalouserGroupEntry, o as sendSeenZalouser, p as buildZalouserGroupCandidates, s as sendTypingZalouser, t as sendDeliveredZalouser, u as formatZalouserMessageSidFull } from "./send-C_N0Xend.js"; //#region extensions/zalouser/src/monitor.ts const ZALOUSER_TEXT_LIMIT = 2e3; function normalizeZalouserEntry(entry) { return entry.replace(/^(zalouser|zlu):/i, "").trim(); } function buildNameIndex(items, nameFn) { const index = /* @__PURE__ */ new Map(); for (const item of items) { const name = nameFn(item)?.trim().toLowerCase(); if (!name) continue; const list = index.get(name) ?? []; list.push(item); index.set(name, list); } return index; } function resolveUserAllowlistEntries(entries, byName) { const additions = []; const mapping = []; const unresolved = []; for (const entry of entries) { if (/^\d+$/.test(entry)) { additions.push(entry); continue; } const match = (byName.get(entry.toLowerCase()) ?? [])[0]; const id = match?.userId ? String(match.userId) : void 0; if (id) { additions.push(id); mapping.push(`${entry}->${id}`); } else unresolved.push(entry); } return { additions, mapping, unresolved }; } function resolveInboundQueueKey(message) { const threadId = message.threadId?.trim() || "unknown"; if (message.isGroup) return `group:${threadId}`; return `direct:${message.senderId?.trim() || threadId}`; } function resolveZalouserDmSessionScope(config) { const configured = config.session?.dmScope; return configured === "main" || !configured ? "per-channel-peer" : configured; } function resolveZalouserInboundSessionKey(params) { if (params.isGroup) return params.route.sessionKey; const directSessionKey = params.core.channel.routing.buildAgentSessionKey({ agentId: params.route.agentId, channel: "zalouser", accountId: params.route.accountId, peer: { kind: "direct", id: params.senderId }, dmScope: resolveZalouserDmSessionScope(params.config), identityLinks: params.config.session?.identityLinks }).toLowerCase(); const legacySessionKey = params.core.channel.routing.buildAgentSessionKey({ agentId: params.route.agentId, channel: "zalouser", accountId: params.route.accountId, peer: { kind: "group", id: params.senderId } }).toLowerCase(); const hasDirectSession = params.core.channel.session.readSessionUpdatedAt({ storePath: params.storePath, sessionKey: directSessionKey }) !== void 0; return params.core.channel.session.readSessionUpdatedAt({ storePath: params.storePath, sessionKey: legacySessionKey }) !== void 0 && !hasDirectSession ? legacySessionKey : directSessionKey; } function logVerbose(core, runtime, message) { if (core.logging.shouldLogVerbose()) runtime.log(`[zalouser] ${message}`); } function isSenderAllowed(senderId, allowFrom) { if (allowFrom.includes("*")) return true; const normalizedSenderId = senderId?.trim().toLowerCase(); if (!normalizedSenderId) return false; return allowFrom.some((entry) => { return entry.toLowerCase().replace(/^(zalouser|zlu):/i, "") === normalizedSenderId; }); } function resolveGroupRequireMention(params) { const entry = findZalouserGroupEntry(params.groups ?? {}, buildZalouserGroupCandidates({ groupId: params.groupId, groupName: params.groupName, includeGroupIdAlias: true, includeWildcard: true, allowNameMatching: params.allowNameMatching })); if (typeof entry?.requireMention === "boolean") return entry.requireMention; return true; } async function sendZalouserDeliveryAcks(params) { await sendDeliveredZalouser({ profile: params.profile, isGroup: params.isGroup, message: params.message, isSeen: true }); await sendSeenZalouser({ profile: params.profile, isGroup: params.isGroup, message: params.message }); } async function processMessage(message, account, config, core, runtime, historyState, statusSink) { const pairing = createChannelPairingController({ core, channel: "zalouser", accountId: account.accountId }); const rawBody = message.content?.trim(); if (!rawBody) return; const commandBody = message.commandContent?.trim() || rawBody; const isGroup = message.isGroup; const chatId = message.threadId; const senderId = message.senderId?.trim(); if (!senderId) { logVerbose(core, runtime, `zalouser: drop message ${chatId} (missing senderId)`); return; } const senderName = message.senderName ?? ""; const configuredGroupName = message.groupName?.trim() || ""; const groupContext = isGroup && !configuredGroupName ? await resolveZaloGroupContext(account.profile, chatId).catch((err) => { logVerbose(core, runtime, `zalouser: group context lookup failed for ${chatId}: ${String(err)}`); return null; }) : null; const groupName = configuredGroupName || groupContext?.name?.trim() || ""; const groupMembers = groupContext?.members?.slice(0, 20).join(", ") || void 0; if (message.eventMessage) try { await sendZalouserDeliveryAcks({ profile: account.profile, isGroup, message: message.eventMessage }); } catch (err) { logVerbose(core, runtime, `zalouser: delivery/seen ack failed for ${chatId}: ${String(err)}`); } const defaultGroupPolicy = resolveDefaultGroupPolicy(config); const { groupPolicy, providerMissingFallbackApplied } = resolveOpenProviderRuntimeGroupPolicy({ providerConfigPresent: config.channels?.zalouser !== void 0, groupPolicy: account.config.groupPolicy, defaultGroupPolicy }); warnMissingProviderGroupPolicyFallbackOnce({ providerMissingFallbackApplied, providerKey: "zalouser", accountId: account.accountId, log: (entry) => logVerbose(core, runtime, entry) }); const groups = account.config.groups ?? {}; const allowNameMatching = isDangerousNameMatchingEnabled(account.config); if (isGroup) { const groupEntry = findZalouserGroupEntry(groups, buildZalouserGroupCandidates({ groupId: chatId, groupName, includeGroupIdAlias: true, includeWildcard: true, allowNameMatching })); const routeAccess = evaluateGroupRouteAccessForPolicy({ groupPolicy, routeAllowlistConfigured: Object.keys(groups).length > 0, routeMatched: Boolean(groupEntry), routeEnabled: isZalouserGroupEntryAllowed(groupEntry) }); if (!routeAccess.allowed) { if (routeAccess.reason === "disabled") logVerbose(core, runtime, `zalouser: drop group ${chatId} (groupPolicy=disabled)`); else if (routeAccess.reason === "empty_allowlist") logVerbose(core, runtime, `zalouser: drop group ${chatId} (groupPolicy=allowlist, no allowlist)`); else if (routeAccess.reason === "route_not_allowlisted") logVerbose(core, runtime, `zalouser: drop group ${chatId} (not allowlisted)`); else if (routeAccess.reason === "route_disabled") logVerbose(core, runtime, `zalouser: drop group ${chatId} (group disabled)`); return; } } const dmPolicy = account.config.dmPolicy ?? "pairing"; const configAllowFrom = (account.config.allowFrom ?? []).map((v) => String(v)); const configGroupAllowFrom = (account.config.groupAllowFrom ?? []).map((v) => String(v)); const senderGroupPolicy = resolveSenderScopedGroupPolicy({ groupPolicy, groupAllowFrom: configGroupAllowFrom }); const shouldComputeCommandAuth = core.channel.commands.shouldComputeCommandAuthorized(commandBody, config); const storeAllowFrom = !isGroup && dmPolicy !== "allowlist" && (dmPolicy !== "open" || shouldComputeCommandAuth) ? await pairing.readAllowFromStore().catch(() => []) : []; const accessDecision = resolveDmGroupAccessWithLists({ isGroup, dmPolicy, groupPolicy: senderGroupPolicy, allowFrom: configAllowFrom, groupAllowFrom: configGroupAllowFrom, storeAllowFrom, groupAllowFromFallbackToAllowFrom: false, isSenderAllowed: (allowFrom) => isSenderAllowed(senderId, allowFrom) }); if (isGroup && accessDecision.decision !== "allow") { if (accessDecision.reasonCode === DM_GROUP_ACCESS_REASON.GROUP_POLICY_EMPTY_ALLOWLIST) logVerbose(core, runtime, "Blocked zalouser group message (no group allowlist)"); else if (accessDecision.reasonCode === DM_GROUP_ACCESS_REASON.GROUP_POLICY_NOT_ALLOWLISTED) logVerbose(core, runtime, `Blocked zalouser sender ${senderId} (not in groupAllowFrom/allowFrom)`); return; } if (!isGroup && accessDecision.decision !== "allow") { if (accessDecision.decision === "pairing") { await pairing.issueChallenge({ senderId, senderIdLine: `Your Zalo user id: ${senderId}`, meta: { name: senderName || void 0 }, onCreated: () => { logVerbose(core, runtime, `zalouser pairing request sender=${senderId}`); }, sendPairingReply: async (text) => { await sendMessageZalouser(chatId, text, { profile: account.profile }); statusSink?.({ lastOutboundAt: Date.now() }); }, onReplyError: (err) => { logVerbose(core, runtime, `zalouser pairing reply failed for ${senderId}: ${String(err)}`); } }); return; } if (accessDecision.reasonCode === DM_GROUP_ACCESS_REASON.DM_POLICY_DISABLED) logVerbose(core, runtime, `Blocked zalouser DM from ${senderId} (dmPolicy=disabled)`); else logVerbose(core, runtime, `Blocked unauthorized zalouser sender ${senderId} (dmPolicy=${dmPolicy})`); return; } const { commandAuthorized } = await resolveSenderCommandAuthorization({ cfg: config, rawBody: commandBody, isGroup, dmPolicy, configuredAllowFrom: configAllowFrom, configuredGroupAllowFrom: configGroupAllowFrom, senderId, isSenderAllowed, readAllowFromStore: async () => storeAllowFrom, shouldComputeCommandAuthorized: (body, cfg) => core.channel.commands.shouldComputeCommandAuthorized(body, cfg), resolveCommandAuthorizedFromAuthorizers: (params) => core.channel.commands.resolveCommandAuthorizedFromAuthorizers(params) }); const hasControlCommand = core.channel.commands.isControlCommandMessage(commandBody, config); if (isGroup && hasControlCommand && commandAuthorized !== true) { logVerbose(core, runtime, `zalouser: drop control command from unauthorized sender ${senderId}`); return; } const peer = isGroup ? { kind: "group", id: chatId } : { kind: "direct", id: senderId }; const route = core.channel.routing.resolveAgentRoute({ cfg: config, channel: "zalouser", accountId: account.accountId, peer: { kind: peer.kind, id: peer.id } }); const historyKey = isGroup ? route.sessionKey : void 0; const requireMention = isGroup ? resolveGroupRequireMention({ groupId: chatId, groupName, groups, allowNameMatching }) : false; const mentionRegexes = core.channel.mentions.buildMentionRegexes(config, route.agentId); const explicitMention = { hasAnyMention: message.hasAnyMention === true, isExplicitlyMentioned: message.wasExplicitlyMentioned === true, canResolveExplicit: message.canResolveExplicitMention === true }; const wasMentioned = isGroup ? core.channel.mentions.matchesMentionWithExplicit({ text: rawBody, mentionRegexes, explicit: explicitMention }) : true; const canDetectMention = mentionRegexes.length > 0 || explicitMention.canResolveExplicit; const mentionGate = resolveMentionGatingWithBypass({ isGroup, requireMention, canDetectMention, wasMentioned, implicitMention: message.implicitMention === true, hasAnyMention: explicitMention.hasAnyMention, allowTextCommands: core.channel.commands.shouldHandleTextCommands({ cfg: config, surface: "zalouser" }), hasControlCommand, commandAuthorized: commandAuthorized === true }); if (isGroup && requireMention && !canDetectMention && !mentionGate.effectiveWasMentioned) { runtime.error?.(`[${account.accountId}] zalouser mention required but detection unavailable (missing mention regexes and bot self id); dropping group ${chatId}`); return; } if (isGroup && mentionGate.shouldSkip) { recordPendingHistoryEntryIfEnabled({ historyMap: historyState.groupHistories, historyKey: historyKey ?? "", limit: historyState.historyLimit, entry: historyKey && rawBody ? { sender: senderName || senderId, body: rawBody, timestamp: message.timestampMs, messageId: resolveZalouserMessageSid({ msgId: message.msgId, cliMsgId: message.cliMsgId, fallback: `${message.timestampMs}` }) } : null }); logVerbose(core, runtime, `zalouser: skip group ${chatId} (mention required, not mentioned)`); return; } const fromLabel = isGroup ? groupName || `group:${chatId}` : senderName || `user:${senderId}`; const storePath = core.channel.session.resolveStorePath(config.session?.store, { agentId: route.agentId }); const inboundSessionKey = resolveZalouserInboundSessionKey({ core, config, route, storePath, isGroup, senderId }); const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(config); const previousTimestamp = core.channel.session.readSessionUpdatedAt({ storePath, sessionKey: inboundSessionKey }); const body = core.channel.reply.formatAgentEnvelope({ channel: "Zalo Personal", from: fromLabel, timestamp: message.timestampMs, previousTimestamp, envelope: envelopeOptions, body: rawBody }); const combinedBody = isGroup && historyKey ? buildPendingHistoryContextFromMap({ historyMap: historyState.groupHistories, historyKey, limit: historyState.historyLimit, currentMessage: body, formatEntry: (entry) => core.channel.reply.formatAgentEnvelope({ channel: "Zalo Personal", from: fromLabel, timestamp: entry.timestamp, envelope: envelopeOptions, body: `${entry.sender}: ${entry.body}${entry.messageId ? ` [id:${entry.messageId}]` : ""}` }) }) : body; const inboundHistory = isGroup && historyKey && historyState.historyLimit > 0 ? (historyState.groupHistories.get(historyKey) ?? []).map((entry) => ({ sender: entry.sender, body: entry.body, timestamp: entry.timestamp })) : void 0; const normalizedTo = isGroup ? `zalouser:group:${chatId}` : `zalouser:${chatId}`; const ctxPayload = core.channel.reply.finalizeInboundContext({ Body: combinedBody, BodyForAgent: rawBody, InboundHistory: inboundHistory, RawBody: rawBody, CommandBody: commandBody, BodyForCommands: commandBody, From: isGroup ? `zalouser:group:${chatId}` : `zalouser:${senderId}`, To: normalizedTo, SessionKey: inboundSessionKey, AccountId: route.accountId, ChatType: isGroup ? "group" : "direct", ConversationLabel: fromLabel, GroupSubject: isGroup ? groupName || void 0 : void 0, GroupChannel: isGroup ? groupName || void 0 : void 0, GroupMembers: isGroup ? groupMembers : void 0, SenderName: senderName || void 0, SenderId: senderId, WasMentioned: isGroup ? mentionGate.effectiveWasMentioned : void 0, CommandAuthorized: commandAuthorized, Provider: "zalouser", Surface: "zalouser", MessageSid: resolveZalouserMessageSid({ msgId: message.msgId, cliMsgId: message.cliMsgId, fallback: `${message.timestampMs}` }), MessageSidFull: formatZalouserMessageSidFull({ msgId: message.msgId, cliMsgId: message.cliMsgId }), OriginatingChannel: "zalouser", OriginatingTo: normalizedTo }); await core.channel.session.recordInboundSession({ storePath, sessionKey: ctxPayload.SessionKey ?? route.sessionKey, ctx: ctxPayload, onRecordError: (err) => { runtime.error?.(`zalouser: failed updating session meta: ${String(err)}`); } }); const { onModelSelected, ...replyPipeline } = createChannelReplyPipeline({ cfg: config, agentId: route.agentId, channel: "zalouser", accountId: account.accountId, typing: { start: async () => { await sendTypingZalouser(chatId, { profile: account.profile, isGroup }); }, onStartError: (err) => { runtime.error?.(`[${account.accountId}] zalouser typing start failed for ${chatId}: ${String(err)}`); logVerbose(core, runtime, `zalouser typing failed for ${chatId}: ${String(err)}`); } } }); await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({ ctx: ctxPayload, cfg: config, dispatcherOptions: { ...replyPipeline, deliver: async (payload) => { await deliverZalouserReply({ payload, profile: account.profile, chatId, isGroup, runtime, core, config, accountId: account.accountId, statusSink, tableMode: core.channel.text.resolveMarkdownTableMode({ cfg: config, channel: "zalouser", accountId: account.accountId }) }); }, onError: (err, info) => { runtime.error(`[${account.accountId}] Zalouser ${info.kind} reply failed: ${String(err)}`); } }, replyOptions: { onModelSelected } }); if (isGroup && historyKey) clearHistoryEntriesIfEnabled({ historyMap: historyState.groupHistories, historyKey, limit: historyState.historyLimit }); } async function deliverZalouserReply(params) { const { payload, profile, chatId, isGroup, runtime, core, config, accountId, statusSink } = 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, "zalouser", accountId); const textChunkLimit = core.channel.text.resolveTextChunkLimit(config, "zalouser", accountId, { fallbackLimit: ZALOUSER_TEXT_LIMIT }); await deliverTextOrMediaReply({ payload, text: reply.text, sendText: async (chunk) => { try { await sendMessageZalouser(chatId, chunk, { profile, isGroup, textMode: "markdown", textChunkMode: chunkMode, textChunkLimit }); statusSink?.({ lastOutboundAt: Date.now() }); } catch (err) { runtime.error(`Zalouser message send failed: ${String(err)}`); } }, sendMedia: async ({ mediaUrl, caption }) => { logVerbose(core, runtime, `Sending media to ${chatId}`); await sendMessageZalouser(chatId, caption ?? "", { profile, mediaUrl, isGroup, textMode: "markdown", textChunkMode: chunkMode, textChunkLimit }); statusSink?.({ lastOutboundAt: Date.now() }); }, onMediaError: (error) => { runtime.error(`Zalouser media send failed: ${String(error)}`); } }); } async function monitorZalouserProvider(options) { let { account, config } = options; const { abortSignal, statusSink, runtime } = options; const core = getZalouserRuntime(); const inboundQueue = new KeyedAsyncQueue(); const historyLimit = Math.max(0, account.config.historyLimit ?? config.messages?.groupChat?.historyLimit ?? 50); const groupHistories = /* @__PURE__ */ new Map(); try { const profile = account.profile; const allowFromEntries = (account.config.allowFrom ?? []).map((entry) => normalizeZalouserEntry(String(entry))).filter((entry) => entry && entry !== "*"); const groupAllowFromEntries = (account.config.groupAllowFrom ?? []).map((entry) => normalizeZalouserEntry(String(entry))).filter((entry) => entry && entry !== "*"); if (allowFromEntries.length > 0 || groupAllowFromEntries.length > 0) { const byName = buildNameIndex(await listZaloFriends(profile), (friend) => friend.displayName); if (allowFromEntries.length > 0) { const { additions, mapping, unresolved } = resolveUserAllowlistEntries(allowFromEntries, byName); const allowFrom = mergeAllowlist({ existing: account.config.allowFrom, additions }); account = { ...account, config: { ...account.config, allowFrom } }; summarizeMapping("zalouser users", mapping, unresolved, runtime); } if (groupAllowFromEntries.length > 0) { const { additions, mapping, unresolved } = resolveUserAllowlistEntries(groupAllowFromEntries, byName); const groupAllowFrom = mergeAllowlist({ existing: account.config.groupAllowFrom, additions }); account = { ...account, config: { ...account.config, groupAllowFrom } }; summarizeMapping("zalouser group users", mapping, unresolved, runtime); } } const groupsConfig = account.config.groups ?? {}; const groupKeys = Object.keys(groupsConfig).filter((key) => key !== "*"); if (groupKeys.length > 0) { const byName = buildNameIndex(await listZaloGroups(profile), (group) => group.name); const mapping = []; const unresolved = []; const nextGroups = { ...groupsConfig }; for (const entry of groupKeys) { const cleaned = normalizeZalouserEntry(entry); if (/^\d+$/.test(cleaned)) { if (!nextGroups[cleaned]) nextGroups[cleaned] = groupsConfig[entry]; mapping.push(`${entry}→${cleaned}`); continue; } const match = (byName.get(cleaned.toLowerCase()) ?? [])[0]; const id = match?.groupId ? String(match.groupId) : void 0; if (id) { if (!nextGroups[id]) nextGroups[id] = groupsConfig[entry]; mapping.push(`${entry}→${id}`); } else unresolved.push(entry); } account = { ...account, config: { ...account.config, groups: nextGroups } }; summarizeMapping("zalouser groups", mapping, unresolved, runtime); } } catch (err) { runtime.log?.(`zalouser resolve failed; using config entries. ${String(err)}`); } let listenerStop = null; let stopped = false; const stop = () => { if (stopped) return; stopped = true; listenerStop?.(); listenerStop = null; }; let settled = false; const { promise: waitForExit, resolve: resolveRun, reject: rejectRun } = createDeferred(); const settleSuccess = () => { if (settled) return; settled = true; stop(); resolveRun(); }; const settleFailure = (error) => { if (settled) return; settled = true; stop(); rejectRun(error instanceof Error ? error : new Error(String(error))); }; const onAbort = () => { settleSuccess(); }; abortSignal.addEventListener("abort", onAbort, { once: true }); let listener; try { listener = await startZaloListener({ accountId: account.accountId, profile: account.profile, abortSignal, onMessage: (msg) => { if (stopped) return; logVerbose(core, runtime, `[${account.accountId}] inbound message`); statusSink?.({ lastInboundAt: Date.now() }); const queueKey = resolveInboundQueueKey(msg); inboundQueue.enqueue(queueKey, async () => { if (stopped || abortSignal.aborted) return; await processMessage(msg, account, config, core, runtime, { historyLimit, groupHistories }, statusSink); }).catch((err) => { runtime.error(`[${account.accountId}] Failed to process message: ${String(err)}`); }); }, onError: (err) => { if (stopped || abortSignal.aborted) return; runtime.error(`[${account.accountId}] Zalo listener error: ${String(err)}`); settleFailure(err); } }); } catch (error) { abortSignal.removeEventListener("abort", onAbort); throw error; } listenerStop = listener.stop; if (stopped) { listenerStop(); listenerStop = null; } if (abortSignal.aborted) settleSuccess(); try { await waitForExit; } finally { abortSignal.removeEventListener("abort", onAbort); } return { stop }; } //#endregion export { monitorZalouserProvider };