openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,525 lines • 58.2 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { t as sleep } from "./sleep-CkI3nkiJ.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { A as normalizeSessionPeerId, E as parseSessionDeliveryRoute, g as toAgentStoreSessionKey } from "./session-key-CqAyZeVk.mjs";
import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { _ as resolveDefaultAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { a as resolveDeliveryQueueAttemptCount } from "./delivery-queue-sqlite.types-B7uW265Q.mjs";
import { t as getChannelPlugin } from "./registry-ByqVE5S3.mjs";
import { n as runWithoutOwnedSessionTranscriptWrites } from "./transcript-write-context-store-kFqld1UQ.mjs";
import { n as deliveryContextKey } from "./delivery-context.shared-CRlipPTj.mjs";
import { i as hasReplyChannelData } from "./payload-Cab4FCxl.mjs";
import { t as deliveryContextFromSession } from "./delivery-context.read-BrYAJ7RK.mjs";
import "./plugins-BoMiRtiY.mjs";
import { n as stripOutboundTargetKindPrefix, r as stripTargetProviderPrefix, t as resolveTargetPrefixedChannel } from "./channel-target-prefix-tRLuyxKs.mjs";
import { d as readSessionEntryInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { i as logWarn } from "./logger-CIwfuhOU.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { p as fireAndForgetHook } from "./hooks-BiZpB_10.mjs";
import { c as triggerInternalHook, n as createInternalHookEvent } from "./internal-hooks-D6nf-Q3g.mjs";
import { t as parseCommandOwnerReference } from "./user-channel-authorization-reference-CAWzJwx-.mjs";
import { n as GatewayOperatorAccessDeniedError } from "./operator-access-policy-BWvd6twL.mjs";
import { r as prepareCommandOwnerAuthority } from "./command-auth-CC1Z19Eh.mjs";
import { i as isSessionDeliveryGenerationRevokedError, n as prepareSessionDeliveryGeneration } from "./session-delivery-generation-CUS9yuZM.mjs";
import { a as countPhysicalOutboundSends, i as areOutboundPayloadsIntentionallySuppressed, n as OutboundDeliveryError, o as isOutboundDeliveryAdmissionClosedError, r as PlatformMessageNotDispatchedError, s as isOutboundDeliveryError, t as OutboundDeliveryAdmissionClosedError } from "./deliver-types-BnSKrpHG.mjs";
import { a as getErrnoCode, c as isDeliveryRecoveryRetryEligible, d as resolveDeliveryNotSentRetryability, f as resolveDeliveryRecoveryDeadlineMs, i as findPlatformMessageRejectedError, l as isProvenDeliveryNotSentError, n as createDeliveryRecoveryCoordinator, o as isAmbiguousDeliveryTransportError, r as createEmptyDeliveryRecoverySummary } from "./delivery-recovery.shared-3Nb7FEaL.mjs";
import { d as summarizeOutboundPayloadForTransport } from "./payloads-CQvywZOF.mjs";
import { s as resolveCurrentConversationByDelivery } from "./conversation-registry-DTUa0zh7.mjs";
import { n as resolveDeliveryQueueStateEnv, t as captureDeliveryQueueStateContext } from "./delivery-queue-state-context-Cxp-xMAQ.mjs";
import "./delivery-queue-sqlite-lyIJZlO0.mjs";
import { a as settleDurableDelivery, n as completeDurableDelivery, r as markDurableDeliveryQueued } from "./delivery-completion-DkLj6KUt.mjs";
import { d as toPluginMessageSentEvent, l as toPluginMessageContext, o as toInternalMessageSentContext, t as buildCanonicalSentMessageHookContext } from "./message-hook-mappers-BCrhfgqk.mjs";
import { n as collectEntrySpoolPaths } from "./delivery-queue-media-paths-Bhk9Ljz0.mjs";
import "./deliver-payload-CXD-N8EQ.mjs";
import { o as resolveAgentRoute } from "./resolve-route-DBnTWpM6.mjs";
import { t as buildChannelAccountKey } from "./session-binding-normalization-c5CMRfx2.mjs";
import { n as hasTrustedMessageAuditListeners, t as emitTrustedMessageAuditEvent } from "./message-audit-events-Byfl_35A.mjs";
import { i as prepareSessionWriterDeliveryAuthority, t as assertSessionWriterDeliveryAuthorized } from "./session-writer-delivery-authority-DNB-b5xs.mjs";
import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs";
import { n as resolveOutboundChannelMessageAdapter } from "./channel-resolution-DjtSMYUG.mjs";
import { a as canReplayAmbiguousFinalText, c as recoveryPlatformAttemptId, d as shouldInspectQueuedDelivery, h as OutboundHandoffRejectedError, i as reconcileUnknownQueuedDelivery, l as resolveMaxRetries, m as runOutboundDeliveryCommitHooks, n as buildUnknownSendContext, p as isOutboundDeliveryResultArray, r as needsUnknownSendReconciliation, s as isPermanentDeliveryError, t as buildReconciledSentResult, u as resolveUnknownSendReplay } from "./delivery-queue-reconciliation-CQDy7zg8.mjs";
import { a as acceptedPreparedOutboundEntries, i as projectQueuedDeliveryOptions, l as preparedOutboundPayloads } from "./delivery-queue-projection-BhmCxxmH.mjs";
import { a as createDeliveryQueueMediaRetention, i as cancelDeliveryQueueMediaRetention, n as releaseSpoolArtifacts } from "./delivery-queue-media-spool-ys6bmM17.mjs";
import { D as ackDelivery, S as claimDeliveryPlatformSendAttempt, a as failDeliveryAfterPlatformSend, b as restoreDeliveryAttemptBeforeDispatch, g as markDeliveryPlatformSendAttemptStarted, h as markDeliveryPlatformOutcomeUnknown, i as failDelivery, k as retireUnsentDelivery, m as loadUnfinishedDelivery, o as failDeliveryBeforePlatformSend, p as loadUnfinishedDeliveries, s as finalizeDeliveryFailureSettlement, u as loadPendingDelivery, v as moveToFailed, x as stageDeliveryFailureSettlement, y as reserveDeliveryAttempt } from "./delivery-queue-storage-BLAjpQqf.mjs";
import { a as resolveOutboundSessionRoute, t as bindOutboundSessionEntry } from "./outbound-session-BGK8YYPT.mjs";
import { t as commitBackgroundPayloadsToSession } from "./background-result-payloads-DpQ26rEd.mjs";
//#region src/infra/outbound/deferred-delivery-admission.ts
async function prepareDeferredDeliveryAdmission(e, t) {
const n = await resolveOutboundChannelMessageAdapter({
channel: e.channel,
cfg: e.cfg,
agentId: t?.agentId,
allowBootstrap: true,
assertCurrent: t?.assertCurrent
});
return () => {
t?.assertCurrent?.();
return n?.durableFinal?.admitDeferredDelivery?.(e) ?? { status: "allowed" };
};
}
//#endregion
//#region src/infra/outbound/deliver-log.ts
const OUTBOUND_DELIVERY_LOG_SCOPE = ["deliver", "OutboundPayloads"].join("");
//#endregion
//#region src/sessions/confirmed-visible-message.ts
const skipped = (e) => ({
ok: true,
skipped: true,
...e ? { diagnostics: e } : {}
});
/** Commits only confirmed external output; a producing conversation already owns its own turn. */
async function commitConfirmedVisibleMessage(e) {
if (e.stateDir !== void 0 && resolveStateDir(process.env) !== e.stateDir) return skipped("state root changed after the delivery began");
const t = e.producer?.agentId ?? resolveDefaultAgentId(e.config);
const n = resolveSessionStorePathCore(e.config.session?.store, { agentId: t });
const toStoreKey = (n) => toAgentStoreSessionKey({
agentId: t,
requestKey: n,
mainKey: e.config.session?.mainKey
});
const r = e.producer?.key ? toStoreKey(e.producer.key) : void 0;
if (e.route && r === toStoreKey(e.route.sessionKey)) return skipped();
const i = await createProducerMatcher({
params: e,
producerKey: r,
storePath: n
});
if (i(e.route?.to ?? e.to, e.route?.threadId ?? e.threadId)) return skipped();
const a = await resolveConfirmedDestination({
params: e,
agentId: t,
storePath: n
});
if ("skip" in a) return skipped(a.skip);
const { destination: o, route: s } = a;
if (!belongsToAgent(e, o, t)) return skipped("Conversation context skipped: the destination belongs to a different agent.");
const c = toStoreKey(o.sessionKey);
if (r === c || s && i(s.to, s.threadId ?? e.threadId)) return skipped();
if (!hasRecordablePayload(e.payload)) return skipped(hasReplyChannelData(e.payload.channelData) ? "native-only payload not added to conversation" : void 0);
e.assertCurrent?.();
if (s) await bindOutboundSessionEntry({
cfg: e.config,
channel: e.channel,
accountId: e.accountId,
route: s,
sourceSessionKey: r,
workerGuard: { assertMutationAllowed: () => e.assertCurrent?.() }
});
if (!await readSessionEntryInWorker({
agentId: t,
sessionKey: c,
storePath: n,
readConsistency: "latest"
})) return {
ok: false,
reason: "destination conversation is unavailable"
};
return await runWithoutOwnedSessionTranscriptWrites(() => commitBackgroundPayloadsToSession({
agentId: t,
sessionKey: c,
payloads: [e.payload],
idempotencyKey: `outbound-delivery:${e.deliveryId}:${e.payloadIndex}`,
provenance: e.provenance,
config: e.config,
signal: e.signal,
assertCurrent: e.assertCurrent
}));
}
async function createProducerMatcher(e) {
const { params: t, producerKey: n } = e;
if (!n) return () => false;
const r = await readSessionEntryInWorker({
sessionKey: n,
storePath: e.storePath,
readConsistency: "latest"
});
const i = deliveryContextFromSession(r);
const a = deliveryContextKey({
...i,
accountId: normalizeAccountId(i?.accountId)
});
return (e, n) => {
const r = deliveryContextKey({
channel: t.channel,
to: e,
accountId: normalizeAccountId(t.accountId),
threadId: n ?? void 0
});
return Boolean(r && r === a);
};
}
async function resolveConfirmedDestination(e) {
const { params: t, agentId: n, storePath: r } = e;
if (t.route) return {
destination: t.route,
route: t.route
};
const i = await resolvePinnedDestination(t, n, r);
if (i) return {
destination: i,
route: t.route
};
const a = await resolveCurrentConversationByDelivery({
agentId: n,
storePath: r
}, {
channel: t.channel,
accountId: normalizeAccountId(t.accountId),
target: t.to.trim(),
threadId: t.threadId == null ? void 0 : String(t.threadId)
});
if (a.ambiguous) {
logWarn("Conversation context lookup is ambiguous: multiple current destinations match.");
return { skip: "Conversation context skipped: multiple current destinations match." };
}
const o = a.conversation;
if (o?.sessionKey) return {
destination: {
sessionKey: o.sessionKey,
peer: {
kind: o.kind,
id: o.peerId
}
},
route: t.route
};
const s = t.route === null ? null : await resolveOutboundSessionRoute({
cfg: t.config,
channel: t.channel,
agentId: n,
accountId: t.accountId,
target: t.to,
threadId: t.threadId,
assertDirectAdapterHandoff: t.assertDirectAdapterHandoff
});
return s ? {
destination: s,
route: s
} : { skip: "Conversation context skipped: destination conversation could not be resolved without a network lookup." };
}
async function resolvePinnedDestination(e, t, n) {
const r = e.expectedGeneration?.sessionKey;
if (!r) return;
const i = toAgentStoreSessionKey({
agentId: t,
requestKey: r,
mainKey: e.config.session?.mainKey
});
const a = await readSessionEntryInWorker({
sessionKey: i,
storePath: n,
readConsistency: "latest"
});
const o = deliveryContextFromSession(a);
if (o?.channel !== e.channel) return;
const s = deliveryAddressKey(e.channel, o);
const c = deliveryAddressKey(e.channel, {
to: e.to,
accountId: e.accountId,
threadId: e.threadId ?? void 0
});
return s && s === c ? { sessionKey: i } : void 0;
}
function deliveryAddressKey(e, t) {
if (!t?.to) return;
return deliveryContextKey({
channel: e,
to: t.to.trim(),
accountId: normalizeAccountId(t.accountId),
threadId: t.threadId ?? void 0
});
}
function belongsToAgent(e, t, n) {
return normalizeAgentId(resolveAgentRoute({
cfg: e.config,
channel: e.channel,
defaultAgentId: n,
accountId: e.accountId,
peer: t.peer
}).agentId) === normalizeAgentId(n);
}
function hasRecordablePayload(e) {
return Boolean(normalizeOptionalString(e.text) || normalizeOptionalString(e.spokenText) || e.mediaUrl || e.mediaUrls?.length || e.location);
}
//#endregion
//#region src/infra/outbound/deliver-queue-state.ts
const log$1 = createSubsystemLogger("outbound/deliver");
/** Keeps live and recovered queue transitions on the same producer claim. */
function createQueuedDeliveryOwner(e, t) {
let n = "held";
const r = {
queueId: e.queueId,
stateDir: t?.stateDir ?? e.stateDir,
claimId: e.expectedPlatformSendAttemptId,
signal: e.signal,
get custody() {
return n;
},
project(e, t) {
const r = e instanceof OutboundDeliveryError ? e : new OutboundDeliveryError(formatErrorMessage(e), {
cause: e,
...t
});
r.queueCustody = n;
return r;
},
async retireUnsent(e) {
r.signal?.throwIfAborted();
if (!r.claimId) return;
const i = await retireUnsentDelivery({
id: r.queueId,
producerClaimId: r.claimId,
stateDir: r.stateDir
}, t, e);
if (i) n = "released";
return i;
},
async ack(e) {
r.signal?.throwIfAborted();
await ackDelivery(r.queueId, r.stateDir, {
...e,
...r.claimId !== void 0 ? { expectedPlatformSendAttemptId: r.claimId } : {}
}, t);
n = "released";
},
async finalizeFailure(e) {
if (e.id !== r.queueId || !await finalizeDeliveryFailureSettlement(e, r.stateDir, t)) return false;
n = "released";
return true;
},
fail(e, n, i) {
r.signal?.throwIfAborted();
const a = [
failDelivery,
failDeliveryAfterPlatformSend,
failDeliveryBeforePlatformSend
].find((t) => t === e);
return a ? a(r.queueId, n, r.stateDir, r.claimId, t, i) : e(r.queueId, n, r.stateDir, r.claimId);
},
async retire() {
r.signal?.throwIfAborted();
const e = await moveToFailed(r.queueId, r.stateDir, r.claimId ?? null, t);
n = "released";
await releaseSpoolArtifacts(e, r.stateDir);
}
};
return r;
}
function findTerminalBatchRejection(e) {
if (e.length === 0 || !e.every(isProvenDeliveryNotSentError)) return;
return e.find((e) => e instanceof OutboundHandoffRejectedError) ?? (e.every((e) => resolveDeliveryNotSentRetryability(e) === false) ? findPlatformMessageRejectedError(e[0]) : void 0);
}
function isProvenBatchNotSent(e, t) {
return isProvenDeliveryNotSentError(e) && t.every((e) => e.status === "failed" ? !e.sentBeforeError && isProvenDeliveryNotSentError(e.error) : e.status === "suppressed" && e.reason !== "adapter_returned_no_identity");
}
async function rejectQueuedDelivery(e, t, n, r) {
try {
e.signal?.throwIfAborted();
const i = await loadPendingDelivery(e.queueId, e.stateDir, n.deliveryQueueStateContext);
if (!i || !e.claimId) return false;
let a;
try {
a = await stageDeliveryFailureSettlement(i, {
outcome: "failed",
error: t.message,
rejectionError: t.message,
terminals: r
}, e.stateDir, e.claimId, n.deliveryQueueStateContext);
} catch (t) {
const n = await e.retireUnsent("failed");
if (!n) throw t;
await n();
return true;
}
if (!a) return false;
if (a.deliveryCompletion) await settleDurableDelivery(a.deliveryCompletion, { rejectionError: t.message }, e.stateDir, n.deliveryQueueStateContext, n.conversationDeliveryTarget);
const o = collectEntrySpoolPaths(preparedOutboundPayloads(a.preparedBatch), e.stateDir);
if (!await e.finalizeFailure(a)) return false;
await releaseSpoolArtifacts(o, e.stateDir);
} catch (t) {
log$1.warn(`failed to finalize permanently rejected delivery ${e.queueId}: ${formatErrorMessage(t)}`);
}
return e.custody === "released";
}
async function persistQueuedPreSendState(e, t) {
const { owner: n } = e;
n.signal?.throwIfAborted();
try {
await markDeliveryPlatformSendAttemptStarted(n.queueId, n.stateDir, { replyToId: e.route.replyToId ?? null }, n.claimId || void 0, t);
return "marked";
} catch (t) {
if (e.queuePolicy === "required") throw t;
log$1.warn(`failed to mark queued delivery ${n.queueId} as platform-send-attempt-started; removing replay intent before best-effort send: ${formatErrorMessage(t)}`);
await n.ack(e.retainSpoolArtifacts ? { retainSpoolArtifacts: true } : void 0);
return "acked";
}
}
async function persistQueuedPostSendState(e, t) {
const { owner: n } = e;
n.signal?.throwIfAborted();
try {
await markDeliveryPlatformOutcomeUnknown(n.queueId, n.stateDir, n.claimId, t);
return "marked";
} catch (t) {
if (e.preserveBatch) {
await n.fail(failDeliveryAfterPlatformSend, `post-send state persistence failed: ${formatErrorMessage(t)}`);
return "failed";
}
e.onPostSendMarkerError?.(t);
log$1.warn(`failed to mark queued delivery ${n.queueId} as platform-outcome-unknown; falling back to direct ack (${e.queuePolicy}): ${formatErrorMessage(t)}`);
try {
await n.ack(e.retainSpoolArtifacts ? { retainSpoolArtifacts: true } : void 0);
return "acked";
} catch (e) {
const r = `post-send state persistence failed: marker=${formatErrorMessage(t)}; ack=${formatErrorMessage(e)}`;
await n.fail(failDeliveryAfterPlatformSend, r);
return "failed";
}
}
}
//#endregion
//#region src/infra/outbound/delivery-generation.ts
/** Translate session-owner decisions into the existing queue retry/terminal contract. */
async function prepareOutboundDeliveryGeneration(e) {
const notDispatched = (e) => {
throw new PlatformMessageNotDispatchedError(e instanceof Error ? e.message : "Session delivery generation is unavailable", {
cause: e,
retryable: !isSessionDeliveryGenerationRevokedError(e)
});
};
const t = await prepareSessionDeliveryGeneration(e).catch(notDispatched);
return {
assertCurrent() {
try {
t.assertCurrent();
} catch (e) {
notDispatched(e);
}
},
release: t.release
};
}
//#endregion
//#region src/infra/outbound/message-sent-hook.ts
const log = createSubsystemLogger("outbound/message-sent-hook");
/** Creates a best-effort emitter shared by direct and inbound-turn delivery owners. */
function createMessageSentEmitter(e) {
const t = e.hookRunner?.hasHooks("message_sent") ?? false;
const n = Boolean(e.sessionKeyForInternalHooks);
const warn = (e) => log.warn(e);
const emitMessageSent = (r) => {
if (!t && !n) return;
const i = buildCanonicalSentMessageHookContext({
to: e.to,
content: r.content,
success: r.success,
error: r.error,
channelId: e.channel,
accountId: e.accountId,
conversationId: e.to,
sessionKey: e.sessionKeyForInternalHooks,
runId: e.runId,
messageId: r.messageId,
isGroup: e.isGroup,
groupId: e.groupId
});
if (t) fireAndForgetHook(e.hookRunner.runMessageSent(toPluginMessageSentEvent(i), toPluginMessageContext(i)), `${e.logPrefix}: message_sent plugin hook failed`, warn);
if (!n) return;
fireAndForgetHook(triggerInternalHook(createInternalHookEvent("message", "sent", e.sessionKeyForInternalHooks, toInternalMessageSentContext(i))), `${e.logPrefix}: message:sent internal hook failed`, warn);
};
return {
emitMessageSent,
hasMessageSentHooks: t
};
}
/** Bind outbound hook correlation to the accepted delivery's runtime session. */
function createOutboundMessageSentEmitter(e, t) {
const n = e.session?.key;
return {
...createMessageSentEmitter({
hookRunner: getGlobalHookRunner(),
channel: e.channel,
to: e.to,
accountId: e.accountId,
sessionKeyForInternalHooks: n,
isGroup: e.session?.conversationType === "group",
runId: e.preparedBatch?.runId,
logPrefix: t
}),
sessionKeyForInternalHooks: n
};
}
//#endregion
//#region src/infra/outbound/outbound-audit.ts
function outboundQueueAuditSourceId(e, t, n) {
const r = `message:outbound:queue:${e}:payload:${t}`;
return n ? `${r}:${n}` : r;
}
function projectRecordedOutboundAuditTerminal(e) {
if (e.some((e) => e.status === "suppressed" && e.reason === "adapter_returned_no_identity")) return {
outcome: "unknown",
failureStage: "platform_send"
};
const t = e.at(-1);
if (t?.status === "sent") return {
outcome: "sent",
results: t.results,
...t.deliveryKind ? { deliveryKind: t.deliveryKind } : {}
};
if (t?.status === "suppressed" && t.reason !== "adapter_returned_no_identity") return {
outcome: "suppressed",
reasonCode: t.reason === "adapter_returned_no_send" ? "no_visible_payload" : t.reason
};
}
function projectOutboundAuditTerminals(e, t) {
const n = /* @__PURE__ */ new Map();
for (const t of e.payloadOutcomes) {
const e = n.get(t.index) ?? [];
e.push(t);
n.set(t.index, e);
}
return Array.from({ length: e.payloadCount }, (e, r) => {
const i = n.get(r) ?? [];
return {
payloadIndex: r,
terminal: projectRecordedOutboundAuditTerminal(i) ?? t(i)
};
});
}
function completedOutboundAuditTerminals(e) {
return projectOutboundAuditTerminals(e, () => {
if (e.payloadCount === 1 && e.results.length > 0) return {
outcome: "sent",
results: e.results
};
return {
outcome: "suppressed",
reasonCode: "no_visible_payload"
};
});
}
function failedOutboundAuditTerminals(e) {
return projectOutboundAuditTerminals(e, (t) => {
const n = t.at(-1);
const r = n?.status === "failed" ? n : void 0;
const i = r?.results ?? [];
const a = i.length > 0 ? i : t.findLast((e) => e.status === "sent")?.results ?? [];
const o = e.payloadCount === 1 ? e.results : [];
const s = a.length > 0 ? a : o;
return {
outcome: "failed",
failureStage: r ? r.stage : e.failureStage,
results: s,
sentBeforeError: s.length > 0 || r !== void 0 && r.sentBeforeError,
...r?.deliveryKind ? { deliveryKind: r.deliveryKind } : {}
};
});
}
function uniformOutboundAuditTerminals(e, t) {
return Array.from({ length: e }, (e, n) => ({
payloadIndex: n,
terminal: t
}));
}
const TARGET_KIND_TO_ROUTE_KINDS = {
channel: ["channel"],
conversation: ["channel"],
thread: ["channel"],
group: ["group"],
room: ["group"],
direct: ["direct", "dm"],
dm: ["direct", "dm"],
user: ["direct", "dm"]
};
const TARGET_PREFIX_RE = /^\s*([a-z][a-z0-9_-]*):/i;
function resolveOutboundTargetFacts(e) {
const t = e.channel.toLowerCase();
const n = resolveTargetPrefixedChannel(e.to);
const r = TARGET_PREFIX_RE.exec(e.to)?.[1];
const i = n === t ? [e.channel, r ?? e.channel] : [e.channel];
const a = stripTargetProviderPrefix(e.to, ...i);
const o = TARGET_PREFIX_RE.exec(a)?.[1]?.toLowerCase();
const s = o && Object.hasOwn(TARGET_KIND_TO_ROUTE_KINDS, o) ? TARGET_KIND_TO_ROUTE_KINDS[o] : void 0;
return {
conversationId: stripOutboundTargetKindPrefix(a, Object.keys(TARGET_KIND_TO_ROUTE_KINDS)),
withoutProvider: a,
allowedRouteKinds: s
};
}
/** True when a parsed session route provably names this delivery's destination. */
function routeNamesDestination(e, t) {
if (!e || e.channel !== t.channel.toLowerCase()) return false;
const { conversationId: n, withoutProvider: r, allowedRouteKinds: i } = resolveOutboundTargetFacts(t);
if (i && !i.includes(e.peerKind)) return false;
return [
t.to,
r,
n
].some((t) => {
const n = normalizeSessionPeerId({
channel: e.channel,
peerKind: e.peerKind,
peerId: t
});
return n !== "" && n.toLowerCase() === e.peerId.toLowerCase();
});
}
function resolveConversationKind(e) {
if (e.session?.conversationKind) return e.session.conversationKind;
const t = [e.session?.policyKey, e.session?.key];
for (const n of t) {
const t = parseSessionDeliveryRoute(n);
if (routeNamesDestination(t, e)) return t.peerKind === "dm" || t.peerKind === "direct" ? "direct" : t.peerKind;
}
if (e.session?.conversationType === "group") return "group";
return "unknown";
}
function firstIdentifier(...e) {
for (const t of e) {
const e = t?.trim();
if (e && e !== "unknown" && e !== "suppressed") return e;
}
}
function resolveResultIdentifiers(e, t) {
const n = t.at(-1);
const r = firstIdentifier(n?.target?.id, n?.toJid) ?? resolveOutboundTargetFacts(e).conversationId;
const i = firstIdentifier(n?.messageId, n?.receipt?.primaryPlatformMessageId, n?.receipt?.platformMessageIds.at(-1));
return {
...r ? { conversationId: r } : {},
...i ? { messageId: i } : {}
};
}
function outboundAuditContext(e, t = false) {
const n = e.session?.agentId;
const r = e.runId ?? e.preparedBatch?.runId ?? (t ? e.replyPayloadSendingHook?.runId : void 0);
return {
actorType: n ? "agent" : "system",
actorId: n ?? "gateway",
...n ? { agentId: n } : {},
...e.preparedBatch?.executionIdentityToken ? { executionIdentityToken: e.preparedBatch.executionIdentityToken } : {},
direction: "outbound",
channel: e.channel,
conversationKind: resolveConversationKind(e),
...e.accountId ? { accountId: e.accountId } : {},
targetId: e.to,
...r ? { runId: r } : {}
};
}
/**
* Emits only after the owning lifecycle has made the delivery terminal.
* Queue retries share one source id, so recovery cannot duplicate the final row.
*/
function emitOutboundAuditTerminal(e) {
try {
const { context: t, terminal: n } = e;
const r = n.results ?? [];
const i = resolveResultIdentifiers(t, r);
const a = (n.outcome === "failed" || n.outcome === "unknown") && n.sentBeforeError === true;
const o = n.outcome === "sent" ? {
status: "succeeded",
outcome: "sent",
...n.deliveryKind ? { deliveryKind: n.deliveryKind } : {}
} : n.outcome === "suppressed" ? {
status: "blocked",
outcome: "suppressed",
reasonCode: n.reasonCode
} : n.outcome === "unknown" ? {
status: "unknown",
outcome: "unknown",
failureStage: n.failureStage
} : {
status: "failed",
outcome: "failed",
errorCode: r.length > 0 || a ? "message_delivery_partial_failure" : "message_delivery_failed",
failureStage: n.failureStage,
...n.deliveryKind ? { deliveryKind: n.deliveryKind } : {}
};
emitTrustedMessageAuditEvent({
...e.sourceId ? { sourceId: e.sourceId } : {},
kind: "message",
action: "message.outbound.finished",
occurredAt: Date.now(),
...o,
...outboundAuditContext(t, true),
durationMs: Math.max(0, Date.now() - e.startedAt),
resultCount: countPhysicalOutboundSends(r),
...i
});
} catch {}
}
/** Emits a replay-safe owner-native receipt after the queue transition commits. */
function emitOutboundAuditLifecycle(e) {
if (!hasTrustedMessageAuditListeners()) return;
const t = e.context.preparedBatch?.sourcePayloadCount ?? 1;
const n = e.payloadIndexes ?? Array.from({ length: t }, (e, t) => t);
try {
for (const r of n) {
if (!Number.isSafeInteger(r) || r < 0 || r >= t) continue;
emitTrustedMessageAuditEvent({
sourceId: outboundQueueAuditSourceId(e.queueId, r, e.outcome),
occurredAt: Date.now(),
status: "started",
...outboundAuditContext(e.context),
durationMs: Math.max(0, Date.now() - e.startedAt),
resultCount: 0,
kind: "message",
...e.outcome === "queued" ? {
action: "message.outbound.queued",
outcome: "queued"
} : {
action: "message.outbound.platform-started",
outcome: "platform_started"
}
});
}
} catch {}
}
/** Emits only after the owning lifecycle has made each logical payload terminal. */
function emitOutboundAuditTerminals(e) {
if (!hasTrustedMessageAuditListeners()) return;
let t;
try {
t = typeof e.terminals === "function" ? e.terminals() : e.terminals;
} catch {
return;
}
for (const n of t) emitOutboundAuditTerminal({
context: e.context,
terminal: n.terminal,
startedAt: e.startedAt,
...e.queueId ? { sourceId: outboundQueueAuditSourceId(e.queueId, n.payloadIndex) } : {}
});
}
//#endregion
//#region src/infra/outbound/delivery-queue-recovery-coordinator.ts
const recoveryCoordinator = createDeliveryRecoveryCoordinator({ maxConcurrentLanes: 4 });
function recoveryLaneKey(e, t, n) {
const r = getChannelPlugin(e.channel);
const i = e.accountId?.trim() || (r ? resolveChannelDefaultAccountId({
plugin: r,
cfg: t
}) : "default");
return JSON.stringify([n, buildChannelAccountKey({
channel: r?.id ?? e.channel,
accountId: i
})]);
}
//#endregion
//#region src/infra/outbound/delivery-queue-recovery-params.ts
async function buildRecoveryDeliverParams(e, t, n, r, i) {
const a = e.deliveryCompletion?.kind === "conversation" ? e.deliveryCompletion : void 0;
const o = e.deliveryCompletion?.kind === "pending-final" ? e.deliveryCompletion : void 0;
let s;
const rejection = (e) => new PlatformMessageNotDispatchedError("Original channel owner authorization could not be checked", {
cause: e,
retryable: !(e instanceof GatewayOperatorAccessDeniedError)
});
if (o?.commandOwnerReference !== void 0) {
const e = parseCommandOwnerReference(o.commandOwnerReference);
if (!e) throw rejection(new GatewayOperatorAccessDeniedError());
try {
s = await prepareCommandOwnerAuthority(t, e, { env: resolveDeliveryQueueStateEnv(n, i) });
} catch (e) {
throw new PlatformMessageNotDispatchedError("Original channel owner preparation interrupted", { cause: e });
}
if (!s.source) throw rejection(new GatewayOperatorAccessDeniedError());
}
const c = await prepareSessionWriterDeliveryAuthority(o?.sessionWriterDeliveryAuthority, o?.storePath, resolveDeliveryQueueStateEnv(n, i));
const assertCurrent = () => {
try {
if (o?.commandOwnerReference !== void 0 && !s?.isCurrent(t)) throw new Error("Original channel owner capture changed during delivery");
} catch (e) {
throw rejection(e);
}
assertSessionWriterDeliveryAuthorized(c.authority);
};
return {
release: c.release,
cfg: t,
...projectQueuedDeliveryOptions(e),
...e.queuePolicy !== void 0 ? { queuePolicy: e.queuePolicy } : {},
...e.requireUnknownSendReconciliation === true ? { requireUnknownSendReconciliation: true } : {},
payloads: preparedOutboundPayloads(e.preparedBatch),
preparedBatch: e.preparedBatch,
reply: e.reply,
...a ? { conversationDeliveryAttemptAuthority: {
agentId: a.agentId,
operationId: a.operationId,
...a.storePath ? { storePath: a.storePath } : {},
...a.routeFingerprint ? { routeFingerprint: a.routeFingerprint } : {}
} } : {},
...o ? {
onDirectAdapterHandoff: async () => assertCurrent(),
assertDirectAdapterHandoff: assertCurrent,
onPlatformSendDispatch: async () => assertCurrent()
} : {},
deliveryQueueId: e.id,
deliveryQueueStateDir: n,
...r ? { deliveryProducerClaimId: r } : {},
...e.requiresProducerClaim === true ? { deliveryProducerLeaseRequired: true } : {},
skipQueue: true,
deferredDeliveryAdmissionPassed: true,
deferCommitHooks: true
};
}
//#endregion
//#region src/infra/outbound/delivery-queue-transcript.ts
/**
* Records a delivery confirmed during recovery, only when one accepted text payload
* proves exactly what was shown. Anything else warns instead of guessing.
*/
async function commitRecoveredVisibleMessages(e, t) {
const { entry: n } = e;
const r = acceptedPreparedOutboundEntries(n.preparedBatch);
const i = r[0];
const a = n.renderedBatchPlan?.items[0];
if (n.legacyPreparedContentUnavailable || n.preparedBatch.channelNormalized !== true || r.length !== 1 || !i || !i.payload.text?.trim() || n.renderedBatchPlan?.items.length !== 1 || !a || a.index !== 0 || a.mediaUrls.length > 0 || a.kinds.length !== 1 || a.kinds[0] !== "text") {
e.log.warn(`Delivery entry ${n.id}: delivered during recovery; content could not be confirmed for the conversation`);
return;
}
try {
const r = await commitConfirmedVisibleMessage({
config: e.cfg,
channel: n.channel,
to: n.to,
accountId: n.accountId,
threadId: n.threadId,
producer: n.session,
provenance: n.transcriptProvenance,
expectedGeneration: n.sessionGeneration ? { sessionKey: n.sessionGeneration.sessionKey } : void 0,
payload: { text: i.payload.text },
deliveryId: n.id,
payloadIndex: i.sourceIndex,
assertCurrent: () => t.workerContext.admission.assertCurrent(),
assertDirectAdapterHandoff: () => t.workerContext.admission.assertCurrent(),
stateDir: t.stateDir
});
const a = r.ok ? r.diagnostics : r.reason;
if (a) e.log.warn(`Delivery entry ${n.id} confirmed transcript: ${a}`);
} catch (t) {
e.log.warn(`Delivery entry ${n.id} confirmed transcript commit failed: ${formatErrorMessage(t)}`);
}
}
//#endregion
//#region src/infra/outbound/delivery-queue-recovery.ts
const withActiveDeliveryClaim = recoveryCoordinator.withClaim;
function emitRecoveredMessageSentEvents(e, t) {
const { emitMessageSent: n } = createOutboundMessageSentEmitter(e, OUTBOUND_DELIVERY_LOG_SCOPE);
for (const e of t) n(e);
}
function emitRecoveredTerminalEvents(e, t) {
if (e.legacyPreparedContentUnavailable) return;
const n = "error" in t ? new Map((t.collected ?? []).map(({ sourceIndex: e, event: t }) => [e, t])) : void 0;
const r = acceptedPreparedOutboundEntries(e.preparedBatch);
let i = [];
if ("result" in t) {
if (r.length === 0) return;
const { result: e } = t;
const n = e.receipt?.parts.length ? e.receipt.parts.toSorted((e, t) => e.index - t.index).map((e) => e.platformMessageId) : e.receipt?.platformMessageIds;
i = r.length === 1 ? [e.messageId || n?.[0]] : n?.length === r.length ? n : [];
}
emitRecoveredMessageSentEvents(e, r.map((e, r) => {
const a = summarizeOutboundPayloadForTransport(e.payload);
const o = a.hookContent ?? a.text;
if ("error" in t) return n?.get(e.sourceIndex) ?? {
success: false,
content: o,
error: t.error
};
const s = i[r];
const c = {
success: true,
content: o
};
if (s) c.messageId = s;
return c;
}));
}
function emitQueuedAuditTerminals(e, t) {
emitOutboundAuditTerminals({
context: e,
terminals: t,
startedAt: e.enqueuedAt,
queueId: e.id
});
}
function emitQueuedDeliveryResults(e, t, n = [], r) {
emitQueuedAuditTerminals(e, () => {
const i = {
payloadCount: e.preparedBatch.sourcePayloadCount,
results: t,
payloadOutcomes: n
};
return r === void 0 ? completedOutboundAuditTerminals(i) : failedOutboundAuditTerminals({
...i,
failureStage: r()
});
});
}
async function recordRecoveryFailure(e, t, n = failDelivery) {
try {
await e.fail(n, t);
} catch (e) {
if (getErrnoCode(e) === "ENOENT") return "already-gone";
}
return "failed";
}
async function settleQueuedFailure(e, t) {
let n = false;
try {
const r = needsUnknownSendReconciliation(e.entry);
const i = e.entry.settlement ?? {
error: e.error,
...e.terminals ? { terminals: e.terminals } : {},
...r ? { unknownSendCleanup: true } : {},
...e.rejectionError !== void 0 ? {
outcome: "failed",
rejectionError: e.rejectionError
} : { outcome: r ? "unknown" : "failed" }
};
const a = await stageDeliveryFailureSettlement(e.entry, i, e.stateDir, e.claimedAttemptId, t);
if (!a) return "already-gone";
if (a.deliveryCompletion) await settleDurableDelivery(a.deliveryCompletion, i.outcome === "failed" && i.rejectionError !== void 0 ? { rejectionError: i.rejectionError } : { platformSendStarted: true }, e.stateDir, t);
const o = collectEntrySpoolPaths(preparedOutboundPayloads(a.preparedBatch), e.stateDir);
const s = o.length > 0 ? await createDeliveryQueueMediaRetention(o, "outbound-media-recovery-lease", e.stateDir, t) : void 0;
try {
if (!await finalizeDeliveryFailureSettlement(a, e.stateDir, t)) return "already-gone";
n = true;
emitRecoveredTerminalEvents(a, {
error: i.error,
collected: e.events
});
emitQueuedAuditTerminals(a, i.terminals ?? (() => uniformOutboundAuditTerminals(a.preparedBatch.sourcePayloadCount, {
outcome: i.outcome,
failureStage: "queue"
})));
if (i.unknownSendCleanup) {
const n = (await resolveOutboundChannelMessageAdapter({
channel: a.channel,
cfg: e.cfg,
agentId: a.session?.agentId,
allowBootstrap: true,
assertCurrent: () => t.workerContext.admission.assertCurrent()
}))?.durableFinal?.afterUnknownSendTerminal;
try {
await n?.(buildUnknownSendContext({
entry: a,
payloads: preparedOutboundPayloads(a.preparedBatch),
cfg: e.cfg
}));
} catch (t) {
e.log.warn(`Delivery entry ${a.id} unknown-send terminal cleanup failed: ${formatErrorMessage(t)}`);
}
}
await releaseSpoolArtifacts(o, e.stateDir);
} finally {
await cancelDeliveryQueueMediaRetention(s, e.stateDir, t);
}
} catch (t) {
e.log.warn(`Delivery entry ${e.entry.id} ${n ? "terminal cleanup failed" : "settlement pending"}: ${formatErrorMessage(t)}`);
}
return n ? "moved-to-failed" : "failed";
}
async function runReconciledSentCommitHooks(e) {
if (e.entry.legacyPreparedContentUnavailable) return;
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?.send?.lifecycle?.afterCommit;
if (!n) return;
const r = buildReconciledSentResult(e.entry, e.reconciliation);
try {
const { entry: t } = e;
const i = preparedOutboundPayloads(t.preparedBatch)[0] ?? {};
const a = {
cfg: e.cfg,
to: t.to,
deliveryQueueId: t.id,
accountId: t.accountId,
replyToId: t.effectiveReplyToId !== void 0 ? t.effectiveReplyToId : t.reply?.replyToId,
replyToMode: t.reply?.source === "implicit" ? t.reply.mode : void 0,
threadId: t.threadId,
silent: t.silent,
text: i.text ?? "",
result: {
messageId: r.messageId,
receipt: r.receipt
}
};
let o;
if (i.presentation !== void 0 || i.delivery !== void 0 || i.interactive !== void 0 || i.channelData !== void 0 && Object.keys(i.channelData).length > 0) o = {
...a,
kind: "payload",
mediaUrl: i.mediaUrl,
payload: i
};
else {
const e = i.mediaUrl ?? i.mediaUrls?.find((e) => e);
o = e ? {
...a,
kind: "media",
mediaUrl: e,
audioAsVoice: i.audioAsVoice,
gifPlayback: t.gifPlayback,
forceDocument: t.forceDocument
} : {
...a,
kind: "text"
};
}
await n(o);
} catch (t) {
e.log.warn(`Delivery entry ${e.entry.id} reconciled sent afterCommit hook failed: ${formatErrorMessage(t)}`);
}
}
async function resolveCompletedOwnerBeforeRecovery(e, t) {
const n = e.entry.deliveryCompletion;
if (!n) return "continue";
let r;
try {
r = await markDurableDeliveryQueued(n, e.entry.id, void 0, e.stateDir, t);
} catch (t) {
const n = `delivery owner state unavailable: ${formatErrorMessage(t)}`;
await e.owner.fail(failDelivery, n).catch(() => void 0);
e.onFailed?.(e.entry, n);
e.log.warn(`Delivery entry ${e.entry.id} ${n}`);
return "failed";
}
if (r.state === "prepared" || r.state === "queued") return "continue";
if (r.state === "unknown") {
const n = await settleQueuedFailure({
...e,
error: "delivery owner state is unknown"
}, t);
return n === "already-gone" ? "failed" : n;
}
try {
const t = r.state !== "delivered" && typeof e.entry.completionRetention === "object";
await e.owner.ack(t ? { suppressCompletionReceipt: true } : void 0);
} catch (t) {
const n = `failed to ack owner-${r.state} delivery: ${formatErrorMessage(t)}`;
e.onFailed?.(e.entry, n);
e.log.warn(`Delivery entry ${e.entry.id} ${n}`);
return "failed";
}
if (r.state === "delivered") {
await commitRecoveredVisibleMessages(e, t);
const n = r.platformMessageId;
if (n) {
const t = {
channel: e.entry.channel,
messageId: n
};
emitRecoveredTerminalEvents(e.entry, { result: t });
await runOutboundDeliveryCommitHooks([t]);
emitQueuedDeliveryResults(e.entry, [t]);
e.onDelivered?.([t], []);
}
} else if (r.state === "rejected") {
emitQueuedDeliveryResults(e.entry, [], [], () => "platform_send");
const t = r.rejectionError ?? "delivery permanently rejected before platform dispatch";
emitRecoveredTerminalEvents(e.entry, { error: t });
e.onFailed?.(e.entry, t);
return "failed";
} else if (r.state === "suppressed") {
emitQueuedAuditTerminals(e.entry, () => uniformOutboundAuditTerminals(e.entry.preparedBatch.sourcePayloadCount, {
outcome: "suppressed",
reasonCode: "no_visible_payload"
}));
e.onDelivered?.([], []);
}
e.onRecovered?.(e.entry);
return "recovered";
}
async function drainQueuedEntry(e, t, n) {
const { entry: r } = e;
const i = n ? (e) => n(e, t) : e.deliver;
const a = createQueuedDeliveryOwner({
queueId: r.id,
stateDir: e.stateDir,
expectedPlatformSendAttemptId: recoveryPlatformAttemptId(r)
}, t);
const o = resolveMaxRetries(r);
const s = resolveDeliveryQueueAttemptCount(r) >= o;
let c;
let l;
let u;
const d = await resolveCompletedOwnerBeforeRecovery({
...e,
owner: a
}, t);
if (d !== "continue") return d;
if (needsUnknownSendReconciliation(r)) {
const n = r.legacyUnknownSendReconciliation ?? await reconcileUnknownQueuedDelivery({
entry: r,
payloads: preparedOutboundPayloads(r.preparedBatch),
cfg: e.cfg,
warn: (t) => e.log.warn(t),
assertCurrent: () => t.workerContext.admission.assertCurrent()
});
if (n?.status === "sent") try {
const i = buildReconciledSentResult(r, n);
if (r.deliveryCompletion) await completeDurableDelivery(r.deliveryCompletion, i, e.stateDir, t, void 0, {
results: [i],
payloadCount: r.preparedBatch.sourcePayloadCount,
payloadOutcomes: [{
index: 0,
status: "sent",
results: [i]
}]
});
await a.ack();
await commitRecoveredVisibleMessages(e, t);
emitRecoveredTerminalEvents(r, { result: i });
await runReconciledSentCommitHooks({
entry: r,
cfg: e.cfg,
reconciliation: n,
log: e.log,
assertCurrent: () => t.workerContext.admission.assertCurrent()
});
emitQueuedDeliveryResults(r, [i]);
e.onRecovered?.(r);
e.onDelivered?.([i], []);
e.log.info(`Delivery entry ${r.id} reconciled unknown_after_send as already sent`);
return "recovered";
} catch (t) {
if (getErrnoCode(t) === "ENOENT") return "already-gone";
const n = `failed to ack reconciled sent delivery: ${formatErrorMessage(t)}`;
e.log.warn(`Delivery entry ${r.id} ${n}`);
e.onFailed?.(r, n);
return await recordRecoveryFailure(a, n);
}
u = resolveUnknownSendReplay(r, n);
if (u) {
c = r.platformSendAttemptId;
l = r.platformSendStartedAt;
e.log.info(u === "blind" ? `Delivery entry ${r.id} retrying an unconfirmed final text reply` : `Delivery entry ${r.id} reconciled ${r.recoveryState} as not sent; replaying`);
} else {
let i = `delivery state is ${r.recoveryState}; refusing blind replay without adapter reconciliation`;
if (n?.status === "not_sent") i = `delivery state is ${r.recoveryState}; refusing full replay after post-send evidence`;
else if (n?.status === "unresolved" && n.error) i = `delivery state is ${r.recoveryState} and reconciliation is unresolved: ${n.error}`;
e.log.warn(`Delivery entry ${r.id} ${i}`);
e.onFailed?.(r, i);
if (n?.status === "unresolved" && n.retryable === true && !s) return await recordRecoveryFailure(a, i);
return settleQueuedFailure({
...e,
error: i
}, t);
}
}
const f = [];
const p = [];
let m;
let h = false;
let g;
let _ = [];
let v = false;
const collectPayloadOutcome = (e) => {
if (!f.includes(e)) f.push(e);
};
const recordAttemptError = (e) => {
g = a.project(e, {
results: _,
payloadOutcomes: f
});
};
const runCommitHooksAfterAck = async () => {
if (m !== "acked" || v) return;
v = true;
emitRecoveredMessageSentEvents(r, p.map(({ event: e }) => e));
if (_.length > 0) await runOutboundDeliveryCommitHooks(_);
};
const y = typeof r.completionRetention === "object" || r.requiresProducerClaim === true || typeof r.producerClaimId === "string" || typeof r.platformSendAttemptId === "string";
const b = y ? await claimDeliveryPlatformSendAttempt(r.id, e.stateDir, l, c, t, u === "blind" ? true : void 0) : void 0;
if (y && !b) {
e.log.info(`Recovery skipped for delivery ${r.id}: producer ownership already claimed`);
return "already-gone";
}
a.claimId = recoveryPlatformAttemptId(r, b);
const persistPostSendState = () => persistQueuedPostSendState({
owner: a,
queuePolicy: r.queuePolicy ?? "best_effort",
preserveBatch: Boolean(b),
retainSpoolArtifacts: true,
onPostSendMarkerError: (t) => {
e.log.warn(`Delivery entry ${r.id} failed to persist post-send state; falling back to direct ack: ${formatErrorMessage(t)}`);
}
}, t);
const x = await reserveDeliveryAttempt(r.id, o, e.stateDir, b || void 0, t);
if (x.status === "exhausted") {
const n = `delivery retry budget exhausted (${x.attemptCount}/${o})`;
e.onFailed?.(r, n);
return settleQueuedFailure({
...e,
error: n,
claimedAttemptId: b
}, t);
}
const S = collectEntrySpoolPaths(preparedOutboundPayloads(r.preparedBatch), e.stateDir);
let C;
let w;
let T;
try {
if (r.sessionGeneration !== void 0) w = await prepareOutboundDeliveryGeneration(r.sessionGeneration);
C = S.length > 0 ? await createDeliveryQueueMediaRetention(S, "outbound-media-recovery-lease", e.stateDir, t) : void 0;
const { release: n, ...o } = await buildRecoveryDeliverParams(r, e.cfg, e.stateDir, b, t);
T = n;
let s = false;
const c = await i({
...o,
deliveryQueueOwner: a,
assertDirectAdapterHandoff: () => {
o.assertDirectAdapterHandoff?.();
w?.assertCurrent();
},
onPayloadDeliveryOutcome: collectPayloadOutcome,
onMessageSentEvent: (e, t) => p.push({
sourceIndex: t,
event: e
}),
onPlatformSendStart: async () => {
h = true;
},
onDeliveryResult: async (e) => {
if (!_.includes(e)) _.push(e);
m ??= await persistPostSendState();
},
onPlatformSendDispatch: async () => {
await o.onPlatformSendDispatch?.();
w?.assertCurrent();
if (s) return;
if (e.shouldContinue?.() === false) throw new OutboundDeliveryAdmissionClosedError();
s = true;
}
});
const l = isOutboundDeliveryResultArray(c) ? c : [];
const u = f.filter((e) => e.status === "failed");
if (f.some((e) => e.status === "suppressed" && e.reason === "adapter_returned_no_identity") || l.length === 0 && u.length === 0 && h && !areOutboundPayloadsIntentionallySuppressed(f)) {
const n = "recovered platform send returned no delivery identity";
await a.fail(failDeliveryAfterPlatformSend, n);
if (r.deliveryCompletion) await settleDurableDelivery(r.deliveryCompletion, { platformSendStarted: true }, e.stateDir, t);
e.onFailed?.(r, n);
e.log.warn(`Delivery entry ${r.id} ${n}; preserving unknown_after_send`);
recordAttemptError(/* @__PURE__ */ new Error(n));
return "failed";
}
if (l.length > 0) _ = [...l];
const d = u[0];
if (d) throw new OutboundDeliveryError(formatErrorMessage(d.error), {
cause: new AggregateError(u.map((e) => e.error)),
results: l,
payloadOutcomes: f,
stage: d.stage
});
if (r.deliveryCompletion) {
const n = l.at(-1);
await settleDurableDelivery(r.deliveryCompletion, n ? {
result: n,
batch: {
results: l,
payloadCount: r.preparedBatch.sourcePayloadCount,
payloadOutcomes: f
}
} : { platformSendStarted: false }, e.stateDir, t);
}
m ??= l.length > 0 ? await persistPostSendState() : void 0;
if (m === "failed") {
const t = "recovered send completed but queue finalization failed";
e.onFailed?.(r, t);
e.log.warn(`Delivery entry ${r.id} ${t}; preserving unknown_after_send`);
recordAttemptError(/* @__PURE__ */ new Error(t));
return "failed";
}
if (m !== "acked") try {
await (l.length === 0 && typeof r.completionRetention === "object" ? a.ack({ suppressCompletionReceipt: true }) : a.ack());
m = "acked";
} catch (t) {
const n = `failed to ack recovered delivery: ${formatErrorMessage(t)}`;
if (l.length > 0) {
await a.fail(failDeliveryAfterPlatformSend, n);
m = "failed";
} else await a.fail(areOutboundPayloadsIntentionallySuppressed(f) ? failDeliveryBeforePlatformSend : failDelivery, n);
e.onFailed?.(r, n);
e.log.warn(`Delivery entry ${r.id} ${n}`);
recordAttemptError(new Error(n));
return "failed";
}
await runCommitHooksAfterAck();
emitQueuedDeliveryResults(r, l, f);
e.onRecovered?.(r);
e.onDelivered?.(l, f);
return "recovered";
} catch (n) {
if (isOutboundDeliveryAdmissionClosedError(n)) {
await restoreDeliveryAttemptBeforeDispatch(r, x.attemptCount, e.stateDir, b, t);
return "stopped";
}
const i = formatErrorMessage(n);
e.onFailed?.(r, i);
if (isOutboundDeliveryError(n)) {
if (n.results.length > 0) _ = [...n.results];
for (const e of n.payloadOutcomes) collectPayloadOutcome(e);
}
recordAttemptError(n);
if (_.length > 0 || m !== void 0 || isOutboundDeliveryError(n) && n.sentBeforeError) {
try {
m ??= await persistPostSendState();
if (m === "marked" && r.retryAmbiguousFinalText === true) await a.fail(failDeliveryAfterPlatformSend, i, _.length === 0 && isAmbiguousDeliveryTransportError(n) ? true : void 0);
} catch (t) {
e.log.error(`Delivery entry ${r.id} could not persist post-send evidence: ${formatErrorMessage(t)}`);
}
if (m === "acked") {
await runCommitHooksAfterAck();
emitQueuedDeliveryResults(r, _, f, () => isOutboundDeliveryError(n) ? n.stage : "platform_send");
}
e.log.warn(`Delivery entry ${r.id} partially sent before recovery failed; preserving unknown_after_send`);
return "failed";
}
if (a.custody === "released") {
emitQueuedDeliveryResults(r, _, f, () => isOutboundDeliveryError(n) ? n.stage : "platform_send");
return "failed";
}
const o = [n, ...f.flatMap((e) => e.status === "failed" ? [e.error] : [])];
const s = findTerminalBatchRejection(o);
if (s || o.every((e) => isPermanentDeliveryError(formatErrorMessage(e)))) return settleQueuedFailure({
...e,
error: i,
claimedAttemptId: b,
...s ? { rejectionError: s.message } : {},
events: p,
terminals: failedOutboundAuditTerminals({
payloadCount: r.preparedBatch.sourcePayloadCount,
results: _,
payloadOutcomes: f,
failureStage: "queue"
})
}, t);
return await recordRecoveryFailure(a, i, isProvenDeliveryNotSentError(n) ? failDeliveryBeforePlatformSend : failDelivery);
} finally {
T?.();
w?.release();
await cancelDeliveryQueueMediaRetention(C, e.stateDir, t);
const n = await loadUnfinishedDelivery(r.id, e.stateDir, t).catch(() => r);
if (!n) await releaseSpoolArtifacts(S, e.stateDir);
if (g) {
if (!n) g.queueCustody = "released";
e.onAttemptFailed?.(g);
}
}
}
/** Startup and reconnect share custody, admission, retry, and settlement ordering. */
async function processQueuedRecovery(e, t, n, r) {
const { entry: i, log: a } = e;
if (e.shouldContinue?.() === false) return "stop";
const o = t.kind === "startup" ? `Delivery ${i.id}` : `${t.logLabel}: entry ${i.id}`;
if (i.settlement) {
await settleQueuedFailure({
...e,
error: i.settlement.error
}, n);
return "continue";
}
if (!shouldInspectQueuedDelivery(i, Date.now())) {
if (t.kind === "startup") a.info(`Recovery skipped for delivery ${i.id}: active platform owner`);
return "continue";
}
const s = await prepareDeferredDeliveryAdmission({
cfg: e.cfg,
channel: i.channel,
to: i.to,
accountId: i.accountId,
phase: "recovery"
}, {
agentId: i.session?.agentId,
assertCurrent: () => n.workerContext.admission.assertCurrent()
});
if (e.shouldContinue?.() === false) return "stop";
const c = s();
if (c.status !== "allowed") {
const r = await settleQueuedFailure({
...e,
error: c.reason
}, n);
const o = t.kind === "startup" ? "Recovery" : t.logLabel;
if (r === "already-gone") a.info(`${o}: entry ${i.id} changed ownership before admission failure was persisted`);
else {
if (t.kind === "startup") t.summary.failed += 1;
a.warn(`${o}: entry ${i.id} permanently rejected before recovery: ${c.reason}`);
}
return "continue";
}
const l = t.kind === "drain" ? t.selectEntry(i, Date.now()) : { match: true };
if (!l.match) {
a.info(`${o} no longer matches, skipping`);
return "continue";
}
const u = resolveMaxRetries(i);
const d = resolveDeliveryQueueAttemptCount(i);
if (d >= u && !needsUnknownSendReconciliation(i)) {
if (t.kind === "startup") {
a.warn(`${o} exceeded max retries (${d}/${u}) — moving to failed/`);
t.summary.skippedMaxRetries += 1;
}
const r = await settleQueuedFailure({
...e,
error: "delivery retry budget exhausted"
}, n);
if (t.kind === "drain" && r === "moved-to-failed") a.warn(`${o} exceeded max retries and was moved to failed/`);
return "continue";
}
const f = isDeliveryRecoveryRetryEligible(i, Date.now());
if (!l.bypassBackoff && !f.eligible) {
if (t.kind === "startup") t.summary.deferredBackoff += 1;
a.info(`${o} not ready for retry yet — backoff ${f.remainingBackoffMs}ms remaining`);
return "continue";
}
if (await recoveryCoordinator.waitForReplay(t.kind === "startup" ? t.deadline : void 0) === "deadline-exceeded") {
if (t.kind === "startup") t.onDeadlineExceeded();
return "stop";
}
if (e.shouldContinue?.() === false) return "stop";
return await drainQueuedEntry({
...e,
onRecovered: (e) => {
if (t.kind === "startup") {
t.summary.recovered += 1;
a.info(`Recovered delivery ${e.id} on ${e.channel}`);
} else a.info(`${t.logLabel}: drained delivery ${e.id} on ${e.channel}`);
},
onFailed: (e, n) => {
if (t.kind === "startup") t.summary.failed += 1;
if (isPermanentDeliveryError(n)) a.warn(`${o} hit permanent error — moving to failed/: ${n}`);
else a.warn(t.kind === "startup" ? `Retry failed for delivery ${e.id}: ${n}` : `${t.logLabel}: retry failed for entry ${e.id}: ${n}`);
}
}, n, r) === "stopped" ? "stop" : "continue";
}
/** The live producer keeps its claim and waits for the same recovery owner as restart. */
async function recoverLiveFinalDelivery(e, t) {
const n = await loadUnfinishedDelivery(e.entryId, e.stateDir, t);
if (!n || !canReplayAmbiguousFinalText(n) || n.settlement) return { status: "not-attempted" };
const r = isDeliveryRecoveryRetryEligible(n, Date.now());
if (!r.eligible) await sleep(r.remainingBackoffMs);
const i = { value: { status: "not-attempted" } };
const a = await loadUnfinishedDelivery(n.id, e.stateDir, t);
if (!a) return i.value;
await processQueuedRecovery({
...e,
entry: a,
onDelivered: (e, t) => {
i.value = {
status: "recovered",
results: e,
payloadOutcomes: t
};
},
onAttemptFailed: (e) => {
i.value = {
status: "failed",
error: e,
results: e.results,
payloadOutcomes: e.payloadOutcomes
};
}
}, {
kind: "drain",
logLabel: "Final delivery recovery",
selectEntry: () => ({
match: true,
bypassBackoff: true
})
}, t);
if (i.value.status === "recovered") return i.value;
const o = await loadUnfinishedDelivery(n.id, e.stateDir, t);
if (o && resolveDeliveryQueueAttemptCount(o) >= resolveMaxRetries(o)) {
if (await settleQueuedFailure({
...e,
entry: o,
error: o.lastError ?? "delivery retry budget exhausted"
}, t) === "moved-to-failed" && i.value.status === "failed") i.value.error.queueCustody = "released";
}
return i.value;
}
async function drainPendingDeliveriesCore(e, t, n = captureDeliveryQueueStateContext(e.stateDir)) {
const r = {
...e,
stateDir: n.stateDir
};
if (!await recoveryCoordinator.withDrain(r.drainKey, async () => {
const e = Date.now();
const i = (await loadUnfinishedDeliveries(r.stateDir, n)).filter((t) => Boolean(t.settlement) || r.selectEntry(t, e).match);
if (i.length > 0) r.onPending?.();
await recoveryCoordinator.scan({
entries: i.filter((t) => shouldInspectQueuedDelivery(t, e)),
laneKey: (e) => recoveryLaneKey(e, r.cfg, n.stateDir),
loadEntry: (e) => loadUnfinishedDelivery(e, r.stateDir, n),
onMissingEntry: (e) => {
r.log.info(`${r.logLabel}: entry ${e.id} already gone, skipping`);
},
onEntry: (e) => processQueuedRecovery({
...r,
entry: e
}, {
kind: "drain",
logLabel: r.logLabel,
selectEntry: r.selectEntry
}, n, t)
});
})) r.log.info(`${r.logLabel}: already in progress for ${r.drainKey}, skipping`);
}
/**
* Scan the canonical delivery queue and retry any pending entries.
* Doctor imports and prepares legacy entries before this runtime recovery pass.
* Uses exponential backoff and moves entries that exhaust their retry budget to failed/.
*/
async function recoverPendingDeliveries(e, t, n = captureDeliveryQueueStateContext(e.stateDir)) {
const r = {
...e,
stateDir: n.stateDir
};
const i = await loadUnfinishedDeliveries(r.stateDir, n);
if (i.length === 0) return createEmptyDeliveryRecoverySummary();
r.onPending?.();
r.log.info(`Found ${i.length} pending delivery entries — starting recovery`);
const a = resolveDeliveryRecoveryDeadlineMs(r.maxRecoveryMs);
const o = createEmptyDeliveryRecoverySummary();
const onDeadlineExceeded = () => {
r.log.warn(`Recovery time budget exceeded — remaining entries deferred to next startup`);
};
await recoveryCoordinator.scan({
entries: i.filter((e) => shouldInspectQueuedDelivery(e, Date.now())),
laneKey: (e) => recoveryLaneKey(e, r.cfg, n.stateDir),
loadEntry: (e) => loadUnfinishedDelivery(e, r.stateDir, n),
deadlineMs: a,
onDeadlineExceeded,
onClaimConflict: (e) => {
r.log.info(`Recovery skipped for delivery ${e.id}: already being processed`);
},
onMissingEntry: (e) => {
r.log.info(`Recovery skipped for delivery ${e.id}: already gone`);
},
onEntry: (e) => processQueuedRecovery({
...r,
entry: e
}, {
kind: "startup",
summary: o,
deadline: a,
onDeadlineExceeded
}, n, t)
});
r.log.info(`Delivery recovery complete: ${o.recovered} recovered, ${o.failed} failed, ${o.skippedMaxRetries} skipped (max retries), ${o.deferredBackoff} deferred (backoff)`);
return o;
}
//#endregion
export { persistQueuedPreSendState as _, completedOutboundAuditTerminals as a, OUTBOUND_DELIVERY_LOG_SCOPE as b, failedOutboundAuditTerminals as c, createOutboundMessageSentEmitter as d, prepareOutboundDeliveryGeneration as f, persistQueuedPostSendState as g, isProvenBatchNotSent as h, withActiveDeliveryClaim as i, uniformOutboundAuditTerminals as l, findTerminalBatchRejection as m, recoverLiveFinalDelivery as n, emitOutboundAuditLifecycle as o, createQueuedDeliveryOwner as p, recoverPendingDeliveries as r, emitOutboundAuditTerminals as s, drainPendingDeliveriesCore as t, createMessageSentEmitter as u, rejectQueuedDelivery as v, prepareDeferredDeliveryAdmission as x, commitConfirmedVisibleMessage as y };