openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
6 lines • 12.2 kB
JavaScript
import{o as writeRuntimeJson,r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{l as trackAsyncWork,o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{n as LEGACY_IMPLICIT_AGENT_ID}from"./session-key-BPgKfU2m.mjs";import{n as resolveRuntimeWorkerArgv}from"./runtime-worker-url-Dqf-I1cs.mjs";import{o as resolveRuntimeProcessEntrypointUrl}from"./runtime-process-url-DJ272Tuo.mjs";import{c as registerSignalExitGate}from"./signal-exit-barrier-DoATIAtq.mjs";import{l as readCommandProcessCleanup,t as CommandProcessCleanupError}from"./exec-result-TD4w1Z1i.mjs";import{i as runUtf8CommandWithTimeout}from"./exec-runner-BiCq-T1F.mjs";import{a as resolveCommandProcessSignal,o as retainCommandProcessCleanup,s as runOutsideCommandProcessScope}from"./exec-spawn-DNCbDcyJ.mjs";import"./exec-c5tqm8tb.mjs";import{t as exitCliAfterOutput}from"./one-shot-exit-LLy48Ehj.mjs";import{fileURLToPath}from"node:url";import{StringDecoder}from"node:string_decoder";
//!src/commands/doctor-process.ts
const MAX_OUTPUT_BYTES=1048576;async function runDoctorProcess(e){const t=resolveCommandProcessSignal(getAsyncWorkSignal());t?.throwIfAborted();const n=new AbortController;const r=resolveRuntimeProcessEntrypointUrl(`doctor`);const i={stdout:{decoder:new StringDecoder(`utf8`),pending:``,write:e.log},stderr:{decoder:new StringDecoder(`utf8`),pending:``,write:e.error}};let a=MAX_OUTPUT_BYTES;let o=false;let s;const write=(e,t)=>{if(s)return;try{i[e].write(t)}catch(e){s={error:e};n.abort(e)}};const append=(e,t)=>{const n=i[e];n.pending+=t;let r;while((r=n.pending.indexOf(`
`))>=0){write(e,n.pending.slice(0,r));n.pending=n.pending.slice(r+1)}};const c=trackAsyncWork(async()=>{const e=await runOutsideCommandProcessScope(()=>runUtf8CommandWithTimeout([process.execPath,...resolveRuntimeWorkerArgv(r)],{input:``,timeoutMs:12e4,signal:t?AbortSignal.any([t,n.signal]):n.signal,cwd:process.cwd(),baseEnv:process.env,.../\.[cm]?ts$/.test(fileURLToPath(r))?{env:{TSX_TSCONFIG_PATH:fileURLToPath(new URL(`../../tsconfig.json`,r))}}:{},killProcessTree:true,requireProcessTreeExtinction:true,outputCapture:`discard`,onOutputChunk(e,t){const n=e.subarray(0,a);a-=n.byteLength;o||=n.byteLength<e.byteLength;append(t,i[t].decoder.write(n))}}));const s=readCommandProcessCleanup(e);if((s?await s.catch(e=>{throw new CommandProcessCleanupError({cause:e})}):e.cleanup)===`uncertain`)throw new CommandProcessCleanupError;return e});const l=c.then(()=>void 0);l.catch(()=>{});retainCommandProcessCleanup(l);const u=registerSignalExitGate(l,()=>n.abort());try{const n=await c.finally(()=>{for(const e of[`stdout`,`stderr`]){if(!o)append(e,i[e].decoder.end());if(i[e].pending)write(e,i[e].pending)}});if(s)throw s.error;t?.throwIfAborted();if(o)e.error("Doctor output was truncated after 1 MiB. Run `openclaw doctor --lint` on this host for the complete report.");if(n.outputErrorStream)throw new Error(`Doctor ${n.outputErrorStream} output could not be read.`);if(n.termination!==`exit`)throw new Error(`Doctor diagnosis did not complete (${n.termination}); no repairs were applied.`);if(n.code!==0)e.exit(n.code??1)}finally{u()}}
//!src/commands/doctor.ts
async function resolveExplicitSessionSqliteMaintenancePaths(e){if(!e.sessionSqliteStore)return[];const[{resolveSessionStoreTargets:t},{resolveSqliteTargetFromSessionStorePath:n},{resolveSqliteDatabaseFilePaths:r}]=await Promise.all([import(`./targets-C8LX-ajf.mjs`),import(`./session-sqlite-target-C_JHodBN.mjs`),import(`./sqlite-files-EVI5kMaY.mjs`)]);const i=t({agents:{entries:{[normalizeAgentId(e.sessionSqliteAgent??`main`)]:{}}}},{store:e.sessionSqliteStore,...e.sessionSqliteAgent?{agent:e.sessionSqliteAgent}:{},...e.sessionSqliteAllAgents?{allAgents:true}:{}},{env:process.env});const a=[];for(const e of i){const t=n(e.storePath,{agentId:e.agentId}).path;a.push(e.storePath,...r(t))}return[...new Set(a)]}async function doctorCommand(e,t,n){const{preparePostgresPoolForUpdate:r}=await import(`./pool-D4IPt2Ny.mjs`);await r(`openclaw doctor --fix`);const i=e??defaultRuntime;if(t?.stateSqlite){const{runDoctorStateSqliteCompact:e}=await import(`./doctor-state-sqlite-compact-B84dawaH.mjs`);const n=await e();if(t.json)writeRuntimeJson(i,n);else if(n.skipped)i.log(`state-sqlite compact: skipped; database missing at ${n.path}`);else{i.log(`state-sqlite compact: reclaimed=${n.reclaimedBytes} bytes, db=${n.before.dbSizeBytes}->${n.after.dbSizeBytes} bytes, wal=${n.before.walSizeBytes}->${n.after.walSizeBytes} bytes`);i.log(`- freelist=${n.before.freelistPages}->${n.after.freelistPages} pages, page-size=${n.after.pageSizeBytes} bytes, auto-vacuum=${n.before.autoVacuum}->${n.after.autoVacuum}`);i.log(`- integrity-check=${n.integrityCheck}, path=${n.path}`)}exitCliAfterOutput(i,0)}if(t?.sessionSqlite){const e=t.sessionSqlite;const{countBlockingSessionSqliteIssues:n}=await import(`./doctor-session-sqlite-types-Du6ClsP7.mjs`);const{isDestructiveDoctorSessionSqliteMode:r,withDoctorSqliteMaintenanceLock:a}=await import(`./doctor-sqlite-maintenance-lock-DjUW6vHV.mjs`);const{runDoctorSessionSqlite:o,reconcileDoctorSessionSqlitePublication:s}=await import(`./doctor-session-sqlite-DIzSb8mD.mjs`);const{withArtifactPreservingStateReads:c}=await import(`./openclaw-state-db-readonly-j3ciDtyb.mjs`);const l={mode:e,...t.fullIntegrityCheck?{integrityCheck:`full`}:{},...t.sessionSqliteStore?{store:t.sessionSqliteStore}:{},...t.sessionSqliteAgent?{agent:t.sessionSqliteAgent}:{},...t.sessionSqliteAllAgents?{allAgents:true}:{}};const runSessionSqlite=async e=>await o(l,e);const reconcileHardlink=e=>s(l,e);const u=await c(async()=>r(e)?await a({env:process.env,operation:`session SQLite ${e}`,...t.sessionSqliteStore?{protectedPaths:await resolveExplicitSessionSqliteMaintenancePaths(t)}:{},...e!==`compact`?{reconcileHardlink}:{},run:runSessionSqlite}):await runSessionSqlite());if(e===`recover`&&t.sessionSqliteGithubIssue===true)await maybeCreateSessionSqliteGithubIssue(i,u,t);if(t.json)writeRuntimeJson(i,u);else{i.log(`session-sqlite ${u.mode}: ${u.totals.targets} target(s), ${u.totals.legacyEntries} legacy entries, ${u.totals.sqliteEntries} sqlite entries, ${u.totals.issues} issue(s)`);if(u.migrationRun){i.log(`- migration-run=${u.migrationRun.runId}`);i.log(`- manifest=${u.migrationRun.manifestPath}`);if(u.migrationRun.failureReportMarkdownPath)i.log(`- failure-report=${u.migrationRun.failureReportMarkdownPath}`)}if(u.supportIssue)i.log(`- support-issue-report=${u.supportIssue.bodyPath??`inline`}`);for(const e of u.targets){i.log(`- ${e.agentId}: imported=${e.importedEntries}/${e.importedTranscriptEvents} events, validated=${e.validatedEntries}/${e.validatedTranscriptEvents} events, archived-unreferenced-jsonl=${e.archivedUnreferencedJsonlFiles.length}, unreferenced-jsonl=${e.unreferencedJsonlFiles.length}`);if(e.restore)i.log(` restored=${e.restore.restoredFiles.length}, skipped=${e.restore.skippedFiles.length}, conflicts=${e.restore.conflicts.length}, manifests=${e.restore.manifestPaths.length}`);if(e.compact)i.log(` compact reclaimed=${e.compact.reclaimedBytes} bytes, db=${e.compact.dbSizeBeforeBytes}->${e.compact.dbSizeAfterBytes} bytes, wal=${e.compact.walSizeBeforeBytes}->${e.compact.walSizeAfterBytes} bytes`);if(e.corruptRecovery)i.log(` corrupt-db-recovery moved=${e.corruptRecovery.movedFiles.length}, skipped=${e.corruptRecovery.skippedFiles.length}`);for(const t of e.issues.slice(0,10))i.log(` [${t.code}]${t.sessionKey?` ${t.sessionKey}:`:``} ${t.message}`);if(e.issues.length>10)i.log(` ...and ${e.issues.length-10} more issue(s)`)}}const d=u.targets.some(e=>n(e)>0);exitCliAfterOutput(i,d?1:0)}if(t?.postUpgrade){const{runPostUpgradeProbes:e}=await import(`./doctor-post-upgrade-BEv8MRoP.mjs`);const{readSourceConfigBestEffort:n}=await import(`./io.runtime-g-lXlyhe.mjs`);const r=await e((await n()).update?.channel);if(t.json)writeRuntimeJson(i,r);else{for(const e of r.findings)i.log(`[${e.level}] ${e.code}: ${e.message}`);if(r.findings.length===0)i.log(`post-upgrade: no findings`)}const a=r.findings.some(e=>e.level===`error`);exitCliAfterOutput(i,a?1:0)}const a=await import(`./doctor-health-Daz1YqP9.mjs`);try{await a.runDoctorHealthFlow(e,t,void 0,n)}catch(e){const{diagnoseDoctorStateStorageFailure:t}=await import(`./doctor-database-preflight-D4Tb6gBX.mjs`);throw t(e)??e}}async function maybeCreateSessionSqliteGithubIssue(e,t,n){const r=n.json!==true;const i=t.supportIssue;if(!i){if(r)e.log(t.totals.issues===0&&t.totals.importedEntries===0&&t.totals.archivedTranscriptFiles===0&&t.totals.archivedUnreferencedJsonlFiles===0&&t.targets.every(e=>!e.restore?.restoredFiles.length&&!e.corruptRecovery?.movedFiles.length)?`session-sqlite recover: nothing to recover; no report filed`:`session-sqlite recover: no support issue payload was generated`);return}const recordStatus=(t,n=`failed`)=>{i.github={message:t,status:n};if(r)e.log(`session-sqlite recover: ${t}`)};const recordCreated=t=>{i.github={status:`created`,url:t};if(r)e.log(`session-sqlite recover: created GitHub issue ${t}`)};const{resolveDoctorRepairMode:a}=await import(`./doctor-repair-mode-CiwOEbJ9.mjs`);const o=n.json!==true&&a(n).canPrompt;let s=n.yes===true;if(o){const{promptYesNo:e}=await import(`./prompt-57-vh2Zi.mjs`);s=await e(`Create a GitHub issue in openclaw/openclaw with the sanitized recovery report?`,false)}if(!s){recordStatus(o?`GitHub issue creation skipped: confirmation was declined.`:`GitHub issue creation skipped: noninteractive recovery requires --yes.`,`skipped`);return}const c=t.migrationRun?.manifestPath;if(!c){recordStatus(`GitHub issue creation is unavailable because its private retry receipt could not be prepared.`);return}const{prepareGithubIssue:l,reconcileGithubIssue:u,submitGithubIssue:d}=await import(`./github-issue-Bs114eCH.mjs`);const{claimSessionSqliteMigrationGithubIssue:f,clearSessionSqliteMigrationGithubIssueClaim:p}=await import(`./doctor-session-sqlite-failure-BeP2Z_ZD.mjs`);const m=l({body:i.body,title:i.title});let h;try{h=await withSessionSqliteGithubIssueReceipt(c,e=>f(c,{marker:m.marker,title:m.title},e))}catch{h=void 0}if(!h){recordStatus(`GitHub issue creation is unavailable because its private retry receipt could not be saved.`);return}i.title=h.issue.title;const g=l({body:i.body,title:h.issue.title});if(g.marker!==h.issue.marker){recordStatus(`GitHub issue creation is unavailable because its private retry receipt is inconsistent.`);return}if(h.status===`existing`){const e=await u(g).catch(()=>({status:`unavailable`}));if(e.status===`created`){recordCreated(e.url);return}recordStatus(`A prior GitHub issue handoff may already have created this report; no duplicate was opened.`);return}const _=await d(g).catch(()=>({reason:`creation-outcome-unknown`,status:`outcome-unknown`}));if(_.status===`created`){recordCreated(_.url);return}if(_.status===`outcome-unknown`){recordStatus(`GitHub issue creation outcome is unknown; no duplicate was opened.`);return}const clearUnsentClaim=()=>withSessionSqliteGithubIssueReceipt(c,e=>p(c,g.marker,e)).catch(()=>false);if(_.status===`fallback-unavailable`){await clearUnsentClaim();recordStatus(`GitHub issue creation is unavailable, and this report is too large for a safe browser fallback.`);return}const v=_.reason===`cli-unavailable`?`GitHub CLI is unavailable.`:_.reason===`authentication-unavailable`?`GitHub authentication is unavailable.`:`GitHub issue creation is unavailable.`;const{detectBrowserOpenSupport:y,openUrl:b}=await import(`./browser-open-tltQWBmd.mjs`);const x=await y().catch(()=>({ok:false}));const S=x.ok?await b(_.url).catch(()=>false):false;if(!x.ok)await clearUnsentClaim();recordStatus(v);if(r)e.log(S?`session-sqlite recover: opened the sanitized fallback in your browser`:`session-sqlite recover: browser handoff unavailable; the sanitized report remains available in the recovery result`)}async function withSessionSqliteGithubIssueReceipt(e,t){const{withDoctorSqliteMaintenanceLock:n}=await import(`./doctor-sqlite-maintenance-lock-DjUW6vHV.mjs`);return await n({env:process.env,operation:`session SQLite GitHub issue receipt`,protectedPaths:[e],run:t})}export{doctorCommand,runDoctorProcess};