UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 7.95 kB
import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{i as waitForAgentInputAdmission}from"./agent-database-preparation-context-CPut921o.mjs";import{D as runWithDiagnosticTraceContext,v as createDiagnosticTraceContextFromActiveScope}from"./diagnostics-timeline-Wd4cnAkV.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{t as getPluginServiceSchedulerBinding}from"./service-scheduler-binding-BU5HgMWe.mjs";import{f as clearChannelHistoryIfEnabled}from"./history-DMzWFL9T.mjs";import{n as withDispatchProcessedOutcomeSink}from"./dispatch-processed-outcome-DoLxm3yh.mjs";import{t as isRecentOutboundMessageIdentity}from"./outbound-echo-BLbwWzMK.mjs";import{t as deliverPendingDeliveryNotice}from"./pending-delivery-notice-kEtbFrXt.mjs";import{i as resolvePairLoopGuardSettings,n as createPairLoopGuard}from"./pair-loop-guard-runtime-QCF1DA70.mjs"; //!src/channels/turn/bot-loop-protection.ts const channelBotPairLoopGuard=createPairLoopGuard({pruneIntervalMs:6e4});function recordChannelBotPairLoopAndCheckSuppression(e){return channelBotPairLoopGuard.recordAndCheck({scopeId:e.scopeId,conversationId:e.conversationId,senderId:e.senderId,receiverId:e.receiverId,eventId:e.eventId,settings:resolvePairLoopGuardSettings(e),nowMs:e.nowMs})} //!src/channels/turn/dispatch-result.ts const hasFinalSignal=e=>e.fallbackDelivered===true||e.deliverySummaryDelivered===true;const hasVisibleSignal=(e,t)=>e?.observedReplyDelivery===true||t.observedReplyDelivery===true||hasFinalSignal(t);const EMPTY_CHANNEL_TURN_DISPATCH_COUNTS={tool:0,block:0,final:0};function hasVisibleChannelTurnDispatchFromReceipt(e,t={}){return e?.settledReceipt?.anyVisibleDelivered===true||hasVisibleSignal(e,t)}function resolveChannelTurnDispatchCounts(e){const t=e?.settledReceipt?.counts;return t?{tool:t.tool?.delivered??0,block:t.block?.delivered??0,final:t.final?.delivered??0}:{...EMPTY_CHANNEL_TURN_DISPATCH_COUNTS,...e?.counts}}function hasVisibleChannelTurnDispatch(e,t={}){if(e?.settledReceipt)return hasVisibleChannelTurnDispatchFromReceipt(e,t);return hasVisibleSignal(e,t)||e?.queuedFinal===true||Object.values(resolveChannelTurnDispatchCounts(e)).some(e=>e>0)}function hasFinalChannelTurnDispatch(e,t={}){const n=e?.settledReceipt?.counts.final;return hasFinalSignal(t)||(e?.settledReceipt?(n?.delivered??0)>0||(n?.failedAfterSend??0)>0:e?.queuedFinal===true||resolveChannelTurnDispatchCounts(e).final>0)} //!src/channels/turn/execution.ts const log=createSubsystemLogger(`channels/turn/execution`);function emit(e,t){e.log?.({channel:e.channel,accountId:e.accountId,messageId:e.messageId,sessionKey:e.ctxPayload.SessionKey??e.routeSessionKey,admission:e.admission?.kind??`dispatch`,...t})}function clearPendingHistoryAfterTurn(e){if(!e?.isGroup||!e.historyKey||!e.historyMap||e.limit===void 0)return;clearChannelHistoryIfEnabled({historyMap:e.historyMap,historyKey:e.historyKey,limit:e.limit})}function resolveRecordSessionKey(e){const t=e.record?.sessionKey;if(t===void 0)return e.ctxPayload.SessionKey??e.routeSessionKey;const n=t.trim();if(!n)throw new Error(`Channel turn record.sessionKey must be non-empty.`);if(n!==t)throw new Error(`Channel turn record.sessionKey must not include surrounding whitespace.`);return t}function dropPreparedChannelTurn(e,t,n=e.messageId){const r={kind:`drop`,reason:t};emit(e,{stage:`authorize`,event:`drop`,messageId:n,admission:r.kind,reason:r.reason});return{admission:r,dispatched:false,ctxPayload:e.ctxPayload,routeSessionKey:e.routeSessionKey}}function resolveOutboundEchoDrop(e){const t=[e.ctxPayload.NativeChannelId,e.ctxPayload.ChatId].find(e=>typeof e===`string`&&e.trim().length>0);if(!t)return;const n=[e.messageId,e.ctxPayload.MessageSidFull,e.ctxPayload.MessageSid].find(n=>typeof n===`string`&&isRecentOutboundMessageIdentity({channel:e.channel,accountId:e.accountId,conversationId:t,messageId:n}));const r=e.outboundEchoSourceId?.trim();const i=r?isRecentOutboundMessageIdentity({channel:e.channel,accountId:e.accountId,conversationId:t,sourceId:r}):false;if(!n&&!i)return;return dropPreparedChannelTurn(e,`outbound-echo`,e.messageId??n)}async function runPreparedChannelTurnCore(e,t){const n=createDiagnosticTraceContextFromActiveScope();return await runWithDiagnosticTraceContext(n,async()=>{const n=e.admission??{kind:`dispatch`};const r=resolveOutboundEchoDrop(e);if(r){clearPendingHistoryAfterTurn(e.history);await e.runDispatchLifecycle?.onDispatchSkipped(`outboundEcho`);return r}if(e.botLoopProtection&&recordChannelBotPairLoopAndCheckSuppression(e.botLoopProtection).suppressed){const t=dropPreparedChannelTurn(e,`bot-loop-protection`);clearPendingHistoryAfterTurn(e.history);await e.runDispatchLifecycle?.onDispatchSkipped(`botLoopProtection`);return t}try{const r=resolveRecordSessionKey(e);const emitStage=(t,i,a)=>emit(e,{stage:t,event:i,...t===`record`?{sessionKey:r}:{},admission:n.kind,...i===`error`?{error:a}:{}});try{const t=e.ctxPayload.AgentId??parseAgentSessionKey(e.routeSessionKey)?.agentId;const n=parseAgentSessionKey(r)?.agentId??t;const i=e.ctxPayload.SessionKey??e.routeSessionKey;for(const a of/* @__PURE__ */ new Set([i,r])){const i=a===r?n:t;if(!i)continue;const o=waitForAgentInputAdmission(i,{storePath:e.storePath,sessionKey:a,signal:getPluginServiceSchedulerBinding()?.().signal});if(o){log.info(`channel message waiting for agent database preparation`,{agentId:i,channel:e.channel,accountId:e.accountId});emit(e,{stage:`record`,event:`start`,reason:`agent-database-preparation-pending`});await o}}e.assertAuthority?.();if(e.ctxPayload.SessionTranscriptContext){const{mergeSessionTranscriptContext:t}=await import(`./session-transcript-context.runtime-BXUji5lH.mjs`);await t({agentId:n,ctx:e.ctxPayload,sessionKey:r,storePath:e.storePath})}emitStage(`record`,`start`);e.assertAuthority?.();await e.recordInboundSession({storePath:e.storePath,sessionKey:r,ctx:e.ctxPayload,groupResolution:e.record?.groupResolution,createIfMissing:e.record?.createIfMissing,updateLastRoute:e.record?.updateLastRoute,onRecordError:e.record?.onRecordError??(()=>void 0),trackSessionMetaTask:e.record?.trackSessionMetaTask,assertAuthority:e.assertAuthority});emitStage(`record`,`done`);await e.afterRecord?.();await deliverPendingDeliveryNotice(r,e.storePath,n)}catch(t){emitStage(`record`,`error`,t);try{await e.onPreDispatchFailure?.(t)}catch{}throw t}emitStage(`dispatch`,`start`);let i;try{e.assertAuthority?.();let r;if(n.kind===`observeOnly`){if(t.suppressObserveOnlyDispatch)await e.runDispatchLifecycle?.onDispatchSkipped(`observeOnly`);else await e.runDispatch();i=e.observeOnlyDispatchResult??{queuedFinal:false,counts:EMPTY_CHANNEL_TURN_DISPATCH_COUNTS}}else({result:i,processedOutcome:r}=await withDispatchProcessedOutcomeSink(()=>e.runDispatch()));function maybeWarnZeroCountVisibleDispatch(){if(n.kind===`observeOnly`||e.ctxPayload.InternalTurnSource!==void 0)return;const t=i;if(t?.deferredToActiveRun)return;if(hasVisibleChannelTurnDispatch(t))return;const a=r?`${r.outcome}${r.reason?`:${r.reason}`:``}`:void 0;log.warn(`visible channel turn dispatched with no queued reply payloads: channel=${e.channel} messageId=${e.messageId??`unknown`} sessionKey=${e.ctxPayload.SessionKey??e.routeSessionKey} cause=${a??`unknown`}`);emit(e,{stage:`dispatch`,event:`warning`,admission:n.kind,reason:`zero-count-visible-dispatch`})}maybeWarnZeroCountVisibleDispatch()}catch(e){emitStage(`dispatch`,`error`,e);throw e}emitStage(`dispatch`,`done`);return{admission:n,dispatched:true,ctxPayload:e.ctxPayload,routeSessionKey:e.routeSessionKey,dispatchResult:i}}finally{clearPendingHistoryAfterTurn(e.history)}})}async function runPreparedChannelTurn(e){return await runPreparedChannelTurnCore(e,{suppressObserveOnlyDispatch:true})}export{resolveChannelTurnDispatchCounts as a,hasVisibleChannelTurnDispatch as i,runPreparedChannelTurnCore as n,recordChannelBotPairLoopAndCheckSuppression as o,hasFinalChannelTurnDispatch as r,runPreparedChannelTurn as t};