UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

308 lines (307 loc) • 13.8 kB
import { o as writeRuntimeJson, r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { l as trackAsyncWork, o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import { n as LEGACY_IMPLICIT_AGENT_ID } from "./session-key-CqAyZeVk.mjs"; import { n as resolveRuntimeWorkerArgv } from "./runtime-worker-url-DRDkoS4J.mjs"; import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-CoHTemu-.mjs"; import { c as registerSignalExitGate } from "./signal-exit-barrier-BOGtFHQL.mjs"; import { t as CommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs"; import { i as runUtf8CommandWithTimeout } from "./exec-runner-Br73vG-X.mjs"; import { a as retainCommandProcessCleanup, i as resolveCommandProcessSignal, o as runOutsideCommandProcessScope } from "./exec-spawn-DMKoejF-.mjs"; import "./exec-aRIvS9s4.mjs"; import { t as exitCliAfterOutput } from "./one-shot-exit-DkbGSQD5.mjs"; import { fileURLToPath } from "node:url"; import { StringDecoder } from "node:string_decoder"; //#region src/commands/doctor-process.ts const MAX_OUTPUT_BYTES = 1048576; /** Hosted Doctor keeps its synchronous checks and process-global state outside the Gateway. */ 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("\n")) >= 0) { write(e, n.pending.slice(0, r)); n.pending = n.pending.slice(r + 1); } }; const c = trackAsyncWork(() => 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 l = c.then((e) => { if (e.cleanup === "uncertain") throw new CommandProcessCleanupError(); }); l.catch(() => {}); retainCommandProcessCleanup(l); const u = registerSignalExitGate(l, () => n.abort()); try { const n = await c; for (const e of ["stdout", "stderr"]) { if (!o) append(e, i[e].decoder.end()); if (i[e].pending) write(e, i[e].pending); } if (n.cleanup === "uncertain") throw new CommandProcessCleanupError(); 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(); } } //#endregion //#region src/commands/doctor.ts async function resolveExplicitSessionSqliteMaintenancePaths(e) { if (!e.sessionSqliteStore) return []; const [{ resolveSessionStoreTargets: t }, { resolveSqliteTargetFromSessionStorePath: n }, { resolveSqliteDatabaseFilePaths: r }] = await Promise.all([ import("./targets-cXkr4Sqy.mjs"), import("./session-sqlite-target-DDpmcfGH.mjs"), import("./sqlite-files-DhYaTb_s.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-BXFHpO5Y.mjs"); await r("openclaw doctor --fix"); const i = e ?? defaultRuntime; if (t?.stateSqlite) { const { runDoctorStateSqliteCompact: e } = await import("./doctor-state-sqlite-compact-YfQNJPdS.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-BG4Mar_q.mjs"); const { isDestructiveDoctorSessionSqliteMode: r, withDoctorSqliteMaintenanceLock: a } = await import("./doctor-sqlite-maintenance-lock-DD8x7Dc0.mjs"); const { runDoctorSessionSqlite: o, reconcileDoctorSessionSqlitePublication: s } = await import("./doctor-session-sqlite-BeIvR4an.mjs"); const { withArtifactPreservingStateReads: c } = await import("./openclaw-state-db-readonly-_6T_jl_p.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-71er8CRn.mjs"); const { readSourceConfigBestEffort: n } = await import("./io.runtime.js"); 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-Bt8pq4BW.mjs"); try { await a.runDoctorHealthFlow(e, t, void 0, n); } catch (e) { const { diagnoseDoctorStateStorageFailure: t } = await import("./doctor-database-preflight-Dhck-D-u.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-BEr6zxKz.mjs"); const o = n.json !== true && a(n).canPrompt; let s = n.yes === true; if (o) { const { promptYesNo: e } = await import("./prompt-D5h12jkR.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-CLk7AfV6.mjs"); const { claimSessionSqliteMigrationGithubIssue: f, clearSessionSqliteMigrationGithubIssueClaim: p } = await import("./doctor-session-sqlite-failure-D8SGYs-N.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-B4ZlLaJk.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-DD8x7Dc0.mjs"); return await n({ env: process.env, operation: "session SQLite GitHub issue receipt", protectedPaths: [e], run: t }); } //#endregion export { doctorCommand, runDoctorProcess };