|
| 1 | +import type { ChannelBotLoopProtectionFacts } from "openclaw/plugin-sdk/channel-inbound"; |
| 2 | +import { resolveChannelProgressDraftConfig } from "openclaw/plugin-sdk/channel-outbound"; |
| 3 | +import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime"; |
| 4 | +import { mergePairLoopGuardConfig } from "openclaw/plugin-sdk/pair-loop-guard-runtime"; |
| 5 | +import { resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload"; |
| 6 | +import type { ReplyDispatchKind, ReplyPayload } from "openclaw/plugin-sdk/reply-runtime"; |
| 7 | +import { logVerbose } from "openclaw/plugin-sdk/runtime-env"; |
| 8 | +import { resolveSlackReplyRenderPlan } from "../../reply-blocks.js"; |
| 9 | +import type { SlackMessageEvent } from "../../types.js"; |
| 10 | +import { readSlackReplyBlocks, resolveSlackThreadTs } from "../replies.js"; |
| 11 | +import { resolveSlackTimestampMs } from "./timestamp.js"; |
| 12 | +import type { PreparedSlackMessage } from "./types.js"; |
| 13 | + |
| 14 | +function resolveSlackMessageTimestampMs(message: SlackMessageEvent): number | undefined { |
| 15 | + const ts = message.event_ts ?? message.ts; |
| 16 | + return resolveSlackTimestampMs(ts); |
| 17 | +} |
| 18 | + |
| 19 | +export function resolveSlackBotLoopProtection( |
| 20 | + prepared: PreparedSlackMessage, |
| 21 | +): ChannelBotLoopProtectionFacts | undefined { |
| 22 | + const senderBotId = prepared.message.bot_id; |
| 23 | + if (!senderBotId) { |
| 24 | + return undefined; |
| 25 | + } |
| 26 | + const receiverBotId = prepared.ctx.botId || prepared.ctx.botUserId; |
| 27 | + if ( |
| 28 | + !receiverBotId || |
| 29 | + senderBotId === prepared.ctx.botId || |
| 30 | + prepared.message.user === prepared.ctx.botUserId |
| 31 | + ) { |
| 32 | + return undefined; |
| 33 | + } |
| 34 | + return { |
| 35 | + scopeId: prepared.route.accountId, |
| 36 | + conversationId: prepared.message.channel, |
| 37 | + senderId: senderBotId, |
| 38 | + receiverId: receiverBotId, |
| 39 | + config: mergePairLoopGuardConfig( |
| 40 | + prepared.account.config.botLoopProtection, |
| 41 | + prepared.channelConfig?.botLoopProtection, |
| 42 | + ), |
| 43 | + defaultsConfig: prepared.ctx.cfg.channels?.defaults?.botLoopProtection, |
| 44 | + defaultEnabled: true, |
| 45 | + nowMs: resolveSlackMessageTimestampMs(prepared.message), |
| 46 | + }; |
| 47 | +} |
| 48 | + |
| 49 | +export function isSlackStreamingEnabled(params: { |
| 50 | + mode: "off" | "partial" | "block" | "progress"; |
| 51 | + nativeStreaming: boolean; |
| 52 | + nativeProgressTaskCards?: boolean; |
| 53 | +}): boolean { |
| 54 | + if (params.mode === "partial") { |
| 55 | + return params.nativeStreaming; |
| 56 | + } |
| 57 | + if (params.mode === "progress") { |
| 58 | + return params.nativeStreaming && params.nativeProgressTaskCards === true; |
| 59 | + } |
| 60 | + return false; |
| 61 | +} |
| 62 | + |
| 63 | +export function shouldEnableSlackPreviewStreaming(params: { |
| 64 | + mode: "off" | "partial" | "block" | "progress"; |
| 65 | +}): boolean { |
| 66 | + return params.mode !== "off"; |
| 67 | +} |
| 68 | + |
| 69 | +export function shouldInitializeSlackDraftStream(params: { |
| 70 | + previewStreamingEnabled: boolean; |
| 71 | + useStreaming: boolean; |
| 72 | +}): boolean { |
| 73 | + return params.previewStreamingEnabled && !params.useStreaming; |
| 74 | +} |
| 75 | + |
| 76 | +export function resolveSlackDisableBlockStreaming(params: { |
| 77 | + useStreaming: boolean; |
| 78 | + shouldUseDraftStream: boolean; |
| 79 | + blockStreamingEnabled: boolean | undefined; |
| 80 | +}): boolean | undefined { |
| 81 | + if (params.useStreaming || params.shouldUseDraftStream) { |
| 82 | + return true; |
| 83 | + } |
| 84 | + return typeof params.blockStreamingEnabled === "boolean" |
| 85 | + ? !params.blockStreamingEnabled |
| 86 | + : undefined; |
| 87 | +} |
| 88 | + |
| 89 | +export function resolveExplicitSlackProgressTitle( |
| 90 | + entry: Parameters<typeof resolveChannelProgressDraftConfig>[0], |
| 91 | +): string | undefined { |
| 92 | + const label = resolveChannelProgressDraftConfig(entry).label; |
| 93 | + if (typeof label !== "string") { |
| 94 | + return undefined; |
| 95 | + } |
| 96 | + const trimmed = label.trim(); |
| 97 | + return trimmed && trimmed.toLowerCase() !== "auto" ? trimmed : undefined; |
| 98 | +} |
| 99 | + |
| 100 | +export function resolveSlackNativeProgressTaskCards( |
| 101 | + entry: Parameters<typeof resolveChannelProgressDraftConfig>[0], |
| 102 | +): boolean { |
| 103 | + const streaming = entry?.streaming; |
| 104 | + if (!streaming || typeof streaming !== "object" || Array.isArray(streaming)) { |
| 105 | + return false; |
| 106 | + } |
| 107 | + const progressConfig = (streaming as Record<string, unknown>).progress; |
| 108 | + return ( |
| 109 | + Boolean(progressConfig) && |
| 110 | + typeof progressConfig === "object" && |
| 111 | + !Array.isArray(progressConfig) && |
| 112 | + (progressConfig as { nativeTaskCards?: unknown }).nativeTaskCards === true |
| 113 | + ); |
| 114 | +} |
| 115 | + |
| 116 | +export function resolveSlackStreamingThreadHint(params: { |
| 117 | + replyToMode: "off" | "first" | "all" | "batched"; |
| 118 | + incomingThreadTs: string | undefined; |
| 119 | + messageTs: string | undefined; |
| 120 | + isThreadReply?: boolean; |
| 121 | +}): string | undefined { |
| 122 | + return resolveSlackThreadTs({ |
| 123 | + replyToMode: params.replyToMode, |
| 124 | + incomingThreadTs: params.incomingThreadTs, |
| 125 | + messageTs: params.messageTs, |
| 126 | + hasReplied: false, |
| 127 | + isThreadReply: params.isThreadReply, |
| 128 | + }); |
| 129 | +} |
| 130 | + |
| 131 | +export type SlackEventDeliveryAttempt = { |
| 132 | + kind: ReplyDispatchKind; |
| 133 | + payload: ReplyPayload; |
| 134 | + threadTs?: string; |
| 135 | + textOverride?: string; |
| 136 | +}; |
| 137 | + |
| 138 | +const SLACK_STREAM_RECIPIENT_TEAM_CACHE_MAX = 2000; |
| 139 | +const slackStreamRecipientTeamCaches = new WeakMap<object, Map<string, string>>(); |
| 140 | + |
| 141 | +function getSlackStreamRecipientTeamCache(client: object): Map<string, string> { |
| 142 | + const existing = slackStreamRecipientTeamCaches.get(client); |
| 143 | + if (existing) { |
| 144 | + return existing; |
| 145 | + } |
| 146 | + const cache = new Map<string, string>(); |
| 147 | + slackStreamRecipientTeamCaches.set(client, cache); |
| 148 | + return cache; |
| 149 | +} |
| 150 | + |
| 151 | +function buildSlackEventDeliveryKey(params: SlackEventDeliveryAttempt): string | null { |
| 152 | + const reply = resolveSendableOutboundReplyParts(params.payload, { |
| 153 | + text: params.textOverride, |
| 154 | + }); |
| 155 | + const renderPlan = resolveSlackReplyRenderPlan( |
| 156 | + params.payload, |
| 157 | + params.textOverride ?? params.payload.text, |
| 158 | + ); |
| 159 | + const plannedBlocks = |
| 160 | + renderPlan.mode === "single" ? renderPlan.blocks : renderPlan.blockPart?.blocks; |
| 161 | + const slackBlocks = readSlackReplyBlocks(params.payload) ?? plannedBlocks; |
| 162 | + const renderedText = renderPlan.mode === "single" ? renderPlan.text : renderPlan.fallbackText; |
| 163 | + if (!reply.hasContent && !slackBlocks?.length && !renderedText.trim()) { |
| 164 | + return null; |
| 165 | + } |
| 166 | + return JSON.stringify({ |
| 167 | + kind: params.kind, |
| 168 | + threadTs: params.threadTs ?? "", |
| 169 | + replyToId: params.payload.replyToId ?? null, |
| 170 | + text: renderedText || reply.trimmedText, |
| 171 | + mediaUrls: reply.mediaUrls, |
| 172 | + blocks: slackBlocks ?? null, |
| 173 | + }); |
| 174 | +} |
| 175 | + |
| 176 | +function readSlackStreamRecipientTeamCache(params: { |
| 177 | + client: object; |
| 178 | + fallbackTeamId?: string; |
| 179 | + userId?: string; |
| 180 | +}): string | undefined { |
| 181 | + if (!params.fallbackTeamId || !params.userId) { |
| 182 | + return undefined; |
| 183 | + } |
| 184 | + const cacheKey = `${params.fallbackTeamId}:${params.userId}`; |
| 185 | + const cache = getSlackStreamRecipientTeamCache(params.client); |
| 186 | + const cached = cache.get(cacheKey); |
| 187 | + if (!cached) { |
| 188 | + return undefined; |
| 189 | + } |
| 190 | + cache.delete(cacheKey); |
| 191 | + cache.set(cacheKey, cached); |
| 192 | + return cached; |
| 193 | +} |
| 194 | + |
| 195 | +function rememberSlackStreamRecipientTeam(params: { |
| 196 | + client: object; |
| 197 | + fallbackTeamId?: string; |
| 198 | + userId?: string; |
| 199 | + teamId: string; |
| 200 | +}): void { |
| 201 | + if (!params.fallbackTeamId || !params.userId) { |
| 202 | + return; |
| 203 | + } |
| 204 | + const cacheKey = `${params.fallbackTeamId}:${params.userId}`; |
| 205 | + const cache = getSlackStreamRecipientTeamCache(params.client); |
| 206 | + if (cache.has(cacheKey)) { |
| 207 | + cache.delete(cacheKey); |
| 208 | + } |
| 209 | + cache.set(cacheKey, params.teamId); |
| 210 | + if (cache.size > SLACK_STREAM_RECIPIENT_TEAM_CACHE_MAX) { |
| 211 | + const oldest = cache.keys().next().value; |
| 212 | + if (oldest) { |
| 213 | + cache.delete(oldest); |
| 214 | + } |
| 215 | + } |
| 216 | +} |
| 217 | + |
| 218 | +export function createSlackEventDeliveryTracker() { |
| 219 | + const deliveredKeys = new Set<string>(); |
| 220 | + return { |
| 221 | + hasDelivered(params: SlackEventDeliveryAttempt) { |
| 222 | + const key = buildSlackEventDeliveryKey(params); |
| 223 | + return key ? deliveredKeys.has(key) : false; |
| 224 | + }, |
| 225 | + markDelivered(params: SlackEventDeliveryAttempt) { |
| 226 | + const key = buildSlackEventDeliveryKey(params); |
| 227 | + if (key) { |
| 228 | + deliveredKeys.add(key); |
| 229 | + } |
| 230 | + }, |
| 231 | + }; |
| 232 | +} |
| 233 | + |
| 234 | +export function shouldUseStreaming(params: { |
| 235 | + streamingEnabled: boolean; |
| 236 | + threadTs: string | undefined; |
| 237 | +}): boolean { |
| 238 | + if (!params.streamingEnabled) { |
| 239 | + return false; |
| 240 | + } |
| 241 | + if (!params.threadTs) { |
| 242 | + logVerbose("slack-stream: streaming disabled — no reply thread target available"); |
| 243 | + return false; |
| 244 | + } |
| 245 | + return true; |
| 246 | +} |
| 247 | + |
| 248 | +export async function resolveSlackStreamRecipientTeamId(params: { |
| 249 | + client: Pick<PreparedSlackMessage["ctx"]["app"]["client"], "users">; |
| 250 | + token: string; |
| 251 | + userId?: PreparedSlackMessage["message"]["user"]; |
| 252 | + fallbackTeamId?: string; |
| 253 | +}): Promise<string | undefined> { |
| 254 | + const cachedTeamId = readSlackStreamRecipientTeamCache(params); |
| 255 | + if (cachedTeamId) { |
| 256 | + return cachedTeamId; |
| 257 | + } |
| 258 | + if (params.userId) { |
| 259 | + try { |
| 260 | + const info = await params.client.users.info({ |
| 261 | + token: params.token, |
| 262 | + user: params.userId, |
| 263 | + }); |
| 264 | + const teamId = info.user?.team_id ?? info.user?.profile?.team; |
| 265 | + if (teamId) { |
| 266 | + rememberSlackStreamRecipientTeam({ ...params, teamId }); |
| 267 | + return teamId; |
| 268 | + } |
| 269 | + } catch (err) { |
| 270 | + logVerbose(`slack-stream: users.info team lookup failed (${formatErrorMessage(err)})`); |
| 271 | + } |
| 272 | + } |
| 273 | + return params.fallbackTeamId; |
| 274 | +} |
0 commit comments