openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
10 lines • 30.8 kB
JavaScript
import{n as GATEWAY_SERVICE_STOP_TIMEOUT_MS}from"./gateway-shutdown-budget-Utx5eFL-.mjs";import{p as toErrorObject}from"./error-coercion-DlKnt6w-.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{t as sleep}from"./sleep-B4CgCyZu.mjs";import{o as isDefaultInstallIdentity}from"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{a as getOpenClawDatabaseMaintenanceScope,t as admitOpenClawMaintenanceLiveAuthorityReads}from"./openclaw-state-maintenance-context-D-pYfco8.mjs";import{a as SqliteSnapshotCleanupError}from"./sqlite-lifecycle-errors-DMaudCZS.mjs";import{r as findStartupMaintenanceRequiredError}from"./startup-maintenance-required-Cz4Y_ofl.mjs";import{c as getStateDatabaseSchemaLease}from"./gateway-state-owner-D_klysuh.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{n as createOpenClawDatabaseMaintenanceScope}from"./openclaw-state-db-async-lifecycle-DlV0ztcV.mjs";import{t as GatewayStateOwnerContentionError}from"./gateway-state-owner-errors-Cke3Bshm.mjs";import{a as resolveSqliteInspectionSignal,r as createSqliteReadOnlyWorkerScope}from"./sqlite-readonly-worker-context-BjXXEC4m.mjs";import"./sqlite-readonly-worker-C1mJaAX6.mjs";import{a as hasCommandProcessCleanupError}from"./exec-result-TD4w1Z1i.mjs";import{l as closeOpenClawStateDatabaseByPathAsync}from"./openclaw-state-db-cache-uycu-8uy.mjs";import{a as isStatePostgres}from"./openclaw-state-db-engine-DiCia3Ut.mjs";import{n as openDoctorStateSchemaReadAdmission}from"./openclaw-state-db-doctor-schema-8QOqwhRP.mjs";import{t as acquireWithWait}from"./acquire-with-wait-C5jtmZa7.mjs";import{E as runWithDoctorMigrationBackup,f as createUpdateDoctorDatabaseWriteCapture,o as UpdateDoctorError,t as DoctorMaintenanceRefusalError}from"./update-doctor-result-B09W3zwf.mjs";import{d as findServiceOwnershipRefusal}from"./service-inspection-error-D006EyWC.mjs";import{r as createUpdateFailureFact}from"./update-failure-facts-Bwgg6oY-.mjs";import{a as resolveCommandProcessSignal,p as withCommandProcessScope}from"./exec-spawn-DNCbDcyJ.mjs";import{n as OpenClawAgentDatabaseLeaseActiveError}from"./openclaw-agent-db-lease-DiGHTqIH.mjs";import{t as DoctorUnreadableStateDatabaseError}from"./state-repair-message-CmSHWF4H.mjs";import{i as readPackageVersion}from"./package-json-DFB01rMW.mjs";import{n as GatewayServiceAuthorityError}from"./service-update-authority-DqjrBTQ9.mjs";import{a as readActiveGatewayLockIdentity}from"./gateway-lock-CQoO1usb.mjs";import{i as UPDATE_RUN_ID_ENV}from"./update-control-plane-sentinel-CjaLU71E.mjs";import{t as resolveDoctorUpdateAdmission}from"./doctor-maintenance-admission-4EDUyhFp.mjs";import{n as readBuiltGatewayBuildId}from"./update-git-runtime-Bysaru5h.mjs";import{i as resolveUpdateDoctorGitRecovery,r as recordUpdateDoctorRefusal,t as formatUpdateDoctorServiceStopRefusal}from"./doctor-update-refusal-BcMVmcsz.mjs";import{n as resolveGatewayService}from"./service-Bz63n2ee.mjs";import{n as probePortUsage}from"./ports-probe-B-fmalcq.mjs";import{g as resolveUpdatedGatewayRestartPort}from"./update-command-service-plan-j12f-M-s.mjs";import{a as readDoctorGatewayOwnerLease,i as createDoctorMaintenanceRefusal,o as readOfflineAppOwnedDoctorInspection,t as assertDoctorMaintenanceInspection}from"./doctor-maintenance-inspection-DzUHB6_d.mjs";import{t as createDoctorServiceInspectionBudget}from"./update-doctor-deadline-CxqP1Bkp.mjs";import{r as sanitizeDoctorNote}from"./emit-notes-DCY5wFZF.mjs";import{c as inspectGatewayRestart}from"./restart-health-rwGZnZS0.mjs";import{c as resolveUpdateParentGatewayActivation,l as shouldManageGatewayService,n as assertDoctorServiceSelection,o as isServiceRepairExternallyManaged}from"./doctor-service-repair-policy-gYXaFNLg.mjs";import{n as resolveDoctorRepairMode,t as isDoctorUpdateRepairMode}from"./doctor-repair-mode-Dilz8sGs.mjs";import{n as readLegacyGatewayLockIdentity,t as assertLegacyGatewayStoppedForMaintenance}from"./gateway-lock-legacy-Cl80SJrj.mjs";import{r as captureFreshDoctorMigrationTables}from"./doctor-migration-backup-BYwdxiJ7.mjs";import{i as resolveDoctorMaintenanceWaitDeadlineMs,n as acquireDoctorGatewayMaintenanceOwner,r as formatDoctorWaitSeconds,t as DOCTOR_MAINTENANCE_WAIT_PROGRESS_INTERVAL_MS}from"./doctor-maintenance-foreground-DTPHmdUM.mjs";import{n as holdDoctorMaintenanceExit,t as formatDoctorRecoveryHint}from"./doctor-maintenance-exit-Ci7Ig37v.mjs";import fs from"node:fs";import path from"node:path";
//!src/commands/doctor-agent-lease-refusal.ts
function createDoctorAgentLeaseRefusal(e,{cause:t,detail:n=`An agent database is in use.`,ownerPids:r=[]}={}){const i=`Doctor could not enter maintenance. ${n} Stop the Gateway and other OpenClaw processes or reboot, then rerun openclaw doctor --fix.`;const a=r.length?` Observed lease holder PID${r.length===1?``:`s`} ${r.slice(0,3).join(`, `)}${r.length>3?`, ...`:`.`}`:``;return new DoctorMaintenanceRefusalError(`${i}${a}`,{kind:`deferred`,reason:`agent-database-in-use`},{cause:t,failureFacts:[createUpdateFailureFact({check:`doctor`,code:`agent-database-lease-active`,message:i},e)]})}async function preflightExternalDoctorAgentLease(e,t,n=resolveSqliteInspectionSignal()){const{readActiveOpenClawAgentDatabaseLeasesReadOnly:r}=await import(`./openclaw-agent-db-lease-inspection-DxZExD0o.mjs`);let i=[];try{i=[...new Set((await r({env:e},openDoctorStateSchemaReadAdmission,n)).map(e=>e.owner_pid))]}catch(e){if(e instanceof SqliteSnapshotCleanupError||hasCommandProcessCleanupError(e))throw e;n?.throwIfAborted()}if(i.length===0)return;if(t){const{readActiveGatewayLockIdentity:t}=await import(`./gateway-lock-BSiLZmt0.mjs`);if(await t({env:e,requireInspection:true}).catch(e=>{if(hasCommandProcessCleanupError(e))throw e;return`unknown`})===void 0)return}throw createDoctorAgentLeaseRefusal(e,{ownerPids:i})}async function assertDoctorAgentLeaseAdmission(e,t=resolveSqliteInspectionSignal()){const{assertNoOpenClawAgentDatabaseLeasesReadOnly:n}=await import(`./openclaw-agent-db-lease-inspection-DxZExD0o.mjs`);try{await n({env:e},openDoctorStateSchemaReadAdmission,t)}catch(n){if(n instanceof SqliteSnapshotCleanupError||hasCommandProcessCleanupError(n))throw n;t?.throwIfAborted();if(n instanceof OpenClawAgentDatabaseLeaseActiveError)throw createDoctorAgentLeaseRefusal(e,{cause:n,ownerPids:n.ownerPids});const{preflightOpenClawDatabaseSchemas:r,getOpenClawDatabaseReadinessFailure:i}=await import(`./openclaw-database-preflight-BW_fgol_.mjs`);const a=(await r({env:e,scope:`state`,openStateSchemaReadAdmission:openDoctorStateSchemaReadAdmission})).indeterminate.find(e=>e.kind===`state`);if(a)throw new DoctorUnreadableStateDatabaseError(a.path,a.reason,{cause:i(a)});throw n}}function describeHolders(e){const t=e.length>3?`${e.slice(0,3).join(`, `)}, ...`:e.join(`, `);return`OpenClaw ${e.length===1?`process`:`processes`} ${t}`}async function admitDoctorAgentLeases(e){const{readActiveOpenClawAgentDatabaseLeasesReadOnly:t}=await import(`./openclaw-agent-db-lease-inspection-DxZExD0o.mjs`);const foreignHolders=e=>e.length>0&&!e.includes(process.pid)?e:void 0;const n=performance.now();let r;let i;let a=false;let o=0;for(;;){await e.acquire();try{await e.state.run(()=>assertDoctorAgentLeaseAdmission(e.state.env,e.signal));if(a)e.log(`Agent databases closed after ${formatDoctorWaitSeconds(performance.now()-n)}; continuing Doctor maintenance.`);return}catch(t){const o=t instanceof DoctorMaintenanceRefusalError?t.cause:void 0;const s=e.wait&&o instanceof OpenClawAgentDatabaseLeaseActiveError?foreignHolders(o.ownerPids):void 0;if(!s)throw t;i=s;r??=await resolveDoctorMaintenanceWaitDeadlineMs(e.state.env);if(performance.now()>=r)throw a?createDoctorAgentLeaseRefusal(e.state.env,{cause:o,detail:`Waited ${formatDoctorWaitSeconds(performance.now()-n)}; database held by PID ${i.slice(0,3).join(`, `)}${i.length>3?`, ...`:``}.`}):t;a=true}const s=await e.state.release();if(s)throw s;let c=100;for(;;){e.signal.throwIfAborted();e.assertCurrent?.();const a=performance.now();if(a>=r)break;if(a>=o){e.log(o===0?`Waiting up to ${formatDoctorWaitSeconds(r-a)} for ${describeHolders(i)} to close an agent database before Doctor maintenance. Let it finish, or stop it to continue sooner.`:`Still waiting for ${describeHolders(i)} to close an agent database (${formatDoctorWaitSeconds(a-n)} of ${formatDoctorWaitSeconds(r-n)}).`);o=a+DOCTOR_MAINTENANCE_WAIT_PROGRESS_INTERVAL_MS}await sleep(Math.min(c,r-a),e.signal);c=Math.min(c*2,2e3);let s;try{s=[...new Set((await t({env:e.state.env},openDoctorStateSchemaReadAdmission,e.signal)).map(e=>e.owner_pid))]}catch(t){if(t instanceof SqliteSnapshotCleanupError||hasCommandProcessCleanupError(t))throw t;e.signal.throwIfAborted();break}if(!foreignHolders(s))break;i=s}}}
//!src/commands/doctor-maintenance-stale-service.ts
function doctorGatewayMaintenanceError(e){const t=formatCliCommand(`openclaw gateway restart`,e.env);const n=`Run ${formatCliCommand(`openclaw gateway status --deep`,e.env)}; resolve the reported failure, then ${formatCliCommand(`openclaw doctor --fix`,e.env)} and ${t}.`;const r=`Doctor ${e.phase} failed. ${e.detail} ${n}`;const i=[{code:e.code,message:e.detail},{code:`stale-gateway-recovery-command`,message:n}].map(t=>createUpdateFailureFact({check:e.phase,...t},e.env));return e.phase===`gateway-stop`?new DoctorMaintenanceRefusalError(r,{kind:`data-at-risk`,reason:`gateway-state-unverified`},{cause:e.cause,failureFacts:i}):new UpdateDoctorError(r,i,{cause:e.cause})}async function inspectStaleDoctorGateway(e){const{before:t,root:n,env:r}=e;const i=await readLegacyGatewayLockIdentity(r);if(!t.running&&!i)return;const a=t.serviceEnv??r;const o=resolveGatewayService();const[s,c,l]=await Promise.all([readPackageVersion(n),readBuiltGatewayBuildId(n),o.readCommand(a).catch(()=>null)]);e.assertCurrent?.();if((!s||!c)&&!i)return;const u=await resolveUpdatedGatewayRestartPort({serviceEnv:a,serviceCommand:l});const d=i?void 0:await inspectGatewayRestart({service:o,port:u,env:a,expectedVersion:s,expectedBuildId:c});e.assertCurrent?.();if(!(i||d?.buildIdMismatch?.actual!=null||d?.versionMismatch||d?.staleConnection!==void 0))return;const f=i?.pid??t.servicePid??d?.runtime.pid;if(t.serviceUpdateVerdict?.kind!==`owned`||!t.serviceEnv||!t.running||i&&(i.state!==`alive`||i.pid!==t.servicePid))throw doctorGatewayMaintenanceError({env:r,phase:`gateway-stop`,code:`stale-gateway-service-unverified`,detail:`Gateway PID ${f??`unknown`} is stale, but its managed service ownership is unverified. ${t.blockMessage??t.serviceMutationSkipMessage??``}`});if(!s||!c)throw doctorGatewayMaintenanceError({env:r,phase:`gateway-stop`,code:`stale-gateway-identity-unavailable`,detail:`The installed candidate's build identity is unavailable.`});return{version:s,buildId:c,pid:f,port:u}}async function assertStaleDoctorGatewayStopped(e){const t=await resolveGatewayService().readRuntime(e.env);const n=await probePortUsage(e.stale.port);const r=await readLegacyGatewayLockIdentity(e.env);e.assertCurrent?.();if(t.status!==`stopped`||(t.pid??0)>0||n!==`free`||r){const i=`service=${t.status}, PID=${t.pid??`none`}, port ${e.stale.port}=${n}, legacy lock owner=${r?.pid??`none`}`;const a=`Stale Gateway PID ${e.stale.pid??`unknown`}`;const o=t.status===`running`||n===`busy`||Boolean(r);throw new Error(e.skipped?`${a} was not stopped: ${e.skipped} Observed: ${i}.`:o?`${a} did not stop: ${i}.`:`${a} could not be confirmed stopped: ${i}.`)}}
//!src/commands/doctor-maintenance-state.ts
async function createDoctorMaintenanceState(e){const{params:t,env:n,settle:r}=e;const{resolveLegacyStateConfigPath:i,resolvePendingLegacyStateDirMigrationPaths:a}=await import(`./state-migrations.state-dir-CKjADuh4.mjs`);let o;let s;let c;let l;const runOwnerCheck=e=>o?o.run(e):l.run(e);const setOwner=e=>{l=e;t.lendPolicyCustody?.(e&&{assertCurrent:t=>getStateDatabaseSchemaLease(resolveOpenClawStateSqlitePath(d))?t():runOwnerCheck(()=>e.assertCurrent(t))})};const u=a({env:n});let d=u?{...n,OPENCLAW_STATE_DIR:u.source,OPENCLAW_CONFIG_PATH:i(u.source)}:n;let f=false;let p=false;const m=t.databaseWriteCapture??createUpdateDoctorDatabaseWriteCapture(t.databaseGenerations,{env:d,pluginOwners:t.databasePluginOwners,root:t.root??void 0,signal:e.signal,assertCurrent:()=>l.assertCurrent(e.assertCurrent),warn:e.warn});const closeResources=async e=>{const t=e===null?void 0:e??(s?void 0:resolveStateDir(d));const n=[];const closeScope=async(e,t)=>{try{await e();t()}catch(r){try{await e();t();n.push(r)}catch(e){n.push(new AggregateError([r,e],`Doctor maintenance resource cleanup failed.`,{cause:e}))}}};const r=o;let i=r===void 0;if(r)await closeScope(()=>r.close(t===void 0?void 0:async()=>{const{closeOpenClawAgentDatabasesAsync:e}=await import(`./openclaw-agent-db-lifecycle-DdTqx9Jz.mjs`);await e(t)}),()=>{i=true});const a=c;if(a)await closeScope(()=>a.close(),()=>{c=void 0});await closeScope(async()=>{const{closeAuthProfileReadPool:e}=await import(`./sqlite-read-pool-BO2ZwfOO.mjs`);e({kind:`root`,rootPath:resolveStateDir(d)})},()=>{if(i){o=void 0;s=void 0}});if(n.length>0)throw n.length===1?n[0]:new AggregateError(n,`Doctor maintenance resource cleanup failed.`)};const settleCapture=async()=>{if(l&&m&&f){await r(async()=>{l.assertCurrent(e.assertCurrent);await m.settle();l.assertCurrent(e.assertCurrent)});f=false}};const enterResources=async(n,i)=>{setOwner(n);try{n.assertCurrent(e.assertCurrent);i?.();s=getOpenClawDatabaseMaintenanceScope();o=createOpenClawDatabaseMaintenanceScope({schemaMaintenance:true,sqliteIntegrityCheck:t.options.fullIntegrityCheck?`full`:`quick`,assertDatabaseAccess:n.assertDatabaseAccess,assertOwnerCurrent:t=>{n.assertCurrent(()=>{e.assertCurrent?.();e.assertReadCurrent()},t)}});if(p)o.run(()=>admitOpenClawMaintenanceLiveAuthorityReads(resolveOpenClawStateSqlitePath(d)));c=createSqliteReadOnlyWorkerScope({signal:e.signal,deadlineOwnedByCaller:false})}catch(e){await n.release();setOwner(void 0);throw e}if(m&&!f){await r(async()=>{await o.run(()=>m.admit());n.assertCurrent(e.assertCurrent)});f=true}};const assertOwnerCurrent=t=>{runOwnerCheck(()=>{l.assertCurrent(o?void 0:e.assertCurrent);if(t!==void 0)l.assertDatabaseAccess(t)})};const h={get env(){return d},get owner(){return l},get resources(){return o},get receipt(){return l?void 0:m?.receipt},run(e){return o.run(()=>c.run(()=>runWithDoctorMigrationBackup(captureFreshDoctorMigrationTables,()=>m?m.run(e):e())))},async acquire(r){r?.();if(o)return;if(u&&d!==n&&!fs.lstatSync(u.source).isDirectory())throw new Error(`Legacy state path is not a directory: ${u.source}; move it manually before rerunning Doctor.`);const i=await acquireDoctorGatewayMaintenanceOwner(path.resolve(resolveOpenClawStateSqlitePath(d)),d,{...t,assertCurrent:e.assertCurrent,assertAdmission:r,deadlineMs:e.deadline(),signal:e.signal});await enterResources(i,r)},async prepareRepair(r){r?.();const i=t.beforeStateMutation;if(i){await o.run(()=>i({env:d,signal:e.signal}));r?.();o.assertAdmission()}if(!m||isStatePostgres()){o.run(()=>admitOpenClawMaintenanceLiveAuthorityReads(resolveOpenClawStateSqlitePath(d)));p=true}const{prepareLegacyStateDirMigration:s}=await import(`./state-migrations.state-dir-CKjADuh4.mjs`);const c=a({env:n});const f=resolveStateDir(d);if(!u)return;if(!c||path.resolve(f)!==path.resolve(c.source))throw new Error(`State directory selection changed before moving ${u.source} to ${u.target}; leave both paths unchanged and reconcile them manually before rerunning Doctor.`);l.assertCurrent(e.assertCurrent);const g=resolveOpenClawStateSqlitePath(d);await closeResources(f);await l.run(()=>closeOpenClawStateDatabaseByPathAsync(g));await settleCapture();await l.release();setOwner(void 0);e.assertCurrent?.();r?.();const _=s({env:n});if(_&&!_.result.migrated)throw new Error(_.result.warnings.join(`
`));d=n;await h.acquire(r);if(_){const{loadDotEnv:n}=await import(`./dotenv-CI3hzOIF.mjs`);n();const r=_.result;for(const e of[...r.changes,...r.notices??[]])t.runtime.log(sanitizeDoctorNote(e));for(const t of r.warnings)e.warn(sanitizeDoctorNote(t))}},async repairSqliteNoCow(n){if(n.length===0)return{changes:[],warnings:[]};const{repairDoctorSqliteNoCow:r}=await import(`./doctor-sqlite-nocow-CFVp_4xJ.mjs`);const{closeAgentDatabaseReaders:i}=await import(`./openclaw-agent-db-readers-DqmNf5I1.mjs`);const a=resolveStateDir(d);const o=resolveOpenClawStateSqlitePath(d);assertOwnerCurrent();await closeResources(a);try{const s=await i(n).then(()=>[],e=>[`Retained agent database readers could not be closed before NOCOW repair: ${formatErrorMessage(e)}`]);const c=await l.run(async()=>{await closeOpenClawStateDatabaseByPathAsync(o);await assertDoctorAgentLeaseAdmission(d,e.signal);return r({paths:n,stateDir:a,env:d,log:e=>t.runtime.log(sanitizeDoctorNote(e)),assertCurrent:()=>assertOwnerCurrent(o)})});return{...c,warnings:[...s,...c.warnings]}}finally{await enterResources(l)}},async enableSqliteReclamation(n){const{enableDoctorSqliteReclamation:r}=await import(`./doctor-sqlite-reclamation-BsME-5t0.mjs`);const{closeOpenClawAgentDatabaseByPathAsync:i}=await import(`./openclaw-agent-db-lifecycle-DdTqx9Jz.mjs`);const a=resolveOpenClawStateSqlitePath(d);e.signal.throwIfAborted();assertOwnerCurrent();await o.run(async()=>{for(const e of n)await i(e.path,e.agentId)});await closeResources(null);let s;let c;try{c=await l.run(async()=>{await closeOpenClawStateDatabaseByPathAsync(a);await assertDoctorAgentLeaseAdmission(d,e.signal);return r({env:d,agents:n,signal:e.signal,assertCurrent:()=>assertOwnerCurrent(a),log:t.runtime.log})})}catch(e){s=toErrorObject(e,`SQLite reclamation failed.`)}try{await enterResources(l)}catch(e){if(s!==void 0)throw new AggregateError([s,e],`SQLite reclamation and maintenance scope restoration failed.`,{cause:e});throw e}if(s!==void 0)throw s;return c},async release(){const e=[];try{await closeResources()}catch(t){if(hasCommandProcessCleanupError(t)||o||c)throw t;e.push(t)}try{await settleCapture()}catch(t){if(hasCommandProcessCleanupError(t))throw t;e.push(t)}try{await l?.release();setOwner(void 0)}catch(t){e.push(t)}if(e.length===0)return;return e.length===1?toErrorObject(e[0],`Doctor maintenance state cleanup failed.`):new AggregateError(e,`Doctor maintenance state cleanup failed.`)}};return h}
//!src/commands/doctor-maintenance.ts
async function beginDoctorMaintenance(e){if(!(e.options.repair===true||e.options.yes===true||e.interactiveRepair))return;const t=createDoctorServiceInspectionBudget(e.serviceInspectionDeadlineAtMs);const n=e.serviceInspectionDeadlineAtMs===void 0?void 0:t;n?.();const r={...e.env??process.env,...e.runId?{[UPDATE_RUN_ID_ENV]:e.runId}:{}};const i=isDoctorUpdateRepairMode(resolveDoctorRepairMode(e.options,r));const a=i||e.waitForMaintenance===true;const o=i?resolveUpdateParentGatewayActivation(r):void 0;let s;let c;let l;let u;const d=[];const warn=t=>{d.push(t);e.runtime.log(t)};const reportGatewayRecoveryFailure=t=>{if(s?.serviceEnv){const n=`Warning: Doctor could not complete Gateway recovery: ${formatErrorMessage(t)}. ${formatDoctorRecoveryHint(s.serviceEnv)}`;d.push(n);e.runtime.error(n)}};const f=[];let p=false;let m=false;let h=false;let g;let assertUpdateAdmissionReadCurrent;let assertUpdateAdmissionCurrent;let _=false;const assertAuthority=e=>{try{e()}catch(e){_=true;throw e}};const v=e.assertCurrent;const y=v?()=>assertAuthority(v):void 0;let b;const settle=async e=>{if(b)throw b.error;try{return await withCommandProcessScope(e)}catch(e){if(hasCommandProcessCleanupError(e))b??={error:e};throw e}};const acquireStoppedMaintenanceResources=e=>acquireWithWait({acquire:()=>C.acquire(e),shouldRetry:e=>s?.stopped===true&&e instanceof GatewayStateOwnerContentionError,deadlineMs:l??performance.now(),pollIntervalMs:250,maxPollIntervalMs:2e3});const throwSettledFailure=e=>{if(e!==void 0)throw e};const releaseAndRestoreAutoStart=e=>settle(async()=>{const t=await C.release();const n=s?.windowsTaskAutoStartRecovery;try{e?.();if(!m)await settle(async()=>n?.restore(true))}finally{if(!b)await settle(async()=>n?.complete(!m))}return t});const release=async e=>throwSettledFailure(await releaseAndRestoreAutoStart(e));const restoreGateway=async(t,n,i,a=assertUpdateAdmissionCurrent)=>{n?.();const o=s;const c=e.root;if(!o?.serviceEnv||!c)return;if(!o.stopped){const{resolveUnstoppedGatewayRestoration:t}=await import(`./doctor-maintenance-restoration-POXJLqwq.mjs`);const n=await t({before:o,serviceEnv:o.serviceEnv,root:c,leaveStopped:e.interactiveRepair&&e.options.repair!==true&&e.options.yes!==true||resolveDoctorRepairMode(e.options,r).updateInProgress,reportStopped:e.reportStoppedService===true});if(n.warning)warn(n.warning);if(!n.restore)return}try{const s=o.serviceEnv;const[{restoreDoctorGatewayService:l},{resolveUpdatedGatewayRestartPort:u},{renderRestartDiagnostics:f,waitForGatewayHealthyRestart:p}]=await Promise.all([import(`./doctor-maintenance-restoration-POXJLqwq.mjs`),import(`./update-command-service-plan-C4uLVD3F.mjs`),import(`./restart-health-eJ2WViR0.mjs`)]);const{service:m,state:h,cfg:_}=await l({before:o,serviceEnv:s,root:c,env:r,cfg:t,writeConfig:i,options:e.options,runtime:e.runtime,signal:S.signal,warnings:d,settle,assertCustody:n,assertRestoreAdmission:a,assertInstallationAdmission:assertUpdateAdmissionCurrent});if(!h)return;const v=await u({config:_,serviceEnv:h.env,serviceCommand:h.command});const y=await settle(()=>p({service:m,port:v,env:h.env,requireRunningService:true,...g?{expectedVersion:g.version,expectedBuildId:g.buildId}:{}}));if(y.outcome===`starting`||y.outcome!==`ready`&&y.runtime.status===`running`){warn(`Warning: Gateway started after Doctor maintenance, but readiness was not verified. ${f(y).join(` `)} Run \`${formatCliCommand(`openclaw gateway status --deep`,h.env)}\` or \`${formatCliCommand(`openclaw gateway diagnostics export`,h.env)}\`.`);return}if(y.outcome!==`ready`)throw doctorGatewayMaintenanceError({env:r,phase:`gateway-restoration`,code:`doctor-gateway-rpc-verification-failed`,detail:`The managed Gateway did not become ready after Doctor maintenance: ${f(y).join(` `)}.`})}catch(t){if(hasCommandProcessCleanupError(t)){b??={error:t};throw t}if(t instanceof GatewayServiceAuthorityError){const{recordDoctorGatewayRestorationRefusal:n}=await import(`./doctor-maintenance-restoration-POXJLqwq.mjs`);await n({serviceEnv:o.serviceEnv,error:t,before:o,warnings:d,failureFacts:f,runtime:e.runtime});return}if(t instanceof UpdateDoctorError)throw t;throw doctorGatewayMaintenanceError({env:r,phase:`gateway-restoration`,code:findServiceOwnershipRefusal(t)?.reason??`doctor-gateway-restoration-failed`,detail:`The managed Gateway could not be restored after Doctor maintenance: ${String(t)}`,cause:t})}e.runtime.log(`Gateway restarted and verified after Doctor maintenance.`);if(o.stopped&&u!==void 0){const t=(Date.now()-u)/1e3;e.runtime.log(`The Gateway was stopped for ${t.toFixed(1)} s.`)}if(g){const e=`Warning: Replaced stale Gateway PID ${g.pid??`unknown`} through its service manager; verified ${g.version} build ${g.buildId} after Doctor maintenance.`;warn(e)}};const finish=async(e,t,n,r)=>{const{finishDoctorGatewayMaintenance:i}=await import(`./doctor-maintenance-restoration-POXJLqwq.mjs`);await i({state:C,stopped:s?.stopped===true,config:e,assertCustody:t,release:releaseAndRestoreAutoStart,restore:(e,t)=>restoreGateway(e,t,n,r),isCleanupUncertain:()=>b!==void 0})};const admitRepair=async()=>{h=false;await assertLegacyGatewayStoppedForMaintenance(C.env);await admitDoctorAgentLeases({state:C,wait:a,acquire:()=>acquireStoppedMaintenanceResources(n).then(()=>assertUpdateAdmissionCurrent?.()),assertCurrent:()=>{y?.();n?.()},signal:S.signal,log:e.runtime.log});n?.();p=true};let x=false;const failAdmission=async(t,n)=>{x=true;if(hasCommandProcessCleanupError(t)){reportGatewayRecoveryFailure(t);throw t}try{if(s?.stopped){try{await acquireStoppedMaintenanceResources()}catch(e){const t=e instanceof GatewayStateOwnerContentionError?`Warning: The stopped Gateway still holds state ownership after the service stop deadline. Shared-state repair is unsafe while that writer remains active. Restoring its service; run ${formatCliCommand(`openclaw gateway status --deep`,r)}, then retry ${formatCliCommand(`openclaw doctor --fix`,r)} after shutdown completes.`:`Warning: Doctor could not reacquire maintenance ownership: ${String(e)} Restoring its service without repairing shared state.`;warn(t)}await finish(void 0,n,void 0,n??assertUpdateAdmissionCurrent)}else await release()}catch(e){reportGatewayRecoveryFailure(e);throw new AggregateError([t,e],`${String(t)} ${String(e)}`,{cause:e})}resolveCommandProcessSignal(S.signal)?.throwIfAborted();if(_||t instanceof DoctorUnreadableStateDatabaseError)throw t;const i=findStartupMaintenanceRequiredError(t)?.kind===`newer-schema`;const a=createDoctorMaintenanceRefusal(t,r,i);const o=h&&!i?await resolveUpdateDoctorGitRecovery({root:e.root}):void 0;if(o){a.message+=`\n${o.message}`;recordUpdateDoctorRefusal(a.message)}throw a};const S=holdDoctorMaintenanceExit(t=>{d.push(t);e.runtime.error(t)});const C=await createDoctorMaintenanceState({params:e,env:r,signal:S.signal,deadline:()=>l,assertCurrent:y,assertReadCurrent:()=>assertUpdateAdmissionReadCurrent?.(),settle,warn});try{await settle(async()=>{const i=isServiceRepairExternallyManaged(void 0,r);if(i)await preflightExternalDoctorAgentLease(r,a,S.signal);if(e.root&&isDefaultInstallIdentity(r)&&!i&&await shouldManageGatewayService(r)){const{maybeStopManagedServiceBeforeMutableUpdate:i}=await import(`./update-command-service-maintenance-2FxULYpZ.mjs`);h=true;let a;try{a=await i({updateInstallKind:`package`,root:e.root,shouldRestart:true,jsonMode:true,phase:`inspect`,timeoutMs:t()})}catch(e){const t=await readOfflineAppOwnedDoctorInspection(e,r);if(!t)throw e;a=t}assertDoctorMaintenanceInspection(a,r);c=a.serviceUpdateVerdict;if(c?.kind===`unavailable`)warn(c.message);if(a.serviceUpdateVerdict?.kind!==`absent`)assertAuthority(()=>{const t=resolveDoctorUpdateAdmission(r,void 0,e.legacyPostCore);assertUpdateAdmissionReadCurrent=()=>assertAuthority(t.assertCurrent);const checkAndRecord=()=>assertAuthority(t.recordContinuation);assertUpdateAdmissionCurrent=()=>C.resources?C.run(checkAndRecord):checkAndRecord()});if(a.serviceUpdateVerdict?.kind===`owned`&&a.serviceEnv)assertDoctorServiceSelection(r,a.serviceEnv);g=await inspectStaleDoctorGateway({root:e.root,env:r,before:a,assertCurrent:assertUpdateAdmissionCurrent});if(o!==void 0&&!g&&a.serviceUpdateVerdict?.kind===`owned`&&a.offline!==true)throw new DoctorMaintenanceRefusalError(`Doctor could not enter maintenance. Error: ${await formatUpdateDoctorServiceStopRefusal(a.serviceEnv??r)}`,{kind:`data-at-risk`,reason:`gateway-state-unverified`});try{await C.acquire(n)}catch(e){if(hasCommandProcessCleanupError(e))throw e;const t=resolveCommandProcessSignal(S.signal)??S.signal;const n=await readDoctorGatewayOwnerLease(C.env,t);const i=n?void 0:await readActiveGatewayLockIdentity({env:a.serviceEnv??r,requireInspection:true});t.throwIfAborted();y?.();assertUpdateAdmissionReadCurrent?.();if(!a.running||!(n?.state===`live`&&n.mode===`supervised`||a.servicePid!==void 0&&i?.pid===a.servicePid))throw e}if(a.serviceUpdateVerdict?.kind===`owned`){h=false;if(a.serviceEnv)assertDoctorServiceSelection(r,a.serviceEnv);if(o===void 0||g){a.serviceUpdateVerdict.refreshDefinition=a.serviceUpdateVerdict.requiresInstallRootRefresh===true;const o=e.root;const{withGatewayServiceOperationLock:c}=await import(`./service-operation-lock-BR4RIMlV.mjs`);await c(a.serviceEnv??r,async c=>{let d=assertUpdateAdmissionCurrent;try{await settle(async()=>{try{l=performance.now()+GATEWAY_SERVICE_STOP_TIMEOUT_MS;const stopService=()=>i({updateInstallKind:`package`,root:o,shouldRestart:true,jsonMode:true,expectedService:a,retainNativeIdentity:true,timeoutMs:t(),assertCurrent:()=>d?.(),assertDeadline:n,warn,onStopped:e=>{s=e;u??=Date.now()}});s=await(C.resources?C.resources.run(stopService):stopService());assertDoctorMaintenanceInspection(s,r);if(s.serviceUpdateVerdict?.kind===`unavailable`)warn(s.serviceUpdateVerdict.message);if(g&&s.serviceEnv)await assertStaleDoctorGatewayStopped({stale:g,env:s.serviceEnv,skipped:s.stopped?void 0:s.serviceMutationSkipMessage??s.blockMessage,assertCurrent:assertUpdateAdmissionCurrent})}catch(e){if(!g||hasCommandProcessCleanupError(e))throw e;throw doctorGatewayMaintenanceError({env:r,phase:`gateway-stop`,code:`stale-gateway-stop-failed`,detail:String(e),cause:e})}if(s?.stopped){u??=Date.now();e.runtime.log(`Stopped the managed Gateway for Doctor repair.`);e.runtime.log(`Doctor stopped it because its repairs write state that the running Gateway also writes, and restores it after repairs settle. If forcibly terminated: ${formatDoctorRecoveryHint(s.serviceEnv??r)}`)}await admitRepair();c()})}catch(e){d=c;await failAdmission(e,c)}})}}else if(c?.kind!==`unavailable`&&c?.kind!==`absent`)e.runtime.log(`The stopped Gateway service was left unchanged; repairing Doctor's selected state only.`)}if(!p)await admitRepair();s?.windowsTaskAutoStartRecovery?.beginMutation();m=s?.serviceUpdateVerdict?.kind===`owned`&&s.serviceUpdateVerdict.requiresInstallRootRefresh===true;await C.prepareRepair(n)})}catch(e){try{if(x)throw e;await failAdmission(e)}finally{S.release(true)}}let w=`held`;const assertHeld=(e,t)=>{if(e!==T||w!==`held`)throw new Error(`${t} requires its original live maintenance owner.`)};const T={signal:S.signal,serviceUpdateVerdict:c,warnings:d,failureFacts:f,get databaseWrites(){return C.receipt},run:e=>C.run(e),releaseState:async()=>throwSettledFailure(await settle(()=>C.release())),async repairSqliteNoCow(t){assertHeld(this,`SQLite NOCOW repair`);const n=await settle(()=>C.repairSqliteNoCow(t));for(const t of n.changes)e.runtime.log(t);for(const e of n.warnings)warn(e)},async enableSqliteReclamation(e){assertHeld(this,`SQLite reclamation`);const t=await settle(()=>C.enableSqliteReclamation(e));for(const e of t.warnings)warn(e)},async release(){if(this!==T)throw new Error(`Gateway restoration requires its original live maintenance owner.`);w=`released`;try{await release()}catch(e){S.release(true);throw e}finally{S.release()}},async finish(e,t,n){if(b){reportGatewayRecoveryFailure(b.error);throw b.error}const assertCustody=(e=`restoring`)=>{if(this!==T||w!==e)throw new Error(`Gateway restoration requires its original live maintenance owner.`)};assertCustody(`held`);w=`restoring`;let r=n!==void 0;try{await finish(e,assertCustody,t)}catch(e){reportGatewayRecoveryFailure(e);r=true;if(n!==void 0)throw new AggregateError([n,e],`${formatErrorMessage(n)} ${formatErrorMessage(e)}`,{cause:e});throw e}finally{w=`released`;S.release(r)}}};return T}export{beginDoctorMaintenance};