openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 10.9 kB
JavaScript
import{o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{n as normalizeAccountId}from"./account-id-3yqrEsRn.mjs";import{t as AgentSelectionRequiredError}from"./agent-scope-config-CG9CFpGX.mjs";import{n as normalizeRouteBindingId}from"./binding-scope-D9i37lvD.mjs";import{t as normalizeChatType}from"./chat-type-BzCV5nTQ.mjs";import{t as warnPluginSdkDeprecation}from"./sdk-deprecation-BDUCyBrU.mjs";import{t as normalizeAnyChannelId}from"./registry-normalize-BP0gv89S.mjs";import{n as getLoadedChannelPlugin}from"./registry-CpNh6QcT.mjs";import"./plugins-DxOycUNJ.mjs";import{s as prepareSessionBindingInspections}from"./session-binding-service-TO5btU7E.mjs";import{t as assertConversationAuthority}from"./conversation-authority--p-Hu1FJ.mjs";import{c as peerKindMatches,o as resolveAgentRoute}from"./resolve-route-DpjPYoyg.mjs";import{i as listRouteBindings}from"./bindings-ChJyFxlC.mjs";import{r as getGlobalPluginRegistry}from"./hook-runner-global-DNCi6wD6.mjs";import{r as PlatformMessageNotDispatchedError}from"./deliver-types-QUMIGH6t.mjs";import{a as readConversation,d as withConversationAuthority}from"./conversation-registry-BcXOQoHL.mjs";import{r as getConversationDeliveryOperation}from"./conversation-delivery-store-CV2h43w9.mjs";import{n as inspectRuntimeConversationBindingRoute,r as resolveConfiguredBindingRoute}from"./binding-routing-Cl7tiSrP.mjs";
//!src/gateway/conversation-errors.ts
var ConversationInputError=class extends Error{constructor(e){super(e);this.name=`ConversationInputError`}};var ConversationOperationConflictError=class extends ConversationInputError{constructor(e){super(e);this.name=`ConversationOperationConflictError`}};
//!src/gateway/conversation-route-ownership.ts
function hasActivePluginClaimOwner(e){return getGlobalPluginRegistry()?.typedHooks.some(t=>t.pluginId===e&&t.hookName===`inbound_claim`)===true}function pluginRouteOwnerInput(e,t){return{cfg:e,accountId:normalizeAccountId(t.accountId),conversation:{kind:t.kind,peerId:t.peerId,target:t.target,...t.threadId?{threadId:t.threadId}:{},...t.nativeChannelId?{nativeChannelId:t.nativeChannelId}:{},...t.routeContext?{context:t.routeContext}:{}}}}function resolvePluginRouteOwner(e,t,n){const r=normalizeAnyChannelId(t.channel);const i=n??(r?getLoadedChannelPlugin(r)?.messaging?.resolveConversationRouteOwner:void 0);if(!i)return;if(!n)warnPluginSdkDeprecation({family:`conversation-route-ownership`,method:`ChannelMessagingAdapter.resolveConversationRouteOwner`,replacement:`ChannelMessagingAdapter.prepareConversationRouteOwnersAsync`});try{const n=i(pluginRouteOwnerInput(e,t));if(n===void 0)return;if(n===null)return{kind:`available`};if(n.kind===`unavailable`)return n;if(n.kind===`plugin`)return hasActivePluginClaimOwner(n.pluginId)?{kind:`available`}:{kind:`available`,agentId:normalizeAgentId(n.fallbackAgentId)};return{kind:`available`,agentId:normalizeAgentId(n.agentId)}}catch(e){if(e instanceof AgentSelectionRequiredError)return{kind:`available`};throw e}}function resolveConfiguredRouteOwner(e,t,n){try{return resolveAgentRoute({cfg:e,channel:t.channel,accountId:t.accountId,peer:{kind:t.kind,id:t.peerId},...n?.parentPeerId&&t.kind!==`direct`?{parentPeer:{kind:t.kind,id:n.parentPeerId}}:{},...n?.guildId?{guildId:n.guildId}:{},...n?.teamId?{teamId:n.teamId}:{},...n?.memberRoleIds?{memberRoleIds:n.memberRoleIds}:{}})}catch(e){if(e instanceof AgentSelectionRequiredError)return;throw e}}function prepareGenericRoute(e){const t={channel:e.conversation.channel,accountId:normalizeAccountId(e.conversation.accountId),conversationId:e.conversation.peerId,...e.context?.parentPeerId?{parentConversationId:e.context.parentPeerId}:{}};return{conversation:t,route:resolveConfiguredBindingRoute({cfg:e.config,route:e.route,conversation:t}).route}}function resolveInspectedGenericRouteOwner(e,t){const n=inspectRuntimeConversationBindingRoute({route:e,inspection:t});if(n.bindingOwnerAvailable===false)return{kind:`unavailable`};if(n.pluginId&&hasActivePluginClaimOwner(n.pluginId))return{kind:`available`};return{kind:`available`,agentId:normalizeAgentId(n.route.agentId)}}function bindingPeerCouldMatchConversation(e,t){const n=e.match.peer;if(!n)return true;const r=normalizeChatType(n.kind);const i=normalizeRouteBindingId(n.id);if(!r||!i)return false;return peerKindMatches(r,t.kind)&&(i===`*`||i===t.peerId)}function hasUnrecordedContextualBinding(e){const t=normalizeLowercaseStringOrEmpty(e.conversation.channel);const n=normalizeAccountId(e.conversation.accountId);const r=Boolean(e.conversation.parentConversationRef||e.conversation.threadId);const i=e.conversation.kind===`channel`;return listRouteBindings(e.config).some(a=>{const o=a.match.accountId?.trim()??``;return Boolean(i&&normalizeRouteBindingId(a.match.guildId)||normalizeRouteBindingId(a.match.teamId)||i&&a.match.roles?.length||r&&a.match.peer?.kind!==`direct`&&normalizeRouteBindingId(a.match.peer?.id))&&normalizeAgentId(a.agentId)!==e.resolvedAgentId&&normalizeLowercaseStringOrEmpty(a.match.channel)===t&&(o===`*`||normalizeAccountId(o)===n)&&bindingPeerCouldMatchConversation(a,e.conversation)})}function finishRouteEligibility(e,t){if(t.kind===`unavailable`)return`unavailable`;if(t.agentId!==normalizeAgentId(e.agentId))return`denied`;return!e.conversation.routeContextObserved&&!e.conversation.routeContext&&hasUnrecordedContextualBinding({config:e.config,conversation:e.conversation,resolvedAgentId:t.agentId})?`denied`:`eligible`}async function prepareConversationRouteEligibilitiesForAgent(e){const t=e.conversations.map(t=>({config:e.config,agentId:e.agentId,conversation:t}));const n=[];const inspectBindings=async e=>{const t=await prepareSessionBindingInspections(e);n.push(t.dispose);return()=>t.inspect()};try{const r=/* @__PURE__ */ new Map;const i=/* @__PURE__ */ new Map;const a=t.map((e,t)=>{const n=normalizeAnyChannelId(e.conversation.channel);const i=n?getLoadedChannelPlugin(n):void 0;const a=i?.messaging?.prepareConversationRouteOwnersAsync;if(a){const e=r.get(a)??[];e.push(t);r.set(a,e)}return{channel:n,plugin:i}});for(const[n,a]of r){let r=true;let o;try{o=await n(a.map(n=>pluginRouteOwnerInput(e.config,t[n].conversation)),e=>{if(!r)throw new Error(`Conversation route preparation is no longer active`);return inspectBindings(e)})}finally{r=false}if(o.length!==a.length)throw new Error(`Plugin route owner returned an incomplete selection`);a.forEach((e,t)=>i.set(e,o[t]))}const o=t.map((e,t)=>{const n=i.get(t);if(resolvePluginRouteOwner(e.config,e.conversation,n))return{kind:`plugin`,resolver:n};const r=resolveConfiguredRouteOwner(e.config,e.conversation,e.conversation.routeContext);return r?{kind:`binding`,...prepareGenericRoute({...e,route:r,context:e.conversation.routeContext})}:{kind:`denied`}});const s=await inspectBindings(o.flatMap(e=>e.kind===`binding`?[e.conversation]:[]));return{read(){for(const{channel:e,plugin:t}of a)if(e&&getLoadedChannelPlugin(e)!==t)throw new Error(`Conversation route owner changed. Retry the request.`);const e=s();let n=0;return o.map((r,i)=>{if(r.kind===`denied`)return`denied`;const a=t[i];const o=r.kind===`plugin`?resolvePluginRouteOwner(a.config,a.conversation,r.resolver):resolveInspectedGenericRouteOwner(r.route,e[n++]);return o?finishRouteEligibility(a,o):`unavailable`})},dispose(){for(const e of n)e()}}}catch(e){for(const e of n)e();throw e}}async function resolveConversationRouteEligibilitiesForAgent(e){const t=await prepareConversationRouteEligibilitiesForAgent(e);try{return t.read()}finally{t.dispose()}}function assertConversationDeliveryRouteAuthorized(e,t){const n=e.conversation;try{assertConversationAuthority(n,e)}catch(t){throw new PlatformMessageNotDispatchedError(`Conversation is no longer available to this agent: ${e.conversationRef}`,{cause:t,retryable:false})}if(t===`eligible`)return;throw new PlatformMessageNotDispatchedError(t===`unavailable`?`Conversation ownership is temporarily unavailable: ${e.conversationRef}`:`Conversation is no longer available to this agent: ${e.conversationRef}`,{cause:void 0,retryable:t===`unavailable`})}async function prepareConversationDeliveryRouteAuthorization(e){const t=await prepareConversationRouteEligibilitiesForAgent({...e,conversations:[e.conversation]});const assertConfigCurrent=()=>{if((e.readCurrentConfig?.()??e.config)!==e.config)throw new PlatformMessageNotDispatchedError(`Conversation routing configuration changed. Retry the request.`,{cause:void 0,retryable:true})};return{assertRequestEligible(){assertConfigCurrent();const n=t.read()[0];if(n===`denied`)throw new ConversationInputError(`Conversation is not available to this agent: ${e.conversationRef}`);if(n===`unavailable`)throw new Error(`Conversation ownership is temporarily unavailable: ${e.conversationRef}`)},assertCurrent(n,r=e){assertConfigCurrent();assertConversationDeliveryRouteAuthorized({...e,...r,conversation:n},t.read()[0])},dispose:()=>t.dispose()}}async function withAuthorizedConversationDelivery(e,t){const n=e.routeAuthority?void 0:await readConversation(e.scope,e.conversationRef);if(!e.routeAuthority&&!n)throw new PlatformMessageNotDispatchedError(`Conversation is no longer available`,{cause:void 0,retryable:false});const r=e.routeAuthority??await prepareConversationDeliveryRouteAuthorization({...e,conversation:n});try{return await withConversationAuthority(e.scope,{conversationRef:e.conversationRef},({conversation:n})=>{r.assertCurrent(n,e);return t})}finally{if(!e.routeAuthority)r.dispose()}}async function withAuthorizedQueuedConversationDelivery(e,t,n){const r=await getConversationDeliveryOperation(t,e.operationId);if(!r)throw new PlatformMessageNotDispatchedError(`Conversation delivery operation no longer exists: ${e.operationId}`,{cause:void 0,retryable:false});const i=await readConversation(t,r.conversationRef);if(!i)throw new PlatformMessageNotDispatchedError(`Conversation is no longer available`,{cause:void 0,retryable:false});const a={conversationRef:r.conversationRef,expectedRouteFingerprint:e.routeFingerprint};const o=await prepareConversationDeliveryRouteAuthorization({...a,config:e.readCurrentConfig(),readCurrentConfig:e.readCurrentConfig,agentId:t.agentId,conversation:i});try{return await withConversationAuthority(t,{operationId:e.operationId},({operation:t,conversation:r})=>{if(!t||t.conversationRef!==a.conversationRef)throw new PlatformMessageNotDispatchedError(`Conversation delivery operation no longer exists: ${e.operationId}`,{cause:void 0,retryable:false});o.assertCurrent(r,a);return n})}finally{o.dispose()}}export{withAuthorizedQueuedConversationDelivery as a,withAuthorizedConversationDelivery as i,prepareConversationRouteEligibilitiesForAgent as n,ConversationInputError as o,resolveConversationRouteEligibilitiesForAgent as r,ConversationOperationConflictError as s,prepareConversationDeliveryRouteAuthorization as t};