UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 2.85 kB
import{r as canonicalPathFromExistingAncestor}from"./fs-safe-Bxzu1j4h.mjs";import{i as isMissingPathError}from"./errno-DUBt6SQQ.mjs";import{i as readErrorCause}from"./errors-D37BJTfI.mjs";import{i as logWarn}from"./logger-BHIcoxTH.mjs";import{c as runWithAgentToolSourceExecutionScope,i as captureAgentToolSourceExecutionGuard}from"./agent-tool-source-execution-guard-D2z6vTFX.mjs";import{a as recordMemoryArtifactWriteProvenance,r as normalizeMemoryArtifactRelativePath,t as clearMemoryArtifactProvenance}from"./memory-artifact-provenance-Bd8naUWA.mjs";import path from"node:path"; //!src/agents/memory-write-provenance.ts function withMemoryWriteProvenance(e,t){if(!t)return e;const readContentBefore=(t,n)=>e.readFile(t,n).then(e=>Buffer.isBuffer(e)?e.toString(`utf8`):e).catch(e=>{if(!isMissingPathError(e)&&!isMissingPathError(readErrorCause(e)))throw e;return``});const n=e.remove;return{...e,writeFile:async(n,r,i)=>{const a=captureAgentToolSourceExecutionGuard();const commit=()=>runWithAgentToolSourceExecutionScope(a,async()=>{a();await e.writeFile(n,r,i)});if(!await t.classifies(n)){await commit();return}await t.write({absolutePath:n,contentBefore:await readContentBefore(n,i),contentAfter:r,commit})},...n?{remove:async e=>{const r=captureAgentToolSourceExecutionGuard();const i=await t.classifies(e)?await readContentBefore(e):``;await runWithAgentToolSourceExecutionScope(r,async()=>{r();await n(e)});await t.clearAfterDelete(e,i)}}:{}}}function resolveMemoryRelativePath(e,t){const n=path.relative(e,t);if(!n||path.isAbsolute(n)||n===`..`||n.startsWith(`..${path.sep}`))return;return normalizeMemoryArtifactRelativePath(n.replaceAll(path.sep,`/`))}function createMemoryWriteProvenanceObserver(e){const t=e.now??Date.now;const n=e.resolvePath??canonicalPathFromExistingAncestor;const resolveRelativePath=async t=>{const[r,i]=await Promise.all([n(e.mutationRoot),n(t)]);return resolveMemoryRelativePath(r,i)};return{classifies:async e=>await resolveRelativePath(e)!==void 0,write:async({absolutePath:n,contentBefore:r,contentAfter:i,commit:a})=>{const o=await resolveRelativePath(n);if(!o){await a();return}const s=await recordMemoryArtifactWriteProvenance({workspaceDir:e.workspaceDir,relativePath:o,contentBefore:r,contentAfter:i,originClass:e.resolveOriginClass(),observedAt:t(),sessionId:e.sessionId,sessionKey:e.sessionKey});try{await a()}catch(e){try{await s?.()}catch(t){throw new Error(`File write failed and memory provenance rollback also failed: ${String(e)}`,{cause:t})}throw e}},clearAfterDelete:async(t,n)=>{const r=await resolveRelativePath(t);if(!r)return;try{await clearMemoryArtifactProvenance({workspaceDir:e.workspaceDir,relativePath:r,contentBefore:n})}catch(e){logWarn(`memory provenance cleanup failed for ${r}: ${String(e)}`)}}}}export{withMemoryWriteProvenance as n,createMemoryWriteProvenanceObserver as t};