UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 7.33 kB
import{a as normalizeFastMode}from"./string-coerce-CpTFcSwY.mjs";import{n as createLazyPromise}from"./lazy-promise-CismJCQR.mjs";import{N as parseAgentSessionKey,m as scopeLegacySessionKeyToAgent}from"./session-key-BPgKfU2m.mjs";import{Dr as validateSessionsSearchParams}from"./src-BDZMFmKa.mjs";import{a as readNonNegativeIntegerParam,d as readToolStringParam,s as readPositiveIntegerParam}from"./common-DIgvX97L.mjs"; //!src/agents/tools/embedded-gateway-stub.ts const SESSIONS_SEARCH_MAX_QUERY_CHARS=4096;const getRuntime=createLazyPromise(()=>import(`./embedded-gateway-stub.runtime-BQe7ktH3.mjs`));let sessionProjection;function bindEmbeddedSessionRowProjection(e){sessionProjection=e;return()=>{if(sessionProjection===e)sessionProjection=void 0}}async function borrowSessionRowProjection(){const e=sessionProjection;if(!e)throw new Error(`Embedded session projection is unavailable`);const t=await e;if(sessionProjection!==e)throw new Error(`Embedded session projection is unavailable`);return t}async function handleSessionsList(e){return(await getRuntime()).listProjectedSessions({projection:await borrowSessionRowProjection(),opts:e})}async function handleSessionsResolve(e){const t=await getRuntime();const n=sessionProjection;return await t.withPreparedSessionResolve({projection:await borrowSessionRowProjection(),isCurrent:()=>sessionProjection===n,client:null,p:e},e=>{if(!e.ok)throw new Error(e.error.message);if(`missing`in e)return{ok:false};if(`ambiguous`in e)return{ok:false,candidates:e.candidates};return{ok:true,key:e.key,agentId:e.agentId}})}async function handleSessionsDescribe(e){const t=readToolStringParam(e,`key`,{required:true});const n=readToolStringParam(e,`agentId`);if(e.includeNativeSubagents||e.includeDerivedTitles||e.includeLastMessage)throw new Error(`Session description enrichment requires a running gateway`);const r=await getRuntime();const i=sessionProjection;const query=e=>{const i=r.resolveRequestedSessionAgentId(e,t,n,`read`);if(!i.ok)throw new Error(i.error.message);return{key:t,agentId:i.agentId}};return r.withReadySessionRows(await borrowSessionRowProjection(),e=>[query(e)],e=>{if(sessionProjection!==i)throw new Error(`Session projection changed while describing the session; retry the request`);const{row:t}=r.prepareProjectedSessionPresentation(e).snapshot(query(e.state.cfg));return{session:t}})}async function handleSessionsSearch(e){const t=await getRuntime();const n=t.getRuntimeConfig();const r=typeof e.query===`string`?e.query.trim():``;if(!r)throw new Error(`query must not be empty`);if(r.length>SESSIONS_SEARCH_MAX_QUERY_CHARS)throw new Error(`query must not exceed ${SESSIONS_SEARCH_MAX_QUERY_CHARS} characters`);if(e.recall){if(!validateSessionsSearchParams(e))throw new Error(`Invalid sessions.search parameters`);const{searchRecallSessionTranscripts:t}=await import(`./sessions-search-recall-BMnfQQN7.mjs`);return t({query:r,limit:readPositiveIntegerParam(e,`limit`),recall:e.recall,projection:await borrowSessionRowProjection()})}if(e.agentId!==void 0&&e.sessionKeys===void 0)throw new Error(`agentId requires sessionKeys`);const i=Array.isArray(e.sessionKeys)?e.sessionKeys.filter(e=>typeof e===`string`):void 0;if(e.sessionKeys!==void 0&&(i?.length??0)===0)throw new Error(`sessionKeys must be a non-empty array of session keys`);const a=typeof e.agentId===`string`?e.agentId.trim():void 0;const o=i?.map(e=>a?t.resolveStoredSessionKeyForAgentStore({cfg:n,agentId:a,sessionKey:e}):t.resolveSessionStoreKey({cfg:n,sessionKey:e}));const s=new Set(o?.map(e=>t.resolveSessionAgentId({sessionKey:e,config:n,...a?{agentId:a}:{}})));if(s.size>1||a&&[...s].some(e=>e!==a))throw new Error(`sessions.search supports one agent per call`);const c=a??s.values().next().value??t.resolveSessionAgentId({sessionKey:`main`,config:n});const l=await t.searchSessionTranscripts({agentId:c,storePath:t.resolveSessionStorePathCore(n.session?.store,{agentId:c}),query:r,limit:readPositiveIntegerParam(e,`limit`),sessionKeys:o});return{results:l.hits,...l.archivedTranscriptsExcluded?{archivedTranscriptsExcluded:l.archivedTranscriptsExcluded}:{},...l.indexing?{indexing:true}:{},...l.truncated?{truncated:true}:{}}}async function handleChatHistory(e){const t=await getRuntime();const n=typeof e.sessionKey===`string`?e.sessionKey:``;const r=typeof e.agentId===`string`?e.agentId:void 0;const i=parseAgentSessionKey(n)?.agentId;const a=r??i;const o=readPositiveIntegerParam(e,`limit`);const s=readNonNegativeIntegerParam(e,`offset`);if(e.offset!==void 0&&s===void 0)throw new Error(`offset must be a non-negative integer`);const c=readToolStringParam(e,`messageId`,{required:e.messageId!==void 0});const l=readToolStringParam(e,`sessionId`,{required:e.sessionId!==void 0});const u=readToolStringParam(e,`cursor`,{required:e.cursor!==void 0});const d=t.decodeChatHistoryPageCursor(u);if(d===null)throw new Error(`invalid history page cursor`);if(s!==void 0&&c!==void 0)throw new Error(`offset and messageId cannot be used together`);if(u!==void 0&&(s!==void 0||c!==void 0))throw new Error(`cursor cannot be used with offset or messageId`);if(l!==void 0&&c===void 0)throw new Error(`sessionId requires messageId`);if(u!==void 0&&!d)throw new Error(`delta cursors require a running gateway`);const f=d?.messageId??c;const p=d?.sessionId??l;const m=readPositiveIntegerParam(e,`maxBytes`);if(m!==void 0&&m<1024)throw new Error(`maxBytes must be at least 1024`);const h=a?{agentId:a}:void 0;const{cfg:g,storePath:_,entry:v,canonicalKey:y}=await t.loadGatewaySessionEntryReadOnlyInWorker({cfg:t.getRuntimeConfig(),key:n,...h});const b=t.resolveSessionAgentId({sessionKey:n,config:g,agentId:a});if(p){const e=await t.resolveSessionKeyBySessionIdAsync({agentId:b,sessionId:p,storePath:_});if(!e||scopeLegacySessionKeyToAgent({sessionKey:e,agentId:b})!==scopeLegacySessionKeyToAgent({sessionKey:y,agentId:b}))throw new Error(`sessionId does not belong to sessionKey`)}const x=p??v?.sessionId;const S=p&&p!==v?.sessionId?void 0:v;const C=t.resolveSessionModelRef(g,v,b);const w=Math.min(1e3,o??200);const T=Math.min(m??Infinity,t.getMaxChatHistoryMessagesBytes());const E=t.resolveEffectiveChatHistoryMaxChars();const D={entry:S,provider:C.provider,sessionId:x,storePath:_,sessionAgentId:b,canonicalKey:y,max:w,maxHistoryBytes:T,responseHistoryBytes:Math.min(524288,T),effectiveMaxChars:E,offset:s,messageId:f,...d?{pageCursor:d}:{}};const O=await t.readChatHistoryPage(D);const{messagesBytes:k,responseHistoryBytes:A,omission:j,...M}=t.prepareChatHistoryResponsePage(O,D);const N=O.responseOffset??s;return{sessionKey:n,sessionId:x,...M,...O.windowReset?{windowReset:true}:{},...N!==void 0?{offset:N}:{},thinkingLevel:v?.thinkingLevel,fastMode:normalizeFastMode(v?.fastMode),verboseLevel:v?.verboseLevel}}function createEmbeddedCallGateway(){return async e=>{const t=e.method?.trim();const n=e.params??{};switch(t){case`sessions.list`:return await handleSessionsList(n);case`sessions.resolve`:return await handleSessionsResolve(n);case`sessions.describe`:return await handleSessionsDescribe(n);case`sessions.search`:return await handleSessionsSearch(n);case`chat.history`:return await handleChatHistory(n);default:throw new Error(`Method "${t}" requires a running gateway (unavailable in local embedded mode).`)}}}export{createEmbeddedCallGateway as n,bindEmbeddedSessionRowProjection as t};