openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 18.1 kB
JavaScript
import{n as isTruthyEnvValue}from"./env-fLMEolk5.mjs";import{i as collectNestedErrorCandidates}from"./error-coercion-DlKnt6w-.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{m as resolveConfigPath}from"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{v as withSqliteSnapshotFailureScope}from"./sqlite-error-diagnostics-ASl1MXPN.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{_ as withSqliteReadOnlyWorkerScope}from"./sqlite-readonly-worker-C1mJaAX6.mjs";import{a as resolveUpdateRehearsalRoot}from"./update-rehearsal-paths-C4qLj9oD.mjs";import{t as UpdateSchemaRefusalError}from"./openclaw-update-schema-refusal-CZZooTUg.mjs";import{C as writeUpdatePostInstallDoctorResult,c as captureUpdateDoctorConfigWrites,g as normalizeUpdatePostInstallDoctorWarnings,i as UPDATE_POST_INSTALL_DOCTOR_RESULT_PATH_ENV,m as getUpdateDoctorConfigCapture,o as UpdateDoctorError,r as UPDATE_POST_INSTALL_DOCTOR_ADVISORY_EXIT_CODE,t as DoctorMaintenanceRefusalError}from"./update-doctor-result-B09W3zwf.mjs";import{n as formatUpdateFailureFact}from"./update-failure-facts-format-C98VJrv8.mjs";import{n as createUpdateErrorFact,r as createUpdateFailureFact}from"./update-failure-facts-Bwgg6oY-.mjs";import{t as ConfigWritePostCommitError}from"./io.write-errors-CQyW8lY6.mjs";import{a as resolveCommandProcessSignal,p as withCommandProcessScope}from"./exec-spawn-DNCbDcyJ.mjs";import{n as withDeferredDebugProxyCapture}from"./runtime-deferral-Cbo74gpv.mjs";import{n as withPluginLoadDiagnostics}from"./load-diagnostics-BDh6-SC2.mjs";import{l as formatUpdateDoctorConfigChange}from"./update-run-step-ClF0wlKW.mjs";import{t as formatDoctorProgressPhase}from"./doctor-progress-DGmacsiq.mjs";import{f as isUpdateDoctorLintPass,t as DOCTOR_SQLITE_NOCOW_REPAIR_ENV}from"./update-phase-CCaxuca0.mjs";import{a as resolveDoctorUpdateRun}from"./update-deferred-model-retirement-DpFGk6Fh.mjs";import{n as retainCurrentDeferredUpdateWarnings}from"./deferred-update-warnings-BoCcCY9z.mjs";import{n as retainUpdateDoctorProcesses}from"./update-doctor-process-custody-CGIgIMQt.mjs";import{a as recordDoctorHealthWarnings,c as showDoctorHealthSummary,o as renderStructuredHealthFindings,r as createDoctorHealthFindingBuffer,t as collectDoctorHealthResultWarnings}from"./doctor-health-contribution-CiqEIP_B.mjs";import{n as resolveDoctorRepairMode,t as isDoctorUpdateRepairMode}from"./doctor-repair-mode-Dilz8sGs.mjs";import{a as prepareDoctorMaintenanceArchives,c as repairDoctorStateDatabase,d as showDoctorOutro,f as showDoctorRepairRefusal,i as prepareDoctorInteractiveMaintenance,l as showDoctorComplete,n as exitDoctorHealthFlow,o as prepareDoctorRuntimeChecks,p as withDoctorProgress,r as prepareDoctorHealthFlow,s as prepareDoctorStateSchema,t as createDoctorProgressMeasure,u as showDoctorIntro}from"./doctor-health-startup-WrxcBhpP.mjs";
//!src/commands/doctor-policy-custody.ts
function createDoctorWriteAuthority(e){let t;const n=e.assertCurrent;return{...e,assertCurrent:()=>t?t.assertCurrent(n):n(),lendPolicyCustody:e=>{t=e}}}
//!src/flows/doctor-health-update-result.ts
async function publishDoctorUpdateResult(e){const{updateResult:t,doctorResult:n,healthContext:r,maintenance:i}=e;for(const e of t.capture.configChanges)createSubsystemLogger(`update`).warn(formatUpdateDoctorConfigChange(e));const a=await retainCurrentDeferredUpdateWarnings(collectDoctorHealthResultWarnings({healthContext:r,startupWarnings:e.startupWarnings,resultWarnings:n.warnings,maintenanceWarnings:i?.warnings}),{readUpdateRun:()=>resolveDoctorUpdateRun(r?.env??process.env)});t.capture.warnings=a;if(!t.resultPath)return;const o={...n};delete o.warnings;delete o.deferredInspectionCheckIds;await writeUpdatePostInstallDoctorResult({resultPath:t.resultPath,result:{...o,...t.capture.deferredInspectionCheckIds?{deferredInspectionCheckIds:t.capture.deferredInspectionCheckIds}:{},...i?.databaseWrites?{databaseWrites:i.databaseWrites}:{},...t.capture.fileWrites?{configFileWrites:t.capture.fileWrites}:{},...a.length?{warnings:a}:{},...t.capture.configChanges.length?{configChanges:t.capture.configChanges}:{},...t.capture.configWriteRefusal?{configWriteRefusal:t.capture.configWriteRefusal}:{},configHash:t.capture.hash,...t.capture.inputHash===void 0?{}:{configInputHash:t.capture.inputHash}}})}
//!src/flows/doctor-health.ts
async function runDoctorHealthFlow(e,t={},n,r){try{var i=_usingCtx();const a=resolveCommandProcessSignal(getAsyncWorkSignal());a?.throwIfAborted();const o=n&&createDoctorWriteAuthority(n);const s=i.u(await retainUpdateDoctorProcesses(o?.assertCurrent,o?.commandAuthority));let requestedExit;const run=()=>withDeferredDebugProxyCapture(async n=>{let i=r;const a=o?.databaseGenerations?true:void 0;const s=!o?.postCoreSchemaRepair&&(t.repair===true||t.yes===true)?resolveUpdateRehearsalRoot(process.env):void 0;if(process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`&&!o?.postCoreSchemaRepair){const{guardUpdateDoctorSchemaUpgrade:n,rehearseDeferredUpdateDoctorSchema:r}=await import(`./commands/doctor-update-schema-guard.js`);const o=await withDoctorProgress(formatDoctorProgressPhase(`Update schema admission`),()=>n({schemas:i,runtime:e,json:t.json,statePublicationOnly:s!==void 0,preserveSourceArtifacts:a}),t.json!==true);if(!s)i=o??i;if(!s&&i?.updateSchemaRehearsal){const n=i;await withDoctorProgress(formatDoctorProgressPhase(`Update schema rehearsal`),()=>r(n,e,t.fullIntegrityCheck),t.json!==true);return}}const c=process.env[UPDATE_POST_INSTALL_DOCTOR_RESULT_PATH_ENV]?.trim();return withPluginLoadDiagnostics(r=>{const runDoctor=(a=getUpdateDoctorConfigCapture())=>runDoctorHealthFlowWithResult((e,t)=>{requestedExit=()=>exitDoctorHealthFlow(e,t)},e,t,i,r,a?{resultPath:c,capture:a}:void 0,o,n,s);return c?captureUpdateDoctorConfigWrites(resolveConfigPath(),runDoctor,o):runDoctor()})});const{withPluginGenerationSourceCustody:c}=await import(`./plugin-generation-source-lookup-CZzCWcmf.mjs`);await c(()=>s?withCommandProcessScope(run,void 0,s):run()).catch(async t=>{const{reportDoctorReadOnlyFilesystemError:n}=await import(`./doctor-maintenance-inspection-BCP9Hvz5.mjs`);await n(t,e);throw t});a?.throwIfAborted();requestedExit?.()}catch(e){i.e=e}finally{i.d()}}async function runDoctorHealthFlowWithResult(e,t,n,r,i,a,o,s,c){try{var l=_usingCtx();const u=resolveCommandProcessSignal(getAsyncWorkSignal());const d=createDoctorProgressMeasure(n);const{effectiveRuntime:f,repairRuntime:p,stateDirExistedAtStart:m,root:h}=await d(`doctor.startup`,()=>prepareDoctorHealthFlow(t,n,showDoctorIntro));let g;let _=[];const v={preserveSourceArtifacts:o?.databaseGenerations?true:void 0};let y;let b;let x;const{buffer:S,reportFindings:C}=createDoctorHealthFindingBuffer(f);let w;let T={status:`error`};const recordRepairRefusal=e=>{const t=showDoctorRepairRefusal(e);if(!t)return false;b=1;T=t;return true};const E=resolveDoctorRepairMode(n);let D=false;let O=false;if(E.canPrompt&&!E.shouldRepair){const t=await d(`doctor.maintenance-admission`,()=>prepareDoctorInteractiveMaintenance({runtime:f,options:n,databasePreflight:r,root:h,outro:showDoctorOutro}));if(t!==`accepted`){if(t!==`handled`)e(f,t.diagnosticExitCode);return}D=true;O=true}const k=l.a(new AsyncDisposableStack);k.defer(async()=>g?.release());try{const{assertDoctorRetiredStateAdmission:e}=await import(`./doctor-retired-state-admission-h9BHnZZ4.mjs`);e();const{prepareAutomaticHeartbeatRepair:t}=await import(`./doctor-automatic-heartbeat-repair-C1zTy9xw.mjs`);const l=await t(n);const A=l?{...n,repair:true}:n;if(!E.updateInProgress&&(n.repair===true||n.yes===true||D))w=await d(`doctor.archive-preparation`,()=>prepareDoctorMaintenanceArchives(r,f,v));if(!E.updateInProgress&&!o&&(E.shouldRepair||D)){try{const{cleanupRetainedUpdateRuntimesBeforeMaintenance:e}=await import(`./doctor-retained-runtime-BncOjlbh.mjs`);await d(`doctor.retained-runtimes`,()=>e(process.env))}catch(e){f.error(formatErrorMessage(e))}u?.throwIfAborted()}const[{beginDoctorMaintenance:j},{createDoctorOriginalCaptureHook:M}]=await Promise.all([import(`./doctor-maintenance-D4y7Sc5q.mjs`),import(`./doctor-original-capture-admission-6nrbPoi3.mjs`)]);g=await d(`doctor.maintenance.begin`,()=>j({options:A,interactiveRepair:D,root:h,runtime:p,assertCurrent:o?.assertCurrent,lendPolicyCustody:o?.lendPolicyCustody,databaseGenerations:o?.databaseGenerations,databaseWriteCapture:o?.databaseWriteCapture,databasePluginOwners:o?.databasePluginOwners,serviceInspectionDeadlineAtMs:o?.serviceInspectionDeadlineAtMs,beforeStateMutation:M({root:h,runtime:p,writeAuthority:o,rehearsalRoot:c,json:n.json,reportFindings:C,fullIntegrityCheck:n.fullIntegrityCheck})}));const runChecks=async()=>{u?.throwIfAborted();const e=g?p:f;const{createDoctorPrompter:t}=await import(`./doctor-prompter-BOnP8RlH.mjs`);const{prepareDoctorDatabasePreflight:i}=await import(`./doctor-database-preflight-D4Tb6gBX.mjs`);const a=t({runtime:e,options:n,signal:resolveCommandProcessSignal(g?.signal??u)});if(!g&&!O){if(!r)await d(`doctor.state-preflight`,()=>i({scope:`state`}));const{maybeOfferUpdateBeforeDoctor:e}=await import(`./doctor-update-JA0r4P-7.mjs`);if(await e({options:n,root:h,confirm:e=>a.confirm(e),outro:showDoctorOutro}))return}const c=g&&r?.agentDatabaseMigrationDiscovery?.discovery.deletionJournal.status===`unavailable`;let T=r&&!c?r:await d(`doctor.database-preflight`,()=>i(v));const{recordAgentDatabaseAdmissions:E}=await import(`./agent-database-admission-S1h6e7go.mjs`);if(n.repair!==true&&n.yes!==true)E(T.agentRefusals??[]);const{guardUpdateDoctorSchemaUpgrade:D}=await import(`./commands/doctor-update-schema-guard.js`);let A=T.verifiedSnapshots??[];await d(`doctor.schema-admission`,()=>D({schemas:T,runtime:e,json:n.json,postCoreSchemaRepair:o?.postCoreSchemaRepair,signal:resolveCommandProcessSignal(g?.signal??u),onVerifiedBackup:e=>{A=e}}));const{prepareDoctorClientCredentials:j}=await import(`./doctor-client-credentials-BFdjZOW_.mjs`);if(!await j({runtime:e,options:n,prompter:a,maintenanceActive:g!==void 0,schemas:T})){b=1;return}if(g&&(n.repair===true||n.yes===true)){if(await d(`doctor.state-database-repair`,()=>repairDoctorStateDatabase(f,n.fullIntegrityCheck?`full`:`quick`)))T=await d(`doctor.database-preflight`,()=>i())}if(g){const{prepareDoctorMigrationBackups:e}=await import(`./doctor-heartbeat-migration-backup-BCgZ1tCO.mjs`);await e({schemas:T,env:process.env,check:n.fullIntegrityCheck?`full`:`quick`,verifiedSnapshots:A,automaticRepair:Boolean(l),runtime:f,measure:d})}const M=await d(`doctor.state-schema`,()=>prepareDoctorStateSchema(T,a.shouldRepair,n.fullIntegrityCheck?`full`:`quick`));const N=await prepareDoctorRuntimeChecks(T,h,e,a,n);T=N.schemas;_=N.nocowPaths;const P=T.agentDatabaseMigrationDiscovery;if(P&&P.stateDir===w?.stateDir)P.preparedTranscriptArchives=w?.preparedTranscriptArchives;const{loadAndMaybeMigrateDoctorConfig:F}=await import(`./doctor-config-flow-DYDgysEB.mjs`);const I=await d(`doctor.config-flow`,()=>F({options:n,retiredStateAdmitted:true,stateSchemaPreparation:M,...l?{automaticHeartbeatRepair:l}:{},agentDatabaseMigrationDiscovery:T.agentDatabaseMigrationDiscovery,confirm:e=>a.confirm(e),runtime:e,prompter:a,reportFindings:C}));k.use(I);const L=T.agentDatabaseMigrationDiscovery&&T.agentDatabaseMigrationDiscovery.stateDir!==resolveStateDir()?await d(`doctor.database-preflight`,()=>i({cfg:I.cfg})):T;const R=new Set(I.stateMigrationStepReceipts?.flatMap(e=>e.id===`media-persistence`?e.recoveredAgentDatabasePaths??[]:[]));const z=L.agentDatabaseMigrationDiscovery?.discovery.sourceIdentities;const B=(L.agentRefusals??[]).filter(e=>!e.paths.every(e=>R.has(e)||R.has(z?.get(e)?.realPath??e)));E(B);const{CONFIG_PATH:V}=await import(`./config/config.js`);const H={runtime:e,healthFindings:S.healthFindings,options:n,retirementOnly:o?.retirementOnly===true,prompter:a,configResult:I,cfg:I.cfg,cfgForPersistence:structuredClone(I.cfg),sourceConfigValid:I.sourceConfigValid??true,configPath:I.path??V,stateDirExistedAtStart:m,gatewayMaintenanceActive:g!==void 0,agentDatabaseRefusals:B,updateWarnings:normalizeUpdatePostInstallDoctorWarnings([...S.updateWarnings??[],...N.warnings]),preparedAgentCount:Math.max(L.agentDatabaseMigrationDiscovery?.configuredAgentDatabaseTargets.length??0,L.agentDatabaseMigrationDiscovery?.registeredAgentDatabases.length??0),runWithPluginMetadataSnapshot:I.runWithPluginMetadataSnapshot,invalidatePluginMetadataSnapshot:I.invalidatePluginMetadataSnapshot};x=H;const{runDoctorHealthContributions:U}=await import(`./doctor-health-contributions-qricxMBI.mjs`);await d(`doctor.contributions`,()=>U(H));if(recordRepairRefusal(H))return;if(g){const{validateDoctorExternalConfigForStartup:e}=await import(`./doctor-external-config-Bnd92SSh.mjs`);if(!await d(`doctor.external-config`,()=>e(f))){b=1;return}const{assertDoctorMaintenanceReady:t}=await import(`./doctor-maintenance-inspection-BCP9Hvz5.mjs`);if(!(await d(`doctor.maintenance-ready`,()=>t(H.cfg,process.env,f.log,L.agentDatabaseMigrationDiscovery?.discovery.targets??[]))).schemaPublicationDeferred){y=L.agentDatabaseMigrationDiscovery?.discovery.targets??[];s?.();if(isTruthyEnvValue(process.env.OPENCLAW_DEBUG_PROXY_ENABLED)){const{initializeDebugProxyCaptureAsync:e}=await import(`./runtime-BZyW3NrK.mjs`);await e(`cli`)}}const{repairGatewayMaintenanceStartupFailures:n}=await import(`./gateway-boot-lifecycle-DST28A_P.mjs`);n()}return H};let N;let P;try{N=await withSqliteSnapshotFailureScope(()=>g?g.run(runChecks):withCommandProcessScope(()=>withSqliteReadOnlyWorkerScope(runChecks,u?{signal:u,deadlineOwnedByCaller:false}:void 0),u));if(N&&g&&n.repair===true&&_.length>0){if(resolveDoctorRepairMode(n).updateInProgress&&!isTruthyEnvValue(process.env[`OPENCLAW_DOCTOR_SQLITE_NOCOW_REPAIR`]))f.log(`SQLite NOCOW repair deferred: the managed updater did not request the store rewrite in this run.`);else{const e=g;await d(`doctor.sqlite-nocow`,()=>e.repairSqliteNoCow(_))}}if(N&&g&&N.prompter.shouldRepair&&isDoctorUpdateRepairMode(N.prompter.repairMode)&&y){const e=g;const t=y;await d(`doctor.sqlite-reclamation`,()=>e.enableSqliteReclamation(t))}}catch(e){P=e;throw e}finally{const e=g;if(e){const t=N;await d(`doctor.maintenance.finish`,()=>e.finish(t?.cfg,t?async e=>{const{writeDoctorGatewayConfig:n}=await import(`./doctor-health-contribution-runners.gateway-C6EcFRuq.mjs`);return n(t,e)}:void 0,P))}}if(!N){showDoctorHealthSummary(x??S);return}if(recordRepairRefusal(N))return;const F=[];let I=false;if(i.length>0){const{collectPluginLoadHealthFindings:e}=await import(`./doctor-workspace-status-DmtMPFBV.mjs`);const t=e(i);renderStructuredHealthFindings(N,t);F.push(...t.map(e=>`${e.checkId}: ${e.message}`));I=t.some(e=>e.severity===`error`)}showDoctorHealthSummary(N);const L=normalizeUpdatePostInstallDoctorWarnings([...F,...N.configResult.warnings??[],...g?.warnings??[],...(N.configResult.stateMigrationStepReceipts??[]).flatMap(e=>e.outcome===`warning`||e.outcome===`skipped`||e.outcome===`deferred`?e.warnings:[]),...N.postInstallDoctorResult?.warnings??[]]);T={...N.postInstallDoctorResult??{status:`ok`},...L.length?{warnings:L}:{},...g?.failureFacts?.length?{failureFacts:[...g.failureFacts,...N.postInstallDoctorResult?.failureFacts??[]]}:{}};if(a?.resultPath&&T.status===`advisory`){b=86;return}if(I){showDoctorOutro(`Doctor finished with plugin load errors.`);if(n.nonInteractive&&!isUpdateDoctorLintPass(process.env))b=1;return}}catch(e){const{DoctorHeartbeatMigrationDeferredError:t}=await import(`./doctor-heartbeat-run-recovery-C3OkxaKF.mjs`);if((!g||e instanceof t)&&e instanceof DoctorMaintenanceRefusalError&&e.refusal.kind===`deferred`&&(isDoctorUpdateRepairMode(resolveDoctorRepairMode(n))||e instanceof t&&isUpdateDoctorLintPass(process.env))){showDoctorHealthSummary(x??S);o?.assertCurrent();const{recordDeferredUpdateDoctorWarning:t,recordUpdateDoctorRefusal:n}=await import(`./doctor-update-refusal-mXkmdiNE.mjs`);n(e.message);f.error(e.message);T={status:`ok`,warnings:[e.message],maintenanceRefusal:e.refusal};if(!a)await t(e.message,f);showDoctorOutro(`Doctor maintenance deferred; pending repairs remain unchanged.`);b=0;return}const{DoctorStateMigrationRefusalError:r}=await import(`./state-migrations.messages-BuqhsWBd.mjs`);const i=e instanceof r?e.failureFacts.map(formatUpdateFailureFact):[];if(x&&i.length>0)recordDoctorHealthWarnings(x,[],i,{prepend:true});if(e instanceof r){const{recordUpdateDoctorRefusal:t,resolveUpdateDoctorGitRecovery:n}=await import(`./doctor-update-refusal-mXkmdiNE.mjs`);const r=await n({root:h,stateRepaired:true});if(r){e.message+=`\n${r.message}`;t(e.message)}}showDoctorHealthSummary(x??S);const s=collectNestedErrorCandidates(e);const{classifyDoctorMaintenanceRefusal:c}=await import(`./doctor-maintenance-inspection-BCP9Hvz5.mjs`);const l=c(e);const u=s.find(e=>e instanceof ConfigWritePostCommitError&&e.rollbackStatus!==`restored`);const d=s.find(e=>e instanceof UpdateSchemaRefusalError);const p=s.flatMap(e=>e instanceof UpdateDoctorError||e instanceof r?e.failureFacts:[]);T={status:`error`,...l.kind===`data-at-risk`?{maintenanceRefusal:l}:{},...!x&&i.length>0?{warnings:i}:{},failureFacts:!u&&!d&&p.length>0?p:[createUpdateFailureFact({leaseLoss:createUpdateErrorFact(`doctor`,e).leaseLoss,check:u?`config-write`:d?`database-schema-preflight`:`doctor`,code:u?`rollback-state-unverified`:d?.code??`doctor-failed`,message:u?`${u.publication} config publication; rollback ${u.rollbackStatus}. ${u.message}`:d?.message??(e instanceof Error?e.message:String(e))})]};if(g&&!(e instanceof r))f.error(`Doctor could not complete maintenance. Check the reported service state and resolve the failure.`);throw e}finally{await d(`doctor.maintenance.release`,()=>k.disposeAsync());if(a)await publishDoctorUpdateResult({updateResult:a,doctorResult:T,healthContext:x,maintenance:g,startupWarnings:S.updateWarnings});if(b!==void 0)e(f,b)}showDoctorComplete({watchExit:n.watchExitAfterComplete===true})}catch(e){l.e=e}finally{await l.d()}}export{runDoctorHealthFlow as t};