UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

19 lines • 31.9 kB
import{o as RESPAWN_SIGNAL_FORCE_KILL_GRACE_MS}from"./gateway-shutdown-budget-Utx5eFL-.mjs";import{g as requestCliParentTermination,h as getCliParentPid}from"./cli-invocation-Covx3kvQ.mjs";import{r as isForegroundGatewayRunArgv}from"./gateway-run-argv-Cz2rb_aK.mjs";import{o as resolveGlobalSingleton}from"./global-singleton-DolL9xGt.mjs";import{a as extractErrorCode,n as coerceErrorMessage,p as toErrorObject}from"./error-coercion-DlKnt6w-.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{n as createCpuTrackedWorker}from"./worker-cpu-Cmr50ooq.mjs";import{t as runInDetachedAsyncContext}from"./detached-async-context-DLLuWsxc.mjs";import{a as recordWorkerMessage}from"./worker-message-metrics-CdbgV0zo.mjs";import{t as isPromiseLike}from"./promise-like-OKzBwzLG.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{t as settlesWithin}from"./settle-within-DXfRNkao.mjs";import{a as normalizeWindowsPathForComparison}from"./path-guards-DGttsOJI.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{v as resolveGatewayLockDir,y as resolveGatewayLockDirForCanonicalStateDir}from"./paths-D_FOvGon.mjs";import{i as resolveRuntimeWorkerThreadExecArgv}from"./runtime-worker-url-Dqf-I1cs.mjs";import{o as resolveRuntimeProcessEntrypointUrl}from"./runtime-process-url-DJ272Tuo.mjs";import{d as resolveIdentityPathViaExistingAncestor,f as resolveIdentityPathViaExistingAncestorSync}from"./path-existence-BR9MXlgL.mjs";import{a as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-maintenance-context-D-pYfco8.mjs";import{l as runWithSqliteCleanup}from"./sqlite-lifecycle-errors-DMaudCZS.mjs";import{n as readProcessMachineIdentity}from"./current-machine-identity-DvsOGL6Z.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{_ as sql,i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS}from"./openclaw-state-db-contract-G6fQNIi2.mjs";import{i as isPidAlive,t as getFileLockProcessStartTime}from"./pid-alive-DDtSxW5l.mjs";import{n as isLockOwnerDefinitelyStale,t as inspectStaleLockOwner}from"./stale-lock-file-BYuveJm1.mjs";import{a as LEGACY_GATEWAY_OWNER_LEASE_TTL_MS,c as classifyGatewayOwnerProcessNamespace,f as parseGatewayLockPayload,l as describeGatewayLockHolder,m as readLockHeartbeat,n as GATEWAY_OWNER_HEARTBEAT_STALE_MS,o as LockPayloadSchema,p as readGatewayLockProcessNamespace,r as GatewayLockNamespaceError,t as GATEWAY_OWNER_HEARTBEAT_MS,u as isLegacyGatewayLeaseLock}from"./gateway-lock-payload-CBa45_pI.mjs";import{t as normalizeSqliteNonNegativeInteger}from"./sqlite-busy-timeout-CKFMTRX2.mjs";import{n as openNodeSqliteDatabase,o as resolveReadOnlyShmSqliteFileUri}from"./node-sqlite-DXyF1fBG.mjs";import{o as resolveOpenClawStateDirForDatabasePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import"./openclaw-state-db-async-lifecycle-DlV0ztcV.mjs";import{a as StateDatabaseOfflineMaintenanceError,i as StateDatabaseMaintenanceScopeError,n as StateDatabaseAccessError,o as createGatewayStateProcessOwnerRetiredError,r as StateDatabaseAdmissionPendingError,t as GatewayStateOwnerContentionError}from"./gateway-state-owner-errors-Cke3Bshm.mjs";import{r as sha256HexPrefixCore}from"./node-crypto-DPk8agfR.mjs";import"./crypto-digest-T8X5EZni.mjs";import{t as applyPrivateModeSync}from"./private-mode-Bw_N-P5J.mjs";import{n as captureRuntimeWorkerSource}from"./runtime-worker-generation-0fwjR0Cv.mjs";import{t as acquireFileLockSync}from"./file-lock-manager-BLv3gBvz.mjs";import{t as classifyOpenClawArgv}from"./gateway-process-argv-CNoJIDKD.mjs";import fs from"node:fs";import path from"node:path";import{randomUUID}from"node:crypto";import os from"node:os";import{MessageChannel,isMainThread}from"node:worker_threads";import{AsyncLocalStorage}from"node:async_hooks"; //!src/infra/gateway-lock-recovery-namespace.ts function classifyGatewayLockProcessNamespace(e,t,n){if(e&&n&&isLegacyGatewayLeaseLock(e)){const t=Date.now();const r=Date.parse(e.createdAt);if(!Number.isFinite(r)||t-r<=3e5)return`unknown`;try{const r=openNodeSqliteDatabase(resolveReadOnlyShmSqliteFileUri(n),{readOnly:true});try{const n=getNodeSqliteKysely(r);const{rows:i}=executeSqliteQuerySync(r,{compile:()=>sql`SELECT expires_at AS expiresAt FROM ${sql`state_leases NOT INDEXED`} WHERE scope = ${`gateway-owner`} AND owner = ${e.ownerId}`.compile(n)});return i.every(e=>typeof e.expiresAt===`number`&&e.expiresAt<=t)?`dead`:`unknown`}finally{r.close()}}catch{return`unknown`}}if((process.platform===`win32`||process.platform===`darwin`)&&e&&e.processNamespace===void 0&&t){try{if(Date.now()-fs.statSync(t).mtimeMs>9e4&&isLockOwnerDefinitelyStale({payload:{pid:e.pid,starttime:e.startTime}}))return`dead`}catch{}return`unknown`}return classifyGatewayOwnerProcessNamespace(e?.processNamespace,{machineIdentity:e?.machineIdentity,readGatewayHeartbeat:t?()=>readLockHeartbeat(t):void 0})} //!src/infra/gateway-state-owner-lifecycle.ts function createGatewayStateProjection(e){let t=1;const reference=()=>{let n=false;return{lockPath:e.lockPath,verifyStillHeld:()=>!n&&e.verifyStillHeld(),retain(){if(n||!e.verifyStillHeld())throw new Error(`Gateway state projection is no longer current`);t+=1;return reference()},release(){readOwnerPaths.clear();if(n)return;if(t===1)e.release();t-=1;n=true}}};return reference()}function hasPhysicalOwnership(e){try{return verifyOwnerLock(e,e.locks.values().next().value)}catch(t){if(e.lost.signal.aborted)return false;throw t}}function verifyOwnerLock(e,t){e.lost.signal.throwIfAborted();e.heartbeat?.inspect();if(!t)return false;const n=e.getProjection?.();if(n&&e.heartbeat&&!e.heartbeat.paths.has(n.lockPath))e.heartbeat.register(n);const r=e.payload.role??`gateway`;if(e.kind===`process`&&e.accepting&&(r===`gateway`||r===`agent-embedded`)&&e.heartbeat){e.heartbeat.assertActive();return true}if(!t.verifyStillHeld()){loseOwner(e,/* @__PURE__ */ new Error(`${t.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`));return false}return true}const log=createSubsystemLogger(`gateway/state`);function loseOwner(e,t){if(e.lost.signal.aborted)return;e.accepting=false;readOwnerPaths.clear();e.heartbeat?.stop();log.error(t.message);e.lost.abort(t)}function observeOwnerLoss(e,t,n){const r=[...e.locks,e.getProjection?.()];if(!n||r.some(e=>e?.lockPath===n))loseOwner(e,t)}const readOwnerPaths=resolveGlobalSingleton(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map);const owners=resolveGlobalSingleton(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map); //!src/infra/gateway-state-owner-cold-admission.ts function createColdAdmissionBudget(e){const t=normalizeSqliteNonNegativeInteger(e.busyTimeoutMs,`busyTimeoutMs`);const n=performance.now()+t;const r=resolveIdentityPathViaExistingAncestorSync(e.databasePath);const remainingBusyTimeoutMs=()=>Math.max(0,Math.ceil(n-performance.now()));const retryDelay=t=>{if(!(t instanceof StateDatabaseAdmissionPendingError)||resolveIdentityPathViaExistingAncestorSync(t.databasePath)!==r||e.canRetry?.()===false)throw t;const i=n-performance.now();if(i<=0)throw t;return Math.min(10,i)};return{remainingBusyTimeoutMs,retryDelay}} //!src/infra/gateway-state-owner-directory.ts const LOCAL_STATE_FILESYSTEM_GUIDANCE=`Run OpenClaw as the user that owns its state directory, and keep that directory on a local filesystem that supports file ownership and permissions`;function ensureOwnerDirectory(e,t){const n=fs.mkdirSync(e,{recursive:true,mode:448});if(n&&t){const r=path.toNamespacedPath(n);const i=[];for(let t=e;;){const{dev:e,ino:n}=fs.lstatSync(t,{bigint:true});i.push({path:t,dev:e,ino:n});if(path.toNamespacedPath(t)===r)break;const a=path.dirname(t);if(a===t)throw new Error(`Created state ownership directory is outside its expected ancestry`);t=a}for(const e of i){const n=t.findIndex(t=>t.path===e.path);if(n<0)t.push(e);else t[n]=e}}const r=fs.lstatSync(e);const i=process.getuid?.();if(!r.isDirectory())throw new Error(`State ownership directory must be a user-owned real directory`);if(i!==void 0&&r.uid!==i)throw new Error(`State ownership directory ${e} is owned by uid ${r.uid}, not this user (uid ${i}). ${LOCAL_STATE_FILESYSTEM_GUIDANCE}`);if(process.platform!==`win32`&&(r.mode&4095)!==448){applyPrivateModeSync(e,448);if((fs.lstatSync(e).mode&63)!==0)throw new Error(`State ownership directory ${e} permissions could not be set to 0700. ${LOCAL_STATE_FILESYSTEM_GUIDANCE}`)}}function removeCreatedProjectionDirectories(e){let t=e[0];while(t){try{const e=fs.lstatSync(t.path,{bigint:true});if(e.isDirectory()&&e.dev===t.dev&&e.ino===t.ino)fs.rmdirSync(t.path)}catch(e){const t=extractErrorCode(e);if(t!==`ENOENT`&&t!==`ENOTEMPTY`&&t!==`EEXIST`)throw e}e.shift();t=e[0]}}function resolveStateOwnerIdentity(e){const t=resolveIdentityPathViaExistingAncestorSync(e);return stateOwnerIdentity(t,resolveIdentityPathViaExistingAncestorSync(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){const t=await resolveIdentityPathViaExistingAncestor(e);return stateOwnerIdentity(t,await resolveIdentityPathViaExistingAncestor(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,t){return{canonicalPath:e,ownerPath:path.join(t,`state.${sha256HexPrefixCore(e,16)}.lock`),key:process.platform===`win32`?normalizeWindowsPathForComparison(e):e}}function stateOwnerDirectory(e){const t=process.getuid?.();return process.platform===`win32`?path.join(os.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,t===void 0?`openclaw-state-owners`:`openclaw-state-owners-${t}`):resolveGatewayLockDirForCanonicalStateDir(resolveOpenClawStateDirForDatabasePath(e))} //!src/infra/gateway-state-owner-heartbeat.runtime.ts function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n} //!src/infra/gateway-state-owner-heartbeat.ts const now=Date.now.bind(Date);function captureLock(e){const t=fs.readFileSync(e.lockPath,`utf8`);if(!e.verifyStillHeld())throw new Error(`OpenClaw state ownership is no longer current`);return t}function startGatewayStateOwnerHeartbeat(e,t){const n={};for(const t of e)n[t.lockPath]=captureLock(t);const r=Object.keys(n)[0];if(!r)throw new Error(`Gateway state ownership requires a held lock`);const i=fs.statSync(r,{bigint:true});const{moduleUrl:a,runtimeGeneration:o}=captureRuntimeWorkerSource(resolveRuntimeProcessEntrypointUrl(`gatewayStateOwnerHeartbeat`));return runInDetachedAsyncContext(()=>{const s=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(s,0,BigInt(now()));const{port1:c,port2:l}=new MessageChannel;const u=createCpuTrackedWorker(a,{workerData:{clock:`epoch`,locks:n,intervalMs:GATEWAY_OWNER_HEARTBEAT_MS,failureMs:6e4,lastBeat:s.buffer,events:l},transferList:[l],execArgv:resolveRuntimeWorkerThreadExecArgv(a)});const d=createDeferredCore();u.on(`message`,e=>{if(e===`closed`)d.resolve()});u.unref();let f=0;const p=/* @__PURE__ */ new Map;const rejectPending=e=>{for(const t of p.values())t.reject(e);p.clear();c.unref()};c.on(`message`,e=>{recordWorkerMessage(`lifecycle`,`from_worker`);if(e===`parent-lost`)requestCliParentTermination();else if(e&&typeof e===`object`&&e.type===`lost`)t(/* @__PURE__ */ new Error(`${e.error}; restart the Gateway.`),e.lockPath);else if(e&&typeof e===`object`&&e.type===`verified`){const t=p.get(e.id);p.delete(e.id);if(p.size===0)c.unref();if(e.error)t?.reject(new Error(e.error));else t?.resolve(e.current)}});c.unref();u.on(`error`,e=>{const n=/* @__PURE__ */ new Error(`${coerceErrorMessage(e)}; restart Gateway.`);rejectPending(n);t(n)});u.once(`exit`,()=>{d.resolve();rejectPending(/* @__PURE__ */ new Error(`Gateway state ownership verification worker stopped`))});let m;const remainingUntilInspection=()=>{const e=Atomics.load(s,0);const t=now()-Number(e);return t<0?0:6e4-t};const inspect=()=>{const e=remainingUntilInspection();if(e<=0)throw new Error(`Gateway state ownership renewal is overdue at ${r}; retry after storage recovers.`);return e};const renewAsync=async()=>{const t=now();const a=new Date(t);for(const t of e)try{const o=n[t.lockPath];if(o===void 0)throw new Error(`owner acquisition bytes were not registered`);const s=await fs.promises.open(t.lockPath,`r+`);try{const n=await s.stat({bigint:true});const c=await fs.promises.lstat(t.lockPath,{bigint:true});const l=Buffer.alloc(Buffer.byteLength(o)+1);const{bytesRead:u}=await s.read(l,0,l.length,0);const d=await fs.promises.lstat(t.lockPath,{bigint:true});if(m||!e.has(t))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(n,c,o,l.subarray(0,u).toString(`utf8`))||!d.isFile()||d.dev!==n.dev||d.ino!==n.ino||t.lockPath===r&&(n.dev!==i.dev||n.ino!==i.ino)){if(t.lockPath!==r)continue;throw new Error(`owner lock was removed or replaced`)}await s.utimes(a,a)}finally{await s.close()}}catch(e){if(t.lockPath!==r&&hasErrnoCode(e,`ENOENT`))continue;throw e}if(!m&&e.size>0)Atomics.store(s,0,BigInt(t))};let h;let g;const watch=()=>{const e=remainingUntilInspection();if(e>0){h=setTimeout(watch,e);h.unref()}else g??=renewAsync().then(()=>{g=void 0;if(!m)watch()},e=>{g=void 0;if(!m)t(/* @__PURE__ */ new Error(`Gateway state ownership is no longer current at ${r}: ${coerceErrorMessage(e)}; restart the Gateway.`))})};watch();const stop=()=>{if(!m){clearTimeout(h);rejectPending(/* @__PURE__ */ new Error(`Gateway state ownership is no longer current`));c.close();u.ref();u.postMessage(`stop`,[]);m=(async()=>{if(!await settlesWithin(d.promise,1e3))process.emitWarning(`Gateway state-owner heartbeat did not close within ${RESPAWN_SIGNAL_FORCE_KILL_GRACE_MS}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`});return u.terminate()})()}return Promise.all([m,g]).then(()=>void 0)};o?.retain(u,async()=>async()=>{await stop()});const assertActive=()=>{if(m||u.threadId===-1)throw new Error(`Gateway state ownership verification worker stopped`)};const _=new Set(Object.keys(n));return{worker:u,paths:_,register(e){const t=captureLock(e);n[e.lockPath]=t;u.postMessage([e.lockPath,t],[]);_.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();const t=++f;return new Promise((n,r)=>{p.set(t,{resolve:n,reject:r});c.ref();try{u.postMessage({type:`verify`,id:t,paths:e},[])}catch(e){p.delete(t);if(p.size===0)c.unref();r(toErrorObject(e,`Gateway state ownership verification failed`))}})},stop}})} //!src/infra/gateway-state-owner-record.ts const ownerInspections=new AsyncLocalStorage;function withPersistedStateOwnerInspection(e){return ownerInspections.run({},e)}function comparableStateOwnerStaleReason(e,t){return t===`dead`?`owner-process-exited`:t===`same`?inspectStaleLockOwner({payload:{pid:e.pid,starttime:e.startTime}})?.reason:void 0}function isGatewayStateOwnerDefinitelyStale(e,t,n){const r=isRecord(e)?e:null;if(!r)return false;const i=classifyGatewayLockProcessNamespace(r,t,n);if(i===`unknown`)throw new GatewayLockNamespaceError(r,t);return comparableStateOwnerStaleReason(r,i)!==void 0}const isStateDatabaseMaintenanceContention=e=>e instanceof AggregateError?e.errors.length>0&&e.errors.every(isStateDatabaseMaintenanceContention):e instanceof StateDatabaseAdmissionPendingError||e instanceof StateDatabaseOfflineMaintenanceError;function assertPersistedStateDatabaseAccessAllowed(e){const{databasePath:t,ownerPath:n,assertMaintenance:r}=e;const i=`OpenClaw state ownership at ${t} could not be verified from ${n}; restart the Gateway.`;let a;try{a=fs.readFileSync(n,`utf8`)}catch(e){if(extractErrorCode(e)===`ENOENT`)return;throw new StateDatabaseAccessError(i,{cause:e})}const o=ownerInspections.getStore();if(o?.deadOwner?.path===n&&o.deadOwner.raw===a)return;const s=parseGatewayLockPayload(a);if(!s)throw new StateDatabaseAdmissionPendingError(t,i);if(!Number.isSafeInteger(s.pid)||s.pid<=0)throw new StateDatabaseAccessError(i);const c=classifyGatewayLockProcessNamespace(s,n,t);const l=comparableStateOwnerStaleReason(s,c);if(l){if(o&&l===`owner-process-exited`)o.deadOwner={path:n,raw:a};return}if(c===`same`&&s.pid===process.pid&&!isMainThread)return;if(c===`same`&&!isPidAlive(s.pid))throw new StateDatabaseAdmissionPendingError(t,i);const u=s.role??`gateway`;if(u===`gateway`||u===`agent-embedded`)return;if(c===`same`&&s.pid===process.pid){r();return}const d=`OpenClaw state at ${t} is undergoing offline maintenance by ${u} process ${s.pid}, started ${s.createdAt}; retry when it finishes. For update progress, run \`openclaw update status --json\`. ${describeGatewayLockHolder(s,n,c===`same`?`live`:`unknown`)}`;if(s.stateOwnerKind===`schema`&&s.role===`sqlite-maintenance`)throw new StateDatabaseAdmissionPendingError(t,d);throw new StateDatabaseOfflineMaintenanceError(t,d)}function defaultPayload(e){const t=resolveOpenClawStateDirForDatabasePath(e);const n=getFileLockProcessStartTime(process.pid);const r=getCliParentPid();const i=r===void 0?null:getFileLockProcessStartTime(r);return{pid:process.pid,ownerId:randomUUID(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:path.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:readGatewayLockProcessNamespace(),machineIdentity:process.platform===`darwin`?readProcessMachineIdentity():void 0,...r===void 0?{}:{parentPid:r},...i===null?{}:{parentStartTime:i},...n===null?{}:{startTime:n}}}function reserveGatewayStateRestoration(e,t){t();const n=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;const r=defaultPayload(e);const stale=({payload:e})=>isGatewayStateOwnerDefinitelyStale(e);const i=acquireFileLockSync(n,{lockPath:n,timeoutMs:0,retry:{retries:0},staleMs:Infinity,staleRecovery:`remove-if-unchanged`,payload:()=>{t();return r},shouldReclaim:stale,shouldRemoveStaleLock:stale});let a=false;return{assertCurrent(){if(a||!i.verifyStillHeld())throw new Error(`Gateway restoration reservation is no longer current.`)},release(){i.release();a=true}}}function assertGatewayRestorationPriority(e,t,n){if(n.role===`gateway`)return;let r;try{r=fs.readFileSync(t,`utf8`)}catch(e){if(extractErrorCode(e)===`ENOENT`)return;throw e}const i=parseGatewayLockPayload(r);if(isGatewayStateOwnerDefinitelyStale(i)||i?.pid===n.pid)return;if(n.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&classifyOpenClawArgv(process.argv,{command:`gateway`}).kind===`openclaw`)return;throw new StateDatabaseAdmissionPendingError(e,`Gateway restoration has priority for OpenClaw state at ${e}; retry when it finishes.`)}function acquireGatewayStateOwnerFile(e,t,n,r=0,i){const a=performance.now()+r;const o=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;assertGatewayRestorationPriority(e,o,n);ensureOwnerDirectory(path.dirname(t),i);const s={holder:null};const stale=({payload:n})=>{s.holder=LockPayloadSchema.safeParse(n).data??null;return isGatewayStateOwnerDefinitelyStale(s.holder,t,e)};if(r>0)try{const n=s.holder=parseGatewayLockPayload(fs.readFileSync(t,`utf8`));if(n&&!isGatewayStateOwnerDefinitelyStale(n,t,e)&&(n.pid===process.pid||(n.role??`gateway`)===`gateway`&&isPidAlive(n.pid)))throw new GatewayStateOwnerContentionError(e)}catch(e){if(extractErrorCode(e)!==`ENOENT`)throw e}for(let c=false;;)try{return acquireFileLockSync(t,{lockPath:t,retry:r>0?{factor:1.25,minTimeout:10,maxTimeout:25,randomize:false}:{retries:0},timeoutMs:Math.max(0,Math.ceil(a-performance.now())),staleMs:Infinity,staleRecovery:`remove-if-unchanged`,reentrantOwner:n.ownerId,payload:()=>{assertGatewayRestorationPriority(e,o,n);return n},shouldReclaim:stale,shouldRemoveStaleLock:stale})}catch(n){const r=extractErrorCode(n);if(r===`ENOENT`&&!c){c=true;ensureOwnerDirectory(path.dirname(t),i);continue}if(r===`file_lock_timeout`||r===`file_lock_stale`){const{holder:r}=s;const i=describeGatewayLockHolder(r??{},t,r&&isPidAlive(r.pid)?`live`:`unknown`);throw new GatewayStateOwnerContentionError(e,n,i,r?{pid:r.pid,role:r.role}:void 0)}throw n}} //!src/infra/gateway-state-owner.ts const schemaOwners=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new AsyncLocalStorage);function getStateDatabaseSchemaLease(e){const t=schemaOwners.getStore()?.get(resolveStateOwnerIdentity(e).key);if(t&&!t.active)throw new Error(`State schema maintenance scope is no longer current`);t?.lease.assertCurrent();return t?.lease}function withStateDatabaseColdAdmission(e,t){const{remainingBusyTimeoutMs:n,retryDelay:r}=createColdAdmissionBudget(e);const i=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));for(;;)try{assertStateDatabaseAccessAllowed(e.databasePath);return t(n)}catch(e){Atomics.wait(i,0,0,r(e))}}function resolveGatewayStateOwnerPath(e){return resolveStateOwnerIdentity(e).ownerPath}function leaseForFile(e,t,n,r){let i=false;const holdsPhysicalLease=()=>verifyOwnerLock(n,t)&&(!r||r.verifyStillHeld());function run(e){a.assertCurrent();readOwnerPaths.clear();const t=new Map(schemaOwners.getStore());const r={lease:a,active:true};t.set(n.key,r);const leave=()=>{r.active=false;readOwnerPaths.clear()};try{const n=schemaOwners.run(t,e);if(isPromiseLike(n))return Promise.resolve(n).finally(leave);leave();return n}catch(e){leave();throw e}}const a={path:e,assertCurrent(){if(i||!holdsPhysicalLease())throw new Error(`OpenClaw state ownership is no longer current`)},assertDatabaseAccess(e){if(i||owners.get(n.key)!==n||resolveStateOwnerIdentity(e).key!==n.key||!holdsPhysicalLease())throw new Error(`OpenClaw state maintenance does not own this database`)},run,release(){readOwnerPaths.clear();if(!i){r?.release();t.release();i=true;n.locks.delete(t);if(r)n.locks.delete(r);if(n.locks.size===0&&owners.get(n.key)===n){n.heartbeat?.stop();n.accepting=false;owners.delete(n.key);n.onReleased?.()}}if(n.locks.size===0)removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireGatewayStateOwner(e){const t=resolveStateOwnerIdentity(e.databasePath);const n=t.ownerPath;const r=owners.get(t.key);if(r)throw new GatewayStateOwnerContentionError(e.databasePath,void 0,describeGatewayLockHolder(r.payload,n,`live`),{pid:r.payload.pid,role:r.payload.role});const i=e.payload?{...e.payload.role===`sqlite-maintenance`?defaultPayload(e.databasePath):{},...e.payload,ownerId:e.payload.ownerId??randomUUID()}:defaultPayload(e.databasePath);const a={key:t.key,path:n,kind:`process`,payload:i,projectionPath:e.projectionPath,getProjection:e.getProjection,locks:/* @__PURE__ */ new Set,projectionDirectories:[],lost:new AbortController,accepting:true,onReleased:e.onReleased};const o=acquireGatewayStateOwnerFile(e.databasePath,n,i);a.locks.add(o);readOwnerPaths.clear();owners.set(a.key,a);const s=leaseForFile(n,o,a);try{a.heartbeat=startGatewayStateOwnerHeartbeat(a.locks,(e,t)=>observeOwnerLoss(a,e,t));const t=e.custody;const onCustodyLost=()=>{const e=t?.reason;loseOwner(a,e instanceof Error?e:/* @__PURE__ */ new Error(`State custody was lost`))};t?.addEventListener(`abort`,onCustodyLost,{once:true});s.assertCurrent()}catch(e){return runWithSqliteCleanup(s,`state process ownership verification`,()=>{throw e})}return{path:n,assertCurrent(){a.lost.signal.throwIfAborted();if(!a.accepting||owners.get(a.key)!==a)throw createGatewayStateProcessOwnerRetiredError();s.assertCurrent()},assertDatabaseAccess:s.assertDatabaseAccess,run:s.run,release(){a.accepting=false;s.release()}}}function acquireStateDatabaseSchemaLease(e,t={}){readOwnerPaths.clear();const n=resolveStateOwnerIdentity(e);let r=owners.get(n.key);const i=r?.path??n.ownerPath;if(r&&(!r.accepting||!hasPhysicalOwnership(r)))throw new GatewayStateOwnerContentionError(e,r.lost.signal.reason);if(r)assertStateDatabaseAccessAllowed(e);const a=r?.payload??{...defaultPayload(e),stateOwnerKind:`schema`};let o;const s=[];try{o=acquireGatewayStateOwnerFile(e,i,a,r?0:t.busyTimeoutMs??5e3,s)}catch(t){if(t instanceof GatewayStateOwnerContentionError)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof StateDatabaseAdmissionPendingError)throw e}throw t}const c=r?.projectionPath??path.join(resolveGatewayLockDir(resolveOpenClawStateDirForDatabasePath(resolveIdentityPathViaExistingAncestorSync(e))),`gateway.state.lock`);let l;try{l=r?.getProjection?.()?.retain()??acquireGatewayStateOwnerFile(e,c,{...a,role:a.role===`gateway`?`gateway`:`agent-embedded`},0,s)}catch(e){return runWithSqliteCleanup({release(){o.release();removeCreatedProjectionDirectories(s)}},`state schema projection admission`,()=>{throw e})}if(r){r.locks.add(o);r.locks.add(l);r.projectionDirectories.push(...s)}else{r={key:n.key,path:i,kind:`schema`,payload:a,projectionPath:c,locks:/* @__PURE__ */ new Set([o,l]),projectionDirectories:s,lost:new AbortController,accepting:true};owners.set(r.key,r)}const u=leaseForFile(i,o,r,l);try{const e=r.heartbeat??=startGatewayStateOwnerHeartbeat(r.locks,(e,t)=>observeOwnerLoss(r,e,t));u.assertCurrent();e.register(l);return u}catch(e){return runWithSqliteCleanup(u,`state schema ownership verification`,()=>{throw e})}}function tryBorrowGatewayStateOwner(e){const t=owners.get(resolveStateOwnerIdentity(e).key);if(!t||t.kind!==`process`)return;if(!t.accepting||!hasPhysicalOwnership(t))throw new GatewayStateOwnerContentionError(e,t.lost.signal.reason);assertStateDatabaseAccessAllowed(e);return acquireStateDatabaseSchemaLease(e)}function hasActiveGatewayStateOwner(e){const t=owners.get(resolveStateOwnerIdentity(e).key);return t?.kind===`process`&&t.accepting&&(t.payload.role??`gateway`)===`gateway`&&hasPhysicalOwnership(t)}function captureGatewayStateOwner(e){const t=resolveStateOwnerIdentity(e);const{key:n}=t;const r=owners.get(n);if(!r||r.kind!==`process`)return;const assertCurrent=(i=e)=>{r.lost.signal.throwIfAborted();const a=resolveIdentityPathViaExistingAncestorSync(i);const o=process.platform===`win32`?normalizeWindowsPathForComparison(a):a;if(owners.get(n)!==r||!r.accepting||o!==n)throw new GatewayStateOwnerContentionError(e);assertStateDatabaseAccessAtOwnerPath(e,t,void 0)};assertCurrent();return{ownerId:r.payload.ownerId,role:r.payload.role??`gateway`,assertCurrent,prepareAccess:createStateDatabaseAccess(t,r).prepareAccess,signal:r.lost.signal}}function captureGatewayStateOwnerAsync(e){return captureAdmittedGatewayStateOwner(e,true)}function prepareStateDatabaseReadAccess(e){return captureAdmittedGatewayStateOwner(e,false)}async function captureAdmittedGatewayStateOwner(e,t){e.assertCurrent();const n=e.identity.canonicalPath;const r=process.platform===`win32`?normalizeWindowsPathForComparison(n):n;const i=owners.get(r);if(!i||i.kind!==`process`)return;const a={canonicalPath:n,key:r,ownerPath:i.path};const assertRegistered=()=>{e.assertCurrent();i.lost.signal.throwIfAborted();if(owners.get(r)!==i)throw createGatewayStateProcessOwnerRetiredError()};const assertCurrent=()=>{assertRegistered();if(!i.accepting)throw createGatewayStateProcessOwnerRetiredError();assertStateDatabaseAccessAtOwnerPath(n,a,void 0)};const o=createStateDatabaseAccess(a,i);const assertReadAllowed=e=>{assertRegistered();o.assertReadAllowed(e)};const s=path.resolve(e.databasePath);const c=t?assertCurrent:assertRegistered;c();if(t||readOwnerPaths.get(s)!==i){const t=await resolveIdentityPathViaExistingAncestor(s);c();if((process.platform===`win32`?normalizeWindowsPathForComparison(t):t)!==r)throw new GatewayStateOwnerContentionError(e.databasePath)}if(!t){assertReadAllowed();if(readOwnerPaths.get(path.resolve(n))===i)readOwnerPaths.set(s,i)}return{ownerId:i.payload.ownerId,role:i.payload.role??`gateway`,signal:i.lost.signal,assertCurrent,assertReadAllowed,prepareAccess:o.prepareAccess}}function assertStateDatabaseReadAllowed(e,t){assertStateDatabaseReadAtOwnerPath(e,t)}function assertStateDatabaseReadAtOwnerPath(e,t,n){if(owners.size===0){assertStateDatabaseAccessAtOwnerPath(e,n??resolveStateOwnerIdentity(e),t);return}const r=path.resolve(e);if(readOwnerPaths.get(r)?.accepting)return;const i=n??resolveStateOwnerIdentity(e);const a=owners.get(i.key);const o=a?.payload.role??`gateway`;if(!a||a.kind!==`process`||!a.accepting||o!==`gateway`&&o!==`agent-embedded`){assertStateDatabaseAccessAtOwnerPath(e,i,t);return}if(!hasPhysicalOwnership(a)){a.lost.signal.throwIfAborted();throw new Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`)}readOwnerPaths.set(r,a)}function assertStateDatabaseAccessAllowed(e,t){assertStateDatabaseAccessAtOwnerPath(e,resolveStateOwnerIdentity(e),t)}async function captureStateDatabaseAccess(e){return createStateDatabaseAccess(await resolveStateOwnerIdentityAsync(e))}function createStateDatabaseAccess(e,t){const{canonicalPath:n}=e;const r=owners.get(e.key);return{canonicalPath:n,processOwner:r?.kind===`process`?{role:r.payload.role??`gateway`,signal:r.lost.signal,assertCurrent(){r.lost.signal.throwIfAborted();if(!r.accepting||owners.get(e.key)!==r)throw createGatewayStateProcessOwnerRetiredError()}}:void 0,prepareAccess:async r=>{const i=t??owners.get(e.key);const a=i?.payload.role??`gateway`;if(!i||i.kind!==`process`||!i.accepting||a!==`gateway`&&a!==`agent-embedded`){assertStateDatabaseAccessAtOwnerPath(n,e,r);return(t=r)=>{if(i&&owners.get(e.key)!==i)throw createGatewayStateProcessOwnerRetiredError();assertStateDatabaseReadAtOwnerPath(n,t,e)}}const o=i.heartbeat;const s=i.locks.values().next().value;const c=i.getProjection?.();if(!o||!s)throw createGatewayStateProcessOwnerRetiredError();const assertCurrent=(t=r)=>{i.lost.signal.throwIfAborted();o.assertActive();if(owners.get(e.key)!==i||i.heartbeat!==o)throw createGatewayStateProcessOwnerRetiredError();if(!i.accepting){assertStateDatabaseAccessAtOwnerPath(n,e,t);return}if(!i.locks.has(s)||i.getProjection?.()!==c)throw createGatewayStateProcessOwnerRetiredError()};assertCurrent();const l=[s.lockPath];if(c)l.push(c.lockPath);const u=await o.verify(l).catch(e=>{i.lost.signal.throwIfAborted();throw e});assertCurrent();if(!u){const e=/* @__PURE__ */ new Error(`${s.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`);loseOwner(i,e);throw e}readOwnerPaths.set(path.resolve(n),i);return assertCurrent},assertReadAllowed(t){assertStateDatabaseReadAtOwnerPath(n,t,e)}}}function assertStateDatabaseAccessAtOwnerPath(e,t,n){const assertMaintenance=()=>{const t=n?n.schemaLease:getStateDatabaseSchemaLease(e);if(t){t.assertDatabaseAccess(e);return}const r=n?n.maintenanceScope:getOpenClawDatabaseMaintenanceScope();if(!r)throw new StateDatabaseMaintenanceScopeError(e);r.assertDatabaseAccess(e)};const r=owners.get(t.key);if(r){if(!hasPhysicalOwnership(r)){r.lost.signal.throwIfAborted();throw new Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`)}const t=r.payload.role??`gateway`;if(!r.accepting||t!==`gateway`&&t!==`agent-embedded`)assertMaintenance();return}assertPersistedStateDatabaseAccessAllowed({databasePath:e,ownerPath:t.ownerPath,assertMaintenance})}function tryAcquireGatewayStateOwner(e){try{return acquireGatewayStateOwner({databasePath:e})}catch(e){if(e instanceof GatewayStateOwnerContentionError)return null;throw e}}export{readOwnerPaths as C,createGatewayStateProjection as S,isGatewayStateOwnerDefinitelyStale as _,captureGatewayStateOwner as a,withPersistedStateOwnerInspection as b,getStateDatabaseSchemaLease as c,resolveGatewayStateOwnerPath as d,tryAcquireGatewayStateOwner as f,defaultPayload as g,assertPersistedStateDatabaseAccessAllowed as h,assertStateDatabaseReadAllowed as i,hasActiveGatewayStateOwner as l,withStateDatabaseColdAdmission as m,acquireStateDatabaseSchemaLease as n,captureGatewayStateOwnerAsync as o,tryBorrowGatewayStateOwner as p,assertStateDatabaseAccessAllowed as r,captureStateDatabaseAccess as s,acquireGatewayStateOwner as t,prepareStateDatabaseReadAccess as u,isStateDatabaseMaintenanceContention as v,classifyGatewayLockProcessNamespace as w,resolveStateOwnerIdentity as x,reserveGatewayStateRestoration as y};