openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2,142 lines • 90.7 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs";
import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { a as coerceSecretRef, h as parseLegacySecretRefEnvMarker, l as isLegacySecretRefWithoutProvider, s as hasLegacySecretRefExtraFields } from "./types.secrets-BmNLLnHp.mjs";
import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { S as resolveIsConfigReadOnly, m as resolveConfigPath, t as CONFIG_PATH } from "./paths-DAcAg5aV.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { i as parseModelCatalogRef } from "./model-catalog-refs-Bk2MNoCv.mjs";
import "./session-key-CqAyZeVk.mjs";
import { t as DEFAULT_ACCOUNT_ID } from "./account-id-BqKT3GuY.mjs";
import { n as listAgentEntries, p as tryResolveSoleAgentId, s as readAgentRosterProperty } from "./agent-roster-t1ooUdXp.mjs";
import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { r as withArtifactPreservingStateReads } from "./artifact-preserving-state-reads-BfhmBr-V.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { i as hasCommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { a as resolveUpdateRehearsalRoot } from "./update-rehearsal-paths-Dr1MbUA_.mjs";
import { r as cloneEnvWithPlatformSemantics, y as resolveFutureConfigActionBlock } from "./config-env-vars-ByeGN-9N.mjs";
import { g as withOpenClawStateDatabaseReadSnapshot } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { t as normalizePluginPolicyId } from "./plugin-policy-id-CkilMowp.mjs";
import { u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs";
import { v as setActiveDegradedPlugins } from "./discovery-availability-DtlJ7XvT.mjs";
import { n as cloneConfigWithResolutionFacts, o as copyConfigResolutionFactsThroughRewrite } from "./resolution-facts-xaIKuREs.mjs";
import { r as getOfficialExternalPluginCatalogEntry } from "./official-external-plugin-catalog-DtkWz1Xo.mjs";
import { i as loadInstalledPluginIndexInstallRecordsSync } from "./installed-plugin-index-record-reader-B-7uGQZ9.mjs";
import { o as getOfficialExternalPluginCatalogManifest } from "./official-external-plugin-catalog-source-4o5oPhVN.mjs";
import { m as resolveNormalizedProviderModelMaxTokens } from "./validation-core-1Fx8ByEb.mjs";
import { i as hashConfigRaw } from "./io.read-helpers-qAcqsRC0.mjs";
import { p as assertOpenClawStateWriteAllowedAtPath } from "./openclaw-state-db-ARhwdPJg.mjs";
import { t as ensureOpenClawStatePermissions } from "./openclaw-state-db-permissions-yFUWKbh-.mjs";
import { p as readRecentConfigAuditRecords } from "./io.audit-Bump5vFv.mjs";
import { m as assertBaseSnapshotStillCurrent, r as withConfigSourceLocks } from "./write-lock-Bg9nHsHM.mjs";
import { E as setAppliedRuntimeConfigSnapshot } from "./runtime-snapshot-WbwbY5b7.mjs";
import { t as getConfigValueAtPath } from "./config-paths-DTAbnrwT.mjs";
import { t as splitTrailingAuthProfile } from "./model-ref-profile-C7DWqVP0.mjs";
import { t as ConfigMutationConflictError } from "./mutation-conflict-Bs0nsNWn.mjs";
import { i as passesManifestOwnerBasePolicy } from "./manifest-owner-policy-B8Brw4Zo.mjs";
import { n as loadPluginManifestRegistryForPluginRegistry } from "./plugin-registry-contributions-iAw3gSDD.mjs";
import { d as recordDeferredPluginMigrations, i as mergeDeferredPluginMigration, l as readDeferredPluginMigrations, r as formatDeferredPluginMigration, t as DeferredPluginMigrationConflictError } from "./deferred-plugin-migrations-C_CU0aKR.mjs";
import { r as hasDeferredPluginMigrationConfig, s as resolveDeferredPluginMigrationConfigPaths } from "./deferred-plugin-migration-config-B3TJC-SY.mjs";
import { r as LEGACY_AGENT_ROSTER_RULES, s as findLegacyConfigRuleIssues } from "./legacy-tools-by-sender-Cj1HdJFy.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { i as tryGetLegacyDefaultAgentId, r as retainLegacyDefaultAgentId, t as inheritLegacyDefaultAgentId } from "./legacy.default-agent-owner-DpmHgK0A.mjs";
import { r as resolveLegacyAgentRosterOwner } from "./legacy.roster-BcYJITMZ.mjs";
import { a as visitAgentEntries } from "./legacy-config-record-shared-D3vIaBh9.mjs";
import { a as runPluginSetupConfigMigrations } from "./setup-registry-CgyZCdrJ.mjs";
import "./plugin-registry-BrQav-kR.mjs";
import { r as resolveModelRuntimePolicy } from "./model-runtime-policy-Cfudvy7O.mjs";
import { i as setPathExistingStrict } from "./path-utils-A4pcYa4R.mjs";
import { n as discoverConfigSecretTargets } from "./target-registry-query-le6rMGHo.mjs";
import "./target-registry-C0PdHjLu.mjs";
import { t as createConfigIO } from "./io.factory-DEa_bi2j.mjs";
import "./env-vars-DN2VAsXE.mjs";
import { n as UPDATE_ENVIRONMENT_FAILURE_REASONS, t as UPDATE_ACTIVATION_TIMEOUT_REASON } from "./update-outcome-PIWCovC4.mjs";
import { t as configIncludeOwnsAgentRoster } from "./agent-roster-provenance-DiT1dDed.mjs";
import { _ as listAgentDatabaseAdmissionRefusals, d as evaluateAgentDatabaseAdmissions, i as canIsolateAgentDatabase, w as recordAgentDatabaseAdmissions } from "./agent-database-admission-CL6wHJ_N.mjs";
import { n as getAgentDatabaseStartupAdmission } from "./agent-database-startup-C_V1xkCB.mjs";
import { o as withPluginLifecycleLease } from "./plugin-lifecycle-lease-CXjHGDEI.mjs";
import "./installed-plugin-index-records-MNCNSlg8.mjs";
import { t as DEFAULT_GOOGLE_API_BASE_URL } from "./google-api-base-url-DccJuq-N.mjs";
import { g as shouldSkipLegacyUpdateDoctorConfigWrite, h as shouldDeferConfiguredPluginInstallRepair } from "./update-phase-YdZvaQsy.mjs";
import { p as resolvePluginDoctorProviderRenames } from "./doctor-contract-registry-CFzLZXmq.mjs";
import { c as throwIfDoctorStateMigrationRefused, t as DoctorStateMigrationRefusalError } from "./state-migrations.messages-CNB52OxC.mjs";
import { t as readRetiredDeferredUpdateWarnings } from "./deferred-update-warnings-DS2enkMR.mjs";
import { t as formatDoctorProgressPhase } from "./doctor-progress-C3vWlya1.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { n as emitDoctorRepairSequenceNotes, r as sanitizeDoctorNote, t as emitDoctorNotes } from "./emit-notes-llcc2fq-.mjs";
import { a as migrateLegacyConfig, c as noteImplicitFallbackClobberWarnings, d as noteMissingDefaultAgentOwner, f as noteOpencodeProviderOverrides, l as noteMcpOriginWarning, n as applyRetiredConfigStep, o as noteDoctorConfigPreflightIssues, p as noteSandboxOriginProxyWarning, r as prepareDoctorConfigReferenceSource, s as noteDoctorHookConfigWarnings, t as applyLegacyCompatibilityStep, u as noteMediaCliModelWarnings } from "./config-flow-steps-ETwvCUK9.mjs";
import { t as applyDoctorConfigMutation } from "./config-mutation-state-C7DKFhoa.mjs";
import { n as applyChannelDoctorCompatibilityMigrations } from "./channel-legacy-config-migrate-DVMnZ4Sy.mjs";
import { t as listDoctorConfiguredChannelIds } from "./configured-channel-ids-4FVS0H72.mjs";
import { d as migrateLegacyWebSearchConfig, f as migrateLegacyXSearchConfig, l as stripRetiredTuningKnobs, o as normalizeLegacyTalkConfig, u as migrateLegacyWebFetchConfig } from "./legacy-config-migrations-8hb5BL3G.mjs";
import { i as isBlockedLegacyCodexModelRef } from "./codex-route-model-ref-BdQcEGbo.mjs";
import { a as rewriteModelRefs, c as normalizeKnownModelRef, r as mergeModelRefMapEntries } from "./legacy-config-migrations.runtime.models.refs-CDWmXREu.mjs";
import { i as isLegacyModelsAddCodexMetadataModel, n as modelEntryWithRuntimePolicy } from "./legacy-config-migrations.runtime.models-DVGtmnPu.mjs";
import { n as planProviderRenames } from "./provider-rename-DQduEyIE.mjs";
import { n as commitAutomaticConfigRepair, r as planAutomaticConfigRepair, t as canPlanAutomaticConfigRepair } from "./automatic-config-repair-BMcsN3sp.mjs";
import { i as loadSetupChannelPluginFromManifestRecord } from "./read-only-idsFCBWl.mjs";
import { a as migrateLegacyCommandOwners } from "./doctor-command-owner-Dul2IrrD.mjs";
import { t as pruneBindingsForMissingAgents } from "./legacy-config-binding-repair-lhCH1nBd.mjs";
import { t as createPluginCapabilityConsentPrompter } from "./plugin-capability-consent-jChdL17s.mjs";
import { t as resolveSingleAccountPromotion } from "./setup-promotion-helpers-egMFKyzE.mjs";
import { r as cronCodexRuntimePolicyTargetKey } from "./store-migration-CzntnWoE.mjs";
import { t as describeConfigSnapshotInputChange } from "./snapshot-inputs-BaF0a6H7.mjs";
import { t as LegacyHeartbeatSchema } from "./doctor-heartbeat-legacy-DmzlheVU.mjs";
import { t as noteDoctorMigrationResult } from "./doctor-migration-notes-BBiomgyk.mjs";
import { n as resolveDoctorRepairMode } from "./doctor-repair-mode-D2HKy2yZ.mjs";
import { f as withDoctorProgress } from "./doctor-health-startup-KiSUu3WC.mjs";
import { a as measureDoctorConfigPreflightStep, t as createConfigPreflightSnapshotReader } from "./config-preflight-snapshot-DOQjWd7q.mjs";
import { n as prepareDoctorConfigRecovery, t as migrateLegacyDoctorConfig } from "./doctor-config-preflight-legacy-config-MGYWYBIt.mjs";
import { t as inspectPluginMigrationAvailability } from "./plugin-migration-availability-DPD6BwfD.mjs";
import { n as runDoctorPluginConvergence } from "./doctor-config-preflight-plugin-verification-B0Vcrtkl.mjs";
import { t as assertDoctorRetiredStateAdmission } from "./doctor-retired-state-admission-8ZZiSC8i.mjs";
import { t as createDoctorPluginMetadataSnapshotScope } from "./plugin-metadata-snapshot-scope-xMC7kccE.mjs";
import { n as createWorkspaceAliasMigrationRepair } from "./doctor-workspace-alias-ZXxD9zqZ.mjs";
import { t as migrateLegacyRuntimeModelRef } from "./legacy-runtime-model-providers-BEx2pev8.mjs";
import { t as canWriteDoctorInclude } from "./roster-include-write-DAz4Iib7.mjs";
import fs, { existsSync } from "node:fs";
import path from "node:path";
import { homedir } from "node:os";
import { isDeepStrictEqual } from "node:util";
//#region src/commands/doctor-config-preflight-migrations.ts
async function assertDoctorPreflightMigrationsComplete(e) {
const t = e.stepReceipts.filter((e) => e.outcome === "refused" && (e.refusal?.code === "agent-database-ownership-mismatch" || e.refusal?.code === "blocked-by-agent-database-refusal") && e.refusedAgentDatabasePaths?.length);
const n = t.length > 0 ? getAgentDatabaseStartupAdmission() ? listAgentDatabaseAdmissionRefusals() : await evaluateAgentDatabaseAdmissions(e.cfg) : [];
if (t.length > 0) recordAgentDatabaseAdmissions(n);
const r = new Set(n.filter((t) => t.code !== "agent-database-ownership-mismatch" || canIsolateAgentDatabase(e.cfg, t.agentId)).flatMap((e) => e.paths.map((e) => path.resolve(e))));
for (const e of t) if (e.refusedAgentDatabasePaths?.every((e) => r.has(path.resolve(e)))) e.outcome = "warning";
try {
throwIfDoctorStateMigrationRefused(e.stepReceipts);
} catch (t) {
if (t instanceof DoctorStateMigrationRefusalError) {
const { assertConfiguredWorkspaceStateReady: t } = await import("./workspace-state-dirs-H0UukwV6.mjs");
try {
await t({
cfg: e.cfg,
operation: "doctor"
});
} catch (t) {
e.report({
changes: [],
warnings: [String(t)]
});
}
}
throw t;
}
}
//#endregion
//#region src/commands/doctor-config-preflight-plugin-migrations.ts
/** One preflight retains unavailable owners until their migration reports completion. */
function createDoctorPluginMigrationPreparation(e) {
const shouldDeferInstallation = () => Boolean(resolveUpdateRehearsalRoot(e.env())) || shouldDeferConfiguredPluginInstallRepair(e.env());
const t = /* @__PURE__ */ new Map();
const matchesOwner = (e, t) => normalizePluginPolicyId(e) === normalizePluginPolicyId(t);
const hasOwner = (e, t) => [...e].some((e) => matchesOwner(e, t));
const previousOwner = (e) => [...t.values()].find((t) => matchesOwner(t.pluginId, e));
let n = [];
let r = [];
let i = false;
let a = false;
const loadPrevious = async (t) => {
if (a) return;
const i = cloneEnvWithPlatformSemantics(e.env());
if (!(t?.exists ?? existsSync(resolveConfigPath(i)))) return;
n = await withArtifactPreservingStateReads(() => withOpenClawStateDatabaseReadSnapshot(async () => {
r = structuredClone(readDeferredPluginMigrations({ env: i }));
return readDeferredPluginMigrations({
env: i,
includeDeferred: true
});
}, { env: i }));
remember();
a = true;
};
let o = false;
const s = /* @__PURE__ */ new Set();
const c = /* @__PURE__ */ new Map();
let l = /* @__PURE__ */ new Map();
let u = /* @__PURE__ */ new Set();
let d = /* @__PURE__ */ new Set();
let f = /* @__PURE__ */ new Set();
let p = /* @__PURE__ */ new Set();
let m = {};
let h;
const g = /* @__PURE__ */ new Set();
const requirePlugins = (e, n) => {
for (const r of e) {
const e = previousOwner(r);
if (e) t.set(e.pluginId, {
...e,
[n]: true
});
}
};
const learn = (e) => {
if (!e) return;
l = new Map(e.statelessPlugins.map(({ id: e, version: t }) => [e, t]));
u = new Set(e.runtimePluginAliases);
d = new Set(e.unavailablePluginIds);
f = new Set(e.discoveryBlockedPluginIds);
p = new Set(e.inactivePluginIds);
m = e.replacementPluginIds ?? {};
requirePlugins(e.requiredPluginIds, "requiresStateMigration");
requirePlugins(e.inspectionRequiredPluginIds, "requiresDoctorInspection");
};
const retain = (e) => {
const t = previousOwner(e.pluginId);
return mergeDeferredPluginMigration(t, t ? {
...e,
pluginId: t.pluginId
} : e);
};
const remember = () => {
for (const e of n) t.set(e.pluginId, e);
};
const prepare = async (r) => {
h = r;
await loadPrevious(r);
if (!r.exists) return [...t.values()];
if (!o && e.enabled) {
const i = await inspectPluginMigrationAvailability({
cfg: r.sourceConfig,
env: e.env(),
retainedPluginIds: [...t.keys()],
deferInstallation: shouldDeferInstallation()
});
learn(i);
n = i.pending.map(retain);
remember();
o = true;
}
return [...t.values()];
};
const reportPending = (t) => {
const n = formatDeferredPluginMigration(t, e.env());
const r = c.get(t.pluginId);
if (r?.warnings[0] === n) return;
e.report({
changes: [],
warnings: [n],
warningDisposition: "recoverable",
outcome: "deferred"
});
if (r) {
r.warnings = [n];
return;
}
const i = {
id: `plugin:${t.pluginId}`,
phase: "final",
source: [{
kind: "owner",
id: t.pluginId
}],
target: [{
kind: "owner",
id: t.pluginId
}],
requiredness: "conditional",
reversibility: "checkpoint-required",
outcome: "deferred",
changes: [],
warnings: [n]
};
c.set(t.pluginId, i);
e.recordReceipt(i);
};
const persistPending = async (a, o, c) => {
try {
const t = await recordDeferredPluginMigrations({
env: e.env(),
pending: a,
...o ? { resolvedPluginIds: o } : {},
...c ? { settlements: c } : {},
expectedPending: r
});
if (t) r = structuredClone(t);
return true;
} catch (e) {
if (!(e instanceof DeferredPluginMigrationConflictError)) throw e;
r = structuredClone(e.pending);
t.clear();
n = e.pending;
s.clear();
l.clear();
u.clear();
d.clear();
f.clear();
p.clear();
m = {};
g.clear();
i = true;
for (const e of n) {
t.set(e.pluginId, e);
reportPending(e);
}
return false;
}
};
return {
deferred: () => n,
retainedPluginIds: () => [...t.keys()],
prepare,
snapshotOptions: async () => {
await loadPrevious();
return {
preparePluginMigrations: !o && e.enabled ? prepare : void 0,
deferredPluginMigrations: [...t.values()]
};
},
async migrate(t) {
const { autoMigrateLegacyPluginDoctorState: n } = await import("./state-migrations.plugin-doctor-xLiL_YjC.mjs");
e.report(await e.measure("plugin-doctor-migrations", () => e.runWithPluginMetadataSnapshot({ config: t }, () => n({
config: t,
env: e.env(),
integrityCheck: e.integrityCheck,
...e.doctorOnlyStateMigrations ? { doctorOnlyStateMigrations: true } : {}
}))));
},
async converged(e, r, i, a) {
h = r;
learn(a);
n = e.map((e) => retain(Object.assign(resolveDeferredPluginMigrationConfigPaths({
config: r.sourceConfigBeforeMigrations ?? r.sourceConfig,
pluginId: e.pluginId,
compatibilityMigrationPaths: i?.plugins.find((t) => matchesOwner(t.id, e.pluginId))?.configContracts?.compatibilityMigrationPaths
}), e)));
remember();
if (!await persistPending([...t.values()])) return;
for (const e of n) reportPending(e);
},
observe(e) {
requirePlugins(e.requiredPluginIds ?? [], "requiresStateMigration");
for (const t of e.statelessPluginIds ?? []) g.add(t);
for (const t of e.completedPluginIds ?? []) s.add(t);
},
async complete() {
if (!e.enabled) return false;
const a = new Set(n.map((e) => e.pluginId));
const o = shouldDeferInstallation();
const _ = h?.sourceConfigBeforeMigrations ?? h?.sourceConfig;
const v = [];
const y = [];
const b = [...t.values()].filter((e) => {
if (hasOwner(s, e.pluginId)) return true;
if (hasOwner(d, e.pluginId) && h?.valid && _ && !o && !hasDeferredPluginMigrationConfig(_, e)) {
const t = Object.entries(m).find(([t]) => matchesOwner(t, e.pluginId))?.[1];
if (t && hasOwner(s, t)) {
v.push({
pluginId: e.pluginId,
status: "superseded",
reason: `Superseded by plugin "${t}", which completed its migration. Existing state has been kept.`
});
return true;
}
if (!(Object.entries(_.plugins?.entries ?? {}).some(([t, n]) => matchesOwner(t, e.pluginId) && n.enabled === true) && passesManifestOwnerBasePolicy({
plugin: { id: e.pluginId },
normalizedConfig: normalizePluginsConfig(_.plugins)
})) && (!e.requiresStateMigration && !e.requiresDoctorInspection || !t && hasOwner(p, e.pluginId))) {
const t = e.requiresStateMigration || e.requiresDoctorInspection;
v.push({
pluginId: e.pluginId,
status: t ? "deferred" : "completed",
reason: `${t ? "Deferred until active" : "Not applicable"}: the plugin owner is unavailable and there is no protected config to migrate. Existing state has been kept.`
});
return true;
}
}
if (e.requiresStateMigration || hasOwner(a, e.pluginId)) return false;
if (hasOwner(g, e.pluginId)) return true;
const t = [...l].find(([t]) => matchesOwner(t, e.pluginId));
if (t) {
const n = `Plugin "${e.pluginId}" version "${t[1] ?? "unknown"}": no plugin migration contract. No migration ran; existing data and settings have been kept.`;
v.push({
pluginId: e.pluginId,
status: "completed",
reason: n
});
y.push(n);
return true;
}
if (e.requiresDoctorInspection) return false;
return u.has(e.pluginId) && !e.validationExcludedPaths?.length && (e.configPaths ?? []).every((e) => e.length === 2 && e[0] === "session" && e[1] === "store");
}).map((e) => e.pluginId);
const x = new Set(b);
const S = [...t.values()].filter((e) => !x.has(e.pluginId)).map((e) => hasOwner(d, e.pluginId) && !hasOwner(f, e.pluginId) && !o ? Object.assign(e, { reason: `The migration owner is unavailable. Install or enable plugin "${e.pluginId}" to migrate its retained data and settings. For a retired plugin, ask its maintainer for a supported migration or recovery path.` }) : hasOwner(a, e.pluginId) ? e : Object.assign(e, {
reason: "The installed plugin has not confirmed that its saved data and settings are ready for this version. If Doctor cannot finish the upgrade, report this warning to the plugin maintainer.",
command: "openclaw doctor --fix"
}));
if (b.length === 0 && S.length === 0) return i;
const persist = () => persistPending(S, b, v);
let C;
if (v.length > 0 && h) {
const t = cloneEnvWithPlatformSemantics(e.env());
const { snapshot: n, writeOptions: i } = await createConfigIO({
env: t,
observe: false,
pluginValidation: "core-only",
deferredPluginMigrations: r,
shellEnvFallback: "defer"
}).readConfigFileSnapshotForWrite();
if (n.readError || describeConfigSnapshotInputChange(h, n, { compareResolvedConfig: false })) throw new ConfigMutationConflictError("Plugin migration source config changed or could not be read; rerun Doctor.");
const a = {
hashes: i.includeFileHashesForWrite ?? {},
targets: i.includeFileTargetsForWrite ?? {}
};
const assertCurrent = () => assertBaseSnapshotStillCurrent(n, resolveConfigPath(t), fs, a);
C = await withPluginLifecycleLease({
env: t,
assertCurrent
}, () => withConfigSourceLocks([n.path, ...Object.entries(a.targets).flat()], persist, t, assertCurrent));
} else C = await persist();
if (!C) return true;
for (const e of b) {
t.delete(e);
const n = c.get(e);
if (n) {
n.outcome = v.some((t) => t.pluginId === e && t.status === "deferred") ? "skipped" : "completed";
n.warnings = [];
}
}
n = n.filter((e) => !x.has(e.pluginId));
if (v.length > 0) e.report({
changes: [],
warnings: y,
warningDisposition: "recoverable",
notices: v.filter((e) => ![...l.keys()].some((t) => matchesOwner(t, e.pluginId))).map((e) => `Plugin "${e.pluginId}": ${e.reason}`)
});
for (const e of S) {
t.set(e.pluginId, e);
reportPending(e);
}
return i || b.length > 0;
}
};
}
//#endregion
//#region src/commands/doctor-config-preflight.cron.ts
/** Preserve a retired partition selector even when other config cannot drive core migrations. */
async function migrateRetainedStore(e) {
const t = retainStoreConfig(e.config);
if (!t) return;
const { repairLegacyCronStoreWithoutPrompt: n } = await e.measure("cron-repair-import", () => import("./legacy-repair-CjiRGSBz.mjs"));
e.report(await e.measure("cron-repair", () => n({
cfg: t,
migrateCodexModelRefs: false
})));
const { migrateLegacyConfigMachineState: r } = await import("./state-migrations.config-machine-state-qSiqIWBe.mjs");
e.report(r({
config: e.config,
env: e.env
}));
}
/** Restores retired cron migration inputs that canonical config migration intentionally strips. */
function withLegacyConfig(e, t) {
const n = t?.cron;
if (!n || !Object.hasOwn(n, "store") && !Object.hasOwn(n, "webhook")) return e;
return {
...e,
cron: {
...e.cron,
...Object.hasOwn(n, "store") ? { store: n.store } : {},
...Object.hasOwn(n, "webhook") ? { webhook: n.webhook } : {}
}
};
}
/** Isolates the trusted partition selector from a partially valid legacy config. */
function retainStoreConfig(e) {
const t = e?.cron;
if (typeof t?.store !== "string" || !t.store.trim()) return;
return { cron: {
store: t.store,
...Object.hasOwn(t, "webhook") ? { webhook: t.webhook } : {}
} };
}
//#endregion
//#region src/commands/doctor-update-run.ts
async function noteStaleUpdateRuns(e = {}) {
const t = /* @__PURE__ */ new Set();
const reportReconciliationError = (e) => {
if (hasCommandProcessCleanupError(e)) throw e;
t.add(`Update history reconciliation could not complete: ${String(e)}`);
};
try {
await inspectStaleUpdateRuns(e, reportReconciliationError);
} catch (e) {
reportReconciliationError(e);
}
for (const e of t) note(e, "Update history");
if (t.size && e.migrateState !== false) try {
await recordUpdateHistoryWarning([...t].join("\n"));
} catch (e) {
if (hasCommandProcessCleanupError(e)) throw e;
note(`Update history warning could not be saved: ${String(e)}`, "Update history");
}
}
async function recordUpdateHistoryWarning(e) {
const [{ runExistingOpenClawStateWriteTransaction: t }, { executeSqliteQuerySync: n, executeSqliteQueryTakeFirstSync: r, getNodeSqliteKysely: i }, { decodeRun: a }, { encodeRun: o }, { updateRunLedgerSchema: s, upsertStep: c }] = await Promise.all([
import("./openclaw-state-db-existing-write-CJaibLb_.mjs"),
import("./kysely-sync-BnoHwGNh.mjs"),
import("./update-run-read.kernel-p8F1hezn.mjs"),
import("./update-run-codec-CvXw0KzS.mjs"),
import("./update-run-write-AWHWpPQO.mjs")
]);
t(({ db: t }) => {
const s = r(t, i(t).selectFrom("update_runs").selectAll().orderBy("created_at_ms", "desc").orderBy("run_id", "desc").limit(1));
if (!s) return;
const l = a(s);
c(l, {
step: "warning:update-history-reconciliation",
status: "completed",
detail: e
});
n(t, i(t).updateTable("update_runs").set({ steps_json: o(l, {}).steps_json }).where("run_id", "=", l.runId));
}, {}, {
schemaSql: s,
operationLabel: "update.history.warning"
});
}
async function inspectStaleUpdateRuns(e, t) {
const [{ staleUpdateRunGuidance: n }, { listUpdateRunsAsync: r }, { renderUpdateRunReport: i }, { updateRunWarningMessages: a }, { readInstalledUpdateCandidate: o, reconcileInterruptedUpdateRuns: s }, { isAcknowledgedAbandonedUpdateRun: c }, { readInterruptedUpdateCandidateAsync: l }] = await Promise.all([
import("./update-run-activity-BAQQOkxs.mjs"),
import("./update-run-reader-g1w6betd.mjs"),
import("./update-run-report-DAe_65N8.mjs"),
import("./update-run-step-CUisvDNE.mjs"),
import("./update-run-interruption-DGFicN4F.mjs"),
import("./update-run-record-BogFM0jS.mjs"),
import("./update-run-interruption-worker-AFXj3cBd.mjs")
]);
const u = await withArtifactPreservingStateReads(() => withOpenClawStateDatabaseReadSnapshot(async () => {
let n;
if (e.migrateState !== false) try {
n = await l({});
} catch (e) {
t(e);
}
return {
candidate: n,
active: await r({
active: true,
limit: 100
}),
history: await r({ limit: 100 })
};
}));
let { active: d, history: f } = u;
let p = [];
if (u.candidate) try {
p = await s({ candidate: u.candidate });
for (const e of p) note(`Update ${e.runId}: recorded succeeded after verifying the installed and serving candidate build ${e.after.buildId}; its updater exited before recording completion.`, "Update history");
} catch (e) {
t(e);
}
if (p.length) {
d = await r({
active: true,
limit: 100
});
f = await r({ limit: 100 });
}
for (const e of d) {
const t = n(e);
if (t) note(`Update ${e.runId}: ${t}`, "Update history");
}
for (const e of f) if (e.status === "failed" && e.reason === "abandoned" && !c(e)) {
const t = o(e) ? "the recorded candidate has not been verified as installed and serving" : "the target build was not recorded, so current version equality cannot prove this update completed";
note(`Update ${e.runId} remains abandoned: ${t}. Run \`openclaw update repair\` to repair the installation and reconcile its history.`, "Update history");
}
const [m] = f;
if (m) {
if (m.status === "failed" && m.reason && (m.reason === "update-activation-timeout" || UPDATE_ENVIRONMENT_FAILURE_REASONS.has(m.reason))) note(`Update ${m.runId}: ${i(m).markdown}`, "Update history");
const e = await readRetiredDeferredUpdateWarnings(m.steps.map((e) => e.detail), { readUpdateRun: () => m });
const t = a(m.steps.filter((t) => !e.has(t.detail ?? "")));
if (t.length) note(`Recorded warnings from update ${m.runId} (a later repair may have resolved them):\n${t.slice(-3).join("\n")}`, "Update history");
}
}
//#endregion
//#region src/commands/doctor/shared/legacy-config-state-migration-input.ts
function resolveStateMigrationConfigInput(e) {
const t = e.snapshot.sourceConfig ?? e.snapshot.config ?? e.snapshot.parsed;
const n = e.snapshot.sourceConfigBeforeMigrations ?? t;
const r = {
sourceConfigBeforeMigrations: n,
...t ? { pluginDoctorConfig: t } : {}
};
if (e.postConvergenceConfig) return {
cfg: e.postConvergenceConfig,
...r
};
if (e.snapshot.valid) return e.snapshot.legacyIssues.length > 0 && t !== void 0 ? {
cfg: e.baseConfig,
pluginDoctorConfig: t,
sourceConfigBeforeMigrations: n
} : {
cfg: e.baseConfig,
sourceConfigBeforeMigrations: n
};
const i = t ?? e.snapshot.parsed;
if (e.snapshot.legacyIssues.length === 0 || i === void 0) return null;
const a = migrateLegacyConfig(i, { sourceConfigBeforeMigrations: e.snapshot.sourceConfigBeforeMigrations });
if (!a.config || a.partiallyValid) return { pluginDoctorConfig: t ?? i };
return {
cfg: a.config,
...r
};
}
//#endregion
//#region src/commands/doctor-config-preflight.ts
const loadState = createLazyRuntimeModule(() => import("./state-migrations.state-dir-DUGRrWf7.mjs"));
const loadCronRepair = createLazyRuntimeModule(() => import("./legacy-repair-CjiRGSBz.mjs"));
/** Preserve retired state inputs before the main Doctor config repair flow. */
async function runDoctorConfigPreflight(e = {}) {
try {
var t = _usingCtx();
const n = t.a(createConfigPreflightSnapshotReader());
let r;
if (e.migrateState !== false && (e.doctorOnlyStateMigrations === true || e.automaticHeartbeatRepair)) {
const { withSqliteReadOnlyWorkerScope: t } = await import("./sqlite-readonly-worker-BXIE20HR.mjs");
r = await t(() => runDoctorConfigPreflightOperation(e, n));
} else r = await runDoctorConfigPreflightOperation(e, n);
return {
...r,
pluginCache: await n.takePluginCache(r.pluginMetadataSnapshot)
};
} catch (e) {
t.e = e;
} finally {
await t.d();
}
}
async function runDoctorConfigPreflightOperation(e, t) {
try {
var n = _usingCtx();
if (!e.retiredStateAdmitted) assertDoctorRetiredStateAdmission();
const r = e.migrateState !== false;
const i = shouldSkipLegacyUpdateDoctorConfigWrite(process.env);
const measurePreflightStep = (t, n) => measureDoctorConfigPreflightStep(t, n, e.measure);
if (r) await measurePreflightStep("state-write-admission", async () => {
const e = resolveOpenClawStateSqlitePath(process.env);
await assertOpenClawStateWriteAllowedAtPath({
databasePath: e,
env: process.env,
recoverOrphanedSidecars: true
});
if (existsSync(e)) ensureOpenClawStatePermissions(e, process.env);
});
await measurePreflightStep("stale-update-runs", () => noteStaleUpdateRuns({ migrateState: r }));
let a;
let o;
let s = false;
let c = false;
let l = false;
const u = [];
const d = [];
const f = [];
let p;
let m = false;
let h = false;
let g = [];
let _;
const v = createDoctorPluginMigrationPreparation({
enabled: r,
env: () => process.env,
report: (e) => noteDoctorStateMigrationResult(e),
recordReceipt: (e) => f.push(e),
measure: measurePreflightStep,
runWithPluginMetadataSnapshot: (e, t) => y.run(e, t),
doctorOnlyStateMigrations: e.doctorOnlyStateMigrations === true,
integrityCheck: e.integrityCheck
});
const y = n.a(createDoctorPluginMetadataSnapshotScope({
getBaseSnapshot: () => _?.pluginMetadataSnapshot,
env: process.env,
getDeferredPluginIds: () => v.deferred().map((e) => e.pluginId)
}));
const noteDoctorStateMigrationResult = (e) => {
v.observe(e);
noteDoctorMigrationResult(e, { prefix: "- " });
};
let b = false;
const prepareSnapshot = async (e) => {
if (b) return;
const { completeUpdateCandidatePluginRehearsal: t } = await import("./update-candidate-plugin-repair-3waflLht.mjs");
const n = await t({
config: e.sourceConfig ?? e.config ?? {},
env: process.env,
installRecords: loadInstalledPluginIndexInstallRecordsSync({ env: process.env })
});
b = true;
noteDoctorStateMigrationResult({
changes: n.copiedFiles > 0 ? [`Update rehearsal: copied ${n.copiedFiles} missing plugin dependency files.`] : [],
warnings: n.warnings
});
};
const getSnapshotPreparation = (e) => e && resolveUpdateRehearsalRoot(process.env) && process.env.OPENCLAW_UPDATE_IN_PROGRESS === "1" ? prepareSnapshot : void 0;
const planScopedConfigRepair = (t) => y.run({ config: t.sourceConfig ?? t.config ?? {} }, async () => {
if (e.doctorOnlyStateMigrations === true) {
const { normalizeHeartbeatRepairSource: e } = await import("./doctor-automatic-heartbeat-repair-BO7VYwP6.mjs");
const { tryProjectRetiredHeartbeatConfig: n } = await import("./doctor-heartbeat-legacy-COP4rUJ3.mjs");
const r = e(t);
const i = n(r.sourceConfig);
if (i && !isDeepStrictEqual(i, t.sourceConfig)) return planAutomaticConfigRepair(t, {
config: i,
changes: r.changes,
pendingStateMigration: true
});
}
return planAutomaticConfigRepair(t);
});
const planAdmittedConfigRepair = (t, n = null) => (e.repairPrefixedConfig === true || r && e.migrateLegacyConfig !== false) && (!s || c) && canPlanAutomaticConfigRepair(t) && !i && (e.repairPrefixedConfig === true || !isTruthyEnvValue(process.env.OPENCLAW_UPDATE_IN_PROGRESS)) && !resolveIsConfigReadOnly(process.env) && !resolveFutureConfigActionBlock({
action: "normalize legacy config",
snapshot: t
}) ? n ?? planScopedConfigRepair(t) : null;
const readConfigSnapshotForPreflight = async (n = true) => await measurePreflightStep("config-snapshot", async () => t.read({
purpose: "doctor",
allowCurrentPluginMetadata: n,
includePluginMetadata: e.preparePluginMetadataSnapshot === true,
measure: e.measure,
observe: e.observe,
skipPluginValidation: isTruthyEnvValue(process.env.OPENCLAW_UPDATE_IN_PROGRESS),
prepareSnapshot: getSnapshotPreparation(e.doctorOnlyStateMigrations === true),
...await v.snapshotOptions()
}));
const x = r ? await measurePreflightStep("state-migrations-import", loadState) : void 0;
if (x) noteDoctorStateMigrationResult(await measurePreflightStep("state-dir-migrations", () => x.autoMigrateLegacyStateDir({ env: process.env })));
await migrateLegacyDoctorConfig({
enabled: e.migrateLegacyConfig !== false,
measure: measurePreflightStep
});
_ = await readConfigSnapshotForPreflight(!x);
const S = await prepareDoctorConfigRecovery({
enabled: e.repairPrefixedConfig === true && !i,
stateMigrationsRequested: r,
snapshotRead: _,
planRepair: planScopedConfigRepair,
readSnapshot: () => readConfigSnapshotForPreflight(false)
});
_ = S.snapshotRead;
let C = _.snapshot;
const w = C.sourceConfigBeforeMigrations ?? C.sourceConfig;
const T = S.activeConfigRepair;
noteDoctorConfigPreflightIssues(C, {
invalidConfigNote: e.invalidConfigNote,
activeRepair: T !== null
});
let E = C.sourceConfig ?? C.config ?? {};
let D = await planAdmittedConfigRepair(C, T);
if (e.doctorOnlyStateMigrations === true && x) {
const { prepareLegacyStateDatabaseSchema: t } = await import("./state-migrations.doctor-CODMy_h9.mjs");
const n = e.stateSchemaPreparation ?? await measurePreflightStep("state-schema", () => t(process.env, e.integrityCheck));
if (n.outcome !== "skipped") {
f.push(n);
noteDoctorStateMigrationResult({
changes: n.changes,
warnings: n.warnings,
notices: n.notices
});
throwIfDoctorStateMigrationRefused(f);
}
}
if (e.doctorOnlyStateMigrations === true && x) {
const { repairRetiredDoctorState: e } = await import("./doctor-retired-state-repair-DuxmGBr8.mjs");
noteDoctorStateMigrationResult(await measurePreflightStep("retired-state-repair", () => e()));
}
if (x && (e.doctorOnlyStateMigrations || e.automaticHeartbeatRepair)) {
const t = C.sourceConfigBeforeMigrations ?? C.sourceConfig;
const { readCronStoreSelectionForDoctor: n, maybeRepairCronStoreSelection: r } = await import("./default-store-selection-BcxQnwh3.mjs");
if (!(e.cronStoreSelection ? await r({
cfg: t,
options: e.cronStoreSelection.options,
prompter: e.cronStoreSelection.prompter ?? {}
}) : (await n(t)).status === "ready")) {
l = true;
const { tryProjectRetiredHeartbeatConfig: e } = await import("./doctor-heartbeat-legacy-COP4rUJ3.mjs");
const n = e(t);
if (n && !isDeepStrictEqual(n, t)) {
s = true;
D = null;
const { canDeferRehearsalCronMigration: e } = await import("./io.cron-owner-refusal-BB6wnOG2.mjs");
c = await e(t, C.path, process.env);
const n = c ? "Update rehearsal: cron and heartbeat data migration is deferred because the source cron partition is unknown. Only the disposable config is projected for validation; original state and config are unchanged." : "Run openclaw doctor --fix interactively to select the cron partition and migrate heartbeat settings. The original config was retained.";
u.push(n);
note(n, "Doctor warning");
}
}
}
if (e.invocationPurpose === "doctor" || e.doctorOnlyStateMigrations === true) {
const { repairLegacySessionEntryStates: t } = await import("./doctor-session-delivery-state-BYYA0Re-.mjs");
const n = e.doctorOnlyStateMigrations === true && x !== void 0;
const r = await measurePreflightStep("session-entry-state", () => t({
apply: n,
cfg: D?.config ?? E,
env: process.env,
deferSchemaRepair: n,
integrityCheck: e.integrityCheck,
onInspectedTargets: (e) => {
g = e.map((e) => e.canonicalPath);
}
}));
u.push(...r.warnings ?? []);
if (!n && r.found > 0) {
const { SessionStoreMigrationRequiredError: e } = await import("./migration-required-Z0-wYqcm.mjs");
throw new e(`Found ${r.found} session rows with legacy entry state. Run openclaw doctor --fix before further session inspection; no rows were changed.`);
}
}
let O;
if (x) {
const t = await runDoctorPluginConvergence({
cfg: D?.config ?? E,
env: process.env,
retainedPluginIds: v.retainedPluginIds(),
measure: e.measure,
deferPackageRepair: e.deferPluginPackageRepair
});
setActiveDegradedPlugins(t.quarantinedPlugins);
await v.converged(t.deferredPlugins ?? [], C, _?.pluginMetadataSnapshot, t.migrationInspection);
const n = await readConfigSnapshotForPreflight(false);
u.push(...t.warnings ?? []);
_ = n;
y.invalidate();
C = n.snapshot;
E = C.sourceConfig ?? C.config ?? {};
D = await planAdmittedConfigRepair(C);
O = D?.snapshot.config;
}
const k = resolveStateMigrationConfigInput({
snapshot: C,
baseConfig: E,
postConvergenceConfig: O
});
const A = k?.cfg ? tryGetLegacyDefaultAgentId(k.cfg) : void 0;
if (x) {
if (e.doctorOnlyStateMigrations === true && !k?.cfg) {
const { detectLegacyExecApprovals: e, migrateLegacyExecApprovals: t } = await import("./state-migrations.exec-approvals-CjNrpdoI.mjs");
const n = resolveStateDir(process.env);
noteDoctorStateMigrationResult(await measurePreflightStep("exec-approvals-migration", () => t({
detected: e({
stateDir: n,
doctorOnlyStateMigrations: true
}),
stateDir: n,
env: process.env
})));
}
if (k) {
if (k.cfg) {
const { autoMigrateLegacyState: t } = await import("./state-migrations.doctor-CODMy_h9.mjs");
const n = k.cfg;
const r = k.pluginDoctorConfig;
const { collectCronCodexRuntimePolicyTargetsReadOnly: i, repairLegacyCronStoreWithoutPrompt: a } = await measurePreflightStep("cron-repair-import", loadCronRepair);
noteDoctorStateMigrationResult(await measurePreflightStep("cron-repair", () => a({
cfg: withLegacyConfig(n, r),
migrateCodexModelRefs: false
})));
if (e.repairPrefixedConfig === true) {
const e = await measurePreflightStep("cron-policy-scan", () => i({ cfg: n }));
d.push(...e.targets);
noteDoctorStateMigrationResult({
changes: [],
warnings: e.warnings
});
}
const o = await measurePreflightStep("legacy-state-migrations", () => y.run({ config: r ?? n }, () => t({
cfg: n,
sourceConfigBeforeMigrations: k.sourceConfigBeforeMigrations,
...r ? { pluginDoctorConfig: r } : {},
configIncludedPaths: C.includedPaths ?? [],
env: process.env,
doctorOnlyStateMigrations: e.doctorOnlyStateMigrations,
invocationPurpose: e.invocationPurpose,
integrityCheck: e.integrityCheck,
inspectedSessionEntryPaths: g,
...e.agentDatabaseMigrationDiscovery ? { agentDatabaseMigrationDiscovery: e.agentDatabaseMigrationDiscovery } : {},
beforeWorkspaceStateMigration: e.beforeWorkspaceStateMigration,
onStepReceipt: (e) => f.push(e)
})));
p = o.postSessionPluginMigration;
m = e.doctorOnlyStateMigrations === true;
h = e.doctorOnlyStateMigrations === true;
noteDoctorStateMigrationResult(o);
if (e.doctorOnlyStateMigrations === true) await assertDoctorPreflightMigrationsComplete({
cfg: n,
stepReceipts: f,
report: noteDoctorStateMigrationResult
});
} else if (k.pluginDoctorConfig) {
const e = k.pluginDoctorConfig;
await migrateRetainedStore({
config: e,
env: process.env,
measure: measurePreflightStep,
report: noteDoctorStateMigrationResult
});
await v.migrate(e);
}
}
}
if (x && e.doctorOnlyStateMigrations === true && !h) {
const { migrateLegacyMediaPersistence: t } = await import("./state-migrations.media-persistence-kWdqbGFb.mjs");
noteDoctorStateMigrationResult(await measurePreflightStep("media-persistence-migration", () => t({
env: process.env,
integrityCheck: e.integrityCheck
})));
const { repairLegacySessionEntryStates: n } = await import("./doctor-session-delivery-state-BYYA0Re-.mjs");
const r = await n({
apply: true,
cfg: D?.config ?? E,
env: process.env,
integrityCheck: e.integrityCheck
});
u.push(...r.warnings ?? []);
}
if (x && e.doctorOnlyStateMigrations === true) {
const { retireDoctorA2uiWidgets: t } = await import("./doctor-a2ui-widgets-Bs_H3jDC.mjs");
const n = await measurePreflightStep("retired-a2ui-widgets", () => t({
cfg: D?.config ?? E,
env: process.env,
integrityCheck: e.integrityCheck
}));
noteDoctorStateMigrationResult(n);
u.push(...n.warnings);
}
if (await v.complete()) {
_ = await readConfigSnapshotForPreflight(false);
C = _.snapshot;
E = C.sourceConfig ?? C.config ?? {};
D = await planAdmittedConfigRepair(C);
}
if (x && e.doctorOnlyStateMigrations === true) {
const { repairRelativeSessionStores: t } = await import("./doctor-relative-session-store-C3qoD7j-.mjs");
noteDoctorStateMigrationResult(await measurePreflightStep("relative-session-store", () => t({
cfg: D?.config ?? E,
env: process.env,
registeredDatabases: e.agentDatabaseMigrationDiscovery?.registeredAgentDatabases
})));
}
const j = e.automaticHeartbeatRepair;
if (j && !l) {
const { commitAutomaticHeartbeatRepair: e } = await import("./doctor-automatic-heartbeat-repair-BO7VYwP6.mjs");
const t = await measurePreflightStep("automatic-heartbeat-config-repair", () => y.run({ config: C.sourceConfig }, () => e(j, C)));
noteDoctorMigrationResult({
changes: t,
warnings: []
});
_ = await readConfigSnapshotForPreflight(false);
C = _.snapshot;
E = C.sourceConfig ?? C.config ?? {};
D = await planAdmittedConfigRepair(C);
}
if (D && !i) {
a ??= C.sourceConfigBeforeMigrations ?? C.sourceConfig;
const t = D;
await measurePreflightStep("automatic-config-repair", () => y.run({ config: t.config }, () => commitAutomaticConfigRepair(t, C, e.doctorOnlyStateMigrations === true && !l ? async (e) => {
const { retireHeartbeatWithDoctor: t } = await import("./doctor-heartbeat-retirement-z8KwWn-S.mjs");
const { normalizeHeartbeatRepairSource: n } = await import("./doctor-automatic-heartbeat-repair-BO7VYwP6.mjs");
const r = n(e).sourceConfig;
await measurePreflightStep("heartbeat-retirement", () => t(r));
o = r;
} : void 0)));
note(`Migrated legacy config keys in the active openclaw.json:\n${D.changes.map((e) => `- ${e}`).join("\n")}`, "Doctor changes");
_ = await readConfigSnapshotForPreflight(false);
C = _.snapshot;
E = C.sourceConfig ?? C.config ?? {};
}
const M = v.deferred();
return {
snapshot: C,
baseConfig: E,
...u.length > 0 ? { warnings: u } : {},
rosterMigrationSource: w,
...A ? { rosterMigrationOwnerId: A } : {},
...M.length > 0 ? { deferredPluginMigrations: M } : {},
...a ? { modelBillingRouteMigrationSource: a } : {},
...o ? { heartbeatMigrationSource: o } : {},
...s ? { heartbeatMigrationDeferred: true } : {},
...l ? { cronStoreSelectionUnresolved: true } : {},
..._.pluginMetadataSnapshot ? { pluginMetadataSnapshot: _.pluginMetadataSnapshot } : {},
...d.length > 0 ? { cronCodexRuntimePolicyTargets: d } : {},
...f.length > 0 ? { stateMigrationStepReceipts: f } : {},
...p ? { postSessionPluginMigration: p } : {},
...m ? { postSessionPluginMigrationPlanBound: true } : {},
...m && M.length === 0 && isDeepStrictEqual(k?.cfg, E) && f.every((e) => e.id === "plugin-doctor-post-session-state" || (e.outcome === "completed" || e.outcome === "skipped") && e.warnings.length === 0) ? { preflightLegacyStateConfig: E } : {}
};
} catch (e) {
n.e = e;
} finally {
await n.d();
}
}
//#endregion
//#region src/commands/doctor/changes-panel-sink.ts
function createDoctorChangesPanelSink(e) {
const t = [];
return {
emit: (n, r = {}) => {
if (n.length === 0) return;
const i = n.join("\n");
const a = r.sanitize ? sanitizeDoctorNote(i) : i;
if (e) {
t.push(a);
return;
}
note(a, "Doctor changes preview");
},
drain: (e) => [...t.splice(0), ...e?.length ? [e.join("\n")] : []]
};
}
//#endregion
//#region src/commands/doctor/finalize-config-flow.ts
async function finalizeDoctorConfigFlow(e) {
const t = {
path: e.snapshot.path,
hash: e.snapshot.hash ?? hashConfigRaw(e.snapshot.raw)
};
let n = e.cfg;
let r = e.shouldRepair && e.pendingChanges;
if (!e.shouldRepair && e.pendingChanges) {
r = await e.confirm({
message: "Apply recommended config repairs now?",
initialValue: true
});
if (r) n = e.candidate;
else if (e.fixHints.length > 0) e.note(e.fixHints.join("\n"), "Doctor");
}
return {
cfg: n,
shouldWriteConfig: r,
confirmedConfigSource: t
};
}
//#endregion
//#region src/commands/doctor/shared/config-migration-result.ts
/** Keep migrated selectors with Doctor's model-policy owner until billing facts are captured. */
async function retainHeartbeatMigrationInput(e, t) {
const n = structuredClone(e);
if (t?.agents?.defaults?.heartbeat && n.agents) {
n.agents.defaults ??= {};
n.agents.defaults.heartbeat = structuredClone(t.agents.defaults.heartbeat);
}
for (const [e, r] of Object.entries(n.agents?.entries ?? {})) {
const n = t?.agents?.entries?.[e]?.heartbeat;
if (n) r.heartbeat = structuredClone(n);
}
if (t) {
const { resolveLegacyHeartbeatAgents: e } = await import("./doctor-heartbeat-legacy-COP4rUJ3.mjs");
const { resolveHeartbeatAutomationModel: t } = await import("./doctor-heartbeat-model-B6KKrFs9.mjs");
for (const { agentId: r, heartbeat: i } of e(n)) {
const e = n.agents?.entries?.[r];
const a = t(n, r).fallback;
if (e && i) {
const { agentId: t, ...n } = i;
e.heartbeat = {
...n,
...a ? { model: a.defaultModel } : {}
};
}
}
}
copyConfigResolutionFactsThroughRewrite(e, n);
return n;
}
/** Preserve migration provenance before repairs, then prepare the post-write health handoff. */
function prepareDoctorConfigMigrationResult(e, t) {
const n = t.sourceConfig.meta?.lastTouchedVersion;
const r = typeof n === "string" ? n : void 0;
const i = e.modelBillingRouteMigrationSource ?? t.sourceConfigBeforeMigrations ?? t.sourceConfig;
return async (t) => {
let n = [];
const a = t.modelBillingRouteConfig ?? t.cfg;
if ((t.shouldWriteConfig || e.modelBillingRouteMigrationSource) && (!isDeepStrictEqual(i.agents, a.agents) || !isDeepStrictEqual(i.models, a.models))) {
const { collectModelBillingRouteMigrationWarnings: e } = await import("./model-billing-route-migration-DtDPMCck.mjs");
n = t.runWithCurrentPluginMetadata(t.cfg, () => e({
before: i,
after: a,
metadataSnapshot: t.metadataSnapshot
}));
}
let o = e.stateMigrationStepReceipts;
let s = e.postSessionPluginMigration;
const c = e.postSessionPluginMigrationPlanBound;
if (c && t.pluginInventoryChanged && s) {
const { preparePostSessionPluginMigration: e } = await import("./state-migrations.plugin-plan-DEdg3qiS.mjs");
const { resolveLivePluginDoctorStateMigrationInventory: n } = await import("./doctor-contract-registry-C9_iSocR.mjs");
s = t.runWithCurrentPluginMetadata(t.cfg, () => e({
mode: "doctor",
inventory: n({
config: t.cfg,
env: process.env
})
}));
if (s.step.refusal) {
const { createLegacyStateMigrationStepReceipt: e } = await import("./state-migrations.messages-B4pupCuT.mjs");
o = [...o ?? [], e(s.step, {
changes: [],
warnings: [s.step.refusal.message]
})];
s = void 0;
}
}
return {
...r ? { sourceLastTouchedVersion: r } : {},
...n.length > 0 ? { modelBillingRouteWarnings: n } : {},
...t.metadataSnapshot ? { pluginMetadataSnapshot: t.metadataSnapshot } : {},
...o ? { stateMigrationStepReceipts: o } : {},
...s ? { postSessionPluginMigration: s } : {},
...c ? { postSessionPluginMigrationPlanBound: true } : {},
...!t.shouldWriteConfig && !t.pluginInventoryChanged && isDeepStrictEqual(e.preflightLegacyStateConfig, t.cfg) ? { preflightLegacyStateConfig: e.preflightLegacyStateConfig } : {}
};
};
}
//#endregion
//#region src/channels/plugins/setup-promotion-discovery.ts
function resolveDiscoveredChannelSetupPromotionSurface(e, t) {
const n = loadPluginManifestRegistryForPluginRegistry({
config: t,
includeDisabled: true
});
if (n.plugins.some((t) => t.channels.includes(e) && t.packageManifest?.setupFeatures?.configPromotion === "preserve-root")) return { configPromotion: "preserve-root" };
if (getOfficialExternalPluginCatalogManifest(getOfficialExternalPluginCatalogEntry(e) ?? {})?.setupFeatures?.configPromotion === "preserve-root") return { configPromotion: "preserve-root" };
const r = n.plugins.find((t) => t.channels.includes(e) && t.packageManifest?.setupFeatures?.configPromotion === true);
if (!r) return null;
const { plugin: i } = loadSetupChannelPluginFromManifestRecord({
record: r,
channelId: e,
env: process.env
});
const a = i?.setupContract ?? i?.setup;
return a && typeof a === "object" ? a : null;
}
//#endregion
//#region src/commands/doctor/shared/legacy-mistral-model-cost.ts
const MISTRAL_MODEL_CACHE_READ_COST_BY_ID = /* @__PURE__ */ new Map([
["codestral-latest", .03],
["devstral-medium-latest", .04],
["magistral-small", .05],
["mistral-large-latest", .05],
["mistral-medium-2508", .04],
["mistral-medium-3-5", .15],
["mistral-small-latest", .01],
["pixtral-large-latest", .2]
]);
function normalizeLegacyMistralModelCost(e) {
const t = e.model.cost;
if (!isRecord(t) || t.cacheRead !== 0) return e.model;
const n = MISTRAL_MODEL_CACHE_READ_COST_BY_ID.get(e.modelId.toLowerCase());
if (n === void 0) return e.model;
e.changes.push(`Normalized models.providers.${sanitizeForLog(e.providerId)}.models[${e.index}].cost.cacheRead (0 → ${n}) for Mistral prompt-cache billing.`);
return {
...e.model,
cost: {
...t,
cacheRead: n
}
};
}
//#endregion
//#region src/commands/doctor/shared/legacy-config-core-normalizers.ts
const log = createSubsystemLogger("doctor");
/** Seed an empty account map without changing an existing account set or route. */
function seedMissingDefaultAccountsFromSingleAccountBase(e, t) {
const n = cloneConfigWithResolutionFacts(e);
const r = t.length;
for (const [r, i] of Object.entries(n.channels ?? {})) {
if (!isRecord(i) || !isRecord(i.accounts) || Object.keys(i.accounts).length) continue;
const n = resolveSingleAccountPromotion({
channelKey: r,
channel: i,
resolveBundledSurface: (t) => resolveDiscoveredChannelSetupPromotionSurface(t, e)
});
if (n.kind === "preserve-root") continue;
if (n.shouldDeferPromotion) {
log.debug(`Deferring channels.${r} single-account promotion until its plugin declares uncovered root keys.`);
continue;
}
if (n.keysToMove.length === 0) continue;
const a = {};
for (const e of n.keysToMove) {
a[e] = i[e];
delete i[e];
}
i.accounts = { [DEFAULT_ACCOUNT_ID]: a };
t.push(`Moved channels.${r} single-account top-level values into channels.${r}.accounts.default.`);
}
if (t.length > r && Array.isArray(n.channels)) n.channels = Object.fromEntries(Object.entries(n.channels));
copyConfigResolutionFactsThroughRewrite(e, n);
return inheritLegacyDefaultAgentId(e, n);
}
function migrateUnblockedLegacyRuntimeModelRef(e, t) {
return isBlockedLegacyCodexModelRef({
modelRef: e,
blockedModelIdentities: t
}) ? null : migrateLegacyRuntimeModelRef(e);
}
function* agentScopes(e) {
if (!isRecord(e)) return;
if (isRecord(e.defaults)) yield ["agents.defaults", e.defaults];
for (const [t, n] of Array.isArray(e.list) ? e.list.entries() : []) if (isRecord(n)) {
const e = normalizeOptionalString(n.id);
yield [
e ? `agents.list.${sanitizeForLog(e)}` : `agents.list[${t}]`,
n,
e
];
}
for (const [t, n] of Object.entries(isRecord(e.entries) ? e.entries : {})) if (isRecord(n)) yield [
`agents.entries.${sanitizeForLog(t)}`,
n,
t
];
}
function* runtimePins(e) {
for (const [t, n] of agentScopes(e.agents)) for (const [e, r] of Object.entries(isRecord(n.models) ? n.models : {})) yield {
path: `${t}.models.${sanitizeForLog(e)}`,
provider: parseModelCatalogRef(e.trim())?.provider,
runtime: isRecord(r) && isRecord(r.agentRuntime) ? r.agentRuntime.id : void 0
};
for (const [t, n] of modelProviders(e)) {
const e = `models.providers.${sanitizeForLog(t)}`;
const r = normalizeProviderId(t);
yield {
path: e,
provider: r,
runtime: isRecord(n.agentRuntime) ? n.agentRuntime.id : void 0
};
for (const [t, i] of providerModels(n)) yield {
path: `${e}.models[${t}]`,
provider: r,
runtime: isRecord(i.agentRuntime) ? i.agentRuntime.id : void 0
};
}
}
/**
* Legacy CLI refs still select their CLI runtime as written. Migration moves them onto the
* canonical provider with an exact runtime pin, which outranks provider-wide, wildcard, and bare
* model pins. When config already routes that provider's models (or bare model keys) to another
* runtime, the operator runs both routes side by side and the rewrite could silently move one
* onto the other, changing billing. A scope that runs the same model both directly and through
* the legacy CLI ref keeps both routes too (see routeGroups). Retain the authored refs and say why.
*/
function retainConflictingLegacyCliProviders(e, t, n) {
const migrate = (e) => migrateUnblockedLegacyRuntimeModelRef(e, t);
const r = /* @__PURE__ */ new Map();
rewriteModelRefs(e, "config", [], (e) => {
const t = migrate(e);
if (t?.cli && !r.has(t.legacyProvider)) r.set(t.legacyProvider, {
ref: e,
migrated: t
});
return null;
});
const i = /* @__PURE__ */ new Set();
for (const { ref: t, migrated: a } of r.values()) for (const r of runtimePins(e)) {
const e = normalizeOptionalLowercaseString(r.runtime);
if (e && e !== "auto" && e !== a.runtime && (r.provider === void 0 || r.provider === a.provider)) {
i.add(a.legacyProvider);
n.push(`Kept legacy ${a.legacyProvider}/* model refs: ${r.path} routes models to the ${sanitizeForLog(e)} runtime, and rewriting ${sanitizeForLog(t)} to ${sanitizeForLog(a.ref)} could switch a route between ${sanitizeForLog(e)} and ${a.runtime}. Both routes keep working as configured.`);
break;
}
}
for (const { path: t, agentId: r, groups: a } of routeGroups(e.agents, migrate)) for (const o of a) for (const a of o) {
const s = migrate(a);
if (!s?.cli || i.has(s.legacyProvider)) continue;
if (normalizeOptionalLowercaseString(resolveModelRuntimePolicy({
config: e,
provider: s.provider,
modelId: s.model,
agentId: r
}).policy?.id) === s.runtime || !o.some((e) => !migrate(e) && canonicalModelRef(e) === s.ref)) continue;
i.add(s.legacyProvider);
n.push(`Kept legacy ${s.legacyProvider}/* model refs: ${t} selects ${sanitizeForLog(s.ref)} both directly and through ${s.runtime}; rewriting would move both routes onto ${s.runtime}. Both routes keep working as configured.`);
}
return i;
}
function canonicalModelRef(e) {
const { model: t } = splitTrailingAuthProfile(e.trim());
return normalizeKnownModelRef(t) ?? t;
}
function stringRefs(e) {
return e.filter((e) => typeof e === "string");
}
function selectionRefs(e) {
const t = isRecord(e) ? e.model : void 0;
return stringRefs(isRecord(t) ? [t.primary, ...Array.isArray(t.fallbacks) ? t.fallbacks : []] : [t]);
}
const SELECTION_OWNERS = [
"",
"heartbeat",
"subagents"
];
/**
* Refs whose runtime one migration pin decides. Migration pins a CLI ref's runtime on the
* canonical ref in its scope's model map. That pin reaches every selection the scope runs,
* including selections inherited from defaults, and a defaults pin reaches every agent. An
* allowlist naming both spellings also requests both routes, as does a model map whose
* canonical key the scope selects or allows; canonical map keys alone are metadata, and
* legacy entries alone are a sign-in seed, so both still migrate.
*/
function* routeGroups(e, t) {
const n = isRecord(e) && isRecord(e.defaults) ? e.defaults : void 0;
const selections = (e) => SELECTION_OWNERS.map((t) => selectionRefs(t ? e?.[t] : e));
const r = selections(n);
const i = r.flat().filter((e) => t(e));
for (const [a, o, s] of agentScopes(e)) {
const e = o === n;
const c = selections(o).flatMap((t, n) => t.length || e ? t : r[n]);
const l = isRecord(o.modelPolicy) ? o.modelPolicy.allow : void 0;
const u = stringRefs(Array.isArray(l) ? l : []);
const d = new Set([...c, ...u].map(canonicalModelRef));
yield {
path: a,
agentId: s,
groups: [
e ? c : [...c, ...i],
Object.keys(isRecord(o.models) ? o.models : {}).filter((e) => t(e) || d.has(canonicalModelRef(e))),
u
]
};
}
}
function mergeModelEntry(e, t) {
return isRecord(e) && isRecord(t) ? mergeModelRefMapEntries(t, e, "models").value : t ?? e;
}
function migrateCodexCliRuntimePolicy(e) {
if (!isRecord(e) || normalizeOptionalLowercaseString(e.id) !== "codex-cli") return false;
e.id = "codex";
return true;
}
function createRuntimeModelRefRewriter(e) {
const t = [];
return {
selected: t,
rewrite: (n) => {
const r = typeof n === "string" ? e(n) : null;
if (r) t.push({
ref: r.ref,
runtime: r.runtime
});
return r?.ref ?? n;
}
};
}
function migrateRuntimeSelection(e, t) {
const { rewrite: n, selected: r } = createRuntimeModelRefRewriter(t);
const i = e.model;
if (typeof i === "string") e.model = n(i);
else if (isRecord(i)) {
if (typeof i.primary === "string") i.primary = n(i.primary);
if (Array.isArray(i.fallbacks)) i.fallbacks = i.fallbacks.map(n);
}
return r;
}
function ensureSelectedModelRuntimePolicies(e, t) {
if (t.length === 0) return false;
const n = isRecord(e.models) ? e.models : {};
let r = false;
for (const { ref: e, runtime: i } of t) {
const t = modelEntryWithRuntimePolicy(n[e], i);
if (t.changed) {
n[e] = t.entry;
r = true;
}
}
if (r) e.models = n;
return r;
}
function migrateRuntimeAgent(e, t, n, r) {
const i = migrateRuntimeSelection(e, r);
if (i.length) n.push(`Moved ${t}.model legacy runtime primary refs to provider references and selected ${i[0].runtime} runtime.`);
const a = isRecord(e.modelPolicy) ? e.modelPolicy : void 0;
const { rewrite: o, selected: s } = createRuntimeModelRefRewriter(r);
const c = Array.isArray(a?.allow) ? a.allow.map(o) : void 0;
if (isRecord(e.models)) {
const i = {};
const a = [];
for (const [t, n] of Object.entries(e.models)) {
const e = r(t);
if (e) a.push({
ref: e.ref,
runtime: e.runtime,
entry: n
});
else i[t] = mergeModelEntry(n, i[t]);
}
for (const { ref: e, runtime: t, entry: n } of a) i[e] = modelEntryWithRuntimePolicy(mergeModelEntry(n, i[e]), t).entry;
if (a.length) {
e.models = i;
n.push(`Moved ${t}.models legacy runtime keys to provider keys.`);
}
}
if (ensureSelectedModelRuntimePolicies(e, s)) n.push(`Preserved runtime policy for ${t}.modelPolicy.allow entries.`);
if (ensureSelectedModelRuntimePolicies(e, i)) n.push(`Selected ${i[0].runtime} runtime for ${t}.models entries.`);
for (const i of ["heartbeat", "subagents"]) {
const a = e[i];
if (!isRecord(a)) continue;
const o = migrateRuntimeSelection(a, r);
if (o.length) {
ensureSelectedModelRuntimePolicies(e, o);
n.push(`Moved ${t}.${i}.model to provider references with model runtime policy.`);
}
}
if (a && s.length) {
a.allow = c;
n.push(`Moved ${t}.modelPolicy.allow legacy runtime refs to provider references.`);
}
for (const [r, i] of Object.entries(isRecord(e.models) ? e.models : {})) if (isRecord(i) && migrateCodexCliRuntimePolicy(i.agentRuntime)) n.push(`Moved ${t}.models.${sanitizeForLog(r)} agentRuntime.id from codex-cli to codex.`);
}
/** Move legacy runtime-tagged refs on a private copy, preserving the caller's source. */
function normalizeLegacyRuntimeModelRefs(e, t, n, r) {
const i = cloneConfigWithResolutionFacts(e);
for (const [e, n] of modelProviders(i)) {
if (migrateCodexCliRuntimePolicy(n.agentRuntime)) t.push(`Moved models.providers.${sanitizeForLog(e)} agentRuntime.id from codex-cli to codex.`);
for (const [r, i] of providerModels(n)) if (migrateCodexCliRuntimePolicy(i.agentRuntime)) {
const n = normalizeOptionalString(i.id) ?? `[${r}]`;
t.push(`Moved models.providers.${sanitizeForLog(e)}.models.${sanitizeForLog(n)} agentRuntime.id from codex-cli to codex.`);
}
}
const a = retainConflictingLegacyCliProviders(i, r, n);
const migrate = (e) => {
const t = migrateUnblockedLegacyRuntimeModelRef(e, r);
return t && !a.has(t.legacyProvider) ? t : null;
};
for (const [e, n] of agentScopes(i.agents)) migrateRuntimeAgent(n, e, t, migrate);
const o = rewriteModelRefs(i, "config", t, (e) => {
const t = migrate(e);
return t && [
"codex-cli",
"claude-cli",
"google-gemini-cli"
].includes(t.legacyProvider) ? t.ref : null;
}).value;
copyConfigResolutionFactsThroughRewrite(e, o);
return inheritLegacyDefaultAgentId(e, o);
}
function* modelProviders(e) {
const t = e.models?.providers;
if (!isRecord(t)) return;
for (const [e, n] of Object.entries(t)) if (isRecord(n)) yield [e, n];
}
function* providerModels(e) {
if (Array.isArray(e.models)) {
for (const [t, n] of e.models.entries()) if (isRecord(n)) yield [t, n];
}
}
/** Mutate the Doctor-owned private candidate; plugin hooks retain their own rollback copies. */
function normalizeLegacyOpenAICodexModelsAddMetadata(e, t) {
for (const [n, r] of modelProviders(e)) {
if (normalizeProviderId(n) !== "openai-codex") continue;
for (const [, e] of providerModels(r)) if (!("metadataSource" in e) && isLegacyModelsAddCodexMetadataModel({
provider: n,
model: e
})) {
e.metadataSource = "models-add";
t.push(`Marked models.providers.${sanitizeForLog(n)}.models.${sanitizeForLog(normalizeOptionalString(e.id) ?? "unknown")} as /models add metadata so official OpenAI Codex metadata can override it.`);
}
}
}
function normalizeLegacyOpenAIModelProviderApi(e, t) {
const migrateApi = (e, n) => {
if (e.api === "openai") {
e.api = "openai-completions";
t.push(`Moved ${n}.api "openai" → "openai-completions".`);
}
};
for (const [t, n] of modelProviders(e)) {
const e = `models.providers.${sanitizeForLog(t)}`;
migrateApi(n, e);
for (const [t, r] of providerModels(n)) migrateApi(r, `${e}.models[${t}]`);
}
}
/** Remove retired bundled skill config after migrating its image model and credentials. */
function normalizeLegacyNanoBananaSkill(e, t) {
const n = "nano-banana-pro";
const r = "google/gemini-3-pro-image-preview";
const i = e.skills;
if (!isRecord(i)) return;
if (Array.isArray(i.allowBundled)) {
const e = i.allowBundled.filter((e) => typeof e !== "string" || e.trim() !== n);
if (e.length !== i.allowBundled.length) {
i.allowBundled = e;
t.push(`Removed ${n} from skills.allowBundled.`);
}
}
const a = i.entries;
if (!isRecord(a) || !isRecord(a[n])) return;
const o = a[n];
if (e.agents?.defaults?.mediaModels?.image === void 0) {
e.agents = {
...e.agents,
defaults: {
...e.agents?.defaults,
mediaModels: {
...e.agents?.defaults?.mediaModels,
image: { primary: r }
}
}
};
t.push(`Moved skills.entries.${n} → agents.defaults.mediaModels.image.primary (${r}).`);
}
const s = normalizeOptionalString(isRecord(o.env) ? o.env.GEMINI_API_KEY : void 0) ?? "";
const c = s || (typeof o.apiKey === "string" ? normalizeOptionalString(o.apiKey) : isRecord(o.apiKey) ? o.apiKey : void 0);
const l = isRecord(e.models) ? e.models : {};
const u = isRecord(l.providers) ? l.providers : {};
const d = isRecord(u.google) ? u.google : {
baseUrl: DEFAULT_GOOGLE_API_BASE_URL,
models: []
};
if (d.apiKey === void 0 && c) {
d.apiKey = c;
d.baseUrl ||= DEFAULT_GOOGLE_API_BASE_URL;
if (!Array.isArray(d.models)) d.models = [];
u.google = d;
l.providers = u;
e.models = l;
t.push(`Moved skills.entries.${n}.${s ? "env.GEMINI_API_KEY" : "apiKey"} → models.providers.google.apiKey.`);
}
delete a[n];
if (Object.keys(a).length === 0) delete i.entries;
t.push(`Removed legacy skills.entries.${n}.`);
if (Object.keys(i).length === 0) delete e.skills;
}
function normalizeConfiguredPositiveInteger(e) {
return typeof e === "number" && Number.isFinite(e) && e > 0 ? Math.floor(e) : void 0;
}
function resolveConfiguredOllamaModelNumCtxBudget(e, t, n) {
if (normalizeConfiguredPositiveInteger(e.contextTokens) !== void 0) return;
const r = normalizeConfiguredPositiveInteger(e.contextWindow);
const i = normalizeConfiguredPositiveInteger(t.contextWindow);
if (r !== void 0 || i !== void 0) return r ?? (n ? void 0 : i);
return normalizeConfiguredPositiveInteger(e.maxTokens) ?? (n ? void 0 : normalizeConfiguredPositiveInteger(t.maxTokens));
}
function normalizeLegacyOllamaNativeNumCtxParams(e, t) {
for (const [n, r] of modelProviders(e)) {
if (!Array.isArray(r.models)) continue;
const e = [...providerModels(r)];
const i = normalizeOptionalLowercaseString(r.api) === "ollama";
const a = r.params;
if (i && (a === void 0 || isRecord(a)) && !Object.hasOwn(a ?? {}, "num_ctx") && !e.some(([, e]) => normalizeConfiguredPositiveInteger(e.contextTokens) !== void 0)) {
const e = normalizeConfiguredPositiveInteger(r.contextWindow) ?? normalizeConfiguredPositiveInteger(r.maxTokens);
if (e !== void 0) {
r.params = {
...a,
num_ctx: e
};
t.push(`Set models.providers.${sanitizeForLog(n)}.params.num_ctx to ${e} for native Ollama compatibility.`);
}
}
const o = i && isRecord(r.params) && Object.hasOwn(r.params, "num_ctx");
for (const [i, a] of e) {
const e = normalizeOptionalLowercaseString(a.api) || normalizeOptionalLowercaseString(r.api);
const s = a.params;
if (e !== "ollama" || s !== void 0 && !isRecord(s) || Object.hasOwn(s ?? {}, "num_ctx")) continue;
const c = resolveConfiguredOllamaModelNumCtxBudget(a, r, o);
if (c !== void 0) {
a.params = {
...s,
num_ctx: c
};
t.push(`Set models.providers.${sanitizeForLog(n)}.models[${i}].params.num_ctx to ${c} for native Ollama compatibility.`);
}
}
}
}
function normalizeLegacyMistralModelDefaults(e, t) {
for (const [n, r] of modelProviders(e)) {
if (normalizeProviderId(n) !== "mistral") continue;
for (const [e, i] of providerModels(r)) {
const r = normalizeOptionalString(i.id) ?? "";
if (!r) continue;
const a = asFiniteNumber(i.contextWindow) ?? null;
const o = asFiniteNumber(i.maxTokens) ?? null;
if (a !== null && o !== null) {
const s = resolveNormalizedProviderModelMaxTokens({
providerId: n,
modelId: r,
contextWindow: a,
rawMaxTokens: o
});
if (s !== o) {
i.maxTokens = s;
t.push(`Normalized models.providers.${n}.models[${e}].maxTokens (${o} → ${s}) to avoid Mistral context-window rejects.`);
}
}
Object.assign(i, normalizeLegacyMistralModelCost({
providerId: n,
model: i,
modelId: r,
index: e,
changes: t
}));
}
}
}
//#endregion
//#region src/commands/doctor/shared/legacy-secret-inputs.ts
/** Normalize only registered credential paths before config validation and backup/write. */
function migrateLegacySecretInputs(e) {
let t;
const n = [];
for (const r of discoverConfigSecretTargets(e)) {
const i = r.value;
const a = isLegacySecretRefWithoutProvider(i);
const o = a ? coerceSecretRef(r.value, e.secrets?.defaults) : parseLegacySecretRefEnvMarker(r.value, e.secrets?.defaults?.env);
if (!o) continue;
t ??= structuredClone(e);
if (setPathExistingStrict(t, r.pathSegments, o)) {
n.push(a ? `Added provider ${o.provider} to ${r.path} SecretRef.` : `Moved ${r.path} ${String(r.value).trim()} marker → structured env SecretRef.`);
if (hasLegacySecretRefExtraFields(i)) n.push(`Canonicalized ${r.path} SecretRef to source/provider/id; Doctor preserves removed fields in the original config backup before writing the repair.`);
}
}
return {
config: t ?? e,
changes: n
};
}
//#endregion
//#region src/commands/doctor/shared/reserved-mcp-server-name-migrate.ts
const RESERVED_MCP_SERVER_NAME = "__proto__";
function resolveMcpServers(e, t) {
const n = asOptionalRecord(e);
const r = t ? asOptionalRecord(n?.nodeHost) : n;
return asOptionalRecord(asOptionalRecord(r?.mcp)?.servers);
}
/** Drop reserved MCP server names before canonical config validation runs. */
function migrateReservedMcpServerNames(e, t = e) {
const n = [{
path: "mcp.servers",
nodeHost: false
}, {
path: "nodeHost.mcp.servers",
nodeHost: true
}].filter(({ nodeHost: n }) => [t, e].some((e) => Object.hasOwn(resolveMcpServers(e, n) ?? {}, RESERVED_MCP_SERVER_NAME)));
if (n.length === 0) return {
config: e,
changes: []
};
const r = structuredClone(e);
const i = [];
for (const { path: e, nodeHost: t } of n) {
const n = resolveMcpServers(r, t);
if (n) delete n[RESERVED_MCP_SERVER_NAME];
i.push(`Dropped MCP server "${RESERVED_MCP_SERVER_NAME}" from ${e} because the name is reserved; re-add it under a different name.`);
}
return {
config: r,
changes: i
};
}
//#endregion
//#region src/commands/doctor/shared/legacy-config-core-migrate.ts
function reportInvalidHeartbeatActiveHours(e, t) {
const reportHeartbeat = (e, n) => {
if (!isRecord(e) || !Object.hasOwn(e, "activeHours")) return;
const r = LegacyHeartbeatSchema.safeParse({ activeHours: e.activeHours });
if (r.success) return;
for (const i of r.error.issues) {
const r = i.path.map(String);
const a = JSON.stringify(getConfigValueAtPath(e, r));
t.push(`Kept invalid ${n}.${r.join(".")}=${a}: ${i.message}. Heartbeat migration is deferred; fix the value, then rerun "openclaw doctor --fix".`);
}
};
reportHeartbeat(e.agents?.defaults?.heartbeat, "agents.defaults.heartbeat");
visitAgentEntries(e, (e, t) => reportHeartbeat(e.heartbeat, `${t}.heartbeat`));
}
function repairNullAgentWorkspaces(e, t) {
let n = 0;
visitAgentEntries(e, (e) => {
if (e.workspace === null) {
n += 1;
delete e.workspace;
}
});
if (n) t.push(`Removed null workspace value${n === 1 ? "" : "s"} from agents.${readAgentRosterProperty(e)?.kind} entr${n === 1 ? "y" : "ies"}.`);
}
/** Normalize pre-admission config through core, plugin setup, channel, and secret-ref migrations. */
function normalizeCompatibilityConfigValues(e, t = {}) {
if (!isRecord(e)) throw new TypeError("Compatibility config normalization requires an object");
const n = [];
const r = [];
const i = migrateReservedMcpServerNames(e, t.sourceRaw);
n.push(...i.changes);
let a = seedMissingDefaultAccountsFromSingleAccountBase(i.config, n);
const o = runPluginSetupConfigMigrations({ config: a });
a = o.config;
n.push(...o.changes);
r.push(...o.warnings ?? []);
for (const e of [
migrateLegacyWebSearchConfig,
migrateLegacyWebFetchConfig,
migrateLegacyXSearchConfig
]) {
const t = e(a);
if (t.changes.length) {
a = t.config;
n.push(...t.changes);
}
}
normalizeLegacyNanoBananaSkill(a, n);
a = normalizeLegacyTalkConfig(a, n);
normalizeLegacyOpenAIModelProviderApi(a, n);
a = normalizeLegacyRuntimeModelRefs(a, n, r, t.blockedModelIdentities);
normalizeLegacyOllamaNativeNumCtxParams(a, n);
normalizeLegacyMistralModelDefaults(a, n);
stripRetiredTuningKnobs(a, n);
const s = applyChannelDoctorCompatibilityMigrations(a, { historicalWebhookListeners: true });
r.push(...s.warnings ?? []);
if (s.changes.length) {
a = s.next;
n.push(...s.changes);
}
const c = migrateLegacySecretInputs(a);
if (c.changes.length) {
a = c.config;
n.push(...c.changes);
}
normalizeLegacyOpenAICodexModelsAddMetadata(a, n);
reportInvalidHeartbeatActiveHours(a, r);
repairNullAgentWorkspaces(a, n);
a = migrateLegacyCommandOwners(a, n);
a = pruneBindingsForMissingAgents(a, n);
copyConfigResolutionFactsThroughRewrite(e, a);
return {
config: inheritLegacyDefaultAgentId(e, a),
changes: n,
...r.length ? { warnings: r } : {}
};
}
//#endregion
//#region src/commands/doctor-config-flow.ts
async function loadAndMaybeMigrateDoctorConfig(e) {
try {
var t = _usingCtx();
const n = t.a(new AsyncDisposableStack());
const { shouldRepair: r, nonInteractive: i } = resolveDoctorRepairMode(e.options);
const a = await runDoctorConfigPreflight({
retiredStateAdmitted: e.retiredStateAdmitted,
stateSchemaPreparation: e.stateSchemaPreparation,
integrityCheck: e.options.fullIntegrityCheck ? "full" : "quick",
observe: false,
invocationPurpose: "doctor",
repairPrefixedConfig: r,
doctorOnlyStateMigrations: r,
deferPluginPackageRepair: i && !r,
preparePluginMetadataSnapshot: true,
...e.automaticHeartbeatRepair ? { automaticHeartbeatRepair: e.automaticHeartbeatRepair } : {},
agentDatabaseMigrationDiscovery: e.agentDatabaseMigrationDiscovery,
beforeWorkspaceStateMigration: createWorkspaceAliasMigrationRepair(e.prompter),
cronStoreSelection: {
options: e.options,
prompter: e.prompter
},
measure: (t, n) => withDoctorProgress(t.slice(t.lastIndexOf(".") + 1).replaceAll("-", " "), n, e.options.json !== true)
});
const { snapshot: o, baseConfig: s, heartbeatMigrationDeferred: c } = a;
if (!r && !e.options.json) {
const { collectRecoveryDiskUsage: e, formatRecoveryDiskUsage: t } = await import("./recovery-disk-usage-B25K84kT.mjs");
note(t(e({
cfg: s,
env: process.env
})), "Recovery copies (read-only)");
}
n.use(a.pluginCache);
if (!o.exists || o.valid) await setAppliedRuntimeConfigSnapshot(o.runtimeConfig, o.sourceConfig);
const l = prepareDoctorConfigReferenceSource(o);
const u = { current: a.pluginMetadataSnapshot };
const { createDoctorPluginMetadataSnapshotScope: d } = await import("./plugin-metadata-snapshot-scope-BqMk1x5X.mjs");
const f = n.use(d({
getBaseSnapshot: () => u.current,
env: process.env,
getDeferredPluginIds: () => a.deferredPluginMigrations?.map((e) => e.pluginId) ?? []
}));
const p = f.run;
const runWithCurrentPluginMetadata = (e, t) => {
const n = tryResolveSoleAgentId(e);
return p({
config: e,
workspaceDir: n ? resolveAgentWorkspaceDir(e, n) : void 0
}, t);
};
let m = {
cfg: s,
candidate: await retainHeartbeatMigrationInput(s, a.heartbeatMigrationSource),
pendingChanges: false,
fixHints: []
};
const h = [];
let g = false;
let _;
let v = false;
let y;
const b = formatCliCommand("openclaw doctor --fix");
const x = createDoctorChangesPanelSink(r);
const S = [...a.warnings ?? []];
const applyConfigMutation = (e, t, n = {}) => {
x.emit(e.changes, n.sanitize ? { sanitize: true } : {});
if (n.emitWarnings !== false && e.warnings?.length) {
emitDoctorNotes({
note,
warningNotes: e.warnings
});
S.push(...e.warnings);
}
m = applyDoctorConfigMutation({
state: m,
mutation: e,
shouldRepair: r,
fixHint: t
});
};
const C = prepareDoctorConfigMigrationResult(a, o);
const w = runWithCurrentPluginMetadata(m.candidate, () => planProviderRenames(o.sourceConfigBeforeMigrations ?? o.sourceConfig, resolvePluginDoctorProviderRenames({ config: m.candidate })));
const T = o.sourceConfigBeforeMigrations ?? o.sourceConfig;
const E = findLegacyConfigRuleIssues(T, LEGACY_AGENT_ROSTER_RULES).length > 0 || listAgentEntries(T).length === 0 || s.agents?.ownership === void 0 && listAgentEntries(s).length > 1;
const D = runWithCurrentPluginMetadata(m.candidate, () => applyLegacyCompatibilityStep({
snapshot: o,
state: m,
shouldRepair: r,
doctorFixCommand: b
}));
m = D.state;
const O = a.rosterMigrationOwnerId ?? tryGetLegacyDefaultAgentId(m.candidate) ?? resolveLegacyAgentRosterOwner(a.rosterMigrationSource ?? T);
if (O) {
retainLegacyDefaultAgentId(m.cfg, O);
retainLegacyDefaultAgentId(m.candidate, O);
}
const k = o.exists && E && !configIncludeOwnsAgentRoster(o);
if (k) {
applyConfigMutation({
config: m.candidate,
changes: ["Prepared the agent roster for persistence."]
}, `Run "${b}" to persist the explicit agent roster.`, { emitWarnings: false });
if (m.candidate.agents?.ownership === "explicit") h.push(["agents", "ownership"]);
}
const { prepareSessionStoreOwnerRecovery: A } = await import("./doctor-session-store-owner-CVX3b7-I.mjs");
const j = await A({
config: m.candidate,
snapshot: o,
prompter: e.prompter
});
applyConfigMutation(j, `Run "${b}" to review session-store ownership recovery.`, { sanitize: true });
const { collectBlockedLegacyOpenAICodexProviderPlan: M } = await import("./legacy-config-migrations.runtime.models-BrSWCxfQ.mjs");
const N = M(m.candidate);
const P = new Set(N.blockedModelIdentities);
if (a.cronCodexRuntimePolicyTargets?.length) {
const { repairCronCodexRuntimePolicies: e } = await import("./runtime-policy-migration-CML9fl3S.mjs");
const t = e({
cfg: m.candidate,
targets: a.cronCodexRuntimePolicyTargets,
blockedModelIdentities: P
});
applyConfigMutation(t, `Run "${b}" to preserve migrated cron runtime policy.`);
const n = new Set(t.blockedTargets.map(cronCodexRuntimePolicyTargetKey));
g = a.cronCodexRuntimePolicyTargets.some((e) => !n.has(cronCodexRuntimePolicyTargetKey(e)));
}
const ee = await (async () => {
if (o.parsed === o.sourceConfig) return [];
const { findDoctorLegacyConfigIssues: e } = await import("./legacy-config-issues-CAhEFJ4d.mjs");
return runWithCurrentPluginMetadata(m.candidate, () => e(o.parsed, o.parsed));
})();
const te = new Set(o.legacyIssues.map((e) => `${e.path}:${e.message}`));
const ne = ee.filter((e) => {
const t = `${e.path}:${e.message}`;
if (te.has(t)) return false;
te.add(t);
return true;
}).map((e) => `- ${e.path}: ${e.message}`);
const re = [...D.issueLines, ...ne];
if (ne.length > 0 && !r && !m.fixHints.includes(`Run "${b}" to migrate legacy config keys.`)) m.fixHints.push(`Run "${b}" to migrate legacy config keys.`);
if (re.length > 0) note(re.join("\n"), "Legacy config keys detected");
x.emit(D.changeLines);
const { repairGeneratedModelMetadataCorruption: ie } = await import("./model-metadata-corruption-repair-858sK6Ie.mjs");
applyConfigMutation(runWithCurrentPluginMetadata(m.candidate, () => ie({
config: m.candidate,
authoredRoot: o.parsed,
configPath: o.path,
currentHash: hashConfigRaw(o.raw),
loadAuditRecords: () => readRecentConfigAuditRecords({
env: process.env,
homedir,
limit: 2048
})
})), `Run "${b}" to remove audit-proven generated model metadata.`);
noteDoctorHookConfigWarnings(m.cfg, o.path);
applyConfigMutation(runWithCurrentPluginMetadata(m.candidate, () => normalizeCompatibilityConfigValues(m.candidate, {
blockedModelIdentities: P,
sourceRaw: o.parsed
})), `Run "${b}" to apply these changes.`);
const { recoverCommandOwnerTargetKinds: ae } = await import("./doctor-command-owner-recovery-Cq-UixIP.mjs");
applyConfigMutation(runWithCurrentPluginMetadata(m.candidate, () => ae({
config: m.candidate,
snapshot: o
})), `Run "${b}" to restore recorded command-owner target kinds.`, { sanitize: true });
const { repairUnownedChannelAccountBindings: oe } = await import("./legacy-config-binding-repair-BuIleUpt.mjs");
applyConfigMutation(runWithCurrentPluginMetadata(m.candidate, () => oe({
config: m.candidate,
sourceConfigBeforeMigrations: o.sourceConfigBeforeMigrations
})), `Run "${b}" to preserve channel account ownership.`);
const { collectTailscaleConfigWarnings: se } = await import("./doctor-tailscale-BfCQZYHm.mjs");
const F = await se({
cfg: m.candidate,
env: process.env
});
emitDoctorNotes({
note,
warningNotes: F
});
S.push(...F);
const { prepareRetiredPhoneControlCleanup: ce } = await import("./doctor-retired-phone-control-QzEa0osy.mjs");
const I = await ce({
cfg: m.candidate,
env: process.env
});
applyConfigMutation({
config: I.config,
changes: I.configChanges,
warnings: I.warnings
}, `Run "${b}" to retire Phone Control lease configuration.`);
if (I.cleanupPending && !r) note(`Retired Phone Control lease state remains. Run "${b}" to archive it.`, "Legacy state detected");
const { recoverInstalledPluginConfigIds: le } = await import("./installed-plugin-id-recovery-CD-455PV.mjs");
const L = await le(m.candidate, process.env);
applyConfigMutation({
...L,
warnings: L.notices
}, `Run "${b}" to apply these changes.`);
if (l) l.installedPluginIdRecovery = L.recovery;
const R = m.candidate;
const { collectCodexPluginActivationWarnings: ue } = await import("./codex-plugin-activation-warning-BDk0YzE5.mjs");
emitDoctorNotes({
note,
warningNotes: ue(R)
});
const { applyPluginAutoEnable: de } = await import("./plugin-auto-enable-56ocMcft.mjs");
applyConfigMutation(runWithCurrentPluginMetadata(m.candidate, () => de({
config: m.candidate,
env: process.env
})), `Run "${b}" to apply these changes.`, { emitWarnings: false });
if (!r) {
const { repairStaleAgentModelRefs: e } = await import("./stale-agent-model-ref-repair-BlWq3XUc.mjs");
const t = runWithCurrentPluginMetadata(m.candidate, () => e(m.candidate, { env: process.env }));
y = t.retiredModelRefConfig;
applyConfigMutation(t, `Run "${b}" to remove stale agent model references.`, { sanitize: true });
}
const [{ collectPluginToolAllowlistWarnings: fe }, { collectGitHubUpgradeWarnings: pe }, { normalizePluginsConfig: me }] = await Promise.all([
import("./plugin-tool-allowlist-warnings-C6P7S9mr.mjs"),
import("./github-preview-upgrade-DLzC6DVh.mjs"),
import("./config-state-DCgWxFQO.mjs")
]);
const z = [...runWithCurrentPluginMetadata(m.candidate, () => fe({
cfg: m.candidate,
env: process.env
})), ...pe(me(m.candidate.plugins))];
if (z.length > 0) note(sanitizeDoctorNote(z.join("\n")), "Doctor warnings");
const he = listDoctorConfiguredChannelIds(m.candidate, { configEntryPolicy: "raw" }).length > 0;
let B;
if (he) {
const e = await import("./channel-doctor-DfTS1VvV.mjs");
B = e.collectChannelDoctorMutableAllowlistWarnings;
const t = await runWithCurrentPluginMetadata(m.candidate, () => e.runChannelDoctorConfigSequences({
cfg: m.candidate,
env: process.env,
shouldRepair: r
}));
emitDoctorNotes({
note,
changeNotes: t.changeNotes,
infoNotes: t.infoNotes,
warningNotes: t.warningNotes
});
const n = await runWithCurrentPluginMetadata(m.candidate, () => e.collectChannelDoctorStaleConfigMutations(m.candidate, { env: process.env }));
for (const e of n) applyConfigMutation(e, `Run "${b}" to remove stale channel plugin references.`, { sanitize: true });
}
const { repairHooksTokenReuseGatewayAuth: ge } = await import("./hooks-token-reuse-repair-D-igBydx.mjs");
applyConfigMutation(await ge(m.candidate, process.env), `Run "${b}" to rotate hooks.token away from Gateway auth.`, { emitWarnings: false });
const { repairSystemAgentWorkspacePin: V } = await import("./system-agent-workspace-repair-DrkST0Wq.mjs");
const H = isRecord(o.parsed) ? o.parsed.agents : void 0;
const U = isRecord(H) ? H.defaults : void 0;
const W = o.authoredConfig?.agents?.defaults?.workspace ?? (isRecord(U) ? U.workspace : void 0);
const G = {
includeOwnsRoster: configIncludeOwnsAgentRoster(o),
authoredDefaultWorkspace: typeof W === "string" ? W : void 0
};
const K = await V(m.candidate, process.env, {
...G,
applyFiles: r
});
h.push(...K.explicitSetPaths ?? []);
applyConfigMutation(K, `Run "${b}" to pin the system agent's workspace.`);
if (r) {
const { runDoctorRepairSequence: t } = await import("./repair-sequencing-Bt5MEy1E.mjs");
const n = e.prompter;
const r = await withDoctorProgress(formatDoctorProgressPhase("Config repairs"), () => t({
state: m,
installedPluginIdRecovery: L.recovery,
doctorFixCommand: b,
modelReplacements: e.options.modelReplacements,
reportFindings: e.reportFindings,
env: process.env,
blockedCodexProviderPlan: N,
pluginMetadataSnapshotState: u,
runWithPluginMetadataSnapshot: p,
...n ? { onCapabilityConsent: createPluginCapabilityConsentPrompter({
note: async (e, t) => note(e, t),
confirm: (e) => n.confirmRuntimeRepair({
...e,
requiresInteractiveConfirmation: true
})
}) } : {}
}), e.options.json !== true);
m = r.state;
S.push(...r.warningNotes);
if (l) l.installedPluginIdRecovery = new Map([...L.recovery, ...r.installedPluginIdRecovery]);
u.current = r.pluginMetadataSnapshot;
_ = r.openAICodexAuthProfileIdMap;
y = r.retiredModelRefConfig;
v = r.modelRetirementRepairRan;
if (r.authProfilesRepaired) {
const { refreshGatewayAuthStateAfterAuthProfileRepair: e } = await import("./auth-profile-repair-B0I6-wjp.mjs");
await e();
}
emitDoctorRepairSequenceNotes({
note,
repairSequence: r,
structuredWarnings: Boolean(e.reportFindings),
emitConfigChange: (e) => x.emit([e])
});
} else {
const { collectDoctorPreviewNotes: t } = await import("./preview-warnings-CjY5zdRD.mjs");
const n = await runWithCurrentPluginMetadata(m.candidate, () => t({
cfg: m.candidate,
activationSourceConfig: R,
doctorFixCommand: b,
env: process.env,
allowExec: e.options.allowExec === true,
blockedCodexProviderPlan: N
}));
emitDoctorNotes({
note,
infoNotes: n.infoNotes,
warningNotes: n.warningNotes
});
}
const q = B ? await runWithCurrentPluginMetadata(m.candidate, () => B({
cfg: m.candidate,
env: process.env
})) : [];
if (q.length > 0) note(sanitizeDoctorNote(q.join("\n")), "Doctor warnings");
const _e = m.candidate;
m = await applyRetiredConfigStep({
state: m,
shouldRepair: r,
doctorFixCommand: b,
sourceConfig: o.sourceConfig,
emitChanges: x.emit,
preflight: a
});
const J = await finalizeDoctorConfigFlow({
...m,
snapshot: o,
shouldRepair: r,
confirm: e.confirm,
note
});
const Y = J.shouldWriteConfig && !D.blocksWrite && !c;
const X = !r && Y && K.restorePending ? await V(J.cfg, process.env, {
...G,
applyFiles: true
}) : void 0;
if (X) {
h.push(...X.explicitSetPaths ?? []);
if (X.warnings?.length) {
emitDoctorNotes({
note,
warningNotes: X.warnings
});
S.push(...X.warnings);
}
}
const Z = X?.config ?? J.cfg;
const ve = Y && canWriteDoctorInclude(o, Z, {
persistCanonicalAgentRoster: k,
explicitSetPaths: h
}, l?.installedPluginIdRecovery);
const ye = [Z.models?.providers?.opencode || Z.models?.providers?.["opencode-zen"] ? "opencode" : void 0, Z.models?.providers?.["opencode-go"] ? "opencode-go" : void 0].filter((e) => e !== void 0);
let Q = [];
if (ye.length > 0) {
const { resolveEnabledProviderPluginIds: e } = await import("./providers-C_AVoPkJ.mjs");
Q = runWithCurrentPluginMetadata(Z, () => e({
config: Z,
onlyPluginIds: ye
}));
}
noteOpencodeProviderOverrides(Z, {
opencodePluginActive: Q.includes("opencode"),
opencodeGoPluginActive: Q.includes("opencode-go")
});
noteImplicitFallbackClobberWarnings(Z);
noteSandboxOriginProxyWarning(Z);
noteMcpOriginWarning(Z);
noteMediaCliModelWarnings(Z);
noteMissingDefaultAgentOwner(Z);
const be = await C({
cfg: Z,
modelBillingRouteConfig: _e,
shouldWriteConfig: Y,
pluginInventoryChanged: u.inventoryChanged,
metadataSnapshot: u.current,
runWithCurrentPluginMetadata
});
const invalidatePluginMetadataSnapshot = () => {
delete $.preflightLegacyStateConfig;
u.current = void 0;
f.invalidate();
};
const xe = x.drain(X?.changes);
const Se = D.blocksWrite ? [] : w;
await setAppliedRuntimeConfigSnapshot(Z, Z);
const Ce = n.move();
const $ = {
[Symbol.asyncDispose]: () => Ce.disposeAsync(),
...J,
cfg: Z,
heartbeatMigrationSource: _e,
...Y && j.changes.length > 0 ? { confirmedConfigSource: {
path: o.path,
hash: o.hash ?? hashConfigRaw(o.raw)
} } : {},
...l ? { referenceSource: l } : {},
path: o.path ?? CONFIG_PATH,
shouldWriteConfig: Y,
...S.length ? { warnings: [...new Set(S)] } : {},
...Y && xe.length > 0 ? { pendingChangePanels: xe } : {},
sourceConfigValid: o.valid,
...D.partiallyValid === true ? { skipPluginValidationOnWrite: true } : {},
...Y && h.length > 0 ? { explicitSetPaths: h } : {},
...Y && k ? { persistCanonicalAgentRoster: true } : {},
...ve ? { skipWizardMetadataForIncludeWrite: true } : {},
...g ? { shouldRepairCronCodexModelRefsAfterConfigWrite: true } : {},
...r && I.cleanupPending && I.cleanupSafe ? { retiredPhoneControlStateCleanupPending: true } : {},
...N.blockedModelIdentities.length > 0 ? { blockedCodexModelIdentities: N.blockedModelIdentities } : {},
..._ ? { openAICodexAuthProfileIdMap: _ } : {},
...y ? { retiredModelRefConfig: y } : {},
...Se.length > 0 ? { providerRenames: Se } : {},
modelRetirementRepairRan: v && !D.blocksWrite && (Y || o.valid),
...be,
runWithPluginMetadataSnapshot: p,
invalidatePluginMetadataSnapshot
};
return $;
} catch (e) {
t.e = e;
} finally {
await t.d();
}
}
//#endregion
export { loadAndMaybeMigrateDoctorConfig };