UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

222 lines (221 loc) • 8.35 kB
import { r as resolveOsHomeDir } from "./home-dir-zhqynwRJ.mjs"; import { t as expandHomePrefix } from "./home-dir-EKmgmdPG.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as resolveConfigDir } from "./config-dir-DMqvtq2W.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import { r as resolveOpenClawPackageRootSync } from "./openclaw-root-C-ayo09z.mjs"; import { a as resolveAllAgentSessionStoreTargetsSync } from "./targets-BVE0__Jb.mjs"; import { r as hydrateSessionStoreSkillPromptRefs } from "./skill-prompt-blobs-C6j7yo4W.mjs"; import { t as decodeXml } from "./xml-CkRZ_Nxa.mjs"; import { t as resolveBundledSkillsDir } from "./bundled-dir-CA3F7BMY.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import fs from "node:fs"; import path from "node:path"; //#region src/commands/doctor-session-snapshots.ts /** Advisory inspection of runtime snapshot paths retained in legacy session stores. */ const SESSION_SNAPSHOTS_CHECK_ID = "core/doctor/session-snapshots"; function resolveSessionSnapshotBundledSkillsDir() { const e = resolveBundledSkillsDir(); if (e) return e; const t = resolveOpenClawPackageRootSync({ argv1: process.argv[1], moduleUrl: import.meta.url, cwd: process.cwd() }); return t ? path.join(t, "skills") : void 0; } function extractSkillLocations(e) { return typeof e === "string" ? [...e.matchAll(/<location>([\s\S]*?)<\/location>/g)].flatMap((e) => { const t = e[1]?.trim(); return t ? [decodeXml(t)] : []; }) : []; } function collectResolvedSkillPaths(e) { if (!Array.isArray(e)) return []; const t = []; for (const n of e) { if (!isRecord(n)) continue; const e = isRecord(n.sourceInfo) ? n.sourceInfo : void 0; for (const [r, i] of [[n.filePath, n.baseDir], [e?.path, e?.baseDir]]) { if (typeof r === "string" && r.trim()) t.push(r.trim()); if (typeof i === "string" && i.trim()) t.push(path.join(i.trim(), "SKILL.md")); } } return t; } function collectInjectedWorkspaceFilePaths(e) { if (!Array.isArray(e)) return []; return e.map((e) => isRecord(e) && typeof e.path === "string" ? e.path.trim() : "").filter(Boolean); } function collectCachedSnapshotPaths(e) { const t = e.skillsSnapshot; const n = e.systemPromptReport; return [ ["skillsSnapshot.prompt", extractSkillLocations(t?.prompt)], ["skillsSnapshot.resolvedSkills", collectResolvedSkillPaths(t?.resolvedSkills)], ["systemPromptReport.injectedWorkspaceFiles", isRecord(n) ? collectInjectedWorkspaceFilePaths(n.injectedWorkspaceFiles) : []] ].flatMap(([e, t]) => t.map((t) => ({ field: e, path: t }))); } function isAbsolutePathLike(e) { return path.isAbsolute(e) || path.win32.isAbsolute(e); } function splitPathSegments(e) { return e.replace(/^[a-z]:/i, "").replaceAll("\\", "/").split("/").filter(Boolean); } function isWindowsAbsolutePath(e) { return /^[a-z]:/i.test(e) && ["/", "\\"].includes(e.slice(2, 3)) || e.startsWith("\\\\"); } function isBundledRuntimeSkillsPath(e) { const t = e.map((e) => e.toLowerCase()); const n = t.lastIndexOf("openclaw"); return t.some((e) => e === "dist-runtime" || e === "node_modules" || e.startsWith("openclaw@")) || n > 0 && ["tmp", "temp"].includes(t[n - 1]); } function extractBundledSkillRelativeSegments(e) { const t = splitPathSegments(e); const n = t.lastIndexOf("skills"); if (n < 0 || !isBundledRuntimeSkillsPath(t.slice(0, n))) return; const r = t.slice(n + 1); if (r.length < 2 || r.at(-1) !== "SKILL.md") return; return r; } function isInsidePath(e, t) { const n = isWindowsAbsolutePath(e); if (n !== isWindowsAbsolutePath(t)) return false; const r = n ? path.win32 : path; const i = r.relative(r.resolve(e), r.resolve(t)); return i === "" || !i.startsWith("..") && !r.isAbsolute(i); } function joinPathForRoot(e, ...t) { return isWindowsAbsolutePath(e) ? path.win32.join(e, ...t) : path.join(e, ...t); } function resolveExpectedBundledSkillPath(e) { const t = resolveOsHomeDir(e.env); const n = t ? expandHomePrefix(e.cachedPath, { home: t }) : e.cachedPath; if (!isAbsolutePathLike(n)) return; const r = extractBundledSkillRelativeSegments(n); if (!r) return; if (r.join("/") === "imsg/SKILL.md") { const t = path.join(resolveConfigDir(e.env), "plugin-skills", "imsg", "SKILL.md"); if (fs.existsSync(t)) return t; } if (isInsidePath(e.bundledSkillsDir, n)) return; const i = joinPathForRoot(e.bundledSkillsDir, ...r); return fs.existsSync(i) ? i : void 0; } /** Finds cached bundled-skill paths that point at old runtime/temp package roots. */ function scanSessionStoreForStaleRuntimeSnapshotPaths(e) { const t = e.bundledSkillsDir?.trim(); if (!t) return []; const n = []; const r = /* @__PURE__ */ new Set(); for (const [i, a] of Object.entries(e.store)) { if (!a || typeof a !== "object") continue; for (const o of collectCachedSnapshotPaths(a)) { const a = resolveExpectedBundledSkillPath({ cachedPath: o.path, bundledSkillsDir: t, env: e.env }); if (!a) continue; const s = `${i}\0${o.field}\0${o.path}`; if (r.has(s)) continue; r.add(s); n.push({ sessionKey: i, field: o.field, cachedPath: o.path, expectedPath: a }); } } return n; } function loadSessionStoreForSnapshotScan(e) { const t = JSON.parse(fs.readFileSync(e, "utf-8")); if (!isRecord(t)) return {}; const n = t; hydrateSessionStoreSkillPromptRefs({ storePath: e, store: n }); return n; } async function scanSessionSnapshotHealth(e, t) { const n = resolveSessionSnapshotBundledSkillsDir(); const r = []; if (n) { const i = resolveAllAgentSessionStoreTargetsSync(e.cfg, { env: e.env }).map((e) => e.storePath).filter((e) => fs.existsSync(e)).toSorted((e, t) => e.localeCompare(t)); for (const a of i) { let i; try { i = loadSessionStoreForSnapshotScan(a); } catch (e) { t?.(a, e); continue; } const o = scanSessionStoreForStaleRuntimeSnapshotPaths({ store: i, bundledSkillsDir: n, env: e.env }); if (o.length > 0) r.push({ storePath: a, findings: o }); } } return { bundledSkillsDir: n, stores: r }; } async function detectSessionSnapshotHealthIssues(e) { const { stores: t } = await scanSessionSnapshotHealth(e); return t.flatMap(({ storePath: e, findings: t }) => t.map((t) => ({ ...t, storePath: e }))); } function sessionSnapshotIssueToHealthFinding(e) { return { checkId: SESSION_SNAPSHOTS_CHECK_ID, severity: "info", message: `${e.sessionKey} historical session metadata references an inactive runtime root.`, path: e.storePath, target: e.cachedPath, requirement: `Current bundled skill path: ${e.expectedPath}`, fixHint: "No repair is needed for this historical metadata. Doctor preserves migration originals; active sessions use stored SQLite state and the current runtime skill catalog." }; } /** Reports historical snapshot paths without rewriting migration source bytes. */ async function noteSessionSnapshotHealth(e) { const { bundledSkillsDir: t, stores: n } = await scanSessionSnapshotHealth(e, (e, t) => { note(`- Failed to inspect session snapshot metadata in ${shortenHomePath(e)}: ${String(t)}`, "Session snapshots"); }); if (!t) return; const r = new Map(n.map(({ storePath: e, findings: t }) => [e, t])); const i = [...r.values()].reduce((e, t) => e + t.length, 0); if (i === 0) return; const a = new Set([...r.values()].flatMap((e) => e.map((e) => e.sessionKey))); const o = [ `- Found ${a.size} session${a.size === 1 ? "" : "s"} with stale cached session metadata paths.`, ` Live bundled skills root is healthy: ${shortenHomePath(t)}`, " Historical metadata references an inactive runtime root. Originals are preserved; active sessions use stored SQLite state and the current runtime skill catalog. No cleanup or session reset is needed." ]; let s = 0; for (const [e, t] of r) { o.push(` Store: ${shortenHomePath(e)}`); for (const e of t.slice(0, Math.max(0, 10 - s))) { o.push(` - ${e.sessionKey} ${e.field}: ${shortenHomePath(e.cachedPath)} -> ${shortenHomePath(e.expectedPath)}`); s += 1; } if (s >= 10) break; } if (i > s) o.push(` ...and ${i - s} more stale cached path${i - s === 1 ? "" : "s"}.`); note(o.join("\n"), "Session snapshots"); } //#endregion export { detectSessionSnapshotHealthIssues, noteSessionSnapshotHealth, sessionSnapshotIssueToHealthFinding };