openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
463 lines (462 loc) • 18.1 kB
JavaScript
import { a as getOrLoadSqliteDatabaseAdmissionForPath } from "./sqlite-database-admission-DQIqro3d.mjs";
import { n as hydrateOpenClawStateWorkerError, r as retainOpenClawStateWorkerErrorPayload } from "./openclaw-state-worker-error-C8y1JGQN.mjs";
import { a as observeSqliteWorkerCommittedFacts, i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { m as emptyOutboundDeliveryQueueAdmission, v as notifyOutboundDeliveryEnqueued } from "./delivery-queue-sqlite.types-B7uW265Q.mjs";
import { a as generateSecureUuid } from "./secure-random-CW5OZnK1.mjs";
import { n as OutboundDeliveryError, r as PlatformMessageNotDispatchedError } from "./deliver-types-BnSKrpHG.mjs";
import { c as OUTBOUND_LEGACY_PREPARATION_QUEUE_NAME, i as OUTBOUND_DELIVERY_MIGRATION_QUEUE_NAME, l as outboundDeliveryQueueName, o as OUTBOUND_DELIVERY_QUEUE_NAME, r as LEGACY_OUTBOUND_DELIVERY_QUEUE_NAME } from "./delivery-queue-namespaces-HQn65gG8.mjs";
import { f as prepareDeliveryQueueTerminalEntry } from "./delivery-queue-sqlite.kernel-Cv08QjUU.mjs";
import { t as captureDeliveryQueueStateContext } from "./delivery-queue-state-context-Cxp-xMAQ.mjs";
import { l as executeDeliveryQueueOperation, o as loadDeliveryQueueEntries } from "./delivery-queue-sqlite-lyIJZlO0.mjs";
import { n as collectEntrySpoolPaths } from "./delivery-queue-media-paths-Bhk9Ljz0.mjs";
import { d as projectPreparedOutboundBatchForStorage, i as projectQueuedDeliveryOptions, l as preparedOutboundPayloads, n as encodeOutboundDeliverySnapshot, r as projectOutboundDelivery, s as createUnmodifiedPreparedOutboundBatch, t as decodeOutboundDeliverySnapshot } from "./delivery-queue-projection-BhmCxxmH.mjs";
import { i as cancelDeliveryQueueMediaRetention, n as releaseSpoolArtifacts } from "./delivery-queue-media-spool-ys6bmM17.mjs";
//#region src/infra/outbound/delivery-queue-ack.ts
/** Retires an unsent live claim while its adapter preparation still owns resources. */
async function retireUnsentDelivery(e, t, n) {
const r = t?.stateDir ?? e.stateDir;
const i = await executeDeliveryQueueOperation(t, r, {
type: "deliveryQueue.retireUnsent",
input: {
...e,
stateDir: r,
terminalOutcome: n
}
});
if (!i) return;
return async () => {
try {
await releaseSpoolArtifacts(i.spoolPaths, r);
} finally {
await cancelDeliveryQueueMediaRetention(i.retention, r, t);
}
};
}
/** Remove a successfully delivered entry, or retain its producer-owned receipt. */
async function ackDelivery(e, t, n, r) {
const i = r ?? captureDeliveryQueueStateContext(t);
const a = i.stateDir;
const o = n ? {
retainSpoolArtifacts: n.retainSpoolArtifacts,
suppressCompletionReceipt: n.suppressCompletionReceipt,
..."expectedPlatformSendAttemptId" in n ? { expectedPlatformSendAttemptId: n.expectedPlatformSendAttemptId } : {}
} : void 0;
const s = await executeDeliveryQueueOperation(i, a, {
type: "deliveryQueue.ack",
input: {
id: e,
stateDir: a,
options: o
}
});
if (!o?.retainSpoolArtifacts) await releaseSpoolArtifacts(s, a);
}
/** Conditionally dead-letter a freshly re-read pending entry without a claimed state. */
async function failPendingDelivery(e, t, n) {
const r = {
queueName: outboundDeliveryQueueName(e.entry),
id: e.id,
entry: e.entry
};
const i = e.expectedPlatformSendAttemptId === void 0 ? prepareDeliveryQueueTerminalEntry(r) : void 0;
const a = n ?? captureDeliveryQueueStateContext(t);
const o = a.stateDir;
const { result: s, spoolPaths: c } = await executeDeliveryQueueOperation(a, o, {
type: "deliveryQueue.failPending",
input: {
id: e.id,
entryJson: i?.expectedJson ?? JSON.stringify(e.entry),
expectedPlatformSendAttemptId: e.expectedPlatformSendAttemptId,
retainSpoolArtifacts: e.retainSpoolArtifacts,
stateDir: o,
prepared: i
}
});
if (s.status === "failed") await releaseSpoolArtifacts(c, o);
return s;
}
//#endregion
//#region src/infra/outbound/delivery-queue-preparation.ts
const STABLE_PREPARATION_LEASE_MS = 3e5;
var StableDeliveryPreparationLostError = class extends Error {
constructor(e) {
super(`Stable outbound preparation ownership was lost: ${e}`);
this.name = "StableDeliveryPreparationLostError";
}
};
async function withStableDeliveryPreparation(e, t) {
const n = t ?? captureDeliveryQueueStateContext(e.stateDir);
const r = await executeDeliveryQueueOperation(n, e.stateDir, {
type: "deliveryQueue.claimPreparation",
input: { id: e.id }
});
if (r.status === "existing") return r;
let i = r.entry;
let a = false;
let o = false;
const replaceEntry = async (t) => {
const r = {
...i,
preparationState: t,
preparationLeaseExpiresAt: Date.now() + STABLE_PREPARATION_LEASE_MS
};
if (!await executeDeliveryQueueOperation(n, e.stateDir, {
type: "deliveryQueue.replacePreparation",
input: {
expectedEntry: i,
replacementEntry: r
}
})) {
a = true;
throw new StableDeliveryPreparationLostError(e.id);
}
i = r;
};
const s = {
current: async () => i,
beforeFirstModifier: () => replaceEntry("modifiers_started"),
markPrepared: () => replaceEntry("prepared"),
markPublished: () => {
o = true;
}
};
try {
const t = await e.run(s);
if (!o) {
if (!await executeDeliveryQueueOperation(n, e.stateDir, {
type: "deliveryQueue.completePreparation",
input: { expectedEntry: i }
})) throw new Error(`Stable outbound preparation could not be settled: ${e.id}`);
}
return {
status: "claimed",
value: t
};
} catch (t) {
if (!o && !a) {
if (i.preparationState === "claimed") {
const t = {
...i,
preparationOwnerId: void 0,
preparationLeaseExpiresAt: 0
};
await executeDeliveryQueueOperation(n, e.stateDir, {
type: "deliveryQueue.replacePreparation",
input: {
expectedEntry: i,
replacementEntry: t
}
});
} else await executeDeliveryQueueOperation(n, e.stateDir, {
type: "deliveryQueue.failPreparation",
input: { entry: i }
});
}
throw t;
}
}
//#endregion
//#region src/infra/outbound/delivery-queue-platform-lease.ts
/** Atomically transfer a stable pending producer intent to one platform sender. */
async function claimDeliveryPlatformSendAttempt(e, t, n, r, i, a) {
return executeDeliveryQueueOperation(i, t, {
type: "deliveryQueue.claimPlatformSend",
input: {
id: e,
claimId: generateSecureUuid(),
...n !== void 0 ? { reconciledPlatformSendStartedAt: n } : {},
...r !== void 0 ? { reconciledPlatformSendAttemptId: r } : {},
...a ? { allowUnknownSendReplay: a } : {}
}
});
}
/** Claim and atomically upgrade a live reusable producer to renewable ownership. */
async function claimReusableDeliveryPlatformSendAttempt(e, t, n) {
return executeDeliveryQueueOperation(n, t, {
type: "deliveryQueue.claimPlatformSend",
input: {
id: e,
claimId: generateSecureUuid(),
requiresProducerClaim: true
}
});
}
/** Extend the exact active producer lease without changing ownership. */
async function renewDeliveryPlatformSendLease(e, t, n, r) {
return executeDeliveryQueueOperation(r, t, {
type: "deliveryQueue.renewPlatformSendLease",
input: {
id: e,
claimId: n
}
});
}
//#endregion
//#region src/infra/outbound/delivery-queue-storage.ts
async function findDeliveryIntentOwner(e, t, n) {
return (await findDeliveryIntentOwners([e], t, n))[0] ?? null;
}
/** Resolve one ordered batch without reopening the store for each intent. */
async function findDeliveryIntentOwners(e, t, n) {
if (e.length === 0) return [];
const r = n ?? captureDeliveryQueueStateContext(t);
return executeDeliveryQueueOperation(r, t, {
type: "deliveryQueue.findIntentOwners",
input: { ids: [...e] }
});
}
function preparedBatchFromLowLevelInput(e) {
if (e.preparedBatch) return e.preparedBatch;
if (!e.payloads) throw new Error("Delivery queue entry requires a prepared payload batch");
return createUnmodifiedPreparedOutboundBatch(e.payloads);
}
function createQueuedDelivery(e, t, n) {
return {
id: t,
enqueuedAt: Date.now(),
...projectQueuedDeliveryOptions(e),
queuePolicy: e.queuePolicy,
requireUnknownSendReconciliation: e.requireUnknownSendReconciliation,
retryAmbiguousFinalText: e.retryAmbiguousFinalText,
...e.initialProducerClaim ?? (e.requiresProducerClaim === true ? { requiresProducerClaim: true } : {}),
preparedBatch: projectPreparedOutboundBatchForStorage(preparedBatchFromLowLevelInput(e)),
reply: e.reply,
sessionGeneration: e.sessionGeneration,
deliveryCompletion: e.deliveryCompletion,
completionRetention: e.completionRetention,
...n ? { retainOnFailure: true } : {},
legacyUnknownSendReconciliation: e.legacyUnknownSendReconciliation,
legacyPreparedContentUnavailable: e.legacyPreparedContentUnavailable,
maxRetries: e.maxRetries,
retryCount: 0,
attemptCount: 0
};
}
/** Keep uncertain publication with recovery even when the broker returns a cleanup error. */
async function enqueueQueuedDelivery(e, t) {
let n;
let r;
try {
r = await executeDeliveryQueueOperation(t, t.stateDir, {
type: "deliveryQueue.enqueue",
input: e
}, { createAdmission: (e) => {
n = e.settled;
const r = createSqliteWorkerOperationAdmission(() => {
throw new Error("Delivery enqueue does not request host transaction admission");
});
observeSqliteWorkerCommittedFacts(r, () => notifyOutboundDeliveryEnqueued(t.stateDir));
return {
nativeLocations: [],
admission: r
};
} });
} catch (e) {
if (n && (await n).kind !== "not-entered") {
const t = new OutboundDeliveryError("Delivery queue publication could not be confirmed", { cause: e });
t.queueCustody = "held";
throw t;
}
throw e;
}
if (typeof r !== "string") {
const e = /* @__PURE__ */ new Error("Delivery queue publication failed");
retainOpenClawStateWorkerErrorPayload(e, r.error);
const t = new OutboundDeliveryError("Delivery queue admission rejected before publication", {
cause: new PlatformMessageNotDispatchedError("Delivery was not queued or sent", { cause: hydrateOpenClawStateWorkerError(e, { includeOrdinary: true }) }),
stage: "queue"
});
t.queueCustody = "released";
throw t;
}
if (r === (e.kind === "prepared" ? "staging-missing" : "missing")) throw new Error(`Delivery queue media stage expired before enqueue: ${e.mediaStageId}`);
return r;
}
/** Persist a delivery entry before attempting send. Returns the entry ID. */
async function enqueueDelivery(e, t, n, r) {
const i = r ?? captureDeliveryQueueStateContext(t);
const a = generateSecureUuid();
const o = createQueuedDelivery(e, a, e.deliveryCompletion !== void 0 || e.completionRetention !== void 0);
if (await enqueueQueuedDelivery({
kind: "random",
entryJson: JSON.stringify(o),
mediaStageId: n
}, i) === "existing") throw new Error(`Delivery queue entry already exists: ${OUTBOUND_DELIVERY_QUEUE_NAME}/${a}`);
return a;
}
/** Inserts one stable queue id without replacing prior pending or completed ownership. */
async function enqueueDeliveryOnce(e, t, n, r, i) {
const a = t.trim();
if (!a) throw new Error("Stable delivery queue id is required");
const o = i ?? captureDeliveryQueueStateContext(n);
const s = createQueuedDelivery(e, a, true);
return {
id: a,
created: await enqueueQueuedDelivery({
kind: "stable",
entryJson: JSON.stringify(s),
mediaStageId: r
}, o) === "created"
};
}
/** Atomically replaces a payload-free stable preparation owner with prepared custody. */
async function enqueuePreparedDeliveryOnce(e, t, n, r, i, a) {
const o = t.trim();
if (!o || o !== n.id) throw new Error("Stable delivery preparation id is invalid");
const s = a ?? captureDeliveryQueueStateContext(r);
const c = createQueuedDelivery(e, o, true);
if (await enqueueQueuedDelivery({
kind: "prepared",
entryJson: JSON.stringify(c),
preparationJson: JSON.stringify(n),
mediaStageId: i
}, s) !== "moved") throw new StableDeliveryPreparationLostError(o);
return {
id: o,
created: true
};
}
/** Update retry evidence on the queue worker's exact namespace and claim. */
function deliveryFailureRecorder(e) {
return async (t, n, r, i, a, o) => {
await executeDeliveryQueueOperation(a, r, {
type: "deliveryQueue.mutateOutbound",
input: {
kind: e,
id: t,
error: n,
expectedPlatformSendAttemptId: i,
ambiguousTransportError: o
}
});
};
}
const failDelivery = deliveryFailureRecorder("fail");
const failDeliveryBeforePlatformSend = deliveryFailureRecorder("fail-before-send");
const failDeliveryAfterPlatformSend = deliveryFailureRecorder("fail-after-send");
async function reserveDeliveryAttempt(e, t, n, r, i) {
return await executeDeliveryQueueOperation(i, n, {
type: "deliveryQueue.reserveOutbound",
input: {
id: e,
maxAttempts: t,
expectedPlatformSendAttemptId: r
}
});
}
/** Restore only the exact reserved attempt before recipient-visible dispatch. */
async function restoreDeliveryAttemptBeforeDispatch(e, t, n, r, i) {
await executeDeliveryQueueOperation(i, n, {
type: "deliveryQueue.restoreOutbound",
input: {
entry: encodeOutboundDeliverySnapshot(e),
reservedAttemptCount: t,
claimedAttemptId: r
}
});
}
function deliveryPlatformSendRecorder(e) {
return async (t, n, r, i, a) => {
await executeDeliveryQueueOperation(a, n, {
type: "deliveryQueue.mutateOutbound",
input: {
kind: e,
id: t,
route: r && ("replyToId" in r ? { replyToId: r.replyToId } : {}),
expectedPlatformSendAttemptId: i
}
});
};
}
const markDeliveryPlatformSendAttemptStarted = deliveryPlatformSendRecorder("start");
const markDeliveryPlatformSendDispatched = deliveryPlatformSendRecorder("dispatch");
async function markDeliveryPlatformOutcomeUnknown(e, t, n, r) {
await executeDeliveryQueueOperation(r, t, {
type: "deliveryQueue.mutateOutbound",
input: {
kind: "unknown",
id: e,
expectedPlatformSendAttemptId: n
}
});
}
async function readOutboundDeliveries(e, t, n) {
const r = n ?? captureDeliveryQueueStateContext(t);
if (e.id === void 0 && e.mode === "unfinished" && getOrLoadSqliteDatabaseAdmissionForPath(r.workerContext.admission.databasePath, emptyOutboundDeliveryQueueAdmission, () => void 0)) {
r.workerContext.admission.assertCurrent();
return [];
}
const i = await executeExistingOpenClawStateRead({
path: r.workerContext.admission.databasePath,
env: r.workerContext.environment
}, {
type: "deliveryQueue.outbound",
...e
}, {
context: r.workerContext,
current: true
});
if (!i) return [];
return i.entries.map(({ queueName: e, entry: t }) => projectOutboundDelivery(e, t));
}
function outboundDeliveryReader(e) {
return async (t, n, r) => (await readOutboundDeliveries({
id: t,
mode: e
}, n, r))[0] ?? null;
}
const loadPendingDelivery = outboundDeliveryReader("pending");
const loadUnfinishedDelivery = outboundDeliveryReader("unfinished");
/** Includes unfinished settlement in FIFO order across both executable formats. */
async function loadUnfinishedDeliveries(e, t) {
return await readOutboundDeliveries({ mode: "unfinished" }, e, t);
}
/** Close send custody before awaiting completion projection; retain its restart work. */
async function stageDeliveryFailureSettlement(e, t, n, r, i) {
const a = await executeDeliveryQueueOperation(i, n, {
type: "deliveryQueue.stageFailure",
input: {
entry: encodeOutboundDeliverySnapshot(e),
settlementEntry: encodeOutboundDeliverySnapshot({
...e,
settlement: t
}),
claimedAttemptId: r
}
});
return a && decodeOutboundDeliverySnapshot(a);
}
async function finalizeDeliveryFailureSettlement(e, t, n) {
return await executeDeliveryQueueOperation(n, t, {
type: "deliveryQueue.finalizeFailure",
input: { entry: encodeOutboundDeliverySnapshot(e) }
});
}
/** One-time migration inventory; normal recovery never reads the legacy namespace. */
function loadLegacyPendingDeliveries(e) {
return loadDeliveryQueueEntries(LEGACY_OUTBOUND_DELIVERY_QUEUE_NAME, e);
}
/** Prepared legacy rows awaiting media staging and canonical publication. */
function loadPendingDeliveryMigrations(e) {
return loadDeliveryQueueEntries(OUTBOUND_DELIVERY_MIGRATION_QUEUE_NAME, e);
}
/** Claimed pre-D4 rows whose modifying policy has not safely published yet. */
function loadPendingLegacyDeliveryPreparations(e) {
return loadDeliveryQueueEntries(OUTBOUND_LEGACY_PREPARATION_QUEUE_NAME, e);
}
/** Move a queue entry out of the pending retry set. */
async function moveToFailed(e, t, n, r) {
const i = r?.stateDir ?? t;
const a = await loadPendingDelivery(e, i, r);
if (!a) throw new Error(`No pending outbound delivery queue entry ${e}`);
if ((await failPendingDelivery({
id: e,
entry: a,
retainSpoolArtifacts: true,
...n !== void 0 ? { expectedPlatformSendAttemptId: n } : {}
}, i, r)).status !== "failed") throw new Error(`Delivery platform claim was lost: ${e}`);
return collectEntrySpoolPaths(preparedOutboundPayloads(a.preparedBatch), i);
}
//#endregion
export { claimReusableDeliveryPlatformSendAttempt as C, ackDelivery as D, withStableDeliveryPreparation as E, failPendingDelivery as O, claimDeliveryPlatformSendAttempt as S, StableDeliveryPreparationLostError as T, markDeliveryPlatformSendDispatched as _, failDeliveryAfterPlatformSend as a, restoreDeliveryAttemptBeforeDispatch as b, findDeliveryIntentOwner as c, loadPendingDeliveryMigrations as d, loadPendingLegacyDeliveryPreparations as f, markDeliveryPlatformSendAttemptStarted as g, markDeliveryPlatformOutcomeUnknown as h, failDelivery as i, retireUnsentDelivery as k, loadLegacyPendingDeliveries as l, loadUnfinishedDelivery as m, enqueueDeliveryOnce as n, failDeliveryBeforePlatformSend as o, loadUnfinishedDeliveries as p, enqueuePreparedDeliveryOnce as r, finalizeDeliveryFailureSettlement as s, enqueueDelivery as t, loadPendingDelivery as u, moveToFailed as v, renewDeliveryPlatformSendLease as w, stageDeliveryFailureSettlement as x, reserveDeliveryAttempt as y };