openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 19.9 kB
JavaScript
import{i as collectNestedErrorCandidates}from"./error-coercion-DlKnt6w-.mjs";import{o as racePromiseWithAbortSignal}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"./session-key-BPgKfU2m.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{g as isReservedSystemAgentId,i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{o as isSameOpenClawAgentDatabasePath}from"./openclaw-agent-db.paths-SkzMsgQ0.mjs";import{A as tryResolveLegacyCompatibilityAgentId,O as tryResolveAmbientOwnerAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{i as isSqliteWorkerError,r as hasSqliteWorkerOutcomeUnknown}from"./sqlite-worker-error-DHUQ0e2U.mjs";import{a as isSqliteCorruptionError,o as isSqliteLockError,p as sqliteErrorCode,r as formatSqliteReadOnlyInspectionFailure}from"./sqlite-error-diagnostics-ASl1MXPN.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{a as WorkerTaskError}from"./src-D4Y-r8_m.mjs";import{M as resolveAgentCreationClaimAgentId,w as AgentDatabaseStartupPublicationError}from"./openclaw-agent-db-resources-KCMTIo4b.mjs";import"./worker-task-pool-Bg54sSAN.mjs";import{a as resolveSqliteDatabaseFilePaths}from"./sqlite-files-731tEtYd.mjs";import{a as resolveUpdateRehearsalRoot}from"./update-rehearsal-paths-C4qLj9oD.mjs";import{h as openClawStateDatabaseCache}from"./openclaw-state-db-cache-uycu-8uy.mjs";import{s as isTerminalSqliteIntegrityError}from"./sqlite-integrity-BzUEDiX5.mjs";import{n as runWithSqliteDatabaseAdmissionTurn}from"./sqlite-database-admission-turn-Bsy2PyA1.mjs";import{o as sessionChanges}from"./session-row-changes-21DJT-m_.mjs";import{n as quotePowerShellArg,t as quoteCliArg}from"./quote-cli-arg-BUHoGELl.mjs";import fs from"node:fs";import{AsyncLocalStorage}from"node:async_hooks";
//!src/infra/sqlite-recovery-files.ts
function moveSqliteFilesAside(e,t){const n=inspectSqliteRecoveryFiles(e);const r=planSqliteRecoveryMoves(n.existing);const i=[];try{for(const n of r.toSorted((t,n)=>{if(t.sourcePath===e)return 1;if(n.sourcePath===e)return-1;return t.sourcePath.localeCompare(n.sourcePath)})){t();fs.renameSync(n.sourcePath,n.destinationPath);i.push(n)}}catch(n){const r=[];const a=[];for(const e of i.toReversed())try{t();if(fs.lstatSync(e.sourcePath,{throwIfNoEntry:false}))throw new Error(`rollback source was recreated: ${e.sourcePath}`,{cause:n});fs.renameSync(e.destinationPath,e.sourcePath)}catch(t){r.push(t);a.push(e.destinationPath)}if(r.length>0){const t=r.map(e=>String(e)).join(`; `);throw new Error(`Could not move corrupt SQLite file set aside or restore it: ${e}; rollback failures: ${t}. Preserved recovery files: ${a.join(`, `)}`,{cause:n})}throw n}return{movedFiles:r.map(e=>e.destinationPath),skippedFiles:n.missing}}function inspectSqliteRecoveryFiles(e){const t=[];const n=[];for(const r of resolveSqliteDatabaseFilePaths(e)){const e=fs.lstatSync(r,{throwIfNoEntry:false});if(!e)n.push(r);else if(!e.isFile())throw new Error(`SQLite recovery path is not a regular file: ${r}`);else t.push(r)}return{existing:t,missing:n}}function planSqliteRecoveryMoves(e){const t=`.corrupt-${Date.now()}`;for(let n=0;n<100;n+=1){const r=n===0?t:`${t}.${n}`;const i=e.map(e=>({destinationPath:`${e}${r}`,sourcePath:e}));if(i.every(e=>!fs.lstatSync(e.destinationPath,{throwIfNoEntry:false})))return i}throw new Error(`Could not choose recovery paths for ${e[0]??`SQLite files`}`)}
//!src/infra/state-migrations.agent-owner-guidance.ts
function formatAgentDatabaseCorruptionRepairHint(e,t){if(formatSqliteReadOnlyInspectionFailure(t).includes(`creating its private snapshot:`))return;if(!collectNestedErrorCandidates(t).some(e=>isSqliteCorruptionError(e)||[`SQLITE_CORRUPT`,`SQLITE_NOTADB`].includes(sqliteErrorCode(e)??``)||e instanceof Error&&isTerminalSqliteIntegrityError(e)))return;return`Stop the Gateway, back up this database and its SQLite sidecars, then run "${formatCliCommand(`openclaw doctor --session-sqlite recover --session-sqlite-agent ${quoteCliArg(e)}`)}" against the same state/config. Recovery repairs supported index corruption or preserves damaged files with a .corrupt-<timestamp> suffix. Restore a verified backup if you need the previous sessions, then restart the Gateway.`}function formatAgentDatabaseOwnershipRepairHint(e){const t=planSqliteRecoveryMoves(resolveSqliteDatabaseFilePaths(e).filter(e=>fs.lstatSync(e,{throwIfNoEntry:false})));t.sort((t,n)=>Number(t.sourcePath===e)-Number(n.sourcePath===e));const n=t.map(({sourcePath:e,destinationPath:t})=>process.platform===`win32`?`Move-Item -LiteralPath ${quotePowerShellArg(e)} -Destination ${quotePowerShellArg(t)} -ErrorAction Stop`:`mv -n -- ${quoteCliArg(e)} ${quoteCliArg(t)}`).join(process.platform===`win32`?`; `:` && `);return`Preserve and inspect this database before accepting a fresh agent. With all OpenClaw processes stopped, the explicit quarantine move is${process.platform===`win32`?` (PowerShell)`:``}:\n${n}\nThen run openclaw doctor --fix and restart the Gateway.`}
//!src/state/agent-database-admission.ts
function createAgentDatabaseAdmissionErrorShape(e){const t=e.code===`agent-database-inspection-pending`;return{code:`UNAVAILABLE`,message:`${e.reason}\n${e.repairHint}`,details:e,retryable:t,...t?{retryAfterMs:250}:{}}}const refusalCauses=/* @__PURE__ */ new WeakMap;const readAdmissions=/* @__PURE__ */ new Map;const refusalsByState=/* @__PURE__ */ new Map;const startupFtsRepairs=/* @__PURE__ */ new Map;function recordAgentDatabaseStartupFtsRepair(e,t,n){if(n===void 0&&startupFtsRepairs.has(e))throw new Error(`Startup FTS repair was already attempted. Run openclaw doctor --fix.`);startupFtsRepairs.set(e,{statePath:t,message:n});if(n)createSubsystemLogger(`state/agent-db`).warn(n)}function listAgentDatabaseStartupFtsRepairs(){const e=stateKey({});return[...startupFtsRepairs.values()].flatMap(t=>t.statePath===e&&t.message?[t.message]:[])}const preparation=new AsyncLocalStorage;function runOutsideAgentDatabasePreparation(e){return preparation.exit(e)}function retainAgentDatabaseStartupWorker(e,t,n){const r=preparation.getStore();if(r?.access!==`write`||r.refusal.agentId!==e||r.key!==stateKey(t))return false;r.assertCurrent();r.workers.defer(()=>racePromiseWithAbortSignal(n(),r.signal));return true}function isAgentDatabasePreparationRetryable(e){return!hasSqliteWorkerOutcomeUnknown(e)&&(isSqliteLockError(e)||isSqliteWorkerError(e,`overloaded`)||e instanceof WorkerTaskError&&e.code===`overloaded`)}function createAgentDatabaseInspectionRefusal(e){const t=resolveUpdateRehearsalRoot(process.env)&&e.reason.includes(`creating its private snapshot:`)&&/(?:code=(?:ENOSPC|EDQUOT)\b|errcode=13\b)/u.test(e.reason);const n=collectNestedErrorCandidates(e.cause).some(e=>e instanceof Error&&e.name===`DataCloneError`);const r=!e.pending&&isSqliteLockError(e.cause);const i=e.cause instanceof AgentDatabaseStartupPublicationError;const a={agentId:e.agentId,paths:e.paths,code:e.pending?`agent-database-inspection-pending`:`agent-database-inspection-failed`,reason:r?`database locked by another process`:e.reason,repairHint:!e.pending&&isAgentDatabasePreparationRetryable(e.cause)?`Wait for competing database work to finish, then restart the Gateway to retry admission. Lock or worker capacity contention does not require database repair.`:t?`Free space in the reported snapshot cache, then retry the update. This candidate snapshot failure does not require repairing the serving database.`:n?`A worker request could not be serialized. Update OpenClaw and restart the Gateway; repeating database migration will not repair this request.`:i?`Sessions remain unavailable because newer config or plugin changes kept replacing this agent's runtime preparation. Restart the Gateway to retry admission. This failure does not require database repair.`:e.pending?`Startup preparation is in progress or waiting for capacity. Retry the request after startup preparation finishes. Pending startup does not indicate a database failure.`:`Sessions remain unavailable. ${formatAgentDatabaseCorruptionRepairHint(e.agentId,e.cause)??`Stop the Gateway, run "openclaw doctor --fix" to inspect and repair this agent database, and restart.`}`};refusalCauses.set(a,e.cause);return a}function stateKey(e){return resolveOpenClawStateSqlitePath(e.env??process.env)}function sameKnownState(e,t){if(e===t)return true;const n=openClawStateDatabaseCache.getKnownOpenClawStateDatabaseIdentity(e);const r=openClawStateDatabaseCache.getKnownOpenClawStateDatabaseIdentity(t);return Boolean(n&&r&&n.key===r.key)}function createAgentDatabaseDeletionRefusal(e){return{agentId:e.agentId,paths:e.paths,code:`agent-deletion`,reason:`Agent ${e.agentId} was deleted during startup inspection`,repairHint:`Deletion has closed this agent's admission. If cleanup remains pending, resolve its reported failure and retry agents.delete. Database repair is not required.`}}function createAgentDatabaseHeldRefusal(e,t){return{agentId:e,paths:t,code:`agent-database-held`,reason:`Agent ${e} database is held for explicit restoration.`,repairHint:`Run openclaw doctor --fix for restoration guidance, then restore the preserved store with agents add. Held databases are not live agents.`}}function releaseAgentDatabaseHeldAdmission(e,t={}){const n=refusalsByState.get(stateKey(t));if(!n)return;for(const[t,r]of n.refusals){let i=false;const a=admissionRefusalParts(r).flatMap(t=>{if(t.code!==`agent-database-held`)return[t];const n=t.paths.filter(t=>!e.some(e=>isSameOpenClawAgentDatabasePath(t,e)));if(n.length===t.paths.length)return[t];i=true;return n.length?[{...t,paths:n}]:[]});if(!i)continue;const o=mergeAdmissionRefusals(a);if(o)n.refusals.set(t,o);else n.refusals.delete(t);sessionChanges.emit({all:true,scope:{agentId:t,topology:true}})}}function captureAgentDatabasePreparationDeletionForIdentity(e,{identityKey:t,databasePath:n}){const r=normalizeAgentId(e);const i=[...refusalsByState].flatMap(([e,i])=>{const a=openClawStateDatabaseCache.getKnownOpenClawStateDatabaseIdentity(e);const o=i.refusals.get(r);return(e===n||a?.key===t)&&o?.code===`agent-database-inspection-pending`?[{key:e,owner:i,refusal:o}]:[]});return()=>{if(openClawStateDatabaseCache.getKnownOpenClawStateDatabaseIdentity(n)?.key!==t)return;for(const{key:e,owner:t,refusal:a}of i){if(refusalsByState.get(e)!==t||t.refusals.get(r)!==a||!sameKnownState(e,n))continue;const i=new Map(t.refusals);i.set(r,createAgentDatabaseDeletionRefusal(a));t.refusals=i}}}function captureAgentDatabasePreparationJournal(e,t={}){const n=preparation.getStore();if(!n||n.refusal.agentId!==normalizeAgentId(e)||!sameKnownState(n.key,stateKey(t)))return;const assertCurrent=()=>{if(!n.active)throw new Error(`Agent database preparation has ended: ${e}`);n.assertCurrent()};assertCurrent();return e=>{assertCurrent();if(e!==false)throw new AgentDatabaseAdmissionError(createAgentDatabaseDeletionRefusal(n.refusal))}}function inspectAgentDatabaseAdmission(e){const t=normalizeAgentId(e.agentId);const n=e.metadata;if(n?.role!==`agent`||!n.agentId||n.agentId===t)return;return{agentId:t,paths:[e.path],embeddedOwnerId:n.agentId,code:`agent-database-ownership-mismatch`,reason:`Refused agent ${t}: database ${e.path} belongs to agent ${n.agentId}; requested agent ${t}.`,repairHint:formatAgentDatabaseOwnershipRepairHint(e.path)}}function canIsolateAgentDatabase(e,t){return listAgentIds(e).includes(t)&&!isReservedSystemAgentId(t)&&t!==tryResolveAmbientOwnerAgentId(e)&&t!==tryResolveLegacyCompatibilityAgentId(e)}function admissionRefusalParts(e){const t=refusalCauses.get(e);return t instanceof AggregateError&&t.errors.length>0&&t.errors.every(t=>t instanceof AgentDatabaseAdmissionError&&t.refusal.agentId===e.agentId)?t.errors.flatMap(e=>admissionRefusalParts(e.refusal)):[e]}function mergeAdmissionRefusals(e){if(e.length<2)return e[0];const t={...e.find(e=>e.code===`agent-database-ownership-mismatch`)??e.find(e=>e.code!==`agent-database-held`&&e.code!==`agent-database-inspection-pending`)??e.find(e=>e.code===`agent-database-held`)??e[0],paths:[...new Set(e.flatMap(e=>e.paths))],reason:e.map(e=>e.reason).join(`
`),repairHint:e.map(e=>e.repairHint).join(`
`)};refusalCauses.set(t,new AggregateError(e.map(e=>new AgentDatabaseAdmissionError(e))));return t}function recordAgentDatabaseAdmissions(e,t={}){const n=stateKey(t);const r=t.source??`diagnostic`;if(r===`diagnostic`&&refusalsByState.get(n)?.source===`startup`)return;const i=/* @__PURE__ */ new Map;for(const t of e){const e=i.get(t.agentId);if(e===t)continue;const n=e?mergeAdmissionRefusals([...admissionRefusalParts(e),...admissionRefusalParts(t)]):t;i.set(t.agentId,n)}refusalsByState.set(n,{source:r,refusals:i})}function hasAgentDatabaseAdmissions(e={}){return refusalsByState.has(stateKey(e))}function readAgentDatabaseAdmissionRefusal(e,t={}){return readSelectedAgentDatabaseAdmissionRefusal(stateKey(t),normalizeAgentId(e),e)}function readAgentDatabaseReadAdmissionRefusal(e,t={}){return readSelectedAgentDatabaseReadAdmissionRefusal(stateKey(t),normalizeAgentId(e),e)}function readSelectedAgentDatabaseReadAdmissionRefusal(e,t,n){const r=readSelectedAgentDatabaseAdmissionRefusal(e,t,n,`read`);const i=r&&readAdmissions.get(r);if(r?.code===`agent-database-inspection-pending`&&i?.key===e)try{i.assertCurrent();return}catch{}return r}function publishPendingAgentDatabaseReadAdmission(e,t){t.assertCurrent();const n=stateKey(t);if(e.code!==`agent-database-inspection-pending`||refusalsByState.get(n)?.refusals.get(e.agentId)!==e)throw new Error(`Agent database admission changed before read preparation: ${e.agentId}`);const r={key:n,paths:t.paths,assertCurrent:t.assertCurrent};readAdmissions.set(e,r);runWithAgentDatabaseReadAdmissionTurn=runWithInspectionReadAdmissionTurn;isAgentDatabaseStartupReadReady=inspectAgentDatabaseStartupReadReady;return()=>{if(readAdmissions.get(e)===r){readAdmissions.delete(e);if(readAdmissions.size===0){runWithAgentDatabaseReadAdmissionTurn=runWithSqliteDatabaseAdmissionTurn;isAgentDatabaseStartupReadReady=noStartupReadAdmission}if(refusalsByState.get(n)?.refusals.has(e.agentId))sessionChanges.invalidate({all:true,scope:{agentId:e.agentId,topology:true}})}}}const noStartupReadAdmission=()=>false;let isAgentDatabaseStartupReadReady=noStartupReadAdmission;function inspectAgentDatabaseStartupReadReady(e,t={}){for(const n of refusalsByState.get(stateKey(t))?.refusals.values()??[])if(readAdmissions.get(n)?.paths.includes(e)&&!readAgentDatabaseReadAdmissionRefusal(n.agentId,t))return true;return false}let runWithAgentDatabaseReadAdmissionTurn=runWithSqliteDatabaseAdmissionTurn;function runWithInspectionReadAdmissionTurn(e,t,n=[],r,i={}){const a=refusalsByState.get(stateKey(i))?.refusals.size?e.filter(e=>!isAgentDatabaseStartupReadReady(e,i)):e;return runWithSqliteDatabaseAdmissionTurn(a,t,n,r,i)}function assertAgentDatabaseReadAdmitted(e,t={}){const n=readAgentDatabaseReadAdmissionRefusal(e,t);if(n)throw new AgentDatabaseAdmissionError(n)}function readSelectedAgentDatabaseAdmissionRefusal(e,t,n,r=`write`){const i=refusalsByState.get(e)?.refusals.get(t);if(i?.code===`agent-database-held`&&admissionRefusalParts(i).every(e=>e.code===`agent-database-held`)&&resolveAgentCreationClaimAgentId(t,e)===t)return;const a=preparation.getStore();if(a&&a.key===e&&a.refusal.agentId===t){if(a.access===`read`&&(r===`write`||!a.active))return i;if(!a.active)throw new Error(`Agent database preparation has ended: ${n}`);a.assertCurrent();if(a.refusal===i)return}return i}async function preparePendingAgentDatabase(e,t,n){await withPendingAgentDatabasePreparation(e,t,`write`,n);sessionChanges.emit({all:true,scope:{agentId:e.agentId,topology:true}})}async function preparePendingAgentDatabaseRead(e,t,n){await withPendingAgentDatabasePreparation(e,t,`read`,n)}async function withPendingAgentDatabasePreparation(e,t,n,r){const i=stateKey(t);const assertCurrent=()=>{t.assertCurrent();if(e.code!==`agent-database-inspection-pending`||refusalsByState.get(i)?.refusals.get(e.agentId)!==e)throw new Error(`Agent database admission changed during preparation: ${e.agentId}`)};assertCurrent();const a={key:i,refusal:e,assertCurrent,access:n,active:true,signal:t.signal,workers:new AsyncDisposableStack};try{await preparation.run(a,async()=>{try{var e=_usingCtx();e.a(a.workers);await r()}catch(t){e.e=t}finally{await e.d()}});a.assertCurrent();if(n===`write`){const t=refusalsByState.get(i);const n=new Map(t.refusals);n.delete(e.agentId);t.refusals=n}}finally{a.active=false}}function failPendingAgentDatabase(e,t,n){const r=stateKey(n);const i=refusalsByState.get(r);if(i?.refusals.get(e.agentId)!==e)return;const a=new Map(i.refusals);a.set(e.agentId,t instanceof AgentDatabaseAdmissionError&&t.refusal.agentId===e.agentId&&t.refusal.code!==`agent-database-inspection-pending`?t.refusal:createAgentDatabaseInspectionRefusal({...e,reason:formatErrorMessage(t),cause:t}));i.refusals=a}function listAgentDatabaseAdmissionRefusals(e={}){return[...refusalsByState.get(stateKey(e))?.refusals.values()??[]]}var AgentDatabaseAdmissionError=class extends Error{constructor(e){super(`Agent ${e.agentId} (${e.paths.join(`, `)}): ${e.reason}\n${e.repairHint}`,{cause:refusalCauses.get(e)});this.refusal=e;this.name=`AgentDatabaseAdmissionError`}};function isAgentDatabaseOwnershipMismatchError(e){return collectNestedErrorCandidates(e).some(e=>e instanceof AgentDatabaseAdmissionError&&e.refusal.code===`agent-database-ownership-mismatch`)}function assertAgentDatabaseAdmitted(e,t={}){const n=readAgentDatabaseAdmissionRefusal(e,t);if(n)throw new AgentDatabaseAdmissionError(n)}function captureAgentDatabaseAdmission(e,t={}){const n=stateKey(t);const r=normalizeAgentId(e);const i=t.access===`read`;return()=>{const t=i?readSelectedAgentDatabaseReadAdmissionRefusal(n,r,e):readSelectedAgentDatabaseAdmissionRefusal(n,r,e);if(t)throw new AgentDatabaseAdmissionError(t)}}async function evaluateAgentDatabaseAdmissions(e,t={}){const{preflightOpenClawDatabaseSchemas:n}=await import(`./openclaw-database-preflight-BW_fgol_.mjs`);const{resolveConfiguredAgentDatabaseCandidatePaths:r}=await import(`./targets-C8LX-ajf.mjs`);const i=t.env??process.env;return(await n({env:i,configuredAgentDatabaseTargets:[],configuredAgentDatabaseCandidatePaths:r(e,{env:i}),agentAdmissionConfig:e},`runtime`)).agentRefusals??[]}export{runOutsideAgentDatabasePreparation as A,publishPendingAgentDatabaseReadAdmission as C,recordAgentDatabaseStartupFtsRepair as D,recordAgentDatabaseAdmissions as E,moveSqliteFilesAside as F,formatAgentDatabaseCorruptionRepairHint as M,formatAgentDatabaseOwnershipRepairHint as N,releaseAgentDatabaseHeldAdmission as O,inspectSqliteRecoveryFiles as P,preparePendingAgentDatabaseRead as S,readAgentDatabaseReadAdmissionRefusal as T,isAgentDatabasePreparationRetryable as _,captureAgentDatabaseAdmission as a,listAgentDatabaseStartupFtsRepairs as b,createAgentDatabaseAdmissionErrorShape as c,createAgentDatabaseInspectionRefusal as d,evaluateAgentDatabaseAdmissions as f,isAgentDatabaseOwnershipMismatchError as g,inspectAgentDatabaseAdmission as h,canIsolateAgentDatabase as i,runWithAgentDatabaseReadAdmissionTurn as j,retainAgentDatabaseStartupWorker as k,createAgentDatabaseDeletionRefusal as l,hasAgentDatabaseAdmissions as m,assertAgentDatabaseAdmitted as n,captureAgentDatabasePreparationDeletionForIdentity as o,failPendingAgentDatabase as p,assertAgentDatabaseReadAdmitted as r,captureAgentDatabasePreparationJournal as s,AgentDatabaseAdmissionError as t,createAgentDatabaseHeldRefusal as u,isAgentDatabaseStartupReadReady as v,readAgentDatabaseAdmissionRefusal as w,preparePendingAgentDatabase as x,listAgentDatabaseAdmissionRefusals as y};