openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
285 lines (284 loc) • 11.4 kB
JavaScript
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { b as isCronRunSessionKey } from "./session-key-CqAyZeVk.mjs";
import { u as normalizeDatabasePath } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { t as OPENCLAW_AGENT_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { s as isConstrainedProcessLowOnMemory } from "./worker-pool-sizing-BAFxhrtU.mjs";
import { x as registerOpenClawStateDatabaseLifecycleListener } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import "./openclaw-agent-db-contract-aCH9b8Uc.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { a as sessionChangeScopeAffectsStoredRows, o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs";
import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { u as isGatewayRestartDrainError, w as runWithGatewayIndependentRootWorkAdmission } from "./gateway-work-admission-79pid1hQ.mjs";
import { S as readAgentDatabaseAdmissionRefusal, _ as listAgentDatabaseAdmissionRefusals } from "./agent-database-admission-CL6wHJ_N.mjs";
import { r as prepareAgentDatabaseDeletionSnapshotRead, t as isAgentDatabaseDeletionSnapshotChangedError } from "./agent-deletion-journal.read-DjOO2RZM.mjs";
import { o as resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target-C8iD4yIo.mjs";
import { s as resolveConfiguredAgentDatabaseTargets } from "./targets-BVE0__Jb.mjs";
import "./config-CMA-J084.mjs";
import { l as runSessionRegistryMaintenanceForStore } from "./sessions-D5Vvu3AE.mjs";
import { n as resolveAllAgentSessionStoreTargetsAsync } from "./targets-runtime-pFH3Bycg.mjs";
import { r as createRetainedAgentDatabaseMatcherFromSnapshot } from "./agent-deletion-discovery-BUESMyCH.mjs";
import { n as subscribeCronRunHistoryChanges } from "./run-history-changes-9hQwml5S.mjs";
import { r as loadCronJobsStoreWithConfigJobsReadOnly } from "./read-only-C2x_PRgh.mjs";
import { t as maintainCronRunHistory } from "./run-history-Cdoy8DIq.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/cron/session-registry-maintenance.ts
const log$1 = createSubsystemLogger("cron/maintenance");
const SESSION_REGISTRY_RETENTION_MS = 6048e5;
function resolveExplicitCronSessionSegment(e) {
return /^(?:agent:[^:]+:)?cron:([^:]+)$/u.exec(e?.trim() ?? "")?.[1]?.toLowerCase();
}
async function readRunningCronJobIds(e) {
try {
const t = (await loadCronJobsStoreWithConfigJobsReadOnly(e)).store.jobs.filter((e) => typeof e.state?.runningAtMs === "number");
const n = /* @__PURE__ */ new Set();
for (const e of t) {
n.add(e.id.toLowerCase());
if (e.sessionTarget === "main") continue;
const t = resolveExplicitCronSessionSegment(e.sessionKey);
if (t) n.add(t);
}
return {
ok: true,
ids: n,
count: t.length
};
} catch (e) {
return {
ok: false,
reason: formatErrorMessage(e)
};
}
}
async function runSessionRegistryMaintenance(e) {
e.assertCurrent?.();
const t = readRuntimeConfig();
const n = await readRunningCronJobIds(e.cronStorePath);
e.assertCurrent?.();
if (!n.ok) return {
retentionMs: SESSION_REGISTRY_RETENTION_MS,
runningCronJobs: 0,
pruned: 0,
skippedStores: 0,
stores: [],
nextSweepAtMs: Date.now() + 6e4,
skippedReason: `cron store unreadable: ${n.reason}`
};
const r = process.env;
return await prepareAgentDatabaseDeletionSnapshotRead({ env: r }).withCurrentSnapshot(async (i, a) => {
const o = listAgentDatabaseAdmissionRefusals({ env: r }).filter((e) => readAgentDatabaseAdmissionRefusal(e.agentId, { env: r })).flatMap((e) => e.paths.map((t) => ({
agentId: e.agentId,
storePath: t,
skippedReason: e.code
})));
const assertCurrent = () => {
e.assertCurrent?.();
a();
};
assertCurrent();
const s = (i?.registeredAgentDatabases ?? []).filter((e) => e.schemaVersion === 38);
const c = createRetainedAgentDatabaseMatcherFromSnapshot(r, () => resolveConfiguredAgentDatabaseTargets(t, {
env: r,
registeredDatabases: s
}), i);
const l = new Map(i?.deletedAgents.map(({ agentId: e, status: t }) => [e, t]));
const u = await resolveAllAgentSessionStoreTargetsAsync(t, {
env: r,
registeredDatabases: s
});
const d = [];
for (const e of u) {
assertCurrent();
const t = l.get(e.agentId) ?? "absent";
const n = t !== "absent" ? e.storePath : resolveSqliteTargetFromSessionStorePath(e.storePath, {
agentId: e.agentId,
env: r,
registeredDatabases: s
}).path;
const i = t === "absent" ? c(n, e.agentId) : void 0;
if (t !== "absent" || typeof i === "object") {
o.push({
...e,
skippedReason: t === "pending" ? "agent-deletion-pending" : "agent-deletion-complete"
});
continue;
}
if (i) {
const t = i === "held" ? "deletion journal reconstruction" : "deletion journal unavailable";
const a = `Held agent ${e.agentId} database ${n} (${t}); skipped session retention. Run "${formatCliCommand("openclaw doctor --fix", r)}" for explicit restoration guidance.`;
log$1.warn(a);
o.push({
...e,
skippedReason: "agent-store-held",
warning: a
});
continue;
}
d.push(e);
}
const f = o.some((e) => "skippedReason" in e && e.skippedReason !== "agent-deletion-pending" && e.skippedReason !== "agent-deletion-complete" && !l.has(e.agentId));
for (const t of f ? [] : d) {
assertCurrent();
const r = await runSessionRegistryMaintenanceForStore({
...t,
apply: e.apply,
retentionMs: SESSION_REGISTRY_RETENTION_MS,
runningCronJobIds: n.ids,
childStores: d,
assertCurrent
});
assertCurrent();
o.push({
agentId: t.agentId,
storePath: t.storePath,
pruned: r.pruned,
preservedRunning: r.preservedRunning,
nextSweepAtMs: r.nextSweepAtMs
});
}
const p = o.flatMap((e) => "nextSweepAtMs" in e ? e.nextSweepAtMs === null ? [] : [e.nextSweepAtMs] : e.skippedReason === "agent-deletion-pending" ? [Date.now() + 6e4] : []);
if (f) p.push(Date.now() + 6e4);
return {
nextSweepAtMs: p.length > 0 ? Math.min(...p) : null,
...f ? { skippedReason: "session child inventory incomplete" } : {},
retentionMs: SESSION_REGISTRY_RETENTION_MS,
runningCronJobs: n.count,
pruned: o.reduce((e, t) => e + ("pruned" in t ? t.pruned : 0), 0),
skippedStores: o.filter((e) => "skippedReason" in e).length,
stores: o
};
});
}
//#endregion
//#region src/cron/maintenance.ts
const log = createSubsystemLogger("cron/maintenance");
let scope;
let scheduledSweep;
let nextHistorySweepAtMs = Infinity;
let nextRegistrySweepAtMs = Infinity;
let lastRegistrySuccessAtMs = null;
let unsubscribeSessionChanges;
let unsubscribeHistoryChanges;
let unsubscribeDatabaseLifecycle;
async function sweep(e, t) {
if (isConstrainedProcessLowOnMemory()) {
const e = scope?.now() ?? Date.now();
if (nextHistorySweepAtMs <= e) nextHistorySweepAtMs = e + 6e4;
if (nextRegistrySweepAtMs <= e) nextRegistrySweepAtMs = e + 6e4;
return;
}
let n = false;
try {
await runWithGatewayIndependentRootWorkAdmission(async () => {
n = true;
const e = captureOpenClawStateWorkerContext();
const r = e.admission.assertCurrent;
const i = scope?.now() ?? Date.now();
if (nextHistorySweepAtMs <= i) {
nextHistorySweepAtMs = Infinity;
try {
const t = await maintainCronRunHistory(e, r);
r();
nextHistorySweepAtMs = Math.min(nextHistorySweepAtMs, t.nextSweepAtMs ?? Infinity);
} catch (e) {
nextHistorySweepAtMs = Math.min(nextHistorySweepAtMs, i + 6e4);
throw e;
}
}
if (nextRegistrySweepAtMs <= i) {
nextRegistrySweepAtMs = Infinity;
try {
const e = await runSessionRegistryMaintenance({
apply: true,
assertCurrent: r,
cronStorePath: t()
});
r();
nextRegistrySweepAtMs = Math.min(nextRegistrySweepAtMs, e.nextSweepAtMs ?? Infinity);
if (e.skippedReason) log.warn("Session registry maintenance skipped", {
reason: e.skippedReason,
retryAtMs: nextRegistrySweepAtMs,
lastSuccessAtMs: lastRegistrySuccessAtMs
});
else {
lastRegistrySuccessAtMs = scope?.now() ?? Date.now();
log.info("Session registry maintenance completed", {
lastSuccessAtMs: lastRegistrySuccessAtMs,
nextSweepAtMs: Number.isFinite(nextRegistrySweepAtMs) ? nextRegistrySweepAtMs : null,
pruned: e.pruned,
skippedStores: e.skippedStores
});
}
} catch (e) {
nextRegistrySweepAtMs = Math.min(nextRegistrySweepAtMs, (scope?.now() ?? Date.now()) + 6e4);
if (!isAgentDatabaseDeletionSnapshotChangedError(e)) throw e;
log.warn("Session registry maintenance deferred", {
reason: "agent-database-snapshot-changed",
retryAtMs: nextRegistrySweepAtMs,
lastSuccessAtMs: lastRegistrySuccessAtMs
});
}
}
}, "cron:maintenance", e);
} catch (t) {
const r = scope?.now() ?? Date.now();
if (nextHistorySweepAtMs <= r) nextHistorySweepAtMs = r + 6e4;
if (nextRegistrySweepAtMs <= r) nextRegistrySweepAtMs = r + 6e4;
if (n || !e.aborted && !isGatewayRestartDrainError(t)) log.warn("Cron maintenance failed", { error: t });
}
}
/** Gateway lifecycle owns retention even when scheduled execution is disabled. */
function startCronMaintenance(e, t) {
if (scope && !scope.signal.aborted) return;
scope = e.scope();
const n = AsyncLocalStorage.bind(() => {
if (!scope || scope.signal.aborted || scheduledSweep) return;
const e = Math.min(nextHistorySweepAtMs, nextRegistrySweepAtMs);
if (!Number.isFinite(e)) return;
const { signal: r } = scope;
scope.schedule({
id: "cron-maintenance",
atMs: e,
run: () => scheduledSweep ??= sweep(r, t).finally(() => {
scheduledSweep = void 0;
n();
})
});
});
lastRegistrySuccessAtMs = null;
nextHistorySweepAtMs = nextRegistrySweepAtMs = scope.now() + 5e3;
const invalidateHistory = () => {
if (scope) {
nextHistorySweepAtMs = Math.min(nextHistorySweepAtMs, scope.now() + 6e4);
n();
}
};
unsubscribeHistoryChanges = subscribeCronRunHistoryChanges((e) => {
if (normalizeDatabasePath(e) === resolveOpenClawStateSqlitePath()) invalidateHistory();
});
unsubscribeDatabaseLifecycle = registerOpenClawStateDatabaseLifecycleListener((e) => {
if (e.kind !== "opened") invalidateHistory();
});
unsubscribeSessionChanges = sessionChanges.subscribeFacts((e) => {
if (!("all" in e ? e.scope === "config" || sessionChangeScopeAffectsStoredRows(e) : sessionChangeScopeAffectsStoredRows(e) && isCronRunSessionKey(e.sessionKey))) return;
if (scope) {
const t = "all" in e && typeof e.scope === "object" && e.scope.topology === true;
nextRegistrySweepAtMs = Math.min(nextRegistrySweepAtMs, scope.now() + (t ? 0 : 6e4));
}
n();
});
n();
}
async function stopCronMaintenance() {
unsubscribeSessionChanges?.();
unsubscribeSessionChanges = void 0;
unsubscribeHistoryChanges?.();
unsubscribeHistoryChanges = void 0;
unsubscribeDatabaseLifecycle?.();
unsubscribeDatabaseLifecycle = void 0;
await Promise.all([scope?.stop(), scheduledSweep]);
}
//#endregion
export { startCronMaintenance, stopCronMaintenance };