UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

304 lines (303 loc) • 14 kB
import { a as resolveRequiredHomeDir } from "./home-dir-EKmgmdPG.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { a as isSameOpenClawAgentDatabasePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs"; import { a as resolveUnsuffixedSqliteTargetFromSessionStorePath } from "./session-sqlite-target-paths-Dw0pT36E.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs"; import { m as readDatabasePathIdentitySync } from "./sqlite-worker-identity-BH8ZkJU9.mjs"; import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import { n as hasOrphanedSqliteSidecars } from "./sqlite-files-rWisKj_V.mjs"; import { a as resolveUpdateRehearsalRoot, r as isUpdateRehearsalReadOnlyPath } from "./update-rehearsal-paths-Dr1MbUA_.mjs"; import { t as readConfigMachineState } from "./config-machine-state-DzLVE1Wy.mjs"; import { n as resolveSessionStoreCompatibilityAgentId } from "./legacy.default-agent-owner-DpmHgK0A.mjs"; import { a as writeConfigMachineState } from "./config-machine-state-write-DanSUxEP.mjs"; import { t as DoctorMaintenanceRefusalError } from "./update-doctor-result-DwaI51On.mjs"; import { c as listOpenClawRegisteredAgentDatabases } from "./openclaw-agent-db-registry-listing-CbXBL50a.mjs"; import { n as withOpenClawAgentDatabaseReadOnly } from "./openclaw-agent-db-readonly-COYfV-vn.mjs"; import { n as unregisterOpenClawAgentDatabase } from "./openclaw-agent-db-registry-DobcJNwx.mjs"; import { o as resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target-C8iD4yIo.mjs"; import { t as getSessionKysely } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs"; import "./session-accessor.sqlite-scope-Cbj2BdoG.mjs"; import "./targets-BVE0__Jb.mjs"; import { n as readSessionDeliveryRepairInventory, r as resolveSqliteCanonicalRepairLookupKeys } from "./session-accessor.sqlite-delivery-repair-BUR-ulKj.mjs"; import { a as readSessionTranscriptArchiveResetInventory } from "./session-accessor.sqlite-archive-store-kernel-CuGqi3Eu.mjs"; import { n as resolveRelativeSessionStoreMigrationTargets } from "./doctor-relative-session-store-paths-JTOj2pad.mjs"; import { n as listSessionMembersInDatabase } from "./session-sharing-store.kernel-BH4li9nE.mjs"; import { i as claimFullyCopied, n as copySessionClaimForRepair, o as claimsMatch, s as readClaim, t as restoreColdSessionClaims } from "./legacy-main-session-migration-restore-CCA3KI6P.mjs"; import { n as backupDoctorSqliteDatabases } from "./doctor-migration-backup-DwSvhlqi.mjs"; import fs from "node:fs"; import path from "node:path"; //#region src/commands/doctor-relative-session-store-preservation.ts /** A retired store must have no independent owner still settling work against it. */ function readRelativeStorePreservationState(e, t, n) { const r = getNodeSqliteKysely(e.db); if (executeSqliteQueryTakeFirstSync(e.db, r.selectFrom("context_engine_turn_outbox").select("advancement_key").limit(1))) n("pending context-engine advancements need to drain through their original Gateway before recovery"); const i = executeSqliteQueryTakeFirstSync(e.db, r.selectFrom("session_goal_operations").select("expires_at").where("expires_at", ">", Date.now()).orderBy("expires_at", "desc").limit(1)); if (i) n(`goal-operation receipts prevent delayed goal recreation until ${new Date(i.expires_at).toISOString()}; retain the old store until that time before retrying`); if (readSessionTranscriptArchiveResetInventory(e).length > 0) n("retained transcript archives require explicit recovery from the original store; automatic archive relocation is unsupported"); const a = readSessionDeliveryRepairInventory(e); if (a.deliveries.some((e) => [ "created", "queued", "unknown" ].includes(e.status))) n("pending conversation deliveries must settle through their original Gateway and queue before recovery"); const o = new Set(t.flatMap((e) => resolveSqliteCanonicalRepairLookupKeys(e, [e]))); if (a.deliveries.some((e) => e.source_session_key === null || !o.has(e.source_session_key))) n("delivery receipts without a retained session require explicit recovery from the original store"); const s = new Set(a.deliveries.map((e) => e.operation_id)); if (a.progress.some((e) => !s.has(e.key))) n("conversation progress without its delivery receipt requires explicit recovery from the original store"); return a; } //#endregion //#region src/commands/doctor-relative-session-store.ts function refuse(e) { throw new DoctorMaintenanceRefusalError(`Cannot merge the old relative session.store: ${e}. Original stores and existing backups are retained. Resolve the reported conflict before retrying Doctor or the update.`, { kind: "data-at-risk", reason: "incomplete-migration" }); } function discoverStoreMoves(e, t, n) { const r = e.session?.store; if (!r || r.startsWith("~") || path.isAbsolute(r)) return []; const i = [...new Map([...n, ...listOpenClawRegisteredAgentDatabases({ env: t, includeIncompatibleSchemaVersions: true })].map((e) => [`${e.agentId}\n${e.path}`, e])).values()]; const a = resolveRelativeSessionStoreMigrationTargets(e, t, i); const o = resolveSessionStoreCompatibilityAgentId(e); const s = resolveUpdateRehearsalRoot(t); const c = /* @__PURE__ */ new Map(); for (const n of listAgentIds(e)) { const e = r.replaceAll("{agentId}", n); const l = resolveSessionStorePathCore(r, { agentId: n, env: t }); const u = resolveUnsuffixedSqliteTargetFromSessionStorePath(l).path; if (isUpdateRehearsalReadOnlyPath(u, t)) refuse(`the new destination ${u} is outside the copied update state; run openclaw doctor --fix against the original state directory outside the update rehearsal first`); const d = resolveSqliteTargetFromSessionStorePath(l, { agentId: n, defaultAgentId: o, env: t, registeredDatabases: i }); const f = []; if (!s) for (const r of /* @__PURE__ */ new Set([process.cwd(), resolveRequiredHomeDir(t)])) f.push({ storePath: path.resolve(r, e), owner: n }); f.push(...a.filter((e) => e.configuredAgentId === n).map((e) => ({ storePath: e.storePath, path: e.path, owner: e.agentId }))); for (const e of f) { if (e.storePath === l || e.path === d.path) continue; const r = resolveUnsuffixedSqliteTargetFromSessionStorePath(e.storePath); if (isUpdateRehearsalReadOnlyPath(e.path ?? r.path, t)) refuse(`the recorded source ${e.path ?? r.path} was not copied for rehearsal; run openclaw doctor --fix against the original state directory outside the update rehearsal first`); const a = e.path ? { path: e.path, agentId: e.owner } : resolveSqliteTargetFromSessionStorePath(e.storePath, { agentId: n, defaultAgentId: o, env: t, registeredDatabases: i }); const s = fs.existsSync(a.path); if (!s && hasOrphanedSqliteSidecars(a.path)) refuse(`SQLite sidecars at ${a.path} need their matching main database restored`); if (!s && !fs.existsSync(e.storePath)) continue; if (isSameOpenClawAgentDatabasePath(a.path, d.path)) continue; const u = s ? readDatabasePathIdentitySync(a.path) : void 0; const f = a.agentId ?? e.owner; const p = `${u?.key ?? a.path}\n${d.path}`; if (!c.has(p)) c.set(p, { source: { path: u?.canonicalPath ?? a.path, ownerStorePath: a.path, databaseAgentId: f }, destination: { path: d.path, ownerStorePath: d.path, databaseAgentId: d.agentId ?? f }, aliases: i.filter((e) => e.agentId === f && !isUpdateRehearsalReadOnlyPath(e.path, t) && isSameOpenClawAgentDatabasePath(e.path, a.path)).map((e) => e.path), legacyStorePath: e.storePath }); } } return [...c.values()]; } function readStoreSnapshot(e, t, n = false) { const r = withOpenClawAgentDatabaseReadOnly((t) => { const r = executeSqliteQuerySync(t.db, getSessionKysely(t.db).selectFrom("session_nodes").select("session_key").orderBy("session_key")).rows.map(({ session_key: n }) => { const r = readClaim(t, e, n, n); if (!r) refuse(`source session ${n} could not be read from ${e.path}`); return r; }); return { claims: r, memberIds: new Map(r.map((e) => [e.key, listSessionMembersInDatabase(t, e.key).map((e) => e.identityId)])), deliveryInventory: n ? readRelativeStorePreservationState(t, r.map((e) => e.key), (t) => refuse(`${e.path}: ${t}`)) : void 0 }; }, { agentId: e.databaseAgentId, path: e.path, env: t }); return r.found ? r.value : { claims: [], memberIds: /* @__PURE__ */ new Map(), deliveryInventory: void 0 }; } function sourceFingerprint(e, t) { return sha256Hex(JSON.stringify([ readDatabasePathIdentitySync(e.path), t.claims.map((e) => [ e.key, e.entry, e.nodeArtifactFingerprint, e.generations.map((e) => e.fingerprint) ]), t.deliveryInventory ])); } /** Offline repair retires the old selector only after backed-up, verified same-owner copies. */ async function repairRelativeSessionStores(e) { const t = []; const n = []; let r; try { r = discoverStoreMoves(e.cfg, e.env, e.registeredDatabases ?? []); } catch (e) { if (e instanceof DoctorMaintenanceRefusalError) throw e; refuse(`store discovery failed: ${formatErrorMessage(e)}`); } if (r.length === 0) return { changes: t, warnings: n }; const i = getOpenClawDatabaseMaintenanceScope(); if (!i?.ownsSchemaMaintenance) refuse("repair requires Doctor maintenance ownership"); const a = { assertCurrent: () => i.assertAdmission() }; for (const { source: i, destination: o, aliases: s, legacyStorePath: c } of r) try { a.assertCurrent(); const r = `sessions.relative-store.v1.${sha256Hex(JSON.stringify([i.path, o.path]))}`; const l = readConfigMachineState(r, { env: e.env }); let u; let d; if (l === void 0) { const l = [ i.path, o.path, resolveOpenClawStateSqlitePath(e.env) ].filter((e) => fs.existsSync(e)); const f = await backupDoctorSqliteDatabases({ env: e.env, pendingDatabasePaths: l, databasePaths: l, authority: a, requireSnapshots: true }); t.push(...f.changes); n.push(...f.warnings); if (!c.endsWith(".sqlite") && fs.existsSync(c)) { const { runDoctorSessionSqlite: t } = await import("./doctor-session-sqlite-BeIvR4an.mjs"); const { countBlockingSessionSqliteIssues: n } = await import("./doctor-session-sqlite-types-BG4Mar_q.mjs"); if ((await t({ cfg: e.cfg, env: e.env, mode: "import", agent: i.databaseAgentId, store: c }, a)).targets.some((e) => n(e) > 0)) refuse(`legacy JSON at ${c} has unresolved Doctor import issues`); } if (!fs.existsSync(i.path)) { a.assertCurrent(); for (const t of /* @__PURE__ */ new Set([i.path, ...s])) unregisterOpenClawAgentDatabase({ agentId: i.databaseAgentId, path: t, env: e.env }); continue; } const p = readStoreSnapshot(i, e.env, true); u = p.claims; await restoreColdSessionClaims(u, e.env, a.assertCurrent); d = sourceFingerprint(i, { ...p, claims: u }); const m = readStoreSnapshot(o, e.env); const h = new Map(m.claims.map((e) => [e.key, e])); const prepareCanonical = async (t) => { const n = h.get(t); if (!n) return; const r = [n]; await restoreColdSessionClaims(r, e.env, a.assertCurrent); h.set(t, r[0]); return r[0]; }; for (const t of u) { a.assertCurrent(); let n = t.key; let r = await prepareCanonical(n); const s = p.memberIds.get(t.key); const sameMembers = (e) => JSON.stringify(s) === JSON.stringify(m.memberIds.get(e) ?? []); if (r && (!claimsMatch(t, r) || !sameMembers(n))) { n = `agent:${parseAgentSessionKey(t.key)?.agentId ?? i.databaseAgentId}:relative-store-recovery-${sha256Hex(`${i.path}\n${t.key}`).slice(0, 24)}`; r = await prepareCanonical(n); if (r && !sameMembers(n)) refuse(`recovered session ${n} already has different sharing permissions`); } const c = { ...t, canonicalKey: n }; const l = await copySessionClaimForRepair({ source: c, destination: o, canonicalKey: n, ...r ? { expectedDestination: r } : {}, mode: "store-relocation", env: e.env, beforePersistentApply: a.assertCurrent }); if (!l || !claimFullyCopied(c, l)) refuse(`conflicting session generations or sharing in ${i.path} and ${o.path}; preserve the originals and their pre-migration backups for recovery`); h.set(n, l); m.memberIds.set(n, s); } a.assertCurrent(); const g = readStoreSnapshot(i, e.env, true); u = g.claims; if (sourceFingerprint(i, g) !== d) refuse(`source ${i.path} changed during the copy`); writeConfigMachineState(r, d, { env: e.env }); t.push(`Merged ${u.length} session(s) from ${i.path} into ${o.path}; retained the original store and its pre-migration backup for recovery.`); } else { const t = readStoreSnapshot(i, e.env, true); u = t.claims; d = sourceFingerprint(i, t); if (l !== d || !c.endsWith(".sqlite") && fs.existsSync(c)) refuse(`the retired source ${i.path} changed; preserve it for explicit recovery without replaying deleted conversations`); } a.assertCurrent(); for (const t of /* @__PURE__ */ new Set([i.path, ...s])) unregisterOpenClawAgentDatabase({ agentId: i.databaseAgentId, path: t, env: e.env }); } catch (e) { if (e instanceof DoctorMaintenanceRefusalError) throw e; refuse(`${i.path}: ${formatErrorMessage(e)}`); } return { changes: t, warnings: n }; } //#endregion export { repairRelativeSessionStores };