UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

504 lines (503 loc) • 20 kB
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs"; import "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { i as isPidAlive } from "./pid-alive-D899x-ak.mjs"; import { m as withExistingOpenClawStateDatabaseReadOnly } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { l as runOpenClawStateWriteTransaction } from "./openclaw-state-db-ARhwdPJg.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { a as resolveCronJobsStorePathFromConfig, c as resolveCronStoreKeyInDatabase } from "./paths-CY4cvrR6.mjs"; import { t as CronStoreSelectionRequiredError } from "./selection-error-CCb6S-v3.mjs"; import { c as projectCronJobThroughStorageCodec, o as loadCronRows, s as loadedCronStoreFromRows } from "./row-codec-D4aymQkb.mjs"; import { t as CRON_JOB_SCRATCH_MAX_BYTES } from "./scratch-contract-COS3OFt4.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import "./store-DaG-8LOU.mjs"; import { t as readScratchStateFromDatabase } from "./scratch-read.kernel-DoxT4y0Y.mjs"; import { n as readCronJobScratchState, t as hashCronScratchSource } from "./scratch-store-rlXr8TbJ.mjs"; import { n as readDefaultProactiveJobReceiptInDatabase } from "./proactive-job-receipt.kernel-DONrwKqL.mjs"; import "./proactive-job-receipt-DquAVkxB.mjs"; import { i as resolveLegacyHeartbeatAgents, o as resolveLegacyHeartbeatConfig } from "./doctor-heartbeat-legacy-DmzlheVU.mjs"; import { n as validateHeartbeatTasks, t as analyzeLegacyHeartbeatTasks } from "./heartbeat-task-legacy-B_GDgmyR.mjs"; import { c as decodeDoctorHeartbeatJobRows, l as readDoctorHeartbeatCutoverReceipt, n as ensureHeartbeatMonitorJobs, o as resolveDoctorHeartbeatReceiptJob, s as selectDoctorHeartbeatMonitor } from "./doctor-heartbeat-cadence-migration-C-SedrS2.mjs"; import { t as writeCronJobScratchInDatabase } from "./scratch-write.kernel-CNOhd-it.mjs"; import { t as noteDoctorMigrationResult } from "./doctor-migration-notes-BBiomgyk.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import { TextDecoder, isDeepStrictEqual } from "node:util"; import { readRegularFile } from "@openclaw/fs-safe/advanced"; //#region src/commands/doctor-heartbeat-scratch-migration.ts /** Doctor-owned migration from workspace HEARTBEAT.md files into cron job scratch. */ const LEGACY_HEARTBEAT_FILENAME = "HEARTBEAT.md"; const utf8Decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); function resolveHeartbeatFileAgentIds(e) { const t = new Set(resolveLegacyHeartbeatAgents(e).map((e) => e.agentId)); return listAgentIds(e).filter((n) => t.has(n) || resolveLegacyHeartbeatConfig(e, n) !== void 0); } async function readHeartbeatSource(e, t, n) { const r = resolveAgentWorkspaceDir(e, t, n?.env); const i = path.join(r, LEGACY_HEARTBEAT_FILENAME); let a; try { a = await fs.lstat(i); if (n?.receipt?.phase === "complete") return { path: i, entryKey: path.join(await fs.realpath(r), LEGACY_HEARTBEAT_FILENAME), retained: true }; const e = await findStaleHeartbeatClaim(i); if (e) throw new Error(`both ${i} and an interrupted migration claim at ${e} exist; reconcile them manually before rerunning doctor`); } catch (e) { if (e.code !== "ENOENT") throw e; if (n?.receipt?.phase === "complete") return; const t = await findStaleHeartbeatClaim(i); if (!t) return; if (!n?.recoverClaims) throw new Error(`an interrupted migration claim exists at ${t}; run openclaw doctor --fix to restore it`, { cause: e }); await restoreClaimNoClobber(t, i); a = await fs.lstat(i); } if (!a.isFile() && !a.isSymbolicLink()) throw new Error("HEARTBEAT.md must be a regular file or contained symlink"); if (a.isFile() && a.nlink > 1) throw new Error("HEARTBEAT.md has multiple hard links; refusing automatic removal"); const o = await fs.realpath(r); const s = await fs.realpath(i); if (s !== o && !isPathInside(o, s)) throw new Error("HEARTBEAT.md symlink target escapes the agent workspace"); const c = await readRegularFile({ filePath: s, maxBytes: CRON_JOB_SCRATCH_MAX_BYTES }); let l; try { l = utf8Decoder.decode(c.buffer); } catch { throw new Error("HEARTBEAT.md is not valid UTF-8"); } return { path: i, entryKey: path.join(o, LEGACY_HEARTBEAT_FILENAME), content: l, sha256: hashCronScratchSource(l) }; } function completedHeartbeatSourceWarning(e, t) { return `Agent "${e}" has completed cutover; ${shortenHomePath(t)} was retained for review without changing the operator-owned automation.`; } function heartbeatScratchMigrationConflict(e, t, n) { if (n.currentRevision > 0 && !n.scratch) return `Agent "${e}" scratch was explicitly unset; it was left unchanged and HEARTBEAT.md was retained for review.`; if (n.scratch && n.scratch.content !== t && !n.scratch.sourceSha256) return `Agent "${e}" already has different cron scratch; the automation keeps it and HEARTBEAT.md was retained for review.`; } function archivePathForSource(e, t, n) { const r = e.replace(/[^A-Za-z0-9._-]+/g, "-"); return path.join(resolveStateDir(n), "backups", "heartbeat-migration", `${r}-${t}.md`); } const HEARTBEAT_CLAIM_INFIX = ".doctor-importing-"; const HEARTBEAT_CLAIM_CHANGED_ERROR = "HeartbeatClaimChangedError"; /** Interrupted-claim sibling for a missing canonical heartbeat path. */ async function findStaleHeartbeatClaim(e) { const t = path.dirname(e); const n = new RegExp(`^${escapeRegExp(path.basename(e))}${escapeRegExp(HEARTBEAT_CLAIM_INFIX)}\\d+-[0-9a-f]{12}$`); let r; try { r = await fs.readdir(t); } catch (e) { if (hasErrnoCode(e, "ENOENT")) return; throw e; } const i = r.filter((e) => n.test(e)); if (i.length > 1) throw new Error(`multiple interrupted migration claims exist for ${e}; remove or restore the stale .doctor-importing-* files manually`); const a = i[0]; if (!a) return; const o = Number(a.slice(a.lastIndexOf(HEARTBEAT_CLAIM_INFIX) + 18).split("-")[0]); if (Number.isSafeInteger(o) && o !== process.pid && isPidAlive(o)) throw new Error(`a migration claim for ${e} is held by running process ${o}; wait for that doctor run to finish`); return path.join(t, a); } /** * Restore a claim without clobbering: `link` fails with EEXIST when another * process recreated the destination while we held the claim, so both files * survive (the recreation in place, the claimed original at a conflict path). */ async function restoreClaimNoClobber(e, t) { try { await fs.link(e, t); await fs.unlink(e); } catch (t) { if (t.code !== "EEXIST") throw t; const n = `${e}.conflict-${Date.now()}`; await fs.rename(e, n); throw new Error(`HEARTBEAT.md was recreated during migration; the claimed original is preserved at ${n}`, { cause: t }); } } /** * Move the source aside and prove the claimed bytes still match what was read. * Pending receipts fence execution until source and destination verification * complete, including edits through descriptors opened before the claim. */ async function claimHeartbeatSource(e) { const t = path.dirname(e.entryKey); const assertWorkspaceUnchanged = async () => { if (await fs.realpath(path.dirname(e.path)) !== t) throw new Error("HEARTBEAT.md workspace changed after the source was read"); }; await assertWorkspaceUnchanged(); const n = `${e.entryKey}${HEARTBEAT_CLAIM_INFIX}${process.pid}-${e.sha256.slice(0, 12)}`; await fs.rename(e.entryKey, n); const restore = async (t) => { await restoreClaimNoClobber(n, e.entryKey).catch((e) => { throw e instanceof Error && e.message.includes("preserved at") ? e : new Error(`HEARTBEAT.md migration claim could not be restored from ${n}`, { cause: t ?? e }); }); }; const readClaimContent = async (e, n = "HEARTBEAT.md target escapes the agent workspace") => { await assertWorkspaceUnchanged(); const r = await fs.realpath(e); if (r !== t && !isPathInside(t, r)) throw new Error(n); const i = await readRegularFile({ filePath: r, maxBytes: CRON_JOB_SCRATCH_MAX_BYTES }); return utf8Decoder.decode(i.buffer); }; try { const t = await readClaimContent(n, "claimed HEARTBEAT.md target escapes the agent workspace"); if (hashCronScratchSource(t) !== e.sha256) throw new Error("HEARTBEAT.md changed before the migration claim was acquired"); } catch (e) { await restore(e); throw e; } const changedError = (e, t) => { const n = new Error(e, t !== void 0 ? { cause: t } : void 0); n.name = HEARTBEAT_CLAIM_CHANGED_ERROR; return n; }; const failChanged = async (e, t) => { const n = changedError(e, t); await restore(n).catch(() => void 0); throw n; }; const verifyUnchanged = async () => { const t = await readClaimContent(n).catch((e) => failChanged("claimed HEARTBEAT.md could not be re-verified before finalization", e)); if (hashCronScratchSource(t) !== e.sha256) await failChanged("HEARTBEAT.md changed while the migration claim was held"); let r; try { await fs.lstat(e.entryKey); r = true; } catch (e) { if (e.code !== "ENOENT") await failChanged("could not verify the original HEARTBEAT.md path", e); r = false; } if (r) await failChanged("HEARTBEAT.md was recreated while the migration claim was held"); }; return { restore, retain: async () => { await restore(void 0); const t = await readClaimContent(e.entryKey).catch((e) => { throw changedError("restored HEARTBEAT.md could not be re-verified", e); }); if (hashCronScratchSource(t) !== e.sha256) throw changedError("HEARTBEAT.md changed after the migration claim was restored"); }, release: async ({ archivePath: t, verifyDestination: r }) => { await verifyUnchanged(); const i = await fs.lstat(n); r(); if (i.isSymbolicLink()) { await fs.unlink(n); return; } for (const i of [t, `${e.entryKey}.doctor-archived`]) { const e = await fs.mkdtemp(`${i}.`); try { r(); await fs.rename(n, path.join(e, LEGACY_HEARTBEAT_FILENAME)); return; } catch (n) { await fs.rmdir(e).catch(() => void 0); if (!hasErrnoCode(n, "EXDEV") || i !== t) throw n; } } } }; } async function archiveSource(e) { const t = archivePathForSource(e.agentId, e.source.sha256, e.env); await fs.mkdir(path.dirname(t), { recursive: true, mode: 448 }); try { await fs.writeFile(t, e.source.content, { flag: "wx", mode: 384 }); } catch (n) { if (n.code !== "EEXIST") throw n; const r = await fs.readFile(t, "utf8"); if (hashCronScratchSource(r) !== e.source.sha256) throw new Error(`heartbeat migration archive collision at ${t}`, { cause: n }); } } /** Reports remaining workspace heartbeat files without changing them. */ async function collectHeartbeatScratchMigrationFindings(e, t = process.env) { const n = { checkId: "core/doctor/heartbeat-scratch-migration", severity: "warning", fixHint: `Run ${formatCliCommand("openclaw doctor --fix")} to migrate HEARTBEAT.md into cron scratch.` }; const r = []; const i = resolveCronJobsStorePathFromConfig(e, t); for (const a of resolveHeartbeatFileAgentIds(e)) { const o = path.join(resolveAgentWorkspaceDir(e, a, t), LEGACY_HEARTBEAT_FILENAME); try { const s = readDoctorHeartbeatCutoverReceipt(i, a, t); const c = await readHeartbeatSource(e, a, { env: t, receipt: s }); if (!c) continue; if (c.retained) { r.push({ ...n, target: a, path: o, requirement: "legacy-heartbeat-file", message: completedHeartbeatSourceWarning(a, c.path), fixHint: "Review the retained file before copying wanted instructions into the automation." }); continue; } if (withExistingOpenClawStateDatabaseReadOnly(({ db: n }) => { const r = resolveCronStoreKeyInDatabase(n, i, t); const o = decodeDoctorHeartbeatJobRows(loadCronRows(n, r)); const l = selectDoctorHeartbeatMonitor(o, a); const u = s ? resolveDoctorHeartbeatReceiptJob(e, o, a, s, l) : l; return !u || !heartbeatScratchMigrationConflict(a, c.content, readScratchStateFromDatabase(n, r, u.id)); }, { env: t }) ?? true) validateHeartbeatTasks(analyzeLegacyHeartbeatTasks(c.content)); r.push({ ...n, target: a, path: o, requirement: "legacy-heartbeat-file", message: `Agent "${a}" still stores heartbeat instructions in HEARTBEAT.md.` }); } catch (e) { const t = e instanceof CronStoreSelectionRequiredError; r.push({ ...n, target: a, path: o, requirement: t ? "heartbeat-migration-deferred" : "heartbeat-file-migration-blocked", severity: t ? "warning" : "error", message: `Agent "${a}" HEARTBEAT.md cannot be migrated: ${formatErrorMessage(e)}` }); } } return r; } /** File ownership is independent of enrollment; disabled agents retain their scratch too. */ async function maybeMigrateHeartbeatFilesToScratch(e) { const t = e.env ?? process.env; const n = resolveCronJobsStorePathFromConfig(e.cfg, t); const r = []; const i = []; const a = []; const o = resolveHeartbeatFileAgentIds(e.cfg); if (!e.shouldRepair) { for (const r of o) try { const i = readDoctorHeartbeatCutoverReceipt(n, r, t); const o = await readHeartbeatSource(e.cfg, r, { env: t, receipt: i }); if (o?.retained) a.push(completedHeartbeatSourceWarning(r, o.path)); else if (o) note(`${shortenHomePath(o.path)} will migrate into automation scratch for ${r}.`, "Heartbeat migration preview"); } catch (e) { i.push(`Agent "${r}" HEARTBEAT.md cannot be migrated: ${formatErrorMessage(e)}`); } noteDoctorMigrationResult({ warnings: i, notices: a }); return { changes: r, warnings: i, ...a.length ? { notices: a } : {} }; } let s; try { const a = await collectHeartbeatScratchMigrationFindings(e.cfg, t); if (a.length === 0) return { changes: r, warnings: i }; s = await ensureHeartbeatMonitorJobs(e.cfg, n, t, a.flatMap((e) => e.target ? [e.target] : [])); } catch (e) { return { changes: r, warnings: [`Could not prepare heartbeat monitor jobs: ${formatErrorMessage(e)}`] }; } const c = /* @__PURE__ */ new Map(); const l = /* @__PURE__ */ new Set(); for (const r of /* @__PURE__ */ new Set([...s.keys(), ...listAgentIds(e.cfg)])) { const o = s.get(r); const u = readDoctorHeartbeatCutoverReceipt(n, r, t); if (!o && u?.phase !== "complete") continue; let d; try { d = await readHeartbeatSource(e.cfg, r, { recoverClaims: true, env: t, receipt: u }); } catch (e) { i.push(`Agent "${r}" HEARTBEAT.md was not migrated: ${formatErrorMessage(e)}`); continue; } if (!d) continue; if (d.retained) { l.add(d.entryKey); a.push(completedHeartbeatSourceWarning(r, d.path)); continue; } if (o) { const e = c.get(d.entryKey) ?? { source: d, agents: [] }; e.agents.push([r, o]); c.set(d.entryKey, e); } } for (const { source: e, agents: o } of c.values()) { const s = []; let c = false; const u = /* @__PURE__ */ new Map(); for (const [r, i] of o) { const o = readCronJobScratchState(n, i.id, { env: t }); const l = o.scratch; u.set(i.id, o.currentRevision); const d = heartbeatScratchMigrationConflict(r, e.content, o); if (d) a.push(d); else { s.push([r, i]); if (l?.sourceSha256 !== e.sha256) c = true; } } const d = l.has(e.entryKey) || s.length !== o.length; if (s.length === 0 || d && !c) continue; try { validateHeartbeatTasks(analyzeLegacyHeartbeatTasks(e.content)); if (!d) await archiveSource({ agentId: s[0][0], source: e, env: t }); } catch (t) { i.push(`${shortenHomePath(e.path)} was not migrated: ${formatErrorMessage(t)}. Rerun doctor to retry safely.`); continue; } let f; try { f = await claimHeartbeatSource(e); } catch (t) { i.push(`${shortenHomePath(e.path)} was not migrated: ${formatErrorMessage(t)}. Rerun doctor to retry safely.`); continue; } let p = true; const m = /* @__PURE__ */ new Map(); const h = []; for (const [r, a] of s) try { const { shouldWriteScratch: i, destination: o } = runOpenClawStateWriteTransaction(({ db: i }) => { const o = resolveCronStoreKeyInDatabase(i, n, t); const s = loadedCronStoreFromRows(loadCronRows(i, o)).store.jobs.find((e) => e.id === a.id); const c = readDefaultProactiveJobReceiptInDatabase(i, o, r); if (!s || c?.phase !== "pending" || c.jobId !== a.id || !isDeepStrictEqual(projectCronJobThroughStorageCodec(s), projectCronJobThroughStorageCodec(a))) throw new Error("automation changed during scratch migration"); const l = readScratchStateFromDatabase(i, o, a.id); if (l.currentRevision !== u.get(a.id)) throw new Error("scratch changed during migration"); if (l.scratch?.sourceSha256 === e.sha256) return { shouldWriteScratch: false, destination: l }; const { result: d } = writeCronJobScratchInDatabase(i, { storeKey: o, jobId: a.id, content: e.content, expectedRevision: l.currentRevision, sourceSha256: e.sha256, nowMs: Date.now() }); if (!d.ok) throw new Error("scratch changed during migration"); return { shouldWriteScratch: true, destination: { currentRevision: d.currentRevision, scratch: d.scratch } }; }, { env: t }, { operationLabel: "doctor.heartbeat-scratch-migration" }); m.set(a.id, o); if (!d || i) h.push(d ? `Copied ${shortenHomePath(e.path)} into cron scratch for ${a.displayName ?? a.name}; retained the shared legacy file because another automation owner's scratch was left unchanged.` : `Migrated ${shortenHomePath(e.path)} into cron scratch for ${a.displayName ?? a.name}.`); } catch (e) { i.push(`Agent "${r}" scratch was not finalized: ${formatErrorMessage(e)}. Rerun doctor to retry safely.`); p = false; } if (!p) { try { await f.restore(void 0); } catch (e) { i.push(formatErrorMessage(e)); } continue; } if (d) { try { await f.retain(); r.push(...h); } catch (t) { i.push(`${shortenHomePath(e.path)} was not migrated: ${formatErrorMessage(t)}. Rerun doctor to retry safely.`); } continue; } try { await f.release({ archivePath: archivePathForSource(s[0][0], e.sha256, t), verifyDestination: () => { if (!withExistingOpenClawStateDatabaseReadOnly(({ db: e }) => { const r = resolveCronStoreKeyInDatabase(e, n, t); const i = loadedCronStoreFromRows(loadCronRows(e, r)).store.jobs; return s.every(([t, n]) => { const a = i.find((e) => e.id === n.id); const o = readDefaultProactiveJobReceiptInDatabase(e, r, t); return o?.phase === "pending" && o.jobId === n.id && a && isDeepStrictEqual(projectCronJobThroughStorageCodec(a), projectCronJobThroughStorageCodec(n)) && isDeepStrictEqual(readScratchStateFromDatabase(e, r, n.id), m.get(n.id)); }); }, { env: t })) throw new Error("automation or scratch changed before source retirement; the migration claim was retained"); } }); r.push(...h); } catch (t) { if (t instanceof Error && t.name === HEARTBEAT_CLAIM_CHANGED_ERROR) { i.push(`${shortenHomePath(e.path)} was not migrated: ${formatErrorMessage(t)}. Rerun doctor to retry safely.`); continue; } r.push(...h); i.push(`${shortenHomePath(e.path)} was migrated but not removed: ${formatErrorMessage(t)}. Rerun doctor to retry safely.`); } } noteDoctorMigrationResult({ changes: r, warnings: i, notices: a }); return { changes: r, warnings: i, ...a.length ? { notices: a } : {} }; } //#endregion export { maybeMigrateHeartbeatFilesToScratch as n, collectHeartbeatScratchMigrationFindings as t };