UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 8.79 kB
import{O as appendPluginInstanceCleanupFailures}from"./plugin-cache-B6QVpzXr.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{t as isConfiguredSessionStoreAgentId}from"./targets-configured-agents-r1NDrR_6.mjs";import{a as getRuntimeConfigSnapshot}from"./runtime-snapshot-Bg5K4JNu.mjs";import{g as runPluginCleanup,i as getPluginInstance}from"./plugin-instance-scope-Bx-frH07.mjs";import{l as getPluginRecordRegistry}from"./registry-lifecycle-DGwblXFd.mjs";import{F as cleanupPluginSessionSchedulerJobs,I as clearPluginRunContext,Y as withPluginHostCleanupTimeout,l as getActivePluginRegistry,z as makePluginSessionSchedulerJobKey}from"./runtime-Cl6PvJHC.mjs";import{a as normalizeOptionalAgentRuntimeId}from"./agent-runtime-id-dWmvEQWJ.mjs";import{t as captureRuntimeConfigAsyncReader}from"./io.runtime-BvSeVFIY.mjs";import{w as readAgentDatabaseAdmissionRefusal}from"./agent-database-admission-DiJx9iIl.mjs";import"./targets-DZpbOEi4.mjs";import"./session-accessor-CY8UYP4m.mjs";import{h as cleanupPluginHostSessionStore}from"./session-accessor.entry-mutation-CQIwywNM.mjs";import{n as resolveAllAgentSessionStoreTargetsAsync}from"./targets-runtime-CDxh6kAB.mjs";import{r as getPluginRuntimeLoadContext}from"./load-context-BgV8IMWg.mjs";import{a as listRetainedDeletedAgentIdsForCleanup}from"./agent-deletion-discovery-BrXQcYYT.mjs"; //!src/plugins/host-hook-cleanup.ts const log=createSubsystemLogger(`plugins/cleanup`);function shouldCleanPlugin(e,t){return!t||e===t}async function clearPluginSessionStores(e){if(!e.pluginId&&!e.sessionKey||e.mode===`promoted-slots`&&e.sessionEntrySlotKeys?.size===0)return 0;const t=e.storeTargets??await e.resolveStoreTargets?.()??await resolveAllAgentSessionStoreTargetsAsync(e.cfg);let n=/* @__PURE__ */ new Set;if(t.some(t=>!isConfiguredSessionStoreAgentId(e.cfg,t.agentId)))try{n=await listRetainedDeletedAgentIdsForCleanup(process.env)}catch{}let r=0;for(const i of t){if(e.shouldCleanup&&!e.shouldCleanup())break;try{if(readAgentDatabaseAdmissionRefusal(i.agentId))continue;if(!isConfiguredSessionStoreAgentId(e.cfg,i.agentId)&&n.has(i.agentId))continue;r+=await cleanupPluginHostSessionStore({agentId:i.agentId,storePath:i.storePath,mode:e.mode,pluginId:e.pluginId,sessionKey:e.sessionKey,sessionEntrySlotKeys:e.sessionEntrySlotKeys,preserveLockedHarnessIds:e.preserveLockedHarnessIds,shouldCleanup:e.shouldCleanup})}catch(t){e.failures.push({pluginId:e.pluginId??`plugin-host`,hookId:`session-store`,error:t})}}return r}function collectSessionEntrySlotKeys(e,t){const n=/* @__PURE__ */ new Set;for(const r of e?.sessionExtensions??[]){if(!shouldCleanPlugin(r.pluginId,t))continue;const e=r.extension.sessionEntrySlotKey;if(e===void 0)continue;n.add(e)}return n}function collectAgentHarnessIds(e,t){const n=/* @__PURE__ */ new Set;for(const r of e?.agentHarnesses??[]){if(!shouldCleanPlugin(r.pluginId,t))continue;const e=normalizeOptionalAgentRuntimeId(r.harness.id);if(e)n.add(e)}return n}async function runPluginHostLifecycleCleanup(e){const t=[];let n=0;const r={reason:e.reason,sessionKey:e.sessionKey};const i=[...e.registry.sessionExtensions.map(({pluginId:e,extension:t})=>({pluginId:e,hookId:`session:${t.namespace}`,cleanup:t.cleanup,context:r})),...e.registry.runtimeLifecycles.map(({pluginId:e,lifecycle:t})=>({pluginId:e,hookId:`runtime:${t.id}`,cleanup:t.cleanup,context:{...r,runId:void 0}}))];for(const{pluginId:r,hookId:a,cleanup:o,context:s}of i){if(e.shouldCleanup?.()===false)break;if(!o||!shouldCleanPlugin(r,e.pluginId))continue;try{await withPluginHostCleanupTimeout(a,()=>runPluginCleanup(o,()=>o(s)));n+=1}catch(e){t.push({pluginId:r,hookId:a,error:e})}}return{cleanupCount:n,failures:t}}async function runPluginHostCleanup(e){const t=[];const n=e.shouldCleanup??(()=>true);if(!n())return{cleanupCount:0,failures:t};const r=await(async()=>{const r=e.registry;const i=r??getActivePluginRegistry();const a=collectSessionEntrySlotKeys(i,e.pluginId);const o=e.reason===`disable`?collectAgentHarnessIds(i,e.pluginId):void 0;const s=e.restartPromotedSessionEntrySlotKeys??a;let c=0;if(!e.skipPersistentSessionState&&n())try{c=await clearPluginSessionStores({cfg:e.cfg??await captureRuntimeConfigAsyncReader()(),mode:e.reason===`restart`?`promoted-slots`:`plugin-owned-state`,pluginId:e.pluginId,sessionKey:e.sessionKey,sessionEntrySlotKeys:e.reason===`restart`?s:a,preserveLockedHarnessIds:o,storeTargets:e.sessionStoreTargets,resolveStoreTargets:e.resolveSessionStoreTargets,shouldCleanup:n,failures:t})}catch(n){t.push({pluginId:e.pluginId??`plugin-host`,hookId:`session-store`,error:n})}if(r){const i=await runPluginHostLifecycleCleanup({...e,registry:r});c+=i.cleanupCount;t.push(...i.failures);if(!n())return{cleanupCount:c,failures:t};const a=await cleanupPluginSessionSchedulerJobs({pluginId:e.pluginId,reason:e.reason,sessionKey:e.sessionKey,records:r.sessionSchedulerJobs,preserveJobIds:e.preserveSchedulerJobIds,cleanupOwnerRegistry:r,preserveOwnerRegistry:e.preserveSchedulerOwnerRegistry,shouldCleanup:n});t.push(...a)}if(e.reason!==`restart`&&n()){const i=new Set((r?.sessionSchedulerJobs??[]).filter(t=>!e.pluginId||t.pluginId===e.pluginId).map(e=>makePluginSessionSchedulerJobKey(e.pluginId,e.job.id)));const a=await cleanupPluginSessionSchedulerJobs({pluginId:e.pluginId,reason:e.reason,sessionKey:e.sessionKey,preserveJobIds:e.preserveSchedulerJobIds,excludeJobKeys:i,cleanupOwnerRegistry:r??void 0,shouldCleanup:n});t.push(...a)}if(n()&&e.pluginId&&e.reason!==`restart`)clearPluginRunContext(e);return{cleanupCount:c,failures:t}})();if(e.reason===`reset`||e.reason===`delete`)for(const{pluginId:t,hookId:n,error:i}of r.failures)log.warn(`Plugin host cleanup failed during session ${e.reason}; check the reported cleanup error and retry.`,{pluginId:t,hookId:n,error:String(i)});return r}function collectHostHookPluginIds(e){return[...e.sessionExtensions,...e.runtimeLifecycles,...e.agentEventSubscriptions,...e.sessionSchedulerJobs].map(e=>e.pluginId)}function collectLoadedPluginIds(e){return new Set(e.plugins.filter(e=>e.status===`loaded`).map(e=>e.id))}function collectSchedulerJobIds(e,t){return new Set((e?.sessionSchedulerJobs??[]).filter(e=>e.pluginId===t).map(e=>e.job.id))}function collectRestartPromotedSessionEntrySlotKeys(e,t,n){const r=collectSessionEntrySlotKeys(e,n);const i=collectSessionEntrySlotKeys(t,n);for(const e of i)r.delete(e);return r}function createPluginHostRetirementObserver(e){return async t=>{const n=await Promise.all(e.map(e=>e(t)));const r=n.flatMap(e=>e.deferredPluginIds??[]);return{cleanupCount:n.reduce((e,t)=>e+t.cleanupCount,0),failures:n.flatMap(e=>e.failures),...r.length?{deferredPluginIds:r}:{}}}}function createPluginHostRegistryRetirement(e){const t=e.previousRegistry;const n=e.shouldCleanup??(()=>true);if(!t||t===e.nextRegistry||!n())return async()=>({cleanupCount:0,failures:[]});const r=e.cfg??getPluginRuntimeLoadContext(t)?.config??getRuntimeConfigSnapshot()??void 0;const i=captureRuntimeConfigAsyncReader();const a=e.nextRegistry?collectLoadedPluginIds(e.nextRegistry):/* @__PURE__ */ new Set;const o=/* @__PURE__ */ new Set([...collectLoadedPluginIds(t),...collectHostHookPluginIds(t)]);const s=/* @__PURE__ */ new Set([...t.plugins.map(e=>e.id),...o]);let c;const resolveSessionStoreTargets=async()=>c??=resolveAllAgentSessionStoreTargetsAsync(r??await i());const l=[];for(const c of s){const s=t.plugins.find(e=>e.id===c);if(s&&(getPluginRecordRegistry(t,s)!==t||e.nextRegistry?.plugins.includes(s)))continue;const u=s?getPluginInstance(s):void 0;const d=e.skipPersistentSessionState||a.has(c);let f={cleanupCount:0,failures:[]};const p=o.has(c)?async()=>{f=await runPluginHostCleanup({cfg:e.skipPersistentSessionState?r:r??await i(),registry:t,pluginId:c,reason:d?`restart`:`disable`,preserveSchedulerJobIds:d?collectSchedulerJobIds(e.nextRegistry,c):void 0,shouldCleanup:n,restartPromotedSessionEntrySlotKeys:d?collectRestartPromotedSessionEntrySlotKeys(t,e.nextRegistry,c):void 0,preserveSchedulerOwnerRegistry:d?e.nextRegistry:void 0,resolveSessionStoreTargets,skipPersistentSessionState:e.skipPersistentSessionState});for(const e of f.failures)log.warn(`Plugin ${e.pluginId} cleanup failed (${e.hookId}): ${formatErrorMessage(e.error)}`)}:void 0;const m=u?u.dispose(u.disposing?void 0:p):Promise.resolve().then(p).then(()=>({errors:[]}));m.catch(()=>{});l.push(async e=>{if(e?.deferConsumers&&u?.hasRetainedConsumers)return{...f,deferredPluginIds:[c]};const t=await(u?u.dispose():m);const n=[...f.failures];appendPluginInstanceCleanupFailures(n,c,t);return{cleanupCount:f.cleanupCount,failures:n}})}return createPluginHostRetirementObserver(l)}export{runPluginHostCleanup as n,runPluginHostLifecycleCleanup as r,createPluginHostRegistryRetirement as t};