openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
434 lines (433 loc) • 19.9 kB
JavaScript
import { C as resolveIsNixMode, S as resolveIsConfigReadOnly } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { a as resolveUpdateRehearsalRoot } from "./update-rehearsal-paths-Dr1MbUA_.mjs";
import { _ as recordUpdateDoctorConfigMigration, m as getUpdateDoctorConfigWriteAuthority, x as runUpdateDoctorIncludeWrite, y as recordUpdateDoctorConfigWriteRefusal } from "./update-doctor-result-DwaI51On.mjs";
import { t as ConfigWritePostCommitError } from "./io.write-errors-CuPAqPbq.mjs";
import { g as shouldSkipLegacyUpdateDoctorConfigWrite } from "./update-phase-YdZvaQsy.mjs";
import { i as recordUpdateModelRetirement } from "./update-deferred-model-retirement-Czgbuzcr.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { a as resolveLegacyParentVersionOverride, n as noteDoctorRepairResult, r as resolveDoctorMode, t as isUpdateDoctorRun } from "./doctor-health-contribution-utils-vPLdl3Wb.mjs";
import fs from "node:fs";
import path from "node:path";
//#region src/flows/doctor-health-contribution-runners.config.ts
/** Removes queued retired profiles after any config references have been durably repaired. */
async function runRetiredAuthProfileCleanup(e) {
if (e.externalConfigRepairsPending) return;
const t = e.configResult.retiredAuthProfileCleanupPlans;
if (!t?.length) return;
const { removeAuthProfilesAcrossOwnerStores: n } = await import("./auth-profiles-UUzo-h8d.mjs");
for (const r of t) if (!await n({
...r,
cfg: e.cfg
})) throw new Error(`Failed to remove retired auth profile "${r.profileIds.join(", ")}".`);
delete e.configResult.retiredAuthProfileCleanupPlans;
}
/** Returns false when persistence was refused or skipped, without authorizing dependent work. */
async function runWriteConfigHealth(e, t = {}) {
if (e.configWriteError) throw e.configWriteError;
if (e.configWriteRefusal) return false;
const { applyWizardMetadata: n } = await import("./onboard-helpers-Cy-Vj-Pl.mjs");
const { copyConfigResolutionFactsThroughRewrite: r } = await import("./resolution-facts-DHQgJtdf.mjs");
const { ConfigMutationConflictError: i, readConfigFileSnapshot: a, transformConfigFile: o } = await import("./config/config.js");
const { collectChangedConfigPaths: s } = await import("./include-write-boundary-D5uYLBzb.mjs");
const { hashConfigRaw: c } = await import("./io.read-helpers-CZfTtz4H.mjs");
const { resolveConfigIncludeWriteBoundary: l } = await import("./mutate-BsBv3lKT.mjs");
const { isDeepStrictEqual: u } = await import("node:util");
const { getDeferredPluginMigrationConfigFacts: d, preserveDeferredPluginMigrationConfig: f } = await import("./deferred-plugin-migration-config-DDq2yGEH.mjs");
const { createSubsystemLogger: p } = await import("./subsystem-DbE05_DO.mjs");
const { recordDoctorHealthWarnings: m } = await import("./doctor-health-contribution-DcYXhJzj.mjs");
const { logConfigUpdated: h } = await import("./logging-Cv8P6EfM.mjs");
const { shortenHomePath: g } = await import("./utils-C6VO5Omq.mjs");
const _ = e.configResult.providerRenames ?? [];
const v = e.prompter.shouldRepair && _.length > 0;
const y = e.configResult.shouldWriteConfig === true && e.configResultWriteCommitted !== true || v;
const b = y || JSON.stringify(e.cfg) !== JSON.stringify(e.cfgForPersistence);
if (resolveIsConfigReadOnly(e.env ?? process.env)) {
if (b) {
const { reportDoctorExternalConfigRepairs: t } = await import("./doctor-external-config-BK-VJ9py.mjs");
await t(e);
return false;
}
if (e.externalConfigRepairsPending) return false;
}
if (b && shouldSkipLegacyUpdateDoctorConfigWrite(e.env ?? process.env)) {
e.runtime.log("Skipping doctor config write during legacy update handoff.");
return false;
}
if (v) {
const { maybeRepairCodexSessionRoutes: t } = await import("./codex-route-session-repair-DfolbhV4.mjs");
const { maybeRepairProviderRenameCronJobs: n } = await import("./provider-rename-state-CRhNIABN.mjs");
const { applyProviderRenames: i } = await import("./provider-rename-B6o_jaBC.mjs");
const a = await n({
renames: _,
env: e.env
});
noteDoctorRepairResult(a);
const o = await t({
cfg: e.cfg,
providerRenames: _,
providerRenameOnly: true,
env: e.env,
shouldRepair: true
});
noteDoctorRepairResult(o);
if (a.warnings.length > 0 || o.warnings.length > 0) throw new Error("Provider references could not be fully repaired. Config was preserved; rerun openclaw doctor --fix.");
const s = i(e.cfg, _);
r(e.cfg, s.config);
e.cfg = s.config;
if (s.changes.length > 0) e.configResult.pendingChangePanels = [...e.configResult.pendingChangePanels ?? [], s.changes.join("\n")];
}
if (b) {
const t = isUpdateDoctorRun(e.env ?? process.env);
const { readDeferredPluginMigrationsAsync: _ } = await import("./deferred-plugin-migrations-D0dr-2ek.mjs");
const b = await _({ env: e.env ?? process.env });
const { restoreDoctorConfigEnvRefs: x } = await import("./config-flow-steps-CFNYG-Na.mjs");
const { prepareDoctorConfigWriteStage: S } = await import("./roster-include-write-THWSuUP_.mjs");
let C = y ? await a({
observe: false,
skipPluginValidation: true,
deferredPluginMigrations: b
}) : void 0;
let w = C ? S({
snapshot: C,
nextConfig: x(e.cfg, e.configResult.referenceSource, e.configResult.explicitSetPaths),
persistCanonicalAgentRoster: e.configResult.persistCanonicalAgentRoster,
installedPluginIdRecovery: e.configResult.referenceSource?.installedPluginIdRecovery,
explicitSetPaths: e.configResult.explicitSetPaths
}) : void 0;
if (w) e.configResult.skipWizardMetadataForIncludeWrite = true;
if (e.configResult.skipWizardMetadataForIncludeWrite !== true && !resolveUpdateRehearsalRoot(e.env ?? process.env)) {
const t = n(e.cfg, {
command: "doctor",
mode: resolveDoctorMode(e.cfg)
});
r(e.cfg, t);
e.cfg = t;
}
const T = resolveLegacyParentVersionOverride(e).lastTouchedVersionOverride;
const { findRetiredConfigUpgradeRequirement: E } = await import("./retired-config-formats-DgKRo6lW.mjs");
const { assertInstalledPluginIdRecoveryCurrent: D } = await import("./installed-plugin-id-recovery-CD-455PV.mjs");
const O = e.configResult.referenceSource?.installedPluginIdRecovery;
let k;
let A = false;
try {
while (w && C) {
const t = w;
const n = {
...e,
cfg: t.config,
cfgForPersistence: C.sourceConfig,
configResultWriteCommitted: false,
configResult: {
cfg: t.config,
shouldWriteConfig: true,
confirmedConfigSource: e.configResult.confirmedConfigSource,
referenceSource: e.configResult.referenceSource,
persistCanonicalAgentRoster: t.persistCanonicalAgentRoster,
skipWizardMetadataForIncludeWrite: true,
skipPluginValidationOnWrite: t.persistCanonicalAgentRoster || e.configResult.skipPluginValidationOnWrite,
preservedLegacyRootKeys: e.configResult.preservedLegacyRootKeys,
explicitSetPaths: e.configResult.explicitSetPaths?.filter(([e]) => !t.persistCanonicalAgentRoster || e === "agents")
}
};
try {
if (!await runWriteConfigHealth(n, { runPostWriteRepairs: false })) {
e.configWriteRefusal = n.configWriteRefusal;
return false;
}
} finally {
if (n.configWriteError) e.configWriteError = n.configWriteError;
if (n.configResultWriteCommitted) {
e.configResult.confirmedConfigSource = n.configResult.confirmedConfigSource;
e.cfgForPersistence = n.cfgForPersistence;
if (t.persistCanonicalAgentRoster) delete e.configResult.persistCanonicalAgentRoster;
A = true;
}
}
const r = "Saved a config migration stage; remaining repairs are still pending.";
recordUpdateDoctorConfigMigration(r);
e.runtime.log(r);
const o = await a({
observe: false,
skipPluginValidation: true,
deferredPluginMigrations: b
});
if (o.path !== e.configResult.confirmedConfigSource?.path || o.hash !== e.configResult.confirmedConfigSource?.hash) throw new i("config changed after Doctor saved a migration stage", { retryable: false });
const { cloneConfigWithResolutionFacts: s } = await import("./resolution-facts-DHQgJtdf.mjs");
const { getConfigValueAtPath: c, setConfigValueAtPath: l } = await import("./config-paths-CwRvBcpZ.mjs");
const u = e.cfg;
e.cfg = s(o.sourceConfig);
for (const n of t.remainingPaths) l(e.cfg, n, c(u, n));
C = o;
w = S({
snapshot: o,
nextConfig: e.cfg,
persistCanonicalAgentRoster: e.configResult.persistCanonicalAgentRoster,
installedPluginIdRecovery: O,
explicitSetPaths: e.configResult.explicitSetPaths
});
}
const n = e.configResult.confirmedConfigSource;
if (!n?.hash) throw new i("Doctor config write has no source revision", { retryable: false });
const { path: r, hash: d } = n;
const f = x(e.cfg, e.configResult.referenceSource, e.configResult.explicitSetPaths);
const h = getUpdateDoctorConfigWriteAuthority(e.configPath);
const g = h ? await a({
skipPluginValidation: t,
observe: false,
deferredPluginMigrations: b
}) : void 0;
const resolveIncludeBoundary = (t) => l({
snapshot: t,
nextConfig: f,
persistCanonicalAgentRoster: y ? e.configResult.persistCanonicalAgentRoster : void 0,
explicitSetPaths: e.configResult.explicitSetPaths
});
const _ = g && resolveIncludeBoundary(g);
const v = _ ? g : void 0;
let j = e.cfg;
const persistConfig = (n) => {
const assertCurrent = () => {
h?.assertCurrent();
n?.();
};
return o({
baseHash: d,
transform: async (t, { snapshot: r }) => {
n?.();
h?.assertCurrent();
const a = E(r.sourceConfigBeforeMigrations ?? r.sourceConfig);
if (a) throw new i(`${a.message} ${a.nextAction}`);
j = r.sourceConfig;
await D(j, O, e.env ?? process.env);
assertCurrent();
if (_) {
const e = resolveIncludeBoundary(r);
if (!u(e, _)) throw new i("included config changed after Doctor prepared its repairs", { retryable: false });
}
const { repairLegacyCronOwnersBeforeConfigWrite: o } = await import("./legacy-owner-Dn06vY8k.mjs");
const s = await o({
snapshot: r,
nextConfig: f,
env: e.env ?? process.env,
assertCurrent
});
for (const t of s) e.runtime.log(t);
return { nextConfig: f };
},
afterWrite: { mode: "auto" },
writeOptions: {
deferredPluginMigrations: b,
assertCurrent,
...O?.size ? { beforeCommit: async () => {
assertCurrent();
await D(j, O, e.env ?? process.env);
assertCurrent();
} } : {},
expectedConfigPath: r,
auditOrigin: "doctor",
allowConfigSizeDrop: e.configResult.shouldWriteConfig === true || t,
skipPluginValidation: e.configResult.skipPluginValidationOnWrite === true || t,
...e.configResult.explicitSetPaths ? { explicitSetPaths: e.configResult.explicitSetPaths } : {},
persistCanonicalAgentRoster: y ? e.configResult.persistCanonicalAgentRoster : void 0,
preservedLegacyRootKeys: e.configResult.preservedLegacyRootKeys,
...T ? { lastTouchedVersionOverride: T } : {}
}
});
};
const writeConfig = async () => {
if (!O?.size) return await persistConfig();
const { withPluginLifecycleLease: t } = await import("./plugin-lifecycle-lease-B1cHoIkh.mjs");
return await t({
env: e.env ?? process.env,
assertCurrent: () => h?.assertCurrent()
}, (e) => persistConfig(() => e.assertOwned()));
};
if (v) {
const t = [...new Set(s(v.sourceConfig, e.cfg).paths.flatMap(([e]) => e === void 0 ? [] : [e]))].toSorted();
k = await runUpdateDoctorIncludeWrite(v.path, c(v.raw), async () => {
const n = `Doctor include-owned keys ${t.join(", ")}: promotion unavailable for include-owned configuration.`;
m(e, [], [n]);
p("update").warn(n);
e.runtime.log(n);
return await writeConfig();
});
} else k = await writeConfig();
} catch (t) {
if (t instanceof ConfigWritePostCommitError) {
e.configWriteError = t;
if (t.publication === "partial") delete e.configResult.confirmedConfigSource;
throw t;
}
recordUpdateDoctorConfigWriteRefusal({
reason: "config-write-refused",
message: formatErrorMessage(t),
keys: []
});
if (t instanceof i) {
note(["The config changed after Doctor prepared these repairs.", A ? "Earlier config fixes were saved; the remaining fixes were not written. Rerun \"openclaw doctor\" to review the current config." : "These config fixes were not written. Rerun \"openclaw doctor\" to review repairs for the current config."].join("\n"), "Doctor warnings");
e.configWriteRefusal = "config-conflict";
return false;
}
const { isConfigIncludeOwnershipError: n, isConfigValidationFailedError: r } = await import("./io.write-errors-CFzAuYZT.mjs");
const a = e.configResultWriteCommitted === true || A ? "Earlier config fixes were already saved; the remaining changes were not written." : "No config changes were written.";
if (n(t)) {
const n = t.includeTargets ?? [];
const r = n.length === 0 ? "its included file" : `the included ${n.length === 1 ? "file" : "files"} ${n.join(", ")}`;
note([`Doctor could not apply config fixes: ${t.message}`, `${a} Repair ${t.ownedConfigPath} in ${r} by hand, then rerun "openclaw doctor --fix" for the remaining changes.`].join("\n"), "Doctor warnings");
e.configWriteRefusal = "include-ownership";
return false;
}
if (r(t)) {
const { formatConfigIssueLines: n } = await import("./issue-format-U_pi1HLf.mjs");
const r = n(t.issues, "-", { normalizeRoot: true });
note([
"Doctor could not apply config fixes: the repaired config still fails validation.",
...r,
`${a} Fix the value(s) above in ${g(e.configPath)} by hand, then rerun "openclaw doctor --fix".`
].join("\n"), "Doctor warnings");
e.configWriteRefusal = "validation";
return false;
}
const { isCronOwnerWriteRefusalError: o } = await import("./io.cron-owner-refusal-BB6wnOG2.mjs");
if (!o(t)) throw t;
note([
t.message,
A ? "Earlier config fixes were saved; the remaining config repairs were not written." : "Doctor left the config unchanged, preserving any retained legacy owner for a later repair.",
"Resolve the reported Gateway or cron-store condition, then rerun \"openclaw doctor --fix\"."
].join("\n"), "Doctor warnings");
e.configWriteRefusal = "cron-owner-safety";
return false;
}
e.configResult.confirmedConfigSource = {
path: k.path,
hash: k.persistedHash
};
const j = e.configResult.pendingChangePanels;
if (j?.length) {
for (const e of j) {
note(e, "Doctor changes");
for (const t of e.split("\n")) recordUpdateDoctorConfigMigration(t);
}
delete e.configResult.pendingChangePanels;
}
e.cfgForPersistence = structuredClone(f({
sourceConfig: k.nextConfig,
nextConfig: e.cfg,
pending: d(k.nextConfig) ?? []
}));
if (e.configResult.shouldWriteConfig === true || v) e.configResultWriteCommitted = true;
delete e.configResult.providerRenames;
h(e.runtime);
const M = `${e.configPath}.pre-update`;
if (t && fs.existsSync(M)) e.runtime.log(`Update changed config; pre-update backup: ${g(M)}`);
}
if (e.configResult.modelRetirementRepairRan === true) {
recordUpdateModelRetirement("completed", e.env ?? process.env);
delete e.configResult.modelRetirementRepairRan;
}
const x = e.configResult.modelBillingRouteWarnings;
if (x?.length) {
const t = p("doctor");
note(x.join("\n"), "Billing route changes");
for (const e of x) t.warn(e);
m(e, [], x);
delete e.configResult.modelBillingRouteWarnings;
}
if (t.runPostWriteRepairs === false) return true;
await runRetiredAuthProfileCleanup(e);
if (e.configResult.retiredPhoneControlStateCleanupPending === true) {
const { finalizeRetiredPhoneControlCleanup: t } = await import("./doctor-retired-phone-control-QzEa0osy.mjs");
const n = await t({ env: e.env ?? process.env });
noteDoctorRepairResult(n);
}
if (!e.prompter.shouldRepair && !e.configResult.openAICodexAuthProfileIdMap?.size && e.configResult.shouldRepairCronCodexModelRefsAfterConfigWrite !== true || e.postConfigWriteRepairsCommitted === true) return true;
const { repairCronCodexModelRefsAfterConfigWrite: S } = await import("./legacy-repair-CjiRGSBz.mjs");
const C = await S({
cfg: e.cfg,
migrateCodexModelRefs: e.prompter.shouldRepair || e.configResult.shouldRepairCronCodexModelRefsAfterConfigWrite === true,
...e.configResult.retiredModelRefConfig ? { retiredModelRefConfig: e.configResult.retiredModelRefConfig } : {},
repairRetiredModelRefs: e.prompter.shouldRepair,
modelReplacements: e.options.modelReplacements,
authProfileIdMap: e.configResult.openAICodexAuthProfileIdMap,
...e.configResult.blockedCodexModelIdentities?.length ? { blockedModelIdentities: new Set(e.configResult.blockedCodexModelIdentities) } : {}
});
e.postConfigWriteRepairsCommitted = true;
noteDoctorRepairResult(C);
return true;
}
/** Commits the finalized config-flow candidate before fallible health diagnostics start. */
async function runInitialConfigWriteHealth(e) {
if (e.configResult.shouldWriteConfig !== true && !e.configResult.modelBillingRouteWarnings?.length && e.configResult.modelRetirementRepairRan !== true && !e.configResult.providerRenames?.length) return;
await runWriteConfigHealth(e, { runPostWriteRepairs: false });
}
async function collectWriteConfigHealthFindings(e) {
const t = [];
const n = e.configPath;
const r = resolveIsNixMode(process.env);
if (resolveIsConfigReadOnly(process.env)) t.push({
checkId: "core/doctor/write-config",
severity: "warning",
message: r ? "Doctor config writes are disabled because OpenClaw is running in Nix mode." : "Doctor config writes are disabled because config is externally managed.",
...n ? { path: n } : {},
requirement: "mutable-config-write-path",
fixHint: r ? "Edit the Nix source for this install and rebuild; do not run doctor --fix against this config file." : "Apply reported config edits in your external deployment source and redeploy; doctor --fix still repairs writable runtime state."
});
if (!n) return t;
const i = path.dirname(n);
const a = fs.existsSync(n);
const o = a ? i : findNearestExistingParent(i);
if (!isDirectoryPath(o)) {
t.push({
checkId: "core/doctor/write-config",
severity: "warning",
message: "Doctor cannot create the config directory because a path component is a file.",
path: o,
target: i,
requirement: "config-directory-path",
fixHint: "Move the file blocking the config directory path before running doctor --fix."
});
return t;
}
try {
fs.accessSync(o, fs.constants.W_OK | fs.constants.X_OK);
} catch {
t.push({
checkId: "core/doctor/write-config",
severity: "warning",
message: a ? "Doctor cannot write config because the config directory is not writable." : "Doctor cannot create the config directory because the nearest existing parent is not writable.",
path: o,
target: a ? n : i,
requirement: "writable-config-directory",
fixHint: "Make the existing config directory or parent directory writable before running doctor --fix."
});
}
return t;
}
function findNearestExistingParent(e) {
let t = e;
while (!pathEntryExists(t)) {
const e = path.dirname(t);
if (e === t) return t;
t = e;
}
return t;
}
function pathEntryExists(e) {
if (fs.existsSync(e)) return true;
try {
fs.lstatSync(e);
return true;
} catch {
return false;
}
}
function isDirectoryPath(e) {
try {
return fs.statSync(e).isDirectory();
} catch {
return false;
}
}
//#endregion
export { runWriteConfigHealth as i, runInitialConfigWriteHealth as n, runRetiredAuthProfileCleanup as r, collectWriteConfigHealthFindings as t };