openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,037 lines (1,036 loc) • 39.5 kB
JavaScript
import { n as GATEWAY_SERVICE_STOP_TIMEOUT_MS } from "./gateway-shutdown-budget-cDAYhBVI.mjs";
import { i as withEngineStoreAdmission } from "./admission-scope-DmxaPNhm.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { n as resolveIdentityPathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import { t as sleep } from "./sleep-CkI3nkiJ.mjs";
import { o as isDefaultInstallIdentity } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { a as getOpenClawDatabaseMaintenanceScope, t as admitOpenClawMaintenanceLiveAuthorityReads } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { c as registerSignalExitGate } from "./signal-exit-barrier-BOGtFHQL.mjs";
import { r as findStartupMaintenanceRequiredError } from "./startup-maintenance-required-DEn4Krys.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { n as createOpenClawDatabaseMaintenanceScope } from "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { c as getStateDatabaseSchemaLease } from "./gateway-state-owner-Bnv5owvG.mjs";
import { t as GatewayStateOwnerContentionError } from "./gateway-state-owner-errors-DI3mhN4z.mjs";
import { b as createSqliteReadOnlyWorkerScope } from "./sqlite-readonly-worker-D3pRJU7r.mjs";
import { i as hasCommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs";
import { l as closeOpenClawStateDatabaseByPathAsync } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import { l as runWithDoctorMigrationBackup } from "./update-doctor-migration-attribution-Dp_N9vmd.mjs";
import { a as isStatePostgres } from "./openclaw-state-db-engine-sM0tpxNy.mjs";
import { n as openDoctorStateSchemaReadAdmission } from "./openclaw-state-db-doctor-schema-C5bP-XwE.mjs";
import { t as acquireWithWait } from "./acquire-with-wait--M6IyZwQ.mjs";
import { d as hasGatewayServiceStopUnsafeError, l as findServiceOwnershipRefusal } from "./service-inspection-error-BKgh5HDJ.mjs";
import { r as createUpdateFailureFact } from "./update-failure-facts-Bk_Ty8lS.mjs";
import { f as createUpdateDoctorDatabaseWriteCapture, o as UpdateDoctorError, t as DoctorMaintenanceRefusalError } from "./update-doctor-result-DwaI51On.mjs";
import { f as withCommandProcessScope, i as resolveCommandProcessSignal } from "./exec-spawn-DMKoejF-.mjs";
import { t as DoctorUnreadableStateDatabaseError } from "./state-repair-message-CG0JUAZp.mjs";
import { i as readPackageVersion } from "./package-json-DXb4lz-W.mjs";
import { n as GatewayServiceAuthorityError } from "./service-update-authority-wlK0pAdP.mjs";
import { n as GatewayLockError, o as readActiveGatewayLockIdentity } from "./gateway-lock-IYOwJQai.mjs";
import { i as UPDATE_RUN_ID_ENV } from "./update-control-plane-sentinel-ThuSZh3z.mjs";
import { t as resolveDoctorUpdateAdmission } from "./doctor-maintenance-admission-CqCSvhaQ.mjs";
import { n as readBuiltGatewayBuildId } from "./update-git-runtime-CP5qQp-3.mjs";
import { i as resolveUpdateDoctorGitRecovery, r as recordUpdateDoctorRefusal, t as formatUpdateDoctorServiceStopRefusal } from "./doctor-update-refusal-B2SaHPHZ.mjs";
import { n as resolveGatewayService } from "./service-hQiIzcTo.mjs";
import { n as probePortUsage } from "./ports-probe-DVN9Sc3E.mjs";
import { h as resolveUpdatedGatewayRestartPort } from "./update-command-service-plan-DuPiwu0P.mjs";
import { t as createDoctorServiceInspectionBudget } from "./update-doctor-deadline-IRbqiQ4w.mjs";
import { r as sanitizeDoctorNote } from "./emit-notes-llcc2fq-.mjs";
import { i as inspectGatewayRestart } from "./restart-health-C1P8c-k3.mjs";
import { a as readOfflineAppOwnedDoctorInspection, i as readDoctorGatewayOwnerLease, r as classifyDoctorMaintenanceRefusal, t as assertDoctorMaintenanceInspection } from "./doctor-maintenance-inspection-CzV_u8fo.mjs";
import { t as formatGatewayLockFailure } from "./gateway-lock-diagnostics-B97G4DPJ.mjs";
import { n as resolveDoctorRepairMode, t as isDoctorUpdateRepairMode } from "./doctor-repair-mode-D2HKy2yZ.mjs";
import { n as readLegacyGatewayLockIdentity, t as assertLegacyGatewayStoppedForMaintenance } from "./gateway-lock-legacy-8QieMnAt.mjs";
import { r as captureFreshDoctorMigrationTables } from "./doctor-migration-backup-DwSvhlqi.mjs";
import { c as resolveUpdateParentGatewayActivation, l as shouldManageGatewayService, n as assertDoctorServiceSelection, o as isServiceRepairExternallyManaged } from "./doctor-service-repair-policy-DAuL0W8-.mjs";
import { i as resolveDoctorMaintenanceWaitDeadlineMs, n as acquireDoctorGatewayMaintenanceOwner, r as formatDoctorWaitSeconds, t as DOCTOR_MAINTENANCE_WAIT_PROGRESS_INTERVAL_MS } from "./doctor-maintenance-foreground-DBVBUZpI.mjs";
import fs from "node:fs";
import path from "node:path";
//#region 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) {
const { readActiveOpenClawAgentDatabaseLeasesReadOnly: n } = await import("./openclaw-agent-db-lease-B4okbi_P.mjs");
let r = [];
try {
r = withEngineStoreAdmission(() => [...new Set(n({ env: e }, openDoctorStateSchemaReadAdmission).map((e) => e.owner_pid))]);
} catch (e) {
if (hasCommandProcessCleanupError(e)) throw e;
}
if (r.length === 0) return;
if (t) {
const { readActiveGatewayLockIdentity: t } = await import("./gateway-lock-C8DzJkpV.mjs");
if (await t({
env: e,
requireInspection: true
}).catch((e) => {
if (hasCommandProcessCleanupError(e)) throw e;
return "unknown";
}) === void 0) return;
}
throw createDoctorAgentLeaseRefusal(e, { ownerPids: r });
}
/** The caller holds both lifecycle coordinators; this check never opens a state writer. */
async function assertDoctorAgentLeaseAdmission(e) {
const { assertNoOpenClawAgentDatabaseLeasesReadOnly: t, OpenClawAgentDatabaseLeaseActiveError: n } = await import("./openclaw-agent-db-lease-B4okbi_P.mjs");
try {
withEngineStoreAdmission(() => t({ env: e }, openDoctorStateSchemaReadAdmission));
} catch (t) {
if (t instanceof n) throw createDoctorAgentLeaseRefusal(e, {
cause: t,
ownerPids: t.ownerPids
});
const { preflightOpenClawDatabaseSchemas: r, getOpenClawDatabaseReadinessFailure: i } = await import("./openclaw-database-preflight-BB0y4HYJ.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 t;
}
}
function describeHolders(e) {
const t = e.length > 3 ? `${e.slice(0, 3).join(", ")}, ...` : e.join(", ");
return `OpenClaw ${e.length === 1 ? "process" : "processes"} ${t}`;
}
/**
* Admits Doctor maintenance once no other process holds an agent database lease.
* Update-time Doctor releases everything the attempt acquired and waits until the
* deadline it shares with state contention: a lease holder must write shared state
* to close its database, which Doctor's maintenance ownership would refuse.
*/
async function admitDoctorAgentLeases(e) {
const { readActiveOpenClawAgentDatabaseLeasesReadOnly: t, OpenClawAgentDatabaseLeaseActiveError: n } = await import("./openclaw-agent-db-lease-B4okbi_P.mjs");
const foreignHolders = (e) => e.length > 0 && !e.includes(process.pid) ? e : void 0;
const r = performance.now();
let i;
let a;
let o = false;
let s = 0;
for (;;) {
await e.acquire();
try {
await e.state.run(() => assertDoctorAgentLeaseAdmission(e.state.env));
if (o) e.log(`Agent databases closed after ${formatDoctorWaitSeconds(performance.now() - r)}; continuing Doctor maintenance.`);
return;
} catch (t) {
const s = t instanceof DoctorMaintenanceRefusalError ? t.cause : void 0;
const c = e.wait && s instanceof n ? foreignHolders(s.ownerPids) : void 0;
if (!c) throw t;
a = c;
i ??= await resolveDoctorMaintenanceWaitDeadlineMs(e.state.env);
if (performance.now() >= i) throw o ? createDoctorAgentLeaseRefusal(e.state.env, {
cause: s,
detail: `Waited ${formatDoctorWaitSeconds(performance.now() - r)}; database held by PID ${a.slice(0, 3).join(", ")}${a.length > 3 ? ", ..." : ""}.`
}) : t;
o = true;
}
const c = await e.state.release();
if (c) throw c;
let l = 100;
for (;;) {
e.signal.throwIfAborted();
e.assertCurrent?.();
const n = performance.now();
if (n >= i) break;
if (n >= s) {
e.log(s === 0 ? `Waiting up to ${formatDoctorWaitSeconds(i - n)} for ${describeHolders(a)} to close an agent database before Doctor maintenance. Let it finish, or stop it to continue sooner.` : `Still waiting for ${describeHolders(a)} to close an agent database (${formatDoctorWaitSeconds(n - r)} of ${formatDoctorWaitSeconds(i - r)}).`);
s = n + DOCTOR_MAINTENANCE_WAIT_PROGRESS_INTERVAL_MS;
}
await sleep(Math.min(l, i - n), e.signal);
l = Math.min(l * 2, 2e3);
let o;
try {
o = withEngineStoreAdmission(() => [...new Set(t({ env: e.state.env }, openDoctorStateSchemaReadAdmission).map((e) => e.owner_pid))]);
} catch (e) {
if (hasCommandProcessCleanupError(e)) throw e;
break;
}
if (!foreignHolders(o)) break;
a = o;
}
}
}
//#endregion
//#region src/commands/doctor-maintenance-exit.ts
/** Let admitted repair work settle before restoring the service and exiting. */
function holdDoctorMaintenanceExit(e) {
const t = new AbortController();
const n = createDeferredCore();
n.promise.catch(() => void 0);
const r = registerSignalExitGate(n.promise, (n, r) => {
if (t.signal.aborted) return;
const i = n ?? r;
const a = `Doctor interrupted${i ? ` by ${i}` : ""}; cancelling inspections and settling admitted repairs before exit.`;
t.abort(new Error(a));
try {
e?.(a);
} catch {}
});
let i = true;
const release = (e = false) => {
if (!i) return;
i = false;
r();
if (e) n.reject(/* @__PURE__ */ new Error("Doctor maintenance did not complete."));
else n.resolve();
};
return {
signal: t.signal,
release
};
}
//#endregion
//#region 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 });
}
/** Identify predecessor code without requiring startup before offline migrations. */
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,
openStateSchemaReadAdmission: openDoctorStateSchemaReadAdmission,
requirePluginHealth: false
});
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) throw new Error(`Stale Gateway PID ${e.stale.pid ?? "unknown"} did not stop: service=${t.status}, PID=${t.pid ?? "none"}, port ${e.stale.port}=${n}, legacy lock owner=${r?.pid ?? "none"}.`);
}
//#endregion
//#region src/commands/doctor-maintenance-state.ts
/** Database custody can change paths while stopped-service custody remains with Doctor. */
async function createDoctorMaintenanceState(e) {
const { params: t, env: n, settle: r } = e;
const { resolveLegacyStateConfigPath: i, resolvePendingLegacyStateDirMigrationPaths: a } = await import("./state-migrations.state-dir-DUGRrWf7.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-W0V62HCS.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-DrqQUr9K.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(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-DUGRrWf7.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("\n"));
d = n;
await h.acquire(r);
if (_) {
const { loadDotEnv: n } = await import("./dotenv-C8xNDyjL.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(e) {
if (e.length === 0) return {
changes: [],
warnings: []
};
const { repairDoctorSqliteNoCow: n } = await import("./doctor-sqlite-nocow-peoHwNsc.mjs");
const r = resolveStateDir(d);
const i = resolveOpenClawStateSqlitePath(d);
assertOwnerCurrent();
await closeResources(r);
try {
return await l.run(async () => {
await closeOpenClawStateDatabaseByPathAsync(i);
await assertDoctorAgentLeaseAdmission(d);
return n({
paths: e,
stateDir: r,
env: d,
log: (e) => t.runtime.log(sanitizeDoctorNote(e)),
assertCurrent: () => assertOwnerCurrent(i)
});
});
} finally {
await enterResources(l);
}
},
async enableSqliteReclamation(n) {
const { enableDoctorSqliteReclamation: r } = await import("./doctor-sqlite-reclamation-_Bbqtbbz.mjs");
const { closeOpenClawAgentDatabaseByPathAsync: i } = await import("./openclaw-agent-db-lifecycle-W0V62HCS.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);
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 cleanupRetainedRuntimes(e) {
const { captureRetainedNativeWorkerSource: t } = await import("./worker-native-lifecycle-_y0_OQJk.mjs");
const { retireIdleOpenClawStateReadWorkers: n } = await import("./openclaw-state-read-worker-BzPX9QC9.mjs");
const { prepareRetainedUpdateRuntimeCleanup: r } = await import("./doctor-retained-runtime-pctTetSz.mjs");
assertOwnerCurrent();
const i = await h.run(() => r(d, { inspectService: e }));
const a = t();
let o;
try {
await closeResources();
o = await n(a);
await a.retireIdleBroker();
} catch (e) {
throw new DoctorMaintenanceRefusalError(`Doctor inspection resource cleanup failed: ${formatErrorMessage(e)}. Resolve this cleanup failure before restarting the Gateway or rerunning openclaw doctor --fix.`, {
kind: "data-at-risk",
reason: "active-mutation"
}, { cause: e });
}
try {
await l.run(() => i(true, {
assertCurrent() {
assertOwnerCurrent();
l.assertDatabaseAccess(resolveOpenClawStateSqlitePath(d));
},
assertResourcesSettled(e) {
const t = a.activeWorkerPaths().some((t) => t === void 0 || isPathInside(e, resolveIdentityPathViaExistingAncestorSync(t)));
if (!o || t) throw new Error(`independent native work in this process (PID: ${process.pid}); let these holders finish, then rerun openclaw doctor --fix`);
}
}));
} finally {
await enterResources(l);
}
},
/** Returns a settled cleanup failure; throws only while Doctor must retain custody. */
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;
}
//#endregion
//#region 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;
const u = [];
const warn = (t) => {
u.push(t);
e.runtime.log(t);
};
const d = [];
let f = false;
let p = false;
let m = false;
let h;
let assertUpdateAdmissionReadCurrent;
let assertUpdateAdmissionCurrent;
let g = false;
const assertAuthority = (e) => {
try {
e();
} catch (e) {
g = true;
throw e;
}
};
const _ = e.assertCurrent;
const v = _ ? () => assertAuthority(_) : void 0;
let y;
const settle = async (e) => {
if (y) throw y.error;
try {
return await withCommandProcessScope(e);
} catch (e) {
if (hasCommandProcessCleanupError(e)) y ??= { error: e };
throw e;
}
};
const acquireStoppedMaintenanceResources = (e) => acquireWithWait({
acquire: () => S.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 S.release();
const n = s?.windowsTaskAutoStartRecovery;
try {
e?.();
if (!p) await settle(async () => n?.restore(true));
} finally {
if (!y) await settle(async () => n?.complete(!p));
}
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-TTd3vCc5.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: d }, { renderRestartDiagnostics: f, waitForGatewayHealthyRestart: p }] = await Promise.all([
import("./doctor-maintenance-restoration-TTd3vCc5.mjs"),
import("./update-command-service-plan-Bc8xWWoh.mjs"),
import("./restart-health-DrLrjcAo.mjs")
]);
const { service: m, state: g, cfg: _ } = await l({
before: o,
serviceEnv: s,
root: c,
env: r,
cfg: t,
writeConfig: i,
options: e.options,
runtime: e.runtime,
signal: x.signal,
warnings: u,
settle,
assertCustody: n,
assertRestoreAdmission: a,
assertInstallationAdmission: assertUpdateAdmissionCurrent
});
if (!g) return;
const v = await d({
config: _,
serviceEnv: g.env,
serviceCommand: g.command
});
const y = await settle(() => p({
service: m,
port: v,
env: g.env,
requireRunningService: true,
...h ? {
expectedVersion: h.version,
expectedBuildId: h.buildId,
requirePluginHealth: false
} : {}
}));
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", g.env)}\` or \`${formatCliCommand("openclaw gateway diagnostics export", g.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) {
e.runtime.error(`Warning: Doctor could not complete Gateway restoration: ${formatErrorMessage(t)}. After Doctor exits, run ${formatCliCommand("openclaw gateway status --deep", r)}; resolve the reported failure, then run ${formatCliCommand("openclaw gateway start", r)}.`);
if (hasCommandProcessCleanupError(t)) {
y ??= { error: t };
throw t;
}
if (t instanceof GatewayServiceAuthorityError) {
const { recordDoctorGatewayRestorationRefusal: n } = await import("./doctor-maintenance-restoration-TTd3vCc5.mjs");
await n({
serviceEnv: o.serviceEnv,
error: t,
before: o,
warnings: u,
failureFacts: d,
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 (h) {
const e = `Warning: Replaced stale Gateway PID ${h.pid ?? "unknown"} through its service manager; verified ${h.version} build ${h.buildId} after Doctor maintenance.`;
warn(e);
}
};
const finish = async (e, t, n, r) => {
const { finishDoctorGatewayMaintenance: i } = await import("./doctor-maintenance-restoration-TTd3vCc5.mjs");
await i({
state: S,
stopped: s?.stopped === true,
config: e,
assertCustody: t,
release: releaseAndRestoreAutoStart,
restore: (e, t) => restoreGateway(e, t, n, r),
isCleanupUncertain: () => y !== void 0
});
};
const admitRepair = async () => {
m = false;
await assertLegacyGatewayStoppedForMaintenance(S.env);
await admitDoctorAgentLeases({
state: S,
wait: a,
acquire: () => acquireStoppedMaintenanceResources(n).then(() => assertUpdateAdmissionCurrent?.()),
assertCurrent: () => {
v?.();
n?.();
},
signal: x.signal,
log: e.runtime.log
});
n?.();
f = true;
};
let b = false;
const failAdmission = async (t, n) => {
b = true;
if (hasCommandProcessCleanupError(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) {
throw new AggregateError([t, e], `${String(t)} ${String(e)}`, { cause: e });
}
resolveCommandProcessSignal(x.signal)?.throwIfAborted();
if (g || t instanceof DoctorUnreadableStateDatabaseError) throw t;
const i = findStartupMaintenanceRequiredError(t)?.kind === "newer-schema";
const a = t instanceof DoctorMaintenanceRefusalError ? t : new DoctorMaintenanceRefusalError(`Doctor could not enter maintenance. ${t instanceof GatewayLockError ? formatGatewayLockFailure(t) : String(t)}${i || hasGatewayServiceStopUnsafeError(t) ? "" : ` Stop the Gateway service and other OpenClaw processes using this state, then run ${formatCliCommand("openclaw doctor --fix", r)} from an independent shell.`}`, classifyDoctorMaintenanceRefusal(t), {
cause: t,
...t instanceof UpdateDoctorError ? { failureFacts: t.failureFacts } : {}
});
const o = m && !i ? await resolveUpdateDoctorGitRecovery({ root: e.root }) : void 0;
if (o) {
a.message += `\n${o.message}`;
recordUpdateDoctorRefusal(a.message);
}
throw a;
};
const x = holdDoctorMaintenanceExit((t) => {
u.push(t);
e.runtime.error(t);
});
const S = await createDoctorMaintenanceState({
params: e,
env: r,
signal: x.signal,
deadline: () => l,
assertCurrent: v,
assertReadCurrent: () => assertUpdateAdmissionReadCurrent?.(),
settle,
warn
});
try {
await settle(async () => {
const i = isServiceRepairExternallyManaged(void 0, r);
if (i) await preflightExternalDoctorAgentLease(r, a);
if (e.root && isDefaultInstallIdentity(r) && !i && await shouldManageGatewayService(r)) {
const { maybeStopManagedServiceBeforeMutableUpdate: i } = await import("./update-command-service-maintenance-Brc4q08S.mjs");
m = 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" && a.offline !== true) assertAuthority(() => {
const e = resolveDoctorUpdateAdmission(r);
assertUpdateAdmissionReadCurrent = () => assertAuthority(e.assertCurrent);
const checkAndRecord = () => assertAuthority(e.recordContinuation);
assertUpdateAdmissionCurrent = () => S.resources ? S.run(checkAndRecord) : checkAndRecord();
});
if (a.serviceUpdateVerdict?.kind === "owned" && a.serviceEnv) assertDoctorServiceSelection(r, a.serviceEnv);
h = await inspectStaleDoctorGateway({
root: e.root,
env: r,
before: a,
assertCurrent: assertUpdateAdmissionCurrent
});
if (o !== void 0 && !h && 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 S.acquire(n);
} catch (e) {
if (hasCommandProcessCleanupError(e)) throw e;
const t = resolveCommandProcessSignal(x.signal) ?? x.signal;
const n = await readDoctorGatewayOwnerLease(S.env, t);
const i = n ? void 0 : await readActiveGatewayLockIdentity({
env: a.serviceEnv ?? r,
requireInspection: true
});
t.throwIfAborted();
v?.();
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") {
m = false;
if (a.serviceEnv) assertDoctorServiceSelection(r, a.serviceEnv);
if (o === void 0 || h) {
a.serviceUpdateVerdict.refreshDefinition = a.serviceUpdateVerdict.requiresInstallRootRefresh === true;
const o = e.root;
const { withGatewayServiceOperationLock: c } = await import("./service-operation-lock-CuhGDKIP.mjs");
await c(a.serviceEnv ?? r, async (c) => {
let u = 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: () => u?.(),
assertDeadline: n,
warn,
onStopped: (e) => {
s = e;
}
});
s = await (S.resources ? S.resources.run(stopService) : stopService());
assertDoctorMaintenanceInspection(s, r);
if (s.serviceUpdateVerdict?.kind === "unavailable") warn(s.serviceUpdateVerdict.message);
if (h && s.serviceEnv) await assertStaleDoctorGatewayStopped({
stale: h,
env: s.serviceEnv,
assertCurrent: assertUpdateAdmissionCurrent
});
} catch (e) {
if (!h || hasCommandProcessCleanupError(e)) throw e;
throw doctorGatewayMaintenanceError({
env: r,
phase: "gateway-stop",
code: "stale-gateway-stop-failed",
detail: String(e),
cause: e
});
}
if (s?.stopped) e.runtime.log("Stopped the managed Gateway for Doctor repair.");
await admitRepair();
c();
});
} catch (e) {
u = 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 (!f) await admitRepair();
s?.windowsTaskAutoStartRecovery?.beginMutation();
p = s?.serviceUpdateVerdict?.kind === "owned" && s.serviceUpdateVerdict.requiresInstallRootRefresh === true;
await S.prepareRepair(n);
});
} catch (e) {
try {
if (b) throw e;
await failAdmission(e);
} finally {
x.release(true);
}
}
let C = "held";
const assertHeld = (e, t) => {
if (e !== w || C !== "held") throw new Error(`${t} requires its original live maintenance owner.`);
};
const w = {
signal: x.signal,
serviceUpdateVerdict: c,
warnings: u,
failureFacts: d,
get databaseWrites() {
return S.receipt;
},
run: (e) => S.run(e),
releaseState: async () => throwSettledFailure(await settle(() => S.release())),
async repairSqliteNoCow(t) {
assertHeld(this, "SQLite NOCOW repair");
const n = await settle(() => S.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(() => S.enableSqliteReclamation(e));
for (const e of t.warnings) warn(e);
},
async cleanupRetainedRuntimes() {
assertHeld(this, "Updater runtime cleanup");
await settle(() => S.cleanupRetainedRuntimes(c !== void 0));
},
async release() {
if (this !== w) throw new Error("Gateway restoration requires its original live maintenance owner.");
C = "released";
try {
await release();
} catch (e) {
x.release(true);
throw e;
} finally {
x.release();
}
},
async finish(e, t, n) {
if (y) throw y.error;
const assertCustody = (e = "restoring") => {
if (this !== w || C !== e) throw new Error("Gateway restoration requires its original live maintenance owner.");
};
assertCustody("held");
C = "restoring";
let r = n !== void 0;
try {
await finish(e, assertCustody, t);
} catch (e) {
r = true;
if (n !== void 0) throw new AggregateError([n, e], `${formatErrorMessage(n)} ${formatErrorMessage(e)}`, { cause: e });
throw e;
} finally {
C = "released";
x.release(r);
}
}
};
return w;
}
//#endregion
export { beginDoctorMaintenance };