UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 19.5 kB
import{o as racePromiseWithAbortSignal}from"./src-De06gkOi.mjs";import{u as getPluginMetadataSnapshotCache}from"./plugin-cache-B6QVpzXr.mjs";import"./abort-signal-BKkRe6pu.mjs";import{t as normalizePluginPolicyId}from"./plugin-policy-id-Nz6ZTOOH.mjs";import{u as normalizePluginsConfig}from"./config-state-C1eV6UWf.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{u as observeDiagnosticsTimelinePhases}from"./diagnostics-timeline-Wd4cnAkV.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as loadPluginManifestRegistryCore}from"./manifest-registry-BHN0dk30.mjs";import{g as runPluginCleanup,u as getPluginValueInstance}from"./plugin-instance-scope-Bx-frH07.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{S as listPluginCacheRetiringRegistries}from"./registry-lifecycle-DGwblXFd.mjs";import{Y as withPluginHostCleanupTimeout}from"./runtime-Cl6PvJHC.mjs";import{a as runPluginCleanupScope}from"./registry-inspection-resources-5ksQH_Ac.mjs";import{n as loadPluginRegistryHandle}from"./loader-BhonRuVa.mjs";import{C as setStandaloneMemoryOwner,S as setStandaloneMemoryManagerActive,a as getMemoryCapabilityRegistration,o as getMemoryProviderRuntime,s as getMemoryRuntime,y as resolveMemoryCapabilityRegistration}from"./memory-state-BSED9PTf.mjs";import{a as isHostMemoryAudience,r as assertMemoryCallerCurrent,s as prepareMemoryCallerRead}from"./memory-audience-BMnQwoeC.mjs";import{a as stripMemoryAnnotationCarriers}from"./curated-annotations-4y7f6dO8.mjs";import{i as readMemorySearchManagerStatus,n as isAutomaticMemoryEntryEligible,s as resolveMemorySearchStaleness}from"./types-C4nBVSG1.mjs";import path from"node:path";import fs from"node:fs/promises"; //!src/plugins/memory-provider-adapter.ts function legacyCoverageWarning(e){const t=resolveMemorySearchStaleness(e);if(t)return t.warning;const n=e.custom?.providerState;if(n&&typeof n===`object`&&`mode`in n){const t=e.vector?.index?.state;if(n.mode===`pending`&&e.requestedProvider!==`none`&&t!==`complete`&&t!==`empty`)return`Memory embeddings are pending. Search results may be incomplete.`;if(n.mode===`degraded`||n.mode===`fts-only`&&e.requestedProvider!==void 0&&e.requestedProvider!==`none`)return`Memory embeddings are unavailable. Keyword search remains available; results may be incomplete.`}if(e.dirty)return`Memory indexing is pending. Search results may be incomplete.`;if(e.provider!==`none`&&e.vector?.enabled&&(e.vector.index?.state===`incomplete`||e.vector.index?.state===`unverified`))return`Memory vector indexing is incomplete. Search results may be incomplete.`}const refreshHandoffs=/* @__PURE__ */ new WeakMap;function refreshMemoryProviderWithHandoff(e,t){const n=refreshHandoffs.get(e);if(!n)throw new Error(`memory refresh requires a bound provider handle`);return n(t)}function bindMemoryProvider(e,t,n,r){let i=false;const a=getPluginValueInstance(e)??(r?getPluginValueInstance(r):void 0);const assertCurrent=e=>{if(i)throw new Error(`memory provider handle is closed`);assertMemoryCallerCurrent(n);if(a&&(e&&!a.acceptingCalls||a.owner?.revoked||a.lifecycle.signal.aborted))throw new Error(`memory provider instance is no longer current`)};const invoke=async e=>{try{var t=_usingCtx();const r=t.u(observeDiagnosticsTimelinePhases(`memory.provider-call.authority`));const i=prepareMemoryCallerRead(n);if(i)await racePromiseWithAbortSignal(i,n.signal);assertCurrent(true);r.mark(`memory.provider-call.execute`);const a=await e();r.mark(`memory.provider-call.revalidate`);const o=prepareMemoryCallerRead(n);if(o)await racePromiseWithAbortSignal(o,n.signal);assertCurrent(false);return a}catch(e){t.e=e}finally{t.d()}};const assertReference=e=>{if(e.providerId!==t)throw new Error(`memory reference belongs to a different provider`)};const assertCitations=e=>{for(const t of e??[])if(t.reference)assertReference(t.reference)};const validatePage=e=>{for(const t of e.hits){assertReference(t.reference);assertCitations(t.citations)}return e};const o=Object.freeze({...e.capabilities,sources:Object.freeze([...e.capabilities.sources]),candidates:Object.freeze([...e.capabilities.candidates])});const assertSearchCapabilities=e=>{const t=e.sources?.find(e=>!o.sources.includes(e));if(t)throw new Error(`memory provider does not support the ${t} source capability`);if(e.cursor!==void 0&&!o.pagination)throw new Error(`memory provider does not support the pagination capability`);if(e.activeProjectKeys?.length&&!o.projectFilter)throw new Error(`memory provider does not support the project filter capability`)};const s=e.refresh?t=>invoke(()=>{const n=e.refresh();t?.();return n}):void 0;const c={capabilities:o,search:t=>invoke(async()=>{assertSearchCapabilities(t);return validatePage(await e.search(t))}),get:t=>invoke(async()=>{assertReference(t.reference);const n=await e.get(t);if(n.status===`ok`){assertReference(n.reference);assertCitations(n.citations)}return n}),health:()=>invoke(()=>e.health()),...e.candidates?{candidates:t=>{return invoke(async()=>{if(!o.candidates.includes(t.kind))throw new Error(`memory provider does not support the ${t.kind} candidates capability`);if(t.activeProjectKeys?.length&&!o.projectFilter)throw new Error(`memory provider does not support the project filter capability`);return validatePage(await e.candidates(t))})}}:{},...s?{refresh:()=>s()}:{},async close(){if(i)return;i=true;await runPluginCleanup(e,()=>e.close())}};if(s)refreshHandoffs.set(c,s);return c}function redactLegacyHealthDetails(e){const{workspaceDir:t,dbPath:n,extraPaths:r,...i}=e;if(!i.vector)return i;const{extensionPath:a,...o}=i.vector;return{...i,vector:o}}async function adaptLegacyMemoryProvider(e,t,n){const r=await e.getMemorySearchManager({cfg:n.cfg,agentId:n.agentId,purpose:n.purpose});const i=r.manager;if(!i)return{provider:null,error:r.error};const{context:a}=n;const o=a.authority.kind===`session`?a.authority:void 0;const assertCurrent=()=>{a.assertCurrent();a.signal?.throwIfAborted()};const authorize=async t=>{assertCurrent();const r=e.authorizeSearchHits?await e.authorizeSearchHits({cfg:n.cfg,agentId:n.agentId,requesterSessionKey:o?.sessionKey,sandboxed:o?.sandboxed??false,trustedAgentScope:!o,conversationRecall:o?.conversationRecall,hits:t}):t.filter(e=>e.source!==`sessions`);assertCurrent();return r};const convert=e=>{const n={providerId:t,id:e.path,fragment:`L${e.startLine}-L${e.endLine}`};const r=e.projectKey?.split(`;`).map(e=>e.trim()).filter(Boolean);return{reference:n,excerpt:stripMemoryAnnotationCarriers(e.snippet),score:e.score,source:e.source,citations:[{label:e.citation??`${e.path}#L${e.startLine}-L${e.endLine}`,reference:n,startLine:e.startLine,endLine:e.endLine}],automaticRecall:{eligible:e.source===`memory`&&isAutomaticMemoryEntryEligible(e)&&r?.length!==0,projectKeys:r,triggers:e.triggers,importance:e.importance}}};const readCoverage=async e=>{try{const t=await readMemorySearchManagerStatus(i,{includeCounts:e});return{status:t,warning:legacyCoverageWarning(t)}}catch{assertCurrent();return{warning:`Memory index coverage could not be verified. Search results may be incomplete.`}}};return{provider:{capabilities:{sources:[`memory`,`sessions`],pagination:false,candidates:[],projectFilter:true},async search(e){if(e.cursor!==void 0)throw new Error(`legacy memory search does not support cursors`);if(typeof i.search!==`function`)throw new Error(`memory runtime manager must implement search`);const{query:t,cursor:n,activeProjectKeys:r,...s}=e;const c=await i.search(t,{...s,activeProjectKeys:r?[...r]:void 0,sessionKey:o?.sessionKey,signal:a.signal});const l=(await authorize(c)).map(convert);const{warning:u}=await readCoverage(false);return{hits:l,coverage:u?`partial`:`complete`,...u?{warning:u}:{}}},async get(e){if(typeof i.readFile!==`function`)throw new Error(`memory runtime manager must implement readFile`);const n=await i.readFile({relPath:e.reference.id,from:e.from,lines:e.lines});if(n.status===`not_found`)return{status:`not_found`};return{status:`ok`,reference:{providerId:t,id:n.path},text:n.text,truncated:n.truncated,from:n.from,lines:n.lines,nextFrom:n.nextFrom}},async health(){const{status:e,warning:t}=await readCoverage();return{status:t?`degraded`:`ready`,message:t,...e?{details:{legacy:redactLegacyHealthDetails(e)}}:{}}},...i.sync?{refresh:()=>i.sync({reason:`provider-refresh`})}:{},async close(){if(n.purpose===`cli`||n.purpose===`status`)await runPluginCleanup(i,()=>i.close?.())}}}} //!src/plugins/memory-runtime.ts const enrolledStandaloneMemoryRuntimes=/* @__PURE__ */ new WeakSet;let standaloneMemoryRegistrySlot;const registeredMemoryManagerAdapters=/* @__PURE__ */ new WeakMap;function normalizeRegisteredMemoryManager(e){const t=registeredMemoryManagerAdapters.get(e);if(t)return t;const readFile=async t=>{const n=await e.readFile(t);return n.status===`ok`||n.status===`not_found`?n:{...n,status:`ok`}};const n=new Proxy({readFile},{get(t,n){if(n===`readFile`)return readFile;const r=Reflect.get(e,n,e);if(typeof r!==`function`)return r;return r.bind(e)}});registeredMemoryManagerAdapters.set(e,n);return n}function resolveMemoryRuntimePluginIds(e){const t=normalizePluginsConfig(e.plugins);const n=t.slots.memory;if(!t.enabled||!n)return[];const r=normalizePluginPolicyId(n);if(t.deny.includes(r)||t.entries[r]?.enabled===false)return[];return[n]}function listCurrentMemoryRuntimes(){const e=new Set(standaloneMemoryRegistrySlot?.retiredRuntimes);for(const t of[getMemoryRuntime(),getMemoryProviderRuntime(),standaloneMemoryRegistrySlot?.providerRuntime,standaloneMemoryRegistrySlot?.runtime])if(t)e.add(t);return[...e]}function assertMemoryProviderRuntime(e){if(e!==void 0&&(!e||typeof e.open!==`function`))throw new Error(`memory providerRuntime must implement open`)}function isValidMemoryProviderCapabilities(e){return Array.isArray(e?.sources)&&e.sources.length>0&&e.sources.every(e=>e===`memory`||e===`sessions`)&&typeof e.pagination===`boolean`&&Array.isArray(e.candidates)&&e.candidates.every(e=>e===`trigger`||e===`project`)&&typeof e.projectFilter===`boolean`}function ensureMemoryRuntime(e){const t=getMemoryRuntime();const n=getMemoryProviderRuntime();assertMemoryProviderRuntime(n);if(t||n)return{runtime:t,providerRuntime:n,providerId:getMemoryCapabilityRegistration()?.pluginId,searchRuntimeRegistered:true};const r=resolveMemoryRuntimePluginIds(e.cfg);if(r.length===0)return;const i=resolveAgentWorkspaceDir(e.cfg,e.agentId);const a=loadPluginRegistryHandle({config:e.cfg,registrationConfigOrigin:e.cfg,manifestRegistry:loadPluginManifestRegistryCore({config:e.cfg,workspaceDir:i}),onlyPluginIds:r,workspaceDir:i,activate:false});const o=resolveMemoryCapabilityRegistration(a.memoryCapabilities);const s=o?.capability.runtime;const c=o?.capability.providerRuntime;assertMemoryProviderRuntime(c);const l=s||c?void 0:a.plugins.find(e=>e.id===r[0]);const u=s||c?{runtime:s,providerRuntime:c,providerId:o?.pluginId,standalone:true,searchRuntimeRegistered:true}:l?.status===`error`?{error:l.error??`Memory plugin "${l.id}" failed to load`}:l?.status===`loaded`&&l.memorySlotSelected===true?{searchRuntimeRegistered:false}:void 0;const d=standaloneMemoryRegistrySlot;if(d?.runtime===s&&d?.providerRuntime===c)return u;const f=new Set(d?.retiredRuntimes);for(const e of[d?.runtime,d?.providerRuntime])if(e)f.add(e);standaloneMemoryRegistrySlot={runtime:s,providerRuntime:c,retiredRuntimes:f};setStandaloneMemoryOwner(o&&(s||c)?{pluginId:o.pluginId,native:c!==void 0}:void 0);for(const e of[u?.runtime,u?.providerRuntime])if(e&&!enrolledStandaloneMemoryRuntimes.has(e)){const t=getPluginValueInstance(e)?.lifecycle;if(t){t.onDispose(()=>{const t=standaloneMemoryRegistrySlot;t?.retiredRuntimes.delete(e);if(t?.runtime===e)delete t.runtime;if(t?.providerRuntime===e)delete t.providerRuntime});enrolledStandaloneMemoryRuntimes.add(e)}}return u}async function getActiveMemorySearchManagerCore(e){const t=ensureMemoryRuntime(e);if(!t?.runtime)return{manager:null,error:t?.error??`memory plugin unavailable`,searchRuntimeRegistered:t?.searchRuntimeRegistered};if(t.standalone)setStandaloneMemoryManagerActive(true);const n=await t.runtime.getMemorySearchManager(e);return{...n,manager:n.manager?normalizeRegisteredMemoryManager(n.manager):null,...t.runtime.searchForCli?{searchForCli:t.runtime.searchForCli.bind(t.runtime)}:{},searchRuntimeRegistered:true}}async function authorizeActiveMemorySearchHits(e){const t=ensureMemoryRuntime(e);return t?.runtime?.authorizeSearchHits?await t.runtime.authorizeSearchHits(e):e.hits.filter(e=>e.source!==`sessions`)}function isActiveMemoryProviderNative(e){return ensureMemoryRuntime(e)?.providerRuntime!==void 0}async function getActiveMemoryProviderCore(e){try{var t=_usingCtx();const n=t.u(observeDiagnosticsTimelinePhases(`memory.provider-open.authority`));if(typeof e.context.assertCurrent!==`function`)throw new Error(`memory provider requires caller authority with assertCurrent`);if(e.context.authority.kind===`session`&&e.context.authority.audience!==void 0&&!isHostMemoryAudience(e.context.authority.audience))throw new Error(`memory provider requires a host-minted memory audience`);const r={...e.context,assertCurrent:()=>assertMemoryCallerCurrent(e.context)};const i={...e,context:r};const a=prepareMemoryCallerRead(r);if(a)await racePromiseWithAbortSignal(a,r.signal);r.assertCurrent();n.mark(`memory.provider-open.runtime`);const o=ensureMemoryRuntime(e);if(!o?.runtime&&!o?.providerRuntime)return{provider:null,error:o?.error??`memory plugin unavailable`};if(o.standalone)setStandaloneMemoryManagerActive(true);const s=o.providerId??normalizePluginsConfig(e.cfg.plugins).slots.memory;if(typeof s!==`string`||!s)return{provider:null,error:`memory provider identity unavailable`};const c=o.providerRuntime?`native`:`legacy`;n.mark(`memory.provider-open.open`);const l=o.providerRuntime?await o.providerRuntime.open(i):await adaptLegacyMemoryProvider(o.runtime,s,i);try{n.mark(`memory.provider-open.revalidate`);const e=prepareMemoryCallerRead(r);if(e)await racePromiseWithAbortSignal(e,r.signal);r.assertCurrent();if(l.provider&&(typeof l.provider.search!==`function`||typeof l.provider.get!==`function`||typeof l.provider.health!==`function`||typeof l.provider.close!==`function`||!isValidMemoryProviderCapabilities(l.provider.capabilities)||l.provider.capabilities.candidates.length>0!==(typeof l.provider.candidates===`function`)))throw new Error(`memory provider must implement search, get, health, close, and valid capabilities with matching candidates`)}catch(e){if(l.provider&&typeof l.provider.close===`function`){n.mark(`memory.provider-open.close`);await runPluginCleanup(l.provider,()=>l.provider.close())}throw e}n.mark(`memory.provider-open.bind`);return{...l,providerId:s,adapter:c,provider:l.provider?bindMemoryProvider(l.provider,s,e.context,o.providerRuntime??o.runtime):null}}catch(e){t.e=e}finally{t.d()}}async function classifyActiveMemoryWorkspacePaths(e){const t=ensureMemoryRuntime(e);if(!t?.runtime)return{status:`unavailable`};if(!t.runtime.classifyWorkspaceMemoryPaths||e.readSources!==void 0&&!t.runtime.supportsWorkspaceMemoryReadSources){const{normalizeMemoryArtifactRelativePath:t,readMemoryArtifactProvenance:n}=await import(`./memory-artifact-provenance-_sKaEF7z.mjs`);const r=e.readSources===void 0?await fs.realpath(e.workspaceDir).catch(()=>void 0):void 0;return{status:`classified`,classifications:await Promise.all(e.relativePaths.map(async i=>{let a=e.readSources?.find(e=>e.relativePath===i)?.canonicalRelativePath;if(e.readSources===void 0&&r){const t=await fs.realpath(path.resolve(e.workspaceDir,i)).catch(()=>void 0);if(t)a=path.relative(r,t).replaceAll(path.sep,`/`)}const o=a&&t(a);if(!o||o.includes(`\0`)||o!==a||path.posix.normalize(o)!==o)return{relativePath:i,originClass:`untrusted`};return{relativePath:i,originClass:(await n({workspaceDir:e.workspaceDir,relativePath:o}))?.originClass??`agent`}}))}}return{status:`classified`,classifications:await t.runtime.classifyWorkspaceMemoryPaths(e)}}function resolveActiveMemoryBackendConfig(e){const t=ensureMemoryRuntime(e);if(t?.providerRuntime){const n=t.providerId??normalizePluginsConfig(e.cfg.plugins).slots.memory?.trim();return n?{backend:`provider-runtime`,providerId:n}:null}return t?.runtime?t.runtime.resolveMemoryBackendConfig(e):null}async function closeActiveMemorySearchManagersCore(e){await Promise.all(listCurrentMemoryRuntimes().map(async e=>runPluginCleanup(e,()=>e.closeAllMemorySearchManagers?.())));standaloneMemoryRegistrySlot?.retiredRuntimes.clear();setStandaloneMemoryManagerActive(false)}async function closeActiveMemorySearchManagerCore(e){await Promise.all(listCurrentMemoryRuntimes().map(async t=>runPluginCleanup(t,()=>t.closeMemorySearchManager?.(e))))}function resetStandaloneMemoryRegistrySlot(){standaloneMemoryRegistrySlot=void 0;setStandaloneMemoryOwner(void 0);setStandaloneMemoryManagerActive(false)}if(process.env.VITEST||false)globalThis[Symbol.for(`openclaw.memoryRuntimeTestApi`)]={resetStandaloneMemoryRegistrySlot};function prepareMemoryRuntimeReload(e,t,n){const r=n?listPluginCacheRetiringRegistries(getPluginMetadataSnapshotCache(n)):[];const runtimes=e=>new Set(e.memoryCapabilities.flatMap(({capability:e})=>[e.runtime,e.providerRuntime].filter(e=>e!==void 0)));const i=runtimes(t);const a=new Set(t.embeddingProviders.map(({provider:e})=>e));const o=[...new Set([e,...r].flatMap(e=>e.embeddingProviders.map(({provider:e})=>e)))].filter(e=>!a.has(e));const s=[];let c;const resume=(e,n=t)=>{const r=[];const i=runtimes(n);for(const{runtime:t,handle:n}of s)if(!e||i.has(t))try{runPluginCleanup(t,()=>n.resume())}catch(e){r.push(e)}if(r.length)throw new AggregateError(r,`Memory reload admission recovery failed`)};try{for(const t of runtimes(e)){const e=!i.has(t);if(!e&&o.length===0)continue;const n=runPluginCleanup(t,()=>{if(t.prepareReload)return t.prepareReload({retireRuntime:e,retiringEmbeddingProviders:o});if(t.closeAllMemorySearchManagers)return{drain:()=>t.closeAllMemorySearchManagers(),resume(){}}});if(n)s.push({runtime:t,handle:n})}}catch(e){try{resume(false)}catch(t){throw new AggregateError([e,t],`Memory reload preparation failed`,{cause:t})}throw e}const close=()=>{if(!c)c=runPluginCleanupScope([...s.map(({runtime:e})=>e),...o],()=>Promise.allSettled(s.map(({runtime:e,handle:t})=>Promise.resolve().then(()=>runPluginCleanup(e,async()=>{try{return await t.drain()}catch(e){return{errors:[e]}}}))))).then(e=>{const t=e.flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length)throw new AggregateError(t,t.map(formatErrorMessage).join(`; `));return{errors:e.flatMap(e=>e.status===`fulfilled`?e.value?.errors??[]:[])}});return c};return{restartPluginIds:new Set(o.length===0?[]:e.memoryCapabilities.flatMap(({pluginId:e,capability:t})=>[t.runtime,t.providerRuntime].some(e=>e!==void 0&&i.has(e))?[e]:[])),drain:()=>withPluginHostCleanupTimeout(`memory managers`,close),close,commit:(e=t)=>resume(true,e),rollback:()=>{resume(false);return new Set(e.memoryCapabilities.flatMap(({pluginId:e,capability:t})=>c&&s.some(({runtime:e})=>e===t.runtime||e===t.providerRuntime)?[e]:[]))}}}export{getActiveMemoryProviderCore as a,prepareMemoryRuntimeReload as c,closeActiveMemorySearchManagersCore as i,resolveActiveMemoryBackendConfig as l,classifyActiveMemoryWorkspacePaths as n,getActiveMemorySearchManagerCore as o,closeActiveMemorySearchManagerCore as r,isActiveMemoryProviderNative as s,authorizeActiveMemorySearchHits as t,refreshMemoryProviderWithHandoff as u};