UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,402 lines • 53.6 kB
import { i as collectNestedErrorCandidates } from "./error-coercion-hDrHOSGy.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { o as emitInternalDiagnosticEvent } from "./diagnostic-events-BjAH1Kbx.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs";
import { i as getOrCreatePromise } from "./lazy-promise-DiCvjz9w.mjs";
import { w as readAskUserQuestionId } from "./reply-payload-k5WsQWxi.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { a as runWithQuestionChannelDeliveries } from "./question-channel-runtime-9JTnl8rq.mjs";
import { r as normalizeOutboundReplyFacts, t as createReplyToDeliveryPolicy } from "./reply-policy-h9jv5pGH.mjs";
import { t as diagnosticErrorCategory } from "./diagnostic-error-metadata-Cc4dyoSL.mjs";
import { i as areOutboundPayloadsIntentionallySuppressed, n as OutboundDeliveryError, o as isOutboundDeliveryAdmissionClosedError, r as PlatformMessageNotDispatchedError } from "./deliver-types-BnSKrpHG.mjs";
import { l as isProvenDeliveryNotSentError, o as isAmbiguousDeliveryTransportError, s as isDeliveryRecoveryOwnedRetry } from "./delivery-recovery.shared-3Nb7FEaL.mjs";
import { d as summarizeOutboundPayloadForTransport } from "./payloads-CQvywZOF.mjs";
import { o as resolveReceiptSourceId } from "./receipt-D4ZtbK66.mjs";
import { t as captureDeliveryQueueStateContext } from "./delivery-queue-state-context-Cxp-xMAQ.mjs";
import "./delivery-queue-sqlite-lyIJZlO0.mjs";
import { a as settleDurableDelivery, i as resolveConversationDeliveryScope, r as markDurableDeliveryQueued, s as createDeliveryPlacementEvidenceRecorder } from "./delivery-completion-DkLj6KUt.mjs";
import { a as normalizeEmptyPayloadForDelivery, c as resolveChannelHandlerParams, i as maybePinDeliveredMessage, l as resolveOutboundMediaAccessForSend, n as deliveryKindForPayload, r as maybeNotifyAfterDeliveredPayload, t as collectPayloadMediaSources, u as stripInternalRuntimeScaffoldingFromPayload } from "./deliver-payload-CXD-N8EQ.mjs";
import { i as prepareSessionWriterDeliveryAuthority, t as assertSessionWriterDeliveryAuthorized } from "./session-writer-delivery-authority-DNB-b5xs.mjs";
import { c as resolveTextChunkLimit, i as chunkMarkdownTextWithMode, n as chunkByParagraph, s as resolveChunkMode } from "./chunk-D9JRZpRm.mjs";
import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs";
import { i as resolveOutboundChannelPluginAsync, n as resolveOutboundChannelMessageAdapter } from "./channel-resolution-DjtSMYUG.mjs";
import { n as deriveDurableFinalDeliveryRequirementsForBatch, r as payloadRequiresDurablePayloadTransport } from "./capabilities-Cm5mmzL6.mjs";
import { g as assertOutboundHandoffCurrent, m as runOutboundDeliveryCommitHooks, o as isOrdinaryFinalText } from "./delivery-queue-reconciliation-CQDy7zg8.mjs";
import { a as createRenderedMessageBatchPlan, n as prepareStructuredOutboundPayloadBatch, o as createChannelHandler, r as throwIfAborted, s as resolveOutboundDurableFinalDeliverySupport, t as prepareOutboundPayloadBatch } from "./deliver-prepare-D0EzlldE.mjs";
import { _ as persistQueuedPreSendState, a as completedOutboundAuditTerminals, b as OUTBOUND_DELIVERY_LOG_SCOPE, c as failedOutboundAuditTerminals, d as createOutboundMessageSentEmitter, f as prepareOutboundDeliveryGeneration, g as persistQueuedPostSendState, h as isProvenBatchNotSent, i as withActiveDeliveryClaim, l as uniformOutboundAuditTerminals, m as findTerminalBatchRejection, n as recoverLiveFinalDelivery, o as emitOutboundAuditLifecycle, p as createQueuedDeliveryOwner, s as emitOutboundAuditTerminals, u as createMessageSentEmitter, v as rejectQueuedDelivery, x as prepareDeferredDeliveryAdmission, y as commitConfirmedVisibleMessage } from "./delivery-queue-recovery-Cwouxa5a.mjs";
import { a as acceptedPreparedOutboundEntries, c as mapPreparedOutboundAcceptedPayloads, i as projectQueuedDeliveryOptions, l as preparedOutboundPayloads, u as preparedOutboundSuppressionOutcomes } from "./delivery-queue-projection-BhmCxxmH.mjs";
import { a as resolveOutboundMediaMaxBytes } from "./configured-max-bytes-lKIaFMol.mjs";
import { r as createInitialDeliveryProducerClaim, t as PLATFORM_SEND_OWNER_LEASE_MS } from "./delivery-queue-sqlite-claim.kernel-D74In62c.mjs";
import { i as cancelDeliveryQueueMediaRetention, n as releaseSpoolArtifacts, r as stageQueuePayloadMedia } from "./delivery-queue-media-spool-ys6bmM17.mjs";
import { C as claimReusableDeliveryPlatformSendAttempt, E as withStableDeliveryPreparation, T as StableDeliveryPreparationLostError, _ as markDeliveryPlatformSendDispatched, a as failDeliveryAfterPlatformSend, c as findDeliveryIntentOwner, i as failDelivery, n as enqueueDeliveryOnce, o as failDeliveryBeforePlatformSend, r as enqueuePreparedDeliveryOnce, t as enqueueDelivery, u as loadPendingDelivery, w as renewDeliveryPlatformSendLease, y as reserveDeliveryAttempt } from "./delivery-queue-storage-BLAjpQqf.mjs";
import { t as renderPresentationForDelivery } from "./presentation-delivery-5KftDvIO.mjs";
import { randomUUID } from "node:crypto";
//#region src/infra/outbound/deliver-queue-admission.ts
function restoreQueuedDeliveryCustody(e, t) {
	const { id: n, enqueuedAt: r, retryCount: i, attemptCount: a, requiresProducerClaim: o, availableAt: s, producerClaimId: c, lastAttemptAt: l, lastError: u, platformSendAttemptId: d, platformSendStartedAt: f, effectiveReplyToId: p, recoveryState: m, maxRetries: h, legacyUnknownSendReconciliation: g, legacyPreparedContentUnavailable: _, ...v } = t;
	const y = e.conversationDeliveryTarget;
	const b = v.deliveryCompletion;
	if (y) {
		if (b?.kind !== "conversation") throw new Error("Conversation delivery target does not match durable custody");
		resolveConversationDeliveryScope(b, e.deliveryQueueStateDir, e.deliveryQueueStateContext, y);
	}
	const x = preparedOutboundPayloads(v.preparedBatch);
	return {
		...e,
		...v,
		payloads: x,
		sessionGeneration: t.sessionGeneration
	};
}
/** Stages producer-owned media and atomically admits one durable outbound intent. */
async function stageAndEnqueueOutboundDelivery(e, t, n) {
	const { channel: r, to: i } = e;
	const a = e.deliveryQueueStateDir;
	const o = e.queuePolicy ?? "best_effort";
	const s = acceptedPreparedOutboundEntries(t).map((e) => stripInternalRuntimeScaffoldingFromPayload(e.payload));
	const c = e.renderedBatchPlan ?? createRenderedMessageBatchPlan(s);
	if (e.deliveryIntentId && e.reusePendingDeliveryIntent) {
		const t = await loadPendingDelivery(e.deliveryIntentId, a, e.deliveryQueueStateContext);
		if (t) return {
			id: t.id,
			created: false
		};
	}
	const l = await stageQueuePayloadMedia({
		stateDir: a,
		payloads: s,
		...e.deliveryCompletion?.kind === "pending-final" && e.deliveryCompletion.commandOwnerReference !== void 0 ? { artifactFormat: "command-owner-v1" } : e.sessionGeneration ? { artifactFormat: "session-generation-v1" } : {},
		mediaAccess: resolveOutboundMediaAccessForSend(e, collectPayloadMediaSources(s)),
		maxBytes: resolveOutboundMediaMaxBytes({
			cfg: e.cfg,
			channel: r,
			accountId: e.accountId
		})
	}, e.deliveryQueueStateContext);
	if (l.status !== "staged") {
		if (o === "required") throw new Error(`Required durable message send is unsupported for ${r}: ${l.reason} cannot be persisted`);
		return null;
	}
	try {
		const s = n?.claimForLiveDelivery ? createInitialDeliveryProducerClaim() : void 0;
		const u = mapPreparedOutboundAcceptedPayloads(t, l.payloads);
		const d = {
			...projectQueuedDeliveryOptions(e),
			channel: r,
			to: i,
			queuePolicy: o,
			requireUnknownSendReconciliation: e.requireUnknownSendReconciliation,
			retryAmbiguousFinalText: e.retryAmbiguousFinalText,
			...e.reusePendingDeliveryIntent ? { requiresProducerClaim: true } : {},
			...s ? { initialProducerClaim: s } : {},
			preparedBatch: u,
			renderedBatchPlan: c,
			reply: normalizeOutboundReplyFacts(e),
			sessionGeneration: e.sessionGeneration,
			completionRetention: e.completionRetention,
			maxRetries: e.maxRetries,
			deliveryCompletion: e.deliveryCompletion
		};
		if (e.deliveryIntentId) {
			const t = await n?.getStablePreparation?.();
			const r = t ? await enqueuePreparedDeliveryOnce(d, e.deliveryIntentId, t, a, l.mediaStageId, e.deliveryQueueStateContext) : await enqueueDeliveryOnce(d, e.deliveryIntentId, a, l.mediaStageId, e.deliveryQueueStateContext);
			if (!r.created) {
				await cancelDeliveryQueueMediaRetention(l.mediaStageId, a, e.deliveryQueueStateContext);
				await releaseSpoolArtifacts(l.artifacts, a);
			}
			return {
				...r,
				...r.created && s ? { producerClaimId: s.producerClaimId } : {}
			};
		}
		return {
			id: await enqueueDelivery(d, a, l.mediaStageId, e.deliveryQueueStateContext),
			created: true,
			...s ? { producerClaimId: s.producerClaimId } : {}
		};
	} catch (t) {
		if (isDeliveryRecoveryOwnedRetry(t)) throw t;
		const n = [t];
		try {
			await cancelDeliveryQueueMediaRetention(l.mediaStageId, a, e.deliveryQueueStateContext);
		} catch (e) {
			n.push(e);
		}
		try {
			await releaseSpoolArtifacts(l.artifacts, a);
		} catch (e) {
			n.push(e);
		}
		throwSqliteLifecycleErrors(n, "Delivery queue admission and media cleanup failed");
		throw t;
	}
}
//#endregion
//#region src/infra/outbound/message-plan.ts
function assertStableMediaFanout(e, t, n, r) {
	if (!e.requiredUnknownSendReconciliation) return;
	if ((e.renderedBatchPlan?.items[t]?.mediaUrls.length ?? n) !== r.mediaUrls.length) throw new Error(`Required durable message send changed platform fan-out after outbound transforms for ${e.channel}`);
}
function withPlannedReplyTo(e, t) {
	return t ? t({ ...e }) : { ...e };
}
/** Plans text sends, preserving reply-to policy across chunked delivery units. */
function planOutboundTextMessageUnits(e) {
	const planTextUnit = (t, n, r) => {
		const i = {
			...withPlannedReplyTo(e.overrides, e.consumeReplyTo),
			deliveryPartIndex: n
		};
		return {
			text: t,
			overrides: r ? {
				...i,
				formatting: {
					...i.formatting,
					...r
				}
			} : i
		};
	};
	const t = [];
	if (!e.chunker || e.textLimit === void 0) t.push(planTextUnit(e.text, 0));
	else {
		const n = e.chunkMode !== "newline" ? [e.text] : (e.chunkerMode ?? "text") === "markdown" ? chunkMarkdownTextWithMode(e.text, e.textLimit, "newline") : chunkByParagraph(e.text, e.textLimit, { splitLongParagraphs: false });
		if (!n.length && e.text) n.push(e.text);
		for (const r of n) {
			const n = e.formatting ? e.chunker(r, e.textLimit, { formatting: e.formatting }) : e.chunker(r, e.textLimit);
			for (const i of n.length === 0 && r ? [r] : n) t.push(planTextUnit(i, t.length, e.chunkedTextFormatting));
		}
	}
	for (const e of t) e.overrides.deliveryPartCount = t.length;
	return t;
}
/** Plans media sends with a caption only on the leading media unit. */
function planOutboundMediaMessageUnits(e) {
	const t = e.mediaUrls.length;
	return e.mediaUrls.map((n, r) => ({
		mediaUrl: n,
		...r === 0 ? { caption: e.caption } : {},
		overrides: {
			...withPlannedReplyTo(e.overrides, e.consumeReplyTo),
			deliveryPartIndex: r,
			deliveryPartCount: t
		}
	}));
}
//#endregion
//#region src/infra/outbound/deliver-core.ts
const log$2 = createSubsystemLogger("outbound/deliver");
function normalizePlatformIds(e) {
	return e.map((e) => e?.trim()).filter((e) => Boolean(e && e !== "unknown" && e !== "suppressed"));
}
async function deliverOutboundPayloadsCore(e) {
	const { cfg: t, channel: n, to: r } = e;
	const i = e.preparedBatch;
	if (!i) throw new Error("Outbound delivery requires a prepared payload batch");
	const a = e.accountId;
	const o = e.reply;
	const s = e.deps;
	const c = e.abortSignal;
	const l = [];
	const u = /* @__PURE__ */ new Map();
	let d = { placement: createDeliveryPlacementEvidenceRecorder() };
	const observeDeliveryResult = (e) => {
		d.placement.observe(e);
		if (resolveReceiptSourceId(e) !== void 0) return true;
		d.suppressionReason = e.outcome === "not_sent" ? d.suppressionReason ?? "adapter_returned_no_send" : "adapter_returned_no_identity";
		return false;
	};
	const resultIdentityKey = (e) => JSON.stringify([
		e.channel,
		e.messageId,
		e.target,
		e.timestamp,
		e.toJid,
		e.pollId
	]);
	const resultPlatformIds = (e, t) => new Set(normalizePlatformIds([
		...t?.receiptOnly ? [] : [e.messageId],
		e.receipt?.primaryPlatformMessageId,
		...e.receipt?.platformMessageIds ?? [],
		...(e.receipt?.parts ?? []).map((e) => e.platformMessageId)
	]));
	const recordIdentifiedDeliveryResults = async (t, n = false) => {
		if (t.length === 0) d.suppressionReason = "adapter_returned_no_identity";
		try {
			const r = [];
			const i = n ? new Map([...u].toReversed()) : u;
			const takeReported = (e) => {
				for (const [t, n] of i) if (e(t, n)) {
					i.delete(t);
					return t;
				}
			};
			const a = /* @__PURE__ */ new Map();
			const o = [];
			for (const e of t) {
				if (!observeDeliveryResult(e)) {
					r.push(false);
					continue;
				}
				const t = normalizePlatformIds((e.receipt?.parts ?? []).map((e) => e.platformMessageId));
				const n = t.length > 0 ? t : [...resultPlatformIds(e, { receiptOnly: true })];
				let i;
				for (const t of n) {
					const n = takeReported((n) => {
						const r = l[n];
						return r?.channel === e.channel && resultPlatformIds(r).has(t);
					});
					if (n !== void 0) {
						a.set(n, null);
						i = Math.min(i ?? n, n);
					}
				}
				if (i === void 0) {
					const t = resultIdentityKey(e);
					i = takeReported((e, n) => n === t);
				}
				if (i !== void 0) a.set(i, e);
				else o.push(e);
				r.push(true);
			}
			if (a.size > 0) {
				const e = l.flatMap((e, t) => {
					const n = a.get(t);
					return n === null ? [] : [n ?? e];
				});
				l.splice(0, l.length, ...e);
			}
			for (const t of o) {
				l.push(t);
				await e.onDeliveryResult?.(t);
			}
			return r;
		} finally {
			u.clear();
		}
	};
	const recordIdentifiedDeliveryResult = async (e) => {
		const [t] = await recordIdentifiedDeliveryResults([e], true);
		return t ?? false;
	};
	const reportIdentifiedDeliveryResult = async (t) => {
		if (!observeDeliveryResult(t)) return;
		const n = l.length;
		l.push(t);
		u.set(n, resultIdentityKey(t));
		await e.onDeliveryResult?.(t);
	};
	let f;
	let p;
	const createHandler = (i) => createChannelHandler({
		...resolveChannelHandlerParams(e, o, i),
		cfg: t,
		channel: n,
		to: r,
		deps: s,
		accountId: a,
		abortSignal: c,
		deliveryQueueId: e.deliveryQueueId,
		onPlatformSendStart: async (t) => {
			p = true;
			await e.onPlatformSendStart?.(t, f);
		},
		onDirectAdapterHandoff: e.onDirectAdapterHandoff,
		withDirectAdapterHandoff: e.withDirectAdapterHandoff,
		assertDirectAdapterHandoff: e.assertDirectAdapterHandoff,
		onPlatformSendDispatch: e.onPlatformSendDispatch,
		onDeliveryResult: reportIdentifiedDeliveryResult
	});
	const m = await createHandler([]);
	let h = m.buildTargetRef({ threadId: e.threadId });
	const maybeAdoptTargetFromDelivery = (t) => {
		if (e.threadId != null || h.threadId != null) return;
		const n = m.adoptTargetFromDelivery?.({
			target: h,
			result: t
		});
		if (n?.threadId != null) h = {
			...h,
			threadId: n.threadId
		};
	};
	const withPreparedTarget = (e) => h.threadId == null ? e : {
		...e,
		threadId: h.threadId
	};
	const adoptSuccessfulResultsSince = (e) => {
		for (const t of l.slice(e)) maybeAdoptTargetFromDelivery(t);
	};
	const g = /* @__PURE__ */ new Map();
	const getDeliveryHandler = (e) => {
		if (e.length === 0) return Promise.resolve(m);
		const t = JSON.stringify(e);
		return getOrCreatePromise(g, t, () => createHandler(e));
	};
	const _ = m.chunker ? resolveTextChunkLimit(t, n, a, { fallbackLimit: m.textChunkLimit }) : void 0;
	const v = e.formatting?.textLimit ?? (m.resolveEffectiveTextChunkLimit ? m.resolveEffectiveTextChunkLimit({
		fallbackLimit: _,
		formatting: e.formatting
	}) : _);
	const y = m.chunker ? e.formatting?.chunkMode ?? resolveChunkMode(t, n, a) : "length";
	const { resolveCurrentReplyTo: b, applyReplyToConsumption: x } = createReplyToDeliveryPolicy({ reply: o });
	const sendTextChunks = async (t, n, r) => {
		const i = planOutboundTextMessageUnits({
			text: n,
			overrides: r,
			chunker: t.chunker,
			chunkerMode: t.chunkerMode,
			chunkedTextFormatting: t.chunkedTextFormatting,
			textLimit: v,
			chunkMode: y,
			formatting: e.formatting,
			consumeReplyTo: x
		});
		for (const e of i) {
			throwIfAborted(c);
			const n = l.length;
			await recordIdentifiedDeliveryResult(await t.sendText(e.text, withPreparedTarget(e.overrides)));
			adoptSuccessfulResultsSince(n);
		}
	};
	const S = acceptedPreparedOutboundEntries(i);
	const C = [...preparedOutboundSuppressionOutcomes(i)];
	for (const t of C) e.onPayloadDeliveryOutcome?.(t);
	const w = e.transcriptDeliveryId ?? e.deliveryQueueId ?? e.deliveryIntentId ?? randomUUID();
	const recordDeliveredPayload = async (t, i, a) => {
		try {
			e.onDeliveredPayload?.(i);
		} catch (e) {
			log$2.warn("Outbound delivered-payload observer failed after platform send.", {
				channel: n,
				to: r,
				error: formatErrorMessage(e)
			});
		}
		await recordConfirmedTranscript({
			params: e,
			payload: t,
			payloadIndex: a,
			deliveryId: w,
			threadId: h.threadId
		});
	};
	const T = e.session?.key ?? e.session?.policyKey;
	for (const [t, a] of S.entries()) {
		u.clear();
		d = { placement: createDeliveryPlacementEvidenceRecorder() };
		const o = a.sourceIndex;
		f = o;
		p = false;
		const s = a.payload;
		const g = l.length;
		let _;
		let v = summarizeOutboundPayloadForTransport(s);
		const y = a.preparedMediaCount;
		let S;
		const recordPayloadOutcome = (t) => {
			const n = S && t.status !== "suppressed" ? {
				...t,
				deliveryKind: S
			} : t;
			C.push(n);
			e.onPayloadDeliveryOutcome?.(n);
		};
		const recordSuppressedPayload = (e) => recordPayloadOutcome({
			index: o,
			status: "suppressed",
			reason: e
		});
		let w = "other";
		let E = 0;
		let D = false;
		let O = false;
		const recordMessageSentEvent = (t) => {
			if (O) return;
			O = true;
			e.onMessageSentEvent?.(t, o);
		};
		const startDeliveryDiagnostics = (e) => {
			w = e;
			E = Date.now();
			D = true;
			emitInternalDiagnosticEvent({
				type: "message.delivery.started",
				channel: n,
				deliveryKind: w,
				...T ? { sessionKey: T } : {}
			});
		};
		const finishDeliveryDiagnostics = (e) => {
			if (!D) return;
			D = false;
			const t = {
				channel: n,
				deliveryKind: w,
				durationMs: Date.now() - E,
				...T ? { sessionKey: T } : {}
			};
			emitInternalDiagnosticEvent(typeof e === "number" ? {
				type: "message.delivery.completed",
				...t,
				resultCount: e
			} : {
				type: "message.delivery.error",
				...t,
				errorCategory: diagnosticErrorCategory(e.error)
			});
		};
		try {
			throwIfAborted(c);
			const u = await getDeliveryHandler(v.mediaUrls);
			const f = stripInternalRuntimeScaffoldingFromPayload(await renderPresentationForDelivery(u, s));
			const p = await getDeliveryHandler(summarizeOutboundPayloadForTransport(f).mediaUrls);
			const m = (i.channelNormalized !== true || f !== s) && p.normalizePayload ? p.normalizePayload(f) : f;
			_ = m ? normalizeEmptyPayloadForDelivery(stripInternalRuntimeScaffoldingFromPayload(m)) : null;
			if (!_) {
				recordSuppressedPayload(a.messageHookChanged ? "empty_after_message_sending_hook" : a.replyHookChanged ? "empty_after_reply_payload_sending_hook" : "no_visible_payload");
				continue;
			}
			const g = summarizeOutboundPayloadForTransport(_);
			assertStableMediaFanout(e, t, y, g);
			v = g;
			const C = await getDeliveryHandler(v.mediaUrls);
			S = deliveryKindForPayload(_, v);
			startDeliveryDiagnostics(S);
			e.onPayload?.(v);
			const w = b(_);
			const T = {
				replyToId: w.replyToId,
				replyToIdSource: w.source,
				...h.threadId != null ? { threadId: h.threadId } : {},
				..._.audioAsVoice === true ? { audioAsVoice: true } : {}
			};
			const deliveryTarget = () => C.buildTargetRef({ threadId: h.threadId });
			const E = l.length;
			let D = _;
			let O = v;
			let k;
			if (C.sendPayload && (C.supportsMediaPayload && v.mediaUrls.length > 1 || payloadRequiresDurablePayloadTransport(_, { sendTextOnlyErrorPayloads: C.sendTextOnlyErrorPayloads }))) {
				await recordIdentifiedDeliveryResult(await C.sendPayload(_, withPreparedTarget(x(T))));
				adoptSuccessfulResultsSince(E);
				if (l.length <= E) {
					finishDeliveryDiagnostics(0);
					recordSuppressedPayload(d.suppressionReason ?? "adapter_returned_no_identity");
					continue;
				}
			} else if (v.mediaUrls.length === 0) {
				if (C.sendFormattedText) {
					await recordIdentifiedDeliveryResults(await C.sendFormattedText(v.text, withPreparedTarget(x(T))));
					adoptSuccessfulResultsSince(E);
				} else await sendTextChunks(C, v.text, T);
			} else if (!C.supportsMedia) {
				log$2.warn("Plugin outbound adapter does not implement sendMedia or sendFormattedMedia; media URLs will be dropped and text fallback will be used", {
					channel: n,
					to: r,
					mediaCount: v.mediaUrls.length
				});
				const e = v.text.trim();
				if (!e) throw new Error("Plugin outbound adapter does not implement sendMedia or sendFormattedMedia and no text fallback is available for media payload");
				await sendTextChunks(C, e, T);
				D = { text: e };
				O = {
					...v,
					text: e,
					mediaUrls: []
				};
			} else {
				k = {};
				const e = planOutboundMediaMessageUnits({
					mediaUrls: v.mediaUrls,
					caption: v.text,
					overrides: T,
					consumeReplyTo: x
				});
				const t = C.sendFormattedMedia ?? C.sendMedia;
				for (const n of e) {
					throwIfAborted(c);
					const e = l.length;
					const r = await t(n.caption ?? "", n.mediaUrl, withPreparedTarget(n.overrides));
					const i = await recordIdentifiedDeliveryResult(r);
					adoptSuccessfulResultsSince(e);
					if (i) {
						k.first ??= r.messageId;
						k.last = r.messageId;
					}
				}
			}
			const A = l.slice(E);
			const j = d.suppressionReason;
			if (A.length > 0) {
				recordPayloadOutcome({
					index: o,
					status: "sent",
					results: A,
					...j ? { incompleteReason: j } : {},
					reportedPlacement: d.placement.snapshot()
				});
				if (!j) await recordDeliveredPayload(D, O, o);
			} else {
				recordSuppressedPayload(d.suppressionReason ?? "adapter_returned_no_identity");
				if (d.suppressionReason === "adapter_returned_no_send") {
					finishDeliveryDiagnostics(0);
					continue;
				}
			}
			const M = k ? k.first : A.find((e) => e.messageId)?.messageId;
			const N = k ? k.last : A.at(-1)?.messageId;
			recordMessageSentEvent({
				success: A.length > 0,
				content: v.hookContent ?? v.text,
				messageId: N
			});
			await maybePinDeliveredMessage({
				handler: C,
				payload: _,
				target: deliveryTarget(),
				messageId: M,
				gatewayClientScopes: e.gatewayClientScopes,
				assertDirectAdapterHandoff: e.assertDirectAdapterHandoff
			});
			await maybeNotifyAfterDeliveredPayload({
				handler: C,
				payload: _,
				target: deliveryTarget(),
				results: A
			});
			finishDeliveryDiagnostics(A.length);
		} catch (t) {
			let n = t;
			if (!p) try {
				assertOutboundHandoffCurrent(e.assertDirectAdapterHandoff);
			} catch (e) {
				n = e;
			}
			const r = l.slice(g);
			adoptSuccessfulResultsSince(g);
			if (_ && r.length > 0) await maybeNotifyAfterDeliveredPayload({
				handler: await getDeliveryHandler(summarizeOutboundPayloadForTransport(_).mediaUrls),
				payload: _,
				target: m.buildTargetRef({ threadId: h.threadId }),
				results: r
			});
			recordPayloadOutcome({
				index: o,
				status: "failed",
				error: n,
				sentBeforeError: r.length > 0 || d.suppressionReason === "adapter_returned_no_identity",
				stage: "platform_send",
				results: r
			});
			finishDeliveryDiagnostics({ error: n });
			recordMessageSentEvent({
				success: false,
				content: v.hookContent ?? v.text,
				error: formatErrorMessage(n),
				...r.at(-1)?.messageId ? { messageId: r.at(-1).messageId } : {}
			});
			if (!e.bestEffort) throw n instanceof OutboundDeliveryError ? n : new OutboundDeliveryError(formatErrorMessage(n), {
				cause: n,
				results: l,
				payloadOutcomes: C,
				stage: "platform_send"
			});
			e.onError?.(n, v);
		}
	}
	return l;
}
async function recordConfirmedTranscript(e) {
	const { params: t } = e;
	if (t.skipDestinationHistory) return;
	const n = e.threadId != null && String(e.threadId) !== String(t.transcriptRoute?.threadId ?? t.threadId);
	let r;
	try {
		const i = await commitConfirmedVisibleMessage({
			config: t.cfg,
			channel: t.channel,
			to: t.to,
			accountId: t.accountId ?? void 0,
			threadId: e.threadId ?? void 0,
			route: n ? void 0 : t.transcriptRoute,
			producer: t.session,
			payload: e.payload,
			deliveryId: e.deliveryId,
			payloadIndex: e.payloadIndex,
			signal: t.abortSignal,
			expectedGeneration: n ? void 0 : t.transcriptExpectedGeneration,
			provenance: t.transcriptProvenance,
			assertCurrent: t.assertTranscriptCurrent,
			assertDirectAdapterHandoff: t.assertDirectAdapterHandoff,
			stateDir: t.transcriptStateDir
		});
		r = i.ok ? i.diagnostics : `result was delivered but was not added to the conversation: ${i.reason}`;
	} catch (e) {
		r = `result was delivered but was not added to the conversation: ${formatErrorMessage(e)}`;
	}
	if (!r) return;
	log$2.warn(`Confirmed outbound transcript: ${r}`, {
		channel: t.channel,
		to: t.to
	});
	try {
		t.onTranscriptDiagnostic?.(r);
	} catch {}
}
//#endregion
//#region src/infra/outbound/deliver-queue-execute.ts
const log$1 = createSubsystemLogger("outbound/deliver");
async function deliverOutboundPayloadsWithQueueCleanup(e, t, n, r, i) {
	const throwIfProducerLeaseLost = () => i?.signal.throwIfAborted();
	const a = e.preparedBatch?.sourcePayloadCount ?? e.payloads.length;
	const o = e.deliveryQueueId === void 0;
	const s = [];
	const c = e.reusePendingDeliveryIntent ? r : void 0;
	const l = e.queuePolicy ?? "best_effort";
	const u = t ?? e.deliveryQueueId;
	const d = t ? l : e.queuePolicy ?? "required";
	const f = e.deliveryQueueStateDir;
	const p = e.requireUnknownSendReconciliation === true && u !== void 0;
	let m;
	let h;
	let g = false;
	let _;
	let v;
	const y = /* @__PURE__ */ new Set();
	const b = /* @__PURE__ */ new Set();
	let x = [];
	let S = false;
	let C = false;
	const settleDeliveryCompletion = async (t) => {
		if (!e.deliveryCompletion) return;
		await settleDurableDelivery(e.deliveryCompletion, t ? {
			result: t,
			batch: {
				results: x,
				payloadCount: a,
				payloadOutcomes: s
			}
		} : { platformSendStarted: g && !S }, f, e.deliveryQueueStateContext, e.conversationDeliveryTarget);
	};
	const w = [];
	const { emitMessageSent: T, hasMessageSentHooks: E, sessionKeyForInternalHooks: D } = createOutboundMessageSentEmitter(e, OUTBOUND_DELIVERY_LOG_SCOPE);
	if (E && e.session?.agentId && !D) log$1.warn(`${OUTBOUND_DELIVERY_LOG_SCOPE}: session.agentId present without session key; internal message:sent hook will be skipped`, {
		channel: e.channel,
		to: e.to,
		agentId: e.session.agentId
	});
	const flushMessageSentEvents = () => {
		if (e.deferCommitHooks) return;
		for (const e of w) T(e);
		w.length = 0;
	};
	const O = t ? e.deliveryQueueOwner : void 0;
	const persistPostSendState = (t) => persistQueuedPostSendState({
		owner: t,
		queuePolicy: l,
		preserveBatch: Boolean(c)
	}, e.deliveryQueueStateContext);
	const failAfterPlatformSend = async (e, t, n) => {
		await e.fail(failDeliveryAfterPlatformSend, t, n);
		h = "failed";
	};
	const emitTerminals = (r) => {
		if (!o) return;
		emitOutboundAuditTerminals({
			context: e,
			terminals: r,
			startedAt: n,
			...t ? { queueId: t } : {}
		});
	};
	const runCommitHooksAfterAck = async () => {
		if (h !== "acked" || e.deferCommitHooks || C) return;
		C = true;
		flushMessageSentEvents();
		await runOutboundDeliveryCommitHooks(x);
	};
	const auditBatch = () => ({
		payloadCount: a,
		results: x,
		payloadOutcomes: s
	});
	const failedTerminals = (e) => failedOutboundAuditTerminals({
		...auditBatch(),
		failureStage: e
	});
	const emitFailedTerminals = (e) => emitTerminals(() => failedTerminals(e));
	const completedTerminals = () => completedOutboundAuditTerminals(auditBatch());
	const finishAck = async (e) => {
		h = "acked";
		await runCommitHooksAfterAck();
		emitTerminals(e);
	};
	const finishPermanentRejection = async (t, n) => {
		const r = failedTerminals("platform_send");
		if (await rejectQueuedDelivery(t, n, e, r)) await finishAck(() => r);
	};
	let k;
	let A;
	const assertPlatformSendAuthorized = () => {
		throwIfAborted(e.abortSignal);
		assertSessionWriterDeliveryAuthorized(A?.authority);
	};
	const j = {
		...e,
		transcriptDeliveryId: u,
		transcriptStateDir: e.deliveryQueueStateDir,
		...p && e.payloads.length === 1 ? { deliveryQueueId: u } : { deliveryQueueId: void 0 },
		requiredUnknownSendReconciliation: p,
		onPlatformSendStart: async (r, i) => {
			throwIfAborted(e.abortSignal);
			_ = r;
			v = i;
			if (e.deliveryQueueOwner && !p && m === void 0) {
				m = await persistQueuedPreSendState({
					owner: e.deliveryQueueOwner,
					queuePolicy: d,
					route: r,
					retainSpoolArtifacts: t === null && e.deliveryQueueId !== void 0
				}, e.deliveryQueueStateContext);
				if (t && m === "acked") h = "acked";
			}
			if (u && i !== void 0 && !y.has(i)) {
				y.add(i);
				emitOutboundAuditLifecycle({
					context: e,
					outcome: "platform_started",
					queueId: u,
					startedAt: n,
					payloadIndexes: [i]
				});
			}
			throwIfAborted(e.abortSignal);
			await e.onPlatformSendStart?.(r);
			throwIfAborted(e.abortSignal);
			g = true;
		},
		onDirectAdapterHandoff: async () => {
			assertPlatformSendAuthorized();
			await e.onPlatformSendDispatch?.();
			throwIfAborted(e.abortSignal);
			k?.assertCurrent();
		},
		assertDirectAdapterHandoff: () => {
			k?.assertCurrent();
			e.assertDirectAdapterHandoff?.();
			assertPlatformSendAuthorized();
		},
		onPlatformSendDispatch: async () => {
			throwIfAborted(e.abortSignal);
			if (u && m !== "acked" && h === void 0) try {
				await markDeliveryPlatformSendDispatched(u, f, _, r || void 0, e.deliveryQueueStateContext);
				m ??= "marked";
			} catch (e) {
				if (p || r) throw e;
				log$1.warn(`failed to refresh queued delivery ${u} at platform dispatch; continuing best-effort send: ${formatErrorMessage(e)}`);
			}
			assertPlatformSendAuthorized();
			await e.onPlatformSendDispatch?.();
			throwIfAborted(e.abortSignal);
			k?.assertCurrent();
			if (v !== void 0) b.add(v);
		},
		onError: (t, n) => {
			throwIfProducerLeaseLost();
			e.onError?.(t, n);
		},
		onPayloadDeliveryOutcome: (t) => {
			if (t.status === "failed" && b.has(t.index) && !isProvenDeliveryNotSentError(t.error)) t.sentBeforeError = true;
			s.push(t);
			e.onPayloadDeliveryOutcome?.(t);
		},
		onDeliveryResult: async (t) => {
			x.push(t);
			if (O && h === void 0) h = await persistPostSendState(O);
			await e.onDeliveryResult?.(t);
		},
		onMessageSentEvent: (t, n) => {
			w.push(t);
			e.onMessageSentEvent?.(t, n);
		}
	};
	let M = false;
	try {
		throwIfProducerLeaseLost();
		A = await prepareSessionWriterDeliveryAuthority(e.deliveryCompletion?.kind === "pending-final" ? e.deliveryCompletion.sessionWriterDeliveryAuthority : void 0);
		if (e.sessionGeneration !== void 0) {
			k = await prepareOutboundDeliveryGeneration(e.sessionGeneration);
			throwIfProducerLeaseLost();
		}
		const n = e.deliveryCompletion?.kind === "conversation" ? e.deliveryCompletion : e.conversationDeliveryAttemptAuthority;
		if (n) {
			if (!n.routeFingerprint || !e.onDeliveryAttempt && !e.withDirectAdapterHandoff) throw new PlatformMessageNotDispatchedError("Conversation delivery is missing its current route authorization", {
				cause: void 0,
				retryable: false
			});
			await e.onDeliveryAttempt?.();
			throwIfProducerLeaseLost();
		}
		const r = await deliverOutboundPayloadsCore(j);
		x = r;
		const i = s.filter((e) => e.status === "failed");
		S = r.length === 0 && areOutboundPayloadsIntentionallySuppressed(s);
		throwIfProducerLeaseLost();
		M = true;
		if (O && c && r.length > 0 && s.some((e) => e.status === "suppressed" && e.reason === "adapter_returned_no_identity")) {
			const e = "platform send returned no delivery identity for part of the delivery batch";
			await failAfterPlatformSend(O, e);
			throw new OutboundDeliveryError(e, {
				cause: /* @__PURE__ */ new Error(e),
				results: r,
				payloadOutcomes: s,
				stage: "platform_send"
			});
		}
		if (!t) {
			await settleDeliveryCompletion(r.at(-1));
			if (!e.deferCommitHooks) {
				flushMessageSentEvents();
				await runOutboundDeliveryCommitHooks(r);
			}
			emitTerminals(i.length > 0 ? () => failedTerminals("platform_send") : completedTerminals);
			return r;
		}
		if (O) {
			if (i.length > 0) {
				const e = i.every((e) => isProvenDeliveryNotSentError(e.error));
				const n = r.length > 0 || s.some((e) => e.status === "failed" ? e.sentBeforeError : e.status === "suppressed" && e.reason === "adapter_returned_no_identity");
				const a = h ?? (n ? await persistPostSendState(O) : void 0);
				const o = !n && a === void 0 ? findTerminalBatchRejection(i.map((e) => e.error)) : void 0;
				if (o) {
					await finishPermanentRejection(O, o);
					return r;
				}
				const c = "partial delivery failure (bestEffort)";
				if (a === void 0 || a === "marked") {
					const r = !n && e ? failDeliveryBeforePlatformSend : failDelivery;
					await O.fail(r, c).catch((e) => {
						log$1.warn(`failed to mark queued delivery ${t} as failed after partial failure; continuing best-effort delivery: ${formatErrorMessage(e)}`);
					});
				} else if (a === "acked") await finishAck(() => failedTerminals("platform_send"));
			} else {
				const n = h ?? (r.length > 0 || m === "marked" && !S ? await persistPostSendState(O) : m === "acked" ? "acked" : void 0);
				await settleDeliveryCompletion(r.at(-1));
				if (r.length === 0 && n === "marked") {
					await failAfterPlatformSend(O, "platform send returned no delivery identity");
					return r;
				}
				if (n === "acked" || n !== "failed" && await O.ack(r.length === 0 && typeof e.completionRetention === "object" ? { suppressCompletionReceipt: true } : void 0).then(() => true).catch(async (e) => {
					const n = x.length > 0 || m !== void 0 && !S;
					try {
						if (n) await failAfterPlatformSend(O, `failed to ack sent delivery: ${formatErrorMessage(e)}`);
						else await O.fail(S ? failDeliveryBeforePlatformSend : failDelivery, `failed to ack unsent delivery: ${formatErrorMessage(e)}`);
					} catch (e) {
						log$1.warn(`failed to preserve queued delivery ${t} after ack failure: ${formatErrorMessage(e)}`);
					}
					if (l === "required") throw e;
					log$1.warn(n ? `failed to ack queued delivery ${t}; preserved unknown-after-send state: ${formatErrorMessage(e)}` : `failed to ack unsent queued delivery ${t}; retained it for retry: ${formatErrorMessage(e)}`);
					return false;
				})) await finishAck(completedTerminals);
			}
		}
		return r;
	} catch (n) {
		let i = n;
		try {
			throwIfProducerLeaseLost();
			if (isOutboundDeliveryAdmissionClosedError(i)) throw i;
			if (!g && x.length === 0 && h === void 0 && !(i instanceof OutboundDeliveryError && i.sentBeforeError)) try {
				assertOutboundHandoffCurrent(j.assertDirectAdapterHandoff);
			} catch (e) {
				i = e;
			}
			if (i instanceof OutboundDeliveryError && i.results.length > 0) x = i.results;
			const n = isProvenBatchNotSent(i, s);
			const a = x.length > 0 || !S && (m === "marked" || h === "marked") || i instanceof OutboundDeliveryError && i.sentBeforeError || c !== void 0 && s.some((e) => e.status === "sent");
			const o = i instanceof OutboundDeliveryError ? i.stage : "platform_send";
			if (O) {
				if (O.custody === "released") {
					await runCommitHooksAfterAck();
					emitFailedTerminals(o);
				} else if (e.abortSignal?.aborted) {
					if (n && x.length === 0 && e.deliveryCompletion) {
						await O.fail(failDeliveryBeforePlatformSend, formatErrorMessage(i));
						h = "failed";
					} else if (a) {
						if (h !== "failed") await failAfterPlatformSend(O, `delivery aborted after platform send: ${formatErrorMessage(i)}`);
					} else if (await O.ack(r ? { suppressCompletionReceipt: true } : void 0).then(() => true).catch(() => false)) await finishAck(() => failedTerminals("queue"));
				} else if (!M) {
					const r = e.retryAmbiguousFinalText === true && g && x.length === 0 && isAmbiguousDeliveryTransportError(i);
					if (x.length > 0 || r || !n && (b.size > 0 || i instanceof OutboundDeliveryError && i.sentBeforeError)) {
						try {
							h ??= await persistPostSendState(O);
							if (h === "marked") await failAfterPlatformSend(O, formatErrorMessage(i), r ? true : void 0);
						} catch (e) {
							log$1.warn(`failed to preserve queued delivery ${t} post-send evidence: ${formatErrorMessage(e)}`);
						}
						await runCommitHooksAfterAck();
						if (h === "acked") emitFailedTerminals(o);
					} else {
						const r = h === void 0 && n ? findTerminalBatchRejection([i, ...s.flatMap((e) => e.status === "failed" ? [e.error] : [])]) : void 0;
						if (r) await finishPermanentRejection(O, r);
						else if (n && e.deliveryRetryOwner === "caller" && !e.deliveryCompletion) try {
							throwIfProducerLeaseLost();
							await O.retire();
							emitFailedTerminals(o);
						} catch (e) {
							log$1.warn(`failed to dead-letter queued delivery ${t} after proven-not-sent failure: ${formatErrorMessage(e)}`);
						}
						else {
							const e = n ? failDeliveryBeforePlatformSend : failDelivery;
							try {
								await O.fail(e, formatErrorMessage(i));
							} catch (e) {
								log$1.warn(`failed to mark queued delivery ${t} as failed: ${formatErrorMessage(e)}`);
							}
						}
					}
				}
			} else {
				flushMessageSentEvents();
				emitFailedTerminals(o);
			}
			throw i;
		} catch (t) {
			throw e.deliveryQueueOwner ? e.deliveryQueueOwner.project(t, {
				results: x,
				payloadOutcomes: s,
				stage: t instanceof OutboundDeliveryError ? t.stage : "queue"
			}) : t;
		}
	} finally {
		A?.release();
		k?.release();
		for (const t of s) if (t.status === "failed" && e.deliveryQueueOwner) t.error = e.deliveryQueueOwner.project(t.error);
	}
}
//#endregion
//#region src/infra/outbound/delivery-queue-lease.ts
const PLATFORM_SEND_OWNER_HEARTBEAT_MS = Math.floor(PLATFORM_SEND_OWNER_LEASE_MS / 3);
var DeliveryProducerLeaseLostError = class extends Error {
	constructor(...e) {
		super(...e);
		this.name = "DeliveryProducerLeaseLostError";
	}
};
function lostProducerLeaseError(e, t) {
	return new DeliveryProducerLeaseLostError(`Delivery platform claim was lost: ${e}`, { cause: t });
}
/** Maintains one already-acquired producer claim during fallible preparation and send. */
async function startDeliveryProducerLease(e) {
	try {
		if (await e.renew() === void 0) throw lostProducerLeaseError(e.id);
	} catch (t) {
		if (t instanceof DeliveryProducerLeaseLostError) throw t;
		throw lostProducerLeaseError(e.id, t);
	}
	const t = new AbortController();
	let n;
	let r;
	const abortLost = (r) => {
		if (!n && !t.signal.aborted) t.abort(lostProducerLeaseError(e.id, r));
	};
	const renew = async () => {
		if (n || t.signal.aborted) return;
		try {
			const t = await e.renew();
			if (n) return;
			if (t === void 0) abortLost();
		} catch (e) {
			abortLost(e);
		}
	};
	const i = setInterval(() => {
		if (!r) r = renew().finally(() => {
			r = void 0;
		});
	}, PLATFORM_SEND_OWNER_HEARTBEAT_MS);
	i.unref?.();
	return {
		signal: t.signal,
		stop: () => {
			if (!n) {
				n = r ?? Promise.resolve();
				clearInterval(i);
			}
			return n;
		}
	};
}
//#endregion
//#region src/infra/outbound/deliver-queue.ts
const log = createSubsystemLogger("outbound/deliver");
function isReusablePreparedDeliveryOwner(e) {
	return e?.namespace === "prepared" && (e.status === "pending" || e.status === "completed");
}
async function runOutboundDelivery(e) {
	return await runOutboundDeliveryInternal({
		...e,
		conversationDeliveryTarget: void 0,
		sessionGeneration: void 0,
		deliveryQueueStateContext: void 0
	});
}
async function runOutboundDeliveryInternal(e, t, n) {
	return await runDelivery(e, (e, t) => prepareOutboundPayloadBatch(e, {
		...t,
		admittedReasoning: n
	}), t);
}
async function runStructuredOutboundDeliveryInternal(e) {
	const { plan: t, ...n } = e;
	const r = t.map((e, t) => Object.assign({}, e, { sourceIndex: t }));
	return await runDelivery({
		...n,
		payloads: r.map((e) => e.payload)
	}, (e, t) => prepareStructuredOutboundPayloadBatch(e, r, t));
}
async function runDelivery(e, t, n) {
	const r = e.conversationDeliveryTarget ?? n ?? captureDeliveryQueueStateContext(e.deliveryQueueId ? e.deliveryQueueStateDir : void 0);
	const i = {
		...e,
		deliveryQueueStateContext: r,
		deliveryQueueStateDir: r.stateDir
	};
	const a = i.deliveryQueueOwner ?? (i.deliveryQueueId ? createQueuedDeliveryOwner({
		queueId: i.deliveryQueueId,
		stateDir: i.deliveryQueueStateDir,
		expectedPlatformSendAttemptId: i.deliveryProducerClaimId
	}, i.deliveryQueueStateContext) : void 0);
	try {
		return await runWithQuestionChannelDeliveries(i.payloads.map(readAskUserQuestionId), () => runOutboundDeliveryWithIntent({
			...i,
			deliveryQueueOwner: a
		}, t));
	} catch (e) {
		throw a ? a.project(e) : e;
	}
}
async function runOutboundDeliveryWithIntent(e, t) {
	const { replyToId: n, replyToMode: r, ...i } = e;
	const a = normalizeOutboundReplyFacts({
		reply: e.reply,
		replyToId: n,
		replyToMode: r
	});
	const o = {
		...i,
		...a ? { reply: a } : {}
	};
	const s = o.deliveryIntentId?.trim();
	if (s) {
		o.deliveryIntentId = s;
		const e = await withActiveDeliveryClaim(s, async () => {
			const e = await withStableDeliveryPreparation({
				id: s,
				stateDir: o.deliveryQueueStateDir,
				run: async (e) => await runOutboundDeliveryWithQueue(o, t, true, e)
			}, o.deliveryQueueStateContext);
			return e.status === "claimed" ? e.value : await runOutboundDeliveryWithQueue(o, t, true);
		});
		if (e.status === "claimed") return e.value;
		const n = o.reusePendingDeliveryIntent ? await findDeliveryIntentOwner(s, o.deliveryQueueStateDir, o.deliveryQueueStateContext) : null;
		throwIfAborted(o.abortSignal);
		if (isReusablePreparedDeliveryOwner(n)) return [];
		throw new Error(`Stable delivery intent is already queued: ${s}`);
	}
	return await runOutboundDeliveryWithQueue(o, t, false);
}
async function deliverWithProducerLease(e, t, n, r, i) {
	return await runWithQuestionChannelDeliveries(e.payloads.map(readAskUserQuestionId), async () => {
		if (e.deliveryProducerLeaseRequired !== true) return await deliverOutboundPayloadsWithQueueCleanup(e, t, n, r);
		const i = t ?? e.deliveryQueueId;
		if (!i || !r) throw new Error("Delivery producer lease requires an exact queue owner");
		const a = e.deliveryQueueStateDir;
		const o = await startDeliveryProducerLease({
			id: i,
			renew: async () => await renewDeliveryPlatformSendLease(i, a, r, e.deliveryQueueStateContext)
		});
		if (e.deliveryQueueOwner) e.deliveryQueueOwner.signal = o.signal;
		const s = e.abortSignal ? AbortSignal.any([e.abortSignal, o.signal]) : o.signal;
		try {
			return await deliverOutboundPayloadsWithQueueCleanup({
				...e,
				abortSignal: s
			}, t, n, r, o);
		} finally {
			await o.stop();
		}
	}, { unbound: i === "unbound" });
}
async function runOutboundDeliveryWithQueue(e, t, n, r) {
	let i = e;
	const a = Date.now();
	const { channel: o, to: s, payloads: c } = i;
	const assertDeliveryCurrent = () => {
		throwIfAborted(i.abortSignal);
		i.deliveryQueueOwner?.signal?.throwIfAborted();
		i.deliveryQueueStateContext?.workerContext.admission.assertCurrent();
	};
	const emitPreQueueFailure = () => {
		if (i.deliveryQueueId !== void 0) return;
		emitOutboundAuditTerminals({
			context: i,
			terminals: () => uniformOutboundAuditTerminals(i.payloads.length, {
				outcome: "failed",
				failureStage: "queue"
			}),
			startedAt: a
		});
	};
	const emitPreparationFailure = (e) => {
		emitPreQueueFailure();
		if (i.payloads.length > 0) {
			const { emitMessageSent: t } = createMessageSentEmitter({
				hookRunner: getGlobalHookRunner(),
				channel: o,
				to: s,
				accountId: i.accountId,
				sessionKeyForInternalHooks: i.session?.key,
				isGroup: i.session?.conversationType === "group",
				runId: i.replyPayloadSendingHook?.runId,
				logPrefix: OUTBOUND_DELIVERY_LOG_SCOPE
			});
			for (const n of i.payloads) {
				const r = summarizeOutboundPayloadForTransport(n);
				t({
					success: false,
					content: r.hookContent ?? r.text,
					error: formatErrorMessage(e)
				});
			}
		}
	};
	if (i.requireUnknownSendReconciliation === true && c.length !== 1) {
		emitPreQueueFailure();
		throw new Error(`Required durable message send is unsupported for ${o}: unknown-send reconciliation requires exactly one payload`);
	}
	if (i.deferredDeliveryAdmissionPassed !== true) {
		let e;
		try {
			e = (await prepareDeferredDeliveryAdmission({
				cfg: i.cfg,
				channel: o,
				to: s,
				accountId: i.accountId,
				phase: "live"
			}, {
				agentId: i.session?.agentId,
				assertCurrent: assertDeliveryCurrent
			}))();
		} catch (e) {
			emitPreparationFailure(e);
			throw e;
		}
		if (e.status === "permanent_rejection") {
			emitPreQueueFailure();
			throw new Error(e.reason);
		}
	}
	if (!i.skipQueue && i.accountId === void 0) {
		const e = await resolveOutboundChannelPluginAsync({
			channel: o,
			cfg: i.cfg,
			agentId: i.session?.agentId,
			allowBootstrap: true,
			assertCurrent: assertDeliveryCurrent
		});
		assertDeliveryCurrent();
		if (e) i = {
			...i,
			accountId: resolveChannelDefaultAccountId({
				plugin: e,
				cfg: i.cfg
			})
		};
	}
	const l = i.queuePolicy ?? "best_effort";
	const u = i.deliveryIntentId ? await loadPendingDelivery(i.deliveryIntentId, i.deliveryQueueStateDir, i.deliveryQueueStateContext) : null;
	if (i.deliveryIntentId && !u && !r) {
		const e = await findDeliveryIntentOwner(i.deliveryIntentId, i.deliveryQueueStateDir, i.deliveryQueueStateContext);
		assertDeliveryCurrent();
		if (e) {
			if (i.reusePendingDeliveryIntent && isReusablePreparedDeliveryOwner(e)) return [];
			throw new Error(e.namespace === "legacy" ? `Stable delivery intent is awaiting queue migration: ${i.deliveryIntentId}` : `Stable delivery intent is already queued: ${i.deliveryIntentId}`);
		}
		if (n) throw new Error(`Stable delivery intent is already queued: ${i.deliveryIntentId}`);
	}
	if (u && !i.reusePendingDeliveryIntent) throw new Error(`Stable delivery intent is already queued: ${i.deliveryIntentId}`);
	let d;
	try {
		d = u?.preparedBatch ?? i.preparedBatch ?? await t(i, { onBeforeFirstModifier: r?.beforeFirstModifier });
		await r?.markPrepared();
	} catch (e) {
		emitPreparationFailure(e);
		throw e;
	}
	const f = preparedOutboundPayloads(d);
	const p = u?.renderedBatchPlan ?? (i.preparedBatch ? i.renderedBatchPlan : void 0) ?? createRenderedMessageBatchPlan(f);
	let m = i.requireUnknownSendReconciliation === true;
	if (i.requireUnknownSendReconciliation !== false && f.length === 1) {
		const e = deriveDurableFinalDeliveryRequirementsForBatch({
			payloads: f,
			replyToId: i.reply?.replyToId,
			threadId: i.threadId,
			silent: i.silent,
			reconcileUnknownSend: true
		});
		delete e.messageSendingHooks;
		const t = await resolveOutboundDurableFinalDeliverySupport({
			cfg: i.cfg,
			agentId: i.session?.agentId,
			channel: o,
			requirements: e
		});
		if (i.requireUnknownSendReconciliation === true && !t.ok) {
			emitPreQueueFailure();
			throw new Error(`Required durable message send is unsupported for ${o}: prepared payload capability mismatch${t.capability ? ` (${t.capability})` : ""}`);
		}
		m = t.ok && (i.requireUnknownSendReconciliation === true || t.automaticUnknownSendReconciliation);
	}
	const h = i.retryAmbiguousFinalText === true && f.length === 1 && f[0]?.channelData !== void 0 ? (await resolveOutboundChannelMessageAdapter({
		cfg: i.cfg,
		agentId: i.session?.agentId,
		channel: o
	}))?.durableFinal?.isTextOnlyChannelData : void 0;
	const g = {
		...i,
		payloads: f,
		preparedBatch: d,
		retryAmbiguousFinalText: i.retryAmbiguousFinalText === true && isOrdinaryFinalText(f, h) ? true : void 0,
		renderedBatchPlan: p,
		...m ? { requireUnknownSendReconciliation: true } : {}
	};
	const _ = Boolean(i.deliveryIntentId || i.deliveryCompletion || i.completionRetention);
	const v = i.skipQueue || f.length === 0 && !_ ? null : await stageAndEnqueueOutboundDelivery(g, d, {
		claimForLiveDelivery: true,
		...r ? { getStablePreparation: r.current } : {}
	}).catch((e) => {
		if (isDeliveryRecoveryOwnedRetry(e)) throw e;
		if (l === "required" || collectNestedErrorCandidates(e).some((e) => e instanceof StableDeliveryPreparationLostError)) {
			emitPreQueueFailure();
			throw e;
		}
		log.warn(`outbound queue write failed; continuing without durability (channel=${i.channel} to=${i.to}): ${formatErrorMessage(e)}`);
		return null;
	});
	const y = v?.id ?? null;
	const b = y ? createQueuedDeliveryOwner({
		queueId: y,
		stateDir: i.deliveryQueueStateDir,
		expectedPlatformSendAttemptId: v?.producerClaimId
	}, i.deliveryQueueStateContext) : i.deliveryQueueOwner;
	g.deliveryQueueOwner = b;
	let x;
	try {
		if (v?.created && r) r.markPublished();
		if (y && b && i.deliveryCompletion) {
			if ((await markDurableDeliveryQueued(i.deliveryCompletion, y, v?.created ? "prepared" : void 0, i.deliveryQueueStateDir, i.deliveryQueueStateContext, i.conversationDeliveryTarget)).state !== "queued") {
				await b.ack({ suppressCompletionReceipt: true });
				return [];
			}
		}
		if (y) {
			emitOutboundAuditLifecycle({
				context: g,
				outcome: "queued",
				queueId: y,
				startedAt: a
			});
			i.onDeliveryIntent?.({
				id: y,
				channel: o,
				to: s,
				...i.accountId ? { accountId: i.accountId } : {},
				queuePolicy: l
			});
		}
		if (!y) return await deliverWithProducerLease(g, null, a, i.deliveryProducerClaimId, u || i.deliveryQueueId !== void 0 ? "unbound" : "captured");
		if (!v?.created && !i.reusePendingDeliveryIntent) throw new Error(`Stable delivery intent is already queued: ${y}`);
		const deliverClaimedIntent = async () => {
			const e = v?.producerClaimId ?? (i.reusePendingDeliveryIntent ? await claimReusableDeliveryPlatformSendAttempt(y, i.deliveryQueueStateDir, i.deliveryQueueStateContext) : void 0);
			if (!e) throw new Error(v?.created ? `Delivery platform claim was lost: ${y}` : `Stable delivery intent is already queued: ${y}`);
			if (b) b.claimId = e;
			let t = g;
			if (v?.created !== true) {
				const n = await loadPendingDelivery(y, i.deliveryQueueStateDir, i.deliveryQueueStateContext);
				if (!n || n.producerClaimId !== e) throw new Error(`Delivery platform claim was lost: ${y}`);
				t = restoreQueuedDeliveryCustody(g, n);
			}
			if (t.retryAmbiguousFinalText !== true) return await deliverWithProducerLease({
				...t,
				deliveryProducerLeaseRequired: true
			}, y, a, e, v?.created === true ? "captured" : "unbound");
			const n = [];
			let r;
			try {
				if ((await reserveDeliveryAttempt(y, 2, i.deliveryQueueStateDir, e, i.deliveryQueueStateContext)).status === "exhausted") throw new Error("delivery retry budget exhausted");
				const o = await deliverWithProducerLease({
					...t,
					deliveryProducerLeaseRequired: true,
					onPayloadDeliveryOutcome: (e) => n.push(e),
					onError: (e, t) => {
						r = [e, t];
					}
				}, y, a, e, v?.created === true ? "captured" : "unbound");
				for (const e of n) t.onPayloadDeliveryOutcome?.(e);
				if (r) t.onError?.(...r);
				return o;
			} catch (e) {
				const a = i.deliveryQueueStateContext ? await recoverLiveFinalDelivery({
					entryId: y,
					cfg: i.cfg,
					stateDir: i.deliveryQueueStateDir,
					log,
					shouldContinue: () => !i.abortSignal?.aborted,
					deliver: (e) => runOutboundDeliveryInternal({
						...e,
						deps: t.deps,
						abortSignal: t.abortSignal && e.abortSignal ? AbortSignal.any([t.abortSignal, e.abortSignal]) : t.abortSignal ?? e.abortSignal,
						assertDirectAdapterHandoff: () => {
							e.assertDirectAdapterHandoff?.();
							t.assertDirectAdapterHandoff?.();
						},
						onPlatformSendDispatch: async () => {
							await e.onPlatformSendDispatch?.();
							await t.onPlatformSendDispatch?.();
						},
						onError: (e, t) => {
							r = [e, t];
						}
					}, i.deliveryQueueStateContext)
				}, i.deliveryQueueStateContext) : { status: "not-attempted" };
				if (a.status !== "not-attempted") {
					n.length = 0;
					n.push(...a.payloadOutcomes);
				}
				for (const e of n) t.onPayloadDeliveryOutcome?.(e);
				if (a.status === "recovered") return a.results;
				if (r) t.onError?.(...r);
				if (a.status === "failed") {
					x = a.error;
					throw a.error;
				}
				throw e;
			}
		};
		if (n) return await deliverClaimedIntent();
		const e = await withActiveDeliveryClaim(y, deliverClaimedIntent);
		if (e.status === "claimed") return e.value;
		if (i.reusePendingDeliveryIntent) return [];
		throw new Error(`Delivery intent is already claimed: ${y}`);
	} catch (e) {
		if (x !== void 0 && e === x) throw e;
		throw b ? b.project(e, { sentBeforeError: u?.recoveryState === "send_attempt_started" || u?.recoveryState === "unknown_after_send" }) : e;
	}
}
//#endregion
export { stageAndEnqueueOutboundDelivery as i, runOutboundDeliveryInternal as n, runStructuredOutboundDeliveryInternal as r, runOutboundDelivery as t };