UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

346 lines (345 loc) • 16.4 kB
import "./boundary-path-C2gXEiXe.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs"; import { a as tableExists } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs"; import { Fn as object, Jn as string, Nt as array, xn as literal } from "./schemas-Cy6abvsu.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import "./crypto-digest-B2m8wIBj.mjs"; import { m as withExistingOpenClawStateDatabaseReadOnly } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { l as runOpenClawStateWriteTransaction } from "./openclaw-state-db-ARhwdPJg.mjs"; import { a as recordLegacyMigrationReceipt, c as resolveLegacyMigrationSourceKey, i as readLegacyMigrationReceiptFromDatabase, o as recordLegacyMigrationRun } from "./state-migrations.receipts-CXYpigJ-.mjs"; import { o as resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target-C8iD4yIo.mjs"; import { s as recordStartupMigrationWarnings } from "./state-migrations.messages-CNB52OxC.mjs"; import { d as shouldFilterLegacySessionRecordsByTarget, l as readLegacySessionStoreEntries, s as isLegacySessionRecordOwnedByTarget, u as resolveLegacyTranscriptPaths } from "./session-sqlite-transcript-verification-Bdys-Rbk.mjs"; import { E as statMigrationPath, T as sameMigrationArtifact, d as listSessionSqliteMigrationManifestPaths, g as resolveSessionSqliteMigrationRunsDir, p as readSessionSqliteMigrationManifest, s as filterRestoreManifestTargets, w as readMigrationArtifactIdentity, x as MigrationArtifactSchema } from "./session-sqlite-migration-manifest-DwBodX3i.mjs"; import { i as sameSourceContent, n as databaseIdentity } from "./deferred-plugin-session-verification-DM8JAFN6.mjs"; import path from "node:path"; import { isDeepStrictEqual } from "node:util"; //#region src/infra/deferred-plugin-session-artifacts.ts /** Doctor verification and cleanup consume the same manifest source custody. */ function collectArchivedSources(e, t, n = false) { const r = /* @__PURE__ */ new Map(); for (const i of listSessionSqliteMigrationManifestPaths(t)) { const t = readSessionSqliteMigrationManifest(i); const a = t ? filterRestoreManifestTargets(t, [e]) : []; for (const e of a) for (const t of e.plannedMoves) if (t.artifact && (!n || t.artifact.disposal.state !== "disposed")) { const e = r.get(t.sourcePath) ?? []; e.push({ path: t.archivePath, identity: t.artifact.identity, dependencies: t.artifact.dependencies }); r.set(t.sourcePath, e); } } return r; } function existingSessionSourcePaths(e, t) { return statMigrationPath(e) ? [e] : (t.get(e) ?? []).map((e) => e.path).filter((e) => statMigrationPath(e)); } //#endregion //#region src/infra/deferred-plugin-session-import-schema.ts const DeferredPluginSessionImportSchema = object({ databaseIdentity: string(), superseded: literal("different-database").optional(), pluginIds: array(string()), sources: array(object({ path: string(), identity: MigrationArtifactSchema.shape.identity })), settledSources: array(object({ path: string(), identity: MigrationArtifactSchema.shape.identity, reason: string() })).optional() }); //#endregion //#region src/infra/deferred-plugin-session-source-read.ts const DEFERRED_PLUGIN_SESSION_IMPORT_RECEIPT_KIND = "deferred-plugin-session-import"; function resolveDeferredPluginSessionSourceKey(e) { return resolveLegacyMigrationSourceKey(DEFERRED_PLUGIN_SESSION_IMPORT_RECEIPT_KIND, e.storePath, `${e.agentId}\0${path.resolve(e.sqlitePath)}`); } function readDeferredPluginSessionImportReceipt(e) { const t = readDeferredPluginSessionImportBindingReceipt(e); return t?.removedSource ? void 0 : t; } /** Archive retirement ends active source custody, not the canonical import's no-replay evidence. */ function readDeferredPluginSessionImportBindingReceipt(e) { const t = { ...e.target, sqlitePath: e.sqlitePath }; const read = (e) => tableExists(e, "migration_sources") ? readLegacyMigrationReceiptFromDatabase(e, resolveDeferredPluginSessionSourceKey(t)) : void 0; return e.database ? read(e.database) : withExistingOpenClawStateDatabaseReadOnly(({ db: e }) => read(e), { env: e.env }); } //#endregion //#region src/infra/state-migrations.deferred-session-import.ts function parseSessionImportReceipt(e, t) { const n = DeferredPluginSessionImportSchema.parse(JSON.parse(t.reportJson)); const r = databaseIdentity(e.sqlitePath); const i = databaseIdentity(e.sqlitePath, "physical"); return { recorded: n, currentDatabaseIdentity: r, physicalIdentity: i, stale: Boolean(n.superseded) || n.databaseIdentity !== r && n.databaseIdentity !== i }; } /** Preserve the foreign receipt before releasing its claim on the live database. */ function supersedeDeferredPluginSessionImport(e) { const { receipt: t } = e; runOpenClawStateWriteTransaction(({ db: n }) => { if (!isDeepStrictEqual(readLegacyMigrationReceiptFromDatabase(n, t.sourceKey), t) || databaseIdentity(e.sqlitePath) !== e.databaseIdentity || databaseIdentity(e.sqlitePath, "physical") !== e.physicalIdentity) throw new Error("Deferred session receipt or database changed before supersession; originals retained."); const r = Date.now(); const i = JSON.parse(t.reportJson); recordLegacyMigrationRun(n, { runId: `${t.sourceKey}:superseded:${sha256Hex(t.reportJson + "\0" + e.databaseIdentity)}`, startedAt: r, finishedAt: r, status: "superseded", upsert: true, reportJson: JSON.stringify({ receipt: i, databaseIdentity: e.databaseIdentity, reason: "Receipt bound to a different database; it cannot certify the live database's history." }) }); executeSqliteQuerySync(n, getNodeSqliteKysely(n).updateTable("migration_sources").set({ status: "superseded", report_json: JSON.stringify({ ...i, superseded: "different-database" }) }).where("source_key", "=", t.sourceKey)); }, { env: e.env }, { operationLabel: "state.supersede-plugin-session-source" }); } //#endregion //#region src/infra/deferred-plugin-session-sources.ts function deferredPluginSessionStoreIds(e) { if (e.target.storePath.endsWith(".sqlite")) return []; return e.pending.map((e) => e.pluginId); } /** File-era repair must not rewrite an original that a deferred owner still needs. */ function preserveDeferredPluginSessionSource(e) { if (deferredPluginSessionStoreIds(e).length > 0) return true; const t = resolveSqliteTargetFromSessionStorePath(e.target.storePath, { agentId: e.target.agentId, env: e.env }); return hasDeferredPluginSessionImport({ target: { ...e.target, sqlitePath: e.target.sqlitePath ?? t.path }, sqlitePath: e.target.sqlitePath ?? t.path, env: e.env }); } /** Receipt verification and retained counting share one synchronous phase; publication revalidates. */ function prepareSessionSourceVerification(e) { const t = /* @__PURE__ */ new Map(); return { cfg: e.cfg, target: e.target, resolvedTarget: { agentId: e.target.agentId, storePath: e.target.storePath, sqlitePath: e.sqlitePath }, sqlitePath: e.sqlitePath, env: e.env, verification: t }; } function sessionSourceVerificationTarget(e, t, n) { const r = JSON.stringify([resolveDeferredPluginSessionSourceKey(e), resolveSessionSqliteMigrationRunsDir(t)]); let i = n.get(r); if (!i) { i = { resolved: /* @__PURE__ */ new Map() }; n.set(r, i); } return i; } /** Archive mappings survive recovery awaits; file identities must still be checked fresh. */ function sessionSourceArchives(e, t, n) { const r = sessionSourceVerificationTarget(e, t, n); return r.archives ??= collectArchivedSources(e, t); } function resolveVerifiedSessionSource(e, t, n, r, i) { const a = sessionSourceVerificationTarget(t, n, r); const o = a.resolved.get(e.path) ?? []; const s = o.find(({ identity: t }) => sameMigrationArtifact(t, e.identity)); if (s) return s.path; const c = statMigrationPath(e.path) ? sameSourceContent(readMigrationArtifactIdentity(e.path), e.identity) ? e.path : void 0 : (i ?? sessionSourceArchives(t, n, r)).get(e.path)?.find(({ identity: t, path: n }) => sameSourceContent(t, e.identity) && statMigrationPath(n) && sameSourceContent(readMigrationArtifactIdentity(n), e.identity))?.path; o.push({ identity: { ...e.identity }, path: c }); a.resolved.set(e.path, o); return c; } function assertVerifiedSessionSources(e, t, n = /* @__PURE__ */ new Map(), r) { const i = { ...e.target, sqlitePath: e.sqlitePath }; const a = /* @__PURE__ */ new Map(); for (const o of t.sources) { let t; try { t = resolveVerifiedSessionSource(o, i, e.env, n); } catch (e) { if (!r) throw e; } if (!t) { if (r) { r(o.path); for (const t of existingSessionSourcePaths(o.path, sessionSourceArchives(i, e.env, n))) if (t !== o.path) r(o.path, t); continue; } throw new Error(`Retained session migration source changed: ${o.path}. Preserve the current file and its ${o.path}.bak-<pid>-<timestamp> siblings, restore the verified original at ${o.path}, then run openclaw doctor --session-sqlite recover --session-sqlite-all-agents against the same state directory. Canonical SQLite sessions were not replayed.`); } a.set(o.path, t); } const o = t.sources.find((t) => t.path === path.resolve(e.target.storePath)); const s = o && a.get(o.path); if (!o && statMigrationPath(e.target.storePath) && r) r(path.resolve(e.target.storePath)); if (r && (!o || !s) || !o && !statMigrationPath(e.target.storePath)) return; if (!o || !s) throw new Error(`Session source changed in ${path.dirname(e.target.storePath)}: the current index has no verified import receipt. Run ${formatCliCommand("openclaw doctor --fix --non-interactive --yes", e.env)} against the same state/config to preserve and reverify it.`); const c = []; const l = readLegacySessionStoreEntries(e.target, c, { sourcePath: s }); if (c.some((e) => e.code !== "entry_invalid") || !l.bytes || l.bytes.length !== o.identity.size || sha256Hex(l.bytes) !== o.identity.sha256) throw new Error(`Retained session migration source changed in ${path.dirname(e.target.storePath)}: ${e.target.storePath}. Run ${formatCliCommand("openclaw doctor --fix --non-interactive --yes", e.env)} against the same state/config to preserve and reverify it.`); for (const { entry: n, sessionKey: i } of l.entries) { if (shouldFilterLegacySessionRecordsByTarget(e.target) && !isLegacySessionRecordOwnedByTarget(e.cfg, e.target, i)) continue; const { transcriptCandidates: o } = resolveLegacyTranscriptPaths(e.target, n); if (o.some((e) => a.has(path.resolve(e)) || r && t.sources.some((t) => t.path === path.resolve(e)))) continue; for (const e of o) if (statMigrationPath(e)) { if (r) { r(e); continue; } throw new Error(`Retained session migration source changed: ${e}. A previously unimported transcript appeared; run openclaw doctor --fix to preserve it in the migration archive.`); } } } /** A completed core import remains authoritative after canonical sessions change or are deleted. */ function readDeferredPluginSessionImport(e) { const t = readDeferredPluginSessionImportReceipt(e); if (!t) return; const n = parseSessionImportReceipt(e, t); if (n.stale) { recordStartupMigrationWarnings(["Retained session import receipt belongs to a different database; sources remain protected. Run openclaw doctor --fix to recover retained history against the live database."]); return; } let r = { ...n.recorded, databaseIdentity: n.currentDatabaseIdentity }; if (e.purpose) return r; const i = e.verification ?? /* @__PURE__ */ new Map(); if (e.allowMissingIndex && !statMigrationPath(e.target.storePath)) r = { ...r, sources: r.sources.filter((t) => t.path !== path.resolve(e.target.storePath) || resolveVerifiedSessionSource(t, { ...e.target, sqlitePath: e.sqlitePath }, e.env, i) || existingSessionSourcePaths(t.path, sessionSourceArchives({ ...e.target, sqlitePath: e.sqlitePath }, e.env, i)).length > 0) }; assertVerifiedSessionSources(e, r, i, e.onSourceConflict); return r; } function hasDeferredPluginSessionImport(e) { return Boolean(readDeferredPluginSessionImportReceipt(e)); } function readStaleDeferredPluginSessionImport(e) { const t = readDeferredPluginSessionImportReceipt(e); const n = t && parseSessionImportReceipt(e, t); return n?.stale ? n.recorded : void 0; } /** Resolve the verified live or archived legacy index whose canonical import is still bound. */ function resolveDeferredPluginSessionStoreSource(e) { const { path: t } = resolveSqliteTargetFromSessionStorePath(e.target.storePath, { agentId: e.target.agentId, env: e.env }); const n = readDeferredPluginSessionImportBindingReceipt({ ...e, sqlitePath: t }); const r = n && parseSessionImportReceipt({ sqlitePath: t }, n); const i = r && !r.stale ? r.recorded.sources.find((t) => t.path === path.resolve(e.target.storePath)) : void 0; return i ? resolveVerifiedSessionSource(i, { ...e.target, sqlitePath: t }, e.env, /* @__PURE__ */ new Map()) : void 0; } /** Reuse verified source bytes only within one uninterrupted synchronous migration loop. */ function prepareDeferredPluginSessionImportReader(e) { const t = /* @__PURE__ */ new Map(); return (n, r) => { const i = { ...e.target, agentId: r }; const a = resolveSqliteTargetFromSessionStorePath(i.storePath, { agentId: r, env: e.env }); const o = { ...i, sqlitePath: a.path }; const s = resolveDeferredPluginSessionSourceKey(o); const c = readLegacyMigrationReceiptFromDatabase(n, s); let l = t.get(s); if (!l || !isDeepStrictEqual(l.receipt, c)) { l = { receipt: c, binding: c ? parseSessionImportReceipt(o, c) : void 0 }; t.set(s, l); } const u = l.binding; if (!u) return { kind: "absent" }; if (u.currentDatabaseIdentity !== databaseIdentity(o.sqlitePath)) throw new Error(`The verified session import database changed for ${path.dirname(o.storePath)}; retained source was not replayed. Run ${formatCliCommand("openclaw doctor --session-sqlite recover --session-sqlite-all-agents", e.env)} against the same state/config.`); return u.stale ? { kind: "stale" } : { kind: "canonical", target: o }; }; } /** Called after full core import validation, before any original can be retired. */ function recordDeferredPluginSessionImport(e) { const t = { databaseIdentity: databaseIdentity(e.sqlitePath), pluginIds: e.pluginIds, sources: e.sources }; const n = e.sources.find((t) => t.path === path.resolve(e.target.storePath)); runOpenClawStateWriteTransaction(({ db: r }) => { assertVerifiedSessionSources(e, t); if (t.databaseIdentity !== databaseIdentity(e.sqlitePath)) throw new Error(`Session import database changed for ${path.dirname(e.target.storePath)} before its receipt was recorded. Run ${formatCliCommand("openclaw doctor --fix --non-interactive --yes", e.env)} against the same state/config to retry.`); const i = resolveDeferredPluginSessionSourceKey({ ...e.target, sqlitePath: e.sqlitePath }); const a = readLegacyMigrationReceiptFromDatabase(r, i); recordLegacyMigrationReceipt(r, { sourceKey: i, migrationKind: DEFERRED_PLUGIN_SESSION_IMPORT_RECEIPT_KIND, sourcePath: path.resolve(e.target.storePath), targetTable: "session_nodes", sourceSha256: n?.identity.sha256 ?? null, sourceSizeBytes: n?.identity.size ?? null, sourceRecordCount: e.recordCount, runId: i, reportJson: JSON.stringify(t), now: Date.now(), upsert: Boolean(a && (a.removedSource || parseSessionImportReceipt(e, a).recorded.superseded)) }); }, { env: e.env }, { operationLabel: "state.retain-plugin-session-source" }); } //#endregion export { preserveDeferredPluginSessionSource as a, recordDeferredPluginSessionImport as c, sessionSourceArchives as d, parseSessionImportReceipt as f, existingSessionSourcePaths as g, DeferredPluginSessionImportSchema as h, prepareSessionSourceVerification as i, resolveDeferredPluginSessionStoreSource as l, readDeferredPluginSessionImportReceipt as m, hasDeferredPluginSessionImport as n, readDeferredPluginSessionImport as o, supersedeDeferredPluginSessionImport as p, prepareDeferredPluginSessionImportReader as r, readStaleDeferredPluginSessionImport as s, deferredPluginSessionStoreIds as t, resolveVerifiedSessionSource as u };