UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2 lines • 35.3 kB
import{Et as e,Ft as t,J as n,Nt as r,V as i,b as a,t as o,tt as s}from"./sqlite-readonly-subsystem-C-VJT-xk.mjs";import{t as c}from"./sqlite-readonly-deferred-B75K7ut7.mjs";import{$ as l,G as u,J as d,K as f,X as p,_ as m,d as h,et as g,f as _,o as v,s as y,tt as b,u as x,v as S}from"./sqlite-readonly-pool-CKutEb9N.mjs";import{c as C,i as w,n as T,r as E,s as D}from"./sqlite-readonly-openclaw-agent-db-validation-cache-Crj0Djyz.mjs";import{Ot as O,Tt as k,c as A,i as j}from"./sqlite-readonly-runtime-process-manifest-CLhsN5hb.mjs";import{D as M,v as N}from"./sqlite-readonly-sqlite-readonly-location-CKoGOncu.mjs";import"./sqlite-readonly-sqlite-wal-CjNCU3qS.mjs";import{_ as ee,g as P,i as F,o as te,r as I,s as ne,t as re,u as ie}from"./sqlite-readonly-sqlite-user-version-DDTE9T44.mjs";import{u as ae,yt as oe}from"./sqlite-readonly-openclaw-state-db-engine-ChXzcctg.mjs";import{Et as se,Q as ce,Vt as le,W as L,Wn as ue,Yn as de,c as fe,pn as pe,r as me,rt as R,t as he}from"./sqlite-readonly-node-sqlite-u3RAlsBE.mjs";import{t as z}from"./sqlite-readonly-usingCtx-03vOGQ3v.mjs";import{U as ge,o as B,st as _e}from"./sqlite-readonly-sqlite-snapshot-capacity-error-Dx-DuFsZ.mjs";import{f as ve,n as V,u as ye}from"./sqlite-readonly-sqlite-snapshot-source-C-Cgj4ZL.mjs";import"./sqlite-readonly-openclaw-root-PLr-9gty.mjs";import{t as be}from"./sqlite-readonly-runtime-worker-url-D7L1HCPF.mjs";import{c as xe}from"./sqlite-readonly-sqlite-schema-sql-BnVx4b5A.mjs";import{t as H}from"./sqlite-readonly-errors-bSzGfuz-.mjs";import"./sqlite-readonly-open-Ckj0ooaA.mjs";import{r as Se}from"./sqlite-readonly-sqlite-transaction-CZJn2Fa5.mjs";import{v as Ce}from"./sqlite-readonly-location.worker.js";import{$ as U,At as we,Bt as W,C as Te,G as Ee,Kt as G,Mt as De,O as Oe,S as ke,T as K,Tt as Ae,U as je,Ut as Me,_ as Ne,f as Pe,i as Fe,jt as Ie,kt as q,p as Le,r as Re,w as ze}from"./sqlite-readonly-openclaw-agent-db-registry-listing-qZe2AwBJ.mjs";import{_ as J,g as Y,m as Be,p as Ve}from"./sqlite-readonly-sqlite-worker-operation-admission-BBMq6s0g.mjs";import"./sqlite-readonly-sqlite-snapshot-staging-owner-D6Poltsh.mjs";import{i as X}from"./sqlite-readonly-update-database-generations-CCiRrbIC.mjs";import"./sqlite-readonly-kysely-sync-DYhhbB39.mjs";import{l as He,o as Ue,u as We}from"./sqlite-readonly-openclaw-state-db-schema-version-tzJM7YfL.mjs";import"./sqlite-readonly-openclaw-agent-db-contract-Bp5NJ0My.mjs";import{t as Ge}from"./sqlite-readonly-targets-configured-agents-a6Ee2dcM.mjs";import{n as Ke,r as qe,t as Je}from"./sqlite-readonly-targets-C_LuAsGP.mjs";import Z from"node:path";import{randomBytes as Ye}from"node:crypto";import Q,{existsSync as Xe,realpathSync as Ze,statSync as Qe}from"node:fs";import"node:fs/promises";import{availableParallelism as $e}from"node:os";import{AsyncLocalStorage as et}from"node:async_hooks";import{fork as tt}from"node:child_process";function mapAgentSessionDirs(e,t,n){return t.filter(e=>e.isDirectory()&&(n?.(e.name)??!0)).map(t=>Z.join(e,t.name,`sessions`)).sort((e,t)=>e.localeCompare(t))}function resolveAgentSessionDirsFromAgentsDirSync(e,t){let n;try{n=Q.readdirSync(e,{withFileTypes:!0})}catch(e){return s(e)??[]}return mapAgentSessionDirs(e,n,t)}const nt=/* @__PURE__ */ new WeakMap;function recordRetryAttemptErrors(e,t){nt.set(e,[...t])}function getRetryAttemptErrors(e){return e!==null&&(typeof e==`object`||typeof e==`function`)?nt.get(e):void 0}function generateSecureFraction(){return Ye(4).readUInt32BE(0)/4294967296}function createRetryFailure(e){let t=e.flatMap(e=>getRetryAttemptErrors(e)??[e]),n=A(t.at(-1)??/* @__PURE__ */ Error(`Retry failed`),`Non-Error thrown`);return t.length>1&&recordRetryAttemptErrors(n,t),n}j({shouldRetry:e=>!se(e),random:generateSecureFraction,createFailure:createRetryFailure}),new a(Symbol(`agentDatabasePreparation`)),o(`state/agent-admission`);const rt=new et;function getAgentDatabaseStartupAdmission(){let e=rt.getStore();return e?.isStopped?void 0:e}function restoreNativeErrorResponse(e){let t=e.cause?Object.assign(Error(e.cause.message),e.cause):void 0;return Object.assign(Error(e.message,t?{cause:t}:void 0),{name:e.name,code:e.code,errcode:e.errcode})}function restoreAgentSchemaInspectionError(e){let t=restoreNativeErrorResponse(e);e.stateError&&Be(t,e.stateError);let n=Ve(t);return n.message=e.message,n}function retireReader(e){e.retired||(e.retired=!0,e.child.connected&&e.child.send({type:`close`},t=>{t&&e.child.kill(`SIGKILL`)}))}function createAgentSchemaInspectionWorker(){let n,r=!1,i=!1,a=0,o=0,s=0,l=0,d,startReader=e=>{let t=ge(`agentSchemaInspection`);u();let n=tt(t,[],{execArgv:be(t).slice(0,-1),serialization:`advanced`,stdio:[`ignore`,`ignore`,`pipe`,`ipc`]});a+=1;let r=f(n),i=c(),o={child:n,closed:i.promise,retired:!1,closeBudgetMs:e};return n.on(`error`,e=>{o.failure??=e,retireReader(o)}),n.once(`close`,()=>{o.runtimeFailure=r(),o.retired=!0,i.resolve()}),o},p={inspect:async(a,u,f)=>{let{input:p,kind:g}=a,b=_(u);if(b?.throwIfAborted(),r||i)throw Error(r?`Agent schema inspection worker is closed`:`Agent schema inspection worker is busy`);i=!0;try{let i=g===`agent`&&!p.verifyCurrentSchemaShape&&!p.requireStartupMigrationReadiness&&!p.inspectEmptyStore,a=!!v(`agent`),u,_=y();if(i&&_?.postgres){if(!Xe(f??p.pathname))return null;let[{readBackupEngine:e},{readBackupEngineImage:n}]=await Promise.all([import(`./sqlite-readonly-physical-store-QUmruBKf.mjs`).then(e=>e.t),import(`./sqlite-readonly-physical-store-inspection-DtIx2pta.mjs`)]),r=f?n(f,p.pathname):e(p.pathname);if(b?.throwIfAborted(),r.engine===`sqlite`){if(a&&!f)return null;a=!1}else{let{withPostgresStoreMetadata:e}=await import(`./sqlite-readonly-postgres-store-metadata-erfNRppW.mjs`),n=await e(_.postgres,r,async(e,n)=>{if(n.store!==`agent`)throw Error(`PostgreSQL agent inspection requires an agent store.`);if(!p.inspectOwnership)return{version:n.version};let{rows:i}=await e.query(`SELECT agent_id, role, schema_version::integer AS schema_version FROM ${xe(r.namespace)}.schema_meta WHERE meta_key = 'primary'`),a=i[0];return{version:n.version,agentSchemaMeta:a?{agentId:t(a.agent_id),role:a.role,schemaVersion:a.schema_version}:null}});return b?.throwIfAborted(),o+=1,n}}if(g===`agent`&&a){if(f)throw Error(`PostgreSQL agent inspection requires its live engine owner, not a SQLite snapshot.`);let{getPendingOpenClawAgentDatabasePreparation:e}=await import(`./sqlite-readonly-openclaw-agent-execution-VyjkwvFi.mjs`);await e(p.pathname),b?.throwIfAborted();let t=p.agentId??L(p.pathname,N,()=>void 0)?.agentId;if(!t){let{prepareSqliteTargetFromSessionStorePath:e}=await import(`./sqlite-readonly-session-sqlite-target-CjjeYpQO.mjs`),n=await e(p.pathname,{env:p.env??process.env},b);if(!n.agentId||n.ownerSource!==void 0&&n.ownerSource!==`database-path`&&n.ownerSource!==`database-registry`)throw Error(`PostgreSQL schema inspection could not establish the custom store owner.`);t=n.agentId}u=t}if(g!==`state`&&!a&&!f&&p.requireStartupMigrationReadiness&&R(p.pathname)){let e=L(p.pathname,T,()=>void 0),t=L(p.pathname,N,()=>void 0);if(e?.schema?.facts?.userVersion===p.supportedVersion&&Atomics.load(new Int32Array(e.valid),0)===1&&Atomics.load(new Int32Array(e.schema.valid),0)===1&&ce(p.pathname)===`${e.identity}:${e.birthtime}`&&t?.agentId===e.agentId&&(p.agentId===void 0||p.agentId===e.agentId)&&t.role===`agent`&&t.schemaVersion===p.supportedVersion)return{version:p.supportedVersion,integrityGateOutcome:`cached`,agentSchemaMeta:t}}let S=f?{pathname:f,identity:X(f)}:void 0;if(n?.retired&&(await n.closed,n=void 0),b?.throwIfAborted(),r)throw Error(`Agent schema inspection worker is closed`);let{timeoutMs:C,size:w}=h(p.requireStartupMigrationReadiness?`startup readiness`:`schema inspection`,p.pathname),E=n??=startReader(C);E.closeBudgetMs=C,d?.(),d=void 0;let D=++l,O=c(),k,kill=()=>{E.retired=!0,E.child.kill(`SIGKILL`)},onAbort=()=>{k=e(b?.reason),kill()},onMessage=e=>{if(!k){if(e.requestId!==D)k=/* @__PURE__ */ Error(`Invalid agent schema inspection response`),kill();else if(!e.ok)k=restoreAgentSchemaInspectionError(e.error),retireReader(E);else{if(g===`state`){let t=e.stateInspection;if(t===null){O.resolve(null);return}if(t===void 0){k=/* @__PURE__ */ Error(`Invalid state schema inspection response`),kill();return}O.resolve({...t,inspectionErrors:t.inspectionErrors.map(restoreAgentSchemaInspectionError)});return}let t=e.inspection;O.resolve(t?{...t,failure:t.failure?restoreAgentSchemaInspectionError(t.failure):void 0}:null)}}},onClose=(t,n)=>{O.reject(b?.aborted?e(b.reason):E.runtimeFailure??k??E.failure??(n===`SIGKILL`?m(`schema inspection`,p.pathname,C,w):/* @__PURE__ */ Error(`Agent schema inspection exited ${t} without a completed result`)))},A=x()?void 0:setTimeout(()=>{k??=m(`schema inspection`,p.pathname,C,w),kill()},C);A?.unref(),E.child.on(`message`,onMessage),E.child.once(`close`,onClose),b?.addEventListener(`abort`,onAbort,{once:!0});try{E.child.send({type:g===`state`?`inspect-state`:`inspect`,requestId:D,input:{...p,...u?{agentId:u}:{},...`env`in p&&p.env?{env:{...p.env}}:{}},snapshot:S,...g===`agent`&&a?{databaseEngineSelection:_}:{}},e=>{e&&(k??=e,kill())});let t=await O.promise;if(b?.aborted)throw kill(),await E.closed,e(b.reason);return S&&X(S.pathname,S.identity),t&&(o+=1,s+=+!!S),t}finally{clearTimeout(A),E.child.off(`message`,onMessage),E.child.off(`close`,onClose),b?.removeEventListener(`abort`,onAbort)}}finally{i=!1}}};return{prestart(e){let t=_(e);if(t?.throwIfAborted(),r||i)throw Error(`Agent schema inspection worker is unavailable for prestart`);if(n)return;let a=n=startReader(0),onAbort=()=>{a.retired=!0,a.child.kill(`SIGKILL`)};t?.addEventListener(`abort`,onAbort,{once:!0});let release=()=>t?.removeEventListener(`abort`,onAbort);d=release,a.closed.then(release)},get processCount(){return a},get inspectionCount(){return o},get snapshotCount(){return s},inspect:async(e,t,n)=>{let r=await p.inspect({kind:`agent`,input:e},t,n);if(r&&`schemas`in r)throw Error(`Unexpected state schema inspection result`);return r},inspectState:async(e,t,n)=>{let r=await p.inspect({kind:`state`,input:e},t,n);if(r&&!(`schemas`in r))throw Error(`Unexpected agent schema inspection result`);return r},async[Symbol.asyncDispose](){if(r=!0,d?.(),d=void 0,!n)return;let e=n,t=setTimeout(()=>e.child.kill(`SIGKILL`),e.closeBudgetMs);t.unref();try{retireReader(e),await e.closed}finally{clearTimeout(t)}}}}async function preflightAgentDatabasesBounded(e,t,n,r,i,a){let o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,claimAgentTarget=(e,t)=>{let n=`${e}\0${t??``}`;return s.has(n)||t===void 0&&o.has(e)?!1:(o.add(e),s.add(n),!0)},l=i?.cleanClose,u=e.map((e,t)=>t);if(l){let t=e.map(e=>l(e));u.sort((e,n)=>Number(t[n])-Number(t[e]))}let d=[],f=/* @__PURE__ */ new Map,p=0,m=[],h=c(),g=e.map(()=>c());for(let e of g)e.promise.catch(()=>{});let v=/* @__PURE__ */ new Set,y=Math.min(2,$e(),e.length),b=[],C=i?r?AbortSignal.any([i.signal,r]):i.signal:_(r),w=i!==void 0||x(),settleForeground=()=>{if(!(!i||v.size===0||b.length>0||f.size>0)&&!e.some((e,t)=>d[t]===void 0&&!v.has(t)))try{b=i.defer([...v].map(t=>({target:e[t],result:g[t].promise})),`Inspection and writable admission continue after the Gateway listener binds.`),h.resolve()}catch(e){h.reject(e)}},worker=async()=>{try{var n=z();let r=n.a(a?.()??createAgentSchemaInspectionWorker());for(m.push(r);;){if(C?.aborted||f.size>0||p>=u.length)return;let n=u[p];p+=1;let a=e[n];if(a===void 0)continue;let o={incompatible:[],indeterminate:[]};try{let e=await t(a,o,claimAgentTarget,(e,t,n)=>r.inspect(e,C??t,n));d[n]=o,g[n].resolve(o),e===`defer`&&i?.canDefer(a)&&v.add(n)}catch(e){f.set(n,e),g[n].reject(e);return}finally{settleForeground()}}}catch(e){n.e=e}finally{await n.d()}},T=Promise.all(Array.from({length:y},()=>S(worker,{signal:C??new AbortController().signal,deadlineOwnedByCaller:w}))).finally(()=>{for(let t=0;t<e.length;t+=1)d[t]===void 0&&g[t].reject(C?.reason??f.values().next().value??/* @__PURE__ */ Error(`Inspection cancelled`))});i?.track(T);let E=i&&setTimeout(()=>{f.size>0||C?.aborted||(e.forEach((e,t)=>{d[t]===void 0&&i.canDefer(e)&&v.add(t)}),settleForeground())},5e3);E?.unref();try{await(i?Promise.race([T,h.promise]):T)}finally{clearTimeout(E)}for(let t=0;t<e.length;t+=1)if(f.has(t)&&(!v.has(t)||b.length===0))throw f.get(t);C?.throwIfAborted();for(let[e,t]of d.entries())t===void 0||v.has(e)||(n.incompatible.push(...t.incompatible),n.indeterminate.push(...t.indeterminate),t.agentRefusals?.length&&(n.agentRefusals??=[]).push(...t.agentRefusals),t.pendingMigrations?.length&&(n.pendingMigrations??=[]).push(...t.pendingMigrations));return b.length&&(n.agentRefusals??=[]).push(...b),{schemaProcessCount:m.reduce((e,t)=>e+t.processCount,0),schemaInspectionCount:m.reduce((e,t)=>e+t.inspectionCount,0),schemaSnapshotCount:m.reduce((e,t)=>e+t.snapshotCount,0)}}async function cleanupOpenClawStatePreflight(e){let t=[];if(e.database){try{e.closeAdmission?.()}catch(e){t.push(e)}try{pe(e.database),e.database.close()}catch(e){t.push(e)}}try{e.snapshot&&!await e.snapshot.cleanupAsync()&&t.push(new ue(`SQLite read-only worker snapshot cleanup failed: ${e.snapshot.location}`))}catch(n){(e.inspectionErrors.length>0||t.length>0||!B(n,e.snapshot?.cleanupRoot))&&t.push(n)}t.length>0&&de([...e.inspectionErrors,...t],`State database schema inspection cleanup failed`)}function createAgentDatabaseDeletionClassifier(e){let t=e.artifactDirectories,r=e.retainedDeletions,a=r.status===`present`?r:r.status===`unavailable`?r.known:void 0,o=a?.entries??[],s=r.status===`unavailable`?`unavailable`:void 0,c=d(),u=a?t?a.held.flatMap(r=>{let i=Z.dirname(l({agentId:r.agentId,env:e.env})),a=Z.dirname(r.path),o=Z.basename(r.path)===`openclaw-agent.sqlite`,s=[{agentId:r.agentId,path:i},...t.filter(e=>b(e.agentId)===r.agentId||o&&c(e.path,a))];return(o&&[e.env.OPENCLAW_AGENT_DIR,e.env.PI_CODING_AGENT_DIR].some(t=>t?.trim()&&c(n(t,e.env),a))||o&&Z.basename(a)===`agent`&&c(Z.dirname(Z.dirname(a)),Z.dirname(Z.dirname(i))))&&s.push({agentId:r.agentId,path:a}),s}):a.held:[],isHeld=(e,n)=>u.some(r=>t&&r.agentId===n||c(r.path,e)),f,configuredTargets=()=>f??=typeof e.configuredAgentDatabaseTargets==`function`?e.configuredAgentDatabaseTargets((e,t)=>isHeld(e,t)||o.some(e=>e.agentId===t)):e.configuredAgentDatabaseTargets;return(n,r)=>{if(isHeld(n,r))return`held`;let a=[];if(u.length&&!t&&r!==void 0){let t=b(r);a=configuredTargets().filter(e=>b(e.agentId)===t),a.length===0&&(a=[...e.registeredAgentDatabases.filter(e=>b(e.agentId)===t),{agentId:t,path:W(n).path}])}if(a.some(e=>isHeld(e.path,e.agentId)))return`held`;let l=o.find(e=>e.agentId===r||(t?[e.agentDir]:e.databasePaths).some(e=>c(e,n)));return l?r===l.agentId?l:(t??[...configuredTargets(),...e.registeredAgentDatabases]).some(r=>!o.some(e=>e.agentId===b(r.agentId))&&c(r.path,n)&&(t!==void 0||p(r.path,e.env)&&(configuredTargets().includes(r)||O(Q.realpathSync.native(i(e.env)),Q.realpathSync.native(r.path)))))?s:l:s}}[{directory:`logs`,basename:`config-audit.jsonl`},{directory:`audit`,basename:`system-agent.jsonl`},{directory:`audit`,basename:`crestodian.jsonl`}].map(({directory:e,basename:t})=>{let n=t.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`);return{directory:e,pattern:RegExp(`^(?:${n}|\\.${n}\\.doctor-importing(?:\\.(?:[2-9]|[1-9][0-9]+))?|${n}\\.migrated(?:\\.(?:[2-9]|[1-9][0-9]+))?\\.raw(?:\\.doctor-scrub-(?:progress|restore|staging))?)$`,`u`)}});const it=/(?:^|\/)(?:[^/]+\.sqlite\.(?:generation-(?:lock|writer)|reindex-lock)\.sqlite|[^/]+\.sqlite\.(?:backup|memory-reindex|tmp)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:-wal|-shm|-journal)?$/iu;function normalizePosix(e){return e&&Z.posix.normalize(e.replaceAll(`\\`,`/`))}function isTransientSqliteBackupPath(e){let t=normalizePosix(e);return it.test(t)}function discoverAgentDatabaseMigrationTargets(e){let t=[],n=[],a=e.deletionJournal??E(e.env)?.retainedDeletions??{status:`unavailable`,cause:`missing`,reason:`shared state database missing`},o=a.status===`present`?a:a.status===`unavailable`?a.known:void 0,s=o?.entries??[],c=createAgentDatabaseDeletionClassifier({...e,retainedDeletions:a}),l=[],u=[],f=/* @__PURE__ */ new Map,failure=(e,n)=>{t.push(n),l.push({path:e,reason:n})},discard=(e,t)=>{e.source===`registry`&&a.status!==`unavailable`&&c(e.path)!==`held`&&u.push({agentId:e.agentId,path:e.path,change:t})},m=[...e.configuredAgentDatabaseTargets.map(e=>({...e,source:`configured`})),...e.registeredAgentDatabases.map(e=>({...e,source:`registry`})),...s.flatMap(e=>{let t=new Set(e.databasePaths);return e.databasePaths.filter(e=>!ye.some(n=>e.endsWith(n)&&t.has(e.slice(0,-n.length)))).map(t=>({agentId:e.agentId,path:t,source:`disk`}))}),...(o?.held??[]).map(e=>({agentId:e.agentId,path:e.path,source:`deletion`}))],h=i(e.env),g=Z.join(h,`agents`);try{for(let t of resolveAgentSessionDirsFromAgentsDirSync(g)){let n=Z.dirname(t),r=Z.join(n,`agent`),i=b(Z.basename(n));for(let t of C({agentDir:r,agentId:i,env:e.env}))m.push({agentId:i,path:t,source:`disk`})}}catch(e){failure(g,`Could not enumerate agent databases under ${g}: ${String(e)}`)}let _;try{_=Q.realpathSync.native(h)}catch(e){k(e,`ENOENT`)||failure(h,`Could not resolve active state directory ${h}: ${String(e)}`)}let v=d(),y=[],x=[],S=[],w=[],T=/* @__PURE__ */ new Set;for(let i of m){let o=i.path;if(isTransientSqliteBackupPath(o))continue;if(!p(o,e.env)){discard(i,`Removed archived or transient agent database registry entry ${o}.`);continue}let s;try{s=Q.realpathSync.native(o)}catch(e){k(e,`ENOENT`)||failure(o,`Could not resolve agent database ${o}: ${String(e)}`)}f.set(o,{realPath:s});let l=c(o,i.agentId),u=s!==void 0&&e.configuredAgentDatabaseTargets.some(e=>{if(b(e.agentId)!==b(i.agentId))return!1;try{return v(o,e.path)}catch{return!1}}),d=!!(s&&_&&(s===_||O(_,s)));if(s&&!d&&!u&&!l){discard(i);let e=`Skipped foreign agent database ${r(o)}; it is outside the active state directory and is not a configured session store.`;t.push(e),n.push(e);continue}let m;try{m=Q.statSync(o,{bigint:!0})}catch(e){if(!k(e,`ENOENT`)){failure(o,`Could not inspect ${i.source===`registry`?`registered `:``}agent database ${o}: ${String(e)}`);continue}}if(!m?.isFile()){if(a.status===`unavailable`)try{ve(o).some(e=>Q.lstatSync(e,{throwIfNoEntry:!1}))&&failure(o,`Could not verify held database ${o}: SQLite family artifacts remain without a regular main database. Restore the matching main database before reconstructing deletion history.`)}catch(e){failure(o,`Could not inspect held database family ${o}: ${String(e)}`)}discard(i,`Removed missing agent database registry entry ${o}.`),i.source===`registry`&&t.push(`Skipped missing registered agent database ${o}.`);continue}if(!s){discard(i),failure(o,`Skipped agent database ${o}; its filesystem boundary is unresolved.`);continue}let h=typeof l==`string`?JSON.stringify([b(i.agentId),o]):`${m.dev}:${m.ino}`;if(!T.has(h)){if(l){if(c(o)){if(T.add(h),typeof l==`string`)w.push({...i,realPath:s});else{let e={...i,agentId:l.agentId,realPath:s};!l.cleanupCompleted&&!l.manualTemplateRemoval?x.push(e):S.push(e)}(typeof l==`string`||l.cleanupCompleted||l.manualTemplateRemoval)&&t.push(`Held agent ${r(typeof l==`string`?i.agentId:l.agentId)} database ${r(o)} (${typeof l==`string`?l===`held`?`deletion journal reconstructed`:`deletion journal unavailable`:`retained-by-deletion`}); run ${G(`openclaw doctor --fix`,e.env)} to inspect restoration.`)}}else T.add(h),y.push({...i,path:o,realPath:s})}}return w.length>0&&t.push(`Agent deletion journal ${a.status===`unavailable`?`missing`:`reconstructed`}; ${w.length} store${w.length===1?``:`s`} held back. Run ${G(`openclaw doctor --fix`,e.env)} to record recovery, then restore or delete each held agent explicitly.`),{targets:y,pendingDeletionTargets:x,schemaTargets:[...y,...x],retainedTargets:S,unverifiedTargets:w,deletionJournal:a,registryRemovals:u,warnings:t,externalWarnings:n,failures:l,sourceIdentities:f}}function selectAgentDatabaseInspectionTargets(e,t,n){let r=e.agentAdmissionConfig&&(e.purpose===`runtime`||e.requireStartupMigrationReadiness||e.reuseStartupSchemaPreparation)?[...n,...(e.configuredAgentDatabaseCandidatePaths??Ke(e.agentAdmissionConfig,{env:e.env})).map(e=>({path:e}))]:void 0,i=/* @__PURE__ */ new Set;return{admissionTargets:r,inspectionTargets:t.filter(t=>!r||Je(r,t.agentId,t.path)?!0:(e.requireStartupMigrationReadiness&&!i.has(t.path)&&(o(`state/agent-admission`).warn(`Skipped ${t.path}${t.agentId?` (agent ${t.agentId})`:``}: database is not a configured target; run openclaw doctor to inspect retained data.`),i.add(t.path)),!1)).map(e=>Object.assign({},e,{presence:inspectDatabaseCandidatePresence(e.path)})).filter(e=>e.presence.status!==`absent`)}}function inspectDatabaseCandidatePresence(e){try{return Qe(e),{status:`present`}}catch(e){return k(e,`ENOENT`)?{status:`absent`}:{status:`indeterminate`,reason:H(e)}}}function recordAgentDatabaseRecoveryInspection(e,t,n,r){let i=r.agentSchemaMeta;r.failure||r.reason||i?.role!==`agent`||!i.agentId||!g(i.agentId)?e?.discovery.failures.push({path:t,reason:`Could not verify the owner of a held custom session store.`}):e?.discovery.unverifiedTargets.push({agentId:b(i.agentId),path:t,realPath:n,source:`configured`})}function collectAgentDatabasePreflightTargets(e){let{registeredDatabases:t,deletionJournal:n,purpose:r}=e,a=n.status===`present`?n.entries:[],o=t,s=[],c=new Set(a.filter(e=>e.cleanupCompleted||e.manualTemplateRemoval).map(e=>e.agentId)),l=/* @__PURE__ */ new Set,u=[],f;if(e.configuredAgentDatabaseTargets!==void 0&&(s=typeof e.configuredAgentDatabaseTargets==`function`?e.configuredAgentDatabaseTargets(t):e.configuredAgentDatabaseTargets),r===`maintenance`&&e.configuredAgentDatabaseTargets!==void 0){let r=discoverAgentDatabaseMigrationTargets({env:e.env,configuredAgentDatabaseTargets:s,registeredAgentDatabases:t,deletionJournal:n});f={stateDir:i(e.env),configuredAgentDatabaseTargets:s,registeredAgentDatabases:t,discovery:r},o=r.schemaTargets;for(let e of[...r.retainedTargets,...r.unverifiedTargets])l.add(e.realPath);u.push(...r.failures)}let m=[...s,...o,...r===`runtime`?(n.status===`present`?n.held:n.status===`unavailable`?n.known?.held:void 0)??[]:[],...e.configuredAgentDatabaseTargets===void 0?[]:t.filter(t=>p(t.path,e.env)),...(e.configuredAgentDatabaseCandidatePaths??[]).map(t=>({agentId:e.requireStartupMigrationReadiness||e.agentAdmissionConfig?W(t).agentId:void 0,path:t}))],h=d(),g=[...l],_=createAgentDatabaseDeletionClassifier({env:e.env,retainedDeletions:n,configuredAgentDatabaseTargets:s,registeredAgentDatabases:t});if(r===`runtime`&&e.agentAdmissionConfig)for(let t of qe(e.agentAdmissionConfig,e.env)){let e=W(t.storePath).path;_(e,t.agentId)===`held`&&m.push({agentId:t.agentId,path:e,held:!0})}return{configuredTargets:s,candidates:r===`runtime`?m.flatMap(e=>{let t=_(e.path,e.agentId);return t===`held`?[{...e,held:!0}]:typeof t==`object`?[]:[e]}):n.status===`unavailable`?f&&e.onAgentDatabaseDiscovery?(e.configuredAgentDatabaseCandidatePaths??[]).filter(e=>!g.some(t=>h(t,e))).map(e=>({agentId:void 0,path:e,holdForDeletionRecovery:!0})):[]:m.filter(t=>n.status===`present`&&n.held.some(e=>h(e.path,t.path))?e.inspectHeldAgentDatabaseTargets?.some(e=>e.agentId===t.agentId&&h(e.path,t.path))===!0:t.agentId===void 0||!c.has(t.agentId)),isRetainedPath:e=>{if(r===`runtime`){let t=_(e);return t===`held`||typeof t==`object`}return g.some(t=>h(t,e))},failures:u,preparedDiscovery:f}}var OpenClawDatabaseSchemaPreflightError=class extends re{constructor(e,t={}){let n=t.operation??`gateway-startup`;super(formatIncompatibleDatabaseSchemas(e,n)),this.incompatibleDatabases=e,this.name=`OpenClawDatabaseSchemaPreflightError`}};function formatIncompatibleDatabase(e){let t=e.agentId?` for agent ${e.agentId}`:``,n=F(e.writerAppVersion)?`It was written by OpenClaw ${e.writerAppVersion}; it is newer than this Gateway (${ie}).`:`writer build ${e.writerAppVersion??`unknown`}.`;return`${e.kind} database${t} ${e.path} uses schema ${e.foundVersion}; this build supports ${e.supportedVersion}; ${n}`}function formatIncompatibleDatabaseSchemas(e,t){return`${t===`doctor`?`Doctor refused to continue`:t===`gateway-restart`?`Gateway refused restart`:`Gateway refused startup`} because ${e.length} OpenClaw database schema(s) are newer than this build. ${e.map(formatIncompatibleDatabase).join(` `)} Refused by ${I()}. `+(e.some(e=>F(e.writerAppVersion))?`Use the newer install that supports these schemas, or run openclaw update to update this Gateway service before restarting. To use an older build, stop the service and restore your pre-upgrade backup created with openclaw backup create. `:`Run a build at least as new as the writer that supports these schemas, or stop the service and restore your pre-upgrade backup created with openclaw backup create. `)+`See ${P}.`}function describeDeferredStateSchemaPublication(e,t,n,r){return{kind:`state`,path:t,foundVersion:n,contentVersion:r,...e?{runId:e.runId,publishAfterMs:e.publishAfterMs}:{},message:e?`Schema content applied; version publication deferred until update run ${e.runId} finishes and its five-minute grace expires (or the running driver is abandoned for 30 minutes).`:`Schema content applied; version publication will complete on the next writable database open.`}}function deduplicateSchemaIssues(e){return[...new Map(e.map(e=>[`${e.code}\0${e.objectName}`,e])).values()]}function inspectCurrentStateStartupSchema(e,t,n){let r=Le(e,{pathname:t});if(r?.schema_version!==n)throw new M(`OpenClaw state database ${t} metadata schema version ${typeof r?.schema_version==`number`?r.schema_version:`invalid`} does not match ${n}.`);let i=Ae(e),a=deduplicateSchemaIssues([...U(e,le,ke,i),...U(e,le,Te,i)]);return{blockingIssues:a.filter(e=>!K(e)&&!ze(e)),startupRepairableIssues:a.filter(K)}}function inspectStateDatabaseSchema(e,t){let{pathname:n,supportedVersion:r}=t,i={incompatible:[],indeterminate:[]},a={schemas:i,inspectionErrors:[]},o=t.purpose===`runtime`&&R(n)&&He(e)?.startupReady===!0;try{let s=(t.purpose===`maintenance`&&t.verifyCurrentSchemaShape?void 0:We(e)?.userVersion??fe(e)?.userVersion)??te(e),c=s>r?s:Ue(e,s);if(c>r){let t=ne(e);if(i.incompatible.push({kind:`state`,path:n,foundVersion:c,supportedVersion:r,...t?{writerAppVersion:t}:{}}),c>36)return a}let l=s>r?Ue(e,s):c;if(l<r&&(i.pendingMigrations=[{kind:`state`,path:n,foundVersion:s,supportedVersion:r}]),s<c&&l===c&&(i.deferredSchemaPublications=[describeDeferredStateSchemaPublication(ae(e),n,s,c)]),!o&&t.requireStartupMigrationReadiness&&c<=36){if(oe(e,n,c<r?D({kind:`state`,foundVersion:c,supportedVersion:r}):void 0),Ee(e,n),Oe(e,n),l===36){let{blockingIssues:t}=inspectCurrentStateStartupSchema(e,n,s);if(t.length>0)throw new M(`OpenClaw state database ${n} requires repair: ${t.map(e=>e.message).join(`; `)}; run openclaw doctor --fix.`)}else Ne.get(l)?.(e,{pathname:n})}else if(!o&&t.verifyCurrentSchemaShape&&l===36)try{Pe(e,{pathname:n,schemaVersions:{userVersion:s,contentVersion:l}})}catch(e){a.inspectionErrors.push(e),i.indeterminate.push({kind:`state`,path:n,reason:H(e)})}if(t.scope===`state`)return a;try{a.registeredDatabases=je(e,n),a.deletionJournal=w(e,n,t.purpose)}catch(e){a.inspectionErrors.push(e),i.indeterminate.push({kind:`state`,path:n,reason:`agent database registry query failed: ${H(e)}`})}return a}catch(e){if(t.requireStartupMigrationReadiness)throw e;let r=J(e,n);return a.inspectionErrors.push(r),i.indeterminate.push({kind:`state`,path:n,reason:H(r)}),a}}const $=/* @__PURE__ */ new WeakMap;async function preflightOpenClawDatabaseSchemas(e,t=`maintenance`){try{var n=z();let i=Ce(`agent`)?{...e,preserveSourceArtifacts:!0}:e;i.signal?.throwIfAborted();let a=i.supportedVersions??{state:36,agent:38},o={incompatible:[],indeterminate:[]},s=i.requireStartupMigrationReadiness?getAgentDatabaseStartupAdmission():void 0,c=i.agentAdmissionConfig,l=new Set(c?[...Ge(c),...Me(c)]:[]),u=s?.scheduling(i.env,c?i.configuredAgentDatabaseCandidatePaths??Ke(c,{env:i.env}):[],l),d,f=n.a({take(){let e=d;return d=void 0,e},async[Symbol.asyncDispose](){await d?.[Symbol.asyncDispose]()}});i.requireStartupMigrationReadiness&&i.scope!==`state`&&v(`agent`)&&(d=createAgentSchemaInspectionWorker(),d.prestart(u&&i.signal?AbortSignal.any([u.signal,i.signal]):u?.signal??i.signal));let p=s?.prepareSchemaHeaders(i.env),m=i.reuseStartupSchemaPreparation&&!i.requireStartupMigrationReadiness&&!i.verifyCurrentSchemaShape&&!i.openStateSchemaReadAdmission?getAgentDatabaseStartupAdmission():void 0,h=m?.takePreparedStateSchema(i.env),g=m?.takePreparedSchemaHeaders(i.env),_=s??m,y=_?.captureRefusals(i.env),b=Z.resolve(_e(i.env)),x=[],S={status:`unavailable`,cause:`missing`,reason:`shared state database missing`},C,w,T,E=[],D=inspectDatabaseCandidatePresence(b);if(D.status===`indeterminate`)return o.indeterminate.push({kind:`state`,path:b,reason:D.reason}),o;try{if(D.status===`present`){if(v(`state`)){let e=await Re({env:i.env},{type:`stateBootstrap.inspect`,input:{pathname:b,supportedVersion:a.state,purpose:t,scope:i.scope}},{signal:i.signal,current:!0});if(!e)throw Error(`Shared state disappeared during PostgreSQL startup admission`);Object.assign(o,e.inspection.schemas),x=e.inspection.registeredDatabases??[],S=e.inspection.deletionJournal??S}else try{var r=z();let e=Fe({env:i.env}),n=e?void 0:h,c=t===`runtime`&&R(b),l=e?.location??(c||n?b:void 0);i.signal?.throwIfAborted();let u={pathname:b,supportedVersion:a.state,requireStartupMigrationReadiness:i.requireStartupMigrationReadiness,verifyCurrentSchemaShape:i.verifyCurrentSchemaShape,scope:i.scope,purpose:t},d=l===void 0&&i.preserveSourceArtifacts===!1,f=r.a(!n&&(t===`runtime`||d)&&!i.requireStartupMigrationReadiness&&!i.openStateSchemaReadAdmission?createAgentSchemaInspectionWorker():void 0),p=f&&d?await f.inspectState(u,i.signal):null;if(!p){if(l===void 0&&(T=await V(Ze.native(b),{preserveSourceArtifacts:i.preserveSourceArtifacts??!0,allowLiveOwner:i.preserveSourceArtifacts!==!1,signal:i.signal,requireCleanup:!0}),l=T.location),i.signal?.throwIfAborted(),f)p=await f.inspectState(u,i.signal,l);else{C=he(c?me(l):l,{readOnly:!0,timeout:ee}),w=i.openStateSchemaReadAdmission?.(C);let e=C;n?.(),p=n?Se(e,()=>inspectStateDatabaseSchema(e,u),{operationLabel:`state.startup-prepared-schema`}):inspectStateDatabaseSchema(C,u),n?.()}}if(!p)throw Error(`Missing state schema inspection result`);if(Object.assign(o,p.schemas),E.push(...p.inspectionErrors),p.schemas.indeterminate.forEach((e,t)=>{let n=p.inspectionErrors[t];$.set(e,i.requireStartupMigrationReadiness?Y(n,b,i.signal):n)}),s&&p.inspectionErrors.length===0&&p.schemas.incompatible.length===0&&p.schemas.indeterminate.length===0&&!p.schemas.pendingMigrations?.length&&s.recordStateSchemaPreparation(i.env),i.scope===`state`||!p.deletionJournal)return o;x=p.registeredDatabases??[],S=p.deletionJournal}catch(e){r.e=e}finally{await r.d()}}}catch(e){let t=J(e,b);if(E.push(t),i.signal?.aborted||i.requireStartupMigrationReadiness)throw Y(t,b,i.signal);let n={kind:`state`,path:b,reason:H(t)};return $.set(n,t),o.indeterminate.push(n),o}finally{await cleanupOpenClawStatePreflight({database:C,closeAdmission:w,snapshot:T,inspectionErrors:E})}if(i.scope===`state`)return o;let{candidates:O,configuredTargets:k,isRetainedPath:A,failures:j,preparedDiscovery:M}=collectAgentDatabasePreflightTargets({...i,registeredDatabases:x,deletionJournal:S,purpose:t}),recordRecoveryFailure=(e,t)=>{M?.discovery.failures.push({path:e,reason:t})};for(let e of j)o.indeterminate.push({kind:`agent`,...e});let{admissionTargets:N,inspectionTargets:P}=selectAgentDatabaseInspectionTargets({...i,purpose:t},O,k),F=/* @__PURE__ */ new Map,te=P.filter(e=>{if(!e.held)return!0;if(e.agentId){let t=F.get(e.agentId)??/* @__PURE__ */ new Set;t.add(e.path),F.set(e.agentId,t)}return!1}),recordInspectionFailure=(e,t,n)=>s?.recordInspectionFailure(e,t,n)?!0:!N||!c||i.requireStartupMigrationReadiness||!e.agentId||!q(c,e.agentId)?!1:((t.agentRefusals??=[]).push(Ie({agentId:e.agentId,paths:[e.path],reason:H(n),cause:n})),!0),I=await preflightAgentDatabasesBounded(te,async(e,n,r,o)=>{let d=e.path;if(_?.reuseRefusal(e,n,y))return;let{presence:f}=e;if(f.status===`indeterminate`){if(e.holdForDeletionRecovery){recordRecoveryFailure(d,f.reason);return}recordInspectionFailure(e,n,Error(f.reason))||n.indeterminate.push({kind:`agent`,path:d,reason:f.reason});return}let m,h=!1;try{let f=Ze.native(d);if(e.agentId===void 0&&A(f)||!r(f,e.agentId))return;let _=g?.(f,a.agent)??null,y=p?.(f),b=e.holdForDeletionRecovery||e.agentId!==void 0&&l.has(e.agentId),x={pathname:f,agentId:e.agentId,env:i.env,supportedVersion:a.agent,inspectOwnership:b,verifyCurrentSchemaShape:!e.holdForDeletionRecovery&&i.verifyCurrentSchemaShape,requireStartupMigrationReadiness:!e.holdForDeletionRecovery&&i.requireStartupMigrationReadiness,deferRuntimeIntegrity:t===`runtime`&&i.preserveSourceArtifacts!==!0&&u?.canDefer(e)};if(_||=await o({...x,preserveSourceArtifacts:i.preserveSourceArtifacts===!0&&!v(`agent`)},i.signal),_||=(m=await V(f,{preserveSourceArtifacts:i.preserveSourceArtifacts??!0,allowLiveOwner:i.preserveSourceArtifacts!==!1,signal:i.signal,requireCleanup:!0}),i.signal?.throwIfAborted(),await o(x,i.signal,m.location)),!_)throw Error(`Agent database inspection returned no result: ${d}`);h=!_.failure&&!_.reason;let{version:S,writerAppVersion:C,agentSchemaMeta:w}=_;if(e.holdForDeletionRecovery){recordAgentDatabaseRecoveryInspection(M,d,f,_);return}if(S<=a.agent&&b&&e.agentId){let t=De({agentId:e.agentId,path:d,metadata:w??null});if(t){(n.agentRefusals??=[]).push(t);return}}if(S<a.agent&&(n.pendingMigrations??=[]).push({kind:`agent`,path:d,...e.agentId===void 0?{}:{agentId:e.agentId},foundVersion:S,supportedVersion:a.agent}),_.failure&&!_.reason)throw _.failure;if(_?.reason){if(s||N&&!i.requireStartupMigrationReadiness)throw _.failure??Error(_.reason);let t={kind:`agent`,path:d,reason:_.reason,...i.requireStartupMigrationReadiness?{agentId:e.agentId}:{}};_.failure&&$.set(t,_.failure),n.indeterminate.push(t);return}if(S>a.agent){let t={kind:`agent`,path:d,...e.agentId===void 0?{}:{agentId:e.agentId},foundVersion:S,supportedVersion:a.agent,...C?{writerAppVersion:C}:{}};(!N||!c||!e.agentId||!q(c,e.agentId)||!recordInspectionFailure(e,n,new OpenClawDatabaseSchemaPreflightError([t])))&&n.incompatible.push(t)}return y?.(_),_.readReady&&(n.readReadyAgentPaths??=[]).push(f),_.preparationPending?`defer`:void 0}catch(t){if(i.signal?.aborted)throw t;if(e.holdForDeletionRecovery){recordRecoveryFailure(d,H(t));return}if(recordInspectionFailure(e,n,t))return;if(i.requireStartupMigrationReadiness)throw t;let r={kind:`agent`,path:d,reason:H(t)};$.set(r,t),n.indeterminate.push(r)}finally{if(m){let t;try{await m.cleanupAsync()||(t={error:/* @__PURE__ */ Error(`SQLite read-only worker snapshot cleanup failed: ${m.location}`)})}catch(e){(!h||!B(e,m.cleanupRoot))&&(t={error:e})}t&&!recordInspectionFailure(e,n,t.error)&&(e.holdForDeletionRecovery?recordRecoveryFailure(d,H(t.error)):n.indeterminate.push({kind:`agent`,path:d,reason:H(t.error)}))}}},o,i.signal,u,f.take);M&&i.onAgentDatabaseDiscovery?.(M);for(let[e,t]of F)(o.agentRefusals??=[]).push(we(e,[...t]));return I.schemaProcessCount+=d?.processCount??0,i.onAgentInspection?.(I),i.onRegisteredAgentDatabases?.(x),o}catch(e){n.e=e}finally{await n.d()}}export{preflightOpenClawDatabaseSchemas};