openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 14.6 kB
JavaScript
import{o as getOrLoadSqliteDatabaseAdmissionForPath}from"./sqlite-database-admission-B3KDkUt-.mjs";import{n as executeExistingOpenClawStateRead}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{n as hydrateOpenClawStateWorkerError,r as retainOpenClawStateWorkerErrorPayload}from"./openclaw-state-worker-error-Ca5E4dEV.mjs";import{i as observeSqliteWorkerCommittedFacts,r as createSqliteWorkerOperationAdmission}from"./sqlite-worker-operation-admission-BZvXBQev.mjs";import{m as emptyOutboundDeliveryQueueAdmission,v as notifyOutboundDeliveryEnqueued}from"./delivery-queue-sqlite.types-glc5FW3-.mjs";import{a as generateSecureUuid}from"./secure-random-CDFMDkJP.mjs";import{n as OutboundDeliveryError,r as PlatformMessageNotDispatchedError}from"./deliver-types-QUMIGH6t.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-BNCoN9F0.mjs";import{f as prepareDeliveryQueueTerminalEntry}from"./delivery-queue-sqlite.kernel-DjujS9GY.mjs";import{t as captureDeliveryQueueStateContext}from"./delivery-queue-state-context-hv3uu8YS.mjs";import{l as executeDeliveryQueueOperation,o as loadDeliveryQueueEntries}from"./delivery-queue-sqlite-BtAn8uTD.mjs";import{n as collectEntrySpoolPaths}from"./delivery-queue-media-paths-0MyGAFWA.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-BtyjW4EQ.mjs";import{i as cancelDeliveryQueueMediaRetention,n as releaseSpoolArtifacts}from"./delivery-queue-media-spool-D-fYGPHv.mjs";
//!src/infra/outbound/delivery-queue-ack.ts
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)}}}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)}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}
//!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}}
//!src/infra/outbound/delivery-queue-platform-lease.ts
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}:{}}})}async function claimReusableDeliveryPlatformSendAttempt(e,t,n){return executeDeliveryQueueOperation(n,t,{type:`deliveryQueue.claimPlatformSend`,input:{id:e,claimId:generateSecureUuid(),requiresProducerClaim:true}})}async function renewDeliveryPlatformSendLease(e,t,n,r){return executeDeliveryQueueOperation(r,t,{type:`deliveryQueue.renewPlatformSendLease`,input:{id:e,claimId:n}})}
//!src/infra/outbound/delivery-queue-storage.ts
async function findDeliveryIntentOwner(e,t,n){return(await findDeliveryIntentOwners([e],t,n))[0]??null}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}}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}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}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`}}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}}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}})}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`);async function loadUnfinishedDeliveries(e,t){return await readOutboundDeliveries({mode:`unfinished`},e,t)}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)}})}function loadLegacyPendingDeliveries(e){return loadDeliveryQueueEntries(LEGACY_OUTBOUND_DELIVERY_QUEUE_NAME,e)}function loadPendingDeliveryMigrations(e){return loadDeliveryQueueEntries(OUTBOUND_DELIVERY_MIGRATION_QUEUE_NAME,e)}function loadPendingLegacyDeliveryPreparations(e){return loadDeliveryQueueEntries(OUTBOUND_LEGACY_PREPARATION_QUEUE_NAME,e)}async function failChatDeliveries(e,t,n){for(const r of await readOutboundDeliveries({mode:`pending`},t,n))if(r.recoveryState===void 0&&r.sessionGeneration?.agentId===e.agentId&&r.sessionGeneration.sessionKey===e.sessionKey)await failPendingDelivery({id:r.id,entry:r},t,n)}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)}export{retireUnsentDelivery as A,claimDeliveryPlatformSendAttempt as C,withStableDeliveryPreparation as D,StableDeliveryPreparationLostError as E,ackDelivery as O,stageDeliveryFailureSettlement as S,renewDeliveryPlatformSendLease as T,markDeliveryPlatformSendAttemptStarted as _,failDelivery as a,reserveDeliveryAttempt as b,finalizeDeliveryFailureSettlement as c,loadPendingDelivery as d,loadPendingDeliveryMigrations as f,markDeliveryPlatformOutcomeUnknown as g,loadUnfinishedDelivery as h,failChatDeliveries as i,failPendingDelivery as k,findDeliveryIntentOwner as l,loadUnfinishedDeliveries as m,enqueueDeliveryOnce as n,failDeliveryAfterPlatformSend as o,loadPendingLegacyDeliveryPreparations as p,enqueuePreparedDeliveryOnce as r,failDeliveryBeforePlatformSend as s,enqueueDelivery as t,loadLegacyPendingDeliveries as u,markDeliveryPlatformSendDispatched as v,claimReusableDeliveryPlatformSendAttempt as w,restoreDeliveryAttemptBeforeDispatch as x,moveToFailed as y};