openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
472 lines (471 loc) • 21.4 kB
JavaScript
import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs";
import { i as collectNestedErrorCandidates } from "./error-coercion-hDrHOSGy.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs";
import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs";
import { v as withSqliteSnapshotFailureScope } from "./sqlite-error-diagnostics-6_hREUnq.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { _ as withSqliteReadOnlyWorkerScope } from "./sqlite-readonly-worker-D3pRJU7r.mjs";
import { a as resolveUpdateRehearsalRoot } from "./update-rehearsal-paths-Dr1MbUA_.mjs";
import { t as UpdateSchemaRefusalError } from "./openclaw-update-schema-refusal-DQDN1MLl.mjs";
import { n as formatUpdateFailureFact } from "./update-failure-facts-format-C2-bha7V.mjs";
import { n as createUpdateErrorFact, r as createUpdateFailureFact } from "./update-failure-facts-Bk_Ty8lS.mjs";
import { S as writeUpdatePostInstallDoctorResult, c as captureUpdateDoctorConfigWrites, h as normalizeUpdatePostInstallDoctorWarnings, i as UPDATE_POST_INSTALL_DOCTOR_RESULT_PATH_ENV, o as UpdateDoctorError, r as UPDATE_POST_INSTALL_DOCTOR_ADVISORY_EXIT_CODE, t as DoctorMaintenanceRefusalError } from "./update-doctor-result-DwaI51On.mjs";
import { t as ConfigWritePostCommitError } from "./io.write-errors-CuPAqPbq.mjs";
import { f as withCommandProcessScope, i as resolveCommandProcessSignal } from "./exec-spawn-DMKoejF-.mjs";
import { n as withDeferredDebugProxyCapture } from "./runtime-deferral-BEf6mqc4.mjs";
import { n as withPluginLoadDiagnostics } from "./load-diagnostics-t12s35CB.mjs";
import { u as formatUpdateDoctorConfigChange } from "./update-run-step-BjlMycA-.mjs";
import { f as isUpdateDoctorLintPass, t as DOCTOR_SQLITE_NOCOW_REPAIR_ENV } from "./update-phase-YdZvaQsy.mjs";
import { a as resolveDoctorUpdateRun } from "./update-deferred-model-retirement-Czgbuzcr.mjs";
import { n as retainCurrentDeferredUpdateWarnings } from "./deferred-update-warnings-DS2enkMR.mjs";
import { t as formatDoctorProgressPhase } from "./doctor-progress-C3vWlya1.mjs";
import { n as retainUpdateDoctorProcesses } from "./update-doctor-process-custody-B8LSKDgy.mjs";
import { a as recordDoctorHealthWarnings, c as showDoctorHealthSummary, o as renderStructuredHealthFindings, r as createDoctorHealthFindingBuffer, t as collectDoctorHealthResultWarnings } from "./doctor-health-contribution-t31v9kPi.mjs";
import { n as resolveDoctorRepairMode, t as isDoctorUpdateRepairMode } from "./doctor-repair-mode-D2HKy2yZ.mjs";
import { a as prepareDoctorMaintenanceArchives, c as repairDoctorStateDatabase, d as showDoctorRepairRefusal, f as withDoctorProgress, i as prepareDoctorInteractiveMaintenance, l as showDoctorIntro, n as exitDoctorHealthFlow, o as prepareDoctorRuntimeChecks, r as prepareDoctorHealthFlow, s as prepareDoctorStateSchema, t as createDoctorProgressMeasure, u as showDoctorOutro } from "./doctor-health-startup-KiSUu3WC.mjs";
//#region src/commands/doctor-policy-custody.ts
/**
* A delegated policy check can read shared state (profile-linked requesters do)
* while Doctor holds maintenance ownership outside a maintenance scope, e.g. on
* child-process custody or post-repair work. The held owner lends storage
* custody to every check, as it does for Doctor's own policy reads; each check
* still reads current policy.
*/
function createDoctorWriteAuthority(e) {
let t;
const n = e.assertCurrent;
return {
...e,
assertCurrent: () => t ? t.assertCurrent(n) : n(),
lendPolicyCustody: (e) => {
t = e;
}
};
}
//#endregion
//#region src/flows/doctor-health-update-result.ts
async function publishDoctorUpdateResult(e) {
const { updateResult: t, doctorResult: n, healthContext: r, maintenance: i } = e;
for (const e of t.capture.configChanges) createSubsystemLogger("update").warn(formatUpdateDoctorConfigChange(e));
const a = await retainCurrentDeferredUpdateWarnings(collectDoctorHealthResultWarnings({
healthContext: r,
startupWarnings: e.startupWarnings,
resultWarnings: n.warnings,
maintenanceWarnings: i?.warnings
}), { readUpdateRun: () => resolveDoctorUpdateRun(r?.env ?? process.env) });
const o = { ...n };
delete o.warnings;
delete o.deferredInspectionCheckIds;
await writeUpdatePostInstallDoctorResult({
resultPath: t.resultPath,
result: {
...o,
...t.capture.deferredInspectionCheckIds ? { deferredInspectionCheckIds: t.capture.deferredInspectionCheckIds } : {},
...i?.databaseWrites ? { databaseWrites: i.databaseWrites } : {},
...t.capture.fileWrites ? { configFileWrites: t.capture.fileWrites } : {},
...a.length ? { warnings: a } : {},
...t.capture.configChanges.length ? { configChanges: t.capture.configChanges } : {},
...t.capture.configWriteRefusal ? { configWriteRefusal: t.capture.configWriteRefusal } : {},
configHash: t.capture.hash,
...t.capture.inputHash === void 0 ? {} : { configInputHash: t.capture.inputHash }
}
});
}
//#endregion
//#region src/flows/doctor-health.ts
/** Runs the full interactive doctor flow against the provided or default runtime. */
async function runDoctorHealthFlow(e, t = {}, n, r) {
try {
var i = _usingCtx();
const a = resolveCommandProcessSignal(getAsyncWorkSignal());
a?.throwIfAborted();
const o = n && createDoctorWriteAuthority(n);
const s = i.u(await retainUpdateDoctorProcesses(o?.assertCurrent, o?.commandAuthority));
let requestedExit;
const run = () => withDeferredDebugProxyCapture(async (n) => {
let i = r;
const a = o?.databaseGenerations ? true : void 0;
const s = !o?.postCoreSchemaRepair && (t.repair === true || t.yes === true) ? resolveUpdateRehearsalRoot(process.env) : void 0;
if (process.env.OPENCLAW_UPDATE_IN_PROGRESS === "1" && !o?.postCoreSchemaRepair) {
const { guardUpdateDoctorSchemaUpgrade: n, rehearseDeferredUpdateDoctorSchema: r } = await import("./commands/doctor-update-schema-guard.js");
const o = await withDoctorProgress(formatDoctorProgressPhase("Update schema admission"), () => n({
schemas: i,
runtime: e,
json: t.json,
statePublicationOnly: s !== void 0,
preserveSourceArtifacts: a
}), t.json !== true);
if (!s) i = o ?? i;
if (!s && i?.updateSchemaRehearsal) {
const n = i;
await withDoctorProgress(formatDoctorProgressPhase("Update schema rehearsal"), () => r(n, e, t.fullIntegrityCheck), t.json !== true);
return;
}
}
const c = process.env[UPDATE_POST_INSTALL_DOCTOR_RESULT_PATH_ENV]?.trim();
return withPluginLoadDiagnostics((r) => {
const runDoctor = (a) => runDoctorHealthFlowWithResult((e, t) => {
requestedExit = () => exitDoctorHealthFlow(e, t);
}, e, t, i, r, c && a ? {
resultPath: c,
capture: a
} : void 0, o, n, s);
return c ? captureUpdateDoctorConfigWrites(resolveConfigPath(), runDoctor, o) : runDoctor();
});
});
const { withPluginGenerationSourceCustody: c } = await import("./plugin-generation-source-lookup-CGVYaeD2.mjs");
await c(() => s ? withCommandProcessScope(run, void 0, s) : run());
a?.throwIfAborted();
requestedExit?.();
} catch (e) {
i.e = e;
} finally {
i.d();
}
}
async function runDoctorHealthFlowWithResult(e, t, n, r, i, a, o, s, c) {
try {
var l = _usingCtx();
const u = resolveCommandProcessSignal(getAsyncWorkSignal());
const d = createDoctorProgressMeasure(n);
const { effectiveRuntime: f, repairRuntime: p, stateDirExistedAtStart: m, root: h } = await d("doctor.startup", () => prepareDoctorHealthFlow(t, n, showDoctorIntro));
let g;
let _ = [];
const v = { preserveSourceArtifacts: o?.databaseGenerations ? true : void 0 };
let y;
let b;
let x;
const { buffer: S, reportFindings: C } = createDoctorHealthFindingBuffer(f);
let w;
let T = { status: "error" };
const recordRepairRefusal = (e) => {
const t = showDoctorRepairRefusal(e);
if (!t) return false;
b = 1;
T = t;
return true;
};
const E = resolveDoctorRepairMode(n);
let D = false;
let O = false;
if (E.canPrompt && !E.shouldRepair) {
const t = await d("doctor.maintenance-admission", () => prepareDoctorInteractiveMaintenance({
runtime: f,
options: n,
databasePreflight: r,
root: h,
outro: showDoctorOutro
}));
if (t !== "accepted") {
if (t !== "handled") e(f, t.diagnosticExitCode);
return;
}
D = true;
O = true;
}
const k = l.a(new AsyncDisposableStack());
k.defer(async () => g?.release());
try {
const { assertDoctorRetiredStateAdmission: e } = await import("./doctor-retired-state-admission-AOrONOCY.mjs");
e();
const { prepareAutomaticHeartbeatRepair: t } = await import("./doctor-automatic-heartbeat-repair-BO7VYwP6.mjs");
const l = await t(n);
const A = l ? {
...n,
repair: true
} : n;
if (!E.updateInProgress && (n.repair === true || n.yes === true || D)) w = await d("doctor.archive-preparation", () => prepareDoctorMaintenanceArchives(r, f, v));
const [{ beginDoctorMaintenance: j }, { createDoctorOriginalCaptureHook: M }] = await Promise.all([import("./doctor-maintenance-BanWS4hA.mjs"), import("./doctor-original-capture-admission-jdUvhHHj.mjs")]);
g = await d("doctor.maintenance.begin", () => j({
options: A,
interactiveRepair: D,
root: h,
runtime: p,
assertCurrent: o?.assertCurrent,
lendPolicyCustody: o?.lendPolicyCustody,
databaseGenerations: o?.databaseGenerations,
databaseWriteCapture: o?.databaseWriteCapture,
databasePluginOwners: o?.databasePluginOwners,
serviceInspectionDeadlineAtMs: o?.serviceInspectionDeadlineAtMs,
beforeStateMutation: M({
root: h,
runtime: p,
writeAuthority: o,
rehearsalRoot: c,
json: n.json,
reportFindings: C,
fullIntegrityCheck: n.fullIntegrityCheck
})
}));
const runChecks = async () => {
u?.throwIfAborted();
const e = g ? p : f;
const { createDoctorPrompter: t } = await import("./doctor-prompter-SEbkj_Tb.mjs");
const { prepareDoctorDatabasePreflight: i } = await import("./doctor-database-preflight-Dhck-D-u.mjs");
const a = t({
runtime: e,
options: n,
signal: resolveCommandProcessSignal(g?.signal ?? u)
});
if (!g && !O) {
if (!r) await d("doctor.state-preflight", () => i({ scope: "state" }));
const { maybeOfferUpdateBeforeDoctor: e } = await import("./doctor-update-BFrrTByl.mjs");
if (await e({
options: n,
root: h,
confirm: (e) => a.confirm(e),
outro: showDoctorOutro
})) return;
}
const c = g && r?.agentDatabaseMigrationDiscovery?.discovery.deletionJournal.status === "unavailable";
let T = r && !c ? r : await d("doctor.database-preflight", () => i(v));
const { recordAgentDatabaseAdmissions: E } = await import("./agent-database-admission-D63FKGXN.mjs");
if (n.repair !== true && n.yes !== true) E(T.agentRefusals ?? []);
const { guardUpdateDoctorSchemaUpgrade: D } = await import("./commands/doctor-update-schema-guard.js");
let A = T.verifiedSnapshots ?? [];
await d("doctor.schema-admission", () => D({
schemas: T,
runtime: e,
json: n.json,
postCoreSchemaRepair: o?.postCoreSchemaRepair,
signal: resolveCommandProcessSignal(g?.signal ?? u),
onVerifiedBackup: (e) => {
A = e;
}
}));
const { prepareDoctorClientCredentials: j } = await import("./doctor-client-credentials-BstRhMZ6.mjs");
if (!await j({
runtime: e,
options: n,
prompter: a,
maintenanceActive: g !== void 0,
schemas: T
})) {
b = 1;
return;
}
if (g && (n.repair === true || n.yes === true)) {
if (await d("doctor.state-database-repair", () => repairDoctorStateDatabase(f, n.fullIntegrityCheck ? "full" : "quick"))) T = await d("doctor.database-preflight", () => i());
}
if (g) {
const { prepareDoctorMigrationBackups: e } = await import("./doctor-heartbeat-migration-backup-Bc1G5MXr.mjs");
await e({
schemas: T,
env: process.env,
check: n.fullIntegrityCheck ? "full" : "quick",
verifiedSnapshots: A,
automaticRepair: Boolean(l),
runtime: f,
measure: d
});
}
const M = await d("doctor.state-schema", () => prepareDoctorStateSchema(T, a.shouldRepair, n.fullIntegrityCheck ? "full" : "quick"));
const N = await prepareDoctorRuntimeChecks(T, h, e, a, n);
T = N.schemas;
_ = N.nocowPaths;
const P = T.agentDatabaseMigrationDiscovery;
if (P && P.stateDir === w?.stateDir) P.preparedTranscriptArchives = w?.preparedTranscriptArchives;
const { loadAndMaybeMigrateDoctorConfig: F } = await import("./doctor-config-flow-C_be81IM.mjs");
const I = await d("doctor.config-flow", () => F({
options: n,
retiredStateAdmitted: true,
stateSchemaPreparation: M,
...l ? { automaticHeartbeatRepair: l } : {},
agentDatabaseMigrationDiscovery: T.agentDatabaseMigrationDiscovery,
confirm: (e) => a.confirm(e),
runtime: e,
prompter: a,
reportFindings: C
}));
k.use(I);
const L = T.agentDatabaseMigrationDiscovery && T.agentDatabaseMigrationDiscovery.stateDir !== resolveStateDir() ? await d("doctor.database-preflight", () => i({ cfg: I.cfg })) : T;
const R = new Set(I.stateMigrationStepReceipts?.flatMap((e) => e.id === "media-persistence" ? e.recoveredAgentDatabasePaths ?? [] : []));
const z = L.agentDatabaseMigrationDiscovery?.discovery.sourceIdentities;
const B = (L.agentRefusals ?? []).filter((e) => !e.paths.every((e) => R.has(e) || R.has(z?.get(e)?.realPath ?? e)));
E(B);
const { CONFIG_PATH: V } = await import("./config/config.js");
const H = {
runtime: e,
healthFindings: S.healthFindings,
options: n,
prompter: a,
configResult: I,
cfg: I.cfg,
cfgForPersistence: structuredClone(I.cfg),
sourceConfigValid: I.sourceConfigValid ?? true,
configPath: I.path ?? V,
stateDirExistedAtStart: m,
gatewayMaintenanceActive: g !== void 0,
agentDatabaseRefusals: B,
updateWarnings: normalizeUpdatePostInstallDoctorWarnings([...S.updateWarnings ?? [], ...N.warnings]),
preparedAgentCount: Math.max(L.agentDatabaseMigrationDiscovery?.configuredAgentDatabaseTargets.length ?? 0, L.agentDatabaseMigrationDiscovery?.registeredAgentDatabases.length ?? 0),
runWithPluginMetadataSnapshot: I.runWithPluginMetadataSnapshot,
invalidatePluginMetadataSnapshot: I.invalidatePluginMetadataSnapshot
};
x = H;
const { runDoctorHealthContributions: U } = await import("./doctor-health-contributions-3uI5m45X.mjs");
await d("doctor.contributions", () => U(H));
if (recordRepairRefusal(H)) return;
if (g) {
const { validateDoctorExternalConfigForStartup: e } = await import("./doctor-external-config-BK-VJ9py.mjs");
if (!await d("doctor.external-config", () => e(f))) {
b = 1;
return;
}
const { assertDoctorMaintenanceReady: t } = await import("./doctor-maintenance-inspection-BHI5ySCK.mjs");
if (!(await d("doctor.maintenance-ready", () => t(H.cfg, process.env, f.log, L.agentDatabaseMigrationDiscovery?.discovery.targets ?? []))).schemaPublicationDeferred) {
y = L.agentDatabaseMigrationDiscovery?.discovery.targets ?? [];
s?.();
if (isTruthyEnvValue(process.env.OPENCLAW_DEBUG_PROXY_ENABLED)) {
const { initializeDebugProxyCaptureAsync: e } = await import("./runtime-B5ujXFJ2.mjs");
await e("cli");
}
}
const { repairGatewayMaintenanceStartupFailures: n } = await import("./gateway-boot-lifecycle-BOPmUDi-.mjs");
n();
}
return H;
};
let N;
let P;
try {
N = await withSqliteSnapshotFailureScope(() => g ? g.run(runChecks) : withCommandProcessScope(() => withSqliteReadOnlyWorkerScope(runChecks, u ? {
signal: u,
deadlineOwnedByCaller: false
} : void 0), u));
if (N && g && n.repair === true && _.length > 0) {
if (resolveDoctorRepairMode(n).updateInProgress && !isTruthyEnvValue(process.env["OPENCLAW_DOCTOR_SQLITE_NOCOW_REPAIR"])) f.log("SQLite NOCOW repair deferred: the managed updater did not request the store rewrite in this run.");
else {
const e = g;
await d("doctor.sqlite-nocow", () => e.repairSqliteNoCow(_));
}
}
if (N && g && N.prompter.shouldRepair) {
const e = g;
if (isDoctorUpdateRepairMode(N.prompter.repairMode) && y) {
const t = y;
await d("doctor.sqlite-reclamation", () => e.enableSqliteReclamation(t));
}
await d("doctor.retained-runtimes", () => e.cleanupRetainedRuntimes());
}
} catch (e) {
P = e;
throw e;
} finally {
const e = g;
if (e) {
const t = N;
await d("doctor.maintenance.finish", () => e.finish(t?.cfg, t ? async (e) => {
const { writeDoctorGatewayConfig: n } = await import("./doctor-health-contribution-runners.gateway-B5F0Zzs0.mjs");
return n(t, e);
} : void 0, P));
}
}
if (!N) {
showDoctorHealthSummary(x ?? S);
return;
}
if (recordRepairRefusal(N)) return;
const F = [];
if (i.length > 0) {
const { collectPluginLoadHealthFindings: e } = await import("./doctor-workspace-status-DjkzxzNA.mjs");
const t = e(i);
renderStructuredHealthFindings(N, t);
F.push(...t.map((e) => `${e.checkId}: ${e.message}`));
}
showDoctorHealthSummary(N);
const I = normalizeUpdatePostInstallDoctorWarnings([
...F,
...N.configResult.warnings ?? [],
...g?.warnings ?? [],
...(N.configResult.stateMigrationStepReceipts ?? []).flatMap((e) => e.outcome === "warning" || e.outcome === "skipped" || e.outcome === "deferred" ? e.warnings : []),
...N.postInstallDoctorResult?.warnings ?? []
]);
T = {
...N.postInstallDoctorResult ?? { status: "ok" },
...I.length ? { warnings: I } : {},
...g?.failureFacts?.length ? { failureFacts: [...g.failureFacts, ...N.postInstallDoctorResult?.failureFacts ?? []] } : {}
};
if (a && T.status === "advisory") {
b = 86;
return;
}
if (F.length > 0) {
showDoctorOutro("Doctor finished with plugin load errors.");
if (n.nonInteractive && !isUpdateDoctorLintPass(process.env)) b = 1;
return;
}
} catch (e) {
const { DoctorHeartbeatMigrationDeferredError: t } = await import("./doctor-heartbeat-run-recovery-sk9pAHyT.mjs");
if ((!g || e instanceof t) && e instanceof DoctorMaintenanceRefusalError && e.refusal.kind === "deferred" && (isDoctorUpdateRepairMode(resolveDoctorRepairMode(n)) || e instanceof t && isUpdateDoctorLintPass(process.env))) {
showDoctorHealthSummary(x ?? S);
o?.assertCurrent();
const { recordDeferredUpdateDoctorWarning: t, recordUpdateDoctorRefusal: n } = await import("./doctor-update-refusal-Cd1FpCVl.mjs");
n(e.message);
f.error(e.message);
T = {
status: "ok",
warnings: [e.message],
maintenanceRefusal: e.refusal
};
if (!a) await t(e.message, f);
showDoctorOutro("Doctor maintenance deferred; pending repairs remain unchanged.");
b = 0;
return;
}
const { DoctorStateMigrationRefusalError: r } = await import("./state-migrations.messages-B4pupCuT.mjs");
const i = e instanceof r ? e.failureFacts.map(formatUpdateFailureFact) : [];
if (x && i.length > 0) recordDoctorHealthWarnings(x, [], i, { prepend: true });
if (e instanceof r) {
const { recordUpdateDoctorRefusal: t, resolveUpdateDoctorGitRecovery: n } = await import("./doctor-update-refusal-Cd1FpCVl.mjs");
const r = await n({
root: h,
stateRepaired: true
});
if (r) {
e.message += `\n${r.message}`;
t(e.message);
}
}
showDoctorHealthSummary(x ?? S);
const s = collectNestedErrorCandidates(e);
const { classifyDoctorMaintenanceRefusal: c } = await import("./doctor-maintenance-inspection-BHI5ySCK.mjs");
const l = c(e);
const u = s.find((e) => e instanceof ConfigWritePostCommitError && e.rollbackStatus !== "restored");
const d = s.find((e) => e instanceof UpdateSchemaRefusalError);
const p = s.flatMap((e) => e instanceof UpdateDoctorError || e instanceof r ? e.failureFacts : []);
T = {
status: "error",
...l.kind === "data-at-risk" ? { maintenanceRefusal: l } : {},
...!x && i.length > 0 ? { warnings: i } : {},
failureFacts: !u && !d && p.length > 0 ? p : [createUpdateFailureFact({
leaseLoss: createUpdateErrorFact("doctor", e).leaseLoss,
check: u ? "config-write" : d ? "database-schema-preflight" : "doctor",
code: u ? "rollback-state-unverified" : d?.code ?? "doctor-failed",
message: u ? `${u.publication} config publication; rollback ${u.rollbackStatus}. ${u.message}` : d?.message ?? (e instanceof Error ? e.message : String(e))
})]
};
if (g && !(e instanceof r)) f.error("Doctor could not complete maintenance. Check the reported service state and resolve the failure.");
throw e;
} finally {
await d("doctor.maintenance.release", () => k.disposeAsync());
if (a) await publishDoctorUpdateResult({
updateResult: a,
doctorResult: T,
healthContext: x,
maintenance: g,
startupWarnings: S.updateWarnings
});
if (b !== void 0) e(f, b);
}
showDoctorOutro("Doctor complete.");
} catch (e) {
l.e = e;
} finally {
await l.d();
}
}
//#endregion
export { runDoctorHealthFlow as t };