openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
388 lines (387 loc) • 18.3 kB
JavaScript
import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { a as getOrLoadSqliteDatabaseAdmissionForPath, b as publishSqliteDatabaseAdmission } from "./sqlite-database-admission-DQIqro3d.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { l as runWithSqliteCleanup, u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs";
import { 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 { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "./openclaw-state-db-contract-DfPjvL0M.mjs";
import { a as setSqliteBusyTimeout } from "./sqlite-busy-timeout-BEDmnGR_.mjs";
import { r as withArtifactPreservingStateReads } from "./artifact-preserving-state-reads-BfhmBr-V.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { Dr as ZodError, Fn as object, Jn as string, Nt as array, xn as literal } from "./schemas-Cy6abvsu.mjs";
import { m as openClawStateDatabaseCache } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import { n as closeTrackedStateDatabase, r as openTrackedStateDatabase } from "./openclaw-state-db-handle-BxpEWiaT.mjs";
import { d as withExistingOpenClawStateDatabaseArtifactPreservingReadOnly, m as withExistingOpenClawStateDatabaseReadOnly, n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { n as withStateDatabaseSchemaMaintenance } from "./state-database-maintenance-Z49n3wcg.mjs";
import { t as assertStateReadSchema } from "./openclaw-state-db-read-connection-DoTwzEPO.mjs";
import { n as runManagedStateTransaction } from "./openclaw-state-db-transaction-Bho3XfIN.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { l as runOpenClawStateWriteTransaction } from "./openclaw-state-db-ARhwdPJg.mjs";
import { a as invalidateSuccessfulMigrationCheckpointsInTransaction } from "./startup-migration-checkpoint-DgsDZ-2_.mjs";
import { o as recordLegacyMigrationRun } from "./state-migrations.receipts-CXYpigJ-.mjs";
import { existsSync } from "node:fs";
import { AsyncLocalStorage } from "node:async_hooks";
import { isDeepStrictEqual } from "node:util";
//#region src/infra/deferred-plugin-migrations.contract.ts
const deferredPluginMigrationSchema = object({
pluginId: string().min(1),
reason: string().min(1),
command: string().min(1),
requiresStateMigration: literal(true).optional(),
requiresDoctorInspection: literal(true).optional(),
configPaths: array(array(string().min(1)).min(1)).optional(),
validationExcludedPaths: array(array(string().min(1)).min(1)).optional()
});
/** Discovery order and Doctor guidance do not change the requirements protecting retained inputs. */
function sameDeferredPluginMigrationInputs(e, t) {
const inputs = (e) => e.map(({ reason: e, command: t, ...n }) => n).toSorted((e, t) => e.pluginId.localeCompare(t.pluginId));
return isDeepStrictEqual(inputs(e), inputs(t));
}
//#endregion
//#region src/infra/deferred-plugin-migrations.kernel.ts
const RUN_PREFIX = "deferred-plugin-migration:";
function readPendingMigrationRows(e, t = false) {
return executeSqliteQuerySync(e, getNodeSqliteKysely(e).selectFrom("migration_runs").select([
"id",
"report_json",
"status"
]).where("id", "like", `${RUN_PREFIX}%`).where("status", "in", t ? ["pending", "deferred"] : ["pending"]).orderBy("id")).rows;
}
function pendingMigrationRecords(e) {
return e.map((e) => deferredPluginMigrationSchema.parse(JSON.parse(e.report_json)));
}
function readPendingMigrationRecords(e, t = false) {
return tableExists(e, "migration_runs") ? pendingMigrationRecords(readPendingMigrationRows(e, t)) : [];
}
//#endregion
//#region src/infra/deferred-plugin-migrations.ts
const pinnedMigrationRead = new AsyncLocalStorage();
function invalidatePinnedMigrationReads() {
for (let e = pinnedMigrationRead.getStore(); e; e = e.parent) e.invalidated = true;
}
const migrationReceipt = {
name: "plugins.deferred-migrations",
lifetime: "process",
read: (e) => isRecord(e) ? e : void 0
};
/** Only committed migration writes retire readiness; ordinary state writes do not. */
function readDeferredPluginMigrationReceipt(e) {
return getOrLoadSqliteDatabaseAdmissionForPath(e, migrationReceipt, () => ({})) ?? {};
}
const configMigrationCompletion = new AsyncLocalStorage();
/** The package owner may finish inspected config-only work through the normal file publisher. */
async function withDeferredPluginConfigCompletion(e, t) {
return await configMigrationCompletion.run({
...e,
published: false
}, t);
}
/** The file rollback's live owner also restores its completed migration obligations. */
function withDeferredPluginConfigRollback(e, t, n) {
const r = configMigrationCompletion.getStore();
if (!r?.published || r.configPath !== e.configPath) {
t();
return;
}
let i;
runOpenClawStateWriteTransaction(({ db: a }) => {
e.assertCurrent();
recordDeferredPluginMigrationsInTransaction(a, {
pending: r.expectedPending,
expectedPending: r.expectedPending.filter((e) => !r.resolvedPluginIds.includes(e.pluginId))
});
try {
t();
} catch (e) {
if (!n()) throw e;
i = { error: e };
}
if (!n()) throw new Error("Config rollback did not publish its restoration.");
}, { env: e.env }, { operationLabel: "state.plugin-migration-input-rollback" });
r.published = false;
if (i) throw i.error;
}
/** Ordinary writes consume canonical config; only migration owners supply pending facts. */
async function readConfigWritePendingMigrations(e, t, n) {
const r = configMigrationCompletion.getStore();
if (!r || r.configPath !== e) return n;
r.assertCurrent();
if (r.published) return await readDeferredPluginMigrationsAsync({ env: t });
return r.expectedPending.filter((e) => !r.resolvedPluginIds.includes(e.pluginId));
}
var DeferredPluginMigrationConflictError = class extends Error {
constructor(e, t = {}) {
const n = t.phase ?? "migration settlement";
const r = t.expected ? ` expected=${formatConflictIds(t.expected.map((e) => e.pluginId))}, current=${formatConflictIds(e.map((e) => e.pluginId))}, changed=${formatChangedObligationFields(t.expected, e)}.` : "";
super(`Plugin migration obligations changed during ${n}.${r} Retained inputs remain protected; run "openclaw doctor --fix" after the other repair finishes.`);
this.name = "DeferredPluginMigrationConflictError";
this.pending = e;
}
};
const MAX_CONFLICT_DIAGNOSTIC_ITEMS = 4;
function formatConflictIds(e) {
const t = [...new Set(e)].toSorted();
const n = t.slice(0, MAX_CONFLICT_DIAGNOSTIC_ITEMS);
const r = t.length - n.length;
return `[${n.join(", ")}${r > 0 ? `, +${r} more` : ""}]`;
}
function formatChangedObligationFields(e, t) {
const n = new Set(e.map((e) => e.pluginId));
const r = new Map(t.map((e) => [e.pluginId, e]));
const i = deferredPluginMigrationSchema.keyof().options;
const a = [];
for (const t of e) {
const e = r.get(t.pluginId);
if (!e) {
a.push(`${t.pluginId}:removed`);
continue;
}
for (const n of i) if (!isDeepStrictEqual(t[n], e[n])) a.push(`${t.pluginId}:${n}`);
}
for (const e of t) if (!n.has(e.pluginId)) a.push(`${e.pluginId}:added`);
return formatConflictIds(a);
}
/** Missing metadata cannot release inputs already claimed by an unfinished migration. */
function mergeDeferredPluginMigration(e, t) {
const mergePaths = (e = [], t = []) => [...new Map([...e, ...t].map((e) => [JSON.stringify(e), e])).values()];
const n = mergePaths(e?.configPaths, t.configPaths);
const r = mergePaths(e?.validationExcludedPaths, t.validationExcludedPaths);
return {
pluginId: t.pluginId,
reason: t.reason,
command: t.command,
...e?.requiresStateMigration || t.requiresStateMigration ? { requiresStateMigration: true } : {},
...e?.requiresDoctorInspection || t.requiresDoctorInspection ? { requiresDoctorInspection: true } : {},
...n.length > 0 ? { configPaths: n } : {},
...r.length > 0 ? { validationExcludedPaths: r } : {}
};
}
function assertPendingGeneration(e, t, n) {
if (!sameDeferredPluginMigrationInputs(e, t)) throw new DeferredPluginMigrationConflictError(e, {
expected: t,
phase: n
});
}
function readDeferredPluginMigrations(e = {}) {
return (e.artifactPreservingReadOnly === false ? withExistingOpenClawStateDatabaseReadOnly : withExistingOpenClawStateDatabaseArtifactPreservingReadOnly)(({ db: t }) => readPendingMigrationRecords(t, e.includeDeferred), e) ?? [];
}
/** Prime resolution in this module before the updater replaces its package. */
async function prepareDeferredPluginMigrationRuntime() {
const { prepareOpenClawStateLeaseWorkerRuntime: e } = await import("./openclaw-state-lease-worker-operation-CWjSct81.mjs");
await Promise.all([
import("./openclaw-state-worker-store-BURqchns.mjs"),
import("./plugin-lifecycle-lease-B1cHoIkh.mjs"),
e()
]);
}
/** Keep Doctor and update inspection off the main thread without creating state. */
async function readDeferredPluginMigrationsAsync(e = {}) {
const read = () => executeExistingOpenClawStateRead(e, {
type: "plugins.deferredMigrations.read",
input: e.includeDeferred ? { includeDeferred: true } : void 0
});
const t = await (e.artifactPreservingReadOnly === false ? read() : withArtifactPreservingStateReads(read));
if (!t) return [];
return t.pending;
}
/** The caller holds the plugin lifecycle lease until its last synchronous policy guard. */
async function withLeasePinnedDeferredPluginMigrations(e, t) {
await e.lease.assertOwned();
const n = await readDeferredPluginMigrationsAsync({
env: e.env,
path: e.lease.databasePath
});
await e.lease.assertOwned();
const r = {
invalidated: false,
...pinnedMigrationRead.getStore() ? { parent: pinnedMigrationRead.getStore() } : {}
};
return await pinnedMigrationRead.run(r, async () => t(n, () => {
e.lease.assertCurrent();
if (r.invalidated) throw new Error("Deferred plugin migration policy changed since review.");
}));
}
/** Completion receipts resolve historical warnings without loading their retired reports. */
function readDeferredPluginMigrationCompletions(e = {}) {
return withExistingOpenClawStateDatabaseArtifactPreservingReadOnly(({ db: e }) => {
if (!tableExists(e, "migration_runs")) return [];
return executeSqliteQuerySync(e, getNodeSqliteKysely(e).selectFrom("migration_runs").select(["id", "finished_at"]).where("id", "like", `${"deferred-plugin-migration:"}%`).where("status", "in", [
"completed",
"superseded",
"deferred"
])).rows.flatMap(({ id: e, finished_at: t }) => t === null ? [] : [{
pluginId: e.slice("deferred-plugin-migration:".length),
completedAtMs: t
}]);
}, e) ?? [];
}
/** Bind asynchronous settlement to the same pending records, including newly added owners. */
function assertDeferredPluginMigrationsCurrent(e) {
withDeferredPluginMigrationsCurrent(e, () => void 0);
}
/** Keep competing obligation writers excluded until synchronous input publication finishes. */
function withDeferredPluginMigrationsCurrent(e, t) {
const n = configMigrationCompletion.getStore();
const r = n && n.configPath === e.configPath && !n.published ? n : void 0;
const i = r?.expectedPending ?? e.expectedPending;
if (i === void 0) return t();
const a = resolveOpenClawStateSqlitePath(e.env);
const o = openClawStateDatabaseCache.getOpenClawStateDatabaseIfOpenAtPath(a);
if (i.length === 0 && !o) {
if (!existsSync(a)) return withStateDatabaseSchemaMaintenance({ databasePath: a }, () => existsSync(a) ? withDeferredPluginMigrationsCurrent(e, t) : t());
const n = openTrackedStateDatabase(a, { existingOnly: true });
let r;
runWithSqliteCleanup({ release() {
const e = [];
try {
clearNodeSqliteKyselyCacheForDatabase(n);
} catch (t) {
e.push(t);
}
try {
closeTrackedStateDatabase(n);
} catch (t) {
e.push(t);
}
throwSqliteLifecycleErrors(e, "Plugin migration publication cleanup failed.");
} }, "Plugin migration input publication", () => {
setSqliteBusyTimeout(n, OPENCLAW_SQLITE_BUSY_TIMEOUT_MS);
runManagedStateTransaction(n, () => {
assertStateReadSchema(n, a);
if (readPendingMigrationRecords(n).length > 0) return;
const e = t();
r = { value: e };
return e;
}, {
databaseLabel: a,
operationLabel: "state.plugin-migration-input-publication"
});
});
if (r) return r.value;
}
const s = runOpenClawStateWriteTransaction(({ db: n }) => {
const a = pendingMigrationRecords(readPendingMigrationRows(n));
if (e.onConflict && !sameDeferredPluginMigrationInputs(a, i)) return e.onConflict(a);
assertPendingGeneration(a, i, e.phase ?? "migration input publication");
r?.assertCurrent();
const o = t();
if (r) {
r.assertCurrent();
recordDeferredPluginMigrationsInTransaction(n, {
pending: a.filter((e) => !r.resolvedPluginIds.includes(e.pluginId)),
resolvedPluginIds: r.resolvedPluginIds,
expectedPending: i
});
}
return o;
}, { env: e.env }, { operationLabel: "state.plugin-migration-input-publication" });
if (r) r.published = true;
return s;
}
function formatDeferredPluginMigration(e, t = process.env) {
const n = e.command === "openclaw doctor --fix" ? "" : ", then \"openclaw doctor --fix\"";
const r = isTruthyEnvValue(t.OPENCLAW_UPDATE_IN_PROGRESS) && !isTruthyEnvValue(t.OPENCLAW_UPDATE_POST_CORE_CONVERGENCE) ? `Let the current update or repair finish. If this warning remains afterward, run "${e.command}"${n} to retry the upgrade.` : `Run "${e.command}"${n} to retry the upgrade.`;
return `Plugin "${e.pluginId}" data/settings upgrade is unfinished: ${e.reason} Your existing data and settings have been kept. ${r}`;
}
/** Native row transform; the worker owns its transaction and lease grants. */
function recordDeferredPluginMigrationsInTransaction(e, t) {
if (t.pending.length > 0 || t.resolvedPluginIds?.length) invalidatePinnedMigrationReads();
const n = new Map(t.pending.map((e) => [e.pluginId, deferredPluginMigrationSchema.parse(e)]));
const r = readPendingMigrationRows(e, true);
if (t.expectedPending) assertPendingGeneration(pendingMigrationRecords(r.filter((e) => e.status === "pending")), t.expectedPending, "migration settlement");
const i = new Map(r.map((e) => [e.id, e]));
const a = [];
const o = [];
const s = Date.now();
for (const t of n.values()) {
const n = `${RUN_PREFIX}${t.pluginId}`;
const r = i.get(n);
const o = mergeDeferredPluginMigration(r ? deferredPluginMigrationSchema.parse(JSON.parse(r.report_json)) : void 0, t);
const c = JSON.stringify(o);
if (r?.status === "pending" && r.report_json === c) continue;
recordLegacyMigrationRun(e, {
runId: n,
startedAt: s,
finishedAt: null,
status: "pending",
reportJson: c,
upsert: true
});
a.push(o);
}
const c = new Map(t.settlements?.map((e) => [e.pluginId, e]));
for (const r of /* @__PURE__ */ new Set([...t.resolvedPluginIds ?? [], ...c.keys()])) {
const t = `${RUN_PREFIX}${r}`;
const a = i.get(t);
if (n.has(r) || !a) continue;
const l = c.get(r);
recordLegacyMigrationRun(e, {
runId: t,
startedAt: s,
finishedAt: s,
status: l?.status ?? "completed",
reportJson: l ? JSON.stringify({
...deferredPluginMigrationSchema.parse(JSON.parse(a.report_json)),
reason: l.reason
}) : a.report_json,
upsert: true
});
o.push(r);
}
if (a.length > 0) invalidateSuccessfulMigrationCheckpointsInTransaction(e);
if (a.length > 0 || o.length > 0) publishSqliteDatabaseAdmission(e, migrationReceipt, {});
return {
deferred: a,
resolved: o,
pending: pendingMigrationRecords(readPendingMigrationRows(e))
};
}
/** Only the migration owner can resolve a pending record after its work completes. */
async function recordDeferredPluginMigrations(e) {
if (e.pending.length === 0 && !e.resolvedPluginIds?.length && !e.settlements?.length) return;
invalidatePinnedMigrationReads();
const t = structuredClone({
pending: e.pending,
resolvedPluginIds: e.resolvedPluginIds,
settlements: e.settlements,
expectedPending: e.expectedPending
});
const { withPluginLifecycleLeaseAsync: n } = await import("./plugin-lifecycle-lease-B1cHoIkh.mjs");
const { runWithOpenClawStateLeaseWorker: r } = await import("./openclaw-state-lease-worker-operation-CWjSct81.mjs");
return n({ env: e.env }, async (n) => {
const i = captureOpenClawStateWorkerContext({
env: e.env,
path: n.databasePath
});
const a = await r(n.stateLease, i, (e, n) => e.execute({
type: "plugins.deferredMigrations.record",
input: {
identity: n,
...t
}
}), { assertCurrent: () => n.assertCurrent() });
if (a.kind === "conflict") throw new DeferredPluginMigrationConflictError(a.pending, { expected: t.expectedPending });
if (a.kind === "invalid") throw new ZodError(a.issues);
const o = a.transitions;
const s = createSubsystemLogger("state-migrations");
for (const t of o.deferred) s.warn(formatDeferredPluginMigration(t, e.env), {
pluginId: t.pluginId,
reason: t.reason,
action: t.command,
status: "pending"
});
for (const t of o.resolved) {
const n = e.settlements?.find((e) => e.pluginId === t);
s.info(`Deferred state migration ${n ? "settled" : "completed"} for plugin "${t}".`, {
pluginId: t,
status: n?.status ?? "completed",
...n ? { reason: n.reason } : {}
});
}
return o.pending;
});
}
//#endregion
export { prepareDeferredPluginMigrationRuntime as a, readDeferredPluginMigrationReceipt as c, recordDeferredPluginMigrations as d, recordDeferredPluginMigrationsInTransaction as f, withLeasePinnedDeferredPluginMigrations as g, withDeferredPluginMigrationsCurrent as h, mergeDeferredPluginMigration as i, readDeferredPluginMigrations as l, withDeferredPluginConfigRollback as m, assertDeferredPluginMigrationsCurrent as n, readConfigWritePendingMigrations as o, withDeferredPluginConfigCompletion as p, formatDeferredPluginMigration as r, readDeferredPluginMigrationCompletions as s, DeferredPluginMigrationConflictError as t, readDeferredPluginMigrationsAsync as u };