UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

584 lines (583 loc) • 19.8 kB
import { h as clampPositiveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs"; import { E as readReplyPayloadSourceOccurrence, _ as isReplyPayloadStatusNotice, c as getReplyPayloadMetadata, k as setReplyPayloadMetadata, o as copyReplyPayloadMetadata, y as isReplyPayloadTerminalContent } from "./reply-payload-k5WsQWxi.mjs"; import { r as logVerbose } from "./globals-CgepmiqE.mjs"; import { s as shouldAttemptTtsPayload } from "./tts-config-CNw5woLC.mjs"; import { t as runAbortableTimeout } from "./with-timeout-D-ymI111.mjs"; import { a as hasOutboundReplyContent } from "./reply-payload-CwASJYas.mjs"; import { a as resolveSendableOutboundReplyParts } from "./reply-payload-parts-0Tn7wkpR.mjs"; import { o as prepareReplyPayloadForDispatcher } from "./reply-dispatcher-DVZA5pVi.mjs"; import { l as shouldRetryReplyDispatch, s as resolveReplyDispatchErrorOutcome } from "./reply-dispatch-outcome-C1yqMjJt.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/auto-reply/reply/block-reply-delivery.ts function hasBlockReplyDeliveryCustody(e) { return e.pending === true || e.outcome !== "delivered" && !shouldRetryReplyDispatch(e.outcome); } const deliveries = new AsyncLocalStorage(); function setBlockReplyDelivery(e, t) { const n = deliveries.getStore(); if (n) { n.settlement = e; n.payload = t; } } function createBlockReplySource() { const e = []; let t = true; let n = 0; let r; let i = Promise.resolve(); const isDelivered = (e) => e.outcome === "delivered" && !e.pending; const a = { get complete() { return t && n === 0 && (!r || isDelivered(r)); }, get pending() { return n > 0 || r !== void 0 && hasBlockReplyDeliveryCustody(r); }, setComplete(e) { t = e; }, run(t) { const o = deliveries.getStore(); if (o) o.source = a; n++; let s = { outcome: "cancelled" }; const c = {}; const l = i.then(() => { if (r && !isDelivered(r)) { s = r; return; } return deliveries.run(c, t); }); const u = l.then(() => c.settlement ?? s).then((t) => { if (c.payload) { e.push({ payload: c.payload, delivery: t }); r = t; } return t; }, (e) => { r = { outcome: resolveReplyDispatchErrorOutcome(e) }; return r; }).finally(() => { n--; }); i = u.then(() => void 0); if (o) o.settlement = u; return l; }, settle: () => i.then(() => r ?? { outcome: "delivered" }), recoverPartial(t) { let n = t.text; for (const t of e) { if (!isDelivered(t.delivery)) break; const e = t.payload.text?.trimStart(); if (!e) continue; const r = n?.trimStart(); if (!r?.startsWith(e)) break; n = r.slice(e.length); } return copyReplyPayloadMetadata(t, { ...t, text: n || void 0 }); } }; return a; } async function recoverBlockReplySources(e, t) { const n = await Promise.all(t.map((e) => e.settle())); const r = t.every((e) => e.complete) ? { outcome: "delivered" } : n.find(hasBlockReplyDeliveryCustody) ?? (t.some((e) => e.pending) ? { outcome: "delivered-not-visible", pending: true } : void 0); if (r) return { payload: copyReplyPayloadMetadata(e, { ...e, text: void 0 }), delivery: r }; return { payload: t.reduce((e, t) => t.recoverPartial(e), e) }; } async function deliverBlockReply(e) { const t = {}; await deliveries.run(t, e); const n = await t.settlement ?? { outcome: "delivered" }; return t.source ? { ...n, source: t.source } : n; } //#endregion //#region src/auto-reply/reply/block-reply-pipeline.ts function createBlockReplyCoalescer(e) { const { config: t, shouldAbort: n, onFlush: r } = e; const { minChars: i, maxChars: a, idleMs: o, joiner: s } = t; let c = ""; let l = {}; let u; let d; const clearIdleTimer = () => { clearTimeout(d); d = void 0; }; const resetBuffer = () => { c = ""; l = {}; u = void 0; }; const scheduleIdleFlush = () => { if (o <= 0) return; clearIdleTimer(); d = setTimeout(() => { flush({ force: false }); }, o); }; const flush = async (e) => { clearIdleTimer(); if (n()) { resetBuffer(); return; } if (!c || !u) return; if (!e?.force && c.length < i) { scheduleIdleFlush(); return; } const t = setReplyPayloadMetadata(copyReplyPayloadMetadata(u, { ...u, text: c }), l); resetBuffer(); await r(t); }; const separatorFor = (e) => c.endsWith("\n") || e.startsWith("\n") ? "" : s; const canMergeBufferedTextWithMedia = (e, t) => Boolean(c) && (!t || c.length + separatorFor(t).length + t.length <= a) && u !== void 0 && [u, e].every((e) => !e.audioAsVoice && !e.isReasoning && !e.isCommentary && !isReplyPayloadStatusNotice(e)) && (!e.replyToId || u.replyToId === e.replyToId); const mergeSource = (e, t) => ({ streamedSourceBoundary: c ? l.streamedSourceBoundary : t.streamedSourceBoundary, blockSourceText: l.blockSourceText !== void 0 || t.blockSourceText !== void 0 ? (l.blockSourceText ?? c) + (t.blockSourceText ?? e) : void 0, blockSourceRange: l.blockSourceRange && t.blockSourceRange ? [l.blockSourceRange[0], t.blockSourceRange[1]] : l.blockSourceRange ?? t.blockSourceRange }); const mergeBufferedTextWithMedia = (e, t) => { const n = t ? `${c}${separatorFor(t)}${t}` : c; const r = mergeSource(t, t ? getReplyPayloadMetadata(e) ?? {} : {}); const i = { ...u, ...e, text: n, replyToId: e.replyToId ?? u?.replyToId, replyToCurrent: e.replyToCurrent || u?.replyToCurrent, replyToTag: e.replyToTag || u?.replyToTag }; const a = copyReplyPayloadMetadata(u ?? i, i); resetBuffer(); return setReplyPayloadMetadata(copyReplyPayloadMetadata(e, a), r); }; const enqueue = (e) => { if (n()) return; const t = resolveSendableOutboundReplyParts(e); const i = t.text; const o = { blockSourceText: getReplyPayloadMetadata(e)?.blockSourceText, blockSourceRange: getReplyPayloadMetadata(e)?.blockSourceRange, streamedSourceBoundary: getReplyPayloadMetadata(e)?.streamedSourceBoundary }; if (t.hasMedia) { if (canMergeBufferedTextWithMedia(e, i)) { r(mergeBufferedTextWithMedia(e, i)); return; } flush({ force: true }); r(e); return; } if (!t.hasText) return; const s = Boolean(e.replyToId && u?.replyToId !== e.replyToId); const d = u && (u.isReasoning !== e.isReasoning || u.isCommentary !== e.isCommentary || u.isCompactionNotice !== e.isCompactionNotice || u.isFallbackNotice !== e.isFallbackNotice || isReplyPayloadStatusNotice(u) !== isReplyPayloadStatusNotice(e)); if (c && (s || u?.audioAsVoice !== e.audioAsVoice || d)) flush({ force: true }); if (!c) u = e; let f = c ? `${c}${separatorFor(i)}${i}` : i; const p = f.length > a; if (p) { if (c) { flush({ force: true }); u = e; } if (i.length >= a) { r(e); return; } f = i; } l = p ? o : mergeSource(i, o); c = f; if (c.length >= a) { flush({ force: true }); return; } scheduleIdleFlush(); }; return { enqueue, flush, hasBuffered: () => Boolean(c), stop: clearIdleTimer }; } function createBlockReplyContentIdentity(e) { const t = resolveSendableOutboundReplyParts(e); return { text: t.trimmedText, mediaList: t.mediaUrls, presentation: e.presentation ?? null, presentationTextMode: e.presentationTextMode ?? null, interactive: e.interactive ?? null, channelData: e.channelData ?? null, location: e.location ?? null, videoAsNote: e.videoAsNote === true }; } function createBlockReplyPayloadKey(e) { return JSON.stringify({ ...createBlockReplyContentIdentity(e), statusNotice: isReplyPayloadStatusNotice(e), reasoning: e.isReasoning === true, commentary: e.isCommentary === true, assistantMessageIndex: getReplyPayloadMetadata(e)?.assistantMessageIndex ?? null, replyToId: e.replyToId ?? null }); } function createBlockReplyContentKey(e) { return JSON.stringify(createBlockReplyContentIdentity(e)); } function createIndexedBlockReplyContentKey(e) { const t = createBlockReplyContentKey(e); const n = getReplyPayloadMetadata(e)?.assistantMessageIndex; return n === void 0 ? t : `${n}:${t}`; } function createBlockReplyPipeline(e) { const { onBlockReply: t, coalescing: n, isAudioPayload: r } = e; const i = clampPositiveTimerTimeoutMs(e.timeoutMs) ?? 0; const a = /* @__PURE__ */ new Set(); const o = /* @__PURE__ */ new Set(); const s = /* @__PURE__ */ new Set(); const c = /* @__PURE__ */ new Set(); const l = /* @__PURE__ */ new Set(); const u = []; let d = false; const f = /* @__PURE__ */ new Map(); let p; let m = Promise.resolve(); let h = false; let g = false; const hasSeenOrQueuedPayloadKey = (e) => l.has(e) || a.has(e) || c.has(e); const resolveDedupeIdentity = (e, t) => { const n = getReplyPayloadMetadata(e)?.blockSourceText; const r = readReplyPayloadSourceOccurrence(e); const i = r ? JSON.stringify(r) : void 0; return { sourceText: n, occurrenceKey: i, key: i ?? t, unkeyedSource: n !== void 0 && i === void 0 }; }; const flushBufferedAssistantBlock = () => { p = void 0; _?.flush({ force: true }); }; const sendPayload = (e, n) => { if (h) return; const r = createBlockReplyPayloadKey(e); const u = createBlockReplyContentKey(e); const d = resolveDedupeIdentity(e, r); if (!n && !d.unkeyedSource) { if (l.has(d.key)) return; l.add(d.key); } if (d.occurrenceKey) l.add(r); if (!d.unkeyedSource && (a.has(d.key) || c.has(d.key))) return; c.add(d.key); const p = isReplyPayloadTerminalContent(e); const _ = resolveSendableOutboundReplyParts(e); const v = getReplyPayloadMetadata(e); const y = { outcome: "cancelled", sourceText: d.sourceText ?? _.trimmedText, contentKey: u, mediaUrls: _.mediaUrls, terminal: p && hasOutboundReplyContent(e, { trimText: true }), messageStart: v?.assistantMessageStartIndex }; const b = v?.assistantMessageIndex; const x = f.get(b) ?? []; x.push(y); f.set(b, x); let S; m = m.then(async () => { if (h) return false; y.outcome = "failed-deliver"; y.pending = true; return await runAbortableTimeout(async (n) => { S = n; return await deliverBlockReply(() => t(e, { abortSignal: n, timeoutMs: i })); }, i || void 0, "block reply delivery"); }).then((t) => { if (!t) return; Object.assign(y, t, { pending: t.pending === true }); const n = isReplyPayloadStatusNotice(e); if (t.outcome !== "delivered" || t.pending) return; if (t.source?.complete !== false) { a.add(d.key); if (p) { if (y.terminal) y.terminalDeliveryConfirmed = true; o.add(u); o.add(createIndexedBlockReplyContentKey(e)); } } for (const e of _.mediaUrls) s.add(e); if (!n) g = true; }).catch((e) => { if (S?.aborted) { h = true; logVerbose(`block reply delivery timed out after ${i}ms; skipping remaining block replies to preserve ordering`); return; } y.outcome = resolveReplyDispatchErrorOutcome(e); y.pending = false; logVerbose(`block reply delivery failed: ${String(e)}`); }).finally(() => { c.delete(d.key); }); }; const _ = n ? createBlockReplyCoalescer({ config: n, shouldAbort: () => h, onFlush: (e) => { p = void 0; sendPayload(e, true); } }) : null; const bufferPayload = (e) => { d ||= Boolean(e.audioAsVoice); if (!r?.(e)) return false; const t = createBlockReplyPayloadKey(e); if (hasSeenOrQueuedPayloadKey(t)) return true; l.add(t); u.push(e); return true; }; const flushBuffered = () => { for (const e of u) { const t = d ? copyReplyPayloadMetadata(e, { ...e, audioAsVoice: true }) : e; sendPayload(t, true); } u.length = 0; }; const enqueueCoalescedPayload = (e) => { if (!_) return; const t = getReplyPayloadMetadata(e)?.assistantMessageIndex; if (t !== void 0 && p !== void 0 && t !== p && _.hasBuffered()) flushBufferedAssistantBlock(); const n = createBlockReplyPayloadKey(e); const r = resolveDedupeIdentity(e, n); if (!r.unkeyedSource && hasSeenOrQueuedPayloadKey(r.key)) return; if (!r.unkeyedSource) l.add(r.key); if (r.occurrenceKey) l.add(n); p = t; _.enqueue(e); }; const enqueue = (e) => { if (h) return; if (bufferPayload(e)) { flushBufferedAssistantBlock(); return; } flushBuffered(); const t = hasOutboundReplyContent({ ...e, text: void 0, mediaUrl: void 0, mediaUrls: void 0 }, { trimText: true }); if (_ && !t) { enqueueCoalescedPayload(e); return; } _?.flush({ force: true }); sendPayload(e, false); }; const flush = async (e) => { await _?.flush(e); p = void 0; flushBuffered(); await m; }; const matchingTerminalAttempts = function* (e) { const t = getReplyPayloadMetadata(e)?.assistantMessageIndex; if (t === void 0) { for (const e of f.values()) yield e.filter((e) => e.terminal); return; } const n = f.get(t)?.[0]?.messageStart ?? t; for (let e = t, r = []; e >= n; e--) { const t = f.get(e); if (t?.length) { r = [...t.filter((e) => e.terminal), ...r]; yield r; } } }; const normalizeSource = (e) => e.replace(/\s+/g, ""); const combinedSource = (e) => normalizeSource(e.map((e) => e.sourceText).join("")); const hasAttempt = (e, t) => { for (const [n, r] of f) if ((t === void 0 || (n ?? 0) >= t) && r.some(e)) return true; return false; }; return { enqueue, flush, stop: () => _?.stop(), hasBuffered: () => _?.hasBuffered() || u.length > 0, didStream: () => g, didStreamTerminalReply: (e = 0) => hasAttempt((e) => e.terminalDeliveryConfirmed === true, e), isAborted: () => h, hasSentExactPayload: (e) => o.has(createIndexedBlockReplyContentKey(e)), getSourceRecovery: (e) => { const t = normalizeSource(resolveSendableOutboundReplyParts(e).trimmedText); for (const n of matchingTerminalAttempts(e)) if (t && combinedSource(n) === t && n.some((e) => e.source?.complete === false)) return Array.from(new Set(n.flatMap((e) => e.source ?? []))); }, isFinalPayloadRetryBlocked: (e) => { const t = createBlockReplyContentKey(e); const n = resolveSendableOutboundReplyParts(e); const r = normalizeSource(n.trimmedText); const i = !hasOutboundReplyContent({ ...e, text: void 0 }); for (const n of matchingTerminalAttempts(e)) { const e = n.filter(hasBlockReplyDeliveryCustody); const a = combinedSource(n); if (e.some((e) => e.contentKey === t) || i && e.length > 0 && a.length > 0 && r.startsWith(a)) return true; } return false; }, hasSentPayload: (e) => { const t = createIndexedBlockReplyContentKey(e); if (o.has(t)) return true; if (!g) return false; const n = resolveSendableOutboundReplyParts(e); if (n.hasMedia || !n.trimmedText) return false; const r = normalizeSource(n.trimmedText); for (const t of matchingTerminalAttempts(e)) { const e = t.filter((e) => e.outcome === "delivered" && !e.pending && e.source?.complete !== false); if (e.length > 0 && combinedSource(e) === r) return true; } return false; }, getSentMediaUrls: () => Array.from(s), hasRetryBlockedDelivery: () => hasAttempt(hasBlockReplyDeliveryCustody), hasRetryBlockedTerminalDelivery: (e = 0) => hasAttempt((e) => e.terminal && hasBlockReplyDeliveryCustody(e), e), getRetryBlockedMediaUrls: () => Array.from(new Set(Array.from(f.values()).flatMap((e) => e.filter(hasBlockReplyDeliveryCustody).flatMap((e) => e.mediaUrls)))) }; } //#endregion //#region src/auto-reply/reply/dispatch-from-config.payloads.ts const ttsRuntimeLoader = createLazyImportLoader(() => import("./tts.runtime.js")); const QUEUE_CAP_REJECTION_TEXT = "This message was not queued because the session queue is full. Please try again after the current response finishes."; const COLLABORATIVE_STEERING_DISABLED_TEXT = "Someone else’s turn is still running, and collaborative steering is disabled. Your message wasn’t queued. Resend it as /followup <message> to run it afterward.\n\nAdmins can enable collaborative steering with messages.queue.allowCollaborativeSteering: true."; function shouldDeliverDespiteSourceReplySuppression(e, t) { return t.suppressAutomaticSourceDelivery && !t.sendPolicyDenied && getReplyPayloadMetadata(e)?.deliverDespiteSourceReplySuppression === true && (t.ctx.InboundEventKind !== "room_event" || t.explicitCommandTurnCtx); } function hasExecApprovalPayload(e) { return isRecord(e.channelData?.execApproval); } function hasExecApprovalUnavailablePayload(e) { return isRecord(e.channelData?.execApprovalUnavailable); } function hasAskUserPayload(e) { return isRecord(e.channelData?.askUser); } function requiresDurableToolResultDelivery(e) { return resolveSendableOutboundReplyParts(e).hasMedia || hasExecApprovalPayload(e) || hasExecApprovalUnavailablePayload(e) || hasAskUserPayload(e); } function createFinalDispatchPayloadDedupeKey(e) { const t = getReplyPayloadMetadata(e); return JSON.stringify({ payload: { text: e.text, mediaUrl: e.mediaUrl, mediaUrls: e.mediaUrls, trustedLocalMedia: e.trustedLocalMedia, sensitiveMedia: e.sensitiveMedia, presentation: e.presentation, presentationTextMode: e.presentationTextMode, delivery: e.delivery, interactive: e.interactive, btw: e.btw, replyToId: e.replyToId, replyToTag: e.replyToTag, replyToCurrent: e.replyToCurrent, audioAsVoice: e.audioAsVoice, videoAsNote: e.videoAsNote === true, location: e.location, spokenText: e.spokenText, ttsSupplement: e.ttsSupplement, isError: e.isError, isReasoning: e.isReasoning, isCommentary: e.isCommentary, isReasoningSnapshot: e.isReasoningSnapshot, isCompactionNotice: e.isCompactionNotice, isFallbackNotice: e.isFallbackNotice, isStatusNotice: e.isStatusNotice, channelData: e.channelData }, identity: { assistantMessageIndex: t?.assistantMessageIndex, assistantTranscriptOwned: t?.assistantTranscriptOwned, replyToIdExplicit: t?.replyToIdExplicit, replyDelivery: t?.replyDelivery, replyDeliverySource: t?.replyDeliverySource, sourceReplyTranscriptMirror: t?.sourceReplyTranscriptMirror } }); } async function maybeApplyTtsToReplyPayload(e) { if (isReplyPayloadStatusNotice(e.payload)) return e.payload; if (!shouldAttemptTtsPayload({ cfg: e.cfg, preparedTtsPreferences: e.preparedTtsPreferences, ttsAuto: e.ttsAuto, agentId: e.agentId, channelId: e.channel, accountId: e.accountId })) return e.payload; const { maybeApplyTtsToPayload: t } = await ttsRuntimeLoader.load(); const n = await t(e); return n === e.payload ? n : copyReplyPayloadMetadata(e.payload, n); } /** Applies dispatcher normalization before TTS or transcript-visible side effects. */ function prepareReplyPayloadForSideEffects(e, t, n, r, i) { if (!n) return null; const a = prepareReplyPayloadForDispatcher(e, t, n); if (a.kind === "deliver") { r.acceptedReplyPayload = true; if (a.payload.isReasoning !== true && a.payload.isCommentary !== true && hasOutboundReplyContent(a.payload, { trimText: true })) i?.(); return a.payload; } r.channelTransformSuppressed ||= a.reason === "channel_transform"; return null; } //#endregion export { setBlockReplyDelivery as _, hasExecApprovalPayload as a, prepareReplyPayloadForSideEffects as c, createBlockReplyContentKey as d, createBlockReplyPipeline as f, recoverBlockReplySources as g, hasBlockReplyDeliveryCustody as h, hasAskUserPayload as i, requiresDurableToolResultDelivery as l, deliverBlockReply as m, QUEUE_CAP_REJECTION_TEXT as n, hasExecApprovalUnavailablePayload as o, createBlockReplySource as p, createFinalDispatchPayloadDedupeKey as r, maybeApplyTtsToReplyPayload as s, COLLABORATIVE_STEERING_DISABLED_TEXT as t, shouldDeliverDespiteSourceReplySuppression as u };