UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

506 lines (505 loc) • 18.8 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { i as resolveRealpathOrAbsolute } from "./boundary-path-C2gXEiXe.mjs"; import { i as isPathStrictlyInside } from "./path-guards-TIjxtj6H.mjs"; import { n as ok, t as err } from "./result-CV1-31DB.mjs"; import { i as isPrimarySessionTranscriptFileName, r as isCompactionCheckpointTranscriptFileName } from "./transcript-file-names-mCC_xfFb.mjs"; import { a as isSessionArchiveArtifactName, d as resolveTrajectoryPointerPath, i as isRetainedSessionTranscriptArchiveName, o as isSessionStoreTempArtifactName, r as isMigrationArchiveArtifactName, s as isTrajectorySessionArtifactName, t as SESSION_STORE_TEMP_STALE_MS, u as resolveTrajectoryPath } from "./artifacts-D7SzhQlr.mjs"; import { a as resolveSessionArtifactDirectory, o as resolveSessionFilePathCore } from "./paths-DvQ5AJvD.mjs"; import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-CoHTemu-.mjs"; import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs"; import { r as getChildLogger } from "./logger-1QDNfT7Y.mjs"; import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs"; import { s as registerOpenClawAgentDatabaseReadCandidateResource } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs"; import { t as WorkerTaskPool } from "./worker-task-pool-BshJjv1P.mjs"; import "./session-sqlite-target-C8iD4yIo.mjs"; import { n as captureSessionStoreReadCandidates } from "./session-store-target-inventory-Cf7beBnr.mjs"; import { i as isSessionEntryDiskBudgetEvictable } from "./store-maintenance-Ba-_6wiR.mjs"; import { l as readLegacyCompactionSnapshotPaths } from "./session-accessor.sqlite-references-sJ03Zh3Z.mjs"; import { i as projectSessionStoreForPersistence } from "./skill-prompt-blobs-C6j7yo4W.mjs"; import fs from "node:fs"; import path from "node:path"; import { performance } from "node:perf_hooks"; import pMap from "p-map"; //#region src/config/sessions/disk-budget-files.ts const SESSIONS_DIR_STAT_CONCURRENCY = 8; async function removeFileIfExists(e) { const t = await fs.promises.stat(e).catch(() => null); if (!t?.isFile()) return err("not-removed"); getOpenClawDatabaseMaintenanceScope()?.assertAdmission(); return fs.promises.rm(e).then(() => ok(t.size), () => err("not-removed")); } function readSessionFileStat(e) { return fs.promises.stat(e).then((t) => t.isFile() ? { path: e, canonicalPath: resolveRealpathOrAbsolute(e), name: path.basename(e), size: t.size, mtimeMs: t.mtimeMs } : null, () => null); } async function readSessionsDirFiles(e) { const t = await fs.promises.readdir(e, { withFileTypes: true }).catch(() => []); return (await pMap(t.filter((e) => e.isFile() && !isMigrationArchiveArtifactName(e.name)), (t) => readSessionFileStat(path.join(e, t.name)), { concurrency: SESSIONS_DIR_STAT_CONCURRENCY })).filter((e) => Boolean(e)); } async function readSessionPromptBlobFiles(e) { const t = path.join(e, "skills-prompts", "sha256"); const n = await fs.promises.readdir(t, { withFileTypes: true }).catch(() => []); const r = []; for (const e of n) { if (!e.isDirectory() || !/^[a-f0-9]{2}$/u.test(e.name)) continue; const n = path.join(t, e.name); const i = await fs.promises.readdir(n, { withFileTypes: true }).catch(() => []); for (const e of i) { if (!e.isFile() || !/^[a-f0-9]{64}\.txt$/u.test(e.name) && !isSessionPromptBlobTempArtifactName(e.name)) continue; const t = await readSessionFileStat(path.join(n, e.name)); if (t) r.push(t); } } return r; } function isSessionPromptBlobTempArtifactName(e) { return /^[a-f0-9]{64}\.txt\.(?:\d+\.)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/u.test(e); } //#endregion //#region src/config/sessions/disk-budget-runtime.ts const measurements = resolveGlobalSingleton(Symbol.for("openclaw.sessionDiskBudgetWorkers"), () => ({ pool: new WorkerTaskPool({ workerUrl: resolveRuntimeProcessEntrypointUrl("sessionDiskBudget"), workerClass: "reader" }), pending: /* @__PURE__ */ new Set() }), () => drainSessionDiskBudgetWorkers()); /** Join admitted scans before retiring workers; later measurements reuse the pool. */ function drainSessionDiskBudgetWorkers() { return measurements.draining ??= Promise.resolve().then(async () => { while (measurements.pending.size > 0) await Promise.allSettled(measurements.pending); await measurements.pool.rotate(); }).finally(() => { measurements.draining = void 0; }); } /** Captures database cleanup custody, then measures physical artifacts in a worker. */ async function measureSessionPhysicalDiskUsage(e) { const t = []; let n; const close = async () => { try { await n; } catch { await measurements.pool.retryFailedRetirements(); } t.splice(0).forEach((e) => e()); }; try { for (const n of captureSessionStoreReadCandidates(e)) for (const e of /* @__PURE__ */ new Set([n.path, n.physicalPath])) t.push(registerOpenClawAgentDatabaseReadCandidateResource({ path: e, scope: n.scope, revoke: () => {}, close })); n = measurements.pool.run(path.resolve(e), {}); measurements.pending.add(n); return await n; } finally { if (n) measurements.pending.delete(n); await close(); } } //#endregion //#region src/config/sessions/session-history-archive-pruning-diagnostics.ts function archivePruningLogFields(e) { const milliseconds = (e) => e === void 0 ? void 0 : Math.round(e); return { trigger: e.trigger, highWaterBytes: e.highWaterBytes, checkpointCalls: e.checkpointCalls, checkpointIncomplete: e.checkpointIncomplete, checkpoint: e.checkpoint, totalBytesBefore: e.totalBytesBefore, totalBytesAfter: e.totalBytesAfter, walBytesBefore: e.walBytesBefore, walBytesAfter: e.walBytesAfter, checkpointMs: milliseconds(e.checkpointMs), checkpointMaxMs: milliseconds(e.checkpointMaxMs), vacuumMs: milliseconds(e.vacuumMs), vacuumPasses: e.vacuumPasses, vacuumPagesRequested: e.vacuumPagesRequested, queryMs: milliseconds(e.queryMs), rowDeletionMs: milliseconds(e.rowDeletionMs), fileRemovalMs: milliseconds(e.fileRemovalMs), removedFiles: e.removedFiles, missingFiles: e.missingFiles, failedRemovals: e.failedRemovals, measurementMs: milliseconds(e.measurementMs), measurements: e.measurements, legacyInventoryMs: milliseconds(e.legacyInventoryMs), completed: e.completed === true }; } async function observeSessionArchivePruning(e, t) { const n = performance.now(); let r = true; try { const e = await t(); r = false; return e; } finally { const t = performance.now() - n; if (r || t >= 1e3) try { getChildLogger({ subsystem: "session-sqlite" }).warn(r ? "SQLite session archive pruning failed" : "slow SQLite session archive pruning", { elapsedMs: Math.round(t), archivePruning: archivePruningLogFields(e) }); } catch {} } } async function timeArchivePruningAsync(e, t, n) { if (!e) return await n(); if (t === "measurementMs") e.measurements = (e.measurements ?? 0) + 1; const r = performance.now(); try { return await n(); } finally { e[t] = (e[t] ?? 0) + performance.now() - r; } } //#endregion //#region src/config/sessions/disk-budget.ts function measureStoreBytes(e) { return Buffer.byteLength(JSON.stringify(e, null, 2), "utf-8"); } function resolveProjectedPromptBlobHash(e) { const t = e?.skillsSnapshot?.promptRef; return t?.algorithm === "sha256" && typeof t.hash === "string" ? t.hash : void 0; } function buildSessionEntryRefCounts(e, t) { const n = /* @__PURE__ */ new Map(); for (const r of Object.values(e)) { const e = t(r); if (!e) continue; n.set(e, (n.get(e) ?? 0) + 1); } return n; } function resolveSessionArtifactPathsForEntry(e) { if (!e.entry.sessionId) return []; let t; try { const n = resolveSessionFilePathCore(e.entry.sessionId, e.entry, { sessionsDir: e.sessionsDir }); const r = resolveRealpathOrAbsolute(e.sessionsDir); const i = resolveRealpathOrAbsolute(n); const a = path.relative(r, i); if (!a || a.startsWith("..") || path.isAbsolute(a)) return []; t = i; } catch { return []; } return [ t, resolveTrajectoryPointerPath(t) ?? `${t}.trajectory-path.json`, resolveTrajectoryPath(t) ?? `${t}.trajectory.jsonl` ]; } function resolveSessionArtifactCanonicalPathsForEntry(e) { return resolveSessionArtifactPathsForEntry(e).map(resolveRealpathOrAbsolute); } function resolveReferencedSessionArtifactPaths(e) { const t = /* @__PURE__ */ new Set(); if (!e.files.some((e) => isUnreferencedSessionArtifactFile(e, t))) return t; const n = resolveRealpathOrAbsolute(e.sessionsDir); for (const r of Object.values(e.store)) { for (const n of resolveSessionArtifactCanonicalPathsForEntry({ sessionsDir: e.sessionsDir, entry: r })) t.add(n); for (const e of readLegacyCompactionSnapshotPaths(r)) { const r = resolveRealpathOrAbsolute(e); if (isPathStrictlyInside(n, r)) t.add(r); } } return t; } async function hasRetainedSessionTranscriptArchives(e) { return (await readSessionsDirFiles(resolveSessionArtifactDirectory(e))).some((e) => isRetainedSessionTranscriptArchiveName(e.name)); } /** Removes oldest retained archives and legacy compact backups, remeasuring after each file. */ async function pruneSessionTranscriptArchivesToHighWater(e) { const { diagnostics: t } = e; const n = await timeArchivePruningAsync(t, "legacyInventoryMs", async () => (await readSessionsDirFiles(resolveSessionArtifactDirectory(e.storePath))).filter((e) => isRetainedSessionTranscriptArchiveName(e.name)).toSorted((e, t) => e.mtimeMs - t.mtimeMs)); let r = await timeArchivePruningAsync(t, "measurementMs", () => measureSessionPhysicalDiskUsage(e.storePath)); let i = 0; for (const a of n) { if (r.totalBytes <= e.highWaterBytes) break; const n = e.removeFile ? await e.removeFile(a) : (await timeArchivePruningAsync(t, "fileRemovalMs", () => removeFileIfExists(a.path))).ok ? "removed" : "failed"; if (n === "failed") { if (t) t.failedRemovals = (t.failedRemovals ?? 0) + 1; continue; } if (n === "removed") { i += 1; if (t) t.removedFiles = (t.removedFiles ?? 0) + 1; } r = await timeArchivePruningAsync(t, "measurementMs", () => measureSessionPhysicalDiskUsage(e.storePath)); } return { removedFiles: i, usage: r }; } function resolvePromptBlobFileHash(e) { return /^[a-f0-9]{64}\.txt$/u.test(e.name) ? e.name.slice(0, -4) : void 0; } function isUnreferencedSessionArtifactFile(e, t) { if (t.has(e.canonicalPath)) return false; return isCompactionCheckpointTranscriptFileName(e.name) || isTrajectorySessionArtifactName(e.name) || isPrimarySessionTranscriptFileName(e.name); } const SESSION_PROMPT_BLOB_UNREFERENCED_GRACE_MS = SESSION_STORE_TEMP_STALE_MS; function isPromptBlobArtifactRemovable(e, t, n, r) { if (isSessionPromptBlobTempArtifactName(e.name)) return e.mtimeMs <= r; if (e.mtimeMs > n) return false; const i = resolvePromptBlobFileHash(e); return i ? !t.has(i) : false; } function isDiskBudgetRemovableSessionFile(e, t, n, r) { if (isSessionStoreTempArtifactName(e.name, r)) return e.mtimeMs <= n; return isSessionArchiveArtifactName(e.name) || isUnreferencedSessionArtifactFile(e, t); } async function removePromptBlobFileForBudget(e) { const t = await fs.promises.stat(e.file.path).catch(() => null); if (!t?.isFile()) return err("not-removed"); if (!isPromptBlobArtifactRemovable({ name: e.file.name, mtimeMs: t.mtimeMs }, e.projectedPromptBlobRefCounts, e.promptBlobCutoffMs, e.tempCutoffMs)) return err("not-removed"); return removeFileIfExists(path.resolve(e.file.path)); } async function pruneUnreferencedSessionArtifacts(e) { const t = Number.isFinite(e.olderThanMs) && e.olderThanMs > 0 ? e.olderThanMs : 0; const n = resolveSessionArtifactDirectory(e.storePath); const r = await readSessionsDirFiles(n); const i = await readSessionPromptBlobFiles(n); if (r.length === 0 && i.length === 0) return { scannedFiles: 0, removedFiles: 0, freedBytes: 0, olderThanMs: t }; const a = typeof e.store === "function" ? await e.store() : e.store; const o = new Map([...r, ...i].map((e) => [e.canonicalPath, e.size])); const s = /* @__PURE__ */ new Set(); const c = Date.now(); const l = c - t; const u = c - SESSION_STORE_TEMP_STALE_MS; const d = c - Math.max(t, SESSION_PROMPT_BLOB_UNREFERENCED_GRACE_MS); const f = resolveReferencedSessionArtifactPaths({ files: r.filter((t) => t.mtimeMs <= l && !e.excludeCanonicalPaths?.has(t.canonicalPath)), sessionsDir: n, store: a }); const p = i.length > 0 ? buildSessionEntryRefCounts(projectSessionStoreForPersistence({ storePath: e.storePath, store: a }).store, resolveProjectedPromptBlobHash) : /* @__PURE__ */ new Map(); const m = path.basename(e.storePath); const h = r.filter((t) => { if (e.excludeCanonicalPaths?.has(t.canonicalPath)) return false; if (isSessionStoreTempArtifactName(t.name, m)) return t.mtimeMs <= u; return t.mtimeMs <= l && isUnreferencedSessionArtifactFile(t, f); }); const g = i.filter((t) => { if (e.excludeCanonicalPaths?.has(t.canonicalPath)) return false; return isPromptBlobArtifactRemovable(t, p, d, u); }); const _ = [...h.map((e) => ({ kind: "store", file: e })), ...g.map((e) => ({ kind: "promptBlob", file: e }))].toSorted((e, t) => e.file.mtimeMs - t.file.mtimeMs); let v = 0; let y = 0; const b = e.dryRun === true; for (const e of _) { if (b) { const t = e.file.canonicalPath; const n = o.get(t); if (n !== void 0 && !s.has(t)) { s.add(t); v += 1; y += n; } continue; } const t = e.kind === "promptBlob" ? await removePromptBlobFileForBudget({ file: e.file, projectedPromptBlobRefCounts: p, promptBlobCutoffMs: d, tempCutoffMs: u }) : await removeFileIfExists(path.resolve(e.file.path)); if (!t.ok) continue; v += 1; y += t.value; } return { scannedFiles: r.length + i.length, removedFiles: v, freedBytes: y, olderThanMs: t }; } async function enforceSessionDiskBudget(e) { const t = e.maintenance.maxDiskBytes; const n = e.maintenance.highWaterBytes; if (t == null || n == null) return; const r = e.log; const i = resolveSessionArtifactDirectory(e.storePath); const a = await readSessionsDirFiles(i); const o = await readSessionPromptBlobFiles(i); const s = resolveRealpathOrAbsolute(e.storePath); const c = a.find((e) => e.canonicalPath === s); const l = projectSessionStoreForPersistence({ storePath: e.storePath, store: e.store }); const u = l.store; let d = measureStoreBytes(u); const f = /* @__PURE__ */ new Map(); const p = /* @__PURE__ */ new Map(); for (const e of o) { const t = resolvePromptBlobFileHash(e); if (t) p.set(t, e); } for (const [e, t] of l.promptBlobs) if (!p.has(e)) f.set(e, t.ref.bytes); const m = buildSessionEntryRefCounts(u, resolveProjectedPromptBlobHash); const h = [...f.values()].reduce((e, t) => e + t, 0); let g = [...a, ...o].reduce((e, t) => e + t.size, 0) - (c?.size ?? 0) + d + h; const _ = g; const v = !(g <= t); if (!v || e.warnOnly) { if (v) r?.warn("session disk budget exceeded (warn-only mode)", { sessionsDir: i, totalBytes: g, maxBytes: t, highWaterBytes: n }); return; } let y = 0; let b = 0; const recordRemoval = (e) => { if (e.ok) { g -= e.value; y += 1; } }; const x = e.commitEvictedIndex; const S = resolveReferencedSessionArtifactPaths({ files: a, sessionsDir: i, store: e.store }); const C = Date.now() - SESSION_STORE_TEMP_STALE_MS; const w = Date.now() - SESSION_PROMPT_BLOB_UNREFERENCED_GRACE_MS; const T = path.basename(e.storePath); const E = o.filter((e) => isPromptBlobArtifactRemovable(e, m, w, C)).toSorted((e, t) => e.mtimeMs - t.mtimeMs); for (const e of E) { if (g <= n) break; recordRemoval(await removePromptBlobFileForBudget({ file: e, projectedPromptBlobRefCounts: m, promptBlobCutoffMs: w, tempCutoffMs: C })); } const D = a.filter((e) => isDiskBudgetRemovableSessionFile(e, S, C, T)).toSorted((e, t) => e.mtimeMs - t.mtimeMs); for (const e of D) { if (g <= n) break; recordRemoval(await removeFileIfExists(path.resolve(e.path))); } if (g > n) { const t = buildSessionEntryRefCounts(e.store, (e) => e?.sessionId); const r = new Map(Object.entries(u).map(([e, t]) => [e, measureStoreBytes({ [e]: t }) - 4])); const a = Object.keys(e.store).filter((t) => isSessionEntryDiskBudgetEvictable({ key: t, entry: e.store[t], preserveKeys: e.preserveKeys, preserveRecentMs: e.maintenance.preserveRecentMs })).toSorted((t, n) => (e.store[t]?.archivedAt ?? Number.POSITIVE_INFINITY) - (e.store[n]?.archivedAt ?? Number.POSITIVE_INFINITY) || t.localeCompare(n)); for (const o of a) { if (g <= n) break; const a = e.store[o]; if (!a) continue; const s = d; const c = u[o]; const l = resolveProjectedPromptBlobHash(c); delete e.store[o]; delete u[o]; const h = r.get(o); r.delete(o); if (typeof h === "number" && Number.isFinite(h) && h >= 0) d = Math.max(2, d - (h + 2)); else d = measureStoreBytes(u); g += d - s; b += 1; if (x) { await x(); if (f.size > 0) for (const e of await readSessionPromptBlobFiles(i)) { const t = resolvePromptBlobFileHash(e); if (t && f.delete(t)) p.set(t, e); } } if (l) { const e = (m.get(l) ?? 1) - 1; if (e > 0) m.set(l, e); else { m.delete(l); const e = f.get(l) ?? 0; if (e > 0) { g -= e; f.delete(l); } else { const e = p.get(l); if (e && x) recordRemoval(await removePromptBlobFileForBudget({ file: e, projectedPromptBlobRefCounts: m, promptBlobCutoffMs: w, tempCutoffMs: C })); } } } const _ = a.sessionId; if (!_) continue; const v = (t.get(_) ?? 1) - 1; if (v > 0) { t.set(_, v); continue; } t.delete(_); if (!x) continue; for (const e of resolveSessionArtifactPathsForEntry({ sessionsDir: i, entry: a })) recordRemoval(await removeFileIfExists(path.resolve(e))); } } if (g > n) r?.warn("session disk budget still above high-water target after cleanup", { sessionsDir: i, totalBytes: g, maxBytes: t, highWaterBytes: n, removedFiles: y, removedEntries: b }); else if (y > 0 || b > 0) r?.info("applied session disk budget cleanup", { sessionsDir: i, totalBytesBefore: _, totalBytesAfter: g, maxBytes: t, highWaterBytes: n, removedFiles: y, removedEntries: b }); } //#endregion export { resolveSessionArtifactCanonicalPathsForEntry as a, measureSessionPhysicalDiskUsage as c, pruneUnreferencedSessionArtifacts as i, hasRetainedSessionTranscriptArchives as n, observeSessionArchivePruning as o, pruneSessionTranscriptArchivesToHighWater as r, timeArchivePruningAsync as s, enforceSessionDiskBudget as t };