UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

525 lines (524 loc) • 20.4 kB
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs"; import { t as applyProcessEnvKeys } from "./process-env-DVJdcOcM.mjs"; import { u as tryResolveDefaultAgentId } from "./agent-roster-t1ooUdXp.mjs"; import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { a as SqliteSnapshotCleanupError } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs"; import { r as withArtifactPreservingStateReads, t as artifactPreservingReads } from "./artifact-preserving-state-reads-BfhmBr-V.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { a as prepareSqliteReadOnlyLocationSync } from "./sqlite-snapshot-source-Q9S7_uQN.mjs"; import { a as resolveUpdateRehearsalRoot } from "./update-rehearsal-paths-Dr1MbUA_.mjs"; import { l as closeOpenClawStateDatabaseByPathAsync } from "./openclaw-state-db-cache-CkwtTqzF.mjs"; import { g as withOpenClawStateDatabaseReadSnapshot, r as forkActiveOpenClawStateDatabaseReadSnapshot, u as withDisposableOpenClawStateReads } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { a as withPluginInstallRoots, i as resolvePluginInstallRoots } from "./install-root-context-CeM6pu6m.mjs"; import { o as withPluginSourceCaptureStorage, t as getPluginSourceCaptureStorage } from "./plugin-source-capture-context-BU9oGeml.mjs"; import { d as loadPinnedRuntimeConfigAsync } from "./runtime-snapshot-WbwbY5b7.mjs"; import { l as readDeferredPluginMigrations } from "./deferred-plugin-migrations-C_CU0aKR.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { t as captureRuntimeConfig } from "./runtime-source-projection-DTwMWCo9.mjs"; import { i as validateConfigObjectWithPlugins } from "./validation-DSwgLhC7.mjs"; import { o as maybeLoadDotEnvForConfig, t as createConfigIO } from "./io.factory-DEa_bi2j.mjs"; import { s as readConfigFileSnapshot, u as readConfigFileSnapshotWithPluginMetadata } from "./io.runtime-DsJ2dLCQ.mjs"; import "./sqlite-B2CoJ4Om.mjs"; import { r as closeAuthProfileReadPool } from "./sqlite-read-pool-C0HEzJkG.mjs"; import "./config-CMA-J084.mjs"; import { f as isUpdateDoctorLintPass, u as isPostCoreConvergencePass } from "./update-phase-YdZvaQsy.mjs"; import { t as UPDATE_DOCTOR_DISPOSAL_WARNING_PREFIX } from "./update-doctor-lint-DBj8vlYP.mjs"; import { t as scrubDoctorErrorMessage } from "./doctor-error-message-BWgd1c6H.mjs"; import { n as configValidationIssuesToHealthFindings } from "./doctor-config-validation-findings-DUD4Pgv3.mjs"; import { n as listExtensionHealthChecksForDoctor } from "./health-check-registry-Cl2vTx8K.mjs"; import { i as parseHealthFindingSeverity, n as healthFindingMeetsSeverity, r as isHealthCheckEnabledByDefault } from "./health-checks-BFk2VaFq.mjs"; import { i as stateSchemaHealthCheck, n as runDoctorLintChecks, r as selectUpdateReadinessChecks, t as exitCodeFromFindings } from "./doctor-lint-flow-BvruTNfX.mjs"; import { c as tryProjectRetiredHeartbeatConfig, i as resolveLegacyHeartbeatAgents } from "./doctor-heartbeat-legacy-DmzlheVU.mjs"; import { i as detectDoctorLintOutputMode, n as createStateSnapshotFailureExecution, o as writeJsonResult, r as createStateSnapshotFailureFinding, t as createDeferredInspectionExecution } from "./doctor-lint-output-Bx6KW9dE.mjs"; import { n as resolveDoctorUpdateBudget, t as admitDoctorUpdateInspection } from "./doctor-update-budget-ckRvPmaG.mjs"; import { n as formatRecoveryDiskUsage, t as collectRecoveryDiskUsage } from "./recovery-disk-usage-Bg1ZybJt.mjs"; import fs from "node:fs"; import path from "node:path"; import os from "node:os"; import { isDeepStrictEqual } from "node:util"; //#region src/commands/doctor-lint-state-snapshot.ts var DoctorLintStateSnapshotError = class extends Error { constructor(e) { super(`Doctor lint could not prepare a private plugin-state snapshot: ${scrubDoctorErrorMessage(e)}`, { cause: e }); this.name = "DoctorLintStateSnapshotError"; } }; /** One mutable inspection image belongs to the report, separate from its immutable read view. */ async function withReadOnlyPluginStateSnapshot(e, t, n) { let r; let i; let a; try { a = { ok: true, value: await t(async (t) => { i ??= await (r ??= prepareReadOnlyPluginStateSnapshot(e, n)); return i.run(t); }) }; } catch (e) { a = { ok: false, error: e }; } try { await i?.close(); } catch (e) { throw new DoctorLintStateSnapshotError(a.ok ? e : new AggregateError([a.error, e], `${scrubDoctorErrorMessage(a.error)}; ${scrubDoctorErrorMessage(e)}`)); } if (!a.ok) throw a.error; return a.value; } async function prepareReadOnlyPluginStateSnapshot(e, t) { const n = resolveOpenClawStateSqlitePath(e); const r = { stateDir: getPluginSourceCaptureStorage()?.stateDir ?? resolveStateDir(e), placement: "temporary" }; const i = resolvePluginInstallRoots(e); let cleanup; let a; let o; try { if (fs.existsSync(n)) { o = await forkActiveOpenClawStateDatabaseReadSnapshot({ env: e }) ?? prepareSqliteReadOnlyLocationSync(n); a = path.dirname(o.location); cleanup = o.cleanupAsync; } else { a = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-doctor-lint-state-")); cleanup = async () => { try { await fs.promises.rm(a, { force: true, recursive: true }); return true; } catch { return false; } }; } } catch (e) { throw new DoctorLintStateSnapshotError(e); } const s = path.join(a, "openclaw-state"); const c = artifactPreservingReads.getStore(); if (c) c.privateRoots.add(s); const l = resolveOpenClawStateSqlitePath({ ...e, OPENCLAW_STATE_DIR: s }); const u = { ...e, OPENCLAW_CONFIG_PATH: resolveConfigPath(e, resolveStateDir(e)), OPENCLAW_STATE_DIR: s }; const close = () => withDoctorLintStateEnv(u, async () => { const e = []; try { closeAuthProfileReadPool({ kind: "root", rootPath: s }); } catch (t) { e.push(t); } try { await closeOpenClawStateDatabaseByPathAsync(l); } catch (t) { e.push(t); } if (e.length > 0) throw new AggregateError(e, e.map((e) => scrubDoctorErrorMessage(e)).join("; ")); if (!await cleanup()) { const e = "Temporary doctor lint state snapshot cleanup did not complete."; if (!t) throw new Error(e); recordSnapshotCleanupWarning(t); } }); try { fs.mkdirSync(path.dirname(l), { recursive: true, mode: 448 }); if (o) for (const e of [ "", "-journal", "-shm", "-wal" ]) { const t = `${o.location}${e}`; if (fs.existsSync(t)) fs.renameSync(t, `${l}${e}`); } } catch (e) { try { await close(); } catch (t) { throw new DoctorLintStateSnapshotError(new AggregateError([e, t], `${scrubDoctorErrorMessage(e)}; ${scrubDoctorErrorMessage(t)}`)); } throw new DoctorLintStateSnapshotError(e); } return { close, run: (e) => withDoctorLintStateEnv(u, () => withPluginSourceCaptureStorage(r, () => withDisposableOpenClawStateReads(l, () => withPluginInstallRoots({ ...i, stateDir: s }, () => e(u))))) }; } function recordSnapshotCleanupWarning(e) { e.push({ checkId: "core/doctor/lint-state-inspection", severity: "warning", requirement: "temporary-snapshot-cleanup", message: "Temporary doctor lint state snapshot cleanup did not complete.", fixHint: "Rerun `openclaw doctor --lint` after the update to check snapshot cleanup." }); } async function withDoctorLintStateEnv(e, t, n = "resolved") { const r = resolveStateDir(e); const i = n === "captured" ? { OPENCLAW_CONFIG_PATH: e.OPENCLAW_CONFIG_PATH, OPENCLAW_STATE_DIR: e.OPENCLAW_STATE_DIR } : { OPENCLAW_CONFIG_PATH: resolveConfigPath(e, r), OPENCLAW_STATE_DIR: r }; const a = Object.keys(i); const o = Object.fromEntries(a.map((e) => [e, process.env[e]])); applyProcessEnvKeys(a, i); try { return await t(); } finally { applyProcessEnvKeys(a, o); } } //#endregion //#region src/commands/doctor-lint-runner.ts const RUNTIME_TOOL_SCHEMA_CHECK_ID = "core/doctor/runtime-tool-schemas"; const PROJECT_CLONE_SHAPE_CHECK_ID = "core/doctor/project-clone-shape"; const SKILLS_READINESS_CHECK_ID = "core/doctor/skills-readiness"; const AUTH_PROFILE_CHECK_ID = "core/doctor/auth-profiles"; const HEARTBEAT_SOURCE_CHECK_IDS = /* @__PURE__ */ new Set(["core/doctor/heartbeat-cadence-migration", "core/doctor/heartbeat-scratch-migration"]); /** Only the rehearsal worker reports before disposal and inherits its CLI's budget anchor. */ async function runDoctorLintCliInProcess(e, t, n) { let r; const report = (e) => { e.writeOutput(); r = e; }; try { const i = await withArtifactPreservingStateReads(() => prepareDoctorLintExecution(e, t, n ? report : void 0, n?.commandStartedAtMs), { agentDatabases: true }); if (!r) report(i); else for (const t of i.cleanupWarnings ?? []) e.error(`${UPDATE_DOCTOR_DISPOSAL_WARNING_PREFIX}: ${t.message}`); return i.exitCode; } catch (t) { if (!r) throw t; e.error(`${UPDATE_DOCTOR_DISPOSAL_WARNING_PREFIX}: ${scrubDoctorErrorMessage(t)}`); return r.exitCode; } } /** Collect advisory doctor findings without writing output or repairing operator state. */ async function collectDoctorFindings(e) { return (await withArtifactPreservingStateReads(() => prepareDoctorLintExecution(e, { severityMin: "info" }), { agentDatabases: true })).findings; } async function prepareDoctorLintExecution(e, t, n, r) { const i = t.severityMin === void 0 ? "warning" : parseHealthFindingSeverity(t.severityMin); if (i === null) throw new Error("Invalid --severity-min value. Expected one of: info, warning, error."); maybeLoadDotEnvForConfig(process.env); const a = { ...process.env }; if (resolveUpdateRehearsalRoot(a) && !t.onlyIds?.length) { const n = await createConfigIO({ env: a, observe: false, pluginValidation: "core-only" }).readConfigFileSnapshot(); if (n.valid) { const i = await resolveDoctorUpdateBudget({ cfg: n.config, env: a, commandStartedAtMs: r }); if (i && !admitDoctorUpdateInspection(i, "agent", [{ id: "core/doctor/lint-inspection", label: "Doctor lint inspection" }])) return createDeferredInspectionExecution(e, t, [...i.deferred.values()]); } } const o = isUpdateDoctorLintPass(a) ? [] : void 0; const runStateChecks = async () => { const r = isPostCoreConvergencePass(a) ? "post-plugin" : void 0; const s = r ? { ...t, updateReadiness: r } : t; const { resolveBundledHealthCheckPluginStateMode: c } = await import("./bundled-health-checks-BJWxOv9V.mjs"); const l = c(s); let u; const d = /* @__PURE__ */ new Set(); if (resolveUpdateRehearsalRoot(a) && !r && !t.onlyIds?.length) { const { resolveDoctorContributionHealthChecks: e } = await import("./doctor-health-contributions-3uI5m45X.mjs"); u = await e(); for (const e of u) if ((e.updateWork?.kind === "inspection" || e.updateWork?.kind === "standalone") && (t.includeAllChecks === true || isHealthCheckEnabledByDefault(e)) && !t.skipIds?.includes(e.id)) d.add(e.id); } const f = !d.has(RUNTIME_TOOL_SCHEMA_CHECK_ID) && (l === "isolated" || !s.onlyIds?.length || s.onlyIds.includes(RUNTIME_TOOL_SCHEMA_CHECK_ID)); const readConfigSnapshot = async (e) => { const t = l === "direct" ? { readConfigFileSnapshot, readConfigFileSnapshotWithPluginMetadata } : createConfigIO({ env: a, configPath: resolveConfigPath(a, resolveStateDir(a)), observe: false, pluginValidation: l === "deferred" ? "core-only" : void 0, deferredPluginMigrations: e }); return l === "deferred" || !f ? t.readConfigFileSnapshot({ observe: false }) : (await t.readConfigFileSnapshotWithPluginMetadata({ observe: false, prepareValidation: "runtime" })).snapshot; }; let p = false; let m; try { return await withReadOnlyPluginStateSnapshot(a, async (t) => { const r = { coreChecks: u, deferredCheckIds: d, cleanupWarnings: o, pluginMetadataEnv: a, sourceEnv: a, readConfigSnapshot, runWithPluginStateSnapshot: t }; if (l !== "isolated" && !n) return m = await executeDoctorLint(e, s, i, r); return await r.runWithPluginStateSnapshot(async (t) => { const a = readDeferredPluginMigrations({ env: t }); const o = []; try { const c = await executeDoctorLint(e, s, i, { ...r, pluginMetadataEnv: t, readConfigSnapshot: () => readConfigSnapshot(a), runWithPluginStateSnapshot: async (e) => e(t), deferInspectionDisposal: n ? (e) => o.push(e) : void 0 }); m = c; n?.(c); p = n !== void 0; return c; } finally { for (const t of o) try { await t(); } catch (t) { e.error(`${UPDATE_DOCTOR_DISPOSAL_WARNING_PREFIX}: ${scrubDoctorErrorMessage(t)}`); } } }); }, o); } catch (t) { if (p || !(t instanceof DoctorLintStateSnapshotError)) throw t; return createStateSnapshotFailureExecution(e, s, i, t, m); } }; let s; try { return await withOpenClawStateDatabaseReadSnapshot(async () => s = await runStateChecks(), { env: a, lazy: Boolean(t.onlyIds?.length) }); } catch (e) { if (!s || !o || !(e instanceof SqliteSnapshotCleanupError)) throw e; recordSnapshotCleanupWarning(o); return s; } } async function executeDoctorLint(e, t, n, r) { const i = await r.readConfigSnapshot(); const a = i.exists && !i.valid ? tryProjectRetiredHeartbeatConfig(i.sourceConfig) : void 0; const o = a && (resolveLegacyHeartbeatAgents(i.sourceConfig).some((e) => e.heartbeat !== void 0) || !isDeepStrictEqual(i.sourceConfig.channels, a.channels)) ? a : void 0; const s = o ? validateConfigObjectWithPlugins(o, { env: r.pluginMetadataEnv, sourceRaw: o }) : void 0; if (i.exists && !i.valid && !s?.ok) { const { collectNodeRuntimeFindings: a } = await import("./node-runtime-diagnostics-C4MzJK1U.mjs"); const o = await a(r.sourceEnv); const s = [...configValidationIssuesToHealthFindings(i.issues), ...o]; const c = s.filter((e) => healthFindingMeetsSeverity(e, n)); return { checksRun: 1, checksSkipped: 0, exitCode: exitCodeFromFindings(s, n), findings: c, cleanupWarnings: r.cleanupWarnings, writeOutput() { if (detectDoctorLintOutputMode(t) === "json") { writeJsonResult({ ok: false, checksRun: 1, checksSkipped: 0, findings: c, warnings: r.cleanupWarnings }); return; } e.error("doctor --lint: config file exists but does not parse cleanly."); for (const t of i.issues) { const n = t.path || "<root>"; e.error(`- ${n}: ${t.message}`); } for (const t of o.filter((e) => healthFindingMeetsSeverity(e, n))) e.error(t.fixHint ? `${t.message}\n${t.fixHint}` : t.message); for (const t of r.cleanupWarnings ?? []) e.error(`${UPDATE_DOCTOR_DISPOSAL_WARNING_PREFIX}: ${t.message}`); } }; } const c = s?.ok ? s.config : i.config; const l = s?.ok ? { exists: i.exists, issues: [], warnings: s.warnings } : i; const u = s?.ok ? i.sourceConfig : void 0; await loadPinnedRuntimeConfigAsync(async () => ({ config: c })); const d = captureRuntimeConfig(c); const f = { ...r.sourceEnv }; const p = tryResolveDefaultAgentId(d); const m = { mode: "lint", runtime: e, cfg: d, cwd: p ? resolveAgentWorkspaceDir(d, p) : process.cwd(), env: f, allowExecSecretRefs: t.allowExec === true, ...i.path !== void 0 ? { configPath: i.path } : {} }; const { registerBundledHealthChecks: h } = await import("./bundled-health-checks-BJWxOv9V.mjs"); const g = h({ cfg: d, cwd: m.cwd, env: r.pluginMetadataEnv, runWithPluginStateSnapshot: r.runWithPluginStateSnapshot, updateReadiness: t.updateReadiness }); const _ = listExtensionHealthChecksForDoctor([], g); const v = t.onlyIds !== void 0 && t.onlyIds.length > 0 && t.onlyIds.every((e) => _.some((t) => t.id === e)); let y = v ? [] : r.coreChecks; if (!y) { const { resolveDoctorContributionHealthChecks: e } = await import("./doctor-health-contributions-3uI5m45X.mjs"); y = await e(); } const b = v ? _ : listExtensionHealthChecksForDoctor(y, g); const runWithPrivateStateSnapshot = async (e) => await r.runWithPluginStateSnapshot(async () => await e()); const runWithSourceState = async (e) => t.updateReadiness ? e() : withDoctorLintStateEnv(f, e, "captured"); const x = { ...m, env: t.updateReadiness ? r.pluginMetadataEnv : f, lintConfigSnapshot: l, deep: t.deep === true, runWithPrivateStateSnapshot, runWithSourceState, deferInspectionDisposal: r.deferInspectionDisposal }; const S = [ stateSchemaHealthCheck, ...y.map((e) => { const t = u && HEARTBEAT_SOURCE_CHECK_IDS.has(e.id) ? { ...x, cfg: u } : x; return { ...e, detect(n, r) { const detect = async () => [...await e.detect(t, r), ...g.filter((t) => t.checkId === e.id)]; const inspectPrivate = async (e) => { let n; try { return await t.runWithPrivateStateSnapshot(async () => n = await e()); } catch (e) { if (!n?.length || !(e instanceof DoctorLintStateSnapshotError)) throw e; return [...n, createStateSnapshotFailureFinding(e)]; } }; if (e.id === SKILLS_READINESS_CHECK_ID) return inspectPrivate(() => t.runWithSourceState(detect)); if (e.id === RUNTIME_TOOL_SCHEMA_CHECK_ID || e.id === PROJECT_CLONE_SHAPE_CHECK_ID) return inspectPrivate(detect); return e.id === AUTH_PROFILE_CHECK_ID || HEARTBEAT_SOURCE_CHECK_IDS.has(e.id) ? t.runWithSourceState(detect) : detect(); } }; }), ...b ]; const C = { checks: t.updateReadiness && t.includeAllChecks !== true ? selectUpdateReadinessChecks(S, t.updateReadiness) : S, includeAllChecks: t.updateReadiness !== void 0 || t.includeAllChecks === true, skipIds: [...t.skipIds ?? [], ...r.deferredCheckIds ?? []], ...t.onlyIds && t.onlyIds.length > 0 ? { onlyIds: t.onlyIds } : {} }; const w = await runDoctorLintChecks(m, C); const T = [...w.findings, ...y.filter((e) => r.deferredCheckIds?.has(e.id)).map((e) => ({ checkId: e.id, source: "doctor", severity: "warning", errorCode: "update-inspection-deferred", requirement: "update-validation-scope", message: "Advisory inspection deferred until after update activation; required migration, config, plugin, and Gateway readiness checks remain enabled.", fixHint: `Run \`openclaw doctor --lint --only ${e.id}\` after activation to complete this inspection.` }))]; const E = new Set(y.filter((e) => e.updateWork?.kind === "inspection" || e.updateWork?.kind === "standalone").map((e) => e.id)); const D = isUpdateDoctorLintPass(r.sourceEnv) ? T.map((e) => e.severity === "error" && E.has(e.checkId) ? { ...e, severity: "warning" } : e) : T; const O = D.flatMap((e) => e.checkId === "core/doctor/database-engine" && e.details ? [e.details] : []); const k = D.filter((e) => healthFindingMeetsSeverity(e, n)); const A = D.filter((e) => !healthFindingMeetsSeverity(e, n) && (e.errorCode === "OPENCLAW_STATE_LEASE_ABORTED" || isUpdateDoctorLintPass(r.sourceEnv) && e.severity === "warning")); const j = exitCodeFromFindings(D, n); const M = collectRecoveryDiskUsage({ cfg: d, env: r.sourceEnv }); return { checksRun: w.checksRun, checksSkipped: w.checksSkipped, exitCode: j, findings: k, databaseStores: O, recoveryCopies: M, warnings: A, cleanupWarnings: r.cleanupWarnings, writeOutput() { if (detectDoctorLintOutputMode(t) === "json") { writeJsonResult({ ok: j === 0, checksRun: w.checksRun, checksSkipped: w.checksSkipped, findings: k, databaseStores: O.length ? O : void 0, recoveryCopies: M, warnings: [...A, ...r.cleanupWarnings ?? []] }); return; } process.stdout.write(`Recovery copies (read-only): ${formatRecoveryDiskUsage(M)}\n`); const e = [ ...k, ...A, ...r.cleanupWarnings ?? [] ]; process.stdout.write(`doctor --lint: ran ${w.checksRun} check(s), ${e.length} finding(s)\n`); if (e.length === 0) { process.stdout.write(" no findings\n"); return; } for (const t of e) { const e = t.path !== void 0 ? ` ${t.path}` : ""; const n = t.line !== void 0 ? `:${t.line}` : ""; process.stdout.write(` [${t.severity}] ${t.checkId}${e}${n} - ${t.message}\n`); if (t.fixHint !== void 0) process.stdout.write(` fix: ${t.fixHint}\n`); } } }; } //#endregion export { collectDoctorFindings, runDoctorLintCliInProcess };