openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
256 lines (255 loc) • 12.9 kB
JavaScript
import { t as assertNoActiveSqliteReaders } from "../sqlite-reader-lifecycle-CF8Y2ajA.mjs";
import { r as assertExistingDatabaseIdentity } from "../sqlite-worker-identity-BRNRpRyc.mjs";
import { t as assertTransactionUsable } from "../sqlite-transaction-DBRLvCDM.mjs";
import { S as assertOpenClawStateDatabaseOwner } from "../openclaw-state-db-fast-path-Kg79WElU.mjs";
import { o as SQLITE_WORKER_PREPARE_COMMAND } from "../sqlite-worker-contract-C51cJHzg.mjs";
import { i as deferSqliteWorkerCommitReceipt, s as requestSqliteWorkerOperationAdmission } from "../sqlite-worker-operation-admission-C5lBzzTk.mjs";
import { p as openClawStateDatabaseCache, x as retainOpenClawStateDatabase } from "../openclaw-state-db-cache-CmYLFRSt.mjs";
import { c as withSqliteWorkerExistingDatabase, i as getSqliteWorkerStateContext } from "../sqlite-worker-state-context-G3Xbcj1W.mjs";
import { l as runOpenClawStateWriteTransaction, r as openOpenClawStateDatabase } from "../openclaw-state-db-DJZ7EKoI.mjs";
import { g as ensureSecretStoreSchema } from "../openclaw-state-db-schema-additive-S7iMdRlC.mjs";
import { n as readPluginMetadataStateRowSync, r as readPluginMetadataStateRowsSync } from "../installed-plugin-index-row-CvqFVPqV.mjs";
import { n as pluginStateWorkerOperations, t as isPluginStateWorkerCommand } from "../plugin-state-worker-contract-DvV7sf3-.mjs";
import { n as loadDeviceIdentityIfPresent, r as loadOrCreateDeviceIdentity } from "../device-identity-CKtmS8Us.mjs";
import { t as refreshSqlitePlannerStatistics } from "../sqlite-planner-statistics-B4K5HWiX.mjs";
import { i as executeOpenClawStateLeaseCommand, t as acquireOpenClawStateLeaseInWorker } from "../openclaw-state-lease-worker-Ddwq3QcA.mjs";
import { t as createWorkerOperationRegistry } from "../worker-operation-registry-DhUe8rTN.mjs";
//#region src/state/openclaw-state.worker.ts
const commandRegistry = createWorkerOperationRegistry({
deviceAuth: async () => (await import("../device-auth-store.worker-BwAYIOhd.mjs")).deviceAuthWorkerOperations,
restartLifecycle: () => import("../restart-lifecycle.worker-D_RfZmUX.mjs").then((loaded) => loaded.restartLifecycleOperations),
worktrees: async () => {
const [templates, reserveCapacity, recoverPending] = await Promise.all([
import("../template-registry.worker-BA9olZeM.mjs").then((loaded) => loaded.worktreeTemplateOperations),
import("../capacity.worker-ZCjXnMpl.mjs").then((loaded) => loaded.reserveWorktreeCapacityInWorker),
import("../registry-run-end.worker-Bq_JC0za.mjs").then((loaded) => loaded.recoverPendingWorktreesInWorker)
]);
return {
...templates,
"worktrees.reserveCapacity": reserveCapacity,
"worktrees.recoverPending": recoverPending
};
}
});
let agentCleanup;
let pluginState;
let capture;
let runtime;
function stateDatabaseInitializationEnvironment() {
const context = getSqliteWorkerStateContext();
return context.initializationEnvironment ?? context.environment;
}
function createSqliteWorkerBackend(_input, context) {
if (context.preparation?.type === "deviceIdentity") loadOrCreateDeviceIdentity({
path: context.databasePath,
env: stateDatabaseInitializationEnvironment(),
identityKey: context.preparation.identityKey
});
return createSharedStateWorkerBackend(context, openOpenClawStateDatabase({
path: context.databasePath,
env: stateDatabaseInitializationEnvironment(),
initializationAgentPaths: getSqliteWorkerStateContext().initializationAgentPaths
}));
}
function openExistingSqliteWorkerBackend(_input, context) {
const identity = context.existingIdentity;
assertExistingDatabaseIdentity(context.databasePath, identity);
const backend = createSharedStateWorkerBackend(context, void 0, identity);
return {
...backend,
execute(command) {
return withSqliteWorkerExistingDatabase(context.databasePath, identity, () => backend.execute(command));
}
};
}
function createSharedStateWorkerBackend(context, initialDatabase, existingIdentity) {
let nativeDatabase = initialDatabase;
let updateRunWriter;
let borrow = nativeDatabase ? retainOpenClawStateDatabase(nativeDatabase) : void 0;
let closed = false;
let secretSchemaAdmitted = false;
const retainedDatabase = () => {
if (!nativeDatabase) {
const opened = openOpenClawStateDatabase({
path: context.databasePath,
env: stateDatabaseInitializationEnvironment(),
initializationAgentPaths: getSqliteWorkerStateContext().initializationAgentPaths
});
borrow = retainOpenClawStateDatabase(opened);
nativeDatabase = opened;
}
if (!nativeDatabase.db.isOpen || openClawStateDatabaseCache.getCachedOpenClawStateDatabase(nativeDatabase.path) !== nativeDatabase) throw new Error("Shared-state worker lost its retained native database");
return nativeDatabase;
};
const open = () => openOpenClawStateDatabase({
database: retainedDatabase(),
path: context.databasePath,
env: getSqliteWorkerStateContext().environment
});
const write = (operation, transactionOptions, database = retainedDatabase(), env = getSqliteWorkerStateContext().environment) => runOpenClawStateWriteTransaction(operation, {
database,
path: context.databasePath,
env
}, transactionOptions);
const writeAdmitted = (operation, { receipt, transactionEnvironment, ...options } = {}) => {
const openedDatabase = open();
return write((database) => {
requestSqliteWorkerOperationAdmission({
stage: "transaction",
facts: void 0
});
const result = operation(database);
requestSqliteWorkerOperationAdmission({
stage: "commit",
facts: receipt === "result" ? result : void 0
});
if (receipt === "result") deferSqliteWorkerCommitReceipt(database.db, result);
return result;
}, options, openedDatabase, transactionEnvironment === "process" ? process.env : void 0);
};
return {
[SQLITE_WORKER_PREPARE_COMMAND](commandType) {
if (commandType.startsWith("deviceAuth.") || commandType.startsWith("restartLifecycle.") || commandType.startsWith("worktrees.templates.") || commandType === "worktrees.reserveCapacity" || commandType === "worktrees.recoverPending") return commandRegistry.prepare(commandType);
if (commandType.startsWith("capture.")) {
if (capture) return;
return import("../store.worker-BY9L3W02.mjs").then((loaded) => {
capture = loaded;
});
}
if (commandType === "agentDatabases.releaseExitedLease") {
if (agentCleanup) return;
return import("../openclaw-agent-execution-cleanup.worker-DI3ijLth.mjs").then((loaded) => {
agentCleanup = loaded;
});
}
if (Object.hasOwn(pluginStateWorkerOperations, commandType)) {
if (pluginState) return;
return import("../plugin-state.worker-DnDVhOkX.mjs").then((loaded) => {
pluginState = loaded;
});
}
if (commandType === "plugins.metadata.read" || commandType === "database.inspectIdle" || commandType === "database.walMaintenance" || commandType === "stateLease.acquire" || commandType === "deviceIdentity.read" || commandType === "deviceIdentity.load" || commandType === "stateLease.verify" || commandType === "stateLease.renew" || commandType === "stateLease.release") return;
if (runtime) return runtime.prepareSharedStateCommand(commandType);
return import("../openclaw-state-worker-runtime-C0jtWRZj.mjs").then((loaded) => {
runtime = loaded;
return runtime.prepareSharedStateCommand(commandType);
});
},
execute(command) {
if (closed) throw new Error("Shared-state worker is closed");
if (commandRegistry.has(command)) return commandRegistry.execute(command, {
open,
write,
writeAdmitted,
stateOptions: () => ({
path: context.databasePath,
env: getSqliteWorkerStateContext().environment
})
});
if (command.type === "capture.upsertSession" || command.type === "capture.endSession" || command.type === "capture.persistPayload" || command.type === "capture.recordEvent" || command.type === "capture.recordEventWithPayload" || command.type === "capture.listSessions" || command.type === "capture.getSessionEvents" || command.type === "capture.summarizeSessionCoverage" || command.type === "capture.readBlob" || command.type === "capture.queryPreset" || command.type === "capture.deleteSessions" || command.type === "capture.purgeAll") {
if (!capture) throw new Error("Capture worker command runtime is not prepared");
return capture.executeCaptureCommand(command, open());
}
if (command.type === "deviceIdentity.read") return loadDeviceIdentityIfPresent({
path: context.databasePath,
identityKey: command.input.identityKey,
env: getSqliteWorkerStateContext().environment
});
if (command.type === "deviceIdentity.load") try {
return loadOrCreateDeviceIdentity({
path: context.databasePath,
identityKey: command.input.identityKey,
env: stateDatabaseInitializationEnvironment()
});
} finally {
if (!nativeDatabase) {
const database = openClawStateDatabaseCache.getCachedOpenClawStateDatabase(context.databasePath);
if (database) {
borrow = retainOpenClawStateDatabase(database);
nativeDatabase = database;
}
}
}
if (command.type === "agentDatabases.releaseExitedLease") {
if (!agentCleanup) throw new Error("Agent database cleanup runtime is not prepared");
return agentCleanup.executeAgentDatabaseCleanupCommand(command, open(), getSqliteWorkerStateContext().environment);
}
if (command.type === "stateLease.acquire") {
if (command.input.schemaPolicy === "existing" && existingIdentity) assertExistingDatabaseIdentity(context.databasePath, existingIdentity);
return acquireOpenClawStateLeaseInWorker(command.input, context.databasePath, open);
}
if (command.type === "stateLease.verify" || command.type === "stateLease.renew" || command.type === "stateLease.release") return executeOpenClawStateLeaseCommand(command, open());
if (command.type === "plugins.metadata.read") {
const options = {
path: context.databasePath,
env: getSqliteWorkerStateContext().environment
};
if ("stateKeys" in command.input) return readPluginMetadataStateRowsSync(command.input.stateKeys, options, command.input.artifactPreservingReadOnly);
return readPluginMetadataStateRowSync(command.input.selector, options, command.input.artifactPreservingReadOnly);
}
if (command.type === "database.walMaintenance") {
const database = open();
const admit = (stage) => {
requestSqliteWorkerOperationAdmission({
stage,
facts: void 0
});
};
return database.walMaintenance.maintainPeriodic?.(command.input, admit, () => runOpenClawStateWriteTransaction(({ db }) => {
admit("transaction");
refreshSqlitePlannerStatistics(db);
admit("commit");
}, { database }, {
busyTimeoutMs: 0,
operationLabel: "state.planner-statistics"
})) ?? { reclaimedPages: 0 };
}
if (command.type === "database.inspectIdle") {
if (!nativeDatabase?.db.isOpen || openClawStateDatabaseCache.getCachedOpenClawStateDatabase(nativeDatabase.path) !== nativeDatabase) {
if (!nativeDatabase && updateRunWriter) {
updateRunWriter.assertSettled();
return "healthy";
}
return "retire";
}
assertOpenClawStateDatabaseOwner(nativeDatabase.db, { pathname: nativeDatabase.path });
return nativeDatabase.walMaintenance.inspectIdle?.() ?? "retire";
}
if (isPluginStateWorkerCommand(command)) {
if (!pluginState) throw new Error("Plugin-state worker command runtime is not prepared");
return pluginState.executePluginStateCommand(command, {
path: context.databasePath,
env: getSqliteWorkerStateContext().environment
}, retainedDatabase, nativeDatabase?.db.isOpen === true);
}
const currentRuntime = runtime;
if (!currentRuntime) throw new Error("Shared-state worker command runtime is not prepared");
if (command.type === "secrets.write" && !secretSchemaAdmitted) {
runOpenClawStateWriteTransaction(({ db }) => ensureSecretStoreSchema(db), { database: open() }, { operationLabel: "secrets.store.admit" });
secretSchemaAdmitted = true;
}
return currentRuntime.executeSharedStateCommand(command, context, open, write, writeAdmitted, () => updateRunWriter ??= currentRuntime.openUpdateRunWriter({
path: context.databasePath,
env: getSqliteWorkerStateContext().environment
}));
},
assertSettled() {
updateRunWriter?.assertSettled();
if (nativeDatabase) {
assertTransactionUsable(nativeDatabase.db);
if (nativeDatabase.db.isOpen && nativeDatabase.db.isTransaction) throw new Error("Shared-state worker retained an unsettled transaction");
if (nativeDatabase.db.isOpen) assertNoActiveSqliteReaders(nativeDatabase.db, "Shared-state worker");
}
},
async close() {
closed = true;
try {
updateRunWriter?.close();
} finally {
await borrow?.releaseAsync();
}
}
};
}
//#endregion
export { createSqliteWorkerBackend, openExistingSqliteWorkerBackend };