openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
10 lines • 17.1 kB
JavaScript
import{C as resolveIsNixMode,S as resolveIsConfigReadOnly}from"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{a as resolveUpdateRehearsalRoot}from"./update-rehearsal-paths-C4qLj9oD.mjs";import{S as runUpdateDoctorIncludeWrite,b as recordUpdateDoctorConfigWriteRefusal,h as getUpdateDoctorConfigWriteAuthority,v as recordUpdateDoctorConfigMigration}from"./update-doctor-result-B09W3zwf.mjs";import{t as ConfigWritePostCommitError}from"./io.write-errors-CQyW8lY6.mjs";import{g as shouldSkipLegacyUpdateDoctorConfigWrite}from"./update-phase-CCaxuca0.mjs";import{i as recordUpdateModelRetirement}from"./update-deferred-model-retirement-DpFGk6Fh.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{a as resolveLegacyParentVersionOverride,n as noteDoctorRepairResult,r as resolveDoctorMode,t as isUpdateDoctorRun}from"./doctor-health-contribution-utils-DsM0Tsf-.mjs";import fs from"node:fs";import path from"node:path";
//!src/flows/doctor-health-contribution-runners.config.ts
async function runRetiredAuthProfileCleanup(e){if(e.externalConfigRepairsPending)return;const t=e.configResult.retiredAuthProfileCleanupPlans;if(!t?.length)return;const{removeAuthProfilesAcrossOwnerStores:n}=await import(`./auth-profiles-BGlKZMbD.mjs`);for(const r of t)if(!await n({...r,cfg:e.cfg}))throw new Error(`Failed to remove retired auth profile "${r.profileIds.join(`, `)}".`);delete e.configResult.retiredAuthProfileCleanupPlans}async function runWriteConfigHealth(e,t={}){if(e.configWriteError)throw e.configWriteError;if(e.configWriteRefusal)return false;const{applyWizardMetadata:n}=await import(`./onboard-helpers-Dx2uoGe6.mjs`);const{copyConfigResolutionFactsThroughRewrite:r}=await import(`./resolution-facts-D4JgkRHv.mjs`);const{ConfigMutationConflictError:i,readConfigFileSnapshot:a,transformConfigFile:o}=await import(`./config/config.js`);const{collectChangedConfigPaths:s}=await import(`./include-write-boundary-Dbq2qtir.mjs`);const{hashConfigRaw:c}=await import(`./io.read-helpers-Dy7TdS1M.mjs`);const{resolveConfigIncludeWriteBoundary:l}=await import(`./mutate-DK9uDX4F.mjs`);const{isDeepStrictEqual:u}=await import(`node:util`);const{getDeferredPluginMigrationConfigFacts:d,preserveDeferredPluginMigrationConfig:f}=await import(`./deferred-plugin-migration-config-D-jbSsCt.mjs`);const{createSubsystemLogger:p}=await import(`./subsystem-DyP22TCO.mjs`);const{recordDoctorHealthWarnings:m}=await import(`./doctor-health-contribution-BggjyZTd.mjs`);const{logConfigUpdated:h}=await import(`./logging-BoexquPk.mjs`);const{shortenHomePath:g}=await import(`./utils-B7PqG5qw.mjs`);const _=e.configResult.providerRenames??[];const v=e.prompter.shouldRepair&&_.length>0;const y=e.configResult.shouldWriteConfig===true&&e.configResultWriteCommitted!==true||v;const b=y||JSON.stringify(e.cfg)!==JSON.stringify(e.cfgForPersistence);if(resolveIsConfigReadOnly(e.env??process.env)){if(b){const{reportDoctorExternalConfigRepairs:t}=await import(`./doctor-external-config-Bnd92SSh.mjs`);await t(e);return false}if(e.externalConfigRepairsPending)return false}if(b&&shouldSkipLegacyUpdateDoctorConfigWrite(e.env??process.env)){e.runtime.log(`Skipping doctor config write during legacy update handoff.`);return false}if(v){const{maybeRepairCodexSessionRoutes:t}=await import(`./codex-route-session-repair-BGdG_KxT.mjs`);const{maybeRepairProviderRenameCronJobs:n}=await import(`./provider-rename-state-DAaLR92K.mjs`);const{applyProviderRenames:i}=await import(`./provider-rename-BynXBMQZ.mjs`);const a=await n({renames:_,env:e.env});noteDoctorRepairResult(a);const o=await t({cfg:e.cfg,providerRenames:_,providerRenameOnly:true,env:e.env,shouldRepair:true});noteDoctorRepairResult(o);if(a.warnings.length>0||o.warnings.length>0)throw new Error(`Provider references could not be fully repaired. Config was preserved; rerun openclaw doctor --fix.`);const s=i(e.cfg,_);r(e.cfg,s.config);e.cfg=s.config;if(s.changes.length>0)e.configResult.pendingChangePanels=[...e.configResult.pendingChangePanels??[],s.changes.join(`
`)]}if(b){const t=isUpdateDoctorRun(e.env??process.env);const{readDeferredPluginMigrationsAsync:_}=await import(`./deferred-plugin-migrations-C_CDW6O2.mjs`);const b=await _({env:e.env??process.env});const{restoreDoctorConfigEnvRefs:x}=await import(`./config-flow-steps-Cgh29i_c.mjs`);const{preparePluginDoctorContractModules:S}=await import(`./doctor-contract-preparation-DZ-sEqwD.mjs`);await S({config:e.cfg,surfaces:[`configRepair`]});const{prepareDoctorConfigWriteStage:C}=await import(`./roster-include-write-cwFt6mqw.mjs`);let w=y?await a({observe:false,skipPluginValidation:true,deferredPluginMigrations:b}):void 0;let T=w?C({snapshot:w,nextConfig:x(e.cfg,e.configResult.referenceSource,e.configResult.explicitSetPaths),persistCanonicalAgentRoster:e.configResult.persistCanonicalAgentRoster,installedPluginIdRecovery:e.configResult.referenceSource?.installedPluginIdRecovery,explicitSetPaths:e.configResult.explicitSetPaths}):void 0;if(T)e.configResult.skipWizardMetadataForIncludeWrite=true;if(e.configResult.skipWizardMetadataForIncludeWrite!==true&&!resolveUpdateRehearsalRoot(e.env??process.env)){const t=n(e.cfg,{command:`doctor`,mode:resolveDoctorMode(e.cfg)});r(e.cfg,t);e.cfg=t}const E=resolveLegacyParentVersionOverride(e).lastTouchedVersionOverride;const{findRetiredConfigUpgradeRequirement:D}=await import(`./retired-config-formats-Bfo3eTcX.mjs`);const{assertInstalledPluginIdRecoveryCurrent:O}=await import(`./installed-plugin-id-recovery-KQ2ftzTt.mjs`);const k=e.configResult.referenceSource?.installedPluginIdRecovery;let A;let j=false;try{while(T&&w){const t=T;const n={...e,cfg:t.config,cfgForPersistence:w.sourceConfig,configResultWriteCommitted:false,configResult:{cfg:t.config,shouldWriteConfig:true,confirmedConfigSource:e.configResult.confirmedConfigSource,referenceSource:e.configResult.referenceSource,persistCanonicalAgentRoster:t.persistCanonicalAgentRoster,skipWizardMetadataForIncludeWrite:true,skipPluginValidationOnWrite:t.persistCanonicalAgentRoster||e.configResult.skipPluginValidationOnWrite,preservedLegacyRootKeys:e.configResult.preservedLegacyRootKeys,explicitSetPaths:e.configResult.explicitSetPaths?.filter(([e])=>!t.persistCanonicalAgentRoster||e===`agents`)}};try{if(!await runWriteConfigHealth(n,{runPostWriteRepairs:false})){e.configWriteRefusal=n.configWriteRefusal;return false}}finally{if(n.configWriteError)e.configWriteError=n.configWriteError;if(n.configResultWriteCommitted){e.configResult.confirmedConfigSource=n.configResult.confirmedConfigSource;e.cfgForPersistence=n.cfgForPersistence;if(t.persistCanonicalAgentRoster)delete e.configResult.persistCanonicalAgentRoster;j=true}}const r=`Saved a config migration stage; remaining repairs are still pending.`;recordUpdateDoctorConfigMigration(r);e.runtime.log(r);const o=await a({observe:false,skipPluginValidation:true,deferredPluginMigrations:b});if(o.path!==e.configResult.confirmedConfigSource?.path||o.hash!==e.configResult.confirmedConfigSource?.hash)throw new i(`config changed after Doctor saved a migration stage`,{retryable:false});const{cloneConfigWithResolutionFacts:s}=await import(`./resolution-facts-D4JgkRHv.mjs`);const{getConfigValueAtPath:c,setConfigValueAtPath:l}=await import(`./config-paths-BUETI18d.mjs`);const u=e.cfg;e.cfg=s(o.sourceConfig);for(const n of t.remainingPaths)l(e.cfg,n,c(u,n));w=o;T=C({snapshot:o,nextConfig:e.cfg,persistCanonicalAgentRoster:e.configResult.persistCanonicalAgentRoster,installedPluginIdRecovery:k,explicitSetPaths:e.configResult.explicitSetPaths})}const n=e.configResult.confirmedConfigSource;if(!n?.hash)throw new i(`Doctor config write has no source revision`,{retryable:false});const{path:r,hash:d}=n;await S({config:e.cfg,surfaces:[`configRepair`]});const f=x(e.cfg,e.configResult.referenceSource,e.configResult.explicitSetPaths);const h=getUpdateDoctorConfigWriteAuthority(e.configPath);const g=h?await a({skipPluginValidation:t,observe:false,deferredPluginMigrations:b}):void 0;const resolveIncludeBoundary=t=>l({snapshot:t,nextConfig:f,persistCanonicalAgentRoster:y?e.configResult.persistCanonicalAgentRoster:void 0,explicitSetPaths:e.configResult.explicitSetPaths});const _=g&&resolveIncludeBoundary(g);const v=_?g:void 0;let M=e.cfg;const persistConfig=n=>{const assertCurrent=()=>{h?.assertCurrent();n?.()};return o({baseHash:d,transform:async(t,{snapshot:r})=>{n?.();h?.assertCurrent();const a=D(r.sourceConfigBeforeMigrations??r.sourceConfig);if(a)throw new i(`${a.message} ${a.nextAction}`);M=r.sourceConfig;await O(M,k,e.env??process.env);assertCurrent();if(_){const e=resolveIncludeBoundary(r);if(!u(e,_))throw new i(`included config changed after Doctor prepared its repairs`,{retryable:false})}const{repairLegacyCronOwnersBeforeConfigWrite:o}=await import(`./legacy-owner-BJvYzqfA.mjs`);const s=await o({snapshot:r,nextConfig:f,env:e.env??process.env,assertCurrent});for(const t of s)e.runtime.log(t);return{nextConfig:f}},afterWrite:{mode:`auto`},writeOptions:{deferredPluginMigrations:b,assertCurrent,...k?.size?{beforeCommit:async()=>{assertCurrent();await O(M,k,e.env??process.env);assertCurrent()}}:{},expectedConfigPath:r,auditOrigin:`doctor`,allowConfigSizeDrop:e.configResult.shouldWriteConfig===true||t,skipPluginValidation:e.configResult.skipPluginValidationOnWrite===true||t,...e.configResult.explicitSetPaths?{explicitSetPaths:e.configResult.explicitSetPaths}:{},persistCanonicalAgentRoster:y?e.configResult.persistCanonicalAgentRoster:void 0,preservedLegacyRootKeys:e.configResult.preservedLegacyRootKeys,...E?{lastTouchedVersionOverride:E}:{}}})};const writeConfig=async()=>{if(!k?.size)return await persistConfig();const{withPluginLifecycleLease:t}=await import(`./plugin-lifecycle-lease-DXYQ3mrW.mjs`);return await t({env:e.env??process.env,assertCurrent:()=>h?.assertCurrent()},e=>persistConfig(()=>e.assertOwned()))};if(v){const t=[...new Set(s(v.sourceConfig,e.cfg).paths.flatMap(([e])=>e===void 0?[]:[e]))].toSorted();A=await runUpdateDoctorIncludeWrite(v.path,c(v.raw),async()=>{const n=`Doctor include-owned keys ${t.join(`, `)}: promotion unavailable for include-owned configuration.`;m(e,[],[n]);p(`update`).warn(n);e.runtime.log(n);return await writeConfig()})}else A=await writeConfig()}catch(t){if(t instanceof ConfigWritePostCommitError){e.configWriteError=t;if(t.publication===`partial`)delete e.configResult.confirmedConfigSource;throw t}recordUpdateDoctorConfigWriteRefusal({reason:`config-write-refused`,message:formatErrorMessage(t),keys:[]});if(t instanceof i){note([`The config changed after Doctor prepared these repairs.`,j?`Earlier config fixes were saved; the remaining fixes were not written. Rerun "openclaw doctor" to review the current config.`:`These config fixes were not written. Rerun "openclaw doctor" to review repairs for the current config.`].join(`
`),`Doctor warnings`);e.configWriteRefusal=`config-conflict`;return false}const{isConfigIncludeOwnershipError:n,isConfigValidationFailedError:r}=await import(`./io.write-errors-s29r7-bx.mjs`);const a=e.configResultWriteCommitted===true||j?`Earlier config fixes were already saved; the remaining changes were not written.`:`No config changes were written.`;if(n(t)){const n=t.includeTargets??[];const r=n.length===0?`its included file`:`the included ${n.length===1?`file`:`files`} ${n.join(`, `)}`;note([`Doctor could not apply config fixes: ${t.message}`,`${a} Repair ${t.ownedConfigPath} in ${r} by hand, then rerun "openclaw doctor --fix" for the remaining changes.`].join(`
`),`Doctor warnings`);e.configWriteRefusal=`include-ownership`;return false}if(r(t)){const{formatConfigIssueLines:n}=await import(`./issue-format-BityoCuQ.mjs`);const r=n(t.issues,`-`,{normalizeRoot:true});note([`Doctor could not apply config fixes: the repaired config still fails validation.`,...r,`${a} Fix the value(s) above in ${g(e.configPath)} by hand, then rerun "openclaw doctor --fix".`].join(`
`),`Doctor warnings`);e.configWriteRefusal=`validation`;return false}const{isCronOwnerWriteRefusalError:o}=await import(`./io.cron-owner-refusal-C4cLLBJf.mjs`);if(!o(t))throw t;note([t.message,j?`Earlier config fixes were saved; the remaining config repairs were not written.`:`Doctor left the config unchanged, preserving any retained legacy owner for a later repair.`,`Resolve the reported Gateway or cron-store condition, then rerun "openclaw doctor --fix".`].join(`
`),`Doctor warnings`);e.configWriteRefusal=`cron-owner-safety`;return false}e.configResult.confirmedConfigSource={path:A.path,hash:A.persistedHash};e.postConfigWriteRepairsCommitted=false;const M=e.configResult.pendingChangePanels;if(M?.length){for(const e of M){note(e,`Doctor changes`);for(const t of e.split(`
`))recordUpdateDoctorConfigMigration(t)}delete e.configResult.pendingChangePanels}e.cfgForPersistence=structuredClone(f({sourceConfig:A.nextConfig,nextConfig:e.cfg,pending:d(A.nextConfig)??[]}));if(e.configResult.shouldWriteConfig===true||v)e.configResultWriteCommitted=true;delete e.configResult.providerRenames;h(e.runtime);const N=`${e.configPath}.pre-update`;if(t&&fs.existsSync(N))e.runtime.log(`Update changed config; pre-update backup: ${g(N)}`)}if(e.configResult.modelRetirementRepairRan===true){recordUpdateModelRetirement(`completed`,e.env??process.env);delete e.configResult.modelRetirementRepairRan}const x=e.configResult.modelBillingRouteWarnings;if(x?.length){const t=p(`doctor`);note(x.join(`
`),`Billing route changes`);for(const e of x)t.warn(e);m(e,[],x);delete e.configResult.modelBillingRouteWarnings}if(t.runPostWriteRepairs===false)return true;await runRetiredAuthProfileCleanup(e);if(e.configResult.retiredPhoneControlStateCleanupPending===true){const{finalizeRetiredPhoneControlCleanup:t}=await import(`./doctor-retired-phone-control-BgbulEw3.mjs`);const n=await t({env:e.env??process.env});noteDoctorRepairResult(n)}if(!e.prompter.shouldRepair&&!e.configResult.openAICodexAuthProfileIdMap?.size&&e.configResult.shouldRepairCronCodexModelRefsAfterConfigWrite!==true||e.postConfigWriteRepairsCommitted===true)return true;const{repairCronCodexModelRefsAfterConfigWrite:S}=await import(`./legacy-repair-CzQbDqyz.mjs`);const C=await S({cfg:e.cfg,migrateCodexModelRefs:e.prompter.shouldRepair||e.configResult.shouldRepairCronCodexModelRefsAfterConfigWrite===true,...e.configResult.retiredModelRefConfig?{retiredModelRefConfig:e.configResult.retiredModelRefConfig}:{},repairRetiredModelRefs:e.prompter.shouldRepair,modelReplacements:e.options.modelReplacements,authProfileIdMap:e.configResult.openAICodexAuthProfileIdMap,...e.configResult.blockedCodexModelIdentities?.length?{blockedModelIdentities:new Set(e.configResult.blockedCodexModelIdentities)}:{}});e.postConfigWriteRepairsCommitted=true;if(C.warnings.length>0)e.retirementOnly=false;noteDoctorRepairResult(C);return true}async function runInitialConfigWriteHealth(e){if(e.configResult.shouldWriteConfig!==true&&!e.configResult.modelBillingRouteWarnings?.length&&e.configResult.modelRetirementRepairRan!==true&&!e.configResult.providerRenames?.length)return;await runWriteConfigHealth(e,{runPostWriteRepairs:false})}async function collectWriteConfigHealthFindings(e){const t=[];const n=e.configPath;const r=resolveIsNixMode(process.env);if(resolveIsConfigReadOnly(process.env))t.push({checkId:`core/doctor/write-config`,severity:`warning`,message:r?`Doctor config writes are disabled because OpenClaw is running in Nix mode.`:`Doctor config writes are disabled because config is externally managed.`,...n?{path:n}:{},requirement:`mutable-config-write-path`,fixHint:r?`Edit the Nix source for this install and rebuild; do not run doctor --fix against this config file.`:`Apply reported config edits in your external deployment source and redeploy; doctor --fix still repairs writable runtime state.`});if(!n)return t;const i=path.dirname(n);const a=fs.existsSync(n);const o=a?i:findNearestExistingParent(i);if(!isDirectoryPath(o)){t.push({checkId:`core/doctor/write-config`,severity:`warning`,message:`Doctor cannot create the config directory because a path component is a file.`,path:o,target:i,requirement:`config-directory-path`,fixHint:`Move the file blocking the config directory path before running doctor --fix.`});return t}try{fs.accessSync(o,fs.constants.W_OK|fs.constants.X_OK)}catch{t.push({checkId:`core/doctor/write-config`,severity:`warning`,message:a?`Doctor cannot write config because the config directory is not writable.`:`Doctor cannot create the config directory because the nearest existing parent is not writable.`,path:o,target:a?n:i,requirement:`writable-config-directory`,fixHint:`Make the existing config directory or parent directory writable before running doctor --fix.`})}return t}function findNearestExistingParent(e){let t=e;while(!pathEntryExists(t)){const e=path.dirname(t);if(e===t)return t;t=e}return t}function pathEntryExists(e){if(fs.existsSync(e))return true;try{fs.lstatSync(e);return true}catch{return false}}function isDirectoryPath(e){try{return fs.statSync(e).isDirectory()}catch{return false}}export{runWriteConfigHealth as i,runInitialConfigWriteHealth as n,runRetiredAuthProfileCleanup as r,collectWriteConfigHealthFindings as t};