UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

395 lines (394 loc) • 15.2 kB
import { n as waitForAgentDatabaseWriteAdmission } from "./agent-database-preparation-context-CkVoUMTY.mjs"; import { j as parseAgentSessionKey, l as resolveAgentIdFromSessionKey } from "./session-key-CqAyZeVk.mjs"; import { T as runWithDiagnosticTraceContext, _ as createDiagnosticTraceContextFromActiveScope } from "./diagnostics-timeline-CSwiG24r.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { t as getPluginServiceSchedulerBinding } from "./service-scheduler-binding-Drpxji0r.mjs"; import { c as normalizeDeliveryContext, n as deliveryContextKey } from "./delivery-context.shared-CRlipPTj.mjs"; import { E as readReplyPayloadSourceOccurrence, c as getReplyPayloadMetadata, k as setReplyPayloadMetadata } from "./reply-payload-k5WsQWxi.mjs"; import { t as deliveryContextFromSession } from "./delivery-context.read-BrYAJ7RK.mjs"; import { c as withSessionEntriesFromStoresInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { f as clearChannelHistoryIfEnabled } from "./history-B0kihfTi.mjs"; import "./session-accessor-CizTbDQj.mjs"; import { c as updateSessionEntry } from "./session-accessor.entry-mutation-IJ4DYZ4a.mjs"; import { t as appendAssistantMessageToSessionTranscript } from "./transcript-CbrBMDcL.mjs"; import { r as PlatformMessageNotDispatchedError } from "./deliver-types-BnSKrpHG.mjs"; import { o as settlePendingFinalDelivery } from "./delivery-completion-DkLj6KUt.mjs"; import { i as prepareSessionWriterDeliveryAuthority, t as assertSessionWriterDeliveryAuthorized } from "./session-writer-delivery-authority-DNB-b5xs.mjs"; import { n as withDispatchProcessedOutcomeSink } from "./dispatch-processed-outcome-BVnjMfpJ.mjs"; import { t as isRecentOutboundMessageIdentity } from "./outbound-echo-CP5L3mPZ.mjs"; import { n as getGatewayLifecycleRuntime } from "./server-lifecycle-runtime-context-B_704IYm.mjs"; import { c as findDeliveryIntentOwner } from "./delivery-queue-storage-BLAjpQqf.mjs"; import { i as resolvePairLoopGuardSettings, n as createPairLoopGuard } from "./pair-loop-guard-runtime-3kSPivB8.mjs"; //#region src/channels/turn/bot-loop-protection.ts const channelBotPairLoopGuard = createPairLoopGuard({ pruneIntervalMs: 6e4 }); function recordChannelBotPairLoopAndCheckSuppression(e) { return channelBotPairLoopGuard.recordAndCheck({ scopeId: e.scopeId, conversationId: e.conversationId, senderId: e.senderId, receiverId: e.receiverId, eventId: e.eventId, settings: resolvePairLoopGuardSettings(e), nowMs: e.nowMs }); } //#endregion //#region src/channels/turn/dispatch-result.ts const hasFinalSignal = (e) => e.fallbackDelivered === true || e.deliverySummaryDelivered === true; const hasVisibleSignal = (e, t) => e?.observedReplyDelivery === true || t.observedReplyDelivery === true || hasFinalSignal(t); const EMPTY_CHANNEL_TURN_DISPATCH_COUNTS = { tool: 0, block: 0, final: 0 }; function hasVisibleChannelTurnDispatchFromReceipt(e, t = {}) { return e?.settledReceipt?.anyVisibleDelivered === true || hasVisibleSignal(e, t); } function resolveChannelTurnDispatchCounts(e) { const t = e?.settledReceipt?.counts; return t ? { tool: t.tool?.delivered ?? 0, block: t.block?.delivered ?? 0, final: t.final?.delivered ?? 0 } : { ...EMPTY_CHANNEL_TURN_DISPATCH_COUNTS, ...e?.counts }; } function hasVisibleChannelTurnDispatch(e, t = {}) { if (e?.settledReceipt) return hasVisibleChannelTurnDispatchFromReceipt(e, t); return hasVisibleSignal(e, t) || e?.queuedFinal === true || Object.values(resolveChannelTurnDispatchCounts(e)).some((e) => e > 0); } function hasFinalChannelTurnDispatch(e, t = {}) { const n = e?.settledReceipt?.counts.final; return hasFinalSignal(t) || (e?.settledReceipt ? (n?.delivered ?? 0) > 0 || (n?.failedAfterSend ?? 0) > 0 : e?.queuedFinal === true || resolveChannelTurnDispatchCounts(e).final > 0); } //#endregion //#region src/channels/turn/direct-delivery-custody.ts var PendingFinalDeliveryNotOwnedError = class extends PlatformMessageNotDispatchedError { constructor(e) { super("Pending final delivery ownership changed before platform dispatch", { cause: /* @__PURE__ */ new Error(`pending final delivery is ${e}`), retryable: false }); } }; const NO_PENDING_FINAL_CUSTODY = { assertPlatformSendAuthorized: () => void 0, onPlatformSendDispatch: () => Promise.resolve(), release: () => void 0 }; function resolvePendingFinalCompletion(e) { const t = getReplyPayloadMetadata(e)?.pendingFinalDeliveryCompletion; return t ? { kind: "pending-final", ...t } : void 0; } const activeDeliveries = /* @__PURE__ */ new Set(); function hasActiveDirectPendingFinalDelivery(e, t) { for (const n of activeDeliveries) if (n.sessionId === e && n.intentId === t) return true; return false; } async function createDirectPendingFinalCustody(e, t) { const n = resolvePendingFinalCompletion(e); const r = getReplyPayloadMetadata(e)?.sessionWriterDeliveryAuthority; if (!n && !r) return; const { authority: i, release: a } = await prepareSessionWriterDeliveryAuthority(r, t); const o = n ? (({ kind: e, ...t }) => t)(n) : void 0; let s; return { bindPendingFinalDelivery: (e) => setReplyPayloadMetadata(e, { ...o ? { pendingFinalDeliveryCompletion: o } : {}, ...i ? { sessionWriterDeliveryAuthority: i } : {} }), assertPlatformSendAuthorized: () => assertSessionWriterDeliveryAuthorized(i), release: () => { if (n) activeDeliveries.delete(n); a(); }, onPlatformSendDispatch: async () => { await (s ??= (async () => { if (!n) return; activeDeliveries.add(n); const e = await settlePendingFinalDelivery(n, "unknown", ["prepared", "queued"]); if (e.state !== "unknown") throw new PendingFinalDeliveryNotOwnedError(e.state); })()); assertSessionWriterDeliveryAuthorized(i); } }; } function toCoreManagedDeliveryInfo(e, t) { const n = e.kind === "block" ? readReplyPayloadSourceOccurrence(t) : void 0; return { kind: e.kind, ...e.participant ? { participant: e.participant } : {}, ...e.assistantMessageIndex === void 0 ? {} : { assistantMessageIndex: e.assistantMessageIndex }, ...n ? { blockSourceRange: n.sourceRange } : {} }; } //#endregion //#region src/channels/turn/pending-delivery-notice.ts const PENDING_DELIVERY_NOTICE = "I couldn’t confirm whether my previous reply reached this chat, so I won’t resend it automatically. Please ask for any missing remainder."; async function deliverPendingDeliveryNotice(e, t, n) { const r = n ?? resolveAgentIdFromSessionKey(e); const i = await withSessionEntriesFromStoresInWorker([{ agentId: r, storePath: t, sessionKeys: [e], projection: "full" }], ([e]) => { const t = e?.result.entries[0]?.entry; const n = t?.pendingDeliveryNotice; const r = normalizeDeliveryContext(n?.context); const i = getGatewayLifecycleRuntime(); if (!t || !i || !n || n.state !== "owed" || !r?.channel || !r.to || deliveryContextKey(r) !== deliveryContextKey(deliveryContextFromSession(t)) || hasActiveDirectPendingFinalDelivery(t.sessionId, n.intentId)) return; e?.assertCurrent(); const a = `main-session-restart-recovery:pending-final:${n.intentId}`; return { entry: t, notice: n, idempotencyKey: a, delivery: i.sendNotice({ channel: r.channel, to: r.to, accountId: r.accountId, threadId: r.threadId, text: PENDING_DELIVERY_NOTICE, idempotencyKey: a }).catch(() => void 0) }; }, { ordered: true }); if (!i) return; const { entry: a, notice: o, idempotencyKey: s } = i; const c = await i.delivery; let l; if (c) l = !c.suppressed; else { const e = await findDeliveryIntentOwner(s); if (e?.status !== "completed" && e?.status !== "failed") return; l = e.status === "completed"; } if (l && !(await appendAssistantMessageToSessionTranscript({ agentId: r, sessionKey: e, storePath: t, expectedSessionId: a.sessionId, expectedLifecycleRevision: a.lifecycleRevision ?? null, text: PENDING_DELIVERY_NOTICE, idempotencyKey: s })).ok) return; await updateSessionEntry({ agentId: r, sessionKey: e, storePath: t }, (e) => e.sessionId === a.sessionId && (e.lifecycleRevision ?? null) === (a.lifecycleRevision ?? null) && e.pendingDeliveryNotice?.intentId === o.intentId && e.pendingDeliveryNotice.state !== "acknowledged" ? { pendingDeliveryNotice: { ...e.pendingDeliveryNotice, state: l ? "acknowledged" : "unresolved" }, updatedAt: Date.now() } : null, { skipMaintenance: true, takeCacheOwnership: true }); } //#endregion //#region src/channels/turn/execution.ts const log = createSubsystemLogger("channels/turn/execution"); function emit(e, t) { e.log?.({ channel: e.channel, accountId: e.accountId, messageId: e.messageId, sessionKey: e.ctxPayload.SessionKey ?? e.routeSessionKey, admission: e.admission?.kind ?? "dispatch", ...t }); } function clearPendingHistoryAfterTurn(e) { if (!e?.isGroup || !e.historyKey || !e.historyMap || e.limit === void 0) return; clearChannelHistoryIfEnabled({ historyMap: e.historyMap, historyKey: e.historyKey, limit: e.limit }); } function resolveRecordSessionKey(e) { const t = e.record?.sessionKey; if (t === void 0) return e.ctxPayload.SessionKey ?? e.routeSessionKey; const n = t.trim(); if (!n) throw new Error("Channel turn record.sessionKey must be non-empty."); if (n !== t) throw new Error("Channel turn record.sessionKey must not include surrounding whitespace."); return t; } function dropPreparedChannelTurn(e, t, n = e.messageId) { const r = { kind: "drop", reason: t }; emit(e, { stage: "authorize", event: "drop", messageId: n, admission: r.kind, reason: r.reason }); return { admission: r, dispatched: false, ctxPayload: e.ctxPayload, routeSessionKey: e.routeSessionKey }; } function resolveOutboundEchoDrop(e) { const t = [e.ctxPayload.NativeChannelId, e.ctxPayload.ChatId].find((e) => typeof e === "string" && e.trim().length > 0); if (!t) return; const n = [ e.messageId, e.ctxPayload.MessageSidFull, e.ctxPayload.MessageSid ].find((n) => typeof n === "string" && isRecentOutboundMessageIdentity({ channel: e.channel, accountId: e.accountId, conversationId: t, messageId: n })); const r = e.outboundEchoSourceId?.trim(); const i = r ? isRecentOutboundMessageIdentity({ channel: e.channel, accountId: e.accountId, conversationId: t, sourceId: r }) : false; if (!n && !i) return; return dropPreparedChannelTurn(e, "outbound-echo", e.messageId ?? n); } async function runPreparedChannelTurnCore(e, t) { const n = createDiagnosticTraceContextFromActiveScope(); return await runWithDiagnosticTraceContext(n, async () => { const n = e.admission ?? { kind: "dispatch" }; const r = resolveOutboundEchoDrop(e); if (r) { clearPendingHistoryAfterTurn(e.history); await e.runDispatchLifecycle?.onDispatchSkipped("outboundEcho"); return r; } if (e.botLoopProtection && recordChannelBotPairLoopAndCheckSuppression(e.botLoopProtection).suppressed) { const t = dropPreparedChannelTurn(e, "bot-loop-protection"); clearPendingHistoryAfterTurn(e.history); await e.runDispatchLifecycle?.onDispatchSkipped("botLoopProtection"); return t; } try { const r = resolveRecordSessionKey(e); const emitStage = (t, i, a) => emit(e, { stage: t, event: i, ...t === "record" ? { sessionKey: r } : {}, admission: n.kind, ...i === "error" ? { error: a } : {} }); try { const t = e.ctxPayload.AgentId ?? parseAgentSessionKey(e.routeSessionKey)?.agentId; const n = parseAgentSessionKey(r)?.agentId ?? t; for (const r of /* @__PURE__ */ new Set([t, n])) { if (!r) continue; const t = waitForAgentDatabaseWriteAdmission(r, { signal: getPluginServiceSchedulerBinding()?.().signal }); if (t) { log.info("channel message waiting for agent database preparation", { agentId: r, channel: e.channel, accountId: e.accountId }); emit(e, { stage: "record", event: "start", reason: "agent-database-preparation-pending" }); await t; } } e.assertAuthority?.(); if (e.ctxPayload.SessionTranscriptContext) { const { mergeSessionTranscriptContext: t } = await import("./session-transcript-context.runtime.js"); await t({ agentId: n, ctx: e.ctxPayload, sessionKey: r, storePath: e.storePath }); } emitStage("record", "start"); e.assertAuthority?.(); await e.recordInboundSession({ storePath: e.storePath, sessionKey: r, ctx: e.ctxPayload, groupResolution: e.record?.groupResolution, createIfMissing: e.record?.createIfMissing, updateLastRoute: e.record?.updateLastRoute, onRecordError: e.record?.onRecordError ?? (() => void 0), trackSessionMetaTask: e.record?.trackSessionMetaTask, assertAuthority: e.assertAuthority }); emitStage("record", "done"); await e.afterRecord?.(); await deliverPendingDeliveryNotice(r, e.storePath, n); } catch (t) { emitStage("record", "error", t); try { await e.onPreDispatchFailure?.(t); } catch {} throw t; } emitStage("dispatch", "start"); let i; try { e.assertAuthority?.(); let r; if (n.kind === "observeOnly") { if (t.suppressObserveOnlyDispatch) await e.runDispatchLifecycle?.onDispatchSkipped("observeOnly"); else await e.runDispatch(); i = e.observeOnlyDispatchResult ?? { queuedFinal: false, counts: EMPTY_CHANNEL_TURN_DISPATCH_COUNTS }; } else ({result: i, processedOutcome: r} = await withDispatchProcessedOutcomeSink(() => e.runDispatch())); function maybeWarnZeroCountVisibleDispatch() { if (n.kind === "observeOnly" || e.ctxPayload.InternalTurnSource !== void 0) return; const t = i; if (t?.deferredToActiveRun) return; if (hasVisibleChannelTurnDispatch(t)) return; const a = r ? `${r.outcome}${r.reason ? `:${r.reason}` : ""}` : void 0; log.warn(`visible channel turn dispatched with no queued reply payloads: channel=${e.channel} messageId=${e.messageId ?? "unknown"} sessionKey=${e.ctxPayload.SessionKey ?? e.routeSessionKey} cause=${a ?? "unknown"}`); emit(e, { stage: "dispatch", event: "warning", admission: n.kind, reason: "zero-count-visible-dispatch" }); } maybeWarnZeroCountVisibleDispatch(); } catch (e) { emitStage("dispatch", "error", e); throw e; } emitStage("dispatch", "done"); return { admission: n, dispatched: true, ctxPayload: e.ctxPayload, routeSessionKey: e.routeSessionKey, dispatchResult: i }; } finally { clearPendingHistoryAfterTurn(e.history); } }); } async function runPreparedChannelTurn(e) { return await runPreparedChannelTurnCore(e, { suppressObserveOnlyDispatch: true }); } //#endregion export { createDirectPendingFinalCustody as a, hasFinalChannelTurnDispatch as c, recordChannelBotPairLoopAndCheckSuppression as d, PendingFinalDeliveryNotOwnedError as i, hasVisibleChannelTurnDispatch as l, runPreparedChannelTurnCore as n, resolvePendingFinalCompletion as o, NO_PENDING_FINAL_CUSTODY as r, toCoreManagedDeliveryInfo as s, runPreparedChannelTurn as t, resolveChannelTurnDispatchCounts as u };