openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 17 kB
JavaScript
import{t as runInDetachedAsyncContext}from"./detached-async-context-DLLuWsxc.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{d as sleepWithAbort,o as racePromiseWithAbortSignal,s as raceWithTimeout}from"./src-De06gkOi.mjs";import"./abort-signal-BKkRe6pu.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{j as normalizeSessionKeyPreservingOpaquePeerIds}from"./session-key-BPgKfU2m.mjs";import{a as withAgentDatabasePreparationContext}from"./agent-database-preparation-context-CPut921o.mjs";import{n as createOpenClawAgentDatabasePathMatcher,r as includesOpenClawAgentDatabasePath}from"./openclaw-agent-db.paths-SkzMsgQ0.mjs";import{D as readSqliteDatabaseCleanClose,b as prepareSqliteDatabaseAdmission,o as getOrLoadSqliteDatabaseAdmissionForPath}from"./sqlite-database-admission-B3KDkUt-.mjs";import{t as OPENCLAW_AGENT_SCHEMA_VERSION}from"./openclaw-schema-versions-rhFQpVhP.mjs";import{o as isSqliteLockError}from"./sqlite-error-diagnostics-ASl1MXPN.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{b as schemaAdmission}from"./sqlite-schema-facts-CWOeTpUB.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{_ as withSqliteReadOnlyWorkerScope}from"./sqlite-readonly-worker-C1mJaAX6.mjs";import{S as AgentDatabaseSchemaAdmissionChangedError,w as AgentDatabaseStartupPublicationError}from"./openclaw-agent-db-resources-KCMTIo4b.mjs";import{r as readSqliteIntegrityFileIdentity}from"./sqlite-file-generation-CHAXRj0p.mjs";import{r as cloneEnvWithPlatformSemantics}from"./config-env-vars-DCDGIBtT.mjs";import{t as createPermitPool}from"./permit-pool-bvWhofXE.mjs";import"./openclaw-agent-db-contract-CiyWpx1X.mjs";import{o as sessionChanges}from"./session-row-changes-21DJT-m_.mjs";import{C as publishPendingAgentDatabaseReadAdmission,S as preparePendingAgentDatabaseRead,_ as isAgentDatabasePreparationRetryable,d as createAgentDatabaseInspectionRefusal,l as createAgentDatabaseDeletionRefusal,n as assertAgentDatabaseAdmitted,p as failPendingAgentDatabase,t as AgentDatabaseAdmissionError,w as readAgentDatabaseAdmissionRefusal,x as preparePendingAgentDatabase,y as listAgentDatabaseAdmissionRefusals}from"./agent-database-admission-DiJx9iIl.mjs";import{s as readAgentDeletionJournalStatusInWorker}from"./agent-deletion-journal.read-DL01GJPw.mjs";import{i as prepareAgentDatabaseStartupVerification,r as createAgentDatabaseRuntimeIntegrityObserver}from"./agent-database-startup-integrity-DmEvzjwm.mjs";import"./backoff-DRW5tqzp.mjs";import{t as retryAsync}from"./retry-DH5OEIsj.mjs";import{t as assertionSucceeds}from"./assertion-BDJqrEL5.mjs";import{AsyncLocalStorage}from"node:async_hooks";
//!src/state/agent-database-startup-observation.ts
function createAgentDatabaseStartupObservation(e,t,n){const r=/* @__PURE__ */ new Map;return{observePreparedIntegrity:n,get hasPendingAgents(){return e.size>0||r.size>0},registerInputRecovery(e,t){const n=normalizeAgentId(e);r.set(n,t);const retire=()=>{if(r.get(n)===t)r.delete(n)};t.completion.then(retire,retire)},isAgentInputRecoveryPending(e){return r.has(normalizeAgentId(e))},waitForAgentPreparation(n,i={}){const a=normalizeAgentId(n);const o=e.get(a);if(!o&&!i.forInput)return;const s=i.signal?AbortSignal.any([t,i.signal]):t;const waitForInputs=()=>{const e=i.forInput?r.get(a):void 0;const t=i.sessionKey?e?.sessions.get(normalizeSessionKeyPreservingOpaquePeerIds(i.sessionKey)):e?.completion;return t&&e?racePromiseWithAbortSignal(t===e.completion?t:Promise.race([t,e.completion]),s):void 0};if(!o||readAgentDatabaseAdmissionRefusal(n,i)!==o.refusal)return waitForInputs();if(!i.forWrite){const e=i.forWrite===false&&!i.forInput?o.readReady:o.completion;return e&&racePromiseWithAbortSignal(e,s).then(waitForInputs)}return raceWithTimeout(o.completion,1e3,()=>{throw new AgentDatabaseAdmissionError({...o.refusal,repairHint:`Agent database verification and preparation in progress. Retry the request shortly.`})},{signal:s,ref:false}).then(()=>{assertAgentDatabaseAdmitted(n,i);return waitForInputs()})}}}function recoveryTiming(e,t=performance.now()){return{elapsedMs:Math.round(t-e.startedAt),phaseDurationsMs:{...e.phaseDurationsMs,[e.phase]:Math.round((e.phaseDurationsMs[e.phase]??0)+t-e.phaseStartedAt)}}}function startAgentDatabasePreparationProgress(e,t){const n=setInterval(()=>{const n=performance.now();for(const[r,i]of e)createSubsystemLogger(`state/agent-admission`).warn(`agent database startup preparation still running`,{agentId:r,phase:i.phase,elapsedMs:Math.round(n-i.startedAt),phaseElapsedMs:Math.round(n-i.phaseStartedAt),...i.phase===`publication-wait`?{publishingAgentId:t()}:{}})},6e4);n.unref();return n}
//!src/state/agent-database-startup.ts
const log=createSubsystemLogger(`state/agent-admission`);const startupAdmission=new AsyncLocalStorage;var AgentDatabaseStartupSupersededError=class extends Error{constructor(e,t){super(`Agent ${e} ${t} preparation was superseded`);this.name=`AgentDatabaseStartupSupersededError`}};var AgentDatabaseStartupAdmission=class{constructor(e=true){this.deferInspections=e;this.controller=new AbortController;this.signal=this.controller.signal;this.activation=createDeferredCore();this.work=/* @__PURE__ */ new Set;this.pending=/* @__PURE__ */ new Map;this.verifying=createPermitPool(2);this.observation=createAgentDatabaseStartupObservation(this.pending,this.signal,createAgentDatabaseRuntimeIntegrityObserver(this.signal,this.activation.promise,this.verifying,e=>this.track(e)));this.adopted=false;this.activated=false;this.stopped=false;this.publication=Promise.resolve();this.opening=createPermitPool(2);this.migrating=createPermitPool(4);this.journalReads=createPermitPool(8);this.waitForAgentPreparation=this.observation.waitForAgentPreparation}get isStopped(){return this.stopped}startProgress(){this.progressTimer??=startAgentDatabasePreparationProgress(this.pending,()=>this.publishingAgentId)}prepareSchemaHeaders(e){const t={statePath:resolveOpenClawStateSqlitePath(e),headers:/* @__PURE__ */ new Map};this.preparedSchemaHeaders=t;return e=>({version:n,writerAppVersion:r,agentSchemaMeta:i})=>{if(!this.stopped&&this.preparedSchemaHeaders===t&&n===42)t.headers.set(e,{version:n,writerAppVersion:r,agentSchemaMeta:i})}}takePreparedSchemaHeaders(e){const t=this.preparedSchemaHeaders;this.preparedSchemaHeaders=void 0;return(n,r)=>{const i=t?.headers.get(n);return!this.stopped&&t?.statePath===resolveOpenClawStateSqlitePath(e)&&i?.version===r?i:void 0}}recordStateSchemaPreparation(e){const t=this.preparedSchemaHeaders;if(this.stopped||t?.statePath!==resolveOpenClawStateSqlitePath(e))return;const n=getOrLoadSqliteDatabaseAdmissionForPath(t.statePath,schemaAdmission,()=>void 0);const r=prepareSqliteDatabaseAdmission(t.statePath);if(n&&r)t.state={identity:r,schemaAdmissionId:n.admissionId}}takePreparedStateSchema(e){const t=this.preparedSchemaHeaders;const n=t?.state;if(!t||!n||t.statePath!==resolveOpenClawStateSqlitePath(e))return;const assertCurrent=()=>{const e=getOrLoadSqliteDatabaseAdmissionForPath(t.statePath,schemaAdmission,()=>void 0);if(this.stopped||prepareSqliteDatabaseAdmission(t.statePath)!==n.identity||e?.admissionId!==n.schemaAdmissionId)throw new Error(`Prepared startup state schema changed before source inspection`)};return assertionSucceeds(assertCurrent)?assertCurrent:void 0}get pendingPreparation(){return this.work.size>0?Promise.allSettled(this.work):void 0}track(e){this.work.add(e);const settled=()=>this.work.delete(e);e.then(settled,settled)}scheduling(e,t,n){const r=createOpenClawAgentDatabasePathMatcher();return{signal:this.signal,canDefer:e=>this.deferInspections&&e.agentId!==void 0&&n.has(e.agentId)&&includesOpenClawAgentDatabasePath(t,e.path,r),cleanClose:e=>{try{return readSqliteDatabaseCleanClose(e.path)}catch{return false}},track:e=>this.track(e),defer:(t,n)=>this.defer({env:e,inspections:t,reason:n})}}recordInspectionFailure(e,t,n){this.signal.throwIfAborted();if(!e.agentId)return false;(t.agentRefusals??=[]).push(createAgentDatabaseInspectionRefusal({agentId:e.agentId,paths:[e.path],reason:formatErrorMessage(n),cause:n}));return true}captureRefusals(e){return new Map(listAgentDatabaseAdmissionRefusals({env:e}).filter(e=>this.pending.get(e.agentId)?.refusal===e).map(e=>[e.agentId,e]))}reuseRefusal(e,t,n){const r=e.agentId&&n?.get(e.agentId);if(!r||!includesOpenClawAgentDatabasePath(r.paths,e.path))return false;(t.agentRefusals??=[]).push(r);return true}defer(e){this.signal.throwIfAborted();const t=cloneEnvWithPlatformSemantics(e.env);const n=/* @__PURE__ */ new Map;for(const t of e.inspections){const e=t.target.agentId;if(!e)throw new Error(`Cannot defer a database without an agent owner: ${t.target.path}`);n.set(e,[...n.get(e)??[],t])}const r=[];for(const[i,a]of n){const n=[...new Set(a.map(({target:e})=>e.path))];const o=createAgentDatabaseInspectionRefusal({agentId:i,paths:n,pending:true,reason:`Agent ${i} has not completed startup inspection and preparation. ${e.reason}`});const s=performance.now();const c=createDeferredCore();const l=createDeferredCore();const u=createDeferredCore();const d={refusal:o,completion:c.promise,readReady:l.promise,startedAt:s,phase:`inspection`,phaseStartedAt:s,phaseDurationsMs:{}};const finishInputs=()=>{u.resolve();if(this.pending.get(i)===d)this.pending.delete(i);if(this.pending.size===0){clearInterval(this.progressTimer);this.progressTimer=void 0}};const phase=e=>{const t=performance.now();d.phaseDurationsMs=recoveryTiming(d,t).phaseDurationsMs;d.phase=e;d.phaseStartedAt=t};this.pending.set(i,d);this.startProgress();r.push(o);log.info(o.reason,{agentId:i,paths:n});const f=n.map(e=>{try{return{pathname:e,identity:readSqliteIntegrityFileIdentity(e)}}catch(t){return{pathname:e,error:t}}});const p=Promise.allSettled(a.map(({result:e})=>e));const m=runInDetachedAsyncContext(async()=>{const e={};let r;const s=createDeferredCore();const releasePublication=()=>{if(this.publishingAgentId===i)this.publishingAgentId=void 0;s.resolve()};let m;let h=false;try{const c=await p;phase(`activation`);const g=await this.activation.promise;if(!g||this.stopped)return;const assertLifetimeCurrent=()=>{this.signal.throwIfAborted();if(!g.isCurrent()||this.pending.get(i)!==d)throw new Error(`Gateway no longer owns preparation for agent ${i}`)};const assertCurrent=()=>{assertLifetimeCurrent();for(const e of f){if(!e.identity)throw e.error;readSqliteIntegrityFileIdentity(e.pathname,e.identity)}};const _={attempts:4,minDelayMs:500,maxDelayMs:8e3,jitter:.2,sleep:e=>sleepWithAbort(e,this.signal),shouldRetry:isAgentDatabasePreparationRetryable};const assertNotDeleted=async()=>{const e=await retryAsync(async()=>{const e=await this.journalReads.acquire({signal:this.signal});try{assertCurrent();return await readAgentDeletionJournalStatusInWorker(i,{env:t},this.signal)}finally{e?.()}},_);assertCurrent();if(e!==`absent`)throw new AgentDatabaseAdmissionError(createAgentDatabaseDeletionRefusal(o))};assertCurrent();for(const e of c){if(e.status===`rejected`)throw e.reason;const t=e.value;const n=t.agentRefusals?.[0];if(n)throw new AgentDatabaseAdmissionError(n);if(t.incompatible.length||t.indeterminate.length||t.pendingMigrations?.length)throw new Error(t.indeterminate.map(e=>e.reason).join(`; `)||`Agent ${i} database requires Doctor before preparation`)}const v=a.every(({target:e},t)=>{const n=c[t];return n?.status===`fulfilled`&&includesOpenClawAgentDatabasePath(n.value.readReadyAgentPaths??[],e.path)});phase(`readiness`);await racePromiseWithAbortSignal(g.preparationReady,this.signal);assertCurrent();if(v)m=prepareAgentDatabaseStartupVerification({agentId:i,paths:n,env:t,signal:this.signal},g,this.verifying);const y={env:t,assertCurrent,signal:this.signal};await withSqliteReadOnlyWorkerScope(async()=>{await assertNotDeleted();await preparePendingAgentDatabase(o,y,async()=>{try{var a=_usingCtx();const f=a.a(new AsyncDisposableStack);const p={agentId:i,paths:n,env:t,signal:this.signal,assertCurrent,phase};const publish=async()=>{phase(`publication-wait`);const a=this.publication;this.publication=s.promise;try{await racePromiseWithAbortSignal(a,this.signal);assertCurrent();this.publishingAgentId=i;for(let t=1;;t++)try{e.withdraw=await g.publishAgent(p)||void 0;break}catch(e){const n=e instanceof AgentDatabaseStartupSupersededError||e instanceof AgentDatabaseSchemaAdmissionChangedError;if(!n&&!_.shouldRetry(e)||t>=_.attempts)throw n?new AgentDatabaseStartupPublicationError(e):e;log.warn(`agent database startup publication interrupted; retrying`,{agentId:i,attempt:t});await _.sleep(_.minDelayMs*2**(t-1));await assertNotDeleted()}phase(`publication`);await assertNotDeleted();if(g.captureReadAdmission){r=publishPendingAgentDatabaseReadAdmission(o,{env:t,paths:v?c.flatMap(e=>e.status===`fulfilled`?e.value.readReadyAgentPaths??[]:[]):n,assertCurrent:g.captureReadAdmission({...p,assertCurrent:assertLifetimeCurrent})});releasePublication();d.readReady=void 0;l.resolve()}}catch(e){if(!this.stopped)failPendingAgentDatabase(o,e,{env:t});releasePublication();throw e}};if(v&&g.captureReadAdmission){await preparePendingAgentDatabaseRead(o,{env:t,assertCurrent},publish);log.info(`agent database reads ready while writable inspection continues`,{agentId:i,...recoveryTiming(d)});runInDetachedAsyncContext(()=>sessionChanges.emit({all:true,scope:{agentId:i,topology:true}}))}const retryPreparation=async e=>{let t=0;await retryAsync(async()=>{if(t++>0)await assertNotDeleted();assertCurrent();await e()},{..._,onRetry:({attempt:e,err:t})=>{const n=isSqliteLockError(t)?`locked`:`capacity reached`;log.warn(`agent database startup ${n}; retrying preparation`,{agentId:i,phase:d.phase,attempt:e})}})};await retryPreparation(async()=>{phase(`open-wait`);const e=await this.opening.acquire({signal:this.signal});try{assertCurrent();phase(`open`);const e=await g.openAgent(p);if(e)f.defer(()=>racePromiseWithAbortSignal(Promise.resolve(e[Symbol.asyncDispose]()),this.signal))}finally{e?.()}});await retryPreparation(async()=>{phase(`migration-wait`);const t=await this.migrating.acquire({signal:this.signal});try{assertCurrent();phase(`migration`);const t=await g.migrateAgent(p);e.maintenance=t?t.maintain:void 0;e.recoverInputs=t?t.recoverInputs:void 0;if(e.recoverInputs)this.observation.registerInputRecovery(i,{sessions:e.recoverInputs.sessions,completion:u.promise})}finally{t?.()}});if(!r)await publish();else await assertNotDeleted()}catch(e){a.e=e}finally{await a.d()}})},{signal:this.signal,deadlineOwnedByCaller:true});log.info(`agent database recovered after background inspection and preparation`,{agentId:i,paths:n,...recoveryTiming(d)});h=true}catch(r){if(!this.stopped){const a=formatErrorMessage(r);failPendingAgentDatabase(o,r,{env:t});if(this.pending.get(i)===d)e.withdraw?.();log.warn(`agent database remains degraded`,{agentId:i,paths:n,reason:a,repairHint:readAgentDatabaseAdmissionRefusal(i,{env:t})?.repairHint,...recoveryTiming(d)})}}finally{if(!h)m?.revoke();r?.();releasePublication();l.resolve();c.resolve();if(!e.recoverInputs||this.stopped||readAgentDatabaseAdmissionRefusal(i,{env:t}))finishInputs()}if(h&&m)this.track(runInDetachedAsyncContext(m.verify));try{if(!readAgentDatabaseAdmissionRefusal(i,{env:t})&&!this.stopped){if(e.recoverInputs){phase(`input-recovery`);await e.recoverInputs.run()}}}catch(e){if(!this.stopped)log.warn(`agent restart input recovery failed`,{agentId:i,reason:formatErrorMessage(e)})}finally{e.recoverInputs=void 0;finishInputs()}if(!readAgentDatabaseAdmissionRefusal(i,{env:t})&&!this.stopped)try{await e.maintenance?.()}catch(e){if(!this.stopped)log.warn(`agent database background maintenance failed`,{agentId:i,reason:formatErrorMessage(e)})}});this.track(m)}return r}adopt(){this.signal.throwIfAborted();if(this.adopted)throw new Error(`Agent database startup admission already belongs to a Gateway`);this.adopted=true;return{stop:()=>this.stop()}}activate(e){if(!this.adopted||this.stopped||this.activated)return;this.activated=true;this.activation.resolve(e)}async releaseStartup(){if(!this.adopted)await this.stop()}stop(){return this.stopping??=(async()=>{this.stopped=true;clearInterval(this.progressTimer);this.preparedSchemaHeaders=void 0;this.controller.abort(/* @__PURE__ */ new Error(`Gateway stopped during agent database inspection`));this.activation.resolve(void 0);while(this.work.size>0)await Promise.allSettled(this.work)})()}};function getAgentDatabaseStartupAdmission(){const e=startupAdmission.getStore();return e?.isStopped?void 0:e}async function withAgentDatabaseStartupAdmission(e,t={}){const n=getAgentDatabaseStartupAdmission()??new AgentDatabaseStartupAdmission(t.deferInspections);try{return await startupAdmission.run(n,()=>withAgentDatabasePreparationContext(()=>n.observation,()=>e(n)))}finally{await n.releaseStartup()}}export{getAgentDatabaseStartupAdmission as n,withAgentDatabaseStartupAdmission as r,AgentDatabaseStartupSupersededError as t};