openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
18 lines • 15.7 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{i as publicChannelTurn}from"./legacy-sdk-reply-dispatch-BBfp03px.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{r as resolveAgentConfig}from"./agent-scope-config-CG9CFpGX.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{t as warnPluginSdkDeprecation}from"./sdk-deprecation-BDUCyBrU.mjs";import{n as resolveInboundDebounceMs,t as createInboundDebouncer}from"./inbound-debounce-AdZEtXcM.mjs";import{l as withSessionEntryReadOnlyInWorker,o as readSessionUpdatedAtInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import"./session-accessor-CY8UYP4m.mjs";import{o as readSessionUpdatedAtCore}from"./session-accessor.sqlite-entry-CQTjQD5y.mjs";import{a as resolveSessionTranscriptRuntimeTarget}from"./session-accessor.transcript-target-CNlRFjvI.mjs";import"./sessions-DQD7zQ95.mjs";import{o as resolveAgentRoute}from"./resolve-route-DpjPYoyg.mjs";import"./hooks-Bu2gwS_g.mjs";import{n as readChannelIngressStoreAllowFromForDmPolicy}from"./store-allow-from-CZObZKr8.mjs";import"./location-CLRIvK_g.mjs";import{l as normalizeOutboundReplyPayload}from"./reply-payload-C6sYX5Rf.mjs";import{t as expandAllowFromWithAccessGroups}from"./access-groups-xlLrXqiU.mjs";import{n as resolveDmGroupAccessWithLists,t as DM_GROUP_ACCESS_REASON}from"./dm-policy-shared-CvTh1Gcv.mjs";import"./mentions-2eKnPtcO.mjs";import"./dispatch-OJrrdqsb.mjs";import{r as isControlCommandMessage}from"./command-detection-Cg03lzSK.mjs";import{t as appendPreparedTranscriptEvent}from"./session-transcript-event-osdYTYCA.mjs";import{a as resolveEnvelopeFormatOptions}from"./envelope-B7t5cF__.mjs";import"./media-7VtkM6sY.mjs";import{a as filterChannelInboundSupplementalContext,n as buildChannelInboundEventContext,r as buildHostChannelInboundEventContext,t as publicChannelTurnParams}from"./reply-options-D-cQz0Qt.mjs";import"./live-CZp14Lp3.mjs";import{t as runPreparedChannelTurn}from"./execution-Cpe8EZ0A.mjs";import{t as createChannelReplyPipeline}from"./reply-pipeline-BCqCQ6iZ.mjs";import{n as dispatchAssembledChannelTurn,r as dispatchRoutedChannelTurn}from"./lifecycle-BolRkuRX.mjs";import{n as runChannelTurn}from"./run-channel-turn-KxIBuYA-.mjs";import{n as createChannelInboundEnvelopeBuilderAsync,o as resolveInboundRouteEnvelopeBuilderWithRuntime}from"./envelope-BKdDYYXy.mjs";import"./channel-access-compat-BMPN_TZD.mjs";import"./direct-dm-guard-policy-DSnz0v84.mjs";import"./logging-B6XiK4pi.mjs";
//!src/channels/direct-dm-access.ts
function toLegacyDmReasonCode(e){switch(e){case DM_GROUP_ACCESS_REASON.DM_POLICY_OPEN:case DM_GROUP_ACCESS_REASON.DM_POLICY_DISABLED:case DM_GROUP_ACCESS_REASON.DM_POLICY_ALLOWLISTED:case DM_GROUP_ACCESS_REASON.DM_POLICY_PAIRING_REQUIRED:case DM_GROUP_ACCESS_REASON.DM_POLICY_NOT_ALLOWLISTED:return e;default:return DM_GROUP_ACCESS_REASON.DM_POLICY_NOT_ALLOWLISTED}}async function resolveInboundDirectDmAccessWithRuntime(e){const t=e.dmPolicy??`pairing`;const n=e.runtime.shouldComputeCommandAuthorized(e.rawBody,e.cfg);const r=t===`pairing`?await readChannelIngressStoreAllowFromForDmPolicy({provider:e.channel,accountId:e.accountId,dmPolicy:t,readStore:e.readStoreAllowFrom}):[];const[i,a]=await Promise.all([e.allowFrom,r].map(t=>expandAllowFromWithAccessGroups({cfg:e.cfg,allowFrom:t,channel:e.channel,accountId:e.accountId,senderId:e.senderId,isSenderAllowed:e.isSenderAllowed,resolveMembership:e.resolveAccessGroupMembership})));const o=resolveDmGroupAccessWithLists({isGroup:false,dmPolicy:t,allowFrom:i,storeAllowFrom:a,groupAllowFromFallbackToAllowFrom:false,isSenderAllowed:t=>e.isSenderAllowed(e.senderId,t)});const s=toLegacyDmReasonCode(o.reasonCode);const c=e.isSenderAllowed(e.senderId,o.effectiveAllowFrom);const l=n?e.runtime.resolveCommandAuthorizedFromAuthorizers?.({useAccessGroups:true,authorizers:[{configured:o.effectiveAllowFrom.length>0,allowed:c}],modeWhenAccessGroupsOff:e.modeWhenAccessGroupsOff})??c:void 0;return{access:{decision:o.decision,reasonCode:s,reason:o.reason,effectiveAllowFrom:o.effectiveAllowFrom},shouldComputeAuth:n,senderAllowedForCommands:c,commandAuthorized:l}}function createPreCryptoDirectDmAuthorizer(e){return async t=>{const n=await e.resolveAccess(t.senderId);const r=`access`in n?n.access:n;if(r.decision===`allow`)return`allow`;if(r.decision===`pairing`){await e.issuePairingChallenge?.({senderId:t.senderId,reply:t.reply});return`pairing`}e.onBlocked?.({senderId:t.senderId,reason:r.reason,reasonCode:r.reasonCode});return`block`}}
//!src/channels/direct-dm.ts
async function dispatchInboundDirectDm(e){const t=resolveAgentRoute({cfg:e.cfg,channel:e.channel,accountId:e.accountId,peer:e.peer});const n=e.resolveChannelIngress?await e.resolveChannelIngress({agentId:t.agentId,sessionKey:t.sessionKey,messageId:e.messageId,inboundEventKind:`user_request`}):e.channelIngress;const r=n===e.channelIngress?e:{...e,channelIngress:n};const i=(await createChannelInboundEnvelopeBuilderAsync({cfg:e.cfg,route:t}))({channel:e.channelLabel,from:e.conversationLabel,body:e.rawBody,timestamp:e.timestamp});const a=e.channelRuntime?.inbound?.buildContext;const o=typeof a===`function`?a:buildChannelInboundEventContext;const s=await Promise.resolve(o({channel:e.channel,accountId:t.accountId,provider:e.provider,surface:e.surface,messageId:e.messageId,messageIdFull:e.messageId,timestamp:e.timestamp,from:e.senderAddress,sender:{id:e.senderId,name:e.conversationLabel},conversation:{kind:`direct`,id:e.peer.id,routePeer:e.peer,label:e.conversationLabel},route:{agentId:t.agentId,accountId:t.accountId,routeSessionKey:t.sessionKey,dispatchSessionKey:t.sessionKey},reply:{to:e.recipientAddress,originatingTo:e.originatingTo??e.senderAddress},message:{body:i,bodyForAgent:e.bodyForAgent??e.rawBody,rawBody:e.rawBody,commandBody:e.commandBody??e.rawBody},access:{commands:{authorized:e.commandAuthorized===true}},channelIngress:r.channelIngress,extra:{NativeDirectUserId:e.peer.id,OriginatingChannel:e.originatingChannel??e.channel,...e.extraContext}}));await dispatchRoutedChannelTurn(buildDirectDmTurnPlan(r,t,s));return{route:t,ctxPayload:s}}function buildDirectDmTurnPlan(e,t,n){const{onModelSelected:r,...i}=createChannelReplyPipeline({cfg:e.cfg,agentId:t.agentId,channel:e.channel,accountId:t.accountId??e.accountId});return{cfg:e.cfg,channel:e.channel,accountId:t.accountId??e.accountId,route:{agentId:t.agentId,sessionKey:t.sessionKey},ctxPayload:n,assertAuthority:e.assertAuthority,record:{onRecordError:e.onRecordError},delivery:{deliver:async t=>await e.deliver(normalizeOutboundReplyPayload(t)),onError:e.onDispatchError},replyPipeline:i,replyOptions:{onModelSelected:r,...e.turnAdoptionLifecycle?{turnAdoptionLifecycle:e.turnAdoptionLifecycle}:{}}}}async function dispatchInboundDirectDmWithRuntime(e){warnPluginSdkDeprecation({family:`channel-inbound-envelope`,method:`dispatchInboundDirectDmWithRuntime`,replacement:`dispatchInboundDirectDm`});const{route:t,buildEnvelope:n}=resolveInboundRouteEnvelopeBuilderWithRuntime({cfg:e.cfg,channel:e.channel,accountId:e.accountId,peer:e.peer,runtime:e.runtime.channel,sessionStore:e.cfg.session?.store});const{storePath:r,body:i}=n({channel:e.channelLabel,from:e.conversationLabel,body:e.rawBody,timestamp:e.timestamp});const a=e.runtime.channel.reply.finalizeInboundContext({Body:i,BodyForAgent:e.bodyForAgent??e.rawBody,RawBody:e.rawBody,CommandBody:e.commandBody??e.rawBody,From:e.senderAddress,To:e.recipientAddress,SessionKey:t.sessionKey,AccountId:t.accountId??e.accountId,ChatType:`direct`,ConversationLabel:e.conversationLabel,SenderId:e.senderId,Provider:e.provider??e.channel,Surface:e.surface??e.channel,MessageSid:e.messageId,MessageSidFull:e.messageId,Timestamp:e.timestamp,CommandAuthorized:e.commandAuthorized,...e.inboundAccessAuthorized===true?{InboundAccessAuthorized:true,ConversationRouteContextObserved:true}:{},ConversationRoutePeerId:e.peer.id,OriginatingChannel:e.originatingChannel??e.channel,OriginatingTo:e.originatingTo??e.senderAddress,NativeDirectUserId:e.peer.id,...e.extraContext});const o=buildDirectDmTurnPlan(e,t,a);await e.runtime.channel.inbound.run({channel:e.channel,accountId:t.accountId??e.accountId,raw:a,adapter:{ingest:()=>({id:e.messageId,timestamp:e.timestamp,rawText:e.rawBody,textForAgent:e.bodyForAgent,textForCommands:e.commandBody,raw:a}),resolveTurn:()=>o}});return{route:t,storePath:r,ctxPayload:a}}
//!src/channels/inbound-debounce-policy.ts
function shouldDebounceTextInbound(e){if(e.allowDebounce===false)return false;if(e.hasMedia)return false;const t=normalizeOptionalString(e.text)??``;if(!t)return false;return!isControlCommandMessage(t,e.cfg,e.commandOptions)}function createChannelInboundDebouncer(e){const t=resolveInboundDebounceMs({cfg:e.cfg,channel:e.channel,overrideMs:e.debounceMsOverride});const{cfg:n,channel:r,debounceMsOverride:i,...a}=e;return{debounceMs:t,debouncer:createInboundDebouncer({debounceMs:t,...a})}}
//!src/channels/session-envelope.ts
function resolveInboundSessionEnvelopeContext(e){warnPluginSdkDeprecation({family:`channel-inbound-envelope`,method:`resolveInboundSessionEnvelopeContext`,replacement:`await resolveInboundSessionEnvelopeContextAsync`});const t=resolveSessionStorePathCore(e.cfg.session?.store,{agentId:e.agentId});return{storePath:t,envelopeOptions:resolveEnvelopeFormatOptions(e.cfg),previousTimestamp:readSessionUpdatedAtCore({storePath:t,sessionKey:e.sessionKey})}}async function resolveInboundSessionEnvelopeContextAsync(e){const t=resolveSessionStorePathCore(e.cfg.session?.store,{agentId:e.agentId});return{storePath:t,envelopeOptions:resolveEnvelopeFormatOptions(e.cfg),previousTimestamp:await readSessionUpdatedAtInWorker({storePath:t,sessionKey:e.sessionKey})}}
//!src/channels/inbound-event/classification.ts
function classifyChannelInboundEvent(e){if(e.unmentionedGroupPolicy!==`room_event`)return`user_request`;if(e.conversation.kind!==`group`&&e.conversation.kind!==`channel`)return`user_request`;if(e.wasMentioned===true||e.hasControlCommand===true||e.hasAbortRequest===true||e.commandSource===`native`)return`user_request`;return`room_event`}function resolveUnmentionedGroupInboundPolicy(e){const t=e.agentId?resolveAgentConfig(e.cfg,e.agentId)?.groupChat:void 0;if(t&&Object.hasOwn(t,`unmentionedInbound`))return t.unmentionedInbound??`user_request`;return e.cfg.messages?.groupChat?.unmentionedInbound??`user_request`}
//!src/channels/feedback-reflection.ts
const DEFAULT_CHANNEL_FEEDBACK_REFLECTION_COOLDOWN_MS=3e5;const MAX_RESPONSE_CHARS=500;const MAX_COOLDOWN_ENTRIES=500;const lastReflectionBySession=/* @__PURE__ */ new Map;async function recordChannelFeedbackEvent(e){const t=resolveSessionStorePathCore(e.cfg.session?.store,{agentId:e.agentId});return withSessionEntryReadOnlyInWorker({agentId:e.agentId,sessionKey:e.sessionKey,storePath:t},()=>{},async(n,r)=>{if(!n.ok)throw n.error;if(!n.value?.sessionId)return false;const i=await resolveSessionTranscriptRuntimeTarget({...r.scope,agentId:e.agentId,sessionId:n.value.sessionId,sessionKey:e.sessionKey,storePath:r.scope?.storePath??t});await appendPreparedTranscriptEvent({...i,env:r.scope?.env},e.event,r.assertCurrent);return true})}function buildReflectionPrompt(e){const t=e.thumbedDownResponse;const n=t&&t.length>MAX_RESPONSE_CHARS?`${truncateUtf16Safe(t,MAX_RESPONSE_CHARS)}...`:t;return[`A user indicated your previous response wasn't helpful.`,n?`\nYour response was:\n> ${n}`:void 0,e.userComment?`\nUser's comment: "${e.userComment}"`:void 0,`
Briefly reflect: what could you improve? Consider tone, length, accuracy, relevance, and specificity. Reply with one JSON object only: {"learning":"...","followUp":false,"userMessage":""}. Keep learning to 1-2 sentences. Set followUp only when the user needs a direct reply.`].filter(Boolean).join(`
`)}function parseReflectionResponse(e){const t=e.trim();const n=[t,...t.match(/```(?:json)?\s*([\s\S]*?)```/i)?.slice(1,2)??[]];for(const e of n)try{const t=JSON.parse(e.trim());const n=typeof t.learning===`string`?t.learning.trim():``;if(!n)continue;return{learning:n,followUp:t.followUp===true||typeof t.followUp===`string`&&[`true`,`yes`].includes(t.followUp.trim().toLowerCase()),userMessage:(typeof t.userMessage===`string`?t.userMessage.trim():``)||void 0}}catch{}return t?{learning:t,followUp:false}:null}async function runChannelFeedbackReflection(e){const t=e.cooldownMs??3e5;if(Date.now()-(lastReflectionBySession.get(e.sessionKey)??Number.NEGATIVE_INFINITY)<t)return{status:`cooldown`};const n=buildReflectionPrompt(e);const r=Date.now();const i=(await createChannelInboundEnvelopeBuilderAsync({cfg:e.cfg,route:{agentId:e.agentId,sessionKey:e.sessionKey}}))({channel:e.channelLabel,from:`system`,body:n,timestamp:r});const a=`conversation:${e.conversationId}`;const o=buildHostChannelInboundEventContext({channelIngress:`unsupported`,channel:e.channel,accountId:e.accountId,messageId:`feedback-reflection:${r}`,timestamp:r,from:`${e.channel}:system:${e.conversationId}`,sender:{id:`system`,name:`system`},conversation:{kind:e.conversationKind,id:e.conversationId},route:{agentId:e.agentId,accountId:e.accountId,routeSessionKey:e.sessionKey,dispatchSessionKey:e.sessionKey},reply:{to:a,originatingTo:a},message:{body:i,bodyForAgent:n,rawBody:n,commandBody:n},access:{commands:{authorized:false}},extra:{ConversationRouteContextObserved:false}});const s=[];await dispatchRoutedChannelTurn({cfg:e.cfg,channel:e.channel,accountId:e.accountId,route:{agentId:e.agentId,sessionKey:e.sessionKey},ctxPayload:o,record:{onRecordError:e.onRecordError},delivery:{deliver:async e=>{if(e.text)s.push(e.text);return{visibleReplySent:false}},onError:t=>e.onDispatchError?.(t)},replyPipeline:{}});const c=s.join(`
`);const l=parseReflectionResponse(c);if(!l)return{status:`empty`};lastReflectionBySession.set(e.sessionKey,Date.now());if(lastReflectionBySession.size>MAX_COOLDOWN_ENTRIES){for(const[e,n]of lastReflectionBySession)if(Date.now()-n>=t)lastReflectionBySession.delete(e)}return{status:`complete`,learning:l.learning,storePath:resolveSessionStorePathCore(e.cfg.session?.store,{agentId:e.agentId}),followUp:l.followUp,userMessage:l.userMessage,responseLength:c.trim().length}}
//!src/plugin-sdk/channel-inbound.ts
function buildChannelTurnContext(e){const t=e.message.inboundEventKind??e.message.inboundTurnKind;const n=buildChannelInboundEventContext({...e,message:{...e.message,...t?{inboundEventKind:t}:{}}});return{...n,InboundTurnKind:n.InboundEventKind}}const filterChannelTurnSupplementalContext=filterChannelInboundSupplementalContext;async function runPreparedInboundReply(e){return await runPreparedChannelTurn(e)}async function runChannelInboundEvent(e){return await runChannelTurn(publicChannelTurnParams(e))}async function dispatchChannelInboundReply(e){return await dispatchAssembledChannelTurn(publicChannelTurn(e))}async function dispatchChannelInboundTurn(e){return await dispatchRoutedChannelTurn(publicChannelTurn(e))}export{dispatchInboundDirectDmWithRuntime as _,runChannelInboundEvent as a,recordChannelFeedbackEvent as c,resolveUnmentionedGroupInboundPolicy as d,resolveInboundSessionEnvelopeContext as f,dispatchInboundDirectDm as g,shouldDebounceTextInbound as h,filterChannelTurnSupplementalContext as i,runChannelFeedbackReflection as l,createChannelInboundDebouncer as m,dispatchChannelInboundReply as n,runPreparedInboundReply as o,resolveInboundSessionEnvelopeContextAsync as p,dispatchChannelInboundTurn as r,DEFAULT_CHANNEL_FEEDBACK_REFLECTION_COOLDOWN_MS as s,buildChannelTurnContext as t,classifyChannelInboundEvent as u,createPreCryptoDirectDmAuthorizer as v,resolveInboundDirectDmAccessWithRuntime as y};