UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

241 lines (240 loc) • 10.1 kB
import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs"; import { i as assertExistingDatabaseIdentity, m as readDatabasePathIdentitySync } from "./sqlite-worker-identity-BH8ZkJU9.mjs"; import { c as SqliteSchemaMismatchError } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs"; import { n as StartupMaintenanceRequiredError } from "./startup-maintenance-required-DEn4Krys.mjs"; import { r as isSqliteSnapshotCapacityError } from "./sqlite-snapshot-capacity-error-DlgtEr8c.mjs"; import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs"; import { n as OpenClawAgentDatabaseMediaMigrationRequiredError } from "./session-metadata-unavailable-error-ClU33Nog.mjs"; import { t as AgentDatabaseMaintenanceRequiredError } from "./openclaw-agent-db-maintenance-authority-C4Yhyki9.mjs"; import { a as closeOpenClawAgentDatabaseByPath } from "./openclaw-agent-db-lifecycle-DqaZZnYh.mjs"; import { o as SESSION_ENTRY_NUMERIC_FIELDS } from "./session-entry-json-BctywCJg.mjs"; import { d as hasLegacySessionEntryState, f as hasLegacySessionProviderState, s as stripRuntimeOnlySessionSkillsFields } from "./store-entry-shape-BGb6O41s.mjs"; import { r as isOpenClawAgentDatabaseOpen } from "./openclaw-agent-db-CwXW4hGa.mjs"; import { i as resolveAllAgentSessionStoreCandidateTargetsSync } from "./targets-BVE0__Jb.mjs"; import { b as scanDoctorSessionEntriesTolerant } from "./session-accessor-CizTbDQj.mjs"; import { n as createLegacyStateMigrationStepReceipt, t as DoctorStateMigrationRefusalError } from "./state-migrations.messages-CNB52OxC.mjs"; import { n as migrateLegacySessionEntryState, t as inspectLegacyRestartTombstone } from "./session-entry-shape-CqYv-iaf.mjs"; import { i as scanDoctorSessionEntryRecords, r as rewriteDoctorSessionEntries } from "./session-entry-rewrite-ql1B0nFY.mjs"; import { i as projectExistingAgentDatabaseTargets } from "./session-sqlite-migration-readers-DbmEQzSW.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import { n as normalizeLegacySessionEntryDelivery } from "./state-migrations.legacy-session-store-D6luaLu_.mjs"; import { n as backupDoctorSqliteDatabases } from "./doctor-migration-backup-DwSvhlqi.mjs"; import { t as runDoctorAgentDatabaseOperation } from "./doctor-agent-database-operation-BYsIdRWr.mjs"; //#region src/commands/doctor-session-delivery-state.ts /** Scan or rewrite legacy delivery fields inside existing session row JSON. */ function repairCanonicalSessionDeliveryStates(e) { return repairCanonicalSessionEntries({ ...e, transform: normalizeLegacySessionEntryDelivery, updateDeliveryProjection: true }); } function repairCanonicalSessionResolvedSkills(e) { return repairCanonicalSessionEntries({ ...e, transform: stripRuntimeOnlySessionSkillsFields, updateDeliveryProjection: false }); } function prepareSessionEntryRepairs(e) { const t = (e.targets ?? projectExistingAgentDatabaseTargets(resolveAllAgentSessionStoreCandidateTargetsSync(e.cfg, { env: e.env, ...e.registeredDatabases ? { registeredDatabases: e.registeredDatabases } : {} }), e.env, e.cfg)).filter((t) => !e.excludedDatabasePaths?.has(t.sqlitePath)); const n = []; const r = []; const i = t.flatMap((t) => { const i = []; const a = { agentId: t.agentId, env: e.env, storePath: t.sqlitePath }; const scan = () => { const n = readDatabasePathIdentitySync(t.sqlitePath); if (e.source === "raw") scanDoctorSessionEntryRecords(a, ({ entry: t, sessionKey: n }) => { if (e.rawNeedsRepair(t, n)) i.push(n); }, n); else scanDoctorSessionEntriesTolerant(a, ({ entry: t, recoveredFromProjections: n, sessionKey: r }) => { if (!n && e.transform(t, r, "scan") !== t) i.push(r); }); assertExistingDatabaseIdentity(t.sqlitePath, n.key, n.birthtime); return { target: t, scope: a, sessionKeys: i, identity: n }; }; try { const r = e.source === "raw" ? { ok: true, value: scan() } : runDoctorAgentDatabaseOperation({ agentId: t.agentId, path: t.sqlitePath, run: scan }); if (!r.ok) return []; n.push({ ...t, canonicalPath: r.value.identity.canonicalPath }); return i.length > 0 ? [r.value] : []; } catch (n) { if (e.source === "raw" && (e.deferToMediaPreparation || e.deferSchemaRepair && (n instanceof SqliteSchemaMismatchError || n instanceof StartupMaintenanceRequiredError && n.kind === "state-migrations" || n instanceof AgentDatabaseMaintenanceRequiredError || n instanceof OpenClawAgentDatabaseMediaMigrationRequiredError))) { const t = e.deferToMediaPreparation ? "media database preparation" : "database schema repair"; note(`- Session entry inspection awaits ${t}: ${formatErrorMessage(n)}`, "Session SQLite"); return []; } if (e.source === "raw" && isTruthyEnvValue(process.env.OPENCLAW_UPDATE_IN_PROGRESS) && isSqliteSnapshotCapacityError(n)) { const e = `Session entry state inspection deferred for agent ${t.agentId}: ${formatErrorMessage(n)}. Free temporary snapshot space, then run ${formatCliCommand("openclaw doctor --fix")} after the update.`; note(e, "Doctor warning"); r.push(e); return []; } throw n; } }); return { targets: t, inspectedTargets: n, pending: i, deferredWarnings: r, found: i.reduce((e, t) => e + t.sessionKeys.length, 0), scannedStores: t.length, apply(t) { let n = 0; for (const { target: r, scope: a, sessionKeys: o, identity: s } of i) { const i = isOpenClawAgentDatabaseOpen(r.sqlitePath); try { n += rewriteDoctorSessionEntries({ scope: a, sessionKeys: o, integrityCheck: e.integrityCheck ?? "quick", ...e.source === "raw" ? { rawTransform: e.rawTransform } : { transform: (t, n) => e.transform(t, n, "repair") }, expectedIdentity: s, updateDeliveryProjection: e.updateDeliveryProjection, ...t ? { assertCurrent: () => t(r) } : {} }); } finally { if (!i) closeOpenClawAgentDatabaseByPath(r.sqlitePath); } } return n; } }; } function repairCanonicalSessionEntries(e) { const t = prepareSessionEntryRepairs({ ...e, source: "canonical" }); return { found: t.found, repaired: e.apply ? t.apply() : 0, scannedStores: t.scannedStores }; } function needsLegacySessionEntryRepair(e) { return hasLegacySessionEntryState(e) || inspectLegacyRestartTombstone(e)?.retire || SESSION_ENTRY_NUMERIC_FIELDS.some((t) => typeof e[t] === "string"); } /** Raw repair and its backup precede all canonical session readers. */ async function repairLegacySessionEntryStates(e) { try { const t = /* @__PURE__ */ new Set(); const n = /* @__PURE__ */ new Map(); const reportRetained = () => { for (const [e, t] of n) note(`${e}: ${t}`, "Session recovery warning"); }; const r = prepareSessionEntryRepairs({ ...e, source: "raw", rawNeedsRepair: (e, t) => { const r = inspectLegacyRestartTombstone(e); if (r && !r.retire) n.set(t, r.warning); return needsLegacySessionEntryRepair(e); }, rawTransform: (e, r, i) => { if (!needsLegacySessionEntryRepair(e)) return { entry: e }; const a = migrateLegacySessionEntryState(e, i); const o = inspectLegacyRestartTombstone(e); n.delete(r); if (o?.retire) t.add(r); else if (o) n.set(r, o.warning); return { ...a, entry: hasLegacySessionProviderState(e) ? normalizeLegacySessionEntryDelivery(a.entry) : a.entry }; }, updateDeliveryProjection: true }); const i = { found: r.found, repaired: 0, scannedStores: r.scannedStores, ...r.deferredWarnings.length > 0 ? { warnings: r.deferredWarnings } : {} }; if (!e.apply || r.found === 0) { reportRetained(); e.onInspectedTargets?.(r.inspectedTargets); return i; } const runWithAuthority = async (n) => { const a = new Map(r.pending.map(({ target: e, identity: t }) => [e, t])); const assertTargetCurrent = (e) => { n.assertCurrent(); const t = a.get(e); assertExistingDatabaseIdentity(e.sqlitePath, t.key, t.birthtime); }; const assertCurrent = () => { for (const e of a.keys()) assertTargetCurrent(e); }; assertCurrent(); const o = await backupDoctorSqliteDatabases({ env: e.env, pendingDatabasePaths: r.pending.map(({ target: e }) => e.sqlitePath), databasePaths: (e.deferToMediaPreparation ? r.inspectedTargets : r.targets).map((e) => e.sqlitePath), authority: { assertCurrent } }); assertCurrent(); note(o.changes.map((e) => `- ${e}`).join("\n"), "Session SQLite backups"); i.repaired = r.apply(assertTargetCurrent); reportRetained(); for (const e of t) note(`Recovered legacy restart tombstone for ${e}; obsolete claims and pending delivery retired (original state backed up).`, "Session recovery warning"); e.onInspectedTargets?.(r.inspectedTargets); note(`- Canonicalized entry state for ${i.repaired} durable session row(s).`, "Session SQLite"); return i; }; const a = getOpenClawDatabaseMaintenanceScope(); const o = e.authority ?? (a?.ownsSchemaMaintenance ? { assertCurrent: () => a.assertAdmission() } : void 0); if (o) return await runWithAuthority(o); const { withDoctorSqliteMaintenanceLock: s } = await import("./doctor-sqlite-maintenance-lock-DD8x7Dc0.mjs"); return await s({ env: e.env, operation: "session entry state repair", run: runWithAuthority }); } catch (e) { const t = [{ kind: "owner", id: "session-entry-state" }]; throw new DoctorStateMigrationRefusalError([createLegacyStateMigrationStepReceipt({ id: "session-entry-state", phase: "final", source: t, target: t, requiredness: "required", reversibility: "checkpoint-required" }, { changes: [], warnings: [formatErrorMessage(e)] })]); } } //#endregion export { repairLegacySessionEntryStates as i, repairCanonicalSessionEntries as n, repairCanonicalSessionResolvedSkills as r, repairCanonicalSessionDeliveryStates as t };