openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
42 lines • 79.3 kB
JavaScript
import{c as normalizeOptionalLowercaseString,l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{s as asFiniteNumber}from"./number-coercion-B3CfI447.mjs";import{n as isTruthyEnvValue}from"./env-fLMEolk5.mjs";import{a as asOptionalRecord,l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{a as coerceSecretRef,h as parseLegacySecretRefEnvMarker,l as isLegacySecretRefWithoutProvider,s as hasLegacySecretRefExtraFields}from"./types.secrets-UWdyCdE6.mjs";import{n as cloneConfigWithResolutionFacts,o as copyConfigResolutionFactsThroughRewrite}from"./resolution-facts-DYKtoyes.mjs";import{n as sanitizeForLog}from"./ansi-54CEWBZf.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{t as normalizePluginPolicyId}from"./plugin-policy-id-Nz6ZTOOH.mjs";import{u as normalizePluginsConfig}from"./config-state-C1eV6UWf.mjs";import{i as passesManifestOwnerBasePolicy}from"./manifest-owner-policy-DVnu9FAE.mjs";import{S as resolveIsConfigReadOnly,m as resolveConfigPath,t as CONFIG_PATH}from"./paths-D_FOvGon.mjs";import{r as createLazyRuntimeModule}from"./lazy-runtime-Ds6M7vp4.mjs";import"./session-key-BPgKfU2m.mjs";import{t as DEFAULT_ACCOUNT_ID}from"./account-id-3yqrEsRn.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{r as normalizeProviderId}from"./provider-id-A-8WTtLA.mjs";import{i as parseModelCatalogRef}from"./model-catalog-refs-eJnrGUHo.mjs";import{n as listAgentEntries,p as tryResolveSoleAgentId,s as readAgentRosterProperty}from"./agent-roster-4XrgUgPK.mjs";import{f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{S as setActiveDegradedPlugins}from"./discovery-Bo4UPPd9.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{v as withOpenClawStateDatabaseReadSnapshot}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{a as withArtifactPreservingStateReads}from"./artifact-preserving-state-reads-CWuQPqxe.mjs";import{a as hasCommandProcessCleanupError}from"./exec-result-TD4w1Z1i.mjs";import{a as resolveUpdateRehearsalRoot}from"./update-rehearsal-paths-C4qLj9oD.mjs";import{r as cloneEnvWithPlatformSemantics,y as resolveFutureConfigActionBlock}from"./config-env-vars-DCDGIBtT.mjs";import{r as getOfficialExternalPluginCatalogEntry}from"./official-external-plugin-catalog-BkSwu5lo.mjs";import{i as loadInstalledPluginIndexInstallRecordsSync}from"./installed-plugin-index-record-reader-rJXlMUQ8.mjs";import{o as getOfficialExternalPluginCatalogManifest}from"./official-external-plugin-catalog-source-WW0GK1Kk.mjs";import{m as resolveNormalizedProviderModelMaxTokens}from"./validation-core-Dgg8JyG6.mjs";import{i as hashConfigRaw}from"./io.read-helpers-B0XuPBY2.mjs";import{m as assertOpenClawStateWriteAllowedAtPath}from"./openclaw-state-db-BlgxYkYw.mjs";import{t as ensureOpenClawStatePermissions}from"./openclaw-state-db-permissions-CSYe8Gz3.mjs";import{p as readRecentConfigAuditRecords}from"./io.audit-DXCsuLiP.mjs";import{m as assertBaseSnapshotStillCurrent,r as withConfigSourceLocks}from"./write-lock-BXv5IgVt.mjs";import{E as setAppliedRuntimeConfigSnapshot}from"./runtime-snapshot-Bg5K4JNu.mjs";import{t as getConfigValueAtPath}from"./config-paths-BNzEq3Gi.mjs";import{t as splitTrailingAuthProfile}from"./model-ref-profile-DFGpvDZX.mjs";import{t as ConfigMutationConflictError}from"./mutation-conflict-qTMp0e4U.mjs";import{n as loadPluginManifestRegistryForPluginRegistry}from"./plugin-registry-contributions-C4xBwxaW.mjs";import{d as recordDeferredPluginMigrations,i as mergeDeferredPluginMigration,l as readDeferredPluginMigrations,r as formatDeferredPluginMigration,t as DeferredPluginMigrationConflictError}from"./deferred-plugin-migrations-D_BIDN9_.mjs";import{r as hasDeferredPluginMigrationConfig,s as resolveDeferredPluginMigrationConfigPaths}from"./deferred-plugin-migration-config-D1j_2i5D.mjs";import{r as LEGACY_AGENT_ROSTER_RULES,s as findLegacyConfigRuleIssues}from"./legacy-tools-by-sender-D6Y_L891.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{i as tryGetLegacyDefaultAgentId,r as retainLegacyDefaultAgentId,t as inheritLegacyDefaultAgentId}from"./legacy.default-agent-owner-DUgZJ5NH.mjs";import{r as resolveLegacyAgentRosterOwner}from"./legacy.roster-CU2eR_i6.mjs";import{a as visitAgentEntries}from"./legacy-config-record-shared-B0hPoAz4.mjs";import{a as withPreparedPluginSetupRead}from"./plugin-setup-module-DKdTsN2H.mjs";import{o as runPluginSetupConfigMigrations}from"./setup-registry-JeNUWxS6.mjs";import"./plugin-registry-BAbRxjjy.mjs";import{r as resolveModelRuntimePolicy}from"./model-runtime-policy-DJvvlwBk.mjs";import{r as validateConfigObjectRawWithPlugins}from"./validation-CGAl0yU4.mjs";import{i as setPathExistingStrict}from"./path-utils-Da5tqfDE.mjs";import{n as discoverConfigSecretTargets}from"./target-registry-query-UuUEzVi7.mjs";import"./target-registry-D_8Q9dwn.mjs";import{t as createConfigIO}from"./io.factory-y6nIrp_4.mjs";import"./env-vars-T_m-ovbQ.mjs";import{n as UPDATE_ENVIRONMENT_FAILURE_REASONS,t as UPDATE_ACTIVATION_TIMEOUT_REASON}from"./update-outcome-Dl4aMuF_.mjs";import{t as configIncludeOwnsAgentRoster}from"./agent-roster-provenance-5AqnirlB.mjs";import{E as recordAgentDatabaseAdmissions,f as evaluateAgentDatabaseAdmissions,i as canIsolateAgentDatabase,y as listAgentDatabaseAdmissionRefusals}from"./agent-database-admission-DiJx9iIl.mjs";import{n as getAgentDatabaseStartupAdmission}from"./agent-database-startup-B70N6vNa.mjs";import{t as DEFAULT_GOOGLE_API_BASE_URL}from"./google-api-base-url-Cn2mlr60.mjs";import{o as withPluginLifecycleLease}from"./plugin-lifecycle-lease-D-y0xYkr.mjs";import"./installed-plugin-index-records-DMOoWiOF.mjs";import{t as formatDoctorProgressPhase}from"./doctor-progress-DGmacsiq.mjs";import{g as shouldSkipLegacyUpdateDoctorConfigWrite,h as shouldDeferConfiguredPluginInstallRepair}from"./update-phase-CCaxuca0.mjs";import{h as resolvePluginDoctorProviderRenames}from"./doctor-contract-registry-DTv7VdR4.mjs";import{n as preparePluginDoctorContractModules}from"./doctor-contract-preparation-qRvs5BHm.mjs";import{c as throwIfDoctorStateMigrationRefused,t as DoctorStateMigrationRefusalError}from"./state-migrations.messages-BurXA9TV.mjs";import{t as readRetiredDeferredUpdateWarnings}from"./deferred-update-warnings-BoCcCY9z.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{n as emitDoctorRepairSequenceNotes,r as sanitizeDoctorNote,t as emitDoctorNotes}from"./emit-notes-DCY5wFZF.mjs";import{a as migrateLegacyConfig,c as noteDoctorHookConfigWarnings,n as applyRetiredConfigStep,o as noteConfigAdvisories,r as prepareDoctorConfigReferenceSource,s as noteDoctorConfigPreflightIssues,t as applyLegacyCompatibilityStep}from"./config-flow-steps-BNUk0fFW.mjs";import{t as applyDoctorConfigMutation}from"./config-mutation-state-Cwwz-hgQ.mjs";import{n as applyChannelDoctorCompatibilityMigrations}from"./channel-legacy-config-migrate-CgDU_wO0.mjs";import{t as listDoctorConfiguredChannelIds}from"./configured-channel-ids-fKSHMbv6.mjs";import{d as migrateLegacyWebSearchConfig,f as migrateLegacyXSearchConfig,l as stripRetiredTuningKnobs,o as normalizeLegacyTalkConfig,u as migrateLegacyWebFetchConfig}from"./legacy-config-migrations-BjWfZbO1.mjs";import{i as isBlockedLegacyCodexModelRef}from"./codex-route-model-ref-DySsVPNo.mjs";import{a as rewriteModelRefs,c as normalizeKnownModelRef,r as mergeModelRefMapEntries}from"./legacy-config-migrations.runtime.models.refs-BcGOdqm2.mjs";import{r as isLegacyModelsAddCodexMetadataModel}from"./legacy-config-migrations.runtime.models-FgZfjZsR.mjs";import{i as modelEntryWithRuntimePolicy}from"./legacy-runtime-model-policy-IOynjY9Z.mjs";import{n as planProviderRenames}from"./provider-rename-PnqDJPfZ.mjs";import{a as loadSetupChannelPluginFromManifestRecord}from"./read-only-B-Uv2t8Q.mjs";import{a as migrateLegacyCommandOwners}from"./doctor-command-owner-D7NATa7X.mjs";import{t as pruneBindingsForMissingAgents}from"./legacy-config-binding-repair-KrbITdMM.mjs";import{t as createPluginCapabilityConsentPrompter}from"./plugin-capability-consent-CNNJbvR9.mjs";import{t as resolveSingleAccountPromotion}from"./setup-promotion-helpers-DVtKxGr5.mjs";import{r as cronCodexRuntimePolicyTargetKey}from"./store-migration-C4AFuxtV.mjs";import{t as describeConfigSnapshotInputChange}from"./snapshot-inputs-C_6Mro9f.mjs";import{t as LegacyHeartbeatSchema}from"./doctor-heartbeat-legacy-DItu0_B3.mjs";import{n as commitAutomaticConfigRepair,r as planAutomaticConfigRepair,t as canPlanAutomaticConfigRepair}from"./automatic-config-repair-BDdrbCM_.mjs";import{t as noteDoctorMigrationResult}from"./doctor-migration-notes-Cd2syDSW.mjs";import{n as resolveDoctorRepairMode}from"./doctor-repair-mode-Dilz8sGs.mjs";import{p as withDoctorProgress}from"./doctor-health-startup-WrxcBhpP.mjs";import{a as measureDoctorConfigPreflightStep,t as createConfigPreflightSnapshotReader}from"./config-preflight-snapshot-CTe1x93o.mjs";import{n as prepareDoctorConfigRecovery,t as migrateLegacyDoctorConfig}from"./doctor-config-preflight-legacy-config-DmfCeqni.mjs";import{t as inspectPluginMigrationAvailability}from"./plugin-migration-availability-DltE1wpv.mjs";import{n as runDoctorPluginConvergence}from"./doctor-config-preflight-plugin-verification-ByReuYqw.mjs";import{t as assertDoctorRetiredStateAdmission}from"./doctor-retired-state-admission-DJPid-yl.mjs";import{t as createDoctorPluginMetadataSnapshotScope}from"./plugin-metadata-snapshot-scope-SFFzftNv.mjs";import{n as createWorkspaceAliasMigrationRepair}from"./doctor-workspace-alias-D2CJRHqk.mjs";import{t as migrateLegacyRuntimeModelRef}from"./legacy-runtime-model-providers-BGH1r4rF.mjs";import{t as canWriteDoctorInclude}from"./roster-include-write-eVvPuLPU.mjs";import fs,{closeSync,existsSync,openSync}from"node:fs";import path from"node:path";import{homedir}from"node:os";import{isDeepStrictEqual}from"node:util";
//!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-qJc0YeSZ.mjs`);try{await t({cfg:e.cfg,operation:`doctor`,blockedByStepId:e.stepReceipts.find(({id:e})=>e===`workspace-state`)?.originatingRefusal?.stepId})}catch(t){e.report({changes:[],warnings:[String(t)]})}}throw t}}
//!src/commands/doctor-config-preflight-plugin-migrations.ts
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-BFHxk7wF.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,r){for(const a of e.deferredPluginMigrations??[]){const e=retain({...a,...resolveDeferredPluginMigrationConfigPaths({config:h?.sourceConfigBeforeMigrations??h?.sourceConfig,pluginId:a.pluginId,compatibilityMigrationPaths:r?.plugins.find(e=>matchesOwner(e.id,a.pluginId))?.configContracts?.compatibilityMigrationPaths})});t.set(e.pluginId,e);n=[...n.filter(t=>t.pluginId!==e.pluginId),e];i=true}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=/* @__PURE__ */ new Set;const x=[...t.values()].filter(e=>hasOwner(p,e.pluginId)&&!hasOwner(f,e.pluginId)&&(e.requiresStateMigration||hasDeferredPluginMigrationConfig(_,e))).map(e=>e.pluginId);if(h?.valid&&_&&!o&&x.length){const{runPostSessionPluginDoctorStateRepairs:t}=await import(`./state-migrations.plugin-doctor-BFHxk7wF.mjs`);const n=await e.runWithPluginMetadataSnapshot({config:_},()=>t({config:_,env:e.env(),inspectPluginIds:x,inspectDisabled:true}));for(const t of n.completedPluginIds??[])if(validateConfigObjectRawWithPlugins(_,{env:e.env(),deferredPluginMigrations:r.filter(e=>!matchesOwner(e.pluginId,t))}).ok)b.add(t)}const S=[...t.values()].filter(e=>{if(hasOwner(b,e.pluginId)){const t=`Plugin "${e.pluginId}" is inactive and its migration detectors found no remaining work. Retained settings have been validated and kept; no runtime or tools were registered.`;v.push({pluginId:e.pluginId,status:`completed`,reason:t});y.push(t);return true}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 C=new Set(S);const w=[...t.values()].filter(e=>!C.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(S.length===0&&w.length===0)return i;const persist=()=>persistPending(w,S,v);let T;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);T=await withPluginLifecycleLease({env:t,assertCurrent},()=>withConfigSourceLocks([n.path,...Object.entries(a.targets).flat()],persist,t,assertCurrent))}else T=await persist();if(!T)return true;for(const e of y)createSubsystemLogger(`state-migrations`).warn(e);for(const e of S){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=>!C.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 w){t.set(e.pluginId,e);reportPending(e)}return i||S.length>0}}}
//!src/commands/doctor-config-preflight.cron.ts
async function migrateRetainedStore(e){const t=retainStoreConfig(e.config);if(!t)return;const{repairLegacyCronStoreWithoutPrompt:n}=await e.measure(`cron-repair-import`,()=>import(`./legacy-repair-CzQbDqyz.mjs`));e.report(await e.measure(`cron-repair`,()=>n({cfg:t,migrateCodexModelRefs:false})));const{migrateLegacyConfigMachineState:r}=await import(`./state-migrations.config-machine-state-DbScrsTh.mjs`);e.report(r({config:e.config,env:e.env}))}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}:{}}}}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}:{}}}}
//!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(`
`))}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-2gHW_IvC.mjs`),import(`./kysely-sync-BeSP_Bof.mjs`),import(`./update-run-read.kernel-BzTM693D.mjs`),import(`./update-run-codec-CBN0T6RA.mjs`),import(`./update-run-write-B02lA8EE.mjs`),import(`./update-run-step-upsert-D3LyxQaT.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-B5jDTljV.mjs`),import(`./update-run-reader-tNF5l9at.mjs`),import(`./update-run-report-CqS7jx74.mjs`),import(`./update-run-step-BiIgl06o.mjs`),import(`./update-run-interruption-T_he3jxn.mjs`),import(`./update-run-record-3IK_eVCd.mjs`),import(`./update-run-interruption-worker-D8t3SoNc.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(`
`)}`,`Update history`)}}
//!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}}
//!src/commands/doctor-config-preflight.ts
const loadState=createLazyRuntimeModule(()=>import(`./state-migrations.state-dir-CKjADuh4.mjs`));const loadCronRepair=createLazyRuntimeModule(()=>import(`./legacy-repair-CzQbDqyz.mjs`));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-CEmDKsql.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);closeSync(openSync(e,`r+`))}});await measurePreflightStep(`stale-update-runs`,()=>noteStaleUpdateRuns({migrateState:r}));let a;let o;let s=false;let c=false;let l=false;let u=false;const d=[];const f=[];const p=[];let m;let h=false;let g=false;let _=[];let v;const y=createDoctorPluginMigrationPreparation({enabled:r,env:()=>process.env,report:e=>noteDoctorStateMigrationResult(e),recordReceipt:e=>p.push(e),measure:measurePreflightStep,runWithPluginMetadataSnapshot:(e,t)=>b.run(e,t),doctorOnlyStateMigrations:e.doctorOnlyStateMigrations===true,integrityCheck:e.integrityCheck});const b=n.a(createDoctorPluginMetadataSnapshotScope({getBaseSnapshot:()=>v?.pluginMetadataSnapshot,env:process.env,getDeferredPluginIds:()=>y.deferred().map(e=>e.pluginId)}));const noteDoctorStateMigrationResult=e=>{u||=e.outcome===`deferred`||e.warnings.length>0&&e.warningDisposition!==`recoverable`;y.observe(e,v?.pluginMetadataSnapshot);noteDoctorMigrationResult(e,{prefix:`- `})};let x=false;const prepareSnapshot=async e=>{if(x)return;const{completeUpdateCandidatePluginRehearsal:t}=await import(`./update-candidate-plugin-repair-CNn-LGzR.mjs`);const n=await t({config:e.sourceConfig??e.config??{},env:process.env,installRecords:loadInstalledPluginIndexInstallRecordsSync({env:process.env})});x=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=>b.run({config:t.sourceConfig??t.config??{}},async()=>{if(e.doctorOnlyStateMigrations===true){const{normalizeHeartbeatRepairSource:e}=await import(`./doctor-automatic-heartbeat-repair-C1zTy9xw.mjs`);const{tryProjectRetiredHeartbeatConfig:n}=await import(`./doctor-heartbeat-legacy-CR4UkMoG.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 y.snapshotOptions()}));const S=r?await measurePreflightStep(`state-migrations-import`,loadState):void 0;if(S)noteDoctorStateMigrationResult(await measurePreflightStep(`state-dir-migrations`,()=>S.autoMigrateLegacyStateDir({env:process.env})));let C=await migrateLegacyDoctorConfig({enabled:e.migrateLegacyConfig!==false,measure:measurePreflightStep});v=await readConfigSnapshotForPreflight(!S);const w=await prepareDoctorConfigRecovery({enabled:e.repairPrefixedConfig===true&&!i,stateMigrationsRequested:r,snapshotRead:v,planRepair:planScopedConfigRepair,readSnapshot:()=>readConfigSnapshotForPreflight(false)});C||=v!==w.snapshotRead;v=w.snapshotRead;let T=v.snapshot;const ee=T.sourceConfigBeforeMigrations??T.sourceConfig;const E=w.activeConfigRepair;noteDoctorConfigPreflightIssues(T,{invalidConfigNote:e.invalidConfigNote,activeRepair:E!==null});let D=T.sourceConfig??T.config??{};let O=await planAdmittedConfigRepair(T,E);if(e.doctorOnlyStateMigrations===true&&S){const{prepareLegacyStateDatabaseSchema:t}=await import(`./state-migrations.doctor-DVSvDgfM.mjs`);const n=e.stateSchemaPreparation??await measurePreflightStep(`state-schema`,()=>t(process.env,e.integrityCheck));if(n.outcome!==`skipped`){p.push(n);noteDoctorStateMigrationResult({changes:n.changes,warnings:n.warnings,notices:n.notices});throwIfDoctorStateMigrationRefused(p)}}if(e.doctorOnlyStateMigrations===true&&S){const{repairRetiredDoctorState:e}=await import(`./doctor-retired-state-repair-DX76Wike.mjs`);noteDoctorStateMigrationResult(await measurePreflightStep(`retired-state-repair`,()=>e()))}if(S&&(e.doctorOnlyStateMigrations||e.automaticHeartbeatRepair)){const t=T.sourceConfigBeforeMigrations??T.sourceConfig;const{readCronStoreSelectionForDoctor:n,maybeRepairCronStoreSelection:r}=await import(`./default-store-selection-CkAhir5_.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-CR4UkMoG.mjs`);const n=e(t);if(n&&!isDeepStrictEqual(n,t)){s=true;O=null;const{canDeferRehearsalCronMigration:e}=await import(`./io.cron-owner-refusal-C4cLLBJf.mjs`);c=await e(t,T.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.`;d.push(n);note(n,`Doctor warning`)}}}if(e.invocationPurpose===`doctor`||e.doctorOnlyStateMigrations===true){const{repairLegacySessionEntryStates:t}=await import(`./doctor-session-delivery-state-DG9tmbL6.mjs`);const n=e.doctorOnlyStateMigrations===true&&S!==void 0;const r=await measurePreflightStep(`session-entry-state`,()=>t({apply:n,cfg:O?.config??D,env:process.env,deferSchemaRepair:n,integrityCheck:e.integrityCheck,onInspectedTargets:e=>{_=e.map(e=>e.canonicalPath)}}));d.push(...r.warnings??[]);if(!n&&r.found>0){const{SessionStoreMigrationRequiredError:e}=await import(`./migration-required-BQyPg-Sn.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 k;if(S){const t=await runDoctorPluginConvergence({cfg:O?.config??D,env:process.env,retainedPluginIds:y.retainedPluginIds(),measure:e.measure,deferPackageRepair:e.deferPluginPackageRepair});C||=t.changed===true;setActiveDegradedPlugins(t.quarantinedPlugins);await y.converged(t.deferredPlugins??[],T,v?.pluginMetadataSnapshot,t.migrationInspection);const n=await readConfigSnapshotForPreflight(false);d.push(...t.warnings??[]);v=n;b.invalidate();T=n.snapshot;D=T.sourceConfig??T.config??{};O=await planAdmittedConfigRepair(T);k=O?.snapshot.config}const A=resolveStateMigrationConfigInput({snapshot:T,baseConfig:D,postConvergenceConfig:k});const j=A?.cfg?tryGetLegacyDefaultAgentId(A.cfg):void 0;if(S){if(e.doctorOnlyStateMigrations===true&&!A?.cfg){const{detectLegacyExecApprovals:e,migrateLegacyExecApprovals:t}=await import(`./state-migrations.exec-approvals-DbUrCCzo.mjs`);const{getActiveOpenClawStateDatabaseReadSnapshotAsync:n,withOpenClawStateDatabaseReadSnapshot:r}=await import(`./openclaw-state-db-readonly-j3ciDtyb.mjs`);const i=resolveStateDir(process.env);noteDoctorStateMigrationResult(await measurePreflightStep(`exec-approvals-migration`,async()=>{const a=await r(async()=>{await n();return e({stateDir:i,doctorOnlyStateMigrations:true})});return t({detected:a,stateDir:i,env:process.env})}))}if(A){if(A.cfg){const{autoMigrateLegacyState:t}=await import(`./state-migrations.doctor-DVSvDgfM.mjs`);const n=A.cfg;const r=A.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}));f.push(...e.targets);noteDoctorStateMigrationResult({changes:[],warnings:e.warnings})}const o=await measurePreflightStep(`legacy-state-migrations`,()=>b.run({config:r??n},()=>t({cfg:n,sourceConfigBeforeMigrations:A.sourceConfigBeforeMigrations,...r?{pluginDoctorConfig:r}:{},configIncludedPaths:T.includedPaths??[],env:process.env,doctorOnlyStateMigrations:e.doctorOnlyStateMigrations,invocationPurpose:e.invocationPurpose,integrityCheck:e.integrityCheck,inspectedSessionEntryPaths:_,...e.agentDatabaseMigrationDiscovery?{agentDatabaseMigrationDiscovery:e.agentDatabaseMigrationDiscovery}:{},beforeWorkspaceStateMigration:e.beforeWorkspaceStateMigration,onStepReceipt:e=>p.push(e)})));m=o.postSessionPluginMigration;h=e.doctorOnlyStateMigrations===true;g=e.doctorOnlyStateMigrations===true;noteDoctorStateMigrationResult(o);if(e.doctorOnlyStateMigrations===true)await assertDoctorPreflightMigrationsComplete({cfg:n,stepReceipts:p,report:noteDoctorStateMigrationResult})}else if(A.pluginDoctorConfig){const e=A.pluginDoctorConfig;await migrateRetainedStore({config:e,env:process.env,measure:measurePreflightStep,report:noteDoctorStateMigrationResult});await y.migrate(e)}}}if(S&&e.doctorOnlyStateMigrations===true&&!g){const{migrateLegacyMediaPersistence:t}=await import(`./state-migrations.media-persistence-B6AT8n9l.mjs`);noteDoctorStateMigrationResult(await measurePreflightStep(`media-persistence-migration`,()=>t({env:process.env,integrityCheck:e.integrityCheck})));const{repairLegacySessionEntryStates:n}=await import(`./doctor-session-delivery-state-DG9tmbL6.mjs`);const r=await n({apply:true,cfg:O?.config??D,env:process.env,integrityCheck:e.integrityCheck});d.push(...r.warnings??[])}if(S&&e.doctorOnlyStateMigrations===true){const{retireDoctorA2uiWidgets:t}=await import(`./doctor-a2ui-widgets-B950yxrc.mjs`);const n=await measurePreflightStep(`retired-a2ui-widgets`,()=>t({cfg:O?.config??D,env:process.env,integrityCheck:e.integrityCheck}));noteDoctorStateMigrationResult(n);d.push(...n.warnings)}if(await y.complete()){const e=T;v=await readConfigSnapshotForPreflight(false);T=v.snapshot;C||=Boolean(describeConfigSnapshotInputChange(e,T))||e.valid!==T.valid||!isDeepStrictEqual(e.config,T.config);D=T.sourceConfig??T.config??{};O=await planAdmittedConfigRepair(T)}if(S&&e.doctorOnlyStateMigrations===true){const{repairRelativeSessionStores:t}=await import(`./doctor-relative-session-store-DzTIYm4n.mjs`);noteDoctorStateMigrationResult(await measurePreflightStep(`relative-session-store`,()=>t({cfg:O?.config??D,env:process.env,registeredDatabases:e.agentDatabaseMigrationDiscovery?.registeredAgentDatabases})))}const M=e.automaticHeartbeatRepair;if(M&&!l){const{commitAutomaticHeartbeatRepair:e}=await import(`./doctor-automatic-heartbeat-repair-C1zTy9xw.mjs`);const t=await measurePreflightStep(`automatic-heartbeat-config-repair`,()=>b.run({config:T.sourceConfig},()=>e(M,T)));noteDoctorMigrationResult({changes:t,warnings:[]});C||=t.length>0;v=await readConfigSnapshotForPreflight(false);T=v.snapshot;D=T.sourceConfig??T.config??{};O=await planAdmittedConfigRepair(T)}if(O&&!i){C=true;a??=T.sourceConfigBeforeMigrations??T.sourceConfig;const t=O;await measurePreflightStep(`automatic-config-repair`,()=>b.run({config:t.config},()=>commitAutomaticConfigRepair(t,T,e.doctorOnlyStateMigrations===true&&!l?async e=>{const{retireHeartbeatWithDoctor:t}=await import(`./doctor-heartbeat-retirement-CSbLpw57.mjs`);const{normalizeHeartbeatRepairSource:n}=await import(`./doctor-automatic-heartbeat-repair-C1zTy9xw.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${O.changes.map(e=>`- ${e}`).join(`
`)}`,`Doctor changes`);v=await readConfigSnapshotForPreflight(false);T=v.snapshot;D=T.sourceConfig??T.config??{}}const N=y.deferred();return{snapshot:T,baseConfig:D,configChanged:C,stateMigrationUnsettled:u,...d.length>0?{warnings:d}:{},rosterMigrationSource:ee,...j?{rosterMigrationOwnerId:j}:{},...N.length>0?{deferredPluginMigrations:N}:{},...a?{modelBillingRouteMigrationSource:a}:{},...o?{heartbeatMigrationSource:o}:{},...s?{heartbeatMigrationDeferred:true}:{},...l?{cronStoreSelectionUnresolved:true}:{},...v.pluginMetadataSnapshot?{pluginMetadataSnapshot:v.pluginMetadataSnapshot}:{},...f.length>0?{cronCodexRuntimePolicyTargets:f}:{},...p.length>0?{stateMigrationStepReceipts:p}:{},...m?{postSessionPluginMigration:m}:{},...h?{postSessionPluginMigrationPlanBound:true}:{},...h&&N.length===0&&isDeepStrictEqual(A?.cfg,D)&&p.every(e=>e.id===`plugin-doctor-post-session-state`||(e.outcome===`completed`||e.outcome===`skipped`)&&e.warnings.length===0)?{preflightLegacyStateConfig:D}:{}}}catch(e){n.e=e}finally{await n.d()}}
//!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(`
`);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(`
`)]:[]]}}
//!src/commands/doctor/finalize-config-flow.ts
function doctorConfigRevision(e){return{path:e.path,hash:e.hash??hashConfigRaw(e.raw)}}async function finalizeDoctorConfigFlow(e){const t=doctorConfigRevision(e.snapshot);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(`
`),`Doctor`)}return{cfg:n,shouldWriteConfig:r,confirmedConfigSource:t}}
//!src/commands/doctor/shared/config-migration-result.ts
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-CR4UkMoG.mjs`);const{resolveHeartbeatAutomationModel:t}=await import(`./doctor-heartbeat-model-DkkpfNBK.mjs`);const{prepareProviderModelPolicySurfaces:r}=await import(`./provider-model-routes-DBM0K6WS.mjs`);await r();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}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-DVl4YIDw.mjs`);n=await 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-mEgC_KET.mjs`);const{prepareLivePluginDoctorStateMigrationInventory:n}=await import(`./doctor-contract-preparation-DZ-sEqwD.mjs`);s=await t.runWithCurrentPluginMetadata(t.cfg,async()=>e({mode:`doctor`,inventory:await n({config:t.cfg,env:process.env})}));if(s.step.refusal){const{createLegacyStateMigrationStepReceipt:e}=await import(`./state-migrations.messages-BuqhsWBd.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}:{}}}}
//!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}
//!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}}}
//!src/commands/doctor/shared/legacy-config-core-normalizers.ts
const log=createSubsystemLogger(`doctor`);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}}}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`];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.`)}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]}}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}]`)}}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}))}}}
//!src/commands/doctor/shared/legacy-secret-inputs.ts
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}}
//!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)}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}}
//!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`}.`)}async 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=await 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);await preparePluginDoctorContractModules({config:a,surfaces:[`configRepair`]});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}:{}}}
//!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-Cn_wbk5p.mjs`);note(t(await 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-BdNAiTK1.mjs`);const f=n.use(d({getBaseSnapshot:()=>u.current,env:process.env,getDeferredPluginIds:()=>a.deferredPluginMigrations?.map(e=>e.pluginId)??[]}));const runWithCurrentPluginMetadata=(e,t)=>{const n=tryResolveSoleAgentId(e);return f.run({config:e,workspaceDir:n?resolveAgentWorkspaceDir(e,n):void 0},t)};let p={cfg:s,candidate:await retainHeartbeatMigrationInput(s,a.heartbeatMigrationSource),pendingChanges:false,fixHints:[]};const m=[];let h=false;let g;let _=false;let v=[`model-retirement`];let y=false;const b=[];let x;const S=formatCliCommand(`openclaw doctor --fix`);const C=createDoctorChangesPanelSink(r);const w=[...a.warnings??[]];const applyConfigMutation=(e,t,n={})=>{C.emit(e.changes,n.sanitize?{sanitize:true}:{});if(n.emitWarnings!==false&&e.warnings?.length){emitDoctorNotes({note,warningNotes:e.warnings});w.push(...e.warnings)}p=applyDoctorConfigMutation({state:p,mutation:e,shouldRepair:r,fixHint:t})};const T=prepareDoctorConfigMigrationResult(a,o);await runWithCurrentPluginMetadata(p.candidate,()=>preparePluginDoctorContractModules({config:p.candidate,surfaces:[`configRepair`]}));const ee=runWithCurrentPluginMetadata(p.candidate,()=>planProviderRenames(o.sourceConfigBeforeMigrations??o.sourceConfig,resolvePluginDoctorProviderRenames({config:p.candidate})));const E=o.sourceConfigBeforeMigrations??o.sourceConfig;const D=findLegacyConfigRuleIssues(E,LEGACY_AGENT_ROSTER_RULES).length>0||listAgentEntries(E).length===0||s.agents?.ownership===void 0&&listAgentEntries(s).length>1;const O=runWithCurrentPluginMetadata(p.candidate,()=>applyLegacyCompatibilityStep({snapshot:o,state:p,shouldRepair:r,doctorFixCommand:S}));p=O.state;const k=a.rosterMigrationOwnerId??tryGetLegacyDefaultAgentId(p.candidate)??resolveLegacyAgentRosterOwner(a.rosterMigrationSource??E);if(k){retainLegacyDefaultAgentId(p.cfg,k);retainLegacyDefaultAgentId(p.candidate,k)}const A=o.exists&&D&&!configIncludeOwnsAgentRoster(o);if(A){applyConfigMutation({config:p.candidate,changes:[`Prepared the agent roster for persistence.`]},`Run "${S}" to persist the explicit agent roster.`,{emitWarnings:false});if(p.candidate.agents?.ownership===`explicit`)m.push([`agents`,`ownership`])}if(o.valid&&p.candidate.models?.providers){const{offerOllamaCloudOutputCapRepair:t}=await import(`./doctor-ollama-output-caps-9sc6ro0q.mjs`);applyConfigMutation(await t({config:p.candidate,authored:o.authoredConfig??o.sourceConfig,cloudCatalog:a.pluginMetadataSnapshot?.byPluginId.get(`ollama`)?.modelCatalog?.providers?.[`ollama-cloud`],prompter:e.prompter}),`Run "${S}" interactively to review the saved Ollama Cloud output cap.`)}const{prepareSessionStoreOwnerRecovery:j}=await import(`./doctor-session-store-owner-DItw2p7_.mjs`);const M=await j({config:p.candidate,snapshot:o,prompter:e.prompter});applyConfigMutation(M,`Run "${S}" to review session-store ownership recovery.`,{sanitize:true});const{collectBlockedLegacyOpenAICodexProviderPlan:N}=await import(`./legacy-config-migrations.runtime.models-DQuODlqQ.mjs`);const P=N(p.candidate);const F=new Set(P.blockedModelIdentities);if(a.cronCodexRuntimePolicyTargets?.length){const{repairCronCodexRuntimePolicies:e}=await import(`./runtime-policy-migration-DC2bHGL6.mjs`);const t=e({cfg:p.candidate,targets:a.cronCodexRuntimePolicyTargets,blockedModelIdentities:F});applyConfigMutation(t,`Run "${S}" to preserve migrated cron runtime policy.`);const n=new Set(t.blockedTargets.map(cronCodexRuntimePolicyTargetKey));h=a.cronCodexRuntimePolicyTargets.some(e=>!n.has(cronCodexRuntimePolicyTargetKey(e)))}const te=await(async()=>{if(o.parsed===o.sourceConfig)return[];const{findDoctorLegacyConfigIssues:e}=await import(`./legacy-config-issues-DroR_z-z.mjs`);return runWithCurrentPluginMetadata(p.candidate,()=>withPreparedPluginSetupRead(()=>e(o.parsed,o.parsed)))})();const ne=new Set(o.legacyIssues.map(e=>`${e.path}:${e.message}`));const I=te.filter(e=>{const t=`${e.path}:${e.message}`;if(ne.has(t))return false;ne.add(t);return true}).map(e=>`- ${e.path}: ${e.message}`);const re=[...O.issueLines,...I];if(I.length>0&&!r&&!p.fixHints.includes(`Run "${S}" to migrate legacy config keys.`))p.fixHints.push(`Run "${S}" to migrate legacy config keys.`);if(re.length>0)note(re.join(`
`),`Legacy config keys detected`);C.emit(O.changeLines);const{repairGeneratedModelMetadataCorruption:ie}=await import(`./model-metadata-corruption-repair-DbZofEjy.mjs`);applyConfigMutation(runWithCurrentPluginMetadata(p.candidate,()=>ie({config:p.candidate,authoredRoot:o.parsed,configPath:o.path,currentHash:hashConfigRaw(o.raw),loadAuditRecords:()=>readRecentConfigAuditRecords({env:process.env,homedir,limit:2048})})),`Run "${S}" to remove audit-proven generated model metadata.`);noteDoctorHookConfigWarnings(p.cfg,o.path);applyConfigMutation(await runWithCurrentPluginMetadata(p.candidate,()=>normalizeCompatibilityConfigValues(p.candidate,{blockedModelIdentities:F,sourceRaw:o.parsed})),`Run "${S}" to apply these changes.`);const{recoverCommandOwnerTargetKinds:ae}=await import(`./doctor-command-owner-recovery-uaqvQl8F.mjs`);applyConfigMutation(runWithCurrentPluginMetadata(p.candidate,()=>ae({config:p.candidate,snapshot:o})),`Run "${S}" to restore recorded command-owner target kinds.`,{sanitize:true});const{repairUnownedChannelAccountBindings:oe}=await import(`./legacy-config-binding-repair-IT6DdjWC.mjs`);applyConfigMutation(runWithCurrentPluginMetadata(p.candidate,()=>oe({config:p.candidate,sourceConfigBeforeMigrations:o.sourceConfigBeforeMigrations})),`Run "${S}" to preserve channel account ownership.`);const{collectTailscaleConfigWarnings:se}=await import(`./doctor-tailscale-CsEfi89h.mjs`);const L=await se({cfg:p.candidate,env:process.env});emitDoctorNotes({note,warningNotes:L});w.push(...L);const{prepareRetiredPhoneControlCleanup:ce}=await import(`./doctor-retired-phone-control-BgbulEw3.mjs`);const R=await ce({cfg:p.candidate,env:process.env});applyConfigMutation({config:R.config,changes:R.configChanges,warnings:R.warnings},`Run "${S}" to retire Phone Control lease configuration.`);if(R.cleanupPending&&!r)note(`Retired Phone Control lease state remains. Run "${S}" to archive it.`,`Legacy state detected`);const{recoverInstalledPluginConfigIds:le}=await import(`./installed-plugin-id-recovery-KQ2ftzTt.mjs`);const z=await le(p.candidate,process.env);applyConfigMutation({...z,warnings:z.notices},`Run "${S}" to apply these changes.`);if(l)l.installedPluginIdRecovery=z.recovery;const ue=p.candidate;const{collectCodexPluginActivationWarnings:de}=await import(`./codex-plugin-activation-warning-oTRpAJtE.mjs`);emitDoctorNotes({note,warningNotes:de(ue)});const{applyPluginAutoEnableAsync:fe}=await import(`./plugin-auto-enable-vCVcote7.mjs`);applyConfigMutation(await runWithCurrentPluginMetadata(p.candidate,()=>fe({config:p.candidate,env:process.env})),`Run "${S}" to apply these changes.`,{emitWarnings:false});if(!r){const{repairStaleAgentModelRefs:e}=await import(`./stale-agent-model-ref-repair-DZMi_uk4.mjs`);const t=runWithCurrentPluginMetadata(p.candidate,()=>e(p.candidate,{env:process.env}));x=t.retiredModelRefConfig;applyConfigMutation(t,`Run "${S}" to remove stale agent model references.`,{sanitize:true})}const[{collectPluginToolAllowlistWarnings:pe},{collectGitHubUpgradeWarnings:me},{normalizePluginsConfig:he}]=await Promise.all([import(`./plugin-tool-allowlist-warnings-CsQ6B5p4.mjs`),import(`./github-preview-upgrade-CN2ZI3Ss.mjs`),import(`./config-state-SzRidEbE.mjs`)]);const B=[...runWithCurrentPluginMetadata(p.candidate,()=>pe({cfg:p.candidate,env:process.env})),...me(he(p.candidate.plugins))];if(B.length>0)note(sanitizeDoctorNote(B.join(`
`)),`Doctor warnings`);const ge=listDoctorConfiguredChannelIds(p.candidate,{configEntryPolicy:`raw`}).length>0;let V;if(ge){const e=await import(`./channel-doctor-DhwxQp-5.mjs`);V=e.collectChannelDoctorMutableAllowlistWarnings;const t=await runWithCurrentPluginMetadata(p.candidate,()=>e.runChannelDoctorConfigSequences({cfg:p.candidate,env:process.env,shouldRepair:r}));emitDoctorNotes({note,changeNotes:t.changeNotes,infoNotes:t.infoNotes,warningNotes:t.warningNotes});y=t.changeNotes.length>0||t.warningNotes.length>0;const n=await runWithCurrentPluginMetadata(p.candidate,()=>e.collectChannelDoctorStaleConfigMutations(p.candidate,{env:process.env}));for(const e of n)applyConfigMutation(e,`Run "${S}" to remove stale channel plugin references.`,{sanitize:true})}const{repairHooksTokenReuseGatewayAuth:_e}=await import(`./hooks-token-reuse-repair-BNzTrfVK.mjs`);applyConfigMutation(await _e(p.candidate,process.env),`Run "${S}" to rotate hooks.token away from Gateway auth.`,{emitWarnings:false});const{repairSystemAgentWorkspacePin:H}=await import(`./system-agent-workspace-repair-n5c8kVMU.mjs`);const U=isRecord(o.parsed)?o.parsed.agents:void 0;const W=isRecord(U)?U.defaults:void 0;const ve=o.authoredConfig?.agents?.defaults?.workspace??(isRecord(W)?W.workspace:void 0);const ye={includeOwnsRoster:configIncludeOwnsAgentRoster(o),authoredDefaultWorkspace:typeof ve===`string`?ve:void 0};const G=await H(p.candidate,process.env,{...ye,applyFiles:r});m.push(...G.explicitSetPaths??[]);applyConfigMutation(G,`Run "${S}" to pin the system agent's workspace.`);if(r){const{runDoctorRepairSequence:t}=await import(`./repair-sequencing-ibgepWeM.mjs`);const n=e.prompter;const r=await withDoctorProgress(formatDoctorProgressPhase(`Config repairs`),()=>t({state:p,installedPluginIdRecovery:z.recovery,doctorFixCommand:S,modelReplacements:e.options.modelReplacements,reportFindings:e.reportFindings,env:process.env,blockedCodexProviderPlan:P,pluginMetadataSnapshotState:u,runWithPluginMetadataSnapshot:f.run,...n?{onCapabilityConsent:createPluginCapabilityConsentPrompter({note:async(e,t)=>note(e,t),confirm:e=>n.confirmRuntimeRepair({...e,requiresInteractiveConfirmation:true})})}:{}}),e.options.json!==true);p=r.state;w.push(...r.repairWarningNotes);b.push(...r.advisoryNotes);if(l)l.installedPluginIdRecovery=new Map([...z.recovery,...r.installedPluginIdRecovery]);u.current=r.pluginMetadataSnapshot;g=r.openAICodexAuthProfileIdMap;x=r.retiredModelRefConfig;_=r.modelRetirementRepairRan;v=r.modelRetirementBlockers;if(r.authProfilesRepaired){const{refreshGatewayAuthStateAfterAuthProfileRepair:e}=await import(`./auth-profile-repair-eRHqES_1.mjs`);await e()}emitDoctorRepairSequenceNotes({note,repairSequence:r,structuredWarnings:Boolean(e.reportFindings),emitConfigChange:e=>C.emit([e])})}else{const{collectDoctorPreviewNotes:t}=await import(`./preview-warnings-ChmchL3I.mjs`);const n=await runWithCurrentPluginMetadata(p.candidate,()=>t({cfg:p.candidate,activationSourceConfig:ue,doctorFixCommand:S,env:process.env,allowExec:e.options.allowExec===true,blockedCodexProviderPlan:P}));emitDoctorNotes({note,infoNotes:n.infoNotes,warningNotes:n.warningNotes})}const K=V?await runWithCurrentPluginMetadata(p.candidate,()=>V({cfg:p.candidate,env:process.env})):[];if(K.length>0)note(sanitizeDoctorNote(K.join(`
`)),`Doctor warnings`);const q=p;p=await applyRetiredConfigStep({state:p,shouldRepair:r,doctorFixCommand:S,sourceConfig:o.sourceConfig,emitChanges:C.emit,preflight:a});const J=await finalizeDoctorConfigFlow({...p,snapshot:o,shouldRepair:r,confirm:e.confirm,note});const Y=J.shouldWriteConfig&&!O.blocksWrite&&!c;const X=!r&&Y&&G.restorePending?await H(J.cfg,process.env,{...ye,applyFiles:true}):void 0;if(X){m.push(...X.explicitSetPaths??[]);if(X.warnings?.length){emitDoctorNotes({note,warningNotes:X.warnings});w.push(...X.warnings)}}const Z=X?.config??J.cfg;const be=Y&&canWriteDoctorInclude(o,Z,{persistCanonicalAgentRoster:A,explicitSetPaths:m},l?.installedPluginIdRecovery);await runWithCurrentPluginMetadata(Z,()=>preparePluginDoctorContractModules({config:Z,surfaces:[`configRepair`]}));await noteConfigAdvisories(Z,runWithCurrentPluginMetadata);const Q=await T({cfg:Z,modelBillingRouteConfig:q.candidate,shouldWriteConfig:Y,pluginInventoryChanged:u.inventoryChanged,metadataSnapshot:u.current,runWithCurrentPluginMetadata});const invalidatePluginMetadataSnapshot=()=>{delete we.preflightLegacyStateConfig;u.current=void 0;f.invalidate()};const xe=C.drain(X?.changes);const $=O.blocksWrite?[]:ee;await setAppliedRuntimeConfigSnapshot(Z,Z);const Se=n.move();const Ce=[...v,p!==q&&`config-repair`,!o.exists&&`config-missing`,!o.valid&&`config-invalid`,O.blocksWrite&&`legacy-write-blocked`,c&&`heartbeat-deferred`,!a.preflightLegacyStateConfig&&`preflight-unsettled`,a.configChanged&&`preflight-config-changed`,a.stateMigrationUnsettled&&`state-migration-unsettled`,a.cronStoreSelectionUnresolved&&`cron-selection-unresolved`,Boolean(a.heartbeatMigrationSource)&&`heartbeat-migration`,Boolean(a.modelBillingRouteMigrationSource)&&`billing-migration`,w.length>0&&`repair-warning`,K.length>0&&`mutable-allowlist-warning`,B.length>0&&`plugin-warning`,Boolean(Q.modelBillingRouteWarnings?.length)&&`billing-warning`,u.inventoryChanged&&`plugin-inventory-changed`,y&&`channel-work`,$.length>0&&`provider-renames`,F.size>0&&`blocked-models`,R.cleanupPending&&`phone-cleanup`,Q.postSessionPluginMigrationPlanBound!==true&&`session-plan-unbound`,Boolean(Q.postSessionPluginMigration?.step.refusal)&&`session-plan-refused`].filter(e=>Boolean(e));const we={[Symbol.asyncDispose]:()=>Se.disposeAsync(),...J,cfg:Z,heartbeatMigrationSource:q.candidate,confirmedConfigSource:Y&&M.changes.length>0?doctorConfigRevision(o):J.confirmedConfigSource,...l?{referenceSource:l}:{},path:o.path??CONFIG_PATH,shouldWriteConfig:Y,...w.length||b.length?{warnings:[.../* @__PURE__ */ new Set([...w,...b])]}:{},...Y&&xe.length>0?{pendingChangePanels:xe}:{},sourceConfigValid:o.valid,...O.partiallyValid===true?{skipPluginValidationOnWrite:true}:{},...Y&&m.length>0?{explicitSetPaths:m}:{},...Y&&A?{persistCanonicalAgentRoster:true}:{},...be?{skipWizardMetadataForIncludeWrite:true}:{},...h?{shouldRepairCronCodexModelRefsAfterConfigWrite:true}:{},...r&&R.cleanupPending&&R.cleanupSafe?{retiredPhoneControlStateCleanupPending:true}:{},...P.blockedModelIdentities.length>0?{blockedCodexModelIdentities:P.blockedModelIdentities}:{},...g?{openAICodexAuthProfileIdMap:g}:{},...x?{retiredModelRefConfig:x}:{},...$.length>0?{providerRenames:$}:{},modelRetirementRepairRan:_&&!O.blocksWrite&&(Y||o.valid),retirementOnly:Ce.length===0,retirementOnlyBlockers:Ce,...Q,runWithPluginMetadataSnapshot:f.run,invalidatePluginMetadataSnapshot};return we}catch(e){t.e=e}finally{await t.d()}}export{loadAndMaybeMigrateDoctorConfig};