UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4 lines • 10.4 kB
import{n as isTruthyEnvValue}from"./env-fLMEolk5.mjs";import{o as measureGatewayBootstrapStep}from"./startup-trace-CnJbL2Y9.mjs";import{n as createNonExitingRuntime,r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{s as raceWithTimeout}from"./src-De06gkOi.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{C as resolveIsNixMode,o as isDefaultInstallIdentity}from"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{r as createUpdateFailureFact}from"./update-failure-facts-Bwgg6oY-.mjs";import{a as resolveCommandProcessSignal,p as withCommandProcessScope}from"./exec-spawn-DNCbDcyJ.mjs";import{n as getPendingCliDisposers}from"./runtime-cleanup-DVuV57ip.mjs";import{o as watchCliExitAfterOutput,t as exitCliAfterOutput}from"./one-shot-exit-LLy48Ehj.mjs";import{t as formatDoctorProgressPhase}from"./doctor-progress-DGmacsiq.mjs";import{r as stylePromptTitle}from"./prompt-style-B-J86yY8.mjs";import{c as showDoctorHealthSummary}from"./doctor-health-contribution-CiqEIP_B.mjs";import{n as resolveDoctorRepairMode}from"./doctor-repair-mode-Dilz8sGs.mjs";import fs,{writeSync}from"node:fs";import{intro,outro}from"@clack/prompts"; //!src/flows/doctor-health-startup.ts const showDoctorIntro=e=>intro(stylePromptTitle(e)??e);const showDoctorOutro=e=>outro(stylePromptTitle(e)??e);function showDoctorComplete(e){showDoctorOutro(`Doctor complete.`);if(e.watchExit)watchCliExitAfterOutput(()=>{writeSync(2,`Doctor finished but the process is still alive: ${JSON.stringify({activeResources:[...new Set(process.getActiveResourcesInfo())].toSorted(),unsettledDisposers:getPendingCliDisposers()})}\n`)})}async function withDoctorProgress(e,t,n){if(!n)return await t();const r=performance.now();const report=(t=``)=>process.stderr.write(`Doctor: ${e}${t}\n`);report();const i=setInterval(()=>{report(` (${Math.floor((performance.now()-r)/1e3)}s elapsed)`)},1e4);i.unref();try{return await t()}finally{clearInterval(i)}}function createDoctorProgressMeasure(e){return(t,n)=>withDoctorProgress(formatDoctorProgressPhase(t),()=>measureGatewayBootstrapStep(t,n),e.json!==true)}function exitDoctorHealthFlow(e,t){if(e===defaultRuntime)exitCliAfterOutput(e,t);e.exit(t)}function stateDirectoryExistsAtDoctorStart(){try{return fs.statSync(resolveStateDir()).isDirectory()}catch{return false}}function readDoctorStartup(e,t){return withCommandProcessScope(async()=>{const n=resolveCommandProcessSignal();return raceWithTimeout(()=>t(n),6e4,()=>{throw new Error(`Doctor startup timed out after 60000ms (${e}). Retry with OPENCLAW_DEBUG=1 openclaw doctor --lint; if it still stalls, capture a Node diagnostic report before retrying repairs.`)},{signal:n})},getAsyncWorkSignal())}async function prepareDoctorHealthFlow(e,t,n){const r=e??(await import(`./runtime-BQCaxGKj.mjs`)).defaultRuntime;const i={...r,exit:createNonExitingRuntime().exit};const a=stateDirectoryExistsAtDoctorStart();n(`OpenClaw doctor`);const o=await readDoctorStartup(`package root`,async e=>{const{resolveOpenClawPackageRoot:t}=await import(`./openclaw-root-BwFF-E70.mjs`);return t({moduleUrl:import.meta.url,argv1:process.argv[1],cwd:process.cwd(),signal:e})});if(resolveIsNixMode()&&(t.repair===true||t.yes===true||t.generateGatewayToken===true)){const{assertConfigWriteAllowedInCurrentMode:e}=await import(`./config-write-guard-Ofxe5ue0.mjs`);e()}if(!resolveDoctorRepairMode(t).updateInProgress){const e=await readDoctorStartup(`source config`,async()=>{const{readSourceConfigBestEffort:e}=await import(`./io.runtime-g-lXlyhe.mjs`);return e()});const t=await readDoctorStartup(`Tailscale prerequisite`,async()=>{const{inspectDoctorTailscalePrerequisite:t}=await import(`./doctor-tailscale-CsEfi89h.mjs`);return t(e)});if(t){const{note:e}=await import(`./terminal-core/note.js`);e(t,`Gateway startup prerequisite`)}}return{effectiveRuntime:r,repairRuntime:i,stateDirExistedAtStart:a,root:o}}async function prepareDoctorInteractiveMaintenance(e){const{createDoctorPrompter:t}=await import(`./doctor-prompter-BOnP8RlH.mjs`);const{prepareDoctorDatabasePreflight:n}=await import(`./doctor-database-preflight-D4Tb6gBX.mjs`);const r=t({runtime:e.runtime,options:e.options});if(!e.databasePreflight)await n({scope:`state`});const{maybeOfferUpdateBeforeDoctor:i}=await import(`./doctor-update-JA0r4P-7.mjs`);if(await i({options:e.options,root:e.root,confirm:e=>r.confirm(e),outro:e.outro}))return`handled`;if(!e.databasePreflight)await n();if(process.platform===`darwin`&&isDefaultInstallIdentity()){const[{readSourceConfigBestEffort:e},{noteMacGatewayPlatformWarnings:t}]=await Promise.all([import(`./io.runtime-g-lXlyhe.mjs`),import(`./doctor-platform-notes-Jvc2SMUT.mjs`)]);await t(await e(),r)}if(await r.confirmRuntimeRepair({message:`Pause the managed Gateway while you review repairs? Doctor restores its prior service state when finished.`,initialValue:true,requiresInteractiveConfirmation:true}))return`accepted`;e.runtime.log(`Doctor repairs skipped. Continuing read-only diagnosis.`);const{runDoctorLintCli:a}=await import(`./doctor-lint-DlVOwPQT.mjs`);return{diagnosticExitCode:await a(e.runtime,{allowExec:e.options.allowExec,deep:e.options.deep})}}function showDoctorRepairRefusal(e){if(!e.configWriteRefusal){if(e.postInstallDoctorResult?.status!==`error`)return;showDoctorHealthSummary(e);showDoctorOutro(`Doctor blocked; required repairs remain incomplete.`);return e.postInstallDoctorResult}showDoctorHealthSummary(e);showDoctorOutro(e.configResultWriteCommitted===true?`Doctor finished, but some config fixes were not applied.`:`Doctor finished, but config fixes were not applied.`);return{status:`error`,failureFacts:[createUpdateFailureFact({check:`config-write`,code:e.configWriteRefusal,message:`Doctor config fixes were not applied.`})]}}async function prepareDoctorMaintenanceArchives(e,t,n={}){const r=resolveCommandProcessSignal(getAsyncWorkSignal());let i;try{const{prepareDoctorDatabasePreflight:t}=await import(`./doctor-database-preflight-D4Tb6gBX.mjs`);i=(e??await t(n)).agentDatabaseMigrationDiscovery;if(i){const{prepareCanonicalTranscriptArchiveMigrations:e}=await import(`./state-migrations.transcript-directives-archives-B2QQMjol.mjs`);await e(i)}}catch(e){t.log(`Archive verification preparation deferred: ${String(e)}`)}r?.throwIfAborted();return i}async function prepareDoctorStateSchema(e,t,n){if(!t||!e.pendingMigrations?.some(e=>e.kind===`state`))return;const{prepareLegacyStateDatabaseSchema:r}=await import(`./state-migrations.doctor-DVSvDgfM.mjs`);const{throwIfDoctorStateMigrationRefused:i}=await import(`./state-migrations.messages-BuqhsWBd.mjs`);const a=await r(process.env,n);i([a]);return a}async function repairDoctorStateDatabase(e,t){const{repairOpenClawStateDatabaseIndexesForDoctor:n,repairOpenClawStateDatabaseReadabilityForDoctor:r}=await import(`./openclaw-state-db-BNMRn-Oq.mjs`);let i=false;for(const a of[n,r]){const n=await a({env:process.env,integrityCheck:t});i||=n.changes.length>0;if(n.warnings.length>0)throw new Error(n.warnings.join(` `));for(const t of n.changes)e.log(t)}return i}async function prepareDoctorRuntimeChecks(e,t,n,r,i){const measure=(e,t)=>withDoctorProgress(formatDoctorProgressPhase(e),t,i.json!==true);const{getOpenClawDatabaseMaintenanceScope:a}=await import(`./openclaw-state-maintenance-context-D7WWeOtL.mjs`);const o=a();if(o?.ownsSchemaMaintenance){const{hasUpdateDoctorMigrationCapture:e}=await import(`./update-doctor-migration-context-IP4LthZS.mjs`);const{resolveOpenClawStateSqlitePath:t}=await import(`./openclaw-state-db.paths-3UU_PbvT.mjs`);if(e()&&fs.existsSync(t())){const{openOpenClawStateDatabaseForDoctor:e}=await import(`./openclaw-state-db-BNMRn-Oq.mjs`);await e();o.assertAdmission()}}const{repairDoctorAgentDeletionJournal:s}=await import(`./doctor-agent-deletion-journal-BZfwXknk.mjs`);const c=await measure(`Agent deletion journal`,()=>s({preflight:e,shouldRepair:r.shouldRepair,env:process.env}));for(const e of[...c.changes,...c.warnings])n.log(e);const l=c.changes.length>0?await measure(`Database preflight`,async()=>(await import(`./doctor-database-preflight-D4Tb6gBX.mjs`)).prepareDoctorDatabasePreflight()):e;const{inspectDoctorSqliteNoCow:u}=await import(`./doctor-sqlite-nocow-CFVp_4xJ.mjs`);const{resolveOpenClawStateSqlitePath:d}=await import(`./openclaw-state-db.paths-3UU_PbvT.mjs`);const f=u([d(),...l.agentDatabaseMigrationDiscovery?.discovery.targets.map(e=>e.path)??[]]);for(const e of f.notes)n.log(e);const{maybeRepairUiProtocolFreshness:p}=await import(`./doctor-ui-BmO6YnDQ.mjs`);const{noteSourceInstallIssues:m}=await import(`./doctor-install-BqnGMcSx.mjs`);const{noteBunCliLauncherIssues:h}=await import(`./doctor-bun-cli-launcher-UiqDbMiT.mjs`);const{noteStalePluginRuntimeSymlinks:g}=await import(`./plugin-runtime-symlinks-CIHUhM-R.mjs`);const{noteStartupOptimizationHints:_}=await import(`./doctor-platform-notes-Jvc2SMUT.mjs`);await measure(`UI protocol`,()=>p(n,r));await measure(`Source install`,()=>m(t));let v;await measure(`CLI launcher`,async()=>{await h({root:t,prompter:r});if(t){const{repairPublishedPnpmLaunchers:e}=await import(`./update-launcher-repair-D65BRcEC.mjs`);const{repaired:r,failed:i}=await e({root:t});for(const e of r)n.log(`Repaired the openclaw launcher ${e.file}: it still pointed at the removed update stage ${e.stage}.`);for(const{file:e,error:t}of i)n.log(`The openclaw launcher ${e} still points at a removed update stage and could not be repaired (${formatErrorMessage(t)}). Recreate it with \`pnpm add -g --allow-build=openclaw openclaw@<installed-version>\` as the account that owns the pnpm install.`);if(r.length>0&&isTruthyEnvValue(process.env.OPENCLAW_UPDATE_IN_PROGRESS)){const{resolveShippedRestartNotice:e}=await import(`./update-refused-restart-recovery-Z6D-n67H.mjs`);v=await e({root:t,diagnose:e=>n.error(e)})}}});await measure(`Plugin runtime links`,()=>g(t));_();return{schemas:l,nocowPaths:f.paths,warnings:v?[...c.warnings,v]:c.warnings}}export{prepareDoctorMaintenanceArchives as a,repairDoctorStateDatabase as c,showDoctorOutro as d,showDoctorRepairRefusal as f,prepareDoctorInteractiveMaintenance as i,showDoctorComplete as l,exitDoctorHealthFlow as n,prepareDoctorRuntimeChecks as o,withDoctorProgress as p,prepareDoctorHealthFlow as r,prepareDoctorStateSchema as s,createDoctorProgressMeasure as t,showDoctorIntro as u};