UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

408 lines (407 loc) • 18.9 kB
import { s as resolveOpenClawCliInvocation } from "../cli-invocation-ZSPsKRWa.mjs"; import { t as safeParseJson } from "../json-coercion-CaJLaav-.mjs"; import { o as writeRuntimeJson, r as defaultRuntime } from "../runtime-B-SLYP-m.mjs"; import { r as resolveStateDir } from "../state-dir-DiG0gXzD.mjs"; import "../paths-DAcAg5aV.mjs"; import { a as getOpenClawDatabaseMaintenanceScope } from "../openclaw-state-maintenance-context-D6i7Zdhn.mjs"; import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "../kysely-sync-YJo2lmGV.mjs"; import { n as clearNodeSqliteKyselyCacheForDatabase } from "../kysely-sync-cache-state-Bb1gOqQO.mjs"; import { a as tableExists } from "../openclaw-state-db-schema-helpers-nImZNMq_.mjs"; import { t as VERSION } from "../version-GlxUMdxI.mjs"; import { n as openNodeSqliteDatabase } from "../node-sqlite-CU4puofF.mjs"; import { s as resolveOpenClawStateSqlitePath } from "../openclaw-state-db.paths-R3ArRCcz.mjs"; import "../openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs"; import { r as prepareSqliteReadOnlyLocation } from "../sqlite-snapshot-source-Q9S7_uQN.mjs"; import { a as resolveUpdateRehearsalRoot } from "../update-rehearsal-paths-Dr1MbUA_.mjs"; import { t as getGatewayServiceInstallation } from "../gateway-service-installation-context-CHlb7Eod.mjs"; import { f as readStateSchemaPublicationBlocker } from "../openclaw-state-db-engine-sM0tpxNy.mjs"; import { n as openDoctorStateSchemaReadAdmission } from "../openclaw-state-db-doctor-schema-C5bP-XwE.mjs"; import { t as UpdateSchemaRefusalError } from "../openclaw-update-schema-refusal-DQDN1MLl.mjs"; import { g as assertGatewayServiceSchemaMigrationAllowed } from "../openclaw-state-db-ARhwdPJg.mjs"; import { r as UpdateRunRecordSchema } from "../update-run-schema-tIwTkB6s.mjs"; import { r as formatCliJsonFailure } from "../failure-output-DVVDqwuu.mjs"; import { t as exitCliAfterOutput } from "../one-shot-exit-DkbGSQD5.mjs"; import { n as POST_CORE_UPDATE_ENV } from "../update-post-core-context-Dy8UPbYC.mjs"; import { n as readUpdateRunDriver, r as sameUpdateRunDriver, t as inspectUpdateRunDriver } from "../update-run-driver-BoURWp0g.mjs"; import { n as prepareDoctorDatabasePreflight } from "../doctor-database-preflight-B73Pb1X8.mjs"; import { t as resolveDoctorUpdateAdmission } from "../doctor-maintenance-admission-CqCSvhaQ.mjs"; import { t as createDoctorRehearsalDatabaseCoverage } from "../doctor-rehearsal-databases-BTJBQN1P.mjs"; import { i as resolveUpdateDoctorGitRecovery, r as recordUpdateDoctorRefusal } from "../doctor-update-refusal-B2SaHPHZ.mjs"; import { p as isUpdatePackageSwapInProgress } from "../update-phase-YdZvaQsy.mjs"; import { lstatSync, realpathSync, statSync } from "node:fs"; import path from "node:path"; import { randomUUID } from "node:crypto"; //#region src/commands/doctor-update-schema-guard.ts function sameSnapshotFile(e, t) { return e.dev !== 0n && e.ino !== 0n && e.dev === t.dev && e.ino === t.ino; } async function readDrivingUpdater(e = false) { const t = await prepareSqliteReadOnlyLocation(resolveOpenClawStateSqlitePath(), { preserveSourceArtifacts: true }); try { const n = openNodeSqliteDatabase(t.location, { readOnly: true }); let r; try { r = openDoctorStateSchemaReadAdmission(n); if (e && process.platform === "win32" && tableExists(n, "update_runs")) { const e = executeSqliteQuerySync(n, getNodeSqliteKysely(n).selectFrom("update_runs").select([ "run_id", "before_json", "origin_json", "steps_json" ]).where("status", "=", "running").orderBy("run_id")).rows; for (const t of e) { const e = UpdateRunRecordSchema.shape.before.safeParse(safeParseJson(t.before_json)); if (!e.success || e.data.version !== "2026.9.4") continue; const n = UpdateRunRecordSchema.shape.origin.safeParse(safeParseJson(t.origin_json)); const r = n.success ? [...n.data.driver ? [n.data.driver] : [], ...n.data.previousDrivers ?? []] : []; const i = UpdateRunRecordSchema.shape.steps.safeParse(safeParseJson(t.steps_json)); if (i.success && !i.data.some((e) => e.step === "driver:identity-unavailable") && r.length > 0 && r.every((e) => inspectUpdateRunDriver(e) === "dead")) continue; return { runId: t.run_id, version: e.data.version, canDeferStateSchema: false, earlyDoctorRunning: false, postCoreStarted: false, requiresReadableSharedContent: true }; } } const t = readStateSchemaPublicationBlocker(n); if (!t) return; const i = executeSqliteQueryTakeFirstSync(n, getNodeSqliteKysely(n).selectFrom("update_runs").select(["status", "steps_json"]).where("run_id", "=", t.runId)); const a = UpdateRunRecordSchema.shape.steps.safeParse(i ? safeParseJson(i.steps_json) : []); const stepStatus = (e) => a.success ? a.data.findLast((t) => t.step === e)?.status : void 0; return { runId: t.runId, version: t.updaterVersion, canDeferStateSchema: tableExists(n, "config_machine_state"), earlyDoctorRunning: i?.status === "running" && stepStatus("openclaw doctor") === "in_progress", postCoreStarted: i?.status === "running" && stepStatus("openclaw doctor") === "completed" && stepStatus("post-update verification") === "in_progress" }; } finally { try { r?.(); } finally { clearNodeSqliteKyselyCacheForDatabase(n); n.close(); } } } finally { await t.cleanupAsync(); } } /** Prepare reusable fleet facts and refuse before CLI bootstrap or Doctor can write state. */ async function guardUpdateDoctorSchemaUpgrade(e) { if (process.env.OPENCLAW_UPDATE_IN_PROGRESS !== "1") return; const t = e.statePublicationOnly ? void 0 : createDoctorRehearsalDatabaseCoverage(process.env); const n = e.schemas ?? await prepareDoctorDatabasePreflight({ scope: e.statePublicationOnly ? "state" : void 0, preserveSourceArtifacts: e.preserveSourceArtifacts }); t?.assertCurrent(); if (!n.pendingMigrations?.length) return n; t?.admit([...n.pendingMigrations.filter((e) => e.kind === "agent").map((e) => e.path), ...n.agentDatabaseMigrationDiscovery?.discovery.schemaTargets.map((e) => e.path) ?? []]); let r; const i = (e.entry !== void 0 || e.statePublicationOnly === true) && n.pendingMigrations.some((e) => e.kind === "state" && e.supportedVersion > 17); try { r = await readDrivingUpdater(i); } catch {} t?.assertCurrent(); if (e.entry === "package-lifecycle" && !r?.requiresReadableSharedContent) return n; if (!r) return n; const a = r.earlyDoctorRunning && !r.postCoreStarted && isUpdatePackageSwapInProgress(process.env) && process.env.OPENCLAW_UPDATE_PARENT_SUPPORTS_DOCTOR_CONFIG_WRITE === "1" && process.env["OPENCLAW_UPDATE_POST_CORE"] !== "1" && process.env.OPENCLAW_UPDATE_PARENT_SUPPORTS_GATEWAY_RESTART === "1" && process.env.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_SERVICE_REPAIR === "0" && process.env.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_ACTIVATION === "0" && process.env.OPENCLAW_SERVICE_REPAIR_POLICY === "external"; const o = n.pendingMigrations.filter((n) => r.requiresReadableSharedContent ? n.kind === "state" && n.supportedVersion > 17 : n.kind === "agent" ? !e.statePublicationOnly && !t?.excludes(n.path) : !r.canDeferStateSchema || a); t?.assertCurrent(); if (o.length === 0) return n; const s = { message: "The update has already committed its package. Complete Doctor repair with the installed compatible build before restarting the Gateway; package rollback cannot undo migrated state.", commands: ["openclaw doctor --fix", "openclaw gateway start"] }; const c = r.postCoreStarted ? s : await resolveUpdateDoctorGitRecovery(); t?.assertCurrent(); if (r.canDeferStateSchema && (a || o.every((e) => e.kind === "agent"))) { const capturePending = () => o.filter((e) => e.kind === "agent").map((e) => ({ database: e, identity: statSync(e.path, { bigint: true }) })); const coverageRefusal = (e, t) => new UpdateSchemaRefusalError(e, r.version, { targetVersion: VERSION, cause: /* @__PURE__ */ new Error(`Missing recoverable database backup coverage: ${t}`), recovery: c }); const t = e.postCoreSchemaRepair; const i = getOpenClawDatabaseMaintenanceScope(); if (t?.runId === r.runId && r.postCoreStarted && i?.ownsSchemaMaintenance) { const a = capturePending(); const assertCurrent = () => { t.assertCurrent(); i.assertAdmission(); const e = a.filter(({ database: e, identity: t }) => { const n = statSync(e.path, { bigint: true, throwIfNoEntry: false }); return !n?.isFile() || !sameSnapshotFile(t, n); }); if (e.length) throw coverageRefusal(e.map(({ database: e }) => e), "a pending agent database changed physical identity."); }; assertCurrent(); const [{ createBackupArchive: c }, { verifyBackupArchive: l }, { resolveUpdateCaptureRoot: u }] = await Promise.all([ import("../backup-create-w7ogQxy8.mjs"), import("../backup-verify-CyW6XuB4.mjs"), import("../update-capture-paths-CAKuUTUb.mjs") ]); assertCurrent(); let d = []; const f = await c({ signal: e.signal, output: path.join(u(resolveStateDir()), `agent-schema-${r.runId}-${randomUUID()}.tar.gz`), includeWorkspace: false, onSqliteSnapshots: (e) => { d = e; } }); s.message += ` Archive retained for inspection at ${f.archivePath}.`; assertCurrent(); const p = []; const m = a.filter(({ database: e, identity: t }) => { const n = d.find((n) => n.role === "agent" && n.agentId === e.agentId && sameSnapshotFile(t, n)); if (!n) return true; p.push(n); return false; }); if (m.length) throw coverageRefusal(m.map(({ database: e }) => e), `the retained archive at ${f.archivePath} has no captured database image for these agent databases.`); const h = d.filter((e) => e.role === "agent"); await l(f.archivePath, h); assertCurrent(); const g = await readDrivingUpdater(); assertCurrent(); if (g?.runId !== r.runId || !g.postCoreStarted) throw new UpdateSchemaRefusalError(o, r.version, { targetVersion: VERSION, recovery: s, cause: /* @__PURE__ */ new Error(`Post-core admission changed; recovery backup remains at ${f.archivePath}.`) }); i.addAgentSchemaMigrationCheck((e) => { t.assertCurrent(); const n = statSync(e.path, { bigint: true, throwIfNoEntry: false }); if (!n?.isFile() || !h.some((t) => t.role === "agent" && t.agentId === e.agentId && sameSnapshotFile(n, t))) throw coverageRefusal([{ kind: "agent", ...e }], "agent database physical identity changed or has no verified snapshot before schema migration."); }); (e.runtime ?? defaultRuntime).log(`Verified agent-schema recovery backup retained at ${f.archivePath}.`); e.onVerifiedBackup?.(p); return n; } if (!c && a) { const e = capturePending(); const t = n.agentDatabaseMigrationDiscovery?.registeredAgentDatabases ?? []; const i = e.filter(({ database: e, identity: n }) => !t.some((t) => { if (t.agentId !== e.agentId) return false; const r = statSync(t.path, { bigint: true, throwIfNoEntry: false }); return r?.isFile() && sameSnapshotFile(n, r); })); if (i.length) throw coverageRefusal(i.map(({ database: e }) => e), "these pending agent databases have no registered snapshot owner."); return { ...n, updateSchemaRehearsal: { runId: r.runId, updaterVersion: r.version } }; } } const l = new UpdateSchemaRefusalError(o, r.version, { targetVersion: VERSION, recovery: c }); if (c && !e.statePublicationOnly) recordUpdateDoctorRefusal(l.message); if (e.json) { const t = e.runtime ?? defaultRuntime; writeRuntimeJson(t, formatCliJsonFailure(l)); exitCliAfterOutput(t, 1); } throw l; } /** Complete a private CLI validation before bootstrap can reach any live writer. */ async function preflightUpdateDoctorCli(e) { const t = readUpdateRunDriver(process.ppid); if (resolveUpdateRehearsalRoot(process.env)) { await guardUpdateDoctorSchemaUpgrade({ ...e, entry: "cli-bootstrap", statePublicationOnly: true }); return; } const n = getGatewayServiceInstallation() ? await prepareDoctorDatabasePreflight() : void 0; const r = await guardUpdateDoctorSchemaUpgrade({ ...e, schemas: n, entry: "cli-bootstrap" }); if (r?.updateSchemaRehearsal) { await rehearseDeferredUpdateDoctorSchemaForParent(r, defaultRuntime, t, e.fullIntegrityCheck); exitCliAfterOutput(defaultRuntime, 0); } const i = n?.pendingMigrations?.find((e) => e.foundVersion > 0 && e.foundVersion < e.supportedVersion); if (i) { if (!(process.env.OPENCLAW_UPDATE_IN_PROGRESS === "1" && Boolean(process.env.OPENCLAW_UPDATE_RUN_ID?.trim()) && resolveDoctorUpdateAdmission(process.env).readContinuation() !== void 0)) assertGatewayServiceSchemaMigrationAllowed(resolveOpenClawStateSqlitePath(), i.foundVersion, i.supportedVersion); } return r ?? n; } /** The shipped Windows driver can still discard a failed npm stage before entering repair. */ async function preflightUpdatePackageLifecycle() { if (process.platform !== "win32" || process.env.OPENCLAW_UPDATE_IN_PROGRESS !== "1") return; let e; try { e = await readDrivingUpdater(true); } catch {} if (!e?.requiresReadableSharedContent) return; await guardUpdateDoctorSchemaUpgrade({ schemas: await prepareDoctorDatabasePreflight({ scope: "state" }), entry: "package-lifecycle" }); } /** The shipped package validator may still roll back; it must never reach live Doctor writers. */ function rehearseDeferredUpdateDoctorSchema(e, t = defaultRuntime, n) { return rehearseDeferredUpdateDoctorSchemaForParent(e, t, readUpdateRunDriver(process.ppid), n); } async function rehearseDeferredUpdateDoctorSchemaForParent(e, t, n, r) { const i = e.updateSchemaRehearsal; if (!i) throw new Error("Missing legacy update schema rehearsal admission."); if (!n) throw new Error("The schema rehearsal parent identity is unavailable."); const assertParent = () => { const e = readUpdateRunDriver(process.ppid); if (!e || !sameUpdateRunDriver(e, n)) throw new Error("The schema rehearsal parent identity changed."); }; assertParent(); const [{ createConfigIO: a }, { resolveOpenClawPackageRoot: o }, { resolveUpdateInstallKind: s }, { prepareUpdateCandidateRehearsal: c }, { resolveGatewayInstallEntrypoint: l }, { runUtf8CommandWithTimeout: u }, { resolveSqliteInspectionBudget: d }] = await Promise.all([ import("../io-DeTUDO0h.mjs"), import("../openclaw-root-y32pjg1o.mjs"), import("../update-check-DzgdmSuQ.mjs"), import("../update-candidate-rehearsal-Pm8Y2jsz.mjs"), import("../gateway-entrypoint-CdlNs46F.mjs"), import("../exec-Df6gUJ1h.mjs"), import("../sqlite-readonly-worker-BXIE20HR.mjs") ]); const f = await o({ moduleUrl: import.meta.url, argv1: process.argv[1] }); const p = await readDrivingUpdater(); if (!f || await s(f) !== "package" || p?.runId !== i.runId || !p.earlyDoctorRunning || p.postCoreStarted) throw new UpdateSchemaRefusalError(e.pendingMigrations ?? [], i.updaterVersion, { targetVersion: VERSION, cause: /* @__PURE__ */ new Error("The shipped package-validation handoff could not be verified.") }); assertParent(); const m = await l(f); if (!m) throw new Error("Candidate Doctor entrypoint is unavailable for private schema validation."); const h = await a({ observe: false, pluginValidation: "core-only" }).readConfigFileSnapshot(); assertParent(); const g = await c({ candidateRoot: f, config: h.sourceConfig ?? h.config, stateDir: resolveStateDir() }); const _ = new Map(g.cleanupDirectories.map((e) => { const t = lstatSync(e, { bigint: true }); if (!t.isDirectory() || t.isSymbolicLink() || realpathSync(e) !== e) throw new Error(`Private Doctor cleanup root is not physical; retained ${e}.`); return [e, t]; })); const assertCleanupDirectory = (e) => { const t = _.get(e); const n = lstatSync(e, { bigint: true }); if (!t || !sameSnapshotFile(t, n) || !n.isDirectory() || n.isSymbolicLink() || n.uid !== t.uid || realpathSync(e) !== e) throw new Error(`Private Doctor cleanup identity changed; inspect ${e}.`); }; let v; let y = false; let b = false; let x = []; try { await g.prepareRuntime(assertParent); const e = { ...g.env, OPENCLAW_UPDATE_IN_PROGRESS: "0" }; const { inspectPreparedDoctorRehearsal: n } = await import("../doctor-update-rehearsal-inventory-CCi1b_CR.mjs"); const a = await n({ stateDir: g.stateDir, pluginCodeLinks: g.pluginCodeLinks, env: e, assertCurrent: assertParent }); const o = await readDrivingUpdater(); if (o?.runId !== i.runId || !o.earlyDoctorRunning || o.postCoreStarted) throw new Error("The schema rehearsal updater changed before Doctor launch."); x = a.fact.warnings; t.log(JSON.stringify(a.fact)); a.assertPrepared(); b = true; const s = resolveOpenClawCliInvocation({ entryPath: m, execArgv: [], args: [ "doctor", "--fix", "--non-interactive", "--no-workspace-suggestions", ...r ? ["--full-integrity-check"] : [] ] }); const c = await u([s.command, ...s.args], { cwd: f, baseEnv: e, timeoutMs: d("legacy update schema rehearsal", g.stateDir, g.snapshotCapacity.sqliteBytes).timeoutMs, killProcessTree: true, requireProcessTreeExtinction: true, outputCapture: { stdout: "discard", stderr: "tail" }, maxOutputBytes: { stderr: 2e4 } }); y = c.cleanup === "normal"; if (!y) throw new Error(`Private Doctor did not settle; rehearsal retained at ${g.stateDir}.`); if (c.code !== 0 || c.termination !== "exit" || c.outputLimitExceeded) { const { redactSupportString: t } = await import("../diagnostic-support-redaction-BjHMYrwC.mjs"); throw new Error(`Private Doctor schema validation failed (${c.termination}): ${t(c.stderr, { env: e, stateDir: g.stateDir }, { maxLength: 2e3 })}`); } } catch (e) { v = { error: e }; } if (y || !b) try { for (const e of _.keys()) assertCleanupDirectory(e); await g.cleanup(assertCleanupDirectory); } catch (e) { if (v) t.error(`Warning: Private Doctor cleanup was not completed: ${String(e)}`); else throw e; } if (v) throw v.error; const S = `Validated schema repair on private copies for OpenClaw ${i.updaterVersion}; live databases are unchanged. Repair is deferred to the fresh post-core updater.`; const { UPDATE_POST_INSTALL_DOCTOR_RESULT_PATH_ENV: C, writeUpdatePostInstallDoctorResult: w } = await import("../update-doctor-result-BiaHv1QW.mjs"); const T = process.env[C]; if (T) await w({ resultPath: T, result: { status: "ok", configHash: "unchanged", warnings: [S, ...x.map((e) => e.message)] } }); for (const e of x) t.error(`Warning: ${e.message}`); t.log(S); } //#endregion export { guardUpdateDoctorSchemaUpgrade, preflightUpdateDoctorCli, preflightUpdatePackageLifecycle, rehearseDeferredUpdateDoctorSchema };