UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines • 17.3 kB
import{a as asOptionalRecord}from"../record-coerce-BTbqdJ3-.mjs";import{b as retirePluginCache,i as createPluginCache,w as withPluginCache}from"../plugin-cache-B6QVpzXr.mjs";import{t as hasErrnoCode}from"../errno-DUBt6SQQ.mjs";import{T as resolveOAuthDir}from"../paths-D_FOvGon.mjs";import{p as readDatabasePathIdentity}from"../sqlite-worker-identity-CikEUuqF.mjs";import{l as quoteSqliteIdentifier}from"../sqlite-schema-sql-XrfUK8rp.mjs";import{t as _usingCtx}from"../usingCtx-CUVyQ_FT.mjs";import{o as getAdmittedSqliteSchemaFacts,t as admitSqliteSchema}from"../sqlite-schema-facts-CWOeTpUB.mjs";import{f as parseGatewayLockPayload}from"../gateway-lock-payload-CBa45_pI.mjs";import{n as openNodeSqliteDatabase}from"../node-sqlite-DXyF1fBG.mjs";import{_ as isGatewayStateOwnerDefinitelyStale,a as captureGatewayStateOwner,d as resolveGatewayStateOwnerPath}from"../gateway-state-owner-D_klysuh.mjs";import{s as resolveOpenClawStateSqlitePath}from"../openclaw-state-db.paths-CbgXfEg1.mjs";import{D as hasVerifiedLiveSqliteOwner,v as withOpenClawStateDatabaseReadSnapshot}from"../openclaw-state-db-readonly-Cd5_cxBs.mjs";import{a as withArtifactPreservingStateReads}from"../artifact-preserving-state-reads-CWuQPqxe.mjs";import{t as listDatabaseEngineStores}from"../registry-ByN-O5dB.mjs";import{a as withDatabaseEngineSelection}from"../context-DZjni16e.mjs";import{a as prepareSqliteReadOnlyLocation}from"../sqlite-snapshot-source-DbIgYrJe.mjs";import{_ as withSqliteReadOnlyWorkerScope,f as runSqliteReadOnlyOperation}from"../sqlite-readonly-worker-C1mJaAX6.mjs";import{o as readStateSchemaContentVersion}from"../openclaw-state-db-schema-version-DreEd78i.mjs";import{g as decodeGatewayOwnerLease,v as readGatewayOwnerLeaseFromDatabase}from"../openclaw-state-db-transaction-B9Gj3UJV.mjs";import{n as assertOpenClawStateDatabaseForMaintenance}from"../openclaw-state-db-maintenance-BGNaiVRT.mjs";import{o as withPluginSourceCaptureStorage}from"../plugin-source-capture-context-BdWCXhar.mjs";import{n as loadBundledPluginManifestRegistry}from"../manifest-registry-build-DSmHjL9c.mjs";import{p as resolvePluginMetadataSnapshot}from"../plugin-metadata-snapshot-CDKhemiT.mjs";import{n as resolveDatabaseEngineSelection}from"../config-eTB-xhop.mjs";import{n as resolveAgentPortRoots}from"../agent-port-B0iL4NPS.mjs";import{n as createDatabaseStoreDiagnostic,t as listLocalDatabaseDiagnosticStores}from"../local-diagnostics-o6eq7hSq.mjs";import{i as withPostgresConnection,r as readPostgresStoreMetadata}from"../postgres-store-metadata-BAneIabP.mjs";import{i as readEngineAnchorIdentity}from"../physical-store-inspection-BHEZGfsf.mjs";import{t as databasePortProviders}from"../port-provider-CdqIxw1H.mjs";import{t as resolveStatePortRoots}from"../state-port-AlRe7zyl.mjs";import{t as describeDatabaseEngineSelection}from"../report-IvbNxPY6.mjs";import{n as serveWorkerTasks}from"../worker-task-server-BeWxX5OH.mjs";import{_ as resolvePluginDoctorStateMigrationRecords,u as listPluginDoctorStateMigrationEntries}from"../doctor-contract-registry-DTv7VdR4.mjs";import{r as createPluginDoctorStateMigrationInput}from"../state-migrations.plugin-doctor-B2U6Zptn.mjs";import fs from"node:fs";import{walkDirectory}from"@openclaw/fs-safe/walk"; //!src/infra/database-engine/sqlite-store-inspection.ts function observeLease(e,t){e.lease=!t||t.state===`dead`?`none`:t.state===`live`?`live-owner`:`unverifiable`;if(e.lease===`unverifiable`)e.nextSteps.push(`Inspect the recorded Gateway lease before offline maintenance.`)}function observeVersion(e,t){e.schema.versioning=`versioned`;e.schema.version=t;const n=e.schema.expectedVersion;if(n===null)return;e.schema.pending=Math.max(0,n-t);if(t<n){e.issues.push(`Schema migrations pending: version ${t}, expected ${n}.`);e.nextSteps.push(`Run openclaw doctor --fix with the matching OpenClaw version.`)}else if(t>n){e.issues.push(`Schema version ${t} is newer than supported version ${n}.`);e.nextSteps.push(`Use an OpenClaw version that supports this schema, or restore its matching backup.`)}}function inspectSqlite(e,t,n){admitSqliteSchema(t);const r=getAdmittedSqliteSchemaFacts(t);e.connectivity=`local`;e.extensions=[];let i=r.userVersion;try{if(e.family===`state`){i=readStateSchemaContentVersion(t);assertOpenClawStateDatabaseForMaintenance(t,{pathname:`shared-state diagnostic snapshot`});observeVersion(e,i)}else if(n?.inspectSqliteSource){const r=n.inspectSqliteSource(t);observeVersion(e,r.version);if(r.migrationRequired&&r.version===e.schema.expectedVersion){e.issues.push(`Store preparation is required before porting.`);e.nextSteps.push(`Database porting performs this preparation on a private copy.`)}}else if(e.schema.versioning===`versioned`)observeVersion(e,i)}catch{if(e.family===`state`||e.family===`agent`)observeVersion(e,i);e.issues.push(`The SQLite schema could not be admitted by its store owner.`);e.nextSteps.push(`Run openclaw doctor --fix with the matching OpenClaw version.`)}if(e.family===`state`)try{observeLease(e,readGatewayOwnerLeaseFromDatabase(t))}catch{e.issues.push(`The recorded Gateway lease could not be verified.`);e.nextSteps.push(`Check the Gateway owner and rerun openclaw doctor.`)}}function inspectSqliteStoreImage(e,t,n,r){const i=readEngineAnchorIdentity(t,n);e.observed=i.engine;e.mismatch=i.engine!==e.configured.effective;if(e.mismatch){e.issues.push(`Configured ${e.configured.effective}, but the physical store is ${i.engine}.`);e.nextSteps.push(e.configured.fixedLocal?`Restore the fixed-local SQLite store from its verified backup.`:`Stop the Gateway and run openclaw database port --family ${e.family} --to ${e.configured.effective}, or restore the matching engine configuration.`)}if(i.engine===`sqlite`)inspectSqlite(e,t,r);return i} //!src/infra/database-engine/diagnostics.ts function inspectSearchMetadata(e,t){const n=asOptionalRecord(t);if(!n)throw new Error(`Invalid PostgreSQL metadata`);const r=typeof n.search_extensions===`string`?JSON.parse(n.search_extensions):n.search_extensions??{};const i=asOptionalRecord(r);if(!i)throw new Error(`Invalid PostgreSQL search-extension metadata`);const a=[];const o=[];for(const[e,t]of Object.entries(i)){const n=asOptionalRecord(t);if(!n)throw new Error(`Invalid PostgreSQL search-extension definition`);a.push(e);if(n.mode===`keyword-only`)o.push(`${e}: keyword-only`)}e.admittedExtensions=a;e.degraded=o.length?o:null}async function inspectPostgres(e,t,n){e.namespace=t.namespace;e.storeId=t.storeId;if(!n){e.issues.push(`PostgreSQL connection is not resolved; connectivity and schema are unknown.`);e.nextSteps.push(`Configure database.postgres.connection or repair its SecretRef, then rerun openclaw doctor.`);return}try{await withPostgresConnection(n,async n=>{e.connectivity=`reachable`;await n.query(`BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY`);try{await n.query(`SET LOCAL statement_timeout = '3000ms'`);const r=(await n.query(`SELECT current_database() AS database, ARRAY(SELECT extname::text FROM pg_extension ORDER BY extname) AS extensions`)).rows[0];if(!r)throw new Error(`PostgreSQL identity is unavailable`);e.database=r.database;e.extensions=r.extensions;const i=await readPostgresStoreMetadata(n,t);if(i.store!==e.family){e.issues.push(`PostgreSQL metadata belongs to a different store family.`);e.nextSteps.push(`Restore the matching PostgreSQL schema and anchor before starting the Gateway.`);return}observeVersion(e,i.version);inspectSearchMetadata(e,(await n.query(`SELECT to_jsonb(meta) AS metadata FROM ${quoteSqliteIdentifier(t.namespace)}.openclaw_schema_meta AS meta`)).rows[0]?.metadata);if(e.family===`agent`&&!e.extensions.includes(`vector`)){e.degraded=[...e.degraded??[],`vector search unavailable: pgvector is not installed`];e.nextSteps.push(`Ask the database administrator to run CREATE EXTENSION vector; grant USAGE on its schema to the OpenClaw role.`)}if(e.family===`state`){const r=await n.query(`SELECT owner, created_at AS "createdAt", expires_at AS "expiresAt", heartbeat_at AS "heartbeatAt", payload_json AS "payloadJson" FROM ${quoteSqliteIdentifier(t.namespace)}.state_leases WHERE scope = $1 AND lease_key = $2 LIMIT 2`,[`gateway-owner`,`global`]);if(r.rows.length>1)throw new Error(`Ambiguous Gateway lease`);const i=r.rows[0];observeLease(e,decodeGatewayOwnerLease(i?{owner:i.owner,createdAt:Number(i.createdAt),expiresAt:i.expiresAt===null?null:Number(i.expiresAt),heartbeatAt:i.heartbeatAt===null?null:Number(i.heartbeatAt),payloadJson:i.payloadJson}:void 0))}}finally{await n.query(`ROLLBACK`)}},{connectionTimeoutMillis:3e3,query_timeout:3e3})}catch{if(e.connectivity===`reachable`){e.issues.push(`PostgreSQL store metadata or owner lease could not be verified.`);e.nextSteps.push(`Check the configured role's schema access and run openclaw doctor --fix with the matching version; restore the matching schema and anchor if verification fails.`)}else{e.connectivity=`unreachable`;e.issues.push(`PostgreSQL is unreachable; schema, extensions, and ownership are unknown.`);e.nextSteps.push(`Check PostgreSQL service/port, network access, and database.postgres.connection or its SecretRef, then rerun openclaw doctor.`)}}}async function readLiveWalSource(e,t){try{const n=e.family===`state`||!e.descriptor?.inspectSqliteSource;if(!e.path||!n||!hasVerifiedLiveSqliteOwner(e.path))return;const{key:r}=await readDatabasePathIdentity(e.path);return await withSqliteReadOnlyWorkerScope(()=>runSqliteReadOnlyOperation(e.path,{type:`databaseStore.inspectLive`,input:{diagnostic:t}},{source:`canonical`,expectedIdentity:r,env:process.env}))}catch{return}}async function inspectDatabaseStore(e){const t=createDatabaseStoreDiagnostic({family:e.family,path:e.path,configured:e.configured});t.schema.versioning=e.schemaVersion===null?`unversioned`:e.descriptor||e.schemaVersion!==void 0?`versioned`:`unknown`;t.schema.expectedVersion=e.schemaVersion===null?null:e.schemaVersion??e.descriptor?.version??null;t.legacyMigrations.state=e.configured.fixedLocal?`none`:`unknown`;if(e.inspectionError===`unreadable-root`){t.issues.push(`The physical store root could not be read; its contents are unknown.`);t.nextSteps.push(`Check store path permissions, then rerun openclaw doctor.`);return t}let n=!e.path;if(e.path)try{fs.statSync(e.path)}catch(e){if(hasErrnoCode(e,`ENOENT`)||hasErrnoCode(e,`ENOTDIR`))n=true;else{t.issues.push(`The physical store path could not be inspected.`);t.nextSteps.push(`Check store path permissions, then rerun openclaw doctor.`);return t}}if(n||!e.path){t.nextSteps.push(`Store is not present. Initialize it through its owning feature, then rerun openclaw doctor.`);return t}try{try{const n=resolveGatewayStateOwnerPath(e.path);let r;try{r=parseGatewayLockPayload(fs.readFileSync(n,`utf8`));if(!r)throw new Error(`Invalid owner record`)}catch(e){if(!hasErrnoCode(e,`ENOENT`))throw e}t.custody=captureGatewayStateOwner(e.path)?`live-owner`:e.family===`state`&&(!r||isGatewayStateOwnerDefinitelyStale(r,n))?`none`:`unverifiable`;if(r&&t.custody===`unverifiable`)t.nextSteps.push(`Inspect the recorded store owner's custody before offline maintenance.`)}catch{t.issues.push(`Physical store custody could not be verified.`);t.nextSteps.push(`Check the Gateway owner and rerun openclaw doctor.`)}let n;const i=await readLiveWalSource(e,t);if(i){Object.assign(t,i.diagnostic);n=i.engine}else{const i=await prepareSqliteReadOnlyLocation(e.path,{preserveSourceArtifacts:true});try{try{var r=_usingCtx();const a=r.u(openNodeSqliteDatabase(i.location,{readOnly:true}));n=inspectSqliteStoreImage(t,a,e.path,e.descriptor)}catch(e){r.e=e}finally{r.d()}}finally{await i.cleanupAsync()}}if(n.engine===`postgres`)await inspectPostgres(t,n,e.postgres)}catch{t.issues.push(`The physical store could not be inspected safely.`);t.nextSteps.push(`Run openclaw doctor --fix with the matching version, or restore this store's verified backup.`)}if(t.observed===`postgres`&&t.degraded===null)t.nextSteps.push(`Search readiness was not verified; reopen the store through its owning feature to verify base search capabilities.`);if(t.schema.expectedVersion===null&&t.schema.versioning!==`unversioned`)t.nextSteps.push(`The store owner did not provide an expected schema version; use the matching plugin or OpenClaw version for schema verification.`);t.nextSteps=[...new Set(t.nextSteps)];return t} //!src/commands/doctor-database-legacy-inspection.ts async function inspectDoctorDatabaseLegacyMigrations(e){const t=listDatabaseEngineStores().filter(e=>e.postgres);const n={};for(const e of t)n[e.id]={state:`none`,pending:[]};const markUnknown=()=>{for(const e of t)n[e.id].state=`unknown`};try{await withArtifactPreservingStateReads(async()=>{const t=resolvePluginDoctorStateMigrationRecords({...e,includeDisabled:true,artifactPreservingReadOnly:true});const r=/* @__PURE__ */ new Set;const i=listPluginDoctorStateMigrationEntries({...e,includeDisabled:true,inventory:{records:t,knownPluginIds:t.map(e=>e.id),sessionStoreOwnerPluginIds:[],descriptors:[],unresolvedPluginIds:[]},onInspectedPlugin:e=>r.add(e),onInspectedStatelessPlugin:e=>r.add(e)});if(t.some(e=>{const t=e.doctorContract?.stateMigrations;return(t===true||Array.isArray(t)&&t.length>0)&&!r.has(e.id)}))markUnknown();for(const t of i){const r=t.migration.sqliteOnly?.family;if(!r)continue;const i=n[r];try{if(await t.migration.detectLegacyState(createPluginDoctorStateMigrationInput({...e,oauthDir:resolveOAuthDir(e.env,e.stateDir)},t))!==null){i.pending.push(`${t.pluginId}/${t.migration.id} (${t.migration.label})`);if(i.state!==`unknown`)i.state=`pending`}}catch{i.state=`unknown`}}},{agentDatabases:true})}catch{markUnknown()}return n} //!src/commands/doctor-database-engine-inspection.worker.ts serveWorkerTasks(async(e,t,n)=>{const r={...e.env,OPENCLAW_STATE_DIR:e.stateDir};const i=[];const a={observed:{},stateRoots:[],discoveryFailed:false,stores:i};let o;try{o=await resolveDatabaseEngineSelection(e.config,r)}catch{a.discoveryFailed=true}const inspect=async()=>{let t;try{t=resolvePluginMetadataSnapshot({...e,env:r})}catch{a.discoveryFailed=true;try{t=loadBundledPluginManifestRegistry({env:r})}catch{t={plugins:[]}}}const n=await inspectDoctorDatabaseLegacyMigrations({...e,env:r});const s=/* @__PURE__ */ new Set;for(const c of describeDatabaseEngineSelection(e.config)){const l=databasePortProviders.find(e=>e.id===c.id);if(!l)continue;let u;try{u=await l.resolveRoots({...e,env:r,plugins:t})}catch{a.discoveryFailed=true;u=c.id===`state`?resolveStatePortRoots(e):c.id===`agent`?await resolveAgentPortRoots({...e,env:r},[]):[]}const d=/* @__PURE__ */ new Set;const f=/* @__PURE__ */ new Set;let p=false;for(const e of u)try{const t=fs.statSync(e,{throwIfNoEntry:false});if(t?.isFile()){d.add(fs.realpathSync(e));p=true}else if(!t&&e.endsWith(`.sqlite`))d.add(e);else if(t?.isDirectory()){const t=await walkDirectory(e,{symlinks:`include`,include:e=>(e.kind===`file`||e.kind===`symlink`)&&e.path.endsWith(`.sqlite`)});if(t.failedDirs.length){a.discoveryFailed=true;for(const e of t.failedDirs){d.add(e.path);f.add(e.path)}}for(const e of t.entries)try{d.add(fs.realpathSync(e.path));p=true}catch{a.discoveryFailed=true;d.add(e.path);f.add(e.path)}}}catch{a.discoveryFailed=true;d.add(e);f.add(e)}let m;if(p)try{m=await l.loadDescriptor(t.plugins.find(e=>e.id===l.id))}catch{a.discoveryFailed=true}for(const e of d.size?[...d].toSorted():[null]){if(e&&s.has(e))continue;if(e)s.add(e);const t=await inspectDatabaseStore({family:c.id,path:e,configured:{default:c.default,override:c.override,effective:c.effective,fixedLocal:c.fixedLocal},descriptor:m,postgres:o?.postgres,inspectionError:e&&f.has(e)?`unreadable-root`:void 0});t.legacyMigrations=n[c.id]??{state:`unknown`,pending:[]};if(t.legacyMigrations.state!==`none`)t.nextSteps.push(`Run openclaw doctor --fix before database port; enable any named disabled plugin for repair.`);i.push(t);if(t.observed!==`unknown`){const e=a.observed[c.id]??=[];if(!e.includes(t.observed))e.push(t.observed)}if(c.id===`state`&&e&&t.observed!==`unknown`){const n=t.observed===`sqlite`?{engine:`sqlite`}:{engine:`postgres`,namespace:t.namespace,storeId:t.storeId};a.stateRoots.push({path:e,physical:n})}}}for(const t of listLocalDatabaseDiagnosticStores()){let n=null;try{n=await t.resolvePath(r)}catch{a.discoveryFailed=true}i.push(await inspectDatabaseStore({family:t.id,path:n,schemaVersion:t.resolveSchemaVersion?await t.resolveSchemaVersion():null,configured:{default:e.config.database?.engine??`sqlite`,override:null,effective:`sqlite`,fixedLocal:true}}))}};const inspectState=()=>{if(o?.effectiveEngines.state!==`sqlite`)return inspect();try{const e=resolveOpenClawStateSqlitePath(r);if(!fs.statSync(e,{throwIfNoEntry:false})?.isFile())return inspect();fs.accessSync(e,fs.constants.R_OK)}catch{return inspect()}return withOpenClawStateDatabaseReadSnapshot(inspect,{env:r,preferLiveOwner:true})};const s=createPluginCache();await n.runNativeSection(async()=>{try{await withPluginCache(s,()=>withPluginSourceCaptureStorage({stateDir:e.stateDir,placement:`temporary`},()=>withArtifactPreservingStateReads(()=>withSqliteReadOnlyWorkerScope(()=>o?withDatabaseEngineSelection(o,inspectState):inspectState(),{signal:n.signal,deadlineOwnedByCaller:true}),{agentDatabases:true})))}finally{await retirePluginCache(s,void 0,{waitForSettlement:true})}});return a});export{};