UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 55 kB
import{Cn as e,Dn as t,It as n,Lt as r,Tt as i,gt as a,kn as o,t as s,wn as c,wt as l,xt as u}from"./openclaw-state-read-subsystem-Dwoo5bcz.mjs";import{a as d,i as f,o as p}from"./openclaw-state-read-cli-invocation-OtTkpH1g.mjs";import{qt as m}from"./openclaw-state-read-sqlite-database-admission-CrkztOzk.mjs";import{Bt as h,Ct as g,F as _,Ft as v,I as y,It as b,N as x,Pt as S,Qt as C,V as w,Xt as T,h as ee,nn as E,pn as D,pt as te,q as ne,st as O,ut as re,yt as ie}from"./openclaw-state-read-src-RL5xtYG2.mjs";import{t as ae}from"./openclaw-state-read-promise-like-3qqJObCs.mjs";import{S as oe}from"./openclaw-state-read-sqlite-post-commit-CsXPYVOo.mjs";import{t as se}from"./openclaw-state-read-deferred-B75K7ut7.mjs";import{K as k,a as A,b as ce,c as le,d as ue,f as de,h as fe,i as pe,j,l as me,m as he,n as ge,o as M,r as _e,s as ve,t as ye,u as be,v as N,x as P}from"./openclaw-state-read-sidecar-lock-registration-XTuJQFHg.mjs";import{T as F,a as xe,d as Se,i as I,n as L,o as R,r as Ce,s as we,t as Te}from"./openclaw-state-read-file-lock-sync-root-6TrRFpor.mjs";import{t as Ee}from"./openclaw-state-read-lock-config-CQM_E5H4.mjs";import{o as De}from"./openclaw-state-read-openclaw-state-db.paths-7XLpcdiq.mjs";import{c as Oe,t as ke}from"./openclaw-state-read-runtime-worker-generation-DIZIqsAo.mjs";import"./openclaw-state-read-openclaw-state-db-contract-vqwNsqc6.mjs";import{c as Ae,i as je,l as Me,n as Ne,o as Pe,p as Fe,t as Ie,u as Le}from"./openclaw-state-read-gateway-lock-payload-BrJys_8Q.mjs";import{i as Re,t as ze}from"./openclaw-state-read-pid-alive-C5QrpWWk.mjs";import{n as Be}from"./openclaw-state-read-node-crypto-40z5rHq3.mjs";import{d as z,f as Ve,l as B,m as V,p as He,u as Ue}from"./openclaw-state-read-sqlite-worker-operation-settlement-DOkqmUGd.mjs";import{t as We}from"./openclaw-state-read-settle-within-Dt-aLhfm.mjs";import{n as Ge}from"./openclaw-state-read-runtime-worker-url-C8NPtAdy.mjs";import{s as Ke}from"./openclaw-state-read-sqlite-worker-request-class-DQkpMMiB.mjs";import{f as qe,n as Je}from"./openclaw-state-read-worker-cpu-CbvwBMyE.mjs";import{o as Ye,t as Xe}from"./openclaw-state-read-gateway-process-argv-BE-3R2z7.mjs";import{t as Ze}from"./openclaw-state-read-sqlite-busy-timeout-B0rAL9T0.mjs";import{t as Qe}from"./openclaw-state-read-sqlite-transaction-Bt-IwVhZ.mjs";import H,{chmodSync as $e,statSync as U,unlinkSync as et,writeFileSync as tt}from"node:fs";import W from"node:path";import{MessageChannel as nt,isMainThread as rt}from"node:worker_threads";import it from"node:os";import{randomUUID as at}from"node:crypto";import{AsyncLocalStorage as ot}from"node:async_hooks";import{setImmediate as st}from"node:timers/promises";const ct=/* @__PURE__ */ new Set([`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`]);function hasRestrictivePermissions(e){try{return!(U(e).mode&63)}catch{return!1}}function filesystemRejectsChmod(e){let t;try{let n=U(e).isDirectory()?e:W.dirname(e);t=W.join(n,`.openclaw-chmod-probe-${at()}`),tt(t,``,{flag:`wx`,mode:384})}catch{return!1}try{return $e(t,384),!1}catch(e){return v(e)&&e.code===`EPERM`}finally{try{et(t)}catch{}}}function canIgnorePrivateChmodError(e,t,n){return t&&ct.has(t)?!0:t!==`EROFS`&&t!==`EPERM`?!1:n||t===`EPERM`&&filesystemRejectsChmod(e)}function applyPrivateModeSync(e,t){if((U(e).mode&4095)===t)return{applied:!0};try{return $e(e,t),{applied:!0}}catch(t){if(!canIgnorePrivateChmodError(e,v(t)?t.code:void 0,hasRestrictivePermissions(e)))throw t;return{applied:!1,error:t}}}function ensureOwnerDirectory(e,t){let n=H.mkdirSync(e,{recursive:!0,mode:448});if(n&&t){let r=W.toNamespacedPath(n),i=[];for(let t=e;;){let{dev:e,ino:n}=H.lstatSync(t,{bigint:!0});if(i.push({path:t,dev:e,ino:n}),W.toNamespacedPath(t)===r)break;let a=W.dirname(t);if(a===t)throw Error(`Created state ownership directory is outside its expected ancestry`);t=a}for(let e of i){let n=t.findIndex(t=>t.path===e.path);n<0?t.push(e):t[n]=e}}let r=H.lstatSync(e),i=process.getuid?.();if(!r.isDirectory()||i!==void 0&&r.uid!==i)throw Error(`State ownership directory must be a user-owned real directory`);if(process.platform!==`win32`&&(r.mode&4095)!=448&&(applyPrivateModeSync(e,448),H.lstatSync(e).mode&63))throw Error(`State ownership directory permissions are not private`)}function removeCreatedProjectionDirectories(e){let n=e[0];for(;n;){try{let e=H.lstatSync(n.path,{bigint:!0});e.isDirectory()&&e.dev===n.dev&&e.ino===n.ino&&H.rmdirSync(n.path)}catch(e){let n=t(e);if(n!==`ENOENT`&&n!==`ENOTEMPTY`&&n!==`EEXIST`)throw e}e.shift(),n=e[0]}}function resolveStateOwnerIdentity(e){let t=i(e);return stateOwnerIdentity(t,i(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){let t=await l(e);return stateOwnerIdentity(t,await l(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,t){return{canonicalPath:e,ownerPath:W.join(t,`state.${Be(e,16)}.lock`),key:process.platform===`win32`?h(e):e}}function stateOwnerDirectory(e){let t=process.getuid?.();return process.platform===`win32`?W.join(it.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,t===void 0?`openclaw-state-owners`:`openclaw-state-owners-${t}`):r(De(e))}function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n}function captureRootSyncAcquireOptions(e){let t=e.lockPath,n=e.staleMs,r=e.timeoutMs,i=e.retry,a=e.staleRecovery,o=e.reentrantOwner,s=e.payload,c=e.shouldReclaim,l=e.shouldRemoveStaleLock,u=e.parsePayload,d=e.onCompromised,f=e.compromiseCheckIntervalMs,p=i===void 0?void 0:Object.freeze({retries:i.retries,factor:i.factor,minTimeout:i.minTimeout,maxTimeout:i.maxTimeout,randomize:i.randomize}),m=Ee(),h=m.retry,g=p??Object.freeze({retries:h?.retries,factor:h?.factor,minTimeout:h?.minTimeout,maxTimeout:h?.maxTimeout,randomize:h?.randomize}),_=r??m.timeoutMs,v=n??m.staleMs??3e4,y=a??m.staleRecovery;return le(g),be(_),me(v),ve(f),Object.freeze({compromiseCheckIntervalMs:f,lockPath:t,onCompromised:d,optionsReceiver:e,parsePayload:u,payload:s,reentrantOwner:o,retry:g,shouldReclaim:c,shouldRemoveStaleLock:l,staleMs:v,staleRecovery:y,timeoutMs:_})}const G=Symbol.for(`fsSafe.syncSidecarLocks`),K=Symbol.for(`fsSafe.syncSidecarLockAdmissions`),lt=Symbol.for(`fsSafe.syncSidecarLockCleanupRegistered`),ut=Symbol.for(`fsSafe.syncSidecarLockCleanupHandler`),dt=Symbol.for(`fsSafe.syncSidecarLockCleanupRegistration`),ft=Symbol.for(`fsSafe.syncRootSidecarLocks.v1`);function foreignSyncHeldLock(e,t){return globalThis[e===`raw`?ft:G]?.get(t)}function getSyncHeldLocks(){let e=globalThis;return e[G]||(e[G]=/* @__PURE__ */ new Map),e[G]}function getSyncLockAdmissions(){let e=globalThis;return e[K]||(e[K]=/* @__PURE__ */ new Map),e[K]}function syncReclaimGuardExists(e){try{return H.lstatSync(e,{throwIfNoEntry:!1})!==void 0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function ensureSyncLockExitCleanupRegistered(e,t,n){ye({event:`exit`,registered:lt,registering:dt,handler:ut,reentryError:()=>M(t,n)},e,!0)}var SyncLockAcquisition=class{lockPath;normalizedTargetPath;retry;timeoutMs;#e=getSyncLockAdmissions();#t={};#n=!1;#r=performance.now();#i=0;#a=0;constructor(e,t,n,r){this.lockPath=e,this.normalizedTargetPath=t,this.retry=n,this.timeoutMs=r}get owns(){return this.#n}hasToken(){return this.#e.get(this.normalizedTargetPath)===this.#t}assert(){if(!this.hasToken())throw M(this.lockPath,this.normalizedTargetPath)}reserve(){if(!this.#n){if(this.#e.has(this.normalizedTargetPath))throw M(this.lockPath,this.normalizedTargetPath);this.#e.set(this.normalizedTargetPath,this.#t),this.#n=!0}}release(){this.#n&&this.hasToken()&&this.#e.delete(this.normalizedTargetPath),this.#n=!1}run(e){this.assert();try{return e()}finally{this.assert()}}waitForRetry(){this.release();let e=pe(this.retry,this.timeoutMs,performance.now()-this.#r,this.#i);if(e===void 0)throw M(this.lockPath,this.normalizedTargetPath);_(e),this.#i+=1}retryDenial(e){if(!_e(e,this.lockPath)||++this.#a>8)return!1;try{this.waitForRetry()}catch(t){throw t?.code===`file_lock_timeout`?e:t}return!0}monitor(e,t,n,r,i,a){if(!n||(r??0)<=0)return;let{lockPath:o,normalizedTargetPath:s}=this,c=setInterval(()=>{let r;try{r=t.verifyStillHeld()}catch{r=!1}!r&&e.timer&&(clearInterval(e.timer),e.timer=void 0,Reflect.apply(n,i,[{lockPath:o,normalizedTargetPath:s}]))},r);a?.(c),e.timer=c,c.unref()}};function observeDirectory(e,t){let n=O(e,void 0,t),r=E.native(C(e));if(T(r,`filesystem`,`sidecar lock parent uses a Windows filesystem namespace alias`),!Se(r,e))throw new D(`path-mismatch`,`sidecar lock parent changed during operation`);return Object.freeze({identity:Object.freeze({dev:n.dev,ino:n.ino}),path:e,realPath:r})}function assertDirectoryCurrent(e,t){O(e.path,e.identity,t);let n=E.native(C(e.path));if(T(n,`filesystem`,`sidecar lock parent uses a Windows filesystem namespace alias`),n!==e.realPath)throw new D(`path-mismatch`,`sidecar lock parent changed during operation`)}function assertRetainedParentCurrent(e,t){let n=e.authority.context,r=t.path===n.rootReal&&t.identity.dev===n.rootIdentity.dev&&t.identity.ino===n.rootIdentity.ino,i;F(n,r?e=>{i=e}:void 0),assertDirectoryCurrent(t,i),F(n)}function exactFileIdentity(e){return Object.freeze({dev:e.dev,ino:e.ino})}function assertRegularFile(e,t){if(e.isSymbolicLink()||!e.isFile())throw new D(`not-file`,`sidecar lock is not a regular file`);if(t!==`allow`&&e.nlink>1n)throw te()}function sameExactIdentity(e,t){return e.dev===t.dev&&e.ino===t.ino}function assertFreshPathCurrent(e){I(e),F(e.authority.context)}function missingAfterCurrentRead(e,t){return t?assertRetainedParentCurrent(e,t.parent):assertFreshPathCurrent(e),null}function readFileLockSyncRootSnapshot(e,t={}){let n=t.expectedReceipt;n?assertRetainedParentCurrent(e,n.parent):assertFreshPathCurrent(e);let r;try{r=g(()=>H.lstatSync(C(e.path),{bigint:!0}),n?.identity)}catch(t){if(b(t)||n&&t instanceof D&&t.code===`path-mismatch`)return missingAfterCurrentRead(e,n);throw t}assertRegularFile(r,e.authority.hardlinks);let i=n?.parent??observeDirectory(W.dirname(e.path)),a,o,s=!1;try{try{a=H.openSync(C(e.path),ee())}catch(r){if(b(r))return missingAfterCurrentRead(e,n);throw t.onOpenFailure?.(r),r}let o;try{o=g(()=>H.fstatSync(a,{bigint:!0}),exactFileIdentity(r))}catch(t){if(t instanceof D&&t.code===`path-mismatch`)return n?assertRetainedParentCurrent(e,i):(assertDirectoryCurrent(i),assertFreshPathCurrent(e)),null;throw t}assertRegularFile(o,e.authority.hardlinks);let s=ne(a,1048576).toString(`utf8`),c;try{c=g(()=>H.lstatSync(C(e.path),{bigint:!0}),exactFileIdentity(o))}catch(t){if(b(t)||t instanceof D&&t.code===`path-mismatch`)return n?assertRetainedParentCurrent(e,i):(assertDirectoryCurrent(i),assertFreshPathCurrent(e)),null;throw t}assertRegularFile(c,e.authority.hardlinks);let l=H.fstatSync(a,{bigint:!0});n?assertRetainedParentCurrent(e,i):(assertDirectoryCurrent(i),assertFreshPathCurrent(e));let u={raw:s,payload:null,stat:l};return Object.freeze({receipt:Object.freeze({identity:exactFileIdentity(o),parent:i}),snapshot:u})}catch(e){throw s=!0,o=e,e}finally{if(a!==void 0)try{H.closeSync(a)}catch(e){throw s?j(e,o,`sidecar snapshot admission and descriptor close both failed`):e}}}function fileLockSyncRootSnapshotStillCurrent(e,t){let n=readFileLockSyncRootSnapshot(e,{expectedReceipt:t.receipt});return!!n&&sameExactIdentity(n.receipt.identity,t.receipt.identity)&&P(n.snapshot,t.snapshot)}function fileReceiptCurrentAfterParentCheck(e,t){let n;try{n=g(()=>H.lstatSync(C(e.path),{bigint:!0}),t.identity)}catch(e){if(b(e)||e instanceof D&&e.code===`path-mismatch`)return!1;throw e}return assertRegularFile(n,e.authority.hardlinks),assertRetainedParentCurrent(e,t.parent),!0}function fileLockSyncRootReceiptStillCurrent(e,t){return assertRetainedParentCurrent(e,t.parent),fileReceiptCurrentAfterParentCheck(e,t)}function ensureParent(e){let t=e.authority,n=t.context;I(e);let r=W.dirname(e.path),i=w({rootPath:n.rootReal,candidatePath:r,rootIdentity:n.rootIdentity});if(!i)throw ie();let a=i.relativePath,o=n.rootReal,s=observeDirectory(o);for(let r of a.split(W.sep).filter(Boolean)){let i=W.join(o,r);F(n),assertDirectoryCurrent(s);let a=!1,c;try{if(c=H.lstatSync(C(i),{bigint:!0}),c.isSymbolicLink()||!c.isDirectory())throw re()}catch(e){if(!b(e))throw e;a=!0}if(a){L(i,t.denyMutations);let r=R(t);r&&I(e),assertDirectoryCurrent(s),F(n),r&&L(i,t.denyMutations);try{H.mkdirSync(C(i))}catch(e){if(e.code!==`EEXIST`)throw e}}let l=observeDirectory(i,c);assertDirectoryCurrent(s),o=l.realPath,s=l}return F(n),assertDirectoryCurrent(s),s}function createFileLockSyncRootFile(e,t){let n=ensureParent(e);R(e.authority)&&(I(e),assertRetainedParentCurrent(e,n));let r=process.platform!==`win32`&&typeof H.constants.O_NOFOLLOW==`number`?H.constants.O_NOFOLLOW:0,i,a;try{t.assertBeforeOpen();try{x(C(e.path))}catch(e){throw e.code===`EEXIST`&&t.onOpenFailure(e),e}try{i=H.openSync(C(e.path),H.constants.O_WRONLY|H.constants.O_CREAT|H.constants.O_EXCL|r,384)}catch(e){throw t.onOpenFailure(e),e}let o=g(()=>H.fstatSync(i,{bigint:!0}));if(assertRegularFile(o,e.authority.hardlinks),a=Object.freeze({identity:exactFileIdentity(o),parent:n}),!fileReceiptCurrentAfterParentCheck(e,a))throw new D(`path-mismatch`,`created sidecar lock changed before admission`);return{fd:i,receipt:a}}catch(t){if(i===void 0)throw t;let n=i;i=void 0;try{if(H.closeSync(n),a&&!removeFileLockSyncRootFile(e,a))throw new D(`path-mismatch`,`created sidecar lock changed before cleanup`)}catch(e){throw j(t,e,`file lock create admission and cleanup both failed`)}throw t}}function refreshFileLockSyncRootFileReceipt(e,t){if(!fileReceiptCurrentAfterParentCheck(e,t))throw new D(`path-mismatch`,`created sidecar lock changed before admission`);return t}function removeFileLockSyncRootFile(e,t,n,r){L(e.path,e.authority.denyMutations);let matches=()=>{if(!n)return fileLockSyncRootReceiptStillCurrent(e,t);let r=readFileLockSyncRootSnapshot(e,{expectedReceipt:t});return!!r&&sameExactIdentity(r.receipt.identity,t.identity)&&P(r.snapshot,n)};if(!matches()||R(e.authority)&&!matches()||r?.()===!1)return!1;L(e.path,e.authority.denyMutations),H.unlinkSync(C(e.path)),assertRetainedParentCurrent(e,t.parent);let i;try{i=g(()=>H.lstatSync(C(e.path),{bigint:!0}))}catch(e){if(b(e))return!0;throw e}if(assertRegularFile(i,e.authority.hardlinks),assertRetainedParentCurrent(e,t.parent),!sameExactIdentity(exactFileIdentity(i),t.identity))return!0;if(n){let r=readFileLockSyncRootSnapshot(e);if(assertRetainedParentCurrent(e,t.parent),r){if(!sameExactIdentity(r.receipt.identity,t.identity)||!P(r.snapshot,n))return!0}else{let n;try{n=g(()=>H.lstatSync(C(e.path),{bigint:!0}))}catch(n){if(b(n))return assertRetainedParentCurrent(e,t.parent),!0;throw n}if(assertRegularFile(n,e.authority.hardlinks),assertRetainedParentCurrent(e,t.parent),!sameExactIdentity(exactFileIdentity(n),t.identity))return!0}}throw new D(`path-mismatch`,`sidecar lock was replaced during removal`)}function fileLockSyncRootGuardExists(e){F(e.authority.context);let t;try{t=H.lstatSync(C(e.path),{bigint:!0})}catch(t){if(b(t))return I(e),F(e.authority.context),!1;throw t}if(t.isSymbolicLink()||!t.isDirectory()&&!t.isFile())throw re();t.isFile()&&assertRegularFile(t,e.authority.hardlinks);let n=observeDirectory(W.dirname(e.path));return t.isFile()?assertRegularFile(g(()=>H.lstatSync(C(e.path),{bigint:!0}),exactFileIdentity(t)),e.authority.hardlinks):O(e.path,exactFileIdentity(t)),assertDirectoryCurrent(n),I(e),F(e.authority.context),!0}function createFileLockSyncRootDirectory(e){let t=ensureParent(e);R(e.authority)&&(I(e),assertRetainedParentCurrent(e,t));try{H.mkdirSync(C(e.path))}catch(e){if(e.code===`EEXIST`)return null;throw e}let n=O(e.path),r=Object.freeze({identity:exactFileIdentity(n),parent:t});return assertRetainedParentCurrent(e,t),O(e.path,r.identity),r}function removeFileLockSyncRootDirectory(e,t){return!fileLockSyncRootDirectoryReceiptStillCurrent(e,t)||(L(e.path,e.authority.denyMutations,!0),R(e.authority)&&!fileLockSyncRootDirectoryReceiptStillCurrent(e,t))?!1:(L(e.path,e.authority.denyMutations,!0),H.rmdirSync(C(e.path)),assertRetainedParentCurrent(e,t.parent),!0)}function fileLockSyncRootDirectoryReceiptStillCurrent(e,t){assertRetainedParentCurrent(e,t.parent);try{O(e.path,t.identity)}catch(e){if(b(e)||e instanceof D&&e.code===`path-mismatch`)return!1;throw e}return assertRetainedParentCurrent(e,t.parent),!0}const q=Symbol.for(`fsSafe.syncRootSidecarLockCleanupRegistering.v1`),pt=Symbol.for(`fsSafe.syncRootSidecarLockCleanupRegistered.v1`),J=Symbol.for(`fsSafe.syncRootSidecarLockCleanupRegistrationFailed.v1`),Y=Symbol.for(`fsSafe.syncRootSidecarLockCleanupHandler.v1`);function unavailable(e){return new D(`helper-unavailable`,e)}function exactListenerCount(e){return process.listeners(`exit`).filter(t=>t===e).length}function ensureFileLockSyncRootExitCleanupRegistered(e){let t=globalThis;if(t[pt]){if(typeof t[Y]==`function`)return;throw t[J]=!0,unavailable(`Root sidecar exit cleanup registration state is inconsistent`)}if(t[J])throw unavailable(`Root sidecar exit cleanup registration previously failed`);if(t[q])throw unavailable(`Root sidecar exit cleanup registration is already in progress`);if(t[Y]!==void 0)throw t[J]=!0,unavailable(`Root sidecar exit cleanup handler exists without registration`);t[q]=!0;let n,r=!1,i=!1;try{if(n=exactListenerCount(e),n!==0)throw i=!0,unavailable(`Root sidecar exit cleanup listener exists without registration`);if(r=!0,process.on(`exit`,e),exactListenerCount(e)!==n+1)throw unavailable(`Root sidecar exit cleanup listener was not registered exactly once`);t[Y]=e,t[pt]=!0,t[J]=!1,t[q]=!1}catch(a){let o=!1,s;if(r&&n!==void 0)try{let t=exactListenerCount(e);for(;t>n;){process.removeListener(`exit`,e);let n=exactListenerCount(e);if(n>=t)throw unavailable(`Root sidecar exit cleanup listener rollback made no progress`);t=n}if(t!==n)throw unavailable(`Root sidecar exit cleanup listener rollback was ambiguous`)}catch(e){o=!0,s=e}throw t[Y]=void 0,t[pt]=!1,t[q]=!1,i?(t[J]=!0,a):o?(t[J]=!0,j(a,s,`Root sidecar exit cleanup registration and rollback both failed`)):(t[J]=!1,a)}}const X=Symbol.for(`fsSafe.syncRootSidecarLocks.v1`),mt=Symbol.for(`fsSafe.syncRootSidecarLockCleanupActive.v1`),ht=/* @__PURE__ */ new WeakMap;function readRootSyncHeldReleaseState(e){return e.releaseState}function readRootSidecarSnapshotSync(e,t,n,r){let i=readFileLockSyncRootSnapshot(e,{expectedReceipt:r,onOpenFailure:n});if(!i)return null;let a;try{a=ue(i.snapshot.raw,t)}catch(n){if(t)try{if(!fileLockSyncRootSnapshotStillCurrent(e,i))throw new D(`path-mismatch`,`sidecar changed during payload parsing`)}catch(e){throw j(n,e,`sidecar parser and post-callback admission both failed`)}throw n}return t&&!fileLockSyncRootSnapshotStillCurrent(e,i)?null:{receipt:i.receipt,snapshot:{...i.snapshot,payload:a}}}function getRootSyncHeldLocks(){let e=globalThis;return e[X]||(e[X]=/* @__PURE__ */ new Map),e[X]}function reactivateExactHeldLock(e,t,n){return e.get(t.normalizedTargetPath)!==t||t.releaseState===`released`?!1:(n&&(t.refCount+=1),t.releaseState=`active`,t.revision+=1,!0)}function finishDeferredExitReleases(e){let t=e.deferredExitReleases;if(t){for(let e of t)e.released=!0;t.clear(),e.deferredExitReleases=void 0}}function restoreDeferredExitReleases(e){let t=e.deferredExitReleases;if(!t)return 0;let n=t.size;return t.clear(),e.deferredExitReleases=void 0,n}function restoreExactHeldLockAfterExitCleanup(e,t){e.get(t.normalizedTargetPath)===t&&t.releaseState!==`released`&&(t.refCount+=restoreDeferredExitReleases(t),t.refCount<=0?(t.releaseState=`released`,t.revision+=1,e.delete(t.normalizedTargetPath)):(t.releaseState=`active`,t.revision+=1))}function releaseAllRootSyncHeldLocks(){let e=globalThis;if(!e[mt]){e[mt]=!0;try{let e=globalThis[X];if(!e)return;getSyncLockAdmissions().clear();for(let[t,n]of e){if(e.get(t)!==n||n.releaseState!==`active`)continue;n.releaseState=`exit-cleaning`,n.revision+=1;let r=n.revision,i=n.timer,a=n.fd;n.timer=void 0,n.fd=void 0,i&&clearInterval(i);try{a!==void 0&&H.closeSync(a)}catch{}let entryIsContinuous=()=>e.get(t)===n&&n.releaseState===`exit-cleaning`&&n.revision===r,beginFreshCleanupAttempt=()=>{n.releaseState=`exit-cleaning`,n.revision+=1,r=n.revision};if(!entryIsContinuous()){if(e.get(t)===n&&readRootSyncHeldReleaseState(n)!==`released`&&n.refCount===0)beginFreshCleanupAttempt();else{restoreExactHeldLockAfterExitCleanup(e,n);continue}}let o=!1;for(let r=0;r<2;r+=1){let i=!1,a=!1,s=!1;try{s=removeFileLockSyncRootFile(n.rootPath,n.rootReceipt,n.snapshot,()=>{let e=entryIsContinuous();return e||(i=!0),e})}catch{a=!0}if(!a&&s&&!i&&entryIsContinuous()){o=!0;break}let c=entryIsContinuous();if(e.get(t)===n&&readRootSyncHeldReleaseState(n)!==`released`&&(i||!c)&&n.refCount===0&&r+1<2)beginFreshCleanupAttempt();else{if(c&&n.refCount>0){o=!0;break}restoreExactHeldLockAfterExitCleanup(e,n);break}}o&&(finishDeferredExitReleases(n),n.releaseState=`released`,n.revision+=1,e.get(t)===n&&e.delete(t))}}finally{e[mt]=!1}}}function ensureRootSyncExitCleanupRegistered(){ensureFileLockSyncRootExitCleanupRegistered(releaseAllRootSyncHeldLocks)}function verifyRootSyncHeldLock(e){let t=e.rootPath,n=e.parsePayload,r=e.rootReceipt,i=n?readRootSidecarSnapshotSync(t,n,void 0,r):readFileLockSyncRootSnapshot(t,{expectedReceipt:r});return i?i.receipt.identity.dev===e.rootReceipt.identity.dev&&i.receipt.identity.ino===e.rootReceipt.identity.ino&&P(i.snapshot,e.snapshot):!1}function releaseRootSyncHeldLock(e,t){let n=getRootSyncHeldLocks();if(n.get(e.normalizedTargetPath)!==e||e.releaseState===`released`)return!0;if(e.releaseState!==`active`){if(e.deferredExitReleases?.has(t)||e.refCount<=0)return!1;if(!fileLockSyncRootReceiptStillCurrent(e.rootPath,e.rootReceipt))throw new D(`path-mismatch`,`held sidecar lock changed before release`);return--e.refCount,e.revision+=1,e.releaseState!==`exit-cleaning`||e.refCount>0||((e.deferredExitReleases??=/* @__PURE__ */ new Set).add(t),!1)}if(e.refCount>1){if(!fileLockSyncRootReceiptStillCurrent(e.rootPath,e.rootReceipt))throw new D(`path-mismatch`,`held sidecar lock changed before release`);return--e.refCount,e.revision+=1,!0}if(e.refCount!==1)return!1;e.refCount=0,e.releaseState=`releasing`,e.revision+=1;let r=e.revision,entryIsContinuous=()=>n.get(e.normalizedTargetPath)===e&&e.releaseState===`releasing`&&e.revision===r&&e.refCount===0,beginFreshReleaseAttempt=()=>{e.releaseState=`releasing`,e.revision+=1,r=e.revision},i=e.fd;e.fd=void 0;try{i!==void 0&&H.closeSync(i)}catch(t){throw reactivateExactHeldLock(n,e,!0),t}if(!entryIsContinuous()){if(n.get(e.normalizedTargetPath)!==e||readRootSyncHeldReleaseState(e)===`released`)return!0;if(e.refCount>0)return reactivateExactHeldLock(n,e,!1),!0;beginFreshReleaseAttempt()}for(let t=0;t<2;t+=1){let r=!1,i;try{i=removeFileLockSyncRootFile(e.rootPath,e.rootReceipt,e.snapshot,()=>{let e=entryIsContinuous();return e||(r=!0),e})}catch(t){throw reactivateExactHeldLock(n,e,!0),t}if(!r&&entryIsContinuous()){if(!i)throw reactivateExactHeldLock(n,e,!0),new D(`path-mismatch`,`owned sidecar lock changed before release`);let t=e.timer;return e.timer=void 0,e.releaseState=`released`,e.revision+=1,n.get(e.normalizedTargetPath)===e&&n.delete(e.normalizedTargetPath),t&&clearInterval(t),!0}if(n.get(e.normalizedTargetPath)!==e||readRootSyncHeldReleaseState(e)===`released`)return!0;if(e.refCount>0)return reactivateExactHeldLock(n,e,!1),!0;if(e.refCount===0&&t+1<2)beginFreshReleaseAttempt();else throw reactivateExactHeldLock(n,e,!0),new D(`path-mismatch`,`held sidecar release continuity changed repeatedly`)}throw new D(`path-mismatch`,`held sidecar release could not complete`)}function createRootSyncHeldLockHandle(e){let t={held:e,released:!1},n=!1,release=()=>{if(!(t.released||n)){n=!0;try{releaseRootSyncHeldLock(e,t)&&(t.released=!0)}finally{n=!1}}},r={lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,verifyStillHeld:()=>verifyRootSyncHeldLock(e),release,[Symbol.dispose]:release};return ht.set(r,t),r}var FileLockSyncRootArbitrationCollision=class extends D{constructor(){super(`path-mismatch`,`file lock arbitration changed during local creation`)}};function cleanupCreatedRootSyncLock(e,t,n,r){let i=!1,a;try{r&&clearInterval(r)}catch(e){i=!0,a=e}try{if(H.closeSync(t),!removeFileLockSyncRootFile(e,n))throw new D(`path-mismatch`,`created sidecar lock changed before cleanup`)}catch(e){throw i?j(a,e,`unpublished lock timer and file cleanup both failed`):e}if(i)throw a}function acquireFileLockSyncWithRoot(e,t,n){let r=xe(n),i=captureRootSyncAcquireOptions(t);ensureRootSyncExitCleanupRegistered(),T(e),i.lockPath!==void 0&&T(i.lockPath);let a=W.resolve(e),o=we(r,a),s=W.resolve(i.lockPath??`${o}.lock`),c=Te(r,s),l=Te(r,`${c.path}.reclaim`),u=Object.freeze([c,l]),d=c.path,f=getRootSyncHeldLocks(),currentTargetHolder=()=>f.get(o)??foreignSyncHeldLock(`root`,o),tryReuseCurrentHeld=()=>{let e=f.get(o);if(e&&!foreignSyncHeldLock(`root`,o)&&i.reentrantOwner!==void 0&&e.reentrantOwner!==void 0&&i.reentrantOwner===e.reentrantOwner&&r.adapter===e.rootAuthority.adapter&&c.relativePath===e.rootPath.relativePath&&W.relative(c.path,e.rootPath.path)===``&&e.releaseState!==`released`){if(!verifyRootSyncHeldLock(e))throw new D(`path-mismatch`,`held sidecar lock changed before reentrant reuse`);if(f.get(o)!==e||e.releaseState===`released`||foreignSyncHeldLock(`root`,o))throw new D(`path-mismatch`,`held sidecar lock changed during reentrant reuse`);return e.refCount+=1,e.revision+=1,createRootSyncHeldLockHandle(e)}};if(f.has(o)&&!foreignSyncHeldLock(`root`,o)){Ce(u);let e=tryReuseCurrentHeld();if(e)return e}let p=new SyncLockAcquisition(d,o,i.retry,i.timeoutMs),m,h=!1,reuseCurrentHeld=()=>m?void 0:tryReuseCurrentHeld(),releaseReclaimGuard=()=>{let e=m;if(e){if(h=!0,!removeFileLockSyncRootDirectory(l,e))throw new D(`path-mismatch`,`owned sidecar reclaim guard changed before release`);m=void 0,h=!1}},assertOwnedReclaimGuardCurrent=()=>{let e=m;if(!e||!fileLockSyncRootDirectoryReceiptStillCurrent(l,e))throw new D(`path-mismatch`,`owned sidecar reclaim guard changed during acquisition`)};try{for(;;){if(p.reserve(),p.assert(),Ce(u),p.assert(),m&&assertOwnedReclaimGuardCurrent(),!m&&fileLockSyncRootGuardExists(l)){p.waitForRetry();continue}if(currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e}let e=Reflect.apply(i.payload,i.optionsReceiver,[]);p.assert();let{raw:t,ownershipToken:n}=ce(e);if(p.assert(),m&&assertOwnedReclaimGuardCurrent(),currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e;p.waitForRetry();continue}let a,s,g,_;try{let l=createFileLockSyncRootFile(c,{assertBeforeOpen:()=>{if(p.assert(),m&&assertOwnedReclaimGuardCurrent(),currentTargetHolder()!==void 0)throw new FileLockSyncRootArbitrationCollision},onOpenFailure:e=>{_={error:e}}});a=l.fd,s=l.receipt,H.writeFileSync(a,t,`utf8`),H.fsyncSync(a);let u={raw:t,payload:e,ownershipToken:n};m&&releaseReclaimGuard(),s=refreshFileLockSyncRootFileReceipt(c,s);let h={fd:a,lockPath:d,normalizedTargetPath:o,parsePayload:i.parsePayload,refCount:1,reentrantOwner:i.reentrantOwner,releaseState:`active`,revision:0,rootAuthority:r,rootPath:c,rootReceipt:s,snapshot:u},v=createRootSyncHeldLockHandle(h);if(p.monitor(h,v,i.onCompromised,i.compromiseCheckIntervalMs,i.optionsReceiver,e=>{g=e}),currentTargetHolder()!==void 0)throw new FileLockSyncRootArbitrationCollision;return p.assert(),f.set(o,h),a=void 0,g=void 0,v}catch(e){if(a!==void 0&&s){let t=a,n=s,r=g;a=void 0,s=void 0,g=void 0;try{cleanupCreatedRootSyncLock(c,t,n,r)}catch(t){throw j(e,t,`file lock acquisition and Root cleanup both failed`)}}if(e instanceof FileLockSyncRootArbitrationCollision){let e=reuseCurrentHeld();if(e)return e;p.waitForRetry();continue}let t=_!==void 0&&_.error===e;if(t&&p.retryDenial(e))continue;if(!t||e.code!==`EEXIST`)throw e;if(m){releaseReclaimGuard();let e=reuseCurrentHeld();if(e)return e;p.waitForRetry();continue}if(currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e;p.waitForRetry();continue}let n=!1,r;try{r=readRootSidecarSnapshotSync(c,i.parsePayload,e=>{n=_e(e,d)})}catch(e){if(n&&p.retryDenial(e))continue;throw e}if(currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e;p.waitForRetry();continue}if(p.assert(),!r){p.waitForRetry();continue}let u=r.snapshot,f=Date.now(),v;if(i.shouldReclaim){if(v=Reflect.apply(i.shouldReclaim,i.optionsReceiver,[{lockPath:d,normalizedTargetPath:o,payload:u.payload,staleMs:i.staleMs,nowMs:f,heldByThisProcess:!1}]),k(v,`shouldReclaim`),p.assert(),!fileLockSyncRootSnapshotStillCurrent(c,r))throw new D(`path-mismatch`,`sidecar changed during reclaim policy callback`)}else v=ge(u,i.staleMs,f);if(v){if(i.staleRecovery===`remove-if-unchanged`&&u.raw!==void 0&&i.shouldRemoveStaleLock){let e=createFileLockSyncRootDirectory(l);if(!e){p.waitForRetry();continue}m=e,h=!1;let t=Reflect.apply(i.shouldRemoveStaleLock,i.optionsReceiver,[{lockPath:d,normalizedTargetPath:o,raw:u.raw,payload:u.payload}]);if(k(t,`shouldRemoveStaleLock`),p.assert(),assertOwnedReclaimGuardCurrent(),t){if(!removeFileLockSyncRootFile(c,r.receipt,u,()=>{if(p.assert(),assertOwnedReclaimGuardCurrent(),currentTargetHolder()!==void 0)throw new FileLockSyncRootArbitrationCollision}))throw new D(`path-mismatch`,`stale sidecar changed before removal`);continue}if(!fileLockSyncRootSnapshotStillCurrent(c,r))throw new D(`path-mismatch`,`sidecar changed during stale-removal policy callback`);releaseReclaimGuard()}throw A(d,o)}p.waitForRetry()}}}catch(e){if(m&&!h)try{releaseReclaimGuard()}catch(t){throw j(e,t,`file lock acquisition and reclaim cleanup both failed`)}throw e}finally{p.release()}}function handleSyncStaleAdmission(e,t){let n={},assertUnheld=()=>{if(e.assert(),t.currentHeld())throw n},retryHolderChange=t=>t===n&&(e.waitForRetry(),!0),r,i=!1;try{r=he(e.lockPath,{rejectNonFile:!0,onOpenFailure:()=>{i=!0,assertUnheld()}}),assertUnheld()}catch(t){if(retryHolderChange(t))return;try{assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}if(i&&e.retryDenial(t))return;throw t}let a=t.staleOptions;try{a.shouldReclaimObserved||(assertUnheld(),a.shouldReclaim=t.options.shouldReclaim,a.shouldReclaimObserved=!0,assertUnheld()),a.shouldRemoveObserved||(assertUnheld(),a.shouldRemove=t.options.shouldRemoveStaleLock,a.shouldRemoveObserved=!0,assertUnheld())}catch(e){if(retryHolderChange(e))return;try{assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}throw e}let o=t.parsePayload&&(e=>{assertUnheld();try{return Reflect.apply(t.parsePayload,void 0,[e])}finally{assertUnheld()}}),s;try{s=de(r,o),assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}if(!s){e.waitForRetry();return}let c=Date.now(),l;try{assertUnheld();try{l=a.shouldReclaim?Reflect.apply(a.shouldReclaim,t.options,[{lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,payload:s.payload,staleMs:t.staleMs,nowMs:c,heldByThisProcess:!1}]):ge(s,t.staleMs,c),k(l,`shouldReclaim`)}finally{assertUnheld()}}catch(e){if(retryHolderChange(e))return;throw e}if(!l)e.waitForRetry();else{if(t.staleRecovery===`remove-if-unchanged`&&s.raw!==void 0&&a.shouldRemove!==void 0){let r;try{assertUnheld();try{r=Reflect.apply(a.shouldRemove,t.options,[{lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,raw:s.raw,payload:s.payload}]),k(r,`shouldRemoveStaleLock`)}finally{assertUnheld()}}catch(e){if(retryHolderChange(e))return;throw e}if(!r)throw A(e.lockPath,e.normalizedTargetPath);try{H.mkdirSync(t.reclaimGuardPath)}catch(t){try{assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}if(t.code===`EEXIST`){e.waitForRetry();return}throw t}let i=!1;try{if(assertUnheld(),N(e.lockPath,s,assertUnheld))return}catch(e){if(e===n)i=!0;else throw e}finally{try{H.rmdirSync(t.reclaimGuardPath)}catch{}}if(i){e.waitForRetry();return}}throw A(e.lockPath,e.normalizedTargetPath)}}function releaseAllSyncHeldLocks(){let e=getSyncHeldLocks();for(let[t,n]of e){n.timer&&=(clearInterval(n.timer),void 0);try{n.fd!==void 0&&H.closeSync(n.fd)}catch{}try{N(n.lockPath,n.snapshot)}catch{}e.delete(t)}getSyncLockAdmissions().clear()}function verifySyncHeldLock(e){let t=e.lockPath,n=e.parsePayload,r=n?fe(t,n):he(t);return!!r&&P(r,e.snapshot)}function releaseSyncHeldLock(e){let t=getSyncHeldLocks();if(t.get(e.normalizedTargetPath)!==e)return!1;if(e.refCount>1)return--e.refCount,!1;if(e.timer&&=(clearInterval(e.timer),void 0),e.fd!==void 0){let t=e.fd;e.fd=void 0,H.closeSync(t)}return N(e.lockPath,e.snapshot),t.delete(e.normalizedTargetPath),!0}function createSyncHeldLockHandle(e){let t=!1,release=()=>{t||=(releaseSyncHeldLock(e),!0)};return{lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,verifyStillHeld:()=>verifySyncHeldLock(e),release,[Symbol.dispose]:release}}function canonicalLockParentSync(e){return process.platform===`win32`?E.native(e):E(e)}function normalizeTargetPath(e){let t=W.resolve(e);T(t);let n=W.dirname(t),r=!1;try{r=H.statSync(n).isDirectory()}catch{}r||H.mkdirSync(y(n),{recursive:!0});let i;try{i=canonicalLockParentSync(W.dirname(t))}catch{return t}T(i);let a=W.join(i,W.basename(t));return T(a),a}function acquireFileLockSync(e,t){let n=t.lockRoot;if(n)return acquireFileLockSyncWithRoot(e,t,n);let r=Ee(),i=t.retry??r.retry??{},a=t.timeoutMs??r.timeoutMs;le(i),be(a);let o=t.staleMs??r.staleMs??3e4;me(o);let s=t.compromiseCheckIntervalMs;ve(s);let c=t.lockPath;T(e),c!==void 0&&T(c);let l=normalizeTargetPath(e),u=W.resolve(c??`${l}.lock`);T(u);let d=t.reentrantOwner,f=getSyncHeldLocks(),currentTargetHolder=()=>f.get(l)??foreignSyncHeldLock(`raw`,l),p=f.get(l);if(p&&!foreignSyncHeldLock(`raw`,l)&&d!==void 0&&p.reentrantOwner!==void 0&&d===p.reentrantOwner)return p.refCount+=1,createSyncHeldLockHandle(p);let m=new SyncLockAcquisition(u,l,i,a),h,g,_=!1,v,y=!1,b,S=!1,C={},w=`${u}.reclaim`;try{for(;;){if(!m.owns){let e=f.get(l);if(e&&!foreignSyncHeldLock(`raw`,l)&&d!==void 0&&e.reentrantOwner!==void 0&&d===e.reentrantOwner)return e.refCount+=1,createSyncHeldLockHandle(e);m.reserve()}let e=currentTargetHolder(),holderWasReplaced=()=>{let t=currentTargetHolder();return t!==void 0&&t!==e};if(!S&&(b=m.run(()=>t.staleRecovery??r.staleRecovery),S=!0,holderWasReplaced())){m.waitForRetry();continue}let n=syncReclaimGuardExists(w);if(!m.hasToken())throw M(u,l);if(holderWasReplaced()||n){m.waitForRetry();continue}let i,a,c;if(h||=m.run(()=>t.payload),holderWasReplaced()){m.waitForRetry();continue}let p=m.run(()=>Reflect.apply(h,t,[]));if(holderWasReplaced()){m.waitForRetry();continue}let{raw:T,ownershipToken:ee}=m.run(()=>ce(p));if(holderWasReplaced()||currentTargetHolder()!==void 0||!_&&(g=m.run(()=>t.onCompromised),_=!0,currentTargetHolder()!==void 0)||!y&&(v=m.run(()=>t.parsePayload),y=!0,currentTargetHolder()!==void 0)){m.waitForRetry();continue}let E=!1,D=!1;try{let e=process.platform!==`win32`&&typeof H.constants.O_NOFOLLOW==`number`?H.constants.O_NOFOLLOW:0;try{x(u)}catch(e){throw D=e.code===`EEXIST`,e}try{i=H.openSync(u,H.constants.O_WRONLY|H.constants.O_CREAT|H.constants.O_EXCL|e,384)}catch(e){throw E=_e(e,u),D=e.code===`EEXIST`,e}H.writeFileSync(i,T,`utf8`),H.fsyncSync(i),c={raw:T,payload:p,stat:H.fstatSync(i,{bigint:!0}),ownershipToken:ee},a={fd:i,lockPath:u,normalizedTargetPath:l,parsePayload:v,refCount:1,reentrantOwner:d,snapshot:c};let n=a;if(ensureSyncLockExitCleanupRegistered(releaseAllSyncHeldLocks,u,l),!m.hasToken()||currentTargetHolder()!==void 0)throw M(u,l);let r=createSyncHeldLockHandle(n);if(m.monitor(n,r,g,s,t),!m.hasToken()||currentTargetHolder()!==void 0)throw M(u,l);return f.set(l,n),m.release(),i=void 0,r}catch(e){if(a?.timer&&(clearInterval(a.timer),a.timer=void 0),a&&f.get(l)===a&&f.delete(l),i!==void 0){let t=c??{payload:null};if(!t.stat)try{t.stat=H.fstatSync(i,{bigint:!0})}catch{}let n=i;i=void 0,a&&(a.fd=void 0);try{H.closeSync(n),t.stat&&N(u,t)}catch(t){throw j(e,t,`file lock acquisition and cleanup both failed`)}}if(E){if(!m.hasToken())throw M(u,l);if(currentTargetHolder()!==void 0){m.waitForRetry();continue}if(m.retryDenial(e))continue;throw e}if(!D)throw e;if(!m.hasToken())throw M(u,l);if(currentTargetHolder()!==void 0){m.waitForRetry();continue}handleSyncStaleAdmission(m,{currentHeld:currentTargetHolder,options:t,parsePayload:v,reclaimGuardPath:w,staleMs:o,staleOptions:C,staleRecovery:b});continue}}}finally{m.release()}}const gt=Date.now.bind(Date);function captureLock(e){let t=H.readFileSync(e.lockPath,`utf8`);if(!e.verifyStillHeld())throw Error(`OpenClaw state ownership is no longer current`);return t}function startGatewayStateOwnerHeartbeat(e,t){let n={};for(let t of e)n[t.lockPath]=captureLock(t);let r=Object.keys(n)[0];if(!r)throw Error(`Gateway state ownership requires a held lock`);let i=H.statSync(r,{bigint:!0}),{moduleUrl:s,runtimeGeneration:l}=ke(Ke(`gatewayStateOwnerHeartbeat`));return a(()=>{let a=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(a,0,BigInt(gt()));let{port1:u,port2:f}=new nt,m=Je(s,{workerData:{clock:`epoch`,locks:n,intervalMs:Ie,failureMs:6e4,lastBeat:a.buffer,events:f},transferList:[f],execArgv:Ge(s)}),h=se();m.on(`message`,e=>{e===`closed`&&h.resolve()}),m.unref();let g=0,_=/* @__PURE__ */ new Map,rejectPending=e=>{for(let t of _.values())t.reject(e);_.clear(),u.unref()};u.on(`message`,e=>{if(qe(`lifecycle`,`from_worker`),e===`parent-lost`)d();else if(e&&typeof e==`object`&&e.type===`lost`)t(/* @__PURE__ */ Error(`${e.error}; restart the Gateway.`),e.lockPath);else if(e&&typeof e==`object`&&e.type===`verified`){let t=_.get(e.id);_.delete(e.id),_.size===0&&u.unref(),e.error?t?.reject(Error(e.error)):t?.resolve(e.current)}}),u.unref(),m.on(`error`,e=>{let n=/* @__PURE__ */ Error(`${c(e)}; restart Gateway.`);rejectPending(n),t(n)}),m.once(`exit`,()=>{h.resolve(),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership verification worker stopped`))});let v,remainingUntilInspection=()=>{let e=Atomics.load(a,0),t=gt()-Number(e);return t<0?0:6e4-t},inspect=()=>{let e=remainingUntilInspection();if(e<=0)throw Error(`Gateway state ownership renewal is overdue at ${r}; retry after storage recovers.`);return e},renewAsync=async()=>{let t=gt(),o=new Date(t);for(let t of e)try{let a=n[t.lockPath];if(a===void 0)throw Error(`owner acquisition bytes were not registered`);let s=await H.promises.open(t.lockPath,`r+`);try{let n=await s.stat({bigint:!0}),c=await H.promises.lstat(t.lockPath,{bigint:!0}),l=Buffer.alloc(Buffer.byteLength(a)+1),{bytesRead:u}=await s.read(l,0,l.length,0),d=await H.promises.lstat(t.lockPath,{bigint:!0});if(v||!e.has(t))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(n,c,a,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 Error(`owner lock was removed or replaced`)}await s.utimes(o,o)}finally{await s.close()}}catch(e){if(t.lockPath!==r&&S(e,`ENOENT`))continue;throw e}!v&&e.size>0&&Atomics.store(a,0,BigInt(t))},y,b,watch=()=>{let e=remainingUntilInspection();e>0?(y=setTimeout(watch,e),y.unref()):b??=renewAsync().then(()=>{b=void 0,v||watch()},e=>{b=void 0,v||t(/* @__PURE__ */ Error(`Gateway state ownership is no longer current at ${r}: ${c(e)}; restart the Gateway.`))})};watch();let stop=()=>(v||=(clearTimeout(y),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership is no longer current`)),u.close(),m.ref(),m.postMessage(`stop`,[]),(async()=>(await We(h.promise,1e3)||process.emitWarning(`Gateway state-owner heartbeat did not close within ${p}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`}),m.terminate()))()),Promise.all([v,b]).then(()=>void 0));l?.retain(m,async()=>async()=>{await stop()});let assertActive=()=>{if(v||m.threadId===-1)throw Error(`Gateway state ownership verification worker stopped`)},x=new Set(Object.keys(n));return{worker:m,paths:x,register(e){let t=captureLock(e);n[e.lockPath]=t,m.postMessage([e.lockPath,t],[]),x.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();let t=++g;return new Promise((n,r)=>{_.set(t,{resolve:n,reject:r}),u.ref();try{m.postMessage({type:`verify`,id:t,paths:e},[])}catch(e){_.delete(t),_.size===0&&u.unref(),r(o(e,`Gateway state ownership verification failed`))}})},stop}})}function hasPhysicalOwnership(e){try{return verifyOwnerLock(e,e.locks.values().next().value)}catch(t){if(e.lost.signal.aborted)return!1;throw t}}function verifyOwnerLock(e,t){if(e.lost.signal.throwIfAborted(),e.heartbeat?.inspect(),!t)return!1;let n=e.getProjection?.();n&&e.heartbeat&&!e.heartbeat.paths.has(n.lockPath)&&e.heartbeat.register(n);let r=e.payload.role??`gateway`;return e.kind===`process`&&e.accepting&&(r===`gateway`||r===`agent-embedded`)&&e.heartbeat?(e.heartbeat.assertActive(),!0):t.verifyStillHeld()?!0:(loseOwner(e,/* @__PURE__ */ Error(`${t.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`)),!1)}const _t=s(`gateway/state`);function loseOwner(e,t){e.lost.signal.aborted||(e.accepting=!1,Z.clear(),e.heartbeat?.stop(),_t.error(t.message),e.lost.abort(t))}function observeOwnerLoss(e,t,n){let r=[...e.locks,e.getProjection?.()];(!n||r.some(e=>e?.lockPath===n))&&loseOwner(e,t)}const Z=e(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map),Q=e(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map),vt=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]),yt=/* @__PURE__ */ new Set([`--tailscale-reset-on-exit`,`--allow-unconfigured`,`--dev`,`--ambient-channels`,`--dev-ambient-channels`,`--reset`,`--update-canary`,`--force`,`--verbose`,`--cli-backend-logs`,`--claude-cli-logs`,`--compact`,`--raw-stream`]);function isForegroundGatewayRunArgv(e){let t=Ye(e,{commandPath:[`gateway`],booleanFlags:[...yt,`--task-supervisor`],valueFlags:[...vt,`--task-supervisor-child`],mode:`command-path`});return t?t.length===0||t.length===1&&t[0]===`run`:!1}const bt=new ot;function comparableStateOwnerStaleReason(e,t){return t===`dead`?`owner-process-exited`:t===`same`?Fe({payload:{pid:e.pid,starttime:e.startTime}})?.reason:void 0}function isGatewayStateOwnerDefinitelyStale(e,t){let n=u(e)?e:null;if(!n)return!1;let r=Pe(n,t);if(r===`unknown`)throw new Ne(n,t);return comparableStateOwnerStaleReason(n,r)!==void 0}function assertPersistedStateDatabaseAccessAllowed(e){let{databasePath:n,ownerPath:r,assertMaintenance:i}=e,a=`OpenClaw state ownership at ${n} could not be verified from ${r}; restart the Gateway.`,o;try{o=H.readFileSync(r,`utf8`)}catch(e){if(t(e)===`ENOENT`)return;throw new Ue(a,{cause:e})}let s=bt.getStore();if(s?.deadOwner?.path===r&&s.deadOwner.raw===o)return;let c=Me(o);if(!c)throw new z(n,a);if(!Number.isSafeInteger(c.pid)||c.pid<=0)throw new Ue(a);let l=Pe(c,r),u=comparableStateOwnerStaleReason(c,l);if(u){s&&u===`owner-process-exited`&&(s.deadOwner={path:r,raw:o});return}if(l===`same`&&c.pid===process.pid&&!rt)return;if(l===`same`&&!Re(c.pid))throw new z(n,a);let d=c.role??`gateway`;if(d===`gateway`||d===`agent-embedded`)return;if(l===`same`&&c.pid===process.pid){i();return}let f=`OpenClaw state at ${n} is undergoing offline maintenance by ${d} process ${c.pid} (ownerKind=${c.stateOwnerKind??`process`}); retry when it finishes. For update progress, run \`openclaw update status --json\`.`;throw c.stateOwnerKind===`schema`&&c.role===`sqlite-maintenance`?new z(n,f):new He(n,f)}function defaultPayload(e){let t=De(e),n=ze(process.pid),r=f(),i=r===void 0?null:ze(r);return{pid:process.pid,ownerId:at(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:W.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:Le(),machineIdentity:process.platform===`darwin`?m():void 0,...r===void 0?{}:{parentPid:r},...i===null?{}:{parentStartTime:i},...n===null?{}:{startTime:n}}}function assertGatewayRestorationPriority(e,n,r){if(r.role===`gateway`)return;let i;try{i=H.readFileSync(n,`utf8`)}catch(e){if(t(e)===`ENOENT`)return;throw e}let a=Me(i);if(!(isGatewayStateOwnerDefinitelyStale(a,n)||a?.pid===r.pid)&&!(r.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&Xe(process.argv,{command:`gateway`}).kind===`openclaw`))throw new z(e,`Gateway restoration has priority for OpenClaw state at ${e}; retry when it finishes.`)}function acquireGatewayStateOwnerFile(e,n,r,i=0,a){let o=performance.now()+i,s=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;assertGatewayRestorationPriority(e,s,r),ensureOwnerDirectory(W.dirname(n),a);let c={holder:null},stale=({payload:e})=>(c.holder=je.safeParse(e).data??null,isGatewayStateOwnerDefinitelyStale(c.holder,n));if(i>0)try{let t=c.holder=Me(H.readFileSync(n,`utf8`));if(t&&!isGatewayStateOwnerDefinitelyStale(t,n)&&(t.pid===process.pid||(t.role??`gateway`)===`gateway`&&Re(t.pid)))throw new B(e)}catch(e){if(t(e)!==`ENOENT`)throw e}for(let l=!1;;)try{return acquireFileLockSync(n,{lockPath:n,retry:i>0?{factor:1.25,minTimeout:10,maxTimeout:25,randomize:!1}:{retries:0},timeoutMs:Math.max(0,Math.ceil(o-performance.now())),staleMs:1/0,staleRecovery:`remove-if-unchanged`,reentrantOwner:r.ownerId,payload:()=>(assertGatewayRestorationPriority(e,s,r),r),shouldReclaim:stale,shouldRemoveStaleLock:stale})}catch(r){let i=t(r);if(i===`ENOENT`&&!l){l=!0,ensureOwnerDirectory(W.dirname(n),a);continue}if(i===`file_lock_timeout`||i===`file_lock_stale`){let{holder:t}=c,i=Ae(t??{},n,t&&Re(t.pid)?`live`:`unknown`);throw new B(e,r,i,t?{pid:t.pid,role:t.role}:void 0)}throw r}}const xt=e(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new ot);function getStateDatabaseSchemaLease(e){let t=xt.getStore()?.get(resolveStateOwnerIdentity(e).key);if(t&&!t.active)throw Error(`State schema maintenance scope is no longer current`);return t?.lease.assertCurrent(),t?.lease}function withStateDatabaseColdAdmission(e,t){let n=Ze(e.busyTimeoutMs,`busyTimeoutMs`),r=performance.now()+n,a=i(e.databasePath),remainingBusyTimeoutMs=()=>Math.max(0,Math.ceil(r-performance.now())),o=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));for(;;)try{return assertStateDatabaseAccessAllowed(e.databasePath),t(remainingBusyTimeoutMs)}catch(t){if(!(t instanceof z)||i(t.databasePath)!==a||e.canRetry?.()===!1)throw t;let n=r-performance.now();if(n<=0)throw t;Atomics.wait(o,0,0,Math.min(10,n))}}function resolveGatewayStateOwnerPath(e){return resolveStateOwnerIdentity(e).ownerPath}function leaseForFile(e,t,n,r){let i=!1,holdsPhysicalLease=()=>verifyOwnerLock(n,t)&&(!r||r.verifyStillHeld());function run(e){a.assertCurrent(),Z.clear();let t=new Map(xt.getStore()),r={lease:a,active:!0};t.set(n.key,r);let leave=()=>{r.active=!1,Z.clear()};try{let n=xt.run(t,e);return ae(n)?Promise.resolve(n).finally(leave):(leave(),n)}catch(e){throw leave(),e}}let a={path:e,assertCurrent(){if(i||!holdsPhysicalLease())throw Error(`OpenClaw state ownership is no longer current`)},assertDatabaseAccess(e){if(i||Q.get(n.key)!==n||resolveStateOwnerIdentity(e).key!==n.key||!holdsPhysicalLease())throw Error(`OpenClaw state maintenance does not own this database`)},run,release(){Z.clear(),i||(r?.release(),t.release(),i=!0,n.locks.delete(t),r&&n.locks.delete(r),n.locks.size===0&&Q.get(n.key)===n&&(n.heartbeat?.stop(),n.accepting=!1,Q.delete(n.key))),n.locks.size===0&&removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireStateDatabaseSchemaLease(e,t={}){Z.clear();let r=resolveStateOwnerIdentity(e),a=Q.get(r.key),o=a?.path??r.ownerPath;if(a&&(!a.accepting||!hasPhysicalOwnership(a)))throw new B(e,a.lost.signal.reason);a&&assertStateDatabaseAccessAllowed(e);let s=a?.payload??{...defaultPayload(e),stateOwnerKind:`schema`},c,l=[];try{c=acquireGatewayStateOwnerFile(e,o,s,a?0:t.busyTimeoutMs??5e3,l)}catch(t){if(t instanceof B)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof z)throw e}throw t}let u=a?.projectionPath??W.join(n(De(i(e))),`gateway.state.lock`),d;try{d=a?.getProjection?.()?.retain()??acquireGatewayStateOwnerFile(e,u,{...s,role:s.role===`gateway`?`gateway`:`agent-embedded`},0,l)}catch(e){return oe({release(){c.release(),removeCreatedProjectionDirectories(l)}},`state schema projection admission`,()=>{throw e})}a?(a.locks.add(c),a.locks.add(d),a.projectionDirectories.push(...l)):(a={key:r.key,path:o,kind:`schema`,payload:s,projectionPath:u,locks:/* @__PURE__ */ new Set([c,d]),projectionDirectories:l,lost:new AbortController,accepting:!0},Q.set(a.key,a));let f=leaseForFile(o,c,a,d);try{let e=a.heartbeat??=startGatewayStateOwnerHeartbeat(a.locks,(e,t)=>observeOwnerLoss(a,e,t));return f.assertCurrent(),e.register(d),f}catch(e){return oe(f,`state schema ownership verification`,()=>{throw e})}}function captureGatewayStateOwner(e){let t=resolveStateOwnerIdentity(e),{key:n}=t,r=Q.get(n);if(!r||r.kind!==`process`)return;let assertCurrent=(a=e)=>{r.lost.signal.throwIfAborted();let o=i(a),s=process.platform===`win32`?h(o):o;if(Q.get(n)!==r||!r.accepting||s!==n)throw new B(e);assertStateDatabaseAccessAtOwnerPath(e,t,void 0)};return assertCurrent(),{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,!0)}function prepareStateDatabaseReadAccess(e){return captureAdmittedGatewayStateOwner(e,!1)}async function captureAdmittedGatewayStateOwner(e,t){e.assertCurrent();let n=e.identity.canonicalPath,r=process.platform===`win32`?h(n):n,i=Q.get(r);if(!i||i.kind!==`process`)return;let a={canonicalPath:n,key:r,ownerPath:i.path},assertRegistered=()=>{if(e.assertCurrent(),i.lost.signal.throwIfAborted(),Q.get(r)!==i)throw V()},assertCurrent=()=>{if(assertRegistered(),!i.accepting)throw V();assertStateDatabaseAccessAtOwnerPath(n,a,void 0)},o=createStateDatabaseAccess(a,i),assertReadAllowed=e=>{assertRegistered(),o.assertReadAllowed(e)},s=W.resolve(e.databasePath),c=t?assertCurrent:assertRegistered;if(c(),t||Z.get(s)!==i){let t=await l(s);if(c(),(process.platform===`win32`?h(t):t)!==r)throw new B(e.databasePath)}return t||(assertReadAllowed(),Z.get(W.resolve(n))===i&&Z.set(s,i)),{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(Q.size===0){assertStateDatabaseAccessAtOwnerPath(e,n??resolveStateOwnerIdentity(e),t);return}let r=W.resolve(e);if(Z.get(r)?.accepting)return;let i=n??resolveStateOwnerIdentity(e),a=Q.get(i.key),o=a?.payload.role??`gateway`;if(!a||a.kind!==`process`||!a.accepting||o!==`gateway`&&o!==`agent-embedded`)assertStateDatabaseAccessAtOwnerPath(e,i,t);else{if(!hasPhysicalOwnership(a))throw a.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);Z.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){let{canonicalPath:n}=e,r=Q.get(e.key);return{canonicalPath:n,processOwner:r?.kind===`process`?{role:r.payload.role??`gateway`,signal:r.lost.signal,assertCurrent(){if(r.lost.signal.throwIfAborted(),!r.accepting||Q.get(e.key)!==r)throw V()}}:void 0,prepareAccess:async r=>{let i=t??Q.get(e.key),a=i?.payload.role??`gateway`;if(!i||i.kind!==`process`||!i.accepting||a!==`gateway`&&a!==`agent-embedded`)return assertStateDatabaseAccessAtOwnerPath(n,e,r),(t=r)=>{if(i&&Q.get(e.key)!==i)throw V();assertStateDatabaseReadAtOwnerPath(n,t,e)};let o=i.heartbeat,s=i.locks.values().next().value,c=i.getProjection?.();if(!o||!s)throw V();let assertCurrent=(t=r)=>{if(i.lost.signal.throwIfAborted(),o.assertActive(),Q.get(e.key)!==i||i.heartbeat!==o)throw V();if(!i.accepting)assertStateDatabaseAccessAtOwnerPath(n,e,t);else if(!i.locks.has(s)||i.getProjection?.()!==c)throw V()};assertCurrent();let l=[s.lockPath];c&&l.push(c.lockPath);let u=await o.verify(l).catch(e=>{throw i.lost.signal.throwIfAborted(),e});if(assertCurrent(),!u){let e=/* @__PURE__ */ Error(`${s.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`);throw loseOwner(i,e),e}return Z.set(W.resolve(n),i),assertCurrent},assertReadAllowed(t){assertStateDatabaseReadAtOwnerPath(n,t,e)}}}function assertStateDatabaseAccessAtOwnerPath(e,t,n){let assertMaintenance=()=>{let t=n?n.schemaLease:getStateDatabaseSchemaLease(e);if(t){t.assertDatabaseAccess(e);return}let r=n?n.maintenanceScope:Oe();if(!r)throw new Ve(e);r.assertDatabaseAccess(e)},r=Q.get(t.key);if(r){if(!hasPhysicalOwnership(r))throw r.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);let t=r.payload.role??`gateway`;(!r.accepting||t!==`gateway`&&t!==`agent-embedded`)&&assertMaintenance()}else assertPersistedStateDatabaseAccessAllowed({databasePath:e,ownerPath:t.ownerPath,assertMaintenance})}const $=e(Symbol.for(`openclaw.sqliteWalWriteAdmissions`),()=>/* @__PURE__ */ new WeakMap);function registerSqliteWalWorkerMaintenance(e,t,n){e.exec(`PRAGMA wal_autocheckpoint = 0;`);let r=$.get(e)?.stopCheckpointTick;$.set(e,{execute:t,cancel:n}),r?.()}function isSqliteWalWorkerMaintained(e){return $.get(e)?.execute!==void 0}function cancelSqliteWalWriteAdmission(e){return $.get(e)?.cancel?.()}function createSqliteWalMaintenanceScheduler(e,t,n,r,i,a,o){let s=$.get(e);$.set(e,{...s,stopCheckpointTick:o});let c;return()=>(c||=(async()=>{let i=a(),o=!1;for(;;){let a=n(i);if(!a||i===0&&$.get(e)?.execute)return;a.continuation=o;let s,admitted=()=>{n(i)&&(s=t(a))},c=$.get(e);c?.execute?(s=await c.execute(a),s?.checkpoint&&r(s.checkpoint)):c?.admit?await c.admit(admitted):admitted();let l=s?.reclaimedPages??0;if(i-=l,l<=0||i<=0)return;o=!0,await st()}})().catch(i).finally(()=>{c=void 0}),c)}function registerDeferredSqliteWalWriteAdmission(e){let t=$.get(e)?.flush;if(t)return t;let n,flush=t=>{let r=n;if(n=void 0,r)try{t(),r.operation(),r.resolve()}catch(e){r.reject(e)}e.isOpen&&e.isTransaction&&Qe(e)};return $.set(e,{stopCheckpointTick:$.get(e)?.stopCheckpointTick,admit:e=>new Promise((t,r)=>{n={operation:e,resolve:t,reject:r}}),flush,cancel:()=>{n?.resolve(),n=void 0}}),flush}export{registerSqliteWalWorkerMaintenance as a,assertStateDatabaseReadAllowed as c,captureStateDatabaseAccess as d,getStateDatabaseSchemaLease as f,applyPrivateModeSync as g,withStateDatabaseColdAdmission as h,registerDeferredSqliteWalWriteAdmission as i,captureGatewayStateOwner as l,resolveGatewayStateOwnerPath as m,createSqliteWalMaintenanceScheduler as n,acquireStateDatabaseSchemaLease as o,prepareStateDatabaseReadAccess as p,isSqliteWalWorkerMaintained as r,assertStateDatabaseAccessAllowed as s,cancelSqliteWalWriteAdmission as t,captureGatewayStateOwnerAsync as u};