openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
11 lines • 16 kB
JavaScript
import{c as toErrorObject}from"./error-coercion-B-1Loz4b.mjs";import{l as resolveGlobalSingleton}from"./string-coerce-BBqv4GXj.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{c as isPathInside,t as resolveStateDir}from"./state-dir-C22DK7p0.mjs";import"./paths-BFN5qw21.mjs";import{t as createSubsystemLogger}from"./subsystem-BMw5Czn-.mjs";import{t as formatErrorMessage}from"./errors-BKYtsKt6.mjs";import"./sqlite-worker-identity-gGA4fE_R.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-BAgG4Sc_.mjs";import{n as normalizeAgentId}from"./agent-id-0RKGHEYi.mjs";import{s as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-db-async-lifecycle-CLe5OGzr.mjs";import{n as matchesAgentDatabaseReadCandidatePath,r as registerAgentDatabaseReaderCloser}from"./agent-database-readers-CvzYLGgy.mjs";import{AsyncLocalStorage}from"node:async_hooks";import{isDeepStrictEqual}from"node:util";import{realpathSync,statSync}from"node:fs";import path from"node:path";import{createHash}from"node:crypto";import{probePathSuffixAliasesSync,resolvePathPrefixSync}from"@openclaw/fs-safe/advanced";import{isMainThread,threadId}from"node:worker_threads";
//!src/state/openclaw-agent-db.paths.ts
const INCOGNITO_AGENT_SQLITE_BASENAME=`incognito-openclaw-agent.sqlite`;const agentSqlitePaths=/* @__PURE__ */ new Map;const agentSqlitePathKeys=agentSqlitePaths.keys();function resolveOpenClawAgentSqlitePath(e){if(e.path!=null)return path.resolve(e.path);const t=normalizeAgentId(e.agentId);const n=resolveStateDir(e.env??process.env);const r=`${t}:${n}`;const i=agentSqlitePaths.get(r);if(i!==void 0)return i;const a=path.resolve(n,`agents`,t,`agent`,`openclaw-agent.sqlite`);agentSqlitePaths.set(r,a);if(agentSqlitePaths.size>256){const e=agentSqlitePathKeys.next();if(!e.done)agentSqlitePaths.delete(e.value)}return a}function resolveIncognitoOpenClawAgentSqlitePath(e){return path.join(path.dirname(resolveOpenClawAgentSqlitePath(e)),INCOGNITO_AGENT_SQLITE_BASENAME)}function isIncognitoOpenClawAgentSqlitePath(e,t){const n=path.resolve(e);return path.basename(n)===`incognito-openclaw-agent.sqlite`&&n===resolveIncognitoOpenClawAgentSqlitePath(t)}const missingSuffixAliasCache=/* @__PURE__ */ new Map;function shouldProbeUnicodeCaseVariants(e,t){const hasNonAscii=e=>e.split(``).some(e=>e.charCodeAt(0)>127);if(!hasNonAscii(e)&&!hasNonAscii(t))return false;const n=e.toLowerCase()===t.toLowerCase();return e.toUpperCase()===t.toUpperCase()||n&&Array.from(e).length===Array.from(t).length}function areMissingSuffixAliases(e){if(e.left===e.right)return true;const t=e.left.split(path.sep);const n=e.right.split(path.sep);if(t.length!==n.length||[...t,...n].some(e=>!e||e===`.`||e===`..`))return false;const r=[e.left,e.right].toSorted();const i=JSON.stringify([e.parentDevice,e.parentInode,e.parentRealPath,...r]);const a=missingSuffixAliasCache.get(i);if(a!==void 0)return a;let o;let s;try{o=probePathSuffixAliasesSync({directory:e.parentRealPath,left:e.left,right:e.right,maxDepth:t.length,shouldProbeCaseVariants:shouldProbeUnicodeCaseVariants})}catch(e){s=e}if(o===void 0)throw new Error(`Cannot determine whether database paths alias under ${JSON.stringify(e.parentRealPath)}: ${JSON.stringify(e.left)} and ${JSON.stringify(e.right)}. Check directory access and retry.`,{cause:s});missingSuffixAliasCache.set(i,o);return o}function anchorDatabasePathWithoutNormalizing(e){const t=path.sep===`\\`?e.replaceAll(`/`,`\\`):e;if(path.isAbsolute(t))return t;if(path.sep===`\\`){const e=/^([A-Za-z]:)(.*)$/u.exec(t);if(e){const t=path.resolve(`${e[1]}.`);return e[2]?`${t}${t.endsWith(path.sep)?``:path.sep}${e[2]}`:t}}const n=process.cwd();return`${n}${n.endsWith(path.sep)?``:path.sep}${t}`}function resolveAgentDatabasePathIdentity(e){const t=anchorDatabasePathWithoutNormalizing(e);try{const e=realpathSync.native(t);const n=statSync(e,{bigint:true});return{lexicalPath:t,realPath:e,device:n.dev.toString(),inode:n.ino.toString()}}catch(e){if(!hasErrnoCode(e,`ENOENT`))throw e;const n=path.parse(t).root;const r=resolvePathPrefixSync(n+t.slice(n.length).split(path.sep).filter(Boolean).join(path.sep));const i=r.existingPath;const a=statSync(i,{bigint:true});return{lexicalPath:t,parentDevice:a.dev.toString(),parentInode:a.ino.toString(),parentRealPath:i,unresolvedSuffix:r.unresolvedSegments.join(path.sep)}}}function areSameAgentDatabasePathIdentities(e,t){if(e.lexicalPath===t.lexicalPath)return true;if(`realPath`in e)return`realPath`in t&&(e.realPath===t.realPath||e.device===t.device&&e.inode===t.inode);return!(`realPath`in t)&&e.parentDevice===t.parentDevice&&e.parentInode===t.parentInode&&areMissingSuffixAliases({left:e.unresolvedSuffix,right:t.unresolvedSuffix,parentDevice:e.parentDevice,parentInode:e.parentInode,parentRealPath:e.parentRealPath})}function createOpenClawAgentDatabasePathMatcher(e=[]){const t=new Map(e.map(e=>[e.lexicalPath,e]));const resolveIdentity=e=>{const n=anchorDatabasePathWithoutNormalizing(e);const r=t.get(n);if(r)return r;const i=resolveAgentDatabasePathIdentity(n);t.set(n,i);return i};return Object.assign((e,t)=>areSameAgentDatabasePathIdentities(resolveIdentity(e),resolveIdentity(t)),{capture(e){resolveIdentity(e)},observations:()=>[...t.values()],createIndex(){const e=/* @__PURE__ */ new Map;const t=[];const n=/* @__PURE__ */ new Map;const r=/* @__PURE__ */ new Map;const i=/* @__PURE__ */ new Map;return a=>{const o=resolveIdentity(a);const s=e.get(o.lexicalPath);if(s!==void 0)return s;let c;if(`realPath`in o){const e=`${o.device}:${o.inode}`;const i=n.get(e);const a=r.get(o.realPath);c=i===void 0?a:a===void 0?i:Math.min(i,a);if(c===void 0){c=t.push(o)-1;n.set(e,c);r.set(o.realPath,c)}}else{const e=`${o.parentDevice}:${o.parentInode}`;const n=i.get(e)??[];c=n.find(e=>areSameAgentDatabasePathIdentities(t[e],o));if(c===void 0){c=t.push(o)-1;n.push(c);i.set(e,n)}}const l=t[c].lexicalPath;e.set(o.lexicalPath,l);return l}},isCurrent(){for(const e of t.values()){const t=resolveAgentDatabasePathIdentity(e.lexicalPath);if(!isDeepStrictEqual(e,t))return false}return true}})}function isSameOpenClawAgentDatabasePath(e,t){return areSameAgentDatabasePathIdentities(resolveAgentDatabasePathIdentity(e),resolveAgentDatabasePathIdentity(t))}function canonicalPathForRegistryBoundary(e){const t=resolveAgentDatabasePathIdentity(e);if(`realPath`in t)return t.realPath;const n=t.unresolvedSuffix.split(path.sep);return n.includes(`..`)?t.parentRealPath:path.join(t.parentRealPath,...n)}function isPersistentOpenClawAgentDatabasePath(e,t=process.env){const n=path.resolve(e);const r=path.join(path.resolve(resolveStateDir(t)),`imports`);if(isPathInside(r,n))return false;const i=canonicalPathForRegistryBoundary(e);const a=canonicalPathForRegistryBoundary(resolveStateDir(t));const o=canonicalPathForRegistryBoundary(path.join(a,`imports`));return!isPathInside(o,i)}
//!src/state/agent-creation-claim.ts
const creationClaim=resolveGlobalSingleton(Symbol.for(`openclaw.agentCreationClaim`),()=>new AsyncLocalStorage);const creationResources=resolveGlobalSingleton(Symbol.for(`openclaw.agentCreationClaimResources`),()=>/* @__PURE__ */ new Map);function getActiveAgentCreationClaim(e,t){const n=creationClaim.getStore();if(!n||n.kind!==`host`||!n.isActive()||n.agentId!==normalizeAgentId(e)||n.statePath!==path.resolve(t))return;return n}function reserveAgentCreationClaimAdmission(e,t,n){const r=getActiveAgentCreationClaim(t.agentId,resolveOpenClawStateSqlitePath(t.env??process.env));if(!r)return;creationResources.set(e,r);r.registerClose(async()=>{if(creationResources.get(e)!==r)return;await n();creationResources.delete(e)});return()=>{creationResources.delete(e)}}function releaseAgentCreationClaimHandle(e){creationResources.delete(e)}
//!src/state/agent-database-admission-error.ts
const AgentDatabaseExecutionAdmissionClosedError=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseExecutionAdmissionClosedError`),()=>class AdmissionClosedError extends Error{});const AgentDatabaseSchemaAdmissionChangedError=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionChangedError`),()=>class SchemaAdmissionChangedError extends Error{constructor(){super(`Agent schema admission changed before publication; retry the operation`)}});const AgentDatabaseSchemaAdmissionInvalidError=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionInvalidError`),()=>class SchemaAdmissionInvalidError extends Error{constructor(){super(`Invalid agent schema admission receipt`)}});const AgentDatabaseStartupPublicationError=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseStartupPublicationError`),()=>class StartupPublicationError extends Error{constructor(e){super(formatErrorMessage(e),{cause:e})}});
//!src/state/agent-deletion-cleanup.ts
const databaseCleanup=resolveGlobalSingleton(Symbol.for(`openclaw.agentDeletionDatabaseCleanup`),()=>new AsyncLocalStorage);const cleanupHandles=resolveGlobalSingleton(Symbol.for(`openclaw.agentDeletionDatabaseCleanupHandles`),()=>/* @__PURE__ */ new Map);const cleanupExecutions=resolveGlobalSingleton(Symbol.for(`openclaw.agentDeletionDatabaseCleanupExecutions`),()=>/* @__PURE__ */ new Map);function captureAgentDeletionResourceOwner(e){const t=databaseCleanup.getStore();if(!t?.ownsDatabase||!e(t)&&(!t.canonicalPath||!e({agentId:t.agentId,path:t.canonicalPath})))return;t.assertCurrentHost();return t}function releaseAgentDeletionDatabaseCleanup(e){cleanupHandles.delete(e)}
//!src/state/openclaw-agent-db-resources.ts
const resources=resolveGlobalSingleton(Symbol.for(`openclaw.agentDatabaseAsyncResources`),()=>({active:/* @__PURE__ */ new Set,closing:/* @__PURE__ */ new Map,selections:/* @__PURE__ */ new Map}));function hasOpenClawAgentDatabaseAsyncResources(e){return e?[...resources.active,...resources.closing.keys()].some(t=>matchesAgentDatabaseClose(e,t)):resources.active.size>0||resources.closing.size>0}function registerAgentDatabaseResourceReleaseHandler(e){resources.onRelease=e}function isAgentDatabaseClosing(e){const t={agentId:normalizeAgentId(e.agentId),path:path.resolve(e.path)};return[...resources.selections.keys()].some(e=>matchesAgentDatabaseClose(e,t))}registerAgentDatabaseReaderCloser(async(e,t)=>{const n=(await Promise.allSettled([.../* @__PURE__ */ new Set([...resources.active,...resources.closing.keys()])].filter(n=>!t?.has(path.resolve(n.path))&&e.some(e=>matchesAgentDatabaseReadCandidatePath(e,n.path))).map(e=>closeAgentDatabaseResource(e)))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(n.length>0)throw new AggregateError(n,`Agent database resource cleanup failed`)});function matchesAgentDatabaseClose(e,t){return(e.path===void 0||e.path===t.path||t.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(t,e.path))&&(e.rootPath===void 0||isPathInside(e.rootPath,t.path)||t.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(t,e.rootPath))&&(e.agentId===void 0||t.ownership===`unresolved`||e.agentId===t.agentId)}function registerOpenClawAgentDatabaseAsyncResource(e,t){return registerAgentDatabaseResource({...e,ownership:`known`,agentId:normalizeAgentId(e.agentId)},t)}function registerOpenClawAgentDatabaseSyncResource(e){return registerAgentDatabaseResource({...e,ownership:`known`,agentId:normalizeAgentId(e.agentId),close:async()=>e.close(),closeSync:e.close})}function registerOpenClawAgentDatabaseReadCandidateResource(e){return registerAgentDatabaseResource({...e,ownership:`unresolved`})}function registerAgentDatabaseResource(e,t){const n={...e,path:path.resolve(e.path)};n.cleanupOwner=captureAgentDeletionResourceOwner(e=>matchesAgentDatabaseClose(e,n));assertAgentDatabaseResourceAdmission(n);const r=t&&n.ownership===`known`?reserveAgentCreationClaimAdmission(n,t,()=>closeAgentDatabaseResource(n)):void 0;const unregister=()=>{resources.active.delete(n);r?.();resources.onRelease?.(n)};getOpenClawDatabaseMaintenanceScope()?.own(unregister,`agent-resources`,()=>closeAgentDatabaseResource(n));resources.active.add(n);return unregister}function assertAgentDatabaseResourceAdmission(e){if([...resources.selections.keys()].some(t=>matchesAgentDatabaseClose(t,e))||[...resources.closing.keys()].some(t=>(t.path===e.path||t.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(t,e.path)||e.ownership===`unresolved`&&matchesAgentDatabaseReadCandidatePath(e,t.path))&&(t.ownership===`unresolved`||e.ownership===`unresolved`||t.agentId===e.agentId)))throw new AgentDatabaseExecutionAdmissionClosedError(`Agent database resources are closing: ${e.path}`)}function closeAgentDatabaseResource(e,t){if(e.ownership===`known`&&e.closeSync){resources.closing.set(e,void 0);try{e.revoke();e.closeSync();resources.active.delete(e);resources.closing.delete(e);resources.onRelease?.(e);return Promise.resolve()}catch(n){if(t)t(e.path,n);const r=Promise.reject(toErrorObject(n,`Agent database cleanup failed`));r.catch(()=>{});return r}}let n=resources.closing.get(e);if(!n){n=Promise.resolve().then(()=>e.close());resources.closing.set(e,n);n.then(()=>{resources.active.delete(e);resources.closing.delete(e);resources.onRelease?.(e)},()=>{resources.closing.set(e,void 0)}).catch(()=>{})}if(t)n.catch(n=>t(e.path,n)).catch(()=>{});e.revoke();return n}function revokeAgentDatabaseResources(e,t){const n=/* @__PURE__ */ new Set([...resources.active,...resources.closing.keys()]);const r=[];for(const i of n){if(!matchesAgentDatabaseClose(e,i))continue;r.push(closeAgentDatabaseResource(i,t))}return r}async function drainAgentDatabaseResources(e,t,n){return withAgentDatabaseCloseFence(e,async()=>{const r=performance.now();const i=[.../* @__PURE__ */ new Set([...resources.active,...resources.closing.keys()])].filter(t=>matchesAgentDatabaseClose(e,t)&&(!n||t.cleanupOwner===n));const a=i.filter(e=>e.retireAfterResources);for(const e of a){if(!resources.closing.has(e))resources.closing.set(e,void 0);e.revoke()}const o=await Promise.allSettled(i.filter(e=>!e.retireAfterResources).map(e=>closeAgentDatabaseResource(e)));const s=performance.now();const c=o.flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(c.length>0)throw new AggregateError(c,`Agent database resource drainage failed`);const l=await Promise.allSettled(a.map(e=>closeAgentDatabaseResource(e)));const u=performance.now();const d=l.flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(d.length>0)throw new AggregateError(d,`Agent database native retirement failed`);const f=await t();const p=performance.now()-r;if(p>=500&&e.path){const t=createHash(`sha256`).update(e.path).digest(`hex`).slice(0,16);const n={totalMs:Math.round(p),resourceJoinMs:Math.round(s-r),workerJoinMs:Math.round(u-s),nativeOwnerMs:Math.round(p-(u-r))};createSubsystemLogger(`state/agent-db`).info(`agent database close settled: agent=${e.agentId??i.find(e=>e.ownership===`known`)?.agentId??`unknown`}; db=${t}; thread=${threadId}; close=${JSON.stringify(n)}`)}return f})}async function withAgentDatabaseCloseFence(e,t){const n={...e};resources.selections.set(n,void 0);try{const e=t([.../* @__PURE__ */ new Set([...resources.active,...resources.closing.keys()])].filter(e=>matchesAgentDatabaseClose(n,e)).map(e=>e.path));resources.selections.set(n,e);return await e}finally{resources.selections.delete(n)}}export{isIncognitoOpenClawAgentSqlitePath as _,matchesAgentDatabaseClose as a,resolveIncognitoOpenClawAgentSqlitePath as b,registerOpenClawAgentDatabaseReadCandidateResource as c,withAgentDatabaseCloseFence as d,releaseAgentDeletionDatabaseCleanup as f,createOpenClawAgentDatabasePathMatcher as g,INCOGNITO_AGENT_SQLITE_BASENAME as h,isAgentDatabaseClosing as i,registerOpenClawAgentDatabaseSyncResource as l,releaseAgentCreationClaimHandle as m,drainAgentDatabaseResources as n,registerAgentDatabaseResourceReleaseHandler as o,AgentDatabaseStartupPublicationError as p,hasOpenClawAgentDatabaseAsyncResources as r,registerOpenClawAgentDatabaseAsyncResource as s,assertAgentDatabaseResourceAdmission as t,revokeAgentDatabaseResources as u,isPersistentOpenClawAgentDatabasePath as v,resolveOpenClawAgentSqlitePath as x,isSameOpenClawAgentDatabasePath as y};