openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 13.2 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{F as resolveNonNegativeIntegerOption}from"./number-coercion-B3CfI447.mjs";import{r as asNullableRecord}from"./record-coerce-BTbqdJ3-.mjs";import{v as normalizeUniqueTrimmedStringList}from"./string-normalization-D_oBUpO3.mjs";import{t as FsSafeError,x as root}from"./fs-safe-Bxzu1j4h.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import{s as readFileWindowFully}from"./file-access-runtime-Jlxwf1va.mjs";import"./security-runtime-Y28JTB1K.mjs";import"./number-runtime-G0nhUVZu.mjs";import{a as decodeWikiPageUtf8,i as createWikiPageFilename,s as extractHumanNotesBlock}from"./markdown-CHgmVGaN.mjs";import path from"node:path";import{createHash}from"node:crypto";
//!extensions/memory-wiki/src/source-sync-state.ts
const MEMORY_WIKI_SOURCE_SYNC_STATE_NAMESPACE=`source-sync`;const MEMORY_WIKI_SOURCE_SYNC_STATE_MAX_ENTRIES=2e4;const MAX_MEMORY_WIKI_NOTES_RECOVERY_BYTES=16777216;const MAX_MEMORY_WIKI_SOURCE_PAGE_HEADER_BYTES=65536;const MAX_MEMORY_WIKI_SOURCE_PAGE_SCAN_BYTES=33554432;let configuredSourceSyncStore;const sourceSyncStateChanges=/* @__PURE__ */ new WeakMap;function normalizeSourceSyncEntry(e){const t=asNullableRecord(e);if(!t||t.group!==`bridge`&&t.group!==`unsafe-local`||typeof t.pagePath!==`string`||typeof t.sourcePath!==`string`||typeof t.sourceUpdatedAtMs!==`number`||typeof t.sourceSize!==`number`||typeof t.renderFingerprint!==`string`)return null;return{group:t.group,pagePath:t.pagePath,sourcePath:t.sourcePath,sourceUpdatedAtMs:t.sourceUpdatedAtMs,sourceSize:t.sourceSize,renderFingerprint:t.renderFingerprint}}function resolveVaultRootKey$1(e){return createHash(`sha256`).update(path.resolve(e),`utf8`).digest(`hex`).slice(0,32)}function resolveStateEntryKey$1(e,t){return createHash(`sha256`).update(`${e}\0${t}`,`utf8`).digest(`hex`)}function assertSourceSyncStateWithinLimit(e){if(e>MEMORY_WIKI_SOURCE_SYNC_STATE_MAX_ENTRIES)throw new Error(`Memory Wiki source sync state exceeds SQLite entry limit (${e}/${MEMORY_WIKI_SOURCE_SYNC_STATE_MAX_ENTRIES})`)}function assertMemoryWikiSourceSyncStateCapacity(e){const t=Object.values(e.state.entries).filter(t=>t.group!==e.group).length;assertSourceSyncStateWithinLimit(t+e.incomingCount)}function createMemoryWikiSourceSyncStateStore(e){const openStore=()=>e({namespace:MEMORY_WIKI_SOURCE_SYNC_STATE_NAMESPACE,maxEntries:MEMORY_WIKI_SOURCE_SYNC_STATE_MAX_ENTRIES,overflowPolicy:`reject-new`});return{async read(e){const t=resolveVaultRootKey$1(e);const n={};for(const e of await openStore().entries()){const r=e.value;if(r.vaultRootKey!==t||typeof r.syncKey!==`string`)continue;const i=normalizeSourceSyncEntry(r);if(i)n[r.syncKey]=i}return{version:1,entries:n}},async write(e,t,n){assertSourceSyncStateWithinLimit(Object.keys(t.entries).length);const r=resolveVaultRootKey$1(e);const i=openStore();if(n)for(const e of n.deleteKeys)await i.delete(resolveStateEntryKey$1(r,e));else{const e=new Set(Object.keys(t.entries).map(e=>resolveStateEntryKey$1(r,e)));for(const t of await i.entries())if(t.value.vaultRootKey===r&&!e.has(t.key))await i.delete(t.key)}for(const e of n?.upsertKeys??Object.keys(t.entries)){const n=t.entries[e];if(!n)throw new Error(`Missing tracked Memory Wiki source sync entry: ${e}`);await i.register(resolveStateEntryKey$1(r,e),{...n,vaultRootKey:r,syncKey:e})}}}}function configureMemoryWikiSourceSyncStateStore(e){configuredSourceSyncStore=e}function resolveSourceSyncStore(e=configuredSourceSyncStore){if(!e)throw new Error(`Memory Wiki source sync state store is not configured.`);return e}async function readMemoryWikiSourceSyncState(e,t){const n=await resolveSourceSyncStore(t).read(e);sourceSyncStateChanges.set(n,{upsertKeys:/* @__PURE__ */ new Set,deleteKeys:/* @__PURE__ */ new Set});return n}async function writeMemoryWikiSourceSyncState(e,t,n){const r=sourceSyncStateChanges.get(t);if(r&&r.upsertKeys.size===0&&r.deleteKeys.size===0)return;const i=r?{upsertKeys:[...r.upsertKeys],deleteKeys:[...r.deleteKeys]}:void 0;await resolveSourceSyncStore(n).write(e,t,i);r?.upsertKeys.clear();r?.deleteKeys.clear()}function removeImportedSourceStateEntry(e,t){delete e.entries[t];const n=sourceSyncStateChanges.get(e);n?.upsertKeys.delete(t);n?.deleteKeys.add(t)}async function readImportedSourcePageForNotes(e,t){try{return decodeWikiPageUtf8(await e.readBytes(t,{maxBytes:MAX_MEMORY_WIKI_NOTES_RECOVERY_BYTES}),t)}catch(e){if(!(e instanceof FsSafeError&&e.code===`too-large`))throw e}const n=await e.open(t);try{const e=Math.min(MAX_MEMORY_WIKI_SOURCE_PAGE_HEADER_BYTES,n.stat.size);const t=Buffer.alloc(e);if(await readFileWindowFully(n.handle,t,0)!==e)throw new Error(`Memory Wiki source page changed during bounded Notes recovery`);const r=new TextDecoder(`utf-8`,{fatal:true,ignoreBOM:true});const i=r.decode(t,{stream:true});const a=/(?:^|\r?\n)## Content\r?\n(`+)[^\r\n]*(?=\r?\n|$)/u.exec(i);if(!a)throw new Error(`Memory Wiki source content fence is missing from the recovery header`);const o=a[1];const s=new RegExp(`\\r?\\n${o}\\r?\\n(?:[\\t ]*\\r?\\n)*## Notes\\r?\\n<!-- openclaw:human:start -->(?=\\r?\\n|$)`,`u`);let c=``;let l=``;let u=0;let d=e;let f=false;const consume=t=>{if(!t)return;let n=t;if(!f){c+=t;const e=s.exec(c);if(!e){c=c.slice(-65536);return}f=true;n=c.slice(e.index);c=``}u+=Buffer.byteLength(n,`utf8`);if(e+u>MAX_MEMORY_WIKI_NOTES_RECOVERY_BYTES)throw new Error(`Memory Wiki human Notes exceed the bounded recovery limit`);l+=n};consume(i);const p=n.handle.createReadStream({autoClose:false,highWaterMark:MAX_MEMORY_WIKI_SOURCE_PAGE_HEADER_BYTES,start:e});for await(const e of p){d+=e.byteLength;if(d>MAX_MEMORY_WIKI_SOURCE_PAGE_SCAN_BYTES)throw new Error(`Memory Wiki source page exceeds the bounded recovery scan limit`);consume(r.decode(e,{stream:true}))}consume(r.decode());if(!f)throw new Error(`Memory Wiki source Notes boundary exceeds the bounded recovery limit`);return`${i}\n${l}`}finally{await n.handle.close()}}async function pruneImportedSourceEntries(e){let t=0;let n;for(const[r,i]of Object.entries(e.state.entries)){if(i.group!==e.group||e.activeKeys.has(r))continue;await e.prepareWrite?.();try{n??=await root(e.vaultRoot)}catch(n){if(!(n instanceof FsSafeError&&n.code===`not-found`))throw n;removeImportedSourceStateEntry(e.state,r);t+=1;continue}let a;try{a=await readImportedSourcePageForNotes(n,i.pagePath)}catch(e){if(!(e instanceof FsSafeError&&e.code===`not-found`))continue}const o=a===void 0?null:extractHumanNotesBlock(a);if(o){const e=i.pagePath.replace(/\//g,`_`);const t=createHash(`sha256`).update(o).digest(`hex`).slice(0,16);const r=[path.join(`.salvage`,createWikiPageFilename(e,`.notes.md`)),path.join(`.salvage`,createWikiPageFilename(`${e}.${t}`,`.notes.md`))];let a=false;for(const e of r)try{await n.create(e,o,{mkdir:true});a=true;break}catch(t){if(!(t instanceof FsSafeError&&t.code===`already-exists`))break;try{if(await n.readText(e,{maxBytes:MAX_MEMORY_WIKI_NOTES_RECOVERY_BYTES})===o){a=true;break}}catch{break}}if(!a)continue}if(a!==void 0)try{await n.remove(i.pagePath)}catch(e){if(!(e instanceof FsSafeError&&e.code===`not-found`))continue}removeImportedSourceStateEntry(e.state,r);t+=1}return t}function setImportedSourceEntry(e){const t=e.state.entries[e.syncKey];if(t?.group===e.entry.group&&t.pagePath===e.entry.pagePath&&t.sourcePath===e.entry.sourcePath&&t.sourceUpdatedAtMs===e.entry.sourceUpdatedAtMs&&t.sourceSize===e.entry.sourceSize&&t.renderFingerprint===e.entry.renderFingerprint)return;e.state.entries[e.syncKey]=e.entry;const n=sourceSyncStateChanges.get(e.state);n?.deleteKeys.delete(e.syncKey);n?.upsertKeys.add(e.syncKey)}
//!extensions/memory-wiki/src/import-runs-state.ts
const MEMORY_WIKI_IMPORT_RUN_STATE_NAMESPACE=`import-runs`;const MEMORY_WIKI_IMPORT_RUN_STATE_MAX_ENTRIES=2e4;let configuredImportRunStore;function resolveMemoryWikiImportRunsDir(e){return path.join(e,`.openclaw-wiki`,`import-runs`)}function resolveVaultRootKey(e){return createHash(`sha256`).update(path.resolve(e),`utf8`).digest(`hex`).slice(0,32)}function resolveStateEntryKey(e,t){return createHash(`sha256`).update(`${e}\0meta\0${t}`,`utf8`).digest(`hex`)}function resolvePathStateEntryKey(e){return createHash(`sha256`).update(`${e.vaultRootKey}\0${e.runId}\0${e.kind}\0${e.index}\0${e.path}`,`utf8`).digest(`hex`)}function normalizeMetaRecord(e){const t=asNullableRecord(e);if(!t||t.kind!==`meta`)return null;const n=typeof t.vaultRootKey===`string`?t.vaultRootKey:``;const r=normalizeOptionalString(t.runId)??``;const i=normalizeOptionalString(t.exportPath)??``;const a=normalizeOptionalString(t.sourcePath)??``;const o=normalizeOptionalString(t.appliedAt)??``;if(t.version!==1||t.importType!==`chatgpt`||!n||!r||!i||!a||!o)return null;const s=normalizeOptionalString(t.rolledBackAt);const c=normalizeOptionalString(t.rollbackStartedAt);const l=normalizeOptionalString(t.rollbackTargetsFinalizedAt);return{version:1,kind:`meta`,vaultRootKey:n,runId:r,importType:`chatgpt`,exportPath:i,sourcePath:a,appliedAt:o,conversationCount:resolveNonNegativeIntegerOption(t.conversationCount,0),createdCount:resolveNonNegativeIntegerOption(t.createdCount,0),updatedCount:resolveNonNegativeIntegerOption(t.updatedCount,0),skippedCount:resolveNonNegativeIntegerOption(t.skippedCount,0),...c?{rollbackStartedAt:c}:{},...l?{rollbackTargetsFinalizedAt:l}:{},...s?{rolledBackAt:s}:{}}}function normalizePathRecord(e){const t=asNullableRecord(e);if(!t||t.kind!==`created-path`&&t.kind!==`updated-path`||typeof t.vaultRootKey!==`string`||typeof t.runId!==`string`||typeof t.path!==`string`||typeof t.index!==`number`||!Number.isFinite(t.index))return null;const n=normalizeOptionalString(t.snapshotPath);const r=normalizeOptionalString(t.contentHash);const i=normalizeUniqueTrimmedStringList(t.recoveryPaths);return{kind:t.kind,vaultRootKey:t.vaultRootKey,runId:t.runId,index:Math.max(0,Math.floor(t.index)),path:t.path,...n?{snapshotPath:n}:{},...r?{contentHash:r}:{},...i.length>0?{recoveryPaths:i}:{}}}function composeImportRunRecord(e,t){const toEntry=e=>({path:e.path,...e.snapshotPath?{snapshotPath:e.snapshotPath}:{},...e.contentHash?{contentHash:e.contentHash}:{},...e.recoveryPaths?{recoveryPaths:[...e.recoveryPaths]}:{}});const{kind:n,vaultRootKey:r,...i}=e;const entries=e=>t.filter(t=>t.kind===e).toSorted((e,t)=>e.index-t.index).map(toEntry);return{...i,createdPaths:entries(`created-path`),updatedPaths:entries(`updated-path`)}}function toPathRecords(e,t){const toPathRecord=(n,r,i)=>({kind:i,vaultRootKey:e,runId:t.runId,index:r,path:n.path,...i===`updated-path`&&n.snapshotPath?{snapshotPath:n.snapshotPath}:{},...n.contentHash?{contentHash:n.contentHash}:{},...n.recoveryPaths?{recoveryPaths:[...n.recoveryPaths]}:{}});return[...t.createdPaths.map((e,t)=>toPathRecord(e,t,`created-path`)),...t.updatedPaths.map((e,t)=>toPathRecord(e,t,`updated-path`))]}function createMemoryWikiImportRunStateStore(e){const openStore=()=>e({namespace:MEMORY_WIKI_IMPORT_RUN_STATE_NAMESPACE,maxEntries:MEMORY_WIKI_IMPORT_RUN_STATE_MAX_ENTRIES});return{async read(e,t){const n=resolveVaultRootKey(e);const r=normalizeMetaRecord(await openStore().lookup(resolveStateEntryKey(n,t)));if(!r||r.vaultRootKey!==n)return null;return composeImportRunRecord(r,(await openStore().entries()).map(e=>normalizePathRecord(e.value)).filter(e=>e!==null&&e.vaultRootKey===n&&e.runId===t))},async write(e,t){const n=resolveVaultRootKey(e);const r=openStore();const i=/* @__PURE__ */ new Set;for(const e of toPathRecords(n,t)){const t=resolvePathStateEntryKey(e);i.add(t);await r.register(t,e)}const{createdPaths:a,updatedPaths:o,rollbackStartedAt:s,rollbackTargetsFinalizedAt:c,rolledBackAt:l,...u}=t;await r.register(resolveStateEntryKey(n,t.runId),{...u,kind:`meta`,vaultRootKey:n,...s?{rollbackStartedAt:s}:{},...c?{rollbackTargetsFinalizedAt:c}:{},...l?{rolledBackAt:l}:{}});for(const e of await r.entries()){const a=normalizePathRecord(e.value);if(a?.vaultRootKey===n&&a.runId===t.runId&&!i.has(e.key))await r.delete(e.key)}},async list(e){const t=resolveVaultRootKey(e);const n=/* @__PURE__ */ new Map;const r=[];for(const e of await openStore().entries()){const i=normalizeMetaRecord(e.value);if(i?.vaultRootKey===t){n.set(i.runId,i);continue}const a=normalizePathRecord(e.value);if(a?.vaultRootKey===t)r.push(a)}return[...n.values()].map(e=>composeImportRunRecord(e,r.filter(t=>t.runId===e.runId)))},async rowCount(){const e=openStore();return await e.count?.()??(await e.entries()).length}}}function configureMemoryWikiImportRunStateStore(e){configuredImportRunStore=e}function getMemoryWikiImportRunStateStore(){if(!configuredImportRunStore)throw new Error(`Memory Wiki import run state store is not configured.`);return configuredImportRunStore}export{resolveMemoryWikiImportRunsDir as a,createMemoryWikiSourceSyncStateStore as c,setImportedSourceEntry as d,writeMemoryWikiSourceSyncState as f,getMemoryWikiImportRunStateStore as i,pruneImportedSourceEntries as l,configureMemoryWikiImportRunStateStore as n,assertMemoryWikiSourceSyncStateCapacity as o,createMemoryWikiImportRunStateStore as r,configureMemoryWikiSourceSyncStateStore as s,MEMORY_WIKI_IMPORT_RUN_STATE_MAX_ENTRIES as t,readMemoryWikiSourceSyncState as u};