UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

466 lines (465 loc) • 17 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { a as pluginInstanceInvocation } from "./plugin-instance-invocation-Bq_toGDw.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { _ as wrapCurrentPluginInstance, l as getPluginValueInstance } from "./plugin-instance-scope-oezVdCr2.mjs"; import { o as copyReplyPayloadMetadata } from "./reply-payload-k5WsQWxi.mjs"; import { a as copyChannelParticipantAdmissionEvidence } from "./admission-evidence-q4_t-NFq.mjs"; import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs"; import { s as getGroupThreadDispatchContext } from "./group-thread-context-DFimpu_J.mjs"; import { c as isPlatformMessageNotDispatchedError, l as isPlatformMessageRejectedError } from "./deliver-types-BnSKrpHG.mjs"; import { d as summarizeOutboundPayloadForTransport, r as createStructuredOutboundPayloadPlan } from "./payloads-CQvywZOF.mjs"; import { i as resolveMessageReceiptPrimaryId } from "./receipt-D4ZtbK66.mjs"; import { o as settlePendingFinalDelivery } from "./delivery-completion-DkLj6KUt.mjs"; import { f as settleReplyPendingFinalDelivery, p as suppressPendingFinalDelivery } from "./reply-dispatcher-DVZA5pVi.mjs"; import { a as isReplyDispatchDeliveryPending } from "./reply-dispatch-outcome-C1yqMjJt.mjs"; import { t as applyMessageSendingHook } from "./deliver-hooks-B6z0_4Yo.mjs"; import { n as deriveInboundMessageHookContext, r as resolveInboundReplyHookTarget } from "./message-hook-mappers-BCrhfgqk.mjs"; import { a as normalizeEmptyPayloadForDelivery } from "./deliver-payload-CXD-N8EQ.mjs"; import { n as observeAgentRunStart } from "./agent-run-start-Cf0O0aGQ.mjs"; import { a as dispatchInboundMessageWithRoutedChannelDispatcher } from "./dispatch-vEUtrodM.mjs"; import { n as withReplySystemEventContext } from "./system-event-session-key-Bh1cHqR9.mjs"; import { t as recordInboundSession } from "./session-DoRia6Kc.mjs"; import { u as createMessageSentEmitter } from "./delivery-queue-recovery-Cwouxa5a.mjs"; import { f as isChannelPartialDeliveryError, u as createSuppressedChannelDeliveryResult } from "./live-DOXDs-ke.mjs"; import { r as runWithSessionInitConflictRetry } from "./session-init-conflict-retry-CV_TC3PH.mjs"; import { i as throwIfDurableInboundReplyDeliveryFailed, n as deliverStructuredInboundReplyWithMessageSendContextCore, r as isDurableInboundReplyDeliveryHandled, t as deliverInboundReplyWithMessageSendContextCore } from "./durable-delivery-w3MeWAQt.mjs"; import { a as createDirectPendingFinalCustody, i as PendingFinalDeliveryNotOwnedError, n as runPreparedChannelTurnCore, o as resolvePendingFinalCompletion, r as NO_PENDING_FINAL_CUSTODY, s as toCoreManagedDeliveryInfo } from "./execution-CaU-Nl7N.mjs"; import { t as createChannelReplyPipeline } from "./reply-pipeline-BLDOfhMa.mjs"; //#region src/channels/turn/delivery-owner.ts function bindChannelDeliveryOwner(e) { const t = getPluginValueInstance(e); return t && t === pluginInstanceInvocation.getStore()?.instance ? e : wrapCurrentPluginInstance(e); } //#endregion //#region src/channels/turn/lifecycle.ts function assembleResolvedChannelTurn(e) { if (!("route" in e)) return e; const { cfg: t, route: n, ...r } = e; let i = e.ctxPayload; if (n.dmScope && i.DmScope !== n.dmScope) { i = { ...i, DmScope: n.dmScope }; copyChannelParticipantAdmissionEvidence(e.ctxPayload, i); } const a = { ctxPayload: i, routeSessionKey: n.sessionKey, storePath: resolveSessionStorePathCore(t.session?.store, { agentId: n.agentId }), recordInboundSession }; if ("runDispatch" in r) return { ...r, ...a }; return { ...r, ...a, cfg: t, agentId: n.agentId }; } function resolveAssembledReplyPipeline(e) { const t = e.turnAdoptionLifecycle ?? e.replyOptions?.turnAdoptionLifecycle; let n = t ? { ...e.replyOptions, turnAdoptionLifecycle: t } : e.replyOptions; if (e.routeSessionKey !== e.ctxPayload.SessionKey) n = withReplySystemEventContext(n ?? {}, { sessionKey: e.routeSessionKey }); if (!e.replyPipeline) return { dispatcherOptions: e.dispatcherOptions, replyOptions: n }; const { onModelSelected: r, ...i } = createChannelReplyPipeline({ cfg: e.cfg, agentId: e.agentId, channel: e.channel, accountId: e.accountId, ...e.replyPipeline }); return { dispatcherOptions: { ...i, ...e.dispatcherOptions }, replyOptions: { onModelSelected: r, ...n } }; } function markChannelDeliveryErrorVisible(e) { if (isRecord(e)) try { Object.assign(e, { sentBeforeError: true, visibleReplySent: true }); return e; } catch {} const t = new Error("visible channel reply delivery failed", { cause: e }); Object.assign(t, { sentBeforeError: true, visibleReplySent: true }); return t; } async function runChannelDeliveryObserver(e) { if (!e.onDelivered || isReplyDispatchDeliveryPending(e.result)) return; try { await e.onDelivered(e.payload, e.info, e.result); } catch (t) { throw e.result?.visibleReplySent === false ? t : markChannelDeliveryErrorVisible(t); } } function resolveChannelDeliveryMessageId(e) { return e?.receipt ? resolveMessageReceiptPrimaryId(e.receipt) : e?.messageIds?.find((e) => e.trim()); } async function settleChannelDeliveryAttempts(e, t) { let n; for (const r of e) try { await settleChannelDeliveryAttempt(r, t.onDelivered, (e) => t.onError?.(e, r.info)); } catch (e) { if (n === void 0 || isChannelPartialDeliveryError(e) && !isChannelPartialDeliveryError(n)) n = e; } if (n !== void 0) throw toErrorObject(n, "channel delivery settlement failed"); } async function settleFailedPendingFinalDelivery(e, t) { const n = resolvePendingFinalCompletion(e); if (!n) return; if (isPlatformMessageRejectedError(t)) await settlePendingFinalDelivery(n, "suppressed", [ "prepared", "queued", "unknown" ]); else if (isPlatformMessageNotDispatchedError(t)) await settlePendingFinalDelivery(n, "prepared", ["queued", "unknown"]); else await settlePendingFinalDelivery(n, "unknown", ["queued", "unknown"]); } function emitChannelDeliveryFailure(e, t, n) { const r = isChannelPartialDeliveryError(t) ? t.deliveryResult : void 0; if (!isPlatformMessageNotDispatchedError(t)) n?.({ success: false, content: r?.content ?? e.text ?? "", error: formatErrorMessage(t), messageId: resolveChannelDeliveryMessageId(r) }); } async function settleChannelDeliveryAttempt(e, t, n) { try { let r; try { r = e.result || void 0; if (r?.finalization) r = { ...r, ...await r.finalization, finalization: void 0 }; } catch (t) { if (t instanceof PendingFinalDeliveryNotOwnedError) return; try { await n?.(t); } catch {} await settleFailedPendingFinalDelivery(e.payload, t); emitChannelDeliveryFailure(e.payload, t, e.emitMessageSent); throw toErrorObject(t, "channel delivery finalization failed"); } const i = isReplyDispatchDeliveryPending(r); if (!i && r?.visibleReplySent !== false) e.emitMessageSent?.({ success: true, content: r?.content ?? e.payload.text ?? "", messageId: resolveChannelDeliveryMessageId(r) }); await settleReplyPendingFinalDelivery(e.payload, i ? "unknown" : r?.visibleReplySent === false ? "suppressed" : "delivered"); await runChannelDeliveryObserver({ onDelivered: t, payload: e.payload, info: e.info, result: r }); } finally { e.releaseCustody?.(); } } async function applyRoutedDirectMessageSending(e) { const t = getGlobalHookRunner(); const n = deriveInboundMessageHookContext(e.turn.ctxPayload); const r = await applyMessageSendingHook({ hookRunner: t, enabled: t?.hasHooks("message_sending") ?? false, payload: e.payload, payloadSummary: summarizeOutboundPayloadForTransport(e.payload), to: resolveInboundReplyHookTarget(e.turn.ctxPayload, n), channel: e.turn.channel, accountId: e.turn.accountId, replyToId: e.payload.replyToId ?? e.turn.ctxPayload.ReplyToIdFull ?? e.turn.ctxPayload.ReplyToId, threadId: e.turn.ctxPayload.MessageThreadId, sessionKey: e.turn.routeSessionKey }); if (r.cancelled) return { payload: e.payload, suppression: createSuppressedChannelDeliveryResult({ reason: "cancelled_by_message_sending_hook", cancelReason: r.hookEffect?.cancelReason, metadata: r.hookEffect?.metadata }) }; const i = normalizeEmptyPayloadForDelivery(r.payload); if (!i) return { payload: r.payload, suppression: createSuppressedChannelDeliveryResult({ reason: r.changed ? "empty_after_message_sending_hook" : "no_visible_payload" }) }; return { payload: copyReplyPayloadMetadata(e.payload, i) }; } async function dispatchChannelTurnWithDeliveryOwner(...e) { const [t, n] = e; const r = resolveAssembledReplyPipeline(t); const i = t.turnAdoptionLifecycle ?? t.replyOptions?.turnAdoptionLifecycle; const a = t.admission?.kind === "observeOnly" ? { deliver: async () => ({ visibleReplySent: false }) } : bindChannelDeliveryOwner(t.delivery); const o = []; const s = []; let c = []; const l = { ...r.replyOptions, assertChannelAuthority: t.assertAuthority, ...observeAgentRunStart(r.replyOptions, (e) => { c = [e.runId, e.executionIdentityToken]; }) }; const u = a.observeMessageSent ? deriveInboundMessageHookContext(t.ctxPayload) : void 0; let d; const getMessageSentEmitter = () => { if (!a.observeMessageSent || !u) return; const e = getGroupThreadDispatchContext(); if (!e && d) return d; const n = createMessageSentEmitter({ hookRunner: getGlobalHookRunner(), channel: t.channel, to: resolveInboundReplyHookTarget(t.ctxPayload, u), accountId: t.accountId, sessionKeyForInternalHooks: e?.ctx.SessionKey ?? t.routeSessionKey, runId: e ? e.runState.runId : c[0], isGroup: u.isGroup, groupId: u.groupId, logPrefix: "dispatchAssembledChannelTurn" }); if (!e) d = n; return n; }; const suppressReply = async (e, t, n) => { const r = createSuppressedChannelDeliveryResult({ reason: n }); await suppressPendingFinalDelivery(e); await runChannelDeliveryObserver({ onDelivered: a.onDelivered, payload: e, info: t, result: r }); return r; }; const onReplySuppressed = async (e, t, n) => { await suppressReply(e, t, n); }; const f = a.deliver?.bind(a); const p = "deliverWithProviderMessageSending" in a ? a.deliverWithProviderMessageSending?.bind(a) : void 0; const m = a.deliverPrepared?.bind(a); const h = "deliverPreparedWithProviderMessageSending" in a ? a.deliverPreparedWithProviderMessageSending?.bind(a) : void 0; const g = { prepare: (e) => ({ payload: e }), deliver: f ? (e, t) => f(e.payload, t) : void 0, deliverWithProviderMessageSending: p ? (e, t) => p(e.payload, t) : void 0, deliverDurable: (e, t) => deliverInboundReplyWithMessageSendContextCore({ ...t, payload: e.payload }) }; async function deliverReply(e, r, i) { const s = a.preparePayload ? await a.preparePayload(e, r) : e; const l = s === null ? null : i.prepare(copyReplyPayloadMetadata(e, s)); if (l === null) return await suppressReply(e, r, "no_visible_payload"); const u = l.payload; const d = "durable" in a ? a.durable : void 0; const f = typeof d === "function" ? await d(u, r) : d; if (f) { const e = await i.deliverDurable(l, { cfg: t.cfg, channel: t.channel, accountId: t.accountId, agentId: t.agentId, ctxPayload: t.ctxPayload, info: r, executionIdentityToken: c[1], ...f }); if (e.status === "failed" && isPlatformMessageNotDispatchedError(e.error)) await settleFailedPendingFinalDelivery(u, e.error); throwIfDurableInboundReplyDeliveryFailed(e); if (isDurableInboundReplyDeliveryHandled(e)) { await runChannelDeliveryObserver({ onDelivered: a.onDelivered, payload: u, info: r, result: e.delivery }); return e.delivery; } } let p = l; let m = u; let h = void 0; let g = r; let _; const v = a.observeMessageSent ? getGroupThreadDispatchContext() ? getMessageSentEmitter()?.emitMessageSent : (e) => getMessageSentEmitter()?.emitMessageSent(e) : void 0; try { if (n === "routed-delivery" && i.deliverWithProviderMessageSending) { const e = await createDirectPendingFinalCustody(m, t.storePath); _ = e?.release; const n = { ...r, ...e ?? NO_PENDING_FINAL_CUSTODY }; g = n; h = await i.deliverWithProviderMessageSending(p, n); } else { if (n === "routed-delivery" && t.admission?.kind !== "observeOnly") { const e = await applyRoutedDirectMessageSending({ turn: t, payload: m }); m = e.payload; if (e.suppression) h = e.suppression; else { const e = i.prepare(m); if (e) { p = e; m = e.payload; } else h = createSuppressedChannelDeliveryResult({ reason: "no_visible_payload" }); } } if (!h) { if (!i.deliver) throw new Error("channel delivery adapter is missing a direct deliverer"); const e = await createDirectPendingFinalCustody(m, t.storePath); _ = e?.release; await e?.onPlatformSendDispatch(); h = await i.deliver(p, toCoreManagedDeliveryInfo(r, m)); } } } catch (e) { try { if (e instanceof PendingFinalDeliveryNotOwnedError) return { visibleReplySent: false }; await settleFailedPendingFinalDelivery(m, e); if (a.observeMessageSent) emitChannelDeliveryFailure(m, e, v); throw e; } finally { _?.(); } } const y = { payload: m, info: g, result: h, releaseCustody: _, emitMessageSent: v }; if (h?.finalization) { h.finalization.catch(() => void 0); o.push(y); } else await settleChannelDeliveryAttempt(y, a.onDelivered); return h; } const deliverPrepared = (e, t) => deliverReply(e.payload, t, { prepare: (t) => { const [n] = createStructuredOutboundPayloadPlan([t]); return n ? { ...n, sourceIndex: e.sourceIndex } : null; }, deliver: m ?? g.deliver, deliverWithProviderMessageSending: h ?? g.deliverWithProviderMessageSending, deliverDurable: (e, t) => deliverStructuredInboundReplyWithMessageSendContextCore({ ...t, plan: e }) }); return await runPreparedChannelTurnCore({ channel: t.channel, accountId: t.accountId, routeSessionKey: t.routeSessionKey, storePath: t.storePath, ctxPayload: t.ctxPayload, recordInboundSession: t.recordInboundSession, assertAuthority: t.assertAuthority, afterRecord: t.afterRecord, record: t.record, history: t.history, admission: t.admission, botLoopProtection: t.botLoopProtection, outboundEchoSourceId: t.outboundEchoSourceId, log: t.log, messageId: t.messageId, ...i ? { runDispatchLifecycle: { turnAdoptionLifecycle: i, onDispatchSkipped: async () => await i.onAdopted() } } : {}, runDispatch: async () => { let e; let i; try { e = await runWithSessionInitConflictRetry(() => (n === "routed-delivery" ? dispatchInboundMessageWithRoutedChannelDispatcher : t.dispatchReplyWithBufferedBlockDispatcher)({ ctx: t.ctxPayload, cfg: t.cfg, ...n === "routed-delivery" ? { ...t.admission?.kind === "observeOnly" ? { suppressOutboundHooks: true } : {}, onReplyPayloadSuppressed: onReplySuppressed } : {}, dispatcherOptions: { ...r.dispatcherOptions, pendingFinalDeliveryAdmission: "deliver", onSkip: (e, t) => { r.dispatcherOptions?.onSkip?.(e, t); if (t.reason !== "channel_transform") return; const { reason: n, ...i } = t; s.push({ payload: e, info: i, result: createSuppressedChannelDeliveryResult({ reason: t.reason }) }); }, deliver: (e, t) => deliverReply(e, t, g), deliverPrepared, onError: a.onError }, dispatchReplyFromConfig: t.dispatchReplyFromConfig, toolsAllow: t.toolsAllow, replyOptions: l, replyResolver: t.replyResolver }), t.sessionInitRetry ? { retryDelaysMs: t.sessionInitRetry.delaysMs, signal: t.sessionInitRetry.signal, sleep: t.sessionInitRetry.sleep } : void 0); } catch (e) { i = e; } let c; try { await settleChannelDeliveryAttempts([...s, ...o], a); } catch (e) { c = e; } if (c !== void 0 && isChannelPartialDeliveryError(c)) throw toErrorObject(c, "channel delivery settlement failed"); if (i !== void 0) throw toErrorObject(i, "channel dispatch failed"); if (c !== void 0) throw toErrorObject(c, "channel delivery settlement failed"); return e; } }, { suppressObserveOnlyDispatch: false }); } async function dispatchAssembledChannelTurn(e) { return await dispatchChannelTurnWithDeliveryOwner(e, "legacy-dispatcher"); } async function dispatchRoutedChannelTurn(e) { return await dispatchChannelTurnWithDeliveryOwner(assembleResolvedChannelTurn(e), "routed-delivery"); } //#endregion export { dispatchAssembledChannelTurn as n, dispatchRoutedChannelTurn as r, assembleResolvedChannelTurn as t };