openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 16.7 kB
JavaScript
import{p as toErrorObject}from"./error-coercion-DlKnt6w-.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{a as pluginInstanceInvocation}from"./plugin-instance-invocation-na_CYyUz.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{u as getPluginValueInstance,y as wrapCurrentPluginInstance}from"./plugin-instance-scope-Bx-frH07.mjs";import{E as readReplyPayloadSourceOccurrence,c as getReplyPayloadMetadata,k as setReplyPayloadMetadata,o as copyReplyPayloadMetadata}from"./reply-payload-C7eQHHoS.mjs";import{a as copyChannelParticipantAdmissionEvidence}from"./admission-evidence-DZ21Kx6F.mjs";import{n as getGlobalHookRunner}from"./hook-runner-global-DNCi6wD6.mjs";import{T as getGroupThreadDispatchContext}from"./hooks-Bu2gwS_g.mjs";import{c as isPlatformMessageNotDispatchedError,l as isPlatformMessageRejectedError,r as PlatformMessageNotDispatchedError}from"./deliver-types-QUMIGH6t.mjs";import{d as summarizeOutboundPayloadForTransport,r as createStructuredOutboundPayloadPlan}from"./payloads-By4nj9Hh.mjs";import{i as resolveMessageReceiptPrimaryId}from"./receipt-DMUG87P5.mjs";import{o as settleDurableDelivery,s as settlePendingFinalDelivery}from"./delivery-completion-BlzQI4lt.mjs";import{f as settleReplyPendingFinalDelivery,p as suppressPendingFinalDelivery}from"./reply-dispatcher-CyCal3OZ.mjs";import{a as isReplyDispatchDeliveryPending}from"./reply-dispatch-outcome-z7FrteHo.mjs";import{t as applyMessageSendingHook}from"./deliver-hooks-BpuBiz6S.mjs";import{n as deriveInboundMessageHookContext,r as resolveInboundReplyHookTarget}from"./message-hook-mappers-Bjx2XRf5.mjs";import{a as normalizeEmptyPayloadForDelivery}from"./deliver-payload-Bx3MDf5n.mjs";import{n as observeAgentRunStart}from"./agent-run-start-yFzndQ4_.mjs";import{a as dispatchInboundMessageWithRoutedChannelDispatcher}from"./dispatch-OJrrdqsb.mjs";import{n as withReplySystemEventContext}from"./system-event-session-key-CxIXvGqO.mjs";import{i as prepareSessionWriterDeliveryAuthority,t as assertSessionWriterDeliveryAuthorized}from"./session-writer-delivery-authority-B84mAU6U.mjs";import{t as recordInboundSession}from"./session-Cox_jf3d.mjs";import{r as runWithSessionInitConflictRetry}from"./session-init-conflict-retry-L9zyrKce.mjs";import{u as createMessageSentEmitter}from"./delivery-queue-recovery-D5ZJSVnC.mjs";import{n as trackActiveDirectPendingFinalDelivery}from"./pending-delivery-notice-kEtbFrXt.mjs";import{f as isChannelPartialDeliveryError,u as createSuppressedChannelDeliveryResult}from"./live-CZp14Lp3.mjs";import{i as throwIfDurableInboundReplyDeliveryFailed,n as deliverStructuredInboundReplyWithMessageSendContextCore,r as isDurableInboundReplyDeliveryHandled,t as deliverInboundReplyWithMessageSendContextCore}from"./durable-delivery-BBZNkKxX.mjs";import{n as runPreparedChannelTurnCore}from"./execution-Cpe8EZ0A.mjs";import{t as createChannelReplyPipeline}from"./reply-pipeline-BCqCQ6iZ.mjs";
//!src/channels/turn/delivery-owner.ts
function bindChannelDeliveryOwner(e){const t=getPluginValueInstance(e);return t&&t===pluginInstanceInvocation.getStore()?.instance?e:wrapCurrentPluginInstance(e)}function bindChannelReplyOptionsOwner(e){const t=pluginInstanceInvocation.getStore()?.instance;if(!t||!e)return e;const n={...e};for(const e of Reflect.ownKeys(n)){const r=Reflect.get(n,e);if(typeof r===`function`&&getPluginValueInstance(r)!==t)Reflect.set(n,e,t.wrap(r))}return n}
//!src/channels/turn/direct-delivery-custody.ts
var PendingFinalDeliveryNotOwnedError=class extends PlatformMessageNotDispatchedError{constructor(e){super(`Pending final delivery ownership changed before platform dispatch`,{cause:/* @__PURE__ */ new Error(`pending final delivery is ${e}`),retryable:false})}};const NO_PENDING_FINAL_CUSTODY={assertPlatformSendAuthorized:()=>void 0,onPlatformSendDispatch:()=>Promise.resolve(),release:()=>void 0};function resolvePendingFinalCompletion(e){const t=getReplyPayloadMetadata(e)?.pendingFinalDeliveryCompletion;return t?{kind:`pending-final`,...t}:void 0}async function createDirectPendingFinalCustody(e,t){const n=resolvePendingFinalCompletion(e);const r=getReplyPayloadMetadata(e)?.sessionWriterDeliveryAuthority;if(!n&&!r)return;const{authority:i,release:a}=await prepareSessionWriterDeliveryAuthority(r,t);const o=n?(({kind:e,...t})=>t)(n):void 0;let s;let c;return{bindPendingFinalDelivery:e=>setReplyPayloadMetadata(e,{...o?{pendingFinalDeliveryCompletion:o}:{},...i?{sessionWriterDeliveryAuthority:i}:{}}),assertPlatformSendAuthorized:()=>assertSessionWriterDeliveryAuthorized(i),release:()=>{c?.();a()},onPlatformSendDispatch:async()=>{await(s??=(async()=>{if(!n)return;c=trackActiveDirectPendingFinalDelivery(n);const e=await settlePendingFinalDelivery(n,`unknown`,[`prepared`,`queued`]);if(e.state!==`unknown`)throw new PendingFinalDeliveryNotOwnedError(e.state)})());assertSessionWriterDeliveryAuthorized(i)}}}function toCoreManagedDeliveryInfo(e,t){const n=e.kind===`block`?readReplyPayloadSourceOccurrence(t):void 0;return{kind:e.kind,...e.participant?{participant:e.participant}:{},...e.assistantMessageIndex===void 0?{}:{assistantMessageIndex:e.assistantMessageIndex},...n?{blockSourceRange:n.sourceRange}:{}}}
//!src/channels/turn/lifecycle.ts
function assembleResolvedChannelTurn(e){if(!(`route`in e))return e;const{cfg:t,route:n,...r}=e;let i=e.ctxPayload;if(n.dmScope&&i.DmScope!==n.dmScope){i={...i,DmScope:n.dmScope};copyChannelParticipantAdmissionEvidence(e.ctxPayload,i)}const a={ctxPayload:i,routeSessionKey:n.sessionKey,storePath:resolveSessionStorePathCore(t.session?.store,{agentId:n.agentId}),recordInboundSession};if(`runDispatch`in r)return{...r,...a};return{...r,...a,cfg:t,agentId:n.agentId}}function resolveAssembledReplyPipeline(e){const t=e.turnAdoptionLifecycle??e.replyOptions?.turnAdoptionLifecycle;const n=bindChannelReplyOptionsOwner(e.replyOptions);let r=t?{...n,turnAdoptionLifecycle:t}:n;if(e.routeSessionKey!==e.ctxPayload.SessionKey)r=withReplySystemEventContext(r??{},{sessionKey:e.routeSessionKey});if(!e.replyPipeline)return{dispatcherOptions:e.dispatcherOptions,replyOptions:r};const{onModelSelected:i,...a}=createChannelReplyPipeline({cfg:e.cfg,agentId:e.agentId,channel:e.channel,accountId:e.accountId,...e.replyPipeline});return{dispatcherOptions:{...a,...e.dispatcherOptions},replyOptions:{onModelSelected:i,...r}}}function markChannelDeliveryErrorVisible(e){if(isRecord(e))try{Object.assign(e,{sentBeforeError:true,visibleReplySent:true});return e}catch{}const t=new Error(`visible channel reply delivery failed`,{cause:e});Object.assign(t,{sentBeforeError:true,visibleReplySent:true});return t}async function runChannelDeliveryObserver(e){if(!e.onDelivered||isReplyDispatchDeliveryPending(e.result))return;try{await e.onDelivered(e.payload,e.info,e.result)}catch(t){throw e.result?.visibleReplySent===false?t:markChannelDeliveryErrorVisible(t)}}function resolveChannelDeliveryMessageId(e){return e?.receipt?resolveMessageReceiptPrimaryId(e.receipt):e?.messageIds?.find(e=>e.trim())}async function settleChannelDeliveryAttempts(e,t){let n;for(const r of e)try{await settleChannelDeliveryAttempt(r,t.onDelivered,e=>t.onError?.(e,r.info))}catch(e){if(n===void 0||isChannelPartialDeliveryError(e)&&!isChannelPartialDeliveryError(n))n=e}if(n!==void 0)throw toErrorObject(n,`channel delivery settlement failed`)}async function settleFailedPendingFinalDelivery(e,t){const n=resolvePendingFinalCompletion(e);if(!n)return;if(isPlatformMessageRejectedError(t))await settleDurableDelivery(n,{rejectionError:t.message});else if(isPlatformMessageNotDispatchedError(t))await settlePendingFinalDelivery(n,`prepared`,[`queued`,`unknown`]);else await settlePendingFinalDelivery(n,`unknown`,[`queued`,`unknown`])}function emitChannelDeliveryFailure(e,t,n){const r=isChannelPartialDeliveryError(t)?t.deliveryResult:void 0;if(!isPlatformMessageNotDispatchedError(t))n?.({success:false,content:r?.content??e.text??``,error:formatErrorMessage(t),messageId:resolveChannelDeliveryMessageId(r)})}async function settleChannelDeliveryAttempt(e,t,n){try{let r;try{r=e.result||void 0;if(r?.finalization)r={...r,...await r.finalization,finalization:void 0}}catch(t){if(t instanceof PendingFinalDeliveryNotOwnedError)return;try{await n?.(t)}catch{}await settleFailedPendingFinalDelivery(e.payload,t);emitChannelDeliveryFailure(e.payload,t,e.emitMessageSent);throw toErrorObject(t,`channel delivery finalization failed`)}const i=isReplyDispatchDeliveryPending(r);if(!i&&r?.visibleReplySent!==false)e.emitMessageSent?.({success:true,content:r?.content??e.payload.text??``,messageId:resolveChannelDeliveryMessageId(r)});await settleReplyPendingFinalDelivery(e.payload,i?`unknown`:r?.visibleReplySent===false?`suppressed`:`delivered`);await runChannelDeliveryObserver({onDelivered:t,payload:e.payload,info:e.info,result:r})}finally{e.releaseCustody?.()}}async function applyRoutedDirectMessageSending(e){const t=getGlobalHookRunner();const n=deriveInboundMessageHookContext(e.turn.ctxPayload);const r=await applyMessageSendingHook({hookRunner:t,enabled:t?.hasHooks(`message_sending`)??false,payload:e.payload,payloadSummary:summarizeOutboundPayloadForTransport(e.payload),to:resolveInboundReplyHookTarget(e.turn.ctxPayload,n),channel:e.turn.channel,accountId:e.turn.accountId,replyToId:e.payload.replyToId??e.turn.ctxPayload.ReplyToIdFull??e.turn.ctxPayload.ReplyToId,threadId:e.turn.ctxPayload.MessageThreadId,sessionKey:e.turn.routeSessionKey});if(r.cancelled)return{payload:e.payload,suppression:createSuppressedChannelDeliveryResult({reason:`cancelled_by_message_sending_hook`,cancelReason:r.hookEffect?.cancelReason,metadata:r.hookEffect?.metadata})};const i=normalizeEmptyPayloadForDelivery(r.payload);if(!i)return{payload:r.payload,suppression:createSuppressedChannelDeliveryResult({reason:r.changed?`empty_after_message_sending_hook`:`no_visible_payload`})};return{payload:copyReplyPayloadMetadata(e.payload,i)}}async function dispatchChannelTurnWithDeliveryOwner(...e){const[t,n]=e;const r=resolveAssembledReplyPipeline(t);const i=t.turnAdoptionLifecycle??t.replyOptions?.turnAdoptionLifecycle;const a=t.admission?.kind===`observeOnly`?{deliver:async()=>({visibleReplySent:false})}:bindChannelDeliveryOwner(t.delivery);const o=[];const s=[];let c=[];const l={...r.replyOptions,assertChannelAuthority:t.assertAuthority,...observeAgentRunStart(r.replyOptions,e=>{c=[e.runId,e.executionIdentityToken]})};const u=a.observeMessageSent?deriveInboundMessageHookContext(t.ctxPayload):void 0;let d;const getMessageSentEmitter=()=>{if(!a.observeMessageSent||!u)return;const e=getGroupThreadDispatchContext();if(!e&&d)return d;const n=createMessageSentEmitter({hookRunner:getGlobalHookRunner(),channel:t.channel,to:resolveInboundReplyHookTarget(t.ctxPayload,u),accountId:t.accountId,sessionKeyForInternalHooks:e?.ctx.SessionKey??t.routeSessionKey,runId:e?e.runState.runId:c[0],isGroup:u.isGroup,groupId:u.groupId,logPrefix:`dispatchAssembledChannelTurn`});if(!e)d=n;return n};const suppressReply=async(e,t,n)=>{const r=createSuppressedChannelDeliveryResult({reason:n});await suppressPendingFinalDelivery(e);await runChannelDeliveryObserver({onDelivered:a.onDelivered,payload:e,info:t,result:r});return r};const onReplySuppressed=async(e,t,n)=>{await suppressReply(e,t,n)};const f=a.deliver?.bind(a);const p=`deliverWithProviderMessageSending`in a?a.deliverWithProviderMessageSending?.bind(a):void 0;const m=a.deliverPrepared?.bind(a);const h=`deliverPreparedWithProviderMessageSending`in a?a.deliverPreparedWithProviderMessageSending?.bind(a):void 0;const g={prepare:e=>({payload:e}),deliver:f?(e,t)=>f(e.payload,t):void 0,deliverWithProviderMessageSending:p?(e,t)=>p(e.payload,t):void 0,deliverDurable:(e,t)=>deliverInboundReplyWithMessageSendContextCore({...t,payload:e.payload})};async function deliverReply(e,r,i){const s=a.preparePayload?await a.preparePayload(e,r):e;const l=s===null?null:i.prepare(copyReplyPayloadMetadata(e,s));if(l===null)return await suppressReply(e,r,`no_visible_payload`);const u=l.payload;const d=`durable`in a?a.durable:void 0;const f=typeof d===`function`?await d(u,r):d;if(f){const e=await i.deliverDurable(l,{cfg:t.cfg,channel:t.channel,accountId:t.accountId,agentId:t.agentId,ctxPayload:t.ctxPayload,info:r,executionIdentityToken:c[1],...f});if(e.status===`failed`&&isPlatformMessageNotDispatchedError(e.error))await settleFailedPendingFinalDelivery(u,e.error);throwIfDurableInboundReplyDeliveryFailed(e);if(isDurableInboundReplyDeliveryHandled(e)){await runChannelDeliveryObserver({onDelivered:a.onDelivered,payload:u,info:r,result:e.delivery});return e.delivery}}let p=l;let m=u;let h=void 0;let g=r;let _;const v=a.observeMessageSent?getGroupThreadDispatchContext()?getMessageSentEmitter()?.emitMessageSent:e=>getMessageSentEmitter()?.emitMessageSent(e):void 0;try{if(n===`routed-delivery`&&i.deliverWithProviderMessageSending){const e=await createDirectPendingFinalCustody(m,t.storePath);_=e?.release;const n={...r,...e??NO_PENDING_FINAL_CUSTODY};g=n;h=await i.deliverWithProviderMessageSending(p,n)}else{if(n===`routed-delivery`&&t.admission?.kind!==`observeOnly`){const e=await applyRoutedDirectMessageSending({turn:t,payload:m});m=e.payload;if(e.suppression)h=e.suppression;else{const e=i.prepare(m);if(e){p=e;m=e.payload}else h=createSuppressedChannelDeliveryResult({reason:`no_visible_payload`})}}if(!h){if(!i.deliver)throw new Error(`channel delivery adapter is missing a direct deliverer`);const e=await createDirectPendingFinalCustody(m,t.storePath);_=e?.release;await e?.onPlatformSendDispatch();h=await i.deliver(p,toCoreManagedDeliveryInfo(r,m))}}}catch(e){try{if(e instanceof PendingFinalDeliveryNotOwnedError)return{visibleReplySent:false};await settleFailedPendingFinalDelivery(m,e);if(a.observeMessageSent)emitChannelDeliveryFailure(m,e,v);throw e}finally{_?.()}}const y={payload:m,info:g,result:h,releaseCustody:_,emitMessageSent:v};if(h?.finalization){h.finalization.catch(()=>void 0);o.push(y)}else await settleChannelDeliveryAttempt(y,a.onDelivered);return h}const deliverPrepared=(e,t)=>deliverReply(e.payload,t,{prepare:t=>{const[n]=createStructuredOutboundPayloadPlan([t]);return n?{...n,sourceIndex:e.sourceIndex}:null},deliver:m??g.deliver,deliverWithProviderMessageSending:h??g.deliverWithProviderMessageSending,deliverDurable:(e,t)=>deliverStructuredInboundReplyWithMessageSendContextCore({...t,plan:e})});return await runPreparedChannelTurnCore({channel:t.channel,accountId:t.accountId,routeSessionKey:t.routeSessionKey,storePath:t.storePath,ctxPayload:t.ctxPayload,recordInboundSession:t.recordInboundSession,assertAuthority:t.assertAuthority,afterRecord:t.afterRecord,record:t.record,history:t.history,admission:t.admission,botLoopProtection:t.botLoopProtection,outboundEchoSourceId:t.outboundEchoSourceId,log:t.log,messageId:t.messageId,...i?{runDispatchLifecycle:{turnAdoptionLifecycle:i,onDispatchSkipped:async()=>await i.onAdopted()}}:{},runDispatch:async()=>{let e;let i;try{e=await runWithSessionInitConflictRetry(()=>(n===`routed-delivery`?dispatchInboundMessageWithRoutedChannelDispatcher:t.dispatchReplyWithBufferedBlockDispatcher)({ctx:t.ctxPayload,cfg:t.cfg,...n===`routed-delivery`?{...t.admission?.kind===`observeOnly`?{suppressOutboundHooks:true}:{},onReplyPayloadSuppressed:onReplySuppressed}:{},dispatcherOptions:{...r.dispatcherOptions,pendingFinalDeliveryAdmission:`deliver`,onSkip:(e,t)=>{r.dispatcherOptions?.onSkip?.(e,t);if(t.reason!==`channel_transform`)return;const{reason:n,...i}=t;s.push({payload:e,info:i,result:createSuppressedChannelDeliveryResult({reason:t.reason})})},deliver:(e,t)=>deliverReply(e,t,g),deliverPrepared,onError:a.onError},dispatchReplyFromConfig:t.dispatchReplyFromConfig,toolsAllow:t.toolsAllow,replyOptions:l,replyResolver:t.replyResolver}),t.sessionInitRetry?{retryDelaysMs:t.sessionInitRetry.delaysMs,signal:t.sessionInitRetry.signal,sleep:t.sessionInitRetry.sleep}:void 0)}catch(e){i=e}let c;try{await settleChannelDeliveryAttempts([...s,...o],a)}catch(e){c=e}if(c!==void 0&&isChannelPartialDeliveryError(c))throw toErrorObject(c,`channel delivery settlement failed`);if(i!==void 0)throw toErrorObject(i,`channel dispatch failed`);if(c!==void 0)throw toErrorObject(c,`channel delivery settlement failed`);return e}},{suppressObserveOnlyDispatch:false})}async function dispatchAssembledChannelTurn(e){return await dispatchChannelTurnWithDeliveryOwner(e,`legacy-dispatcher`)}async function dispatchRoutedChannelTurn(e){return await dispatchChannelTurnWithDeliveryOwner(assembleResolvedChannelTurn(e),`routed-delivery`)}export{dispatchAssembledChannelTurn as n,dispatchRoutedChannelTurn as r,assembleResolvedChannelTurn as t};