UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4 lines • 7.01 kB
import{r as resolveOsHomeDir}from"./home-dir-DrOv-SYd.mjs";import{t as expandHomePrefix}from"./home-dir-DEN5DisQ.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as resolveOpenClawPackageRootSync}from"./openclaw-root-DP80HYD2.mjs";import{t as resolveConfigDir}from"./config-dir-DaqnOvHp.mjs";import{f as shortenHomePath}from"./utils-Dlk0IYAa.mjs";import{r as hydrateSessionStoreSkillPromptRefs}from"./skill-prompt-blobs-Dpa-q0ZJ.mjs";import{a as resolveAllAgentSessionStoreTargetsSync}from"./targets-DZpbOEi4.mjs";import{t as decodeXml}from"./xml-CHe3sJCs.mjs";import{t as resolveBundledSkillsDir}from"./bundled-dir-BeZ0g1Uz.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import fs from"node:fs";import path from"node:path"; //!src/commands/doctor-session-snapshots.ts 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}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.`}}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(` `),`Session snapshots`)}export{detectSessionSnapshotHealthIssues,noteSessionSnapshotHealth,sessionSnapshotIssueToHealthFinding};