openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
15 lines • 17.5 kB
JavaScript
import{l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{s as asFiniteNumber}from"./number-coercion-B3CfI447.mjs";import{r as asNullableRecord}from"./record-coerce-BTbqdJ3-.mjs";import{l as normalizeSingleOrTrimmedStringList}from"./string-normalization-D_oBUpO3.mjs";import{t as truncateUtf8Prefix}from"./utf8-truncate-B8GdsL7T.mjs";import{t as walkRootDirectory}from"./root-walk-C9rOcTgR.mjs";import{t as fromMarkdown}from"./lib-vtjvZm5r.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import"./text-utility-runtime-CDtGqkrl.mjs";import"./root-walk-CGmToAv9.mjs";import path from"node:path";import{createHash}from"node:crypto";import{isDeepStrictEqual}from"node:util";import{isUtf8}from"node:buffer";import YAML from"yaml";
//!extensions/memory-wiki/src/bounded-walk.ts
const MEMORY_WIKI_WALK_MAX_DEPTH=128;const MEMORY_WIKI_WALK_MAX_ENTRIES=2e4;async function walkMemoryWikiDirectory(e,t,n={}){const r=[];try{for await(const i of walkRootDirectory(e,t,{maxDepth:n.maxDepth??MEMORY_WIKI_WALK_MAX_DEPTH,maxEntries:n.maxEntries??MEMORY_WIKI_WALK_MAX_ENTRIES,symlinkPolicy:`skip`,limitBehavior:`throw`,...n.entryFilter?{entryFilter:n.entryFilter}:{},...n.onDirectoryError?{onDirectoryError:n.onDirectoryError}:{}}))r.push(i)}catch(e){const t=e.code;if(t===`not-file`||t===`not-found`)return[];throw e}return r}async function listMemoryWikiPagePaths(e,t){return(await walkMemoryWikiDirectory(e,t)).filter(e=>e.kind===`file`&&e.relativePath.endsWith(`.md`)&&path.basename(e.relativePath)!==`index.md`).map(e=>e.relativePath.split(path.sep).join(`/`))}
//!extensions/memory-wiki/src/frontmatter-source.ts
const FRONTMATTER_PATTERN=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;const NUMERIC_FRONTMATTER_TAGS=/* @__PURE__ */ new Set([`tag:yaml.org,2002:int`,`tag:yaml.org,2002:float`]);function renderWikiFrontmatter(e,t){const n=t===void 0?null:t.match(FRONTMATTER_PATTERN)?.[1]??null;const r=n===null?null:readFrontmatterDocument(n);if(!r)return YAML.stringify(e).trimEnd();const i=asNullableRecord(r.toJS())??{};for(const t of Object.keys(i))if(!Object.hasOwn(e,t))r.delete(t);for(const[t,n]of Object.entries(e))if(!Object.hasOwn(i,t)||!isDeepStrictEqual(i[t],n))r.set(t,n);const a=r.toString().replace(/(?<!\n)\n$/,``);return a.trim()===``?`{}`:a}function readFrontmatterDocument(e){const t=/* @__PURE__ */ new WeakMap;const n=YAML.parseDocument(e,{keepSourceTokens:true,prettyErrors:false,customTags:e=>e.map(e=>{if(typeof e===`string`||e.collection!==void 0||!NUMERIC_FRONTMATTER_TAGS.has(e.tag)||typeof e.stringify!==`function`)return e;const n=e.stringify;const preserveSource=(e,...r)=>{const i=t.get(e);return i&&Object.is(e.value,i.value)?i.source:n(e,...r)};return{...e,stringify:preserveSource}})});if(n.errors.length>0||!(n.contents instanceof YAML.YAMLMap))return null;if(!n.contents.items.every(e=>YAML.isPair(e)&&YAML.isScalar(e.key)&&typeof e.key.value===`string`)||holdsAnAnchorOrExplicitTag(n.contents))return null;YAML.visit(n,{Scalar(e,n){if(typeof n.value===`number`&&n.source!==void 0)t.set(n,{value:n.value,source:n.source})}});return n}function holdsAnAnchorOrExplicitTag(e){if(YAML.isAlias(e))return true;if(YAML.isNode(e)&&(typeof e.anchor===`string`||typeof e.tag===`string`))return true;if(YAML.isPair(e))return holdsAnAnchorOrExplicitTag(e.key)||holdsAnAnchorOrExplicitTag(e.value);return YAML.isCollection(e)&&e.items.some(e=>holdsAnAnchorOrExplicitTag(e))}
//!extensions/memory-wiki/src/markdown-links.ts
const WIKI_RELATED_START_MARKER=`<!-- openclaw:wiki:related:start -->`;const WIKI_RELATED_END_MARKER=`<!-- openclaw:wiki:related:end -->`;const OBSIDIAN_LINK_PATTERN=/(?<!\\)(?:\\\\)*\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g;const RELATED_BLOCK_PATTERN=new RegExp(`${WIKI_RELATED_START_MARKER}[\\s\\S]*?${WIKI_RELATED_END_MARKER}`,`g`);function normalizeMarkdownLinkTarget(e,t){return path.posix.normalize(path.posix.join(path.posix.dirname(e),t))}function decodeMarkdownLinkPath(e){try{return decodeURIComponent(e)}catch{return e}}function forEachLiteralRange(e,t,n=false){const visit=e=>{if(e.type===`code`||e.type===`inlineCode`||n&&e.type===`html`){const n=e.position?.start?.offset;const r=e.position?.end?.offset;if(n!==void 0&&r!==void 0)t(n,r);return}for(const t of e.children??[])visit(t)};visit(e)}function forEachMarkdownCodeRange(e,t){forEachLiteralRange(fromMarkdown(e),t)}function maskMarkdownCode(e,t=false){const n=t?`${e}\n\n#`:e;return maskMarkdownLiteralRanges(e,fromMarkdown(n))}function maskMarkdownLiteralRanges(e,t,n=false){const r=e.split(``);forEachLiteralRange(t,(t,n)=>{if(n>e.length)return;for(let e=t;e<n;e++)if(r[e]!==`
`&&r[e]!==`\r`)r[e]=` `},n);return r.join(``)}function extractWikiLinks(e,t){if(!e.includes(`[`))return[];const n=e.replace(RELATED_BLOCK_PATTERN,``);const r=fromMarkdown(n);const i=maskMarkdownLiteralRanges(n,r,true);const a=[];for(const e of i.matchAll(OBSIDIAN_LINK_PATTERN)){const t=e[1]?.trim();if(t)a.push(t)}const visit=e=>{if(e.type===`link`||e.type===`image`){const n=e.url?.trim();if(n&&!n.startsWith(`#`)&&!/^[a-z]+:/i.test(n)){const e=decodeMarkdownLinkPath(n.split(`#`)[0]?.split(`?`)[0]??``).replace(/\\/g,`/`).trim();if(e)a.push(normalizeMarkdownLinkTarget(t,e))}}for(const t of e.children??[])visit(t)};visit(r);return a}
//!extensions/memory-wiki/src/wiki-page-kinds.ts
const WIKI_PAGE_GROUPS=[{kind:`source`,dir:`sources`,heading:`Sources`},{kind:`entity`,dir:`entities`,heading:`Entities`},{kind:`concept`,dir:`concepts`,heading:`Concepts`},{kind:`synthesis`,dir:`syntheses`,heading:`Syntheses`},{kind:`report`,dir:`reports`,heading:`Reports`}];
//!extensions/memory-wiki/src/markdown.ts
const WIKI_RAW_SOURCE_MARKER=`<!-- openclaw:wiki:raw-source -->`;const MAX_WIKI_SEGMENT_BYTES=240;const MAX_WIKI_SAFE_WRITE_FILENAME_COMPONENT_BYTES=255-Buffer.byteLength(`.00000000-0000-4000-8000-000000000000.fallback.tmp`)-Buffer.byteLength(`.`);const WIKI_SEGMENT_HASH_BYTES=12;const WIKI_RESERVED_PAGE_STEMS=/* @__PURE__ */ new Set([`index`]);const HUMAN_START_MARKER=`<!-- openclaw:human:start -->`;const HUMAN_END_MARKER=`<!-- openclaw:human:end -->`;function capWikiValueWithHash(e,t,n){if(Buffer.byteLength(e)<=t)return e;const r=createHash(`sha1`).update(e).digest(`hex`).slice(0,WIKI_SEGMENT_HASH_BYTES);return`${truncateUtf8Prefix(e,t-Buffer.byteLength(`-${r}`)).replace(/-+$/g,``)||n}-${r}`}function slugifyWikiSegment(e){const t=normalizeLowercaseStringOrEmpty(e).replace(/[^\p{L}\p{N}\p{M}]+/gu,`-`).replace(/^-+|-+$/g,``);if(!t)return`page`;return capWikiValueWithHash(t,MAX_WIKI_SEGMENT_BYTES,`page`)}function slugifyWikiPageStem(e){const t=slugifyWikiSegment(e);if(!WIKI_RESERVED_PAGE_STEMS.has(t))return t;return`${t}-${createHash(`sha1`).update(t).digest(`hex`).slice(0,WIKI_SEGMENT_HASH_BYTES)}`}function createWikiPageFilename(e,t=`.md`){const n=t.startsWith(`.`)?t:`.${t}`;return`${capWikiValueWithHash(e,Math.max(1,MAX_WIKI_SAFE_WRITE_FILENAME_COMPONENT_BYTES-Buffer.byteLength(n)),`page`)}${n}`}function parseWikiMarkdown(e){const t=e.match(FRONTMATTER_PATTERN);if(!t)return{hasFrontmatter:false,frontmatter:{},body:e};const n=t[1];const r=asNullableRecord(YAML.parse(n));if(!r)throw new TypeError(`Wiki frontmatter must be a YAML mapping`);return{hasFrontmatter:true,frontmatter:r,body:e.slice(t[0].length)}}function renderWikiMarkdown(e){return`---\n${renderWikiFrontmatter(e.frontmatter,e.original)}\n---\n\n${e.body.trimStart()}`}function extractTitleFromMarkdown(e){for(const t of maskMarkdownCode(e).matchAll(/^#[ \t].*$/gm)){const n=normalizeOptionalString(e.slice(t.index+1,t.index+t[0].length));if(n)return n}}function normalizeOptionalStringFields(e,t){const n={};for(const r of t){const t=normalizeOptionalString(e[r]);if(t)n[r]=t}return n}function normalizeWikiClaimEvidence(e){const t=asNullableRecord(e);if(!t)return null;const n=asFiniteNumber(t.weight);const r=asFiniteNumber(t.confidence);const i={...normalizeOptionalStringFields(t,[`kind`,`sourceId`,`path`,`lines`]),...n!==void 0?{weight:n}:{},...r!==void 0?{confidence:r}:{},...normalizeOptionalStringFields(t,[`privacyTier`,`note`,`updatedAt`])};return Object.keys(i).length>0?i:null}function normalizeWikiClaims(e){if(!Array.isArray(e))return[];return e.flatMap(e=>{const t=asNullableRecord(e);if(!t)return[];const n=normalizeOptionalString(t.text);if(!n)return[];const r=Array.isArray(t.evidence)?t.evidence.flatMap(e=>{const t=normalizeWikiClaimEvidence(e);return t?[t]:[]}):[];const i=asFiniteNumber(t.confidence);return[{...normalizeOptionalStringFields(t,[`id`]),text:n,...normalizeOptionalStringFields(t,[`status`]),...i!==void 0?{confidence:i}:{},evidence:r,...normalizeOptionalStringFields(t,[`updatedAt`])}]})}function normalizeWikiPersonCard(e){const t=asNullableRecord(e);if(!t)return;const n=asFiniteNumber(t.confidence);const r={...normalizeOptionalStringFields(t,[`canonicalId`]),handles:normalizeSingleOrTrimmedStringList(t.handles),socials:normalizeSingleOrTrimmedStringList(t.socials),emails:normalizeSingleOrTrimmedStringList(t.emails??t.email),...normalizeOptionalStringFields(t,[`timezone`,`lane`]),askFor:normalizeSingleOrTrimmedStringList(t.askFor),avoidAskingFor:normalizeSingleOrTrimmedStringList(t.avoidAskingFor),bestUsedFor:normalizeSingleOrTrimmedStringList(t.bestUsedFor),notEnoughFor:normalizeSingleOrTrimmedStringList(t.notEnoughFor),...n!==void 0?{confidence:n}:{},...normalizeOptionalStringFields(t,[`privacyTier`,`lastRefreshedAt`])};return Object.values(r).some(e=>Array.isArray(e)?e.length>0:e!==void 0)?r:void 0}function normalizeWikiRelationships(e){if(!Array.isArray(e))return[];return e.flatMap(e=>{const t=asNullableRecord(e);if(!t)return[];const n=asFiniteNumber(t.weight);const r=asFiniteNumber(t.confidence);const i={...normalizeOptionalStringFields(t,[`targetId`,`targetPath`,`targetTitle`,`kind`]),...n!==void 0?{weight:n}:{},...r!==void 0?{confidence:r}:{},...normalizeOptionalStringFields(t,[`evidenceKind`,`privacyTier`,`note`,`updatedAt`])};return Object.keys(i).length>0?[i]:[]})}function hasGeneratedWrapperLines(e,t){if(!t[0]?.test(e[0]??``)||t[1]&&!t[1].test(e[1]??``))return false;let n=2;for(const r of e.slice(2)){const e=t[n];if(!e)return true;if(e.test(r))n+=1}return n===t.length}const SOURCE_CONTENT_HEADING=/(?:^|\r?\n)## Content\r?\n/u;function afterSourceContentFence(e){const t=SOURCE_CONTENT_HEADING.exec(e);if(!t)return 0;const n=t.index+t[0].length;const r=/^`+/.exec(e.slice(n))?.[0];if(!r)return n;const i=new RegExp(`\\r?\\n${r}(?=\\r?\\n|$)`,`u`).exec(e.slice(n+r.length));if(!i)return n;return n+r.length+i.index+i[0].length}function findNotesHumanBlock(e,t=false){const n=t?e.match(FRONTMATTER_PATTERN)?.[0].length??0:afterSourceContentFence(e);const r=maskMarkdownCode(e.slice(n),true);const i=r.indexOf(HUMAN_START_MARKER);const a=r.lastIndexOf(HUMAN_END_MARKER);if(i===-1&&a<0){if(t)return null;if(!/(?:^|\r?\n)## Notes[\t ]*(?:\r?\n|$)([\s\S]*)/u.exec(e.slice(n))?.[1]?.trim())return null}if(i===-1||a<i)throw new Error(`Memory Wiki human Notes are missing ${i===-1?HUMAN_START_MARKER:HUMAN_END_MARKER}; restore the missing marker before updating or removing this page`);return{start:n+i,end:n+a+27}}function extractHumanNotesBlock(e,t){const n=findNotesHumanBlock(e,t?.producerMarkdown);if(!n)return null;return e.slice(n.start+29,n.end-27).trim()?e.slice(n.start,n.end):null}function preserveHumanNotesBlock(e,t,n){const r=findNotesHumanBlock(t,n?.producerMarkdown);const i=findNotesHumanBlock(e,n?.producerMarkdown);if(!r||!i)return e;return e.slice(0,i.start)+t.slice(r.start,r.end)+e.slice(i.end)}const GENERATED_SOURCE_WRAPPERS=[{kind:`bridge`,patterns:[/^# Memory Bridge(?:\s*\(|:)/u,/^## Bridge Source\s*$/u,/^## Content\s*$/u]},{kind:`unsafe-local`,patterns:[/^# Unsafe Local Import:/u,/^## Unsafe Local Source\s*$/u,/^## Content\s*$/u]},{kind:`local-file`,patterns:[/^#\s+\S/u,/^## Source\s*$/u,/^- Type: `local-file`\s*$/u,/^## Content\s*$/u]},{kind:`chatgpt-export`,patterns:[/^# ChatGPT Export:/u,/^## Source\s*$/u,/^- Conversation id: `[^`]+`\s*$/u,/^## Active Branch Transcript\s*$/u]}];function detectGeneratedSourceBody(e){if(!e.includes(`<!-- openclaw:human:start -->`)||!e.includes(`<!-- openclaw:human:end -->`))return;const t=e.replace(/\r\n?/g,`
`).trimStart().split(`
`).map(e=>e.trimEnd()).filter(e=>e.trim().length>0&&e.trim()!==`<!-- openclaw:wiki:raw-source -->`);return GENERATED_SOURCE_WRAPPERS.find(({patterns:e})=>hasGeneratedWrapperLines(t,e))?.kind}function detectUnmanagedRawSourceBody(e){const trimBlankLines=e=>e.replace(/^(?:[ \t]*\n)+/u,``);const t=trimBlankLines(e.replace(/\r\n?/g,`
`));const n=trimBlankLines(t.replace(/^#\s+.+?\s*\n/u,``));return t.startsWith(`<!-- openclaw:wiki:raw-source -->`)||n.startsWith(`<!-- openclaw:wiki:raw-source -->`)}function hasWikiSourceFrontmatter(e){return normalizeOptionalString(e.pageType)!==void 0||normalizeOptionalString(e.sourceType)!==void 0||normalizeOptionalString(e.provenanceMode)!==void 0}function isUnmanagedRawSourceSummary(e){return e.kind===`source`&&e.unmanagedRawSourceBody===true&&!e.generatedSourceBody}function formatWikiLink(e){if(e.renderMode===`obsidian`)return`[[${e.relativePath.replace(/\.md$/i,``)}|${e.title}]]`;const t=e.sourceRelativeTo?path.posix.relative(path.posix.dirname(e.sourceRelativeTo),e.relativePath):e.relativePath;const n=/[\s()<>]/.test(t)?`<${t.replace(/[<>]/g,`\\$&`)}>`:t;return`[${escapeWikiTitle(e.title)}](${n})`}function escapeWikiTitle(e){return e.replace(/[\\[\]`*_~<&#]/g,`\\$&`)}function renderMarkdownFence(e,t=`text`){let n=3;for(const t of e.matchAll(/`+/g))n=Math.max(n,t[0].length+1);const r="`".repeat(n);return`${r}${t}\n${e}\n${r}`}function inferWikiPageKind(e){const t=e.split(path.sep).join(`/`);return WIKI_PAGE_GROUPS.find(e=>t.startsWith(`${e.dir}/`))?.kind??null}function scanWikiPageSummary(e){const t=inferWikiPageKind(e.relativePath);if(!t)return{status:`ignored`};let n;try{n=parseWikiMarkdown(e.raw)}catch(t){return{status:`invalid-frontmatter`,error:{relativePath:e.relativePath.split(path.sep).join(`/`),message:t instanceof Error?t.message:String(t)}}}const r=typeof n.frontmatter.title===`string`&&n.frontmatter.title.trim()||extractTitleFromMarkdown(n.body)||path.basename(e.relativePath,`.md`);const i=detectGeneratedSourceBody(n.body);const a=i===`bridge`||i===`unsafe-local`?i:void 0;const o=!i&&!hasWikiSourceFrontmatter(n.frontmatter)&&detectUnmanagedRawSourceBody(n.body);return{status:`valid`,parsed:n,page:{absolutePath:e.absolutePath,relativePath:e.relativePath.split(path.sep).join(`/`),kind:t,title:r,hasFrontmatter:n.hasFrontmatter,id:normalizeOptionalString(n.frontmatter.id),pageType:normalizeOptionalString(n.frontmatter.pageType),entityType:normalizeOptionalString(n.frontmatter.entityType),canonicalId:normalizeOptionalString(n.frontmatter.canonicalId),aliases:normalizeSingleOrTrimmedStringList(n.frontmatter.aliases),sourceIds:normalizeSingleOrTrimmedStringList(n.frontmatter.sourceIds),linkTargets:e.includeLinks===false?[]:extractWikiLinks(e.raw,e.relativePath.split(path.sep).join(`/`)),claims:normalizeWikiClaims(n.frontmatter.claims),contradictions:normalizeSingleOrTrimmedStringList(n.frontmatter.contradictions),questions:normalizeSingleOrTrimmedStringList(n.frontmatter.questions),confidence:asFiniteNumber(n.frontmatter.confidence),privacyTier:normalizeOptionalString(n.frontmatter.privacyTier),personCard:normalizeWikiPersonCard(n.frontmatter.personCard),relationships:normalizeWikiRelationships(n.frontmatter.relationships),bestUsedFor:normalizeSingleOrTrimmedStringList(n.frontmatter.bestUsedFor),notEnoughFor:normalizeSingleOrTrimmedStringList(n.frontmatter.notEnoughFor),sourceType:normalizeOptionalString(n.frontmatter.sourceType),provenanceMode:normalizeOptionalString(n.frontmatter.provenanceMode),...a?{importedSourceBody:a}:{},...i?{generatedSourceBody:i}:{},...o?{unmanagedRawSourceBody:o}:{},sourcePath:normalizeOptionalString(n.frontmatter.sourcePath),bridgeRelativePath:normalizeOptionalString(n.frontmatter.bridgeRelativePath),bridgeWorkspaceDir:normalizeOptionalString(n.frontmatter.bridgeWorkspaceDir),bridgeAgentIds:normalizeSingleOrTrimmedStringList(n.frontmatter.bridgeAgentIds),unsafeLocalConfiguredPath:normalizeOptionalString(n.frontmatter.unsafeLocalConfiguredPath),unsafeLocalRelativePath:normalizeOptionalString(n.frontmatter.unsafeLocalRelativePath),lastRefreshedAt:normalizeOptionalString(n.frontmatter.lastRefreshedAt),updatedAt:normalizeOptionalString(n.frontmatter.updatedAt)}}}function toWikiPageSummary(e){const t=scanWikiPageSummary(e);return t.status===`valid`?t.page:null}var WikiPageNotUtf8Error=class extends Error{constructor(e){super(`Wiki page is not valid UTF-8 and cannot be rewritten safely: ${e}. The file was left unchanged. Keep a byte-for-byte backup, convert a copy to UTF-8 with its original encoding, then retry.`);this.name=`WikiPageNotUtf8Error`}};function decodeWikiPageUtf8(e,t){if(!isUtf8(e))throw new WikiPageNotUtf8Error(t);return e.toString(`utf8`)}export{listMemoryWikiPagePaths as C,forEachMarkdownCodeRange as S,slugifyWikiSegment as _,decodeWikiPageUtf8 as a,WIKI_RELATED_END_MARKER as b,formatWikiLink as c,parseWikiMarkdown as d,preserveHumanNotesBlock as f,slugifyWikiPageStem as g,scanWikiPageSummary as h,createWikiPageFilename as i,isUnmanagedRawSourceSummary as l,renderWikiMarkdown as m,HUMAN_START_MARKER as n,escapeWikiTitle as o,renderMarkdownFence as p,WIKI_RAW_SOURCE_MARKER as r,extractHumanNotesBlock as s,HUMAN_END_MARKER as t,normalizeWikiClaims as u,toWikiPageSummary as v,walkMemoryWikiDirectory as w,WIKI_RELATED_START_MARKER as x,WIKI_PAGE_GROUPS as y};