UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 9.57 kB
import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{b as isCronRunSessionKey}from"./session-key-BPgKfU2m.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{u as normalizeDatabasePath}from"./sqlite-worker-identity-CikEUuqF.mjs";import{t as OPENCLAW_AGENT_SCHEMA_VERSION}from"./openclaw-schema-versions-rhFQpVhP.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{s as isMemoryPressureHigh}from"./worker-pool-sizing-Xnck39gX.mjs";import{S as registerOpenClawStateDatabaseLifecycleListener}from"./openclaw-state-db-cache-uycu-8uy.mjs";import"./openclaw-agent-db-contract-CiyWpx1X.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{a as sessionChangeScopeAffectsStoredRows,o as sessionChanges}from"./session-row-changes-21DJT-m_.mjs";import{h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import{u as isGatewayRestartDrainError,w as runWithGatewayIndependentRootWorkAdmission}from"./gateway-work-admission-CnMW3_qr.mjs";import{w as readAgentDatabaseAdmissionRefusal,y as listAgentDatabaseAdmissionRefusals}from"./agent-database-admission-DiJx9iIl.mjs";import{r as prepareAgentDatabaseDeletionSnapshotRead,t as isAgentDatabaseDeletionSnapshotChangedError}from"./agent-deletion-journal.read-DL01GJPw.mjs";import{o as resolveSqliteTargetFromSessionStorePath}from"./session-sqlite-target-fDZeQkPI.mjs";import{s as resolveConfiguredAgentDatabaseTargets}from"./targets-DZpbOEi4.mjs";import"./config-DkZ8y8Gv.mjs";import{l as runSessionRegistryMaintenanceForStore}from"./sessions-DQD7zQ95.mjs";import{n as resolveAllAgentSessionStoreTargetsAsync}from"./targets-runtime-CDxh6kAB.mjs";import{r as createRetainedAgentDatabaseMatcherFromSnapshot}from"./agent-deletion-discovery-BrXQcYYT.mjs";import{r as loadCronJobsStoreWithConfigJobsReadOnly}from"./read-only-CWdlWw2g.mjs";import{t as maintainCronRunHistory}from"./run-history-DknLtD2J.mjs";import{n as subscribeCronRunHistoryChanges}from"./run-history-changes-lKlEjqNm.mjs";import{AsyncLocalStorage}from"node:async_hooks"; //!src/cron/session-registry-maintenance.ts const log$1=createSubsystemLogger(`cron/maintenance`);const SESSION_REGISTRY_RETENTION_MS=6048e5;function resolveExplicitCronSessionSegment(e){return/^(?:agent:[^:]+:)?cron:([^:]+)$/u.exec(e?.trim()??``)?.[1]?.toLowerCase()}async function readRunningCronJobIds(e){try{const t=(await loadCronJobsStoreWithConfigJobsReadOnly(e)).store.jobs.filter(e=>typeof e.state?.runningAtMs===`number`);const n=/* @__PURE__ */ new Set;for(const e of t){n.add(e.id.toLowerCase());if(e.sessionTarget===`main`)continue;const t=resolveExplicitCronSessionSegment(e.sessionKey);if(t)n.add(t)}return{ok:true,ids:n,count:t.length}}catch(e){return{ok:false,reason:formatErrorMessage(e)}}}async function runSessionRegistryMaintenance(e){e.assertCurrent?.();const t=readRuntimeConfig();const n=await readRunningCronJobIds(e.cronStorePath);e.assertCurrent?.();if(!n.ok)return{retentionMs:SESSION_REGISTRY_RETENTION_MS,runningCronJobs:0,pruned:0,skippedStores:0,stores:[],nextSweepAtMs:Date.now()+6e4,skippedReason:`cron store unreadable: ${n.reason}`};const r=process.env;return await prepareAgentDatabaseDeletionSnapshotRead({env:r}).withCurrentSnapshot(async(i,a)=>{const o=listAgentDatabaseAdmissionRefusals({env:r}).filter(e=>readAgentDatabaseAdmissionRefusal(e.agentId,{env:r})).flatMap(e=>e.paths.map(t=>({agentId:e.agentId,storePath:t,skippedReason:e.code})));const assertCurrent=()=>{e.assertCurrent?.();a()};assertCurrent();const s=(i?.registeredAgentDatabases??[]).filter(e=>e.schemaVersion===42);const c=createRetainedAgentDatabaseMatcherFromSnapshot(r,()=>resolveConfiguredAgentDatabaseTargets(t,{env:r,registeredDatabases:s}),i);const l=new Map(i?.deletedAgents.map(({agentId:e,status:t})=>[e,t]));const u=await resolveAllAgentSessionStoreTargetsAsync(t,{env:r,registeredDatabases:s});const d=[];for(const e of u){assertCurrent();const t=l.get(e.agentId)??`absent`;const n=t!==`absent`?e.storePath:resolveSqliteTargetFromSessionStorePath(e.storePath,{agentId:e.agentId,env:r,registeredDatabases:s}).path;const i=t===`absent`?c(n,e.agentId):void 0;if(t!==`absent`||typeof i===`object`){o.push({...e,skippedReason:t===`pending`?`agent-deletion-pending`:`agent-deletion-complete`});continue}if(i){const t=i===`held`?`deletion journal reconstruction`:`deletion journal unavailable`;const a=`Held agent ${e.agentId} database ${n} (${t}); skipped session retention. Run "${formatCliCommand(`openclaw doctor --fix`,r)}" for explicit restoration guidance.`;log$1.warn(a);o.push({...e,skippedReason:`agent-store-held`,warning:a});continue}d.push(e)}const f=o.some(e=>`skippedReason`in e&&e.skippedReason!==`agent-deletion-pending`&&e.skippedReason!==`agent-deletion-complete`&&!l.has(e.agentId));for(const t of f?[]:d){assertCurrent();const r=await runSessionRegistryMaintenanceForStore({...t,apply:e.apply,retentionMs:SESSION_REGISTRY_RETENTION_MS,runningCronJobIds:n.ids,childStores:d,assertCurrent});assertCurrent();o.push({agentId:t.agentId,storePath:t.storePath,pruned:r.pruned,preservedRunning:r.preservedRunning,nextSweepAtMs:r.nextSweepAtMs})}const p=o.flatMap(e=>`nextSweepAtMs`in e?e.nextSweepAtMs===null?[]:[e.nextSweepAtMs]:e.skippedReason===`agent-deletion-pending`?[Date.now()+6e4]:[]);if(f)p.push(Date.now()+6e4);return{nextSweepAtMs:p.length>0?Math.min(...p):null,...f?{skippedReason:`session child inventory incomplete`}:{},retentionMs:SESSION_REGISTRY_RETENTION_MS,runningCronJobs:n.count,pruned:o.reduce((e,t)=>e+(`pruned`in t?t.pruned:0),0),skippedStores:o.filter(e=>`skippedReason`in e).length,stores:o}})} //!src/cron/maintenance.ts const log=createSubsystemLogger(`cron/maintenance`);let scope;let scheduledSweep;let nextHistorySweepAtMs=Infinity;let nextRegistrySweepAtMs=Infinity;let lastRegistrySuccessAtMs=null;let unsubscribeSessionChanges;let unsubscribeHistoryChanges;let unsubscribeDatabaseLifecycle;async function sweep(e,t){if(isMemoryPressureHigh()){const e=scope?.now()??Date.now();if(nextHistorySweepAtMs<=e)nextHistorySweepAtMs=e+6e4;if(nextRegistrySweepAtMs<=e)nextRegistrySweepAtMs=e+6e4;return}let n=false;try{await runWithGatewayIndependentRootWorkAdmission(async()=>{n=true;const e=captureOpenClawStateWorkerContext();const r=e.admission.assertCurrent;const i=scope?.now()??Date.now();if(nextHistorySweepAtMs<=i){nextHistorySweepAtMs=Infinity;try{const t=await maintainCronRunHistory(e,r);r();nextHistorySweepAtMs=Math.min(nextHistorySweepAtMs,t.nextSweepAtMs??Infinity)}catch(e){nextHistorySweepAtMs=Math.min(nextHistorySweepAtMs,i+6e4);throw e}}if(nextRegistrySweepAtMs<=i){nextRegistrySweepAtMs=Infinity;try{const e=await runSessionRegistryMaintenance({apply:true,assertCurrent:r,cronStorePath:t()});r();nextRegistrySweepAtMs=Math.min(nextRegistrySweepAtMs,e.nextSweepAtMs??Infinity);if(e.skippedReason)log.warn(`Session registry maintenance skipped`,{reason:e.skippedReason,retryAtMs:nextRegistrySweepAtMs,lastSuccessAtMs:lastRegistrySuccessAtMs});else{lastRegistrySuccessAtMs=scope?.now()??Date.now();log.info(`Session registry maintenance completed`,{lastSuccessAtMs:lastRegistrySuccessAtMs,nextSweepAtMs:Number.isFinite(nextRegistrySweepAtMs)?nextRegistrySweepAtMs:null,pruned:e.pruned,skippedStores:e.skippedStores})}}catch(e){nextRegistrySweepAtMs=Math.min(nextRegistrySweepAtMs,(scope?.now()??Date.now())+6e4);if(!isAgentDatabaseDeletionSnapshotChangedError(e))throw e;log.warn(`Session registry maintenance deferred`,{reason:`agent-database-snapshot-changed`,retryAtMs:nextRegistrySweepAtMs,lastSuccessAtMs:lastRegistrySuccessAtMs})}}},`cron:maintenance`,e)}catch(t){const r=scope?.now()??Date.now();if(nextHistorySweepAtMs<=r)nextHistorySweepAtMs=r+6e4;if(nextRegistrySweepAtMs<=r)nextRegistrySweepAtMs=r+6e4;if(n||!e.aborted&&!isGatewayRestartDrainError(t))log.warn(`Cron maintenance failed`,{error:t})}}function startCronMaintenance(e,t){if(scope&&!scope.signal.aborted)return;scope=e.scope();const n=AsyncLocalStorage.bind(()=>{if(!scope||scope.signal.aborted||scheduledSweep)return;const e=Math.min(nextHistorySweepAtMs,nextRegistrySweepAtMs);if(!Number.isFinite(e))return;const{signal:r}=scope;scope.schedule({id:`cron-maintenance`,atMs:e,run:()=>scheduledSweep??=sweep(r,t).finally(()=>{scheduledSweep=void 0;n()})})});lastRegistrySuccessAtMs=null;nextHistorySweepAtMs=nextRegistrySweepAtMs=scope.now()+5e3;const invalidateHistory=()=>{if(scope){nextHistorySweepAtMs=Math.min(nextHistorySweepAtMs,scope.now()+6e4);n()}};unsubscribeHistoryChanges=subscribeCronRunHistoryChanges(e=>{if(normalizeDatabasePath(e)===resolveOpenClawStateSqlitePath())invalidateHistory()});unsubscribeDatabaseLifecycle=registerOpenClawStateDatabaseLifecycleListener(e=>{if(e.kind!==`opened`)invalidateHistory()});unsubscribeSessionChanges=sessionChanges.subscribeFacts(e=>{if(!(`all`in e?e.scope===`config`||sessionChangeScopeAffectsStoredRows(e):sessionChangeScopeAffectsStoredRows(e)&&isCronRunSessionKey(e.sessionKey)))return;if(scope){const t=`all`in e&&typeof e.scope===`object`&&e.scope.topology===true;nextRegistrySweepAtMs=Math.min(nextRegistrySweepAtMs,scope.now()+(t?0:6e4))}n()});n()}async function stopCronMaintenance(){unsubscribeSessionChanges?.();unsubscribeSessionChanges=void 0;unsubscribeHistoryChanges?.();unsubscribeHistoryChanges=void 0;unsubscribeDatabaseLifecycle?.();unsubscribeDatabaseLifecycle=void 0;await Promise.all([scope?.stop(),scheduledSweep])}export{startCronMaintenance,stopCronMaintenance};