openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,153 lines (1,152 loc) • 37.5 kB
JavaScript
import { g as readStringValue, l as normalizeOptionalString, m as readNonBlankString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { S as parseDateStringTimestampMs, c as asFiniteNumberInRange, l as asNonNegativeFiniteNumber, s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { i as asOptionalObjectRecord, r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs";
import { v as normalizeUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs";
import { g as readRegularFile } from "./fs-safe-BbWvmdVn.mjs";
import { a as isPidDefinitelyDead, t as getFileLockProcessStartTime } from "./pid-alive-D899x-ak.mjs";
import { r as decodeUtf8Input } from "./utf8-input-BHczGT8v.mjs";
import { t as KeyedAsyncQueue } from "./keyed-async-queue-DewLnYvW.mjs";
import { t as DEFAULT_MEMORY_DEEP_DREAMING_MAX_PROMOTED_SNIPPET_TOKENS } from "./dreaming-C72ZWZJr.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import { r as replaceFileAtomic } from "./security-runtime-C-zE_Zy_.mjs";
import "./runtime-doctor-migrations-YTlcIEpR.mjs";
import "./text-utility-runtime-Ds8jsG0J.mjs";
import "./process-runtime-DcBPEA8Y.mjs";
import "./number-runtime-W4chuk8B.mjs";
import "./error-runtime-BM740gJj.mjs";
import { n as getMemoryWorkspaceMaintenance } from "./memory-workspace-files-Ekb7DRdf.mjs";
import "./memory-core-host-status-B88S-xY5.mjs";
import { t as replaceManagedMarkdownBlock } from "./memory-host-markdown-DAu07cV4.mjs";
import { C as captureMemoryMutationAuthority, S as writeMemoryCoreWorkspaceEntry, b as readMemoryCoreWorkspaceEntries, c as SHORT_TERM_META_NAMESPACE, g as memoryCoreWorkspaceStateKey, h as memoryCoreWorkspaceEntryKey, l as SHORT_TERM_PHASE_SIGNAL_NAMESPACE, m as memoryCoreStateReference, s as SHORT_TERM_LOCK_NAMESPACE, u as SHORT_TERM_RECALL_NAMESPACE, x as writeMemoryCoreWorkspaceEntries, y as openWorkspaceStore } from "./dreaming-state-DzOG6jkz.mjs";
import { n as DEFAULT_PROMOTION_MIN_SCORE, r as DEFAULT_PROMOTION_MIN_UNIQUE_QUERIES, t as DEFAULT_PROMOTION_MIN_RECALL_COUNT } from "./short-term-promotion-types-tSDV20wq.mjs";
import path from "node:path";
import { createHash } from "node:crypto";
import fs from "node:fs/promises";
import { AsyncLocalStorage } from "node:async_hooks";
//#region extensions/memory-core/src/memory-workspace-lock.ts
const SHORT_TERM_LOCK_STALE_MS = 6e4;
const inProcessMemoryWorkspaceLocks = new KeyedAsyncQueue();
const memoryWorkspaceLockScopes = new AsyncLocalStorage();
function findActiveWorkspaceLockScope(e) {
let t = memoryWorkspaceLockScopes.getStore();
while (t) {
if (!t.active || !t.lease.active) return;
if (t.lease.key === e) return t;
t = t.parent;
}
}
async function runWorkspaceLockScope(e, t) {
const n = {
lease: e,
active: true,
childTail: Promise.resolve(),
parent: memoryWorkspaceLockScopes.getStore()
};
try {
return await memoryWorkspaceLockScopes.run(n, t);
} finally {
n.active = false;
await n.childTail;
}
}
function resolveLockPath(e) {
return memoryCoreStateReference(SHORT_TERM_LOCK_NAMESPACE, e);
}
function parseLockOwnerPid(e) {
const t = e.trim().match(/^(\d+):/);
const n = Number.parseInt(t?.[1] ?? "", 10);
return Number.isInteger(n) && n > 0 ? n : null;
}
function isShortTermLockStealable(e, t) {
if (t - e.acquiredAt <= SHORT_TERM_LOCK_STALE_MS) return false;
const n = parseLockOwnerPid(e.owner);
if (n === null) return true;
if (n === process.pid) return true;
if (isPidDefinitelyDead(n)) return true;
if (e.ownerStartTime === void 0) return false;
const r = getFileLockProcessStartTime(n);
return r !== null && r !== e.ownerStartTime;
}
async function deleteShortTermLockEntryIfCurrent(e, t, n, r) {
if (!e.observe || !e.compareAndApply) throw new Error("memory-core short-term lock store requires atomic comparisons");
const { owner: i, acquiredAt: a } = n;
const decideDeletion = (e) => ({
operation: "delete",
action: e !== void 0 && e.owner === i && e.acquiredAt === a ? "delete" : "keep"
});
let o = r ?? await e.observe(t);
while (true) {
const n = await e.compareAndApply(t, o.comparison, decideDeletion(o.value));
if (n.status !== "conflict") return n.status === "applied";
o = n.current;
}
}
/** Captured input preparation shares local ordering without claiming a durable write lease. */
async function withMemoryWorkspacePreparation(e, t) {
const n = memoryCoreWorkspaceStateKey(e);
if (findActiveWorkspaceLockScope(n)) return await withMemoryWorkspaceLock(e, t);
return await inProcessMemoryWorkspaceLocks.enqueue(n, t);
}
async function withMemoryWorkspaceLock(e, t) {
const n = memoryCoreWorkspaceStateKey(e);
const r = findActiveWorkspaceLockScope(n);
if (r) {
const e = r.childTail.then(() => runWorkspaceLockScope(r.lease, t));
r.childTail = e.then(() => void 0, () => void 0);
return await e;
}
return await inProcessMemoryWorkspaceLocks.enqueue(n, async () => {
const e = {
key: n,
active: true
};
try {
return await runWorkspaceLockScope(e, t);
} finally {
e.active = false;
}
});
}
//#endregion
//#region extensions/memory-core/src/concept-vocabulary.ts
const MAX_CONCEPT_TAGS = 8;
const CONCEPT_STOP_WORDS = /* @__PURE__ */ new Set([
"about",
"after",
"agent",
"again",
"also",
"assistant",
"because",
"before",
"being",
"between",
"build",
"called",
"could",
"daily",
"default",
"deploy",
"during",
"every",
"file",
"files",
"from",
"have",
"into",
"just",
"line",
"lines",
"long",
"main",
"make",
"memory",
"month",
"more",
"most",
"move",
"much",
"next",
"note",
"notes",
"over",
"part",
"past",
"port",
"same",
"score",
"search",
"session",
"sessions",
"short",
"should",
"since",
"some",
"subagent",
"system",
"than",
"that",
"their",
"there",
"these",
"they",
"this",
"through",
"today",
"user",
"using",
"with",
"work",
"workspace",
"year",
"and",
"are",
"for",
"its",
"our",
"the",
"then",
"were",
"you",
"your",
"al",
"con",
"como",
"de",
"del",
"el",
"en",
"es",
"la",
"las",
"los",
"para",
"por",
"que",
"se",
"sin",
"su",
"sus",
"una",
"uno",
"unos",
"unas",
"y",
"au",
"aux",
"avec",
"dans",
"des",
"du",
"est",
"et",
"le",
"les",
"ou",
"pour",
"qui",
"sans",
"ses",
"son",
"sur",
"une",
"un",
"auf",
"aus",
"bei",
"das",
"dem",
"den",
"der",
"die",
"ein",
"eine",
"einem",
"einen",
"einer",
"für",
"ich",
"im",
"in",
"mit",
"nach",
"oder",
"ohne",
"über",
"und",
"von",
"zu",
"zum",
"zur",
"が",
"から",
"する",
"して",
"した",
"で",
"と",
"に",
"の",
"は",
"へ",
"まで",
"も",
"や",
"を",
"与",
"为",
"了",
"及",
"和",
"在",
"将",
"或",
"把",
"是",
"用",
"的",
"과",
"는",
"도",
"로",
"를",
"에",
"에서",
"와",
"은",
"으로",
"을",
"이",
"하다",
"한",
"할",
"해",
"했다",
"cjs",
"cpp",
"cts",
"jsx",
"json",
"md",
"mjs",
"mts",
"text",
"toml",
"ts",
"tsx",
"txt",
"yaml",
"yml"
]);
const PROTECTED_GLOSSARY = [
"backup",
"backups",
"embedding",
"embeddings",
"failover",
"gateway",
"glacier",
"gpt",
"kv",
"network",
"openai",
"router",
"s3",
"vlan",
"sauvegarde",
"routeur",
"passerelle",
"konfiguration",
"sicherung",
"überwachung",
"configuración",
"respaldo",
"enrutador",
"puerta-de-enlace",
"バックアップ",
"フェイルオーバー",
"ルーター",
"ネットワーク",
"ゲートウェイ",
"障害対応",
"路由器",
"备份",
"故障转移",
"网络",
"网关",
"라우터",
"백업",
"페일오버",
"네트워크",
"게이트웨이",
"장애대응"
].map((e) => normalizeLowercaseStringOrEmpty(e.normalize("NFKC")));
const COMPOUND_TOKEN_RE = /[\p{L}\p{N}]+(?:[._/-][\p{L}\p{N}]+)+/gu;
const LETTER_OR_NUMBER_RE = /[\p{L}\p{N}]/u;
const LATIN_RE = /\p{Script=Latin}/u;
const HAN_RE = /\p{Script=Han}/u;
const HIRAGANA_RE = /\p{Script=Hiragana}/u;
const KATAKANA_RE = /\p{Script=Katakana}/u;
const HANGUL_RE = /\p{Script=Hangul}/u;
const DEFAULT_WORD_SEGMENTER = new Intl.Segmenter("und", { granularity: "word" });
function classifyConceptTagScript(e) {
const t = e.normalize("NFKC");
const n = LATIN_RE.test(t);
const r = HAN_RE.test(t) || HIRAGANA_RE.test(t) || KATAKANA_RE.test(t) || HANGUL_RE.test(t);
if (n && r) return "mixed";
if (r) return "cjk";
if (n) return "latin";
return "other";
}
function minimumTokenLengthForScript(e) {
if (e === "cjk") return 2;
return 3;
}
function isKanaOnlyToken(e) {
return !HAN_RE.test(e) && !HANGUL_RE.test(e) && (HIRAGANA_RE.test(e) || KATAKANA_RE.test(e));
}
function normalizeConceptToken(e) {
const t = normalizeLowercaseStringOrEmpty(e.normalize("NFKC").replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "").replaceAll("_", "-"));
if (!t || !LETTER_OR_NUMBER_RE.test(t) || t.length > 32) return null;
if (/^\p{N}+(?:[./-]\p{N}+)*$/u.test(t) || /^\d{4}-\d{2}-\d{2}\.[\p{L}\p{N}]+$/u.test(t)) return null;
const n = classifyConceptTagScript(t);
if (t.length < minimumTokenLengthForScript(n) && !PROTECTED_GLOSSARY.includes(t)) return null;
if (isKanaOnlyToken(t) && t.length < 3) return null;
if (CONCEPT_STOP_WORDS.has(t)) return null;
return t;
}
const GLOSSARY_ENTRIES = PROTECTED_GLOSSARY.map((e) => ({
entry: e,
wholeWord: e.length < minimumTokenLengthForScript(classifyConceptTagScript(e)) ? new RegExp(`(?<![\\p{L}\\p{N}])${escapeRegExp(e)}(?![\\p{L}\\p{N}])`, "u") : void 0
}));
function collectGlossaryMatches(e) {
const t = normalizeLowercaseStringOrEmpty(e.normalize("NFKC"));
return GLOSSARY_ENTRIES.filter(({ entry: e, wholeWord: n }) => n ? n.test(t) : t.includes(e)).map(({ entry: e }) => e);
}
function collectSegmentTokens(e) {
return Array.from(DEFAULT_WORD_SEGMENTER.segment(e), (e) => e.isWordLike ? e.segment : "").filter(Boolean);
}
function deriveConceptTags(e) {
const t = e.snippet.replace(/<!--[\s\S]*?-->/gu, " ");
const n = `${path.basename(e.path)} ${t}`;
const r = [];
const i = [
collectGlossaryMatches(n),
n.match(COMPOUND_TOKEN_RE) ?? [],
collectSegmentTokens(n)
];
for (const e of i) for (const t of e) {
const e = normalizeConceptToken(t);
if (!e || r.includes(e)) continue;
r.push(e);
if (r.length >= 8) return r;
}
return r;
}
function summarizeConceptTagScriptCoverage(e) {
const t = {
latinEntryCount: 0,
cjkEntryCount: 0,
mixedEntryCount: 0,
otherEntryCount: 0
};
for (const n of e) if (n.length > 0) t[`${classifyConceptTagScript(n.join(" "))}EntryCount`] += 1;
return t;
}
//#endregion
//#region extensions/memory-core/src/short-term-promotion-utils.ts
const GENERIC_DAY_HEADING_RE = /^(?:(?:mon|monday|tue|tues|tuesday|wed|wednesday|thu|thur|thurs|thursday|fri|friday|sat|saturday|sun|sunday)(?:,\s+)?)?(?:(?:jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)\s+\d{1,2}(?:st|nd|rd|th)?(?:,\s*\d{4})?|\d{1,2}[/-]\d{1,2}(?:[/-]\d{2,4})?|\d{4}[/-]\d{2}[/-]\d{2})$/i;
const SHORT_TERM_PATH_RE = /(?:^|\/)memory\/(?:[^/]+\/)*(\d{4})-(\d{2})-(\d{2})(?:-[^/]+)?\.md$/;
const DREAMING_MEMORY_PATH_RE = /(?:^|\/)memory\/dreaming\//;
const SHORT_TERM_SESSION_CORPUS_RE = /(?:^|\/)memory\/\.dreams\/session-corpus\/(\d{4})-(\d{2})-(\d{2})\.(?:md|txt)$/;
const SHORT_TERM_BASENAME_RE = /^(\d{4})-(\d{2})-(\d{2})(?:-[^/]+)?\.md$/;
const MAX_QUERY_HASHES = 32;
const SHORT_TERM_RECALL_MAX_ENTRIES = 512;
const SHORT_TERM_RECALL_MAX_SNIPPET_CHARS = 800;
const DREAMING_TRANSCRIPT_PROMPT_LINE_RE = /\[[^\]]*dreaming-narrative[^\]]*]\s*(?:User|Assistant):\s*Write a dream diary entry from these memory fragments:?/i;
const RAW_SESSION_METADATA_RE = /\bSession Key\b.{0,260}\bSession ID\b|\bSession ID\b.{0,260}\bSession Key\b/i;
const RAW_CONVERSATION_SUMMARY_RE = /^(?:[-*+]\s*)?Conversation Summary:\s*(?:$|(?:[-*+]\s*)?(?:user|assistant|(?:\*\*)?Session (?:Key|ID)(?:\*\*)?):\s)/i;
const RAW_TRANSCRIPT_TURN_RE = /^(?:[-*+]\s*)?(?:user|assistant):\s/i;
const MEMORY_FLUSH_PROMPT_RE = /Save important context from this session to the daily memory file\.\s*STRICT RULES:/i;
const PROMOTION_SCORE_METADATA_RE = /\[\s*score=\d+(?:\.\d+)?\s+(?:signals=\d+\s+)?recalls=\d+\s+avg=\d+(?:\.\d+)?\s+source=memory\//i;
const DREAMING_DIFF_PREFIX_RE = /@@\s*-\d+(?:,\d+)?\s+[-*+]\s+/iy;
function clampScore(e) {
if (!Number.isFinite(e)) return 0;
return Math.max(0, Math.min(1, e));
}
function resolvePromotionThresholds(e) {
return {
minScore: asFiniteNumberInRange(Number(e.minScore), {
min: 0,
max: 1
}) ?? DEFAULT_PROMOTION_MIN_SCORE,
minRecallCount: toFiniteNonNegativeInt(e.minRecallCount, DEFAULT_PROMOTION_MIN_RECALL_COUNT),
minUniqueQueries: toFiniteNonNegativeInt(e.minUniqueQueries, DEFAULT_PROMOTION_MIN_UNIQUE_QUERIES),
maxAgeDays: toFiniteNonNegativeInt(e.maxAgeDays, -1)
};
}
function isGenericDailyHeading(e) {
const t = e.trim().replace(/\s+/g, " ");
return !t || /^(today|yesterday|tomorrow|morning|afternoon|evening|night)$/i.test(t) || GENERIC_DAY_HEADING_RE.test(t);
}
function normalizeSnippet(e) {
return e.trim().replace(/\s+/g, " ");
}
const PROMOTED_SNIPPET_CHARS_PER_TOKEN_ESTIMATE = 4;
function truncatePromotedSnippet(e, t) {
const n = toFiniteNonNegativeInt(t, 160) * PROMOTED_SNIPPET_CHARS_PER_TOKEN_ESTIMATE;
if (n === 0 || e.length <= n) return e;
const r = truncateUtf16Safe(e, n);
const i = Math.max(r.lastIndexOf(". "), r.lastIndexOf("! "), r.lastIndexOf("? "));
const a = r.lastIndexOf(" ");
const o = i >= Math.floor(n * .55) ? i + 1 : a >= Math.floor(n * .65) ? a : n;
return `${r.slice(0, o).trimEnd()}...`;
}
function formatPromotedSnippetForMemory(e, t) {
return truncatePromotedSnippet(normalizeSnippet(e || "(no snippet captured)").replace(/^[-*+] +/, "").trim() || "(no snippet captured)", t);
}
function normalizeProjectKeyList(e) {
if (typeof e !== "string") return;
const t = /* @__PURE__ */ new Set();
for (const n of e.split(";")) {
const e = n.trim();
if (!e || /[\r\n<>]/u.test(e)) continue;
if (e.startsWith("path:")) {
t.add(e);
continue;
}
const r = e.indexOf("/");
if (r < 1) {
t.add(e);
continue;
}
t.add(`${e.slice(0, r).toLowerCase()}${e.slice(r)}`);
}
return t.size > 0 ? [...t].join("; ") : void 0;
}
function mergeProjectKeyLists(...e) {
return normalizeProjectKeyList(e.filter((e) => typeof e === "string").join(";"));
}
function truncateShortTermSnippet(e) {
if (e.length <= SHORT_TERM_RECALL_MAX_SNIPPET_CHARS) return e;
return truncateUtf16Safe(e, SHORT_TERM_RECALL_MAX_SNIPPET_CHARS).trimEnd();
}
function enforceShortTermRecallSnippetCap(e) {
for (const t of Object.values(e.entries)) t.snippet = truncateShortTermSnippet(t.snippet);
}
function consumeDreamingLeadPrefix(e) {
let t = 0;
while (t < e.length) {
DREAMING_DIFF_PREFIX_RE.lastIndex = t;
if (DREAMING_DIFF_PREFIX_RE.exec(e)) {
t = DREAMING_DIFF_PREFIX_RE.lastIndex;
continue;
}
const n = e[t];
if (n === "[" || n === "(") {
t += 1;
while (e[t] === " ") t += 1;
continue;
}
if ((n === "-" || n === "*" || n === "+" || n === ">") && e[t + 1] === " ") {
t += 2;
continue;
}
break;
}
return e.slice(t);
}
function hasDreamingNarrativeLead(e) {
const t = consumeDreamingLeadPrefix(e);
const n = truncateUtf16Safe(t, 200);
return /\b(?:Candidate|Reflections?):/i.test(n) || /#{1,6}\s+Reflections?\b/i.test(n);
}
function isContaminatedDreamingSnippet(e, t = {}) {
const n = normalizeSnippet(e);
if (!n) return false;
if (/<!--\s*openclaw-memory-promotion:/i.test(n) || DREAMING_TRANSCRIPT_PROMPT_LINE_RE.test(n) || RAW_SESSION_METADATA_RE.test(n) || RAW_CONVERSATION_SUMMARY_RE.test(n) || !t.allowTranscriptTurnSnippet && RAW_TRANSCRIPT_TURN_RE.test(n) || MEMORY_FLUSH_PROMPT_RE.test(n) || PROMOTION_SCORE_METADATA_RE.test(n)) return true;
const r = hasDreamingNarrativeLead(n);
const i = /\bconfidence:\s*\d/i.test(n);
const a = /\bevidence:\s*(?:memory\/\.dreams\/session-corpus\/|memory\/)/i.test(n);
const o = /\bstatus:\s*staged\b/i.test(n);
const s = /\brecalls:\s*\d+\b/i.test(n);
const c = /\bnote:\s*reflection\b/i.test(n);
return r && i && a && (o && s || c);
}
function normalizeMemoryPath(e) {
return e.replaceAll("\\", "/").replace(/^\.\//, "");
}
function buildClaimHash(e) {
return createHash("sha1").update(normalizeSnippet(e)).digest("hex").slice(0, 12);
}
function buildDailyClaimEntryKey(e) {
return `memory:claim:${e}`;
}
function buildEntryKey(e) {
const t = `${e.source}:${normalizeMemoryPath(e.path)}:${e.startLine}:${e.endLine}`;
return e.claimHash ? `${t}:${e.claimHash}` : t;
}
function hashQuery(e) {
return createHash("sha1").update(normalizeLowercaseStringOrEmpty(e)).digest("hex").slice(0, 12);
}
function mergeRecentDistinct(e, t, n) {
const r = [...new Set(e.filter((e) => typeof e === "string" && e.length > 0))];
if (t && !r.includes(t)) r.push(t);
return r.length <= n ? r : r.slice(r.length - n);
}
function normalizeIsoDay(e) {
if (typeof e !== "string") return null;
return e.trim().match(/^(\d{4}-\d{2}-\d{2})/)?.[1] ?? null;
}
function totalSignalCountForEntry(e) {
return e.recallCount + e.dailyCount + e.groundedCount;
}
function normalizeShortTermRecallStore(e, t) {
const n = asOptionalObjectRecord(e);
if (!n) return {
version: 1,
updatedAt: t,
entries: {}
};
const r = asOptionalObjectRecord(n.entries);
const i = {};
if (r) for (const [e, n] of Object.entries(r)) {
const r = asOptionalObjectRecord(n);
if (!r) continue;
const a = typeof r.path === "string" ? normalizeMemoryPath(r.path) : "";
const o = Number(r.startLine);
const s = Number(r.endLine);
const c = r.source === "memory" ? "memory" : null;
if (!a || !Number.isInteger(o) || !Number.isInteger(s) || !c) continue;
const l = Math.max(0, Math.floor(Number(r.recallCount) || 0));
const u = Math.max(0, Math.floor(Number(r.dailyCount) || 0));
const d = Math.max(0, Math.floor(Number(r.groundedCount) || 0));
const f = Math.max(0, Number(r.totalScore) || 0);
const p = clampScore(Number(r.maxScore) || 0);
const m = readStringValue(r.firstRecalledAt) ?? t;
const h = readStringValue(r.lastRecalledAt) ?? t;
const g = readStringValue(r.promotedAt);
const _ = normalizeOptionalString(r.claimHash);
const v = normalizeProjectKeyList(r.projectKey);
const y = typeof r.snippet === "string" ? normalizeSnippet(r.snippet) : "";
if (y && isContaminatedDreamingSnippet(y, { allowTranscriptTurnSnippet: isShortTermSessionCorpusPath(a) })) continue;
const b = truncateShortTermSnippet(y);
const x = normalizeUniqueTrimmedStringList(r.queryHashes).slice(0, 32);
const S = (Array.isArray(r.userQueryHashes) ? normalizeUniqueTrimmedStringList(r.userQueryHashes).slice(0, 32) : void 0) ?? (u === 0 && d === 0 ? x : void 0);
const C = Array.isArray(r.recallDays) ? r.recallDays.map(normalizeIsoDay).filter((e) => e !== null) : [];
const w = Array.isArray(r.conceptTags) ? normalizeUniqueTrimmedStringList(r.conceptTags.map(normalizeLowercaseStringOrEmpty)).slice(0, 8) : deriveConceptTags({
path: a,
snippet: y
});
const T = asOptionalObjectRecord(r.provenance);
const E = normalizeOptionalString(T?.supersedesKey);
const D = Date.parse(h);
const O = Number.isFinite(D) ? D : Date.parse(t);
const k = T ? {
originClass: T.originClass === "owner" || T.originClass === "agent" || T.originClass === "system" || T.originClass === "untrusted" ? T.originClass : "untrusted",
sessionKind: T.sessionKind === "interactive" || T.sessionKind === "cron" || T.sessionKind === "heartbeat" || T.sessionKind === "subagent" || T.sessionKind === "unknown" ? T.sessionKind : "unknown",
observedAt: asFiniteNumber(T.observedAt) ?? O,
...E ? { supersedesKey: E } : {}
} : void 0;
const A = e || buildEntryKey({
path: a,
startLine: o,
endLine: s,
source: c,
claimHash: _
});
i[A] = {
key: A,
path: a,
startLine: o,
endLine: s,
source: c,
snippet: b,
recallCount: l,
dailyCount: u,
groundedCount: d,
totalScore: f,
maxScore: p,
firstRecalledAt: m,
lastRecalledAt: h,
queryHashes: x,
...S ? { userQueryHashes: S } : {},
recallDays: C.slice(-16),
conceptTags: w,
...k ? { provenance: k } : {},
..._ ? { claimHash: _ } : {},
...v ? { projectKey: v } : {},
...g ? { promotedAt: g } : {}
};
}
return {
version: 1,
updatedAt: readStringValue(n.updatedAt) ?? t,
entries: i
};
}
function parseStoreTimestampMs(e) {
return parseDateStringTimestampMs(e) ?? Number.NEGATIVE_INFINITY;
}
function compareStoreTimestampDesc(e, t) {
const n = parseStoreTimestampMs(e);
const r = parseStoreTimestampMs(t);
if (n === r) return 0;
return r > n ? 1 : -1;
}
function compareShortTermRecallRetention(e, t) {
const n = compareStoreTimestampDesc(e.lastRecalledAt, t.lastRecalledAt);
if (n !== 0) return n;
const r = totalSignalCountForEntry(t) - totalSignalCountForEntry(e);
if (r !== 0) return r;
const i = t.totalScore - e.totalScore;
if (i !== 0) return i;
const a = t.maxScore - e.maxScore;
if (a !== 0) return a;
const o = compareStoreTimestampDesc(e.promotedAt, t.promotedAt);
if (o !== 0) return o;
return e.key.localeCompare(t.key);
}
function enforceShortTermRecallStoreRetention(e) {
const t = Object.entries(e.entries);
if (t.length <= 512) return 0;
const n = t.toSorted(([, e], [, t]) => compareShortTermRecallRetention(e, t)).slice(0, 512);
e.entries = Object.fromEntries(n.toSorted(([e], [t]) => e.localeCompare(t)));
return t.length - n.length;
}
function toFiniteNonNegativeInt(e, t = 0) {
return asNonNegativeFiniteNumber(Math.floor(Number(e))) ?? t;
}
function calculateRecencyComponent(e, t) {
if (!Number.isFinite(e) || e < 0) return 1;
if (!Number.isFinite(t) || t <= 0) return 1;
const n = Math.LN2 / t;
return Math.exp(-n * e);
}
function isShortTermMemoryPath(e) {
const t = normalizeMemoryPath(e);
return !DREAMING_MEMORY_PATH_RE.test(t) && (SHORT_TERM_PATH_RE.test(t) || SHORT_TERM_SESSION_CORPUS_RE.test(t) || SHORT_TERM_BASENAME_RE.test(t));
}
function isShortTermSessionCorpusPath(e) {
return SHORT_TERM_SESSION_CORPUS_RE.test(normalizeMemoryPath(e));
}
function normalizeMemoryPathForWorkspace(e, t) {
const n = normalizeMemoryPath(t);
const r = normalizeMemoryPath(e);
if (path.isAbsolute(t) && n.startsWith(`${r}/`)) return n.slice(r.length + 1);
return n;
}
function parseEntryRangeFromKey(e, t, n) {
const r = toFiniteNonNegativeInt(t);
const i = toFiniteNonNegativeInt(n);
if (r > 0 && i > 0) return {
startLine: r,
endLine: i
};
const a = e.match(/:(\d+):(\d+)$/);
if (a) return {
startLine: Math.max(1, toFiniteNonNegativeInt(a[1])),
endLine: Math.max(1, toFiniteNonNegativeInt(a[2]))
};
return {
startLine: 1,
endLine: 1
};
}
//#endregion
//#region extensions/memory-core/src/short-term-promotion-store.ts
const SHORT_TERM_STORE_NAMESPACES = {
recall: SHORT_TERM_RECALL_NAMESPACE,
phase: SHORT_TERM_PHASE_SIGNAL_NAMESPACE
};
async function pruneShortTermStore(e, t) {
if (t.length === 0) return;
const n = [SHORT_TERM_RECALL_NAMESPACE, SHORT_TERM_PHASE_SIGNAL_NAMESPACE].map(openWorkspaceStore);
await n[0].createOperation(n, {
moduleName: "recall-operation-api.js",
exportName: "pruneRecallEntries"
}).execute({
type: "prune",
input: { keys: t.map((t) => memoryCoreWorkspaceEntryKey(e, t)) }
}, { writeStores: [0, 1] });
}
async function readShortTermStore(e, t, n) {
const [r, i] = await Promise.all([readMemoryCoreWorkspaceEntries({
namespace: SHORT_TERM_STORE_NAMESPACES[t],
workspaceDir: e
}), readMemoryCoreWorkspaceEntries({
namespace: SHORT_TERM_META_NAMESPACE,
workspaceDir: e
})]);
return {
version: 1,
updatedAt: i.find((e) => e.key === t)?.value?.updatedAt ?? n,
entries: Object.fromEntries(r.map((e) => [e.key, e.value]))
};
}
async function writeShortTermStore(e, t, n) {
await writeMemoryCoreWorkspaceEntries({
namespace: SHORT_TERM_STORE_NAMESPACES[t],
workspaceDir: e,
entries: Object.entries(n.entries).map(([e, t]) => ({
key: e,
value: t
}))
});
await writeMemoryCoreWorkspaceEntry({
namespace: SHORT_TERM_META_NAMESPACE,
workspaceDir: e,
key: t,
value: { updatedAt: n.updatedAt }
});
}
function resolveStorePath(e) {
return memoryCoreStateReference(SHORT_TERM_RECALL_NAMESPACE, e);
}
function resolvePhaseSignalPath(e) {
return memoryCoreStateReference(SHORT_TERM_PHASE_SIGNAL_NAMESPACE, e);
}
async function readStore(e, t) {
const n = normalizeShortTermRecallStore(await readShortTermStore(e, "recall", t), t);
enforceShortTermRecallStoreRetention(n);
return n;
}
function emptyPhaseSignalStore(e) {
return {
version: 1,
updatedAt: e,
entries: {}
};
}
async function readPhaseSignalStore(e, t) {
const n = await readShortTermStore(e, "phase", t);
const r = {};
for (const [e, t] of Object.entries(n.entries)) {
const n = asNullableRecord(t);
if (!n) continue;
const i = readNonBlankString(n.key) ?? e;
const a = toFiniteNonNegativeInt(n.lightHits, 0);
const o = toFiniteNonNegativeInt(n.remHits, 0);
if (a === 0 && o === 0) continue;
const s = readNonBlankString(n.lastLightAt);
const c = readNonBlankString(n.lastRemAt);
const l = readNonBlankString(n.lastRemConsideredAt);
r[i] = {
key: i,
lightHits: a,
remHits: o,
...s ? { lastLightAt: s } : {},
...c ? { lastRemAt: c } : {},
...l ? { lastRemConsideredAt: l } : {}
};
}
return {
version: 1,
updatedAt: readNonBlankString(n.updatedAt) ?? t,
entries: r
};
}
async function writePhaseSignalStore(e, t) {
await writeShortTermStore(e, "phase", t);
}
async function writeStore(e, t) {
enforceShortTermRecallSnippetCap(t);
enforceShortTermRecallStoreRetention(t);
await writeShortTermStore(e, "recall", t);
}
//#endregion
//#region extensions/memory-core/src/dreaming-dreams-file.ts
const DREAMS_FILENAMES = ["DREAMS.md", "dreams.md"];
const DEEP_START_MARKER = "<!-- openclaw:dreaming:deep:start -->";
const DEEP_END_MARKER = "<!-- openclaw:dreaming:deep:end -->";
async function resolveDreamsPath(e) {
const t = getMemoryWorkspaceMaintenance(e);
if (t) return await t.resolveDreamsPath();
for (const t of DREAMS_FILENAMES) {
const n = path.join(e, t);
try {
await fs.access(n);
return n;
} catch (e) {
if (extractErrorCode(e) !== "ENOENT") throw e;
}
}
return path.join(e, DREAMS_FILENAMES[0]);
}
function isEmptyDreamsReadError(e, t) {
if (t === "ENOENT" || t === "ENOTDIR" || t === "not-found" || t === "not-file" || t === "path-alias" || t === "path-mismatch" || t === "symlink") return true;
return e instanceof Error && e.message === "path must be a regular file";
}
async function readDreamsFile(e, t) {
const n = t ? getMemoryWorkspaceMaintenance(t) : void 0;
if (n) return await n.readDreams(e);
try {
return decodeUtf8Input((await readRegularFile({ filePath: e })).buffer, `DREAMS.md ${e} (preserve the original and convert a copy to UTF-8 before retrying)`);
} catch (e) {
if (isEmptyDreamsReadError(e, extractErrorCode(e))) return "";
throw e;
}
}
async function assertSafeDreamsPath(e) {
const t = await fs.lstat(e).catch((e) => {
if (extractErrorCode(e) === "ENOENT") return null;
throw e;
});
if (!t) return;
if (t.isSymbolicLink()) throw new Error("Refusing to write symlinked DREAMS.md");
if (!t.isFile()) throw new Error("Refusing to write non-file DREAMS.md");
}
async function writeDreamsFileAtomic(e, t, n) {
const r = captureMemoryMutationAuthority();
r?.();
const i = n ? getMemoryWorkspaceMaintenance(n) : void 0;
if (i) return await i.writeDreams(e, t, r);
const a = path.dirname(e);
const o = await fs.mkdir(a, { recursive: true }) ? 448 : (await fs.stat(a)).mode & 4095;
await assertSafeDreamsPath(e);
await replaceFileAtomic({
filePath: e,
content: t,
dirMode: o,
mode: 384,
preserveExistingMode: true,
tempPrefix: `${path.basename(e)}.dreams`,
throwOnCleanupError: true,
assertBeforeMutation: r
});
}
async function updateDreamsFile(e) {
return await withMemoryWorkspaceLock(e.workspaceDir, async () => {
const t = await resolveDreamsPath(e.workspaceDir);
const n = await readDreamsFile(t, e.workspaceDir);
const { content: r, result: i, shouldWrite: a = true } = await e.updater(n, t);
if (a) await writeDreamsFileAtomic(t, r.endsWith("\n") ? r : `${r}\n`, e.workspaceDir);
return i;
});
}
async function updateDeepDreamsFile(e) {
const t = e.bodyLines.join("\n");
return await updateDreamsFile({
workspaceDir: e.workspaceDir,
updater: (n, r) => ({
content: replaceManagedMarkdownBlock({
original: n,
heading: "## Deep Sleep",
startMarker: DEEP_START_MARKER,
endMarker: DEEP_END_MARKER,
body: t
}),
result: r,
shouldWrite: e.bodyLines.length > 0
})
});
}
const DIARY_START_MARKER = "<!-- openclaw:dreaming:diary:start -->";
const DIARY_END_MARKER = "<!-- openclaw:dreaming:diary:end -->";
const BACKFILL_ENTRY_MARKER = "openclaw:dreaming:backfill-entry";
const RECENT_DIARY_CONTEXT_LIMIT = 3;
const RECENT_DIARY_CONTEXT_MAX_CHARS = 360;
function formatNarrativeDate(e, t) {
const n = {
timeZone: t ?? process.env.TZ,
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "2-digit",
hour12: true,
timeZoneName: "short"
};
return new Intl.DateTimeFormat("en-US", n).format(new Date(e));
}
function ensureDiarySection(e) {
if (e.includes(DIARY_START_MARKER) && e.includes(DIARY_END_MARKER)) return e;
const t = `# Dream Diary\n\n${DIARY_START_MARKER}\n${DIARY_END_MARKER}\n`;
if (e.trim().length === 0) return t;
return t + "\n" + e;
}
function replaceDiaryContent(e, t) {
const n = ensureDiarySection(e);
const r = n.indexOf(DIARY_START_MARKER);
const i = n.indexOf(DIARY_END_MARKER);
if (r < 0 || i < 0 || i < r) return n;
const a = n.slice(0, r + 38);
const o = n.slice(i);
return a + (t.trim().length > 0 ? `\n${t.trim()}\n` : "\n") + o;
}
function splitDiaryBlocks(e) {
return e.split(/\n---\n/).map((e) => e.trim()).filter((e) => e.length > 0);
}
function clampDreamDiaryContextEntry(e) {
const t = e.replace(/\s+/g, " ").trim();
if (t.length <= RECENT_DIARY_CONTEXT_MAX_CHARS) return t;
return `${truncateUtf16Safe(t, RECENT_DIARY_CONTEXT_MAX_CHARS).trimEnd()}...`;
}
function diaryTextLines(e) {
return e.split("\n").map((e) => e.trim()).filter((e) => e.length > 0 && !e.startsWith("<!--") && !e.startsWith("#"));
}
function normalizeDiaryBlockBody(e) {
return clampDreamDiaryContextEntry(diaryTextLines(e).filter((e) => !(e.startsWith("*") && e.endsWith("*") && e.length > 2)).join(" "));
}
function isOptionalDiaryContextReadError(e) {
const t = extractErrorCode(e);
return t === "EACCES" || t === "EPERM" || t === "ERR_INVALID_UTF8" || isEmptyDreamsReadError(e, t);
}
function readDiaryBlocks(e) {
const t = e.indexOf(DIARY_START_MARKER);
const n = e.indexOf(DIARY_END_MARKER);
if (t < 0 || n < t) return null;
return splitDiaryBlocks(e.slice(t + 38, n));
}
function getDiaryContextEntries(e) {
return (readDiaryBlocks(e) ?? []).map(normalizeDiaryBlockBody).filter((e) => e.length > 0);
}
async function readRecentDreamDiaryEntries(e) {
const t = Math.max(0, Math.floor(e.limit ?? RECENT_DIARY_CONTEXT_LIMIT));
if (t === 0) return [];
let n;
try {
n = await readDreamsFile(await resolveDreamsPath(e.workspaceDir), e.workspaceDir);
} catch (e) {
if (isOptionalDiaryContextReadError(e)) return [];
throw e;
}
return getDiaryContextEntries(n).slice(-t).toReversed();
}
function normalizeDiaryBlockFingerprint(e) {
let t = "";
const n = [];
for (const r of diaryTextLines(e)) {
if (!t && r.startsWith("*") && r.endsWith("*") && r.length > 2) {
t = r.slice(1, -1).trim();
continue;
}
n.push(r);
}
return `${t.replace(/\s+/g, " ").trim()}\n${n.join("\n")}`;
}
function joinDiaryBlocks(e) {
return e.map((e) => `---\n\n${e.trim()}\n`).join("\n");
}
function dedupeDiaryBlocks(e, t = /* @__PURE__ */ new Set()) {
return e.filter((e) => {
const n = normalizeDiaryBlockFingerprint(e);
if (t.has(n)) return false;
t.add(n);
return true;
});
}
function filterDiaryContent(e, t) {
const n = ensureDiarySection(e);
const r = readDiaryBlocks(n);
if (!r) return {
updated: n,
removed: 0,
kept: 0
};
const i = t(r);
return {
updated: replaceDiaryContent(n, joinDiaryBlocks(i)),
removed: r.length - i.length,
kept: i.length
};
}
function stripBackfillDiaryBlocks(e) {
return filterDiaryContent(e, (e) => e.filter((e) => !e.includes(BACKFILL_ENTRY_MARKER)));
}
function formatBackfillDiaryDate(e) {
const t = /^(\d{4})-(\d{2})-(\d{2})$/.exec(e);
if (!t) return e;
const [, n, r, i] = t;
const a = {
timeZone: "UTC",
year: "numeric",
month: "long",
day: "numeric"
};
const o = Date.UTC(Number(n), Number(r) - 1, Number(i), 12);
return new Intl.DateTimeFormat("en-US", a).format(new Date(o));
}
function buildBackfillDiaryEntry(e) {
const t = formatBackfillDiaryDate(e.isoDay);
const n = `<!-- ${BACKFILL_ENTRY_MARKER} day=${e.isoDay}${e.sourcePath ? ` source=${e.sourcePath}` : ""} -->`;
const r = e.bodyLines.map((e) => e.trimEnd()).join("\n").trim();
return [
`*${t}*`,
n,
r
].filter((e) => e.length > 0).join("\n\n");
}
async function writeBackfillDiaryEntries(e) {
return await updateDreamsFile({
workspaceDir: e.workspaceDir,
updater: (t, n) => {
const r = e.preserveExisting ? {
updated: t,
removed: 0
} : stripBackfillDiaryBlocks(t);
const i = readDiaryBlocks(r.updated) ?? [];
const a = e.entries.map(buildBackfillDiaryEntry);
const o = new Set(i.map((e) => normalizeDiaryBlockFingerprint(e)));
const s = e.preserveExisting ? dedupeDiaryBlocks(a, o) : a;
const c = [...i, ...s];
return {
content: replaceDiaryContent(r.updated, joinDiaryBlocks(c)),
result: {
dreamsPath: n,
written: s.length,
replaced: r.removed
}
};
}
});
}
async function removeBackfillDiaryEntries(e) {
return await updateDreamsFile({
workspaceDir: e.workspaceDir,
updater: (e, t) => {
const n = stripBackfillDiaryBlocks(e);
return {
content: n.updated,
result: {
dreamsPath: t,
removed: n.removed
},
shouldWrite: n.removed > 0 || e.length > 0
};
}
});
}
async function dedupeDreamDiaryEntries(e) {
return await updateDreamsFile({
workspaceDir: e.workspaceDir,
updater: (e, t) => {
const { updated: n, removed: r, kept: i } = filterDiaryContent(e, dedupeDiaryBlocks);
return {
content: n,
result: {
dreamsPath: t,
removed: r,
kept: i
},
shouldWrite: r > 0
};
}
});
}
async function appendNarrativeEntry(e) {
const t = `\n---\n\n*${formatNarrativeDate(e.nowMs, e.timezone)}*\n\n${e.narrative}\n`;
return await updateDreamsFile({
workspaceDir: e.workspaceDir,
updater: async (n, r) => {
const i = e.sourceEntryKeys ?? [];
const a = i.length > 0 ? (await readStore(e.workspaceDir, new Date(e.nowMs).toISOString())).entries : void 0;
const o = new Set(getDiaryContextEntries(n));
if (i.some((e) => !a?.[e]) || e.recentDiaryEntries?.some((e) => !o.has(e))) return {
content: n,
result: void 0,
shouldWrite: false
};
let s;
if (n.includes(DIARY_START_MARKER) && n.includes(DIARY_END_MARKER)) {
const e = n.lastIndexOf(DIARY_END_MARKER);
s = n.slice(0, e) + t + "\n" + n.slice(e);
} else if (n.includes(DIARY_START_MARKER)) {
const e = n.indexOf(DIARY_START_MARKER) + 38;
s = n.slice(0, e) + t + "\n<!-- openclaw:dreaming:diary:end -->\n" + n.slice(e);
} else {
const e = `# Dream Diary\n\n${DIARY_START_MARKER}${t}\n${DIARY_END_MARKER}\n`;
s = n.trim().length === 0 ? e : `${e}\n${n}`;
}
return {
content: s,
result: r
};
}
});
}
//#endregion
export { isShortTermLockStealable as $, formatPromotedSnippetForMemory as A, normalizeMemoryPathForWorkspace as B, buildClaimHash as C, clampScore as D, calculateRecencyComponent as E, isShortTermSessionCorpusPath as F, resolvePromotionThresholds as G, normalizeSnippet as H, mergeProjectKeyLists as I, truncateShortTermSnippet as J, toFiniteNonNegativeInt as K, mergeRecentDistinct as L, isContaminatedDreamingSnippet as M, isGenericDailyHeading as N, compareStoreTimestampDesc as O, isShortTermMemoryPath as P, deleteShortTermLockEntryIfCurrent as Q, normalizeIsoDay as R, SHORT_TERM_BASENAME_RE as S, buildEntryKey as T, parseEntryRangeFromKey as U, normalizeShortTermRecallStore as V, parseStoreTimestampMs as W, normalizeConceptToken as X, deriveConceptTags as Y, summarizeConceptTagScriptCoverage as Z, readStore as _, readDreamsFile as a, writePhaseSignalStore as b, resolveDreamsPath as c, writeBackfillDiaryEntries as d, resolveLockPath as et, writeDreamsFileAtomic as f, readShortTermStore as g, readPhaseSignalStore as h, dedupeDreamDiaryEntries as i, hashQuery as j, enforceShortTermRecallStoreRetention as k, updateDeepDreamsFile as l, pruneShortTermStore as m, appendNarrativeEntry as n, withMemoryWorkspacePreparation as nt, readRecentDreamDiaryEntries as o, emptyPhaseSignalStore as p, totalSignalCountForEntry as q, clampDreamDiaryContextEntry as r, removeBackfillDiaryEntries as s, DREAMS_FILENAMES as t, withMemoryWorkspaceLock as tt, updateDreamsFile as u, resolvePhaseSignalPath as v, buildDailyClaimEntryKey as w, writeStore as x, resolveStorePath as y, normalizeMemoryPath as z };