UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

176 lines (175 loc) • 7.46 kB
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { a as resolveDeliveryQueueAttemptCount } from "./delivery-queue-sqlite.types-B7uW265Q.mjs"; import { r as PlatformMessageNotDispatchedError } from "./deliver-types-BnSKrpHG.mjs"; import { n as resolveOutboundChannelMessageAdapter } from "./channel-resolution-DjtSMYUG.mjs"; import { t as hasActiveDeliveryOwner } from "./delivery-queue-types-CVbI1W4D.mjs"; //#region src/infra/outbound/deliver-handoff.ts var OutboundHandoffRejectedError = class extends PlatformMessageNotDispatchedError { constructor(e) { super(formatErrorMessage(e), { cause: e, retryable: false }); } }; /** Finds an exact rejected host handoff through delivery wrappers. */ function findOutboundHandoffRejectedError(e) { const t = /* @__PURE__ */ new Set(); let n = e; while (n && typeof n === "object" && !t.has(n)) { if (n instanceof OutboundHandoffRejectedError) return n; t.add(n); n = "cause" in n ? n.cause : void 0; } } /** Call only while the current preparation or handoff is proven not dispatched. */ function assertOutboundHandoffCurrent(e) { try { e?.(); } catch (e) { if (e instanceof PlatformMessageNotDispatchedError && e.retryable) throw e; throw new OutboundHandoffRejectedError(e); } } //#endregion //#region src/infra/outbound/delivery-commit-hooks.ts const log = createSubsystemLogger("outbound/deliver"); const outboundDeliveryCommitHooks = /* @__PURE__ */ new WeakMap(); /** Attaches an after-commit hook without changing the delivery result shape. */ function attachOutboundDeliveryCommitHook(e, t) { if (t) { const n = outboundDeliveryCommitHooks.get(e) ?? []; n.push(t); outboundDeliveryCommitHooks.set(e, n); } return e; } /** Runs after-commit hooks for delivered results while isolating hook failures. */ async function runOutboundDeliveryCommitHooks(e) { for (const t of e) for (const e of outboundDeliveryCommitHooks.get(t) ?? []) try { await e(); } catch (e) { log.warn("Plugin message adapter after-commit hook failed.", { channel: t.channel, messageId: t.messageId, error: formatErrorMessage(e) }); } } /** Type guard for batched outbound delivery results crossing loose boundaries. */ function isOutboundDeliveryResultArray(e) { return Array.isArray(e); } //#endregion //#region src/infra/outbound/delivery-queue-recovery-policy.ts const DEFAULT_MAX_RETRIES = 5; const TEXT_FINAL_FIELDS = { text: true, replyToId: true, replyToTag: true, replyToCurrent: true }; function isOrdinaryFinalText(e, t) { const n = e[0]; return e.length === 1 && n !== void 0 && Boolean(n.text?.trim()) && Object.entries(n).every(([e, r]) => r === void 0 || Object.hasOwn(TEXT_FINAL_FIELDS, e) || e === "channelData" && n.channelData !== void 0 && t?.(n.channelData) === true); } /** * The one rule for unconfirmed sends no adapter can reconcile: an ordinary agent final text is * resent once, accepting a rare duplicate over a lost reply. A crash mid-send leaves * `send_attempt_started`; a live ambiguous transport failure is typed. Other post-send evidence * (accepted chunks, untyped failures) never qualifies, and an adapter's `not_sent` verdict keeps * its own replay rule. */ function canReplayAmbiguousFinalText(e, t) { return e.retryAmbiguousFinalText === true && t?.status !== "not_sent" && (e.ambiguousTransportError === true || e.recoveryState === "send_attempt_started") && resolveDeliveryQueueAttemptCount(e) < Math.min(2, resolveMaxRetries(e)); } function resolveUnknownSendReplay(e, t) { if (t?.status === "not_sent" && e.recoveryState === "send_attempt_started") return "proven"; return canReplayAmbiguousFinalText(e, t) ? "blind" : void 0; } function shouldInspectQueuedDelivery(e, t) { return Boolean(e.settlement) || !hasActiveDeliveryOwner(e, t); } /** Resolves the platform attempt identity a recovered delivery must reconcile against. */ function recoveryPlatformAttemptId(e, t) { return t !== void 0 ? t : typeof e.platformSendAttemptId === "string" ? e.platformSendAttemptId : e.recoveryState === "producer_claimed" && typeof e.producerClaimId === "string" ? e.producerClaimId : typeof e.completionRetention === "object" || e.requiresProducerClaim === true ? null : void 0; } const PERMANENT_ERROR_PATTERNS = [ /no conversation reference found/i, /chat not found/i, /user not found/i, /bot.*not.*member/i, /bot was blocked by the user/i, /forbidden: bot was kicked/i, /chat_id is empty/i, /recipient is not a valid/i, /ambiguous .* recipient/i, /User .* not in room/i ]; function resolveMaxRetries(e) { const t = e.maxRetries; return typeof t === "number" && Number.isInteger(t) && t > 0 ? t : DEFAULT_MAX_RETRIES; } function isPermanentDeliveryError(e) { return PERMANENT_ERROR_PATTERNS.some((t) => t.test(e)); } //#endregion //#region src/infra/outbound/delivery-queue-reconciliation.ts function buildReconciledSentResult(e, t) { return { channel: e.channel, messageId: t.messageId ?? t.receipt.primaryPlatformMessageId ?? t.receipt.platformMessageIds[0] ?? "", receipt: t.receipt }; } function needsUnknownSendReconciliation(e) { return e.recoveryState === "send_attempt_started" || e.recoveryState === "unknown_after_send"; } function buildUnknownSendContext(e) { const { entry: t } = e; return { cfg: e.cfg, queueId: t.id, channel: t.channel, to: t.to, ...t.accountId !== void 0 ? { accountId: t.accountId } : {}, enqueuedAt: t.enqueuedAt, retryCount: t.retryCount, ...t.platformSendStartedAt !== void 0 ? { platformSendStartedAt: t.platformSendStartedAt } : {}, ...t.effectiveReplyToId !== void 0 ? { effectiveReplyToId: t.effectiveReplyToId } : {}, payloads: e.payloads, ...t.renderedBatchPlan ? { renderedBatchPlan: t.renderedBatchPlan } : {}, ...t.reply ? { replyToId: t.reply.replyToId } : {}, ...t.reply?.source === "implicit" ? { replyToMode: t.reply.mode } : {}, ...t.threadId !== void 0 ? { threadId: t.threadId } : {}, ...t.silent !== void 0 ? { silent: t.silent } : {} }; } /** Reconciles provider state without applying or rediscovering outbound policy. */ async function reconcileUnknownQueuedDelivery(e) { const t = await resolveOutboundChannelMessageAdapter({ channel: e.entry.channel, cfg: e.cfg, agentId: e.entry.session?.agentId, allowBootstrap: true, assertCurrent: e.assertCurrent }); e.assertCurrent?.(); const n = t?.durableFinal?.capabilities?.reconcileUnknownSend === true ? t.durableFinal.reconcileUnknownSend : void 0; if (!n) return null; const { entry: r } = e; try { return await n(buildUnknownSendContext(e)); } catch (t) { const n = formatErrorMessage(t); e.warn(`Delivery entry ${r.id} unknown-send reconciliation failed: ${n}`); return { status: "unresolved", error: n, retryable: !isPermanentDeliveryError(n) }; } } //#endregion export { findOutboundHandoffRejectedError as _, canReplayAmbiguousFinalText as a, recoveryPlatformAttemptId as c, shouldInspectQueuedDelivery as d, attachOutboundDeliveryCommitHook as f, assertOutboundHandoffCurrent as g, OutboundHandoffRejectedError as h, reconcileUnknownQueuedDelivery as i, resolveMaxRetries as l, runOutboundDeliveryCommitHooks as m, buildUnknownSendContext as n, isOrdinaryFinalText as o, isOutboundDeliveryResultArray as p, needsUnknownSendReconciliation as r, isPermanentDeliveryError as s, buildReconciledSentResult as t, resolveUnknownSendReplay as u };