openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 9.15 kB
JavaScript
import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{o as redactSensitiveUrlLikeString}from"./redact-sensitive-url-Byg68d6v.mjs";import{m as resolveConfigPath}from"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{f as resolveIdentityPathViaExistingAncestorSync}from"./path-existence-BR9MXlgL.mjs";import{c as registerSignalExitGate}from"./signal-exit-barrier-DoATIAtq.mjs";import{a as hasCommandProcessCleanupError}from"./exec-result-TD4w1Z1i.mjs";import{i as GATEWAY_CLIENT_NAMES,r as GATEWAY_CLIENT_MODES}from"./client-info-Dr3-kuD1.mjs";import{F as waitForGatewayRootWorkIdle}from"./gateway-work-admission-CnMW3_qr.mjs";import{t as GATEWAY_SERVER_CAPS}from"./server-capabilities-HdXShIdT.mjs";import path from"node:path";import{AsyncLocalStorage}from"node:async_hooks";
//!src/cli/local-state-owner.ts
const localOwnerScope=new AsyncLocalStorage;var LocalStateOwnerError=class extends Error{constructor(e,t,n){super(t,{cause:n});this.code=e;this.name=`LocalStateOwnerError`}};async function waitForLocalBackgroundWork(e){await waitForGatewayRootWorkIdle({signal:e,onWaiting:e=>process.stderr.write(`Waiting for ${e} background ${e===1?`task`:`tasks`} to finish. Press Ctrl-C to stop.\n`)})}async function runWithLocalStateOwner(e){const t=localOwnerScope.getStore();t?.assertCurrent();const n=e.databasePortRecovery?{...e.databasePortRecovery}:void 0;const r={...process.env};const i=resolveStateDir(r);const a=resolveIdentityPathViaExistingAncestorSync(i);const o={...r,OPENCLAW_STATE_DIR:a,OPENCLAW_CONFIG_PATH:resolveConfigPath(r,i)};const s=e.params;const c=[...e.scopes??[`operator.admin`]];const[{acquireGatewayLock:l,isGatewayLifecycleContentionError:u,readActiveGatewayLockIdentity:d,readLockPayloadSync:f,resolveGatewayLockPaths:p},{captureGatewayStateOwner:m,tryBorrowGatewayStateOwner:h},{createOpenClawDatabaseMaintenanceScope:g},{getScopedDatabaseEngineSelection:_,withDatabaseEngineSelection:v}]=await Promise.all([import(`./gateway-lock-BSiLZmt0.mjs`),import(`./gateway-state-owner-BcD6afkY.mjs`),import(`./openclaw-state-db-async-lifecycle-D8_rltWE.mjs`),import(`./context-DavGEvQ1.mjs`)]);const y=p(o);const b=path.join(y.stateDir,`state`,`openclaw.sqlite`);const x=new AbortController;const S=createDeferredCore();const C=registerSignalExitGate(S.promise,()=>x.abort());const assertTargetCurrent=()=>{x.signal.throwIfAborted();e.assertTargetCurrent?.()};const w=(e.onForeignOwner===`refuse`?`This command is offline-only. ${e.onlineAlternative?`${e.onlineAlternative} `:``}`:`Update the Gateway or fix authentication and retry. `+(e.requireLocalBackendSharedAuth?`Provide the Gateway's shared secret through OPENCLAW_GATEWAY_TOKEN or OPENCLAW_GATEWAY_PASSWORD in this CLI process; device pairing is not a substitute. `:``))+`To run offline, stop the Gateway through its service owner, wait for ownership to release, then rerun this exact command.`;const refuse=t=>{throw new LocalStateOwnerError(`OWNER_UNAVAILABLE`,`Cannot admit ${e.method} for ${e.target} in state root ${y.stateDir}: ${redactSensitiveUrlLikeString(formatErrorMessage(t))}. No local mutation was attempted. Inspect openclaw gateway status. ${w}`,t)};const discover=async()=>{try{assertTargetCurrent();const t={env:o,requireInspection:true,signal:x.signal};return e.onForeignOwner?await d({...t,includeEmbedded:true}):await d(t)}catch(e){return refuse(e)}};const runLocal=async(n,r)=>{const assertCurrent=()=>{assertTargetCurrent();n()};assertCurrent();const{loadConfig:i}=await import(`./config/config.js`);assertCurrent();let a;let s=true;const c=r?(e,t)=>{if(!s||e!==b||t!==y.configPath)return false;assertCurrent();return true}:t?.holdsOfflineTarget?.(b,y.configPath)?t.holdsOfflineTarget:void 0;try{return await localOwnerScope.run({assertCurrent,holdsOfflineTarget:c},()=>e.runLocal({env:o,get config(){assertCurrent();a??=i();assertCurrent();return a},signal:x.signal,assertCurrent,...c?{localGatewayAbsent:true}:{}}))}finally{s=false}};const route=async t=>{const listenerPort=()=>{if(!t.ownerId)return refuse(/* @__PURE__ */ new Error(`Gateway lacks the expected-owner contract; update the Gateway.`));if(t.port===void 0)return refuse(/* @__PURE__ */ new Error(`The state owner has no Gateway listener`));return t.port};const requestGateway=async(n,r,i,a=i?e.expectFinal:void 0)=>{const o=listenerPort();const{callGateway:s,isGatewayClientRequestError:l}=await import(`./call-CggG9h6i.mjs`);let u=false;try{assertTargetCurrent();return await s({method:n,configPath:y.configPath,params:i?{...r,expectedOwnerId:t.ownerId}:r,localPortOverride:o,ignoreEnvUrlOverride:true,requireLocalBackendSharedAuth:e.requireLocalBackendSharedAuth,allowLocalBackendAuthNone:e.requireLocalBackendSharedAuth,requiredMethods:[n],requiredCapabilities:[GATEWAY_SERVER_CAPS.LOCAL_STATE_OWNER_ROUTING,...e.requiredCapabilities??[]],timeoutMs:e.timeoutMs??6e5,expectFinal:a,signal:x.signal,scopes:c,onSignalAbort:i?e.onGatewaySignalAbort:void 0,onResponse:i&&e.onGatewayResponse?async(n,r)=>{const guardedRequest=(e,r,i)=>{assertTargetCurrent();const a=f(y.ownerLockPath,true);if(!a||a.ownerId!==t.ownerId||a.pid!==t.pid)refuse(/* @__PURE__ */ new Error(`Gateway owner changed during the operation`));return n(e,r,i)};await e.onGatewayResponse(guardedRequest,AbortSignal.any([x.signal,r]))}:void 0,clientName:GATEWAY_CLIENT_NAMES.CLI,mode:GATEWAY_CLIENT_MODES.CLI,assertDispatchCurrent:()=>{assertTargetCurrent();const e=f(y.ownerLockPath,true);if(!e||e.ownerId!==t.ownerId||e.pid!==t.pid)refuse(/* @__PURE__ */ new Error(`Gateway owner changed before dispatch`));u=true}})}catch(t){const r=l(t)&&typeof t.details===`object`&&t.details!==null&&`mutationAccepted`in t.details&&t.details.mutationAccepted===false;throw new LocalStateOwnerError(u&&!r?`OUTCOME_UNKNOWN`:`OWNER_REFUSED`,`Gateway owning ${y.stateDir} on local port ${o} could not complete ${n} for ${e.target}: ${redactSensitiveUrlLikeString(formatErrorMessage(t))}. `+(u&&!r?`The outcome may be partial; inspect ${e.recoveryCommand??`the operation's status`} and the target before retrying. No local fallback was attempted.`:`No local mutation was attempted. ${w}`),t)}};if(typeof e.onForeignOwner===`function`){assertTargetCurrent();const t=await e.onForeignOwner({env:o,signal:x.signal,assertCurrent:assertTargetCurrent,requestOwner:(e,t,n)=>requestGateway(e,t,false,n?.expectFinal)});assertTargetCurrent();return t}if(e.onForeignOwner===`refuse`)return refuse(/* @__PURE__ */ new Error(`This operation requires exclusive offline state ownership`));listenerPort();const n=typeof s===`function`?await s(x.signal):s;return await requestGateway(e.method,n,true)};try{assertTargetCurrent();const t=m(b);if(t){if(n)return refuse(/* @__PURE__ */ new Error(`Database port recovery requires exclusive offline ownership`));if(e.databaseAccess===`none`)return refuse(/* @__PURE__ */ new Error(`Config-only repair requires exclusive offline ownership`));return await runLocal(t.assertCurrent)}const r=n?void 0:await discover();if(r)return await route(r);let i;try{i=await l({env:o,role:e.databasePortMaintenance?`sqlite-maintenance`:`agent-embedded`,allowInTests:true,databasePortRecovery:n,databaseAccess:e.databaseAccess})}catch(e){if(!n&&u(e)){const e=await discover();if(e)return await route(e)}return refuse(e)}if(!i)return refuse(/* @__PURE__ */ new Error(`Offline state ownership was not acquired`));let a;try{if(e.databaseAccess!==`none`&&e.databaseEngine===`configured`&&!_()){const[{createConfigIO:e},t,{resolveDatabaseEngineSelection:n},{loadDotEnvAsync:r}]=await Promise.all([import(`./io-Daz-kTPd.mjs`),import(`./io.invalid-config-Cw04snJA.mjs`),import(`./config-CVpxUujP.mjs`),import(`./dotenv-CI3hzOIF.mjs`)]);i.assertCurrent();assertTargetCurrent();await r({env:o});i.assertCurrent();assertTargetCurrent();const s=await e({env:o,configPath:o.OPENCLAW_CONFIG_PATH,observe:false,pluginValidation:`core-only`}).readConfigFileSnapshot();if(t.isConfigReadFailure(s))throw t.createConfigReadError(s);if(!s.valid)throw t.createInvalidConfigError(s.path,t.formatInvalidConfigDetails(s.issues));i.assertCurrent();assertTargetCurrent();a=await n(s.config,o);i.assertCurrent();assertTargetCurrent()}}catch(e){await i.release();throw e}const runOwned=async()=>{if(e.databaseAccess!==`none`)try{await i.acquireConfiguredPostgresOwner?.()}catch(e){await i.release();refuse(e)}const t=e.databasePortMaintenance||e.databaseAccess===`none`?void 0:g({assertOwnerCurrent:()=>i.assertCurrent(),assertDatabaseAccess:i.assertDatabaseAccess});const{createAgentCleanupScope:n}=await import(`./run-cleanup-timeout-eJRDcIuX.mjs`);const r=n();let a=false;try{return await(t??i).run(()=>r.run(()=>runLocal(i.assertCurrent,true)))}catch(e){a=hasCommandProcessCleanupError(e);throw e}finally{a||=r.outcome===`uncertain`;if(t)await waitForLocalBackgroundWork(e.signal?AbortSignal.any([x.signal,e.signal]):x.signal);await t?.close();const n=a?h(b):void 0;await i.release();n?.assertCurrent()}};return a?await v(a,runOwned):await runOwned()}finally{S.resolve();C()}}export{waitForLocalBackgroundWork as n,runWithLocalStateOwner as t};