UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 9.01 kB
import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{c as resolveIncognitoOpenClawAgentSqlitePath}from"./openclaw-agent-db.paths-SkzMsgQ0.mjs";import{t as chatRef}from"./chat-ref-DFIHpEiJ.mjs";import{l as withSessionEntryReadOnlyInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import{a as isSessionDeliveryGenerationRevokedError}from"./session-delivery-generation-CkLxbVNp.mjs";import{n as acquireTranscriptLease}from"./transcript-lease-BrjxUac5.mjs"; //!src/plugins/memory-audience.ts const MAX_LINEAGE_HOPS=64;const SESSION_ID_PATTERN=/^[a-f0-9-]{36}$/;const audienceRecords=/* @__PURE__ */ new WeakMap;const audienceSessionKeys=/* @__PURE__ */ new WeakMap;function releaseRecordLeases(e){for(const t of e.leases.splice(0))t.release()}const collectedAudienceRecords=new FinalizationRegistry(e=>{for(let t=e;t;t=t.parent){t.holders-=1;if(t.holders>0)return;releaseRecordLeases(t)}});function isAgentSessionKey(e,t){return parseAgentSessionKey(e)?.agentId===t}function isSessionId(e){return typeof e===`string`&&SESSION_ID_PATTERN.test(e)}function resolveGenerationStorePath(e,t,n){return isIncognitoSessionKey(t)?resolveIncognitoOpenClawAgentSqlitePath({agentId:e}):n}async function readEntryInWorker(e){const t=await withSessionEntryReadOnlyInWorker({agentId:e.agentId,sessionKey:e.sessionKey,storePath:e.storePath},e.assertCallerCurrent,async e=>e);if(!t.ok)throw t.error;return t.value}async function leaseSessionGeneration(e){try{return await acquireTranscriptLease(chatRef({agentId:e.agentId,sessionKey:e.sessionKey,storePath:resolveGenerationStorePath(e.agentId,e.sessionKey,e.storePath)}),{sessionId:e.entry?.sessionId??null,lifecycleRevision:e.entry?.lifecycleRevision},{exact:`lifecycle`})}catch(e){if(isSessionDeliveryGenerationRevokedError(e))return;throw e}}function assertRecordCurrent(e){for(let t=e;t;t=t.parent){if(t.state===`released`)throw new Error(`memory audience was released by its owner`);if(t.state===`stale`)throw new Error(`memory audience is no longer current`);for(const e of t.leases)try{e.assertCurrent()}catch(e){if(isSessionDeliveryGenerationRevokedError(e)){t.state=`stale`;releaseRecordLeases(t);throw new Error(`memory audience is no longer current`,{cause:e})}throw new Error(`memory audience currency is unavailable; retry the operation`,{cause:e})}}}function mintMemoryAudience(e,t,n){const r=Object.freeze(e);audienceRecords.set(r,n);audienceSessionKeys.set(r,t);for(let e=n;e;e=e.parent)e.holders+=1;collectedAudienceRecords.register(r,n);return{audience:r,release:()=>{if(n.state!==`current`)return;n.state=`released`;releaseRecordLeases(n)}}}async function resolveMemoryAudienceFromEntry(e,t){let{sessionKey:n,sessionId:r,senderIsOwner:i}=e;const{agentId:a}=e;let o=a;let s=false;const c=e.assertCallerCurrent??(()=>{});const l=/* @__PURE__ */ new Set;const u={leases:[],state:`current`,holders:0};let d;let f=false;const p=e.scheduledParent?.senderIsOwner;const deny=(e,t)=>{releaseRecordLeases(u);return{status:`denied`,kind:e,reason:t}};try{for(let m=0;m<MAX_LINEAGE_HOPS;m+=1){if(!isAgentSessionKey(n,o)||!isSessionId(r)||l.has(n))return deny(`ineligible`,`session lineage at ${n} is malformed or cyclic`);l.add(n);const h=o===a?e.storePath:e.resolveAgentStorePath(o);const g=m===0?t:await readEntryInWorker({agentId:o,sessionKey:n,storePath:h,assertCallerCurrent:c});if(!g||g.sessionId!==r||m>0&&!f&&g.lifecycleRevision!==d){if(m===0)return deny(`unverified`,`session ${n} no longer matches its admitted turn`);return deny(`stale-lineage`,`session ${e.sessionKey} has stale lineage: ancestor ${n} was reset or removed after its child was spawned. Respawn or recreate it from a current session to restore memory access; resetting it keeps the stale lineage.`)}const _=await leaseSessionGeneration({agentId:o,sessionKey:n,storePath:h,entry:g});if(!_)return deny(`unverified`,`session ${n} changed while its memory audience was resolved`);u.leases.push(_);f=false;const v=m===0?e.scheduledParent:void 0;if(v?.sessionKey===n){if(g.sessionId!==v.sessionId||v.lifecycleRevision!==void 0&&g.lifecycleRevision!==v.lifecycleRevision)return deny(`stale-lineage`,`scheduled run session ${n} was reset or replaced after its automation was linked to it`);i=v.senderIsOwner}else if(v&&g.spawnedBy===void 0){n=v.sessionKey;r=v.sessionId;d=v.lifecycleRevision;f=v.lifecycleRevision===void 0;i=v.senderIsOwner;continue}const y=m>0&&g.spawnedBy===void 0?g.scheduledMemoryParent:void 0;if(y?.senderIsOwner&&i===true){if(y.lifecycleRevision===``)return deny(`ineligible`,`scheduled run session ${n} has a malformed parent receipt`);n=y.sessionKey;r=y.sessionId;d=y.lifecycleRevision;f=y.lifecycleRevision===void 0;continue}if(g.spawnedBy!==void 0){if(typeof g.spawnedBySenderIsOwner!==`boolean`)return deny(`stale-lineage`,`spawned session ${n} predates memory lineage receipts (spawnedBySenderIsOwner), so it has no inherited memory audience. Respawn it from its parent session to restore memory access.`);if(!g.spawnedBy||g.parentSessionKey!==void 0&&g.parentSessionKey!==g.spawnedBy||!isSessionId(g.spawnedBySessionId)||g.parentSessionLifecycleRevision===``)return deny(`ineligible`,`spawned session ${n} has malformed lineage receipts`);const t=parseAgentSessionKey(g.spawnedBy)?.agentId;if(t&&t!==o){if(!e.resolveAgentStorePath||!g.spawnedBySenderIsOwner)return deny(`ineligible`,`session lineage at ${n} crosses agents without an owner spawn`);s=true;o=t}n=g.spawnedBy;r=g.spawnedBySessionId;d=g.parentSessionLifecycleRevision;i=g.spawnedBySenderIsOwner;continue}c();assertRecordCurrent(u);if(g.chatType===`direct`&&i===true&&p!==false)return{status:`granted`,...mintMemoryAudience({kind:`owner-private`,agentId:a},e.sessionKey,u)};if(s)return deny(`ineligible`,`cross-agent lineage grants only owner-private memory; root session ${n} is not an owner direct chat`);if(g.chatType===`direct`||g.chatType===`group`||g.chatType===`channel`)return{status:`granted`,...mintMemoryAudience({kind:`conversation`,agentId:a,sessionKey:n,sessionId:r},e.sessionKey,u)};return deny(`ineligible`,`root session ${n} has no durable chat type`)}return deny(`ineligible`,`session lineage exceeds ${MAX_LINEAGE_HOPS} hops`)}catch(e){releaseRecordLeases(u);c();return deny(`unverified`,`session storage could not verify the lineage: ${formatErrorMessage(e)}`)}}function isHostMemoryAudience(e){return typeof e===`object`&&e!==null&&audienceRecords.has(e)}function assertMemoryAudienceSession(e,t){if(!isHostMemoryAudience(e))throw new Error(`memory audience was not minted by this host`);if(audienceSessionKeys.get(e)!==t)throw new Error(`memory audience is bound to a different session`)}async function delegateMemoryAudience(e,t){assertMemoryAudienceCurrent(e);const n=audienceRecords.get(e);const{agentId:r}=e;const i=t.assertCallerCurrent??(()=>{});if(!isAgentSessionKey(t.sessionKey,r))throw new Error(`memory audience delegation requires a session for the same agent`);const a=await readEntryInWorker({agentId:r,sessionKey:t.sessionKey,storePath:t.storePath,assertCallerCurrent:i});if(a?typeof a.sessionId!==`string`||a.sessionId.length===0:t.detached!==true)throw new Error(`memory audience delegation requires an existing child session: ${t.sessionKey}`);const o=await leaseSessionGeneration({agentId:r,sessionKey:t.sessionKey,storePath:t.storePath,entry:a});if(!o)throw new Error(`child session changed during memory audience delegation: ${t.sessionKey}`);const s={parent:n,leases:[o],state:`current`,holders:0};try{i();assertRecordCurrent(s)}catch(e){releaseRecordLeases(s);throw e}return mintMemoryAudience({...e},t.sessionKey,s)}function prepareMemoryAudienceRead(e){const t=audienceRecords.get(e);if(!t)throw new Error(`memory audience was not minted by this host`);const n=[];try{for(let e=t;e;e=e.parent){if(e.state!==`current`)assertRecordCurrent(e);for(const t of e.leases){const e=t.prepareRead();if(e)n.push(e)}}}catch(e){Promise.all(n).catch(()=>{});throw e}if(n.length>0)return Promise.all(n).then(()=>prepareMemoryAudienceRead(e));assertRecordCurrent(t)}function prepareMemoryCallerRead(e){e.signal?.throwIfAborted();const{authority:t}=e;if(t.kind===`session`&&t.audience){assertMemoryAudienceSession(t.audience,t.sessionKey);return prepareMemoryAudienceRead(t.audience)}}function assertMemoryAudienceCurrent(e){const t=audienceRecords.get(e);if(!t)throw new Error(`memory audience was not minted by this host`);assertRecordCurrent(t)}function assertMemoryCallerCurrent(e){e.assertCurrent();const{authority:t}=e;if(t.kind===`session`&&t.audience){assertMemoryAudienceSession(t.audience,t.sessionKey);assertMemoryAudienceCurrent(t.audience)}e.signal?.throwIfAborted()}export{isHostMemoryAudience as a,resolveMemoryAudienceFromEntry as c,delegateMemoryAudience as i,assertMemoryAudienceSession as n,prepareMemoryAudienceRead as o,assertMemoryCallerCurrent as r,prepareMemoryCallerRead as s,assertMemoryAudienceCurrent as t};