UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines • 12.8 kB
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{f as syncDirectoryIfSupported}from"./directory-durability-o_aQCRBZ.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{T as walkDirectory,t as FsSafeError,x as root}from"./fs-safe-Bxzu1j4h.mjs";import{i as isMissingPathError}from"./errno-DUBt6SQQ.mjs";import"./paths-D_FOvGon.mjs";import"./errors-D37BJTfI.mjs";import"./paths-CcxgiC3g.mjs";import"./agent-scope-config-CG9CFpGX.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{n as sha256Hex,r as sha256HexPrefixCore}from"./node-crypto-DPk8agfR.mjs";import"./crypto-digest-T8X5EZni.mjs";import{s as writeFileWindowFully}from"./file-descriptor-CRkf5tcV.mjs";import{t as KeyedAsyncQueue}from"./keyed-async-queue-qBcorzrt.mjs";import{s as withFileLock}from"./file-lock-BXJR2ZD_.mjs";import"./file-lock-BNiiJdHH.mjs";import{w as resolveMemoryDreamingWorkspaces}from"./dreaming-DWa9EF3D.mjs";import"./memory-state-BSED9PTf.mjs";import"./agent-scope-runtime-DKb8jQZx.mjs";import"./memory-core-host-status-mlVnC6Ei.mjs";import{t as listStoredMemoryHostEvents}from"./event-store-DaRWHXuF.mjs";import path from"node:path";import fs from"node:fs/promises";import{readFileHandleBounded,sameFileIdentity}from"@openclaw/fs-safe/advanced"; //!src/memory-host-sdk/event-export.ts const MAX_MEMORY_HOST_PUBLIC_EXPORT_BYTES=1048576;function serializeMemoryHostEventExport(e){const t=[];let n=0;for(const r of e.toReversed()){const e=JSON.stringify(r.value.event);const i=Buffer.byteLength(e,`utf8`)+1;if(n+i>1048576)break;t.push(e);n+=i}return t.toReversed().join(` `)+` `} //!src/plugin-sdk/memory-host-event-export.ts function isRejectedWorkspaceArtifactPath(e){if(!(e instanceof FsSafeError))return false;return e.code===`hardlink`||e.code===`not-file`||e.code===`outside-workspace`||e.code===`path-alias`||e.code===`path-mismatch`||e.code===`symlink`}async function openMemoryHostEventArtifact(e){try{return await e()}catch(e){if(isMissingPathError(e)||isRejectedWorkspaceArtifactPath(e))return;throw e}}function memoryHostEventExportOwnerContent(e,t){return`${JSON.stringify({schemaVersion:4,kind:`openclaw-memory-host-events-export`,stateHash:e.stateHash,workspaceHash:e.workspaceHash,...t.identity?{fileDev:String(t.identity.dev),fileIno:String(t.identity.ino)}:{},...t.currentSha256?{contentSha256:t.currentSha256}:{},...t.pendingSha256?{pendingContentSha256:t.pendingSha256}:{}})}\n`}async function writePinnedMemoryHostEventArtifact(e,t){const n=Buffer.from(t,`utf8`);await writeFileWindowFully(e,n,0);await e.truncate(n.length);await e.chmod(384);await e.sync()}async function rewriteMemoryHostEventArtifactIfUnchanged(e){try{var t=_usingCtx();const r=await openMemoryHostEventArtifact(()=>e.workspaceRoot.open(e.relativePath));if(!r)return false;const i=t.a(r);if(e.expectedIdentity?!sameFileIdentity(e.expectedIdentity,i.exactIdentity):(await readFileHandleBounded(i.handle,Infinity)).toString(`utf8`)!==e.expectedContent)return false;try{var n=_usingCtx();const t=await openMemoryHostEventArtifact(()=>e.workspaceRoot.openWritable(e.relativePath,{mode:384,writeMode:`update`}));if(!t)return false;const r=n.a(t);if(!sameFileIdentity(i.exactIdentity,r.exactIdentity))return false;await r.handle.writeFile(e.nextContent,{encoding:`utf8`});await r.handle.truncate(Buffer.byteLength(e.nextContent,`utf8`));await r.handle.chmod(384);await r.handle.sync()}catch(e){n.e=e}finally{await n.d()}const a=await openMemoryHostEventArtifact(()=>e.workspaceRoot.open(e.relativePath));if(!a)return false;const o=t.a(a);return sameFileIdentity(i.exactIdentity,o.exactIdentity)&&(await readFileHandleBounded(o.handle,Infinity)).toString(`utf8`)===e.nextContent}catch(e){t.e=e}finally{await t.d()}}async function isMemoryHostEventArtifactAtIdentity(e){try{var t=_usingCtx();const n=await openMemoryHostEventArtifact(()=>e.workspaceRoot.open(e.relativePath));if(!n)return false;const r=t.a(n);if(!sameFileIdentity(e.expectedIdentity,r.exactIdentity))return false;return e.expectedContent===void 0||(await readFileHandleBounded(r.handle,Infinity)).equals(Buffer.from(e.expectedContent,`utf8`))}catch(e){t.e=e}finally{await t.d()}}async function publishMemoryHostEventArtifact(e){try{var t=_usingCtx();const n=await openMemoryHostEventArtifact(()=>e.workspaceRoot.openWritable(e.owner.relativePath,{mode:384,writeMode:`replace`}));if(!n)return;const r=t.a(n);if(!r.createdForWrite)return;const i=r.exactIdentity;const isPublishedArtifactCurrent=()=>isMemoryHostEventArtifactAtIdentity({workspaceRoot:e.workspaceRoot,relativePath:e.owner.relativePath,expectedIdentity:i,expectedContent:e.content});await syncDirectoryIfSupported(path.dirname(e.absolutePath));const a=memoryHostEventExportOwnerContent(e.owner,{pendingSha256:e.contentSha256,identity:i});if(!await rewriteMemoryHostEventArtifactIfUnchanged({workspaceRoot:e.workspaceRoot,relativePath:e.owner.ownerRelativePath,expectedContent:e.expectedOwnerContent,nextContent:a}))return;await syncDirectoryIfSupported(path.dirname(e.absolutePath));await writePinnedMemoryHostEventArtifact(r.handle,e.content);if(!await isPublishedArtifactCurrent())return;await syncDirectoryIfSupported(path.dirname(e.absolutePath));if(!await rewriteMemoryHostEventArtifactIfUnchanged({workspaceRoot:e.workspaceRoot,relativePath:e.owner.ownerRelativePath,expectedContent:a,nextContent:memoryHostEventExportOwnerContent(e.owner,{currentSha256:e.contentSha256,identity:i})}))return;await syncDirectoryIfSupported(path.dirname(e.absolutePath));if(!await isPublishedArtifactCurrent())return;return i}catch(e){t.e=e}finally{await t.d()}} //!src/plugin-sdk/memory-host-core.ts const MEMORY_HOST_EVENTS_FILENAME=`memory-host-events.jsonl`;const MEMORY_HOST_EVENTS_OWNER_FILENAME=`.openclaw-memory-host-events-owner.json`;const MAX_MEMORY_HOST_PUBLIC_EXPORT_EVENTS=1e3;const MEMORY_HOST_EVENT_EXPORT_LOCK_OPTIONS={retries:{retries:20,factor:1.3,minTimeout:25,maxTimeout:250,randomize:true},stale:3e4};const memoryHostEventExportQueue=new KeyedAsyncQueue;function isWorkspaceWriteUnavailable(e,t=/* @__PURE__ */ new Set){if(!e||typeof e!==`object`||t.has(e))return false;t.add(e);const n=e.code;if(n===`EACCES`||n===`EEXIST`||n===`ENOTDIR`||n===`EPERM`||n===`EROFS`||e instanceof FsSafeError&&(n===`not-file`||n===`not-removable`))return true;if(e instanceof FsSafeError&&e.category===`policy`&&n!==`invalid-path`)return false;return isWorkspaceWriteUnavailable(e.cause,t)}async function resolveMemoryHostEventExportOwner(e){const t=path.resolve(resolveStateDir());await fs.mkdir(t,{recursive:true,mode:448});const n=await fs.realpath(t);const r=sha256HexPrefixCore(n,32);const i=sha256HexPrefixCore(path.resolve(e),32);const a=path.posix.join(`memory`,`events`,r);return{queueKey:`${r}\0${i}`,lockTarget:path.join(n,`.memory-host-events-export-${i}`),relativePath:path.posix.join(a,MEMORY_HOST_EVENTS_FILENAME),ownerRelativePath:path.posix.join(a,MEMORY_HOST_EVENTS_OWNER_FILENAME),stateHash:r,workspaceHash:i}}function readMemoryHostEventArtifactText(e,t){return e.readText(t).catch(e=>{if(isMissingPathError(e))return;if(isRejectedWorkspaceArtifactPath(e))return null;throw e})}async function readMemoryHostEventExportOwnership(e,t){const n=await readMemoryHostEventArtifactText(e,t.ownerRelativePath);if(n===null)return{kind:`foreign`};if(n===void 0)return{kind:`missing`};let r;try{r=JSON.parse(n)}catch{return{kind:`foreign`}}if(!isRecord(r)||r.schemaVersion!==3&&r.schemaVersion!==4||r.kind!==`openclaw-memory-host-events-export`||r.stateHash!==t.stateHash||r.workspaceHash!==t.workspaceHash||r.contentSha256!==void 0&&typeof r.contentSha256!==`string`||r.pendingContentSha256!==void 0&&typeof r.pendingContentSha256!==`string`||r.contentSha256===void 0&&r.pendingContentSha256===void 0||r.fileDev===void 0!==(r.fileIno===void 0)||r.fileDev!==void 0&&(typeof r.fileDev!==`string`||!/^-?\d+$/u.test(r.fileDev)||typeof r.fileIno!==`string`||!/^-?\d+$/u.test(r.fileIno)))return{kind:`foreign`};const i=typeof r.fileDev===`string`&&typeof r.fileIno===`string`?{dev:BigInt(r.fileDev),ino:BigInt(r.fileIno)}:void 0;const a=r.schemaVersion===3;if(a&&i&&(String(Number(i.dev))!==r.fileDev||String(Number(i.ino))!==r.fileIno))return{kind:`foreign`};let o;try{o=await e.open(t.relativePath)}catch(e){if(isMissingPathError(e))o=void 0;else if(isRejectedWorkspaceArtifactPath(e))return{kind:`foreign`};else throw e}if(!o)return{kind:`orphan`,ownerContent:n};let s;const c=o.exactIdentity;const l=i!==void 0&&(a?Number(BigInt.asUintN(64,c.dev))===Number(i.dev)&&Number(BigInt.asUintN(64,c.ino))===Number(i.ino):sameFileIdentity(i,c));try{var u=_usingCtx();const e=u.a(o);if(o.stat.size>1048576)s=void 0;else s=(await readFileHandleBounded(e.handle,MAX_MEMORY_HOST_PUBLIC_EXPORT_BYTES)).toString(`utf8`)}catch(e){u.e=e}finally{await u.d()}const d=s===void 0?void 0:sha256Hex(s);const f=r.contentSha256;const p=r.pendingContentSha256;return l?{kind:`owned`,content:s,identity:c,ownerContent:n,needsFinalize:a||s===void 0||d!==f||p!==void 0}:{kind:`foreign`}}async function materializeMemoryHostEventExport(e){const t=path.resolve(e.workspaceDir);if(!(await fs.stat(t).catch(e=>{if(isMissingPathError(e))return;throw e}))?.isDirectory())return;const n=await root(t,{hardlinks:`reject`,mkdir:true,mode:384,symlinks:`reject`});const r=n.rootReal;const i=await resolveMemoryHostEventExportOwner(r);return memoryHostEventExportQueue.enqueue(i.queueKey,async()=>{const e=path.join(r,...i.relativePath.split(`/`));return await withFileLock(i.lockTarget,MEMORY_HOST_EVENT_EXPORT_LOCK_OPTIONS,async()=>{const t=await listStoredMemoryHostEvents({workspaceDir:r,limit:MAX_MEMORY_HOST_PUBLIC_EXPORT_EVENTS});const a=await readMemoryHostEventExportOwnership(n,i);if(a.kind===`foreign`)return;if(t.length===0&&a.kind!==`owned`)return;const o=t.length>0?serializeMemoryHostEventExport(t):``;const s=sha256Hex(o);let c;if(a.kind===`missing`){if(await readMemoryHostEventArtifactText(n,i.relativePath)!==void 0)return}try{if(a.kind!==`owned`){const t=memoryHostEventExportOwnerContent(i,{pendingSha256:s});if(a.kind===`missing`)await n.create(i.ownerRelativePath,t,{mkdir:true,mode:384});else if(!await rewriteMemoryHostEventArtifactIfUnchanged({workspaceRoot:n,relativePath:i.ownerRelativePath,expectedContent:a.ownerContent,nextContent:t}))return;await syncDirectoryIfSupported(path.dirname(e));c=await publishMemoryHostEventArtifact({workspaceRoot:n,owner:i,absolutePath:e,expectedOwnerContent:t,content:o,contentSha256:s});if(!c)return}else{c=a.identity;let t=a.ownerContent;if(a.content!==o){const r=memoryHostEventExportOwnerContent(i,{pendingSha256:s,identity:a.identity,...a.content===void 0?{}:{currentSha256:sha256Hex(a.content)}});if(!await rewriteMemoryHostEventArtifactIfUnchanged({workspaceRoot:n,relativePath:i.ownerRelativePath,expectedContent:t,nextContent:r}))return;await syncDirectoryIfSupported(path.dirname(e));if(!await rewriteMemoryHostEventArtifactIfUnchanged({workspaceRoot:n,relativePath:i.relativePath,expectedIdentity:a.identity,nextContent:o}))return;await syncDirectoryIfSupported(path.dirname(e));t=r}if(a.content!==o||a.needsFinalize){if(!await rewriteMemoryHostEventArtifactIfUnchanged({workspaceRoot:n,relativePath:i.ownerRelativePath,expectedContent:t,nextContent:memoryHostEventExportOwnerContent(i,{currentSha256:s,identity:a.identity})}))return;await syncDirectoryIfSupported(path.dirname(e))}}}catch(e){if(isWorkspaceWriteUnavailable(e))return;throw e}if(t.length===0||!c)return;return await isMemoryHostEventArtifactAtIdentity({workspaceRoot:n,relativePath:i.relativePath,expectedIdentity:c,expectedContent:o})?{absolutePath:e,relativePath:i.relativePath}:void 0})})}async function listMemoryWorkspacePublicArtifacts(e){const t=[];const addArtifact=(n,r,i,a=`markdown`)=>{t.push({kind:n,workspaceDir:e.workspaceDir,relativePath:r,absolutePath:i,agentIds:[...e.agentIds],contentType:a})};if(new Set((await fs.readdir(e.workspaceDir,{withFileTypes:true}).catch(()=>[])).filter(e=>e.isFile()).map(e=>e.name)).has(`MEMORY.md`))addArtifact(`memory-root`,`MEMORY.md`,path.join(e.workspaceDir,`MEMORY.md`));const n=path.join(e.workspaceDir,`memory`);const r=await walkDirectory(n,{symlinks:`skip`,include:e=>e.kind===`file`&&e.name.endsWith(`.md`)});for(const{path:t}of r.entries.toSorted((e,t)=>e.path.localeCompare(t.path))){const n=path.relative(e.workspaceDir,t).replace(/\\/g,`/`);addArtifact(n.startsWith(`memory/dreaming/`)?`dream-report`:`daily-note`,n,t)}const i=await materializeMemoryHostEventExport({workspaceDir:e.workspaceDir});if(i)addArtifact(`event-log`,i.relativePath,i.absolutePath,`json`);return t}async function listMemoryHostPublicArtifacts(e){const t=resolveMemoryDreamingWorkspaces(e.cfg);const n=[];for(const e of t)n.push(...await listMemoryWorkspacePublicArtifacts({workspaceDir:e.workspaceDir,agentIds:e.agentIds}));return n}export{listMemoryHostPublicArtifacts as t};