UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines • 12.3 kB
import{b as uniqueStrings}from"./string-normalization-D_oBUpO3.mjs";import{n as ok,t as err}from"./result-CkiK_t2O.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as createLazyImportLoader}from"./lazy-promise-CismJCQR.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{n as normalizeAccountId}from"./account-id-3yqrEsRn.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{i as getLoadedChannelPluginForRead}from"./registry-loaded-BEn6LBRM.mjs";import{t as INTERNAL_MESSAGE_CHANNEL}from"./message-channel-constants-BbP_hczw.mjs";import"./message-channel-514k57tV.mjs";import{t as chatRef}from"./chat-ref-DFIHpEiJ.mjs";import{l as normalizeSessionDeliveryState}from"./delivery-context.shared-L-4UIv4-.mjs";import{i as resolveChannelAllowFrom}from"./account-resolution-BMEKSThh.mjs";import{r as resolveAgentMainSessionKey}from"./main-session-C6FGqx0x.mjs";import{n as readSessionEntriesFromStoreInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import{n as foldedSessionKeyAliasCandidates}from"./store-entry-DbH6jRLn.mjs";import{t as resolveCronAgentSessionKey}from"./session-key-CeBBOtWJ.mjs";import{n as stripOutboundTargetKindPrefix,r as stripTargetProviderPrefix}from"./channel-target-prefix-CDxsZqXF.mjs";import{n as extractDeliveryInfoBatch}from"./delivery-info-BTs-RtuV.mjs";import{t as runTasksWithConcurrency}from"./run-with-concurrency-BX7H2nwl.mjs";import{n as hasExplicitCronDeliveryTarget}from"./delivery-target-validation-C-8re9js.mjs";import{t as resolveSessionDeliveryTarget}from"./targets-session-CAONApI3.mjs";import{r as isReservedTargetLiteralError}from"./target-errors-CihWlpA7.mjs";import{t as resolveOutboundTargetWithPlugin}from"./targets-resolve-shared-2myJgJEw.mjs"; //!src/infra/outbound/targets-loaded.ts async function tryResolveLoadedOutboundTarget(e){return resolveOutboundTargetWithPlugin({plugin:getLoadedChannelPluginForRead(e.channel),target:e})} //!src/cron/isolated-agent/delivery-route-session-key.ts function selectCronRouteCurrentSessionKey(e,t,n,r){const i=parseAgentSessionKey(e);if(!i||i.agentId!==t)return;const a=/^([^:]+):(direct|group|channel):([^:]+)(?::(?:thread|topic):.+)?$/i.exec(i.rest);const o=stripOutboundTargetKindPrefix(stripTargetProviderPrefix(r,n));return a?.[1]?.toLowerCase()===n.toLowerCase()&&a[3]===o?e:void 0} //!src/cron/isolated-agent/delivery-target-context.ts async function readCronDeliveryTargetContexts(e,t){const n=/* @__PURE__ */ new Map;const r=t.map(({agentId:t,sessionKey:r})=>{try{const i=r?.trim();const a=JSON.stringify([t,i]);let o=n.get(a);if(!o){o={agentId:t,rawSessionKey:i,mainSessionKey:resolveAgentMainSessionKey({cfg:e,agentId:t}),storePath:resolveSessionStorePathCore(e.session?.store,{agentId:t}),threadSessionKey:i?resolveCronAgentSessionKey({sessionKey:i,agentId:t,mainKey:e.session?.mainKey,cfg:e}):void 0};n.set(a,o)}return ok(o)}catch(e){return err(e)}});const i=await extractDeliveryInfoBatch(r.map(e=>e.ok?{sessionKey:e.value.threadSessionKey,agentId:e.value.agentId}:{}),{cfg:e});const a=/* @__PURE__ */ new Set;for(const[e,t]of r.entries())if(t.ok&&!i[e]?.deliveryContext)a.add(t.value);const o=/* @__PURE__ */ new Map;for(const e of a){const t=JSON.stringify([e.agentId,e.storePath]);const n=o.get(t);if(n)n.push(e);else o.set(t,[e])}const read=async e=>{const{agentId:t,storePath:n}=e[0];try{const r=await readSessionEntriesFromStoreInWorker({agentId:t,storePath:n,projection:`list`,snapshotFields:[],sessionKeys:[...new Set(e.flatMap(({threadSessionKey:e,mainSessionKey:t})=>[e,t].flatMap(e=>e?[e].concat(foldedSessionKeyAliasCandidates(e)):[])))]});return ok(new Map(r.entries.map(({sessionKey:e,entry:t})=>[e,t])))}catch(e){return err(e)}};const s=/* @__PURE__ */ new Map;await runTasksWithConcurrency({limit:8,tasks:[...o.values()].map(e=>async()=>{const t=await read(e);for(const n of e)s.set(n,!t.ok&&e.length>1?await read([n]):t)})});return r.map((e,t)=>{if(!e.ok)return e;const{mainSessionKey:n,rawSessionKey:r,threadSessionKey:a}=e.value;const o=i[t];const c=o?.deliveryContext;const l=c&&o?.threadId?{...c,threadId:o.threadId}:c;const u=l?void 0:s.get(e.value);if(u&&!u.ok)return u;const d=a?u?.value.get(a):void 0;const f=u?.value.get(n);const p=d??f;return ok({mainSessionKey:n,rawSessionKey:r,threadSessionKey:a,main:l||p?{sessionId:l?a??n:p.sessionId,updatedAt:l?0:p.updatedAt,delivery:l?normalizeSessionDeliveryState({context:l}):structuredClone(p?.delivery)}:void 0,usedSharedMainFallback:!l&&!d&&f!==void 0})})} //!src/cron/isolated-agent/delivery-target.ts function requiresExternalCronDelivery(e,t){return hasExplicitCronDeliveryTarget(e)||t.channel!==void 0&&t.channel!==`webchat`}const targetsRuntimeLoader=createLazyImportLoader(()=>import(`./targets.runtime-B57XJlSr.mjs`));async function resolveOutboundTargetWithRuntime(e){try{const t=await tryResolveLoadedOutboundTarget(e);if(t)return t;const{resolveOutboundTarget:n}=await targetsRuntimeLoader.load();return await n({...e,allowBootstrap:true})}catch(e){return{ok:false,error:/* @__PURE__ */ new Error(`Invalid delivery target: ${formatErrorMessage(e)}`)}}}const channelSelectionRuntimeLoader=createLazyImportLoader(()=>import(`./channel-selection.runtime-CYx6flr7.mjs`));const deliveryTargetRuntimeLoader=createLazyImportLoader(()=>import(`./delivery-target.runtime-CGTtkvKK.mjs`));const sessionGenerationRuntimeLoader=createLazyImportLoader(()=>import(`./session-delivery-generation-0RTLbrRH.mjs`));async function prepareCronDeliverySourceGenerations(e,t){if(t.length===0)return[];const{prepareChatLeaseBatch:n}=await sessionGenerationRuntimeLoader.load();return n(t.map(({agentId:t,sourceConversation:n})=>chatRef({agentId:t,storePath:resolveSessionStorePathCore(e.session?.store,{agentId:t}),sessionKey:n.sessionKey})))}async function prepareCronDeliveryTargetContexts(e,t){if(t.length===0)return[];await deliveryTargetRuntimeLoader.load();return readCronDeliveryTargetContexts(e,t)}function isNonEmptyThreadId(e){return e!=null&&e!==``}function routesSharePeer(e,t){return Boolean(e&&t&&e.baseSessionKey===t.baseSessionKey&&e.peer.kind===t.peer.kind&&e.peer.id===t.peer.id)}function stripSelectedProviderPrefix(e){const t=e.to?.trim();if(!t)return;return stripTargetProviderPrefix(t,e.channel).trim()||void 0}async function resolveDeliveryTarget(e,t,n,r){const i=typeof n.channel===`string`?n.channel:`last`;const a=typeof n.to===`string`?n.to:void 0;const o=i===`last`;const s=await deliveryTargetRuntimeLoader.load();const c=n.sourceConversation;if(c&&!hasExplicitCronDeliveryTarget(n))try{const n=r?.sourceGeneration;if(n&&!n.ok)throw n.error;const i=n?.value??await(await sessionGenerationRuntimeLoader.load()).prepareChatLease(chatRef({agentId:t,storePath:resolveSessionStorePathCore(e.session?.store,{agentId:t}),sessionKey:c.sessionKey}));try{i.assertCurrent()}finally{if(!n)i.release()}}catch(e){return{ok:false,mode:`implicit`,sourceConversationUnavailable:true,error:/* @__PURE__ */ new Error(`Creating conversation unavailable: ${formatErrorMessage(e)}`)}}const l=r?.sessionContext??await(async()=>{const r=(await readCronDeliveryTargetContexts(e,[{agentId:t,sessionKey:n.sessionKey}]))[0];if(!r.ok)throw r.error;return r.value})();const{rawSessionKey:u,threadSessionKey:d,usedSharedMainFallback:f}=l;const p=n.sessionTarget===`current`||n.sourceConversation!==void 0;const m=p&&f?void 0:l.main;if(n.target===`owner`){const r=await s.resolveProactiveDeliveryTargetWithSessionRoute({cfg:e,agentId:t,entry:m,currentSessionKey:d,policy:{target:`owner`,channel:i===`last`?void 0:i,accountId:n.accountId,directPolicy:n.directPolicy}});const a=stripSelectedProviderPrefix({channel:r.channel,to:r.to});return r.channel!==`none`&&a?{ok:true,channel:r.channel,to:a,accountId:r.accountId,threadId:r.threadId,mode:`explicit`}:{ok:false,channel:r.channel,accountId:r.accountId,mode:`explicit`,...r.reason===`dm-blocked`?{deliverySuppressionReason:`channel_transform`}:{},error:/* @__PURE__ */ new Error(`Owner delivery unavailable (${r.reason??`no-route`}); configure an authorized owner DM or edit this automation's delivery`)}}const h=resolveSessionDeliveryTarget({entry:m,requestedChannel:i,explicitTo:a,explicitThreadId:n.threadId,allowMismatchedLastTo:o});let g;let _;if(!h.channel){if(h.lastChannel)g=h.lastChannel;else if(!p||hasExplicitCronDeliveryTarget(n))try{const{resolveMessageChannelSelection:t}=await channelSelectionRuntimeLoader.load();g=(await t({cfg:e})).channel}catch(e){const t=formatErrorMessage(e);_=/* @__PURE__ */ new Error(`${t} Set delivery.channel explicitly or use a main session with a previous channel.`)}}const v=g?resolveSessionDeliveryTarget({entry:m,requestedChannel:i,explicitTo:a,explicitThreadId:n.threadId,fallbackChannel:g,allowMismatchedLastTo:o,mode:h.mode}):h;const y=v.channel??g;const b=v.mode;let x=v.to;let S=(typeof n.accountId===`string`?n.accountId.trim()||void 0:void 0)??v.accountId;if(!S&&y)S=s.resolveFirstBoundAccountId({cfg:e,channelId:y,agentId:t})??s.resolveChannelDefaultAccountIdForDelivery({cfg:e,channel:y,agentId:t});if(!y)return{ok:false,channel:void 0,to:void 0,accountId:S,threadId:void 0,mode:b,error:_??/* @__PURE__ */ new Error(`Channel is required when delivery.channel=last has no previous channel.`)};const C=isNonEmptyThreadId(n.threadId)?n.threadId:void 0;const failTarget=e=>({ok:false,channel:y,to:void 0,accountId:S,threadId:C,mode:b,error:e});let w;if(b===`implicit`){const{getLoadedChannelPluginForRead:t,mapAllowFromEntries:n}=s;const r=t(y);const i=normalizeAccountId(S);const a=r?await resolveChannelAllowFrom({plugin:r,cfg:e,accountId:i}):void 0;const o=a?n(a):[];const c=uniqueStrings(o);w=c;if(x&&c.length>0){if(!(await resolveOutboundTargetWithRuntime({channel:y,to:x,cfg:e,accountId:S,mode:b,allowFrom:w})).ok)x=c[0]}}if(!u&&b===`implicit`&&!a&&f&&x!=null&&x===v.lastTo)return failTarget(/* @__PURE__ */ new Error(`Refusing implicit isolated cron delivery: the target would be inherited from the shared agent-main session bucket's last recipient, which is ambiguous across conversations and can deliver to the wrong room (and replay there after a restart). Set delivery.channel and delivery.to explicitly, or run the cron from a session that carries its own delivery context.`));const T=x;const E=await resolveOutboundTargetWithRuntime({channel:y,to:x,cfg:e,accountId:S,mode:b,allowFrom:w});if(!E.ok){if(!x||!isReservedTargetLiteralError(E.error))return failTarget(E.error)}else x=E.to;const D=await s.resolveChannelTargetForDelivery({cfg:e,channel:y,agentId:t,input:x,accountId:S});if(!D.ok)return failTarget(D.error);const O=D.target;const k=O.source===`directory`?O.to:T??x;const A=O.resolutionSource===`normalized`?stripSelectedProviderPrefix({channel:y,to:O.to}):O.to.trim();if(!A)return failTarget(/* @__PURE__ */ new Error(`Target is required`));x=A;const resolveRoute=async n=>{try{return await s.resolveOutboundSessionRouteForDelivery({cfg:e,channel:y,agentId:t,...n,currentSessionKey:selectCronRouteCurrentSessionKey(u,t,y,n.target)})}catch{return null}};const j=await resolveRoute({accountId:S,target:k,resolvedTarget:O,threadId:C});const M=s.channelCanResolveOutboundSessionRoute({cfg:e,channel:y,agentId:t});const N=j&&(j.threadId!==void 0||j.to!==k);if(j&&M&&N){const e=stripSelectedProviderPrefix({channel:y,to:j.to});if(!e)return failTarget(/* @__PURE__ */ new Error(`Target is required`));x=e}let P=false;if(r?.inheritSessionThread!==false&&isNonEmptyThreadId(v.threadId)){if(a){const e=v.lastTo;P=routesSharePeer(j,e&&v.lastChannel===y?await resolveRoute({accountId:v.lastAccountId??S,target:e,threadId:v.lastThreadId}):null)}else P=v.channel===v.lastChannel&&v.to===v.lastTo}const F=C??j?.threadId??(P?v.threadId:void 0);const I=j&&j.threadId===F?j:await resolveRoute({accountId:S,target:x,resolvedTarget:O,threadId:F});if(n.directPolicy===`block`&&(O.kind===`user`||j?.chatType===`direct`||j?.peer.kind===`direct`))return{...failTarget(/* @__PURE__ */ new Error(`Automation delivery to direct messages is blocked by delivery.directPolicy`)),deliverySuppressionReason:`channel_transform`};return{ok:true,channel:y,to:x,accountId:S,threadId:F,mode:b,...I?{sessionRoute:I}:{}}}export{resolveDeliveryTarget as i,prepareCronDeliveryTargetContexts as n,requiresExternalCronDelivery as r,prepareCronDeliverySourceGenerations as t};