UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

157 lines (156 loc) • 6.45 kB
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { c as listOpenClawRegisteredAgentDatabases } from "./openclaw-agent-db-registry-listing-CbXBL50a.mjs"; import "./openclaw-agent-db-CwXW4hGa.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import { i as retireLegacySessionCostUsageCache, t as openUsageCostRefreshFailures } from "./session-cost-usage-refresh-health-Cop3TQMY.mjs"; import { i as maybeScrubConfigAuditLog } from "./doctor-config-audit-scrub-CfY6NM7Z.mjs"; import { n as runDoctorAgentDatabaseOperationAsync } from "./doctor-agent-database-operation-BYsIdRWr.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import os from "node:os"; //#region src/commands/doctor-usage-cost-cache.ts const LEGACY_USAGE_COST_TEMP_GRACE_MS = 1e4; const LEGACY_USAGE_COST_TEMP_PATTERNS = [ /^\.usage-cost-cache\.\d+\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/u, /^\.usage-cost-cache(?:\.json)?\.\d+\.tmp$/u, /^\.usage-cost-cache\.json\.lock\.\d+(?:\.\d+)?\.tmp$/u ]; async function readFilesystemEntryOrMissing(e, t) { try { return await t(); } catch (t) { if (hasErrnoCode(t, "ENOENT")) return null; throw new Error(`${shortenHomePath(e)}: ${formatErrorMessage(t)}`, { cause: t }); } } async function detectLegacyUsageCostCacheFiles(e = process.env) { const t = resolveStateDir(e, os.homedir); const n = [path.join(t, "sessions")]; const r = path.join(t, "agents"); const i = await readFilesystemEntryOrMissing(r, () => fs.readdir(r, { withFileTypes: true })) ?? []; for (const e of i) if (e.isDirectory()) n.push(path.join(r, e.name, "sessions")); const a = []; for (const e of n) { const t = await readFilesystemEntryOrMissing(e, () => fs.readdir(e, { withFileTypes: true })) ?? []; for (const n of t) { if (!n.isFile()) continue; const t = path.join(e, n.name); if (n.name === ".usage-cost-cache.json" || n.name === ".usage-cost-cache.json.lock") { a.push(t); continue; } if (LEGACY_USAGE_COST_TEMP_PATTERNS.some((e) => e.test(n.name))) { const e = await readFilesystemEntryOrMissing(t, () => fs.stat(t)); if (e && Date.now() - e.mtimeMs >= LEGACY_USAGE_COST_TEMP_GRACE_MS) a.push(t); } } } return a.toSorted(); } async function maybeRemoveLegacyUsageCostCacheFiles(e) { const t = await detectLegacyUsageCostCacheFiles(e.env).catch((t) => { const n = e.shouldRepair ? "openclaw doctor --fix" : "openclaw doctor"; const r = e.shouldRepair ? "scan and cleanup" : "scan"; note([ `Legacy usage-cost cache ${r} could not be completed; ${e.shouldRepair ? "no sidecar files were removed" : "cache state may remain uninspected"}.`, `- ${formatErrorMessage(t)}`, `Resolve the filesystem error and rerun \`${n}\`.` ].join("\n"), "Usage cost cache"); return null; }); if (!t?.length) return; if (!e.shouldRepair) { note(`${t.length} rebuildable usage-cost cache ${t.length === 1 ? "file remains" : "files remain"}. Run \`openclaw doctor --fix\` to remove ${t.length === 1 ? "it" : "them"}.`, "Usage cost cache"); return; } const n = []; for (const e of t) await fs.rm(e, { force: true }).catch((t) => { n.push(`${e}: ${String(t)}`); }); if (n.length > 0) { note(`Failed removing legacy usage-cost cache files:\n${n.join("\n")}`, "Usage cost cache"); return; } note(`Removed ${t.length} rebuildable legacy usage-cost cache ${t.length === 1 ? "file" : "files"}; SQLite rebuilds the cache on demand.`, "Usage cost cache"); } async function maybeRemoveLegacySkillUploadTree(e) { const t = resolveStateDir(e.env ?? process.env, os.homedir); const n = path.join(t, "tmp", "skill-uploads"); try { await fs.lstat(n); if (!e.shouldRepair) { note("Legacy skill-upload staging remains. Run `openclaw doctor --fix` to discard it; active uploads now live in SQLite and must be retried.", "Skill uploads"); return; } await fs.rm(n, { recursive: true, force: true }); } catch (t) { if (!hasErrnoCode(t, "ENOENT")) note(`Failed ${e.shouldRepair ? "removing" : "inspecting"} legacy skill-upload staging: ${String(t)}`, "Skill uploads"); return; } note("Removed legacy skill-upload staging; unfinished transient uploads must be retried.", "Skill uploads"); } async function maybeRemoveObsoleteControlUiAssetCache(e) { const t = path.join(resolveStateDir(e.env ?? process.env, os.homedir), "cache", "control-ui-assets"); try { await fs.lstat(t); if (!e.shouldRepair) { note(`Obsolete Control UI asset cache remains at ${shortenHomePath(t)}. Run \`openclaw doctor --fix\` to remove it.`, "Control UI assets"); return []; } await fs.rm(t, { recursive: true, force: true }); note(`Removed obsolete Control UI asset cache at ${shortenHomePath(t)}.`, "Control UI assets"); } catch (n) { if (!hasErrnoCode(n, "ENOENT")) { const r = `Could not ${e.shouldRepair ? "remove" : "inspect"} obsolete Control UI asset cache at ${shortenHomePath(t)}: ${formatErrorMessage(n)}. Resolve the filesystem error and rerun \`openclaw doctor --fix\`.`; note(r, "Doctor warnings"); return [r]; } } return []; } async function maybeRepairLegacyRuntimeFiles(e, t) { const n = await openUsageCostRefreshFailures(t).entries().catch((e) => { note(`Could not read usage refresh failure history: ${formatErrorMessage(e)}`, "Usage cost cache"); return []; }); if (n.length > 0) note(n.map(({ value: e }) => `- ${e.agentId}: ${e.sessionFile}: ${e.reason}`).join("\n"), "Usage cost cache"); await maybeScrubConfigAuditLog({ shouldRepair: e, env: t }); await maybeRemoveLegacyUsageCostCacheFiles({ shouldRepair: e, env: t }); if (e) for (const e of listOpenClawRegisteredAgentDatabases({ env: t })) await runDoctorAgentDatabaseOperationAsync({ agentId: e.agentId, path: e.path, run: async () => { if ((await readFilesystemEntryOrMissing(e.path, () => fs.stat(e.path)))?.isFile()) await retireLegacySessionCostUsageCache({ agentId: e.agentId, env: t, databasePath: e.path }); } }); await maybeRemoveLegacySkillUploadTree({ shouldRepair: e, env: t }); return await maybeRemoveObsoleteControlUiAssetCache({ shouldRepair: e, env: t }); } //#endregion export { maybeRepairLegacyRuntimeFiles };