openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
663 lines (662 loc) • 24.7 kB
JavaScript
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { r as terminalText } from "./safe-text-C80HAQ2e.mjs";
import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { _ as resolveDefaultAgentId, h as resolveConfiguredAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { n as resolvePreferredOpenClawTmpDir } from "./tmp-openclaw-dir-Bf0oU1Cn.mjs";
import { n as createNormalizedPluginsConfig } from "./config-state-B1JlHgba.mjs";
import { t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs";
import { r as theme } from "./theme-BOI0xyRZ.mjs";
import { E as resolveMemoryRemDreamingConfig } from "./dreaming-C72ZWZJr.mjs";
import { r as formatCliJsonFailure } from "./failure-output-DVVDqwuu.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./runtime-config-snapshot-Dy0VFqWf.mjs";
import "./memory-core-host-engine-storage-DcaZNQQh.mjs";
import { l as normalizeExtraMemoryPathEntries } from "./read-file-_FfN9cuw.mjs";
import { i as readMemorySearchManagerStatus } from "./types-Bo5s7TN4.mjs";
import { t as listAgentIdsCompatibility } from "./agent-scope-runtime-CDpr-vor.mjs";
import { i as withProgressTotals } from "./progress-DZHhZ1Fk.mjs";
import { t as resolveCommandSecretRefsViaGateway } from "./command-secret-gateway-Dh_PhH7v.mjs";
import { s as getMemoryEmbeddingCommandSecretTargetIds } from "./command-secret-targets-CH2XIeV_.mjs";
import { i as resolvePluginConfigObject } from "./plugin-config-runtime-CFUaG6iN.mjs";
import "./terminal-safe-text-DY8-BpAj.mjs";
import { r as withManager } from "./cli-utils-BPmaaZlG.mjs";
import "./temp-path-CW7QMeae.mjs";
import "./memory-core-host-status-B88S-xY5.mjs";
import "./memory-core-host-runtime-cli-BUOnGR8W.mjs";
import "./memory-core-host-runtime-core-vt7Kf2j2.mjs";
import { r as getActiveMemoryProvider } from "./memory-host-search-fc8laXW-.mjs";
import { d as writeBackfillDiaryEntries, s as removeBackfillDiaryEntries } from "./dreaming-dreams-file-Cbm7FmRe.mjs";
import { n as previewGroundedRemMarkdown } from "./rem-evidence-CFhxE14I.mjs";
import { i as removeGroundedShortTermCandidates } from "./short-term-promotion-B9mXaw_L.mjs";
import { h as DAILY_MEMORY_FILENAME_RE } from "./session-ingestion-BF9O-2hL.mjs";
import { i as seedHistoricalDailyMemorySignals } from "./dreaming-phases-DvqxrQ_N.mjs";
import { r as recordShortTermRecalls } from "./short-term-promotion-record-CRlApliA.mjs";
import { t as previewRemHarness } from "./rem-harness-CPJhVJom.mjs";
import { r as getMemorySearchManager } from "./memory-CbaBXNEU.mjs";
import { n as runSessionBackfill } from "./session-backfill-BKUhP7yJ.mjs";
import path from "node:path";
import fs from "node:fs/promises";
//#region extensions/memory-core/src/cli-memory-slot.ts
async function loadMemoryCommandConfig(e, t, n) {
const r = getMemoryEmbeddingCommandSecretTargetIds(n);
const i = n ?? await captureRuntimeConfigAsyncReader({ skipPluginValidation: true })();
try {
const { resolvedConfig: n, diagnostics: a, hadUnresolvedTargets: o } = await resolveCommandSecretRefsViaGateway({
config: i,
commandName: e,
targetIds: r,
...t ? { mode: t } : {}
});
if (o && resolveForeignMemorySlotOwner(i)) throw new Error(a.join("\n"));
return {
config: n,
diagnostics: a
};
} catch (n) {
const { code: r, ownerKind: a, ownerId: o, paths: s } = asNullableRecord(n) ?? {};
const c = formatErrorMessage(n);
if (t !== "read_only_status" || resolveForeignMemorySlotOwner(i) || a === "capability" && typeof o === "string" && o.startsWith("memory-provider:") || Array.isArray(s) && s.some((e) => typeof e === "string" && e.includes("memory.search.remote.apiKey")) || c.includes("capability:memory-provider:") || r !== "SECRET_SURFACE_UNAVAILABLE" && !c.includes("SECRET_SURFACE_UNAVAILABLE")) throw n;
return {
config: i,
diagnostics: [`${e}: ${c}; continuing with degraded read-only config so healthy memory surfaces remain visible.`]
};
}
}
/** Returns the plugin that owns the memory slot when it is not Memory Core. */
function resolveForeignMemorySlotOwner(e) {
const t = createNormalizedPluginsConfig(e.plugins).slots.memory;
return typeof t === "string" && t !== "memory-core" ? t : void 0;
}
/** Explains that a Memory Core command touches only its sidecar index. */
function formatMemoryCoreSidecarNotice(e) {
return `Memory Core is running as the consolidation sidecar; plugins.slots.memory selects "${e}". This command acts on Memory Core's sidecar index, not the agent's selected memory.`;
}
/**
* Reads the selected provider's health with host status authority, the same
* contract the host status scan uses, and always releases the provider lease.
*/
async function readSelectedMemoryProviderStatus(e) {
const { cfg: t, agentId: n, owner: r } = e;
let i = null;
let a = r;
let o;
try {
const { config: e } = await loadMemoryCommandConfig("memory status", "read_only_status", t);
const s = await getActiveMemoryProvider({
cfg: e,
agentId: n,
purpose: "status",
context: {
authority: {
kind: "host",
operation: "status"
},
assertCurrent() {}
}
});
i = s.provider;
o = i ? await i.health() : {
status: "unavailable",
message: s.error ?? "memory provider unavailable"
};
a = s.providerId ?? r;
} catch (e) {
o = {
status: "unavailable",
message: formatErrorMessage(e)
};
} finally {
await i?.close().catch(() => {});
}
return {
agentId: n,
provider: a,
health: o,
memoryCore: "consolidation-sidecar"
};
}
//#endregion
//#region extensions/memory-core/src/cli-runtime-common.ts
const { warn: warn$1 } = theme;
async function syncMemoryWithProgress(e) {
const t = e.elapsed ? Date.now() : 0;
let n = "Indexing memory…";
let r = 0;
let i = 0;
const formatDuration = (e) => {
const t = Math.floor(e / 1e3);
return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`;
};
const buildLabel = () => {
const e = Math.max(1, Date.now() - t);
const a = formatDuration(e);
if (i <= 0 || r <= 0) return `${n} · elapsed ${a}`;
const o = Math.max(0, (i - r) * e / r);
return `${n} · elapsed ${a} · eta ${formatDuration(o)}`;
};
await withProgressTotals({
label: n,
total: 0,
fallback: e.options.verbose ? "line" : void 0
}, async (t, a) => {
const o = e.elapsed ? setInterval(() => a.setLabel(buildLabel()), 1e3) : void 0;
try {
await e.sync({
reason: "cli",
force: Boolean(e.options.force),
progress: (o) => {
if (o.label) n = terminalText`${o.label}`;
r = o.completed;
i = o.total;
t({
completed: o.completed,
total: o.total,
label: e.elapsed ? buildLabel() : o.label === void 0 ? void 0 : terminalText`${o.label}`
});
if (e.elapsed) a.setLabel(buildLabel());
else if (o.label) a.setLabel(terminalText`${o.label}`);
}
});
} catch (t) {
if (!e.onError) throw t;
e.onError(t);
} finally {
if (o !== void 0) clearInterval(o);
}
});
}
function emitMemoryCommandWarning(e, t) {
defaultRuntime[t ? "error" : "log"](warn$1(terminalText`${e}`));
}
/** Tells the operator that a Memory Core command acts on its sidecar index only. */
function emitMemoryCoreSidecarNotice(e, t) {
emitMemoryCommandWarning(formatMemoryCoreSidecarNotice(e), Boolean(t?.json));
}
function resolveMemoryPluginConfig(e) {
return resolvePluginConfigObject(e, "memory-core") ?? {};
}
function formatAuditCounts(e) {
const t = e.conceptTagScripts;
const n = t ? [
"latin",
"cjk",
"mixed",
"other"
].flatMap((e) => {
const n = t[`${e}EntryCount`];
return n > 0 ? [`${n} ${e}`] : [];
}).join(", ") : "";
const r = n ? ` · scripts=${n}` : "";
return `${e.entryCount} entries · ${e.promotedCount} promoted · ${e.conceptTaggedEntryCount} concept-tagged · ${e.spacedEntryCount} spaced${r}`;
}
function resolveExplicitMemoryAgent(e, t) {
const n = t?.trim();
if (t !== void 0 && !n) throw new Error("--agent must not be blank");
return n ? resolveConfiguredAgentId(e, n) : void 0;
}
function resolveMemoryAgent(e, t) {
return resolveExplicitMemoryAgent(e, t) ?? resolveDefaultAgentId(e);
}
function resolveMemoryAgentIds(e, t) {
const n = resolveExplicitMemoryAgent(e, t);
return n === void 0 ? listAgentIdsCompatibility(e) : [n];
}
function formatExtraPaths(e, t) {
return normalizeExtraMemoryPathEntries(e, t).map((e) => {
const t = shortenHomePath(e.path);
const n = [...e.pattern ? [`pattern: ${e.pattern}`] : [], ...e.evergreen ? ["evergreen"] : []];
return n.length > 0 ? `${t} (${n.join(", ")})` : t;
});
}
async function withMemoryCommand(e) {
const { agent: t, json: n } = e.options;
const r = n && !e.allAgents ? defaultRuntime.writeJson : void 0;
const { config: i, diagnostics: a } = await loadMemoryCommandConfig(e.commandName, e.purpose === "status" ? "read_only_status" : void 0);
for (const e of a) emitMemoryCommandWarning(`[secrets] ${e}`, n === true);
const o = resolveForeignMemorySlotOwner(i);
if (o && e.requiresMemorySlot) {
const n = `${e.commandName} reads only Memory Core's sidecar index, but plugins.slots.memory selects "${o}". Search the selected memory through the agent's memory tools or the ${o} plugin's own commands.`;
defaultRuntime.error(terminalText`${n}`);
process.exitCode = 1;
r?.({
...formatCliJsonFailure(n),
agentId: resolveMemoryAgent(i, t)
});
return i;
}
if (o) emitMemoryCoreSidecarNotice(o, { json: n });
const s = e.allAgents ? resolveMemoryAgentIds(i, t) : [resolveMemoryAgent(i, t)];
for (const t of s) await withManager({
getManager: () => getMemorySearchManager({
cfg: i,
agentId: t,
purpose: e.purpose,
inspectSources: e.inspectSources,
acquireLocalService: e.acquireLocalService,
runInBackgroundContext: e.runInBackgroundContext
}),
onMissing: (n) => {
if (!n?.trim()) {
defaultRuntime.log("Memory search disabled.");
r?.({
agentId: t,
status: "disabled"
});
return;
}
const i = `${e.commandName} failed (${t}): ${n}`;
defaultRuntime.error(terminalText`${i}`);
process.exitCode = 1;
r?.({
...formatCliJsonFailure(i),
agentId: t
});
},
onCloseError: (e) => defaultRuntime.error(terminalText`Memory manager close failed: ${formatErrorMessage(e)}`),
close: async (e) => {
await e.close?.();
},
run: async (n) => e.run({
manager: n,
cfg: i,
agentId: t
})
});
return i;
}
async function scanMemoryManagerSources(e) {
if (!e.sourceCounts?.length) return;
const t = e.sourceCounts.map((e) => ({
source: e.source,
totalFiles: e.eligible ?? null,
issues: e.issues ?? []
}));
return {
sources: t,
totalFiles: t.some((e) => e.totalFiles === null) ? null : t.reduce((e, t) => e + (t.totalFiles ?? 0), 0),
issues: t.flatMap((e) => e.issues)
};
}
function formatMemoryIndexOutcome(e, t, n) {
const r = e.files ?? 0;
if (r === 0 && e.workspaceDir && t?.totalFiles === 0) return `No memory files found in ${shortenHomePath(e.workspaceDir)}; nothing indexed (${n}).`;
return `Memory index updated (${n}): ${r} ${r === 1 ? "file" : "files"} indexed.`;
}
//#endregion
//#region extensions/memory-core/src/cli-rem.runtime.ts
const { heading, muted, warn } = theme;
async function runMemorySessionBackfill(e, t) {
await withMemoryCommand({
commandName: "memory session-backfill",
options: e,
purpose: "status",
...t,
run: async ({ manager: t, cfg: n, agentId: r }) => {
const i = (await readMemorySearchManagerStatus(t)).workspaceDir?.trim();
if (!i) throw new Error("Memory session-backfill requires a resolvable workspace directory.");
if (e.rollback && (e.apply || e.rem || e.from || e.to || e.archiveFiles?.length)) throw new Error("Memory session-backfill --rollback cannot be combined with input, range, --rem, or --apply options.");
const a = resolveMemoryPluginConfig(n);
const o = resolveMemoryRemDreamingConfig({
pluginConfig: a,
cfg: n
});
printSessionBackfillResult(await runSessionBackfill({
agentId: r,
workspaceDir: i,
pluginConfig: a,
from: e.from,
to: e.to,
limitDays: e.limitDays,
rem: e.rem,
apply: e.apply,
rollback: e.rollback,
archiveFiles: e.archiveFiles,
timezone: o.timezone
}), e);
}
});
}
function printSessionBackfillResult(e, t) {
if (t.json) {
defaultRuntime.writeJson(e);
return;
}
if (e.rollback) {
defaultRuntime.log([
`${heading("Session Backfill")} ${muted("(rollback)")}`,
muted(terminalText`workspace=${shortenHomePath(e.workspaceDir)}`),
muted(`removedDiaryEntries=${e.rollback.removedDiaryEntries}`),
muted(`removedStagedEntries=${e.rollback.removedStagedEntries}`)
].join("\n"));
return;
}
const n = [
`${heading("Session Backfill")} ${muted(terminalText`(${e.agentId})`)}`,
muted(terminalText`workspace=${shortenHomePath(e.workspaceDir)}`),
muted(`batches=${e.batchCount ?? 1} days=${e.days.length} candidates=${e.candidateCount} staged=${e.stagedEntries}`)
];
for (const t of e.batches ?? []) n.push(muted(`batch=${t.batch} days=${t.days} candidates=${t.candidates} staged=${t.stagedEntries}`));
for (const t of e.days) {
n.push("", heading(terminalText`${t.day}`), muted(`candidates=${t.candidateCount}`));
n.push(...t.topCandidates.map((e) => terminalText`- ${e}`));
}
if (e.days.length === 0) n.push("", "No new hash-untracked trusted session candidates.");
if (!e.applied && !e.rem) n.push("", muted("Dry run; use --apply to stage candidates."));
defaultRuntime.log(n.join("\n"));
}
async function runMemoryRemHarness(e, t) {
await withMemoryCommand({
commandName: "memory rem-harness",
options: e,
purpose: "status",
...t,
run: async ({ manager: t, cfg: n, agentId: r }) => {
const i = (await readMemorySearchManagerStatus(t)).workspaceDir?.trim();
const a = resolveMemoryPluginConfig(n);
const o = resolveMemoryRemDreamingConfig({
pluginConfig: a,
cfg: n
});
const s = Date.now();
const previewWorkspace = async (t, r) => {
if (!t) throw new Error("Memory rem-harness requires a resolvable workspace directory.");
const i = r ? await seedHistoricalDailyMemorySignals({
workspaceDir: t,
filePaths: r.workspaceSourceFiles,
limit: o.limit,
nowMs: s,
timezone: o.timezone
}) : void 0;
const c = await previewRemHarness({
workspaceDir: t,
cfg: n,
pluginConfig: a,
grounded: Boolean(e.grounded),
groundedInputPaths: r?.workspaceSourceFiles ?? [],
includePromoted: Boolean(e.includePromoted),
nowMs: s
});
return {
workspaceDir: t,
sourceFiles: r?.sourceFiles ?? [],
seeded: i,
preview: c
};
};
const { workspaceDir: c, sourceFiles: l, seeded: u, preview: d } = e.path ? await withHistoricalMemoryWorkspace("rem-harness", e.path, (e) => previewWorkspace(e.workspaceDir, e)) : await previewWorkspace(i ?? "");
const f = u?.importedFileCount ?? 0;
const p = u?.importedSignalCount ?? 0;
const m = u?.skippedPaths ?? [];
const h = d.groundedInputPaths;
const g = d.rem;
const _ = d.grounded;
const v = d.deep.candidates;
if (e.json) {
defaultRuntime.writeJson({
workspaceDir: c,
sourcePath: e.path ? path.resolve(e.path) : null,
sourceFiles: l,
historicalImport: e.path ? {
importedFileCount: f,
importedSignalCount: p,
skippedPaths: m
} : null,
remConfig: d.remConfig,
deepConfig: {
minScore: d.deepConfig.minScore,
minRecallCount: d.deepConfig.minRecallCount,
minUniqueQueries: d.deepConfig.minUniqueQueries,
recencyHalfLifeDays: d.deepConfig.recencyHalfLifeDays,
maxAgeDays: d.deepConfig.maxAgeDays ?? null,
maxPromotedSnippetTokens: d.deepConfig.maxPromotedSnippetTokens
},
rem: {
skipped: d.remSkipped,
...g
},
grounded: _,
deep: {
candidateCount: d.deep.candidateCount,
candidates: v
}
});
return;
}
const y = [
`${heading("REM Harness")} ${muted(terminalText`(${r})`)}`,
muted(terminalText`workspace=${shortenHomePath(c)}`),
...e.path ? [
muted(terminalText`sourcePath=${shortenHomePath(path.resolve(e.path))}`),
muted(`historicalFiles=${l.length} importedFiles=${f} importedSignals=${p}`),
...m.length > 0 ? [warn(terminalText`skipped=${m.map((e) => shortenHomePath(e)).join(", ")}`)] : []
] : [],
...e.grounded ? [muted(terminalText`groundedInputs=${h.length > 0 ? h.map((e) => shortenHomePath(e)).join(", ") : "none"}`)] : [],
muted(`recentRecallEntries=${d.recallEntryCount} deepCandidates=${v.length}`),
"",
heading("REM Preview"),
...g.bodyLines.map((e) => terminalText`${e}`),
..._ ? [
"",
heading("Grounded REM"),
..._.files.flatMap((e) => [
muted(terminalText`${e.path}`),
e.renderedMarkdown.split("\n").map((e) => terminalText`${e}`).join("\n"),
""
])
] : [],
"",
heading("Deep Candidates"),
...v.length > 0 ? v.slice(0, 10).map((e) => terminalText`${e.score.toFixed(3)} ${e.snippet} [${shortenHomePath(e.path)}:${e.startLine}-${e.endLine}]`) : ["- No deep candidates."]
];
defaultRuntime.log(y.join("\n"));
}
});
}
async function runMemoryRemBackfill(e, t) {
await withMemoryCommand({
commandName: "memory rem-backfill",
options: e,
purpose: "status",
...t,
run: async ({ manager: t, cfg: n, agentId: r }) => {
const i = (await readMemorySearchManagerStatus(t)).workspaceDir?.trim();
const a = resolveMemoryPluginConfig(n);
const o = resolveMemoryRemDreamingConfig({
pluginConfig: a,
cfg: n
});
if (!i) throw new Error("Memory rem-backfill requires a resolvable workspace directory.");
if (e.rollback || e.rollbackShortTerm) {
const t = e.rollback ? await removeBackfillDiaryEntries({ workspaceDir: i }) : null;
const n = e.rollbackShortTerm ? await removeGroundedShortTermCandidates({ workspaceDir: i }) : null;
if (e.json) {
defaultRuntime.writeJson({
workspaceDir: i,
rollback: Boolean(e.rollback),
rollbackShortTerm: Boolean(e.rollbackShortTerm),
...t ? {
dreamsPath: t.dreamsPath,
removedEntries: t.removed
} : {},
...n ? {
shortTermStorePath: n.storePath,
removedShortTermEntries: n.removed
} : {}
});
return;
}
defaultRuntime.log([
`${heading("REM Backfill")} ${muted("(rollback)")}`,
muted(terminalText`workspace=${shortenHomePath(i)}`),
...t ? [muted(terminalText`dreamsPath=${shortenHomePath(t.dreamsPath)}`), muted(`removedEntries=${t.removed}`)] : [],
...n ? [muted(terminalText`shortTermStorePath=${shortenHomePath(n.storePath)}`), muted(`removedShortTermEntries=${n.removed}`)] : []
].join("\n"));
return;
}
if (!e.path) throw new Error("Memory rem-backfill requires --path <file-or-dir> unless using --rollback.");
const { sourceFiles: s, groundedFiles: c, written: l, stagedShortTermEntries: u, replacedShortTermEntries: d } = await withHistoricalMemoryWorkspace("rem-backfill", e.path, async ({ workspaceDir: t, sourceFiles: n, workspaceSourceFiles: r }) => {
const a = await previewGroundedRemMarkdown({
workspaceDir: t,
inputPaths: r
});
const s = new Map(r.map((e, r) => [path.relative(t, e).replace(/\\/g, "/"), n[r] ?? e]));
const c = a.files.map((e) => {
const t = extractIsoDayFromPath(e.path);
if (!t) return null;
return {
isoDay: t,
sourcePath: s.get(e.path) ?? e.path,
bodyLines: groundedMarkdownToDiaryLines(e.renderedMarkdown)
};
}).filter((e) => e !== null);
const l = await writeBackfillDiaryEntries({
workspaceDir: i,
entries: c,
timezone: o.timezone
});
let u = 0;
let d = 0;
if (e.stageShortTerm) {
d = (await removeGroundedShortTermCandidates({ workspaceDir: i })).removed;
const e = collectGroundedShortTermSeedItems(a.files);
if (e.length > 0) await recordShortTermRecalls({
workspaceDir: i,
query: "__dreaming_grounded_backfill__",
signalType: "grounded",
results: e,
dedupeByQueryPerDay: true,
nowMs: Date.now(),
timezone: o.timezone
});
u = e.length;
}
return {
sourceFiles: n,
groundedFiles: a.scannedFiles,
written: l,
stagedShortTermEntries: u,
replacedShortTermEntries: d
};
});
if (e.json) {
defaultRuntime.writeJson({
workspaceDir: i,
sourcePath: path.resolve(e.path),
sourceFiles: s,
groundedFiles: c,
writtenEntries: l.written,
replacedEntries: l.replaced,
dreamsPath: l.dreamsPath,
...e.stageShortTerm ? {
stagedShortTermEntries: u,
replacedShortTermEntries: d
} : {}
});
return;
}
defaultRuntime.log([
`${heading("REM Backfill")} ${muted(terminalText`(${r})`)}`,
muted(terminalText`workspace=${shortenHomePath(i)}`),
muted(terminalText`sourcePath=${shortenHomePath(path.resolve(e.path))}`),
muted(`historicalFiles=${s.length} writtenEntries=${l.written} replacedEntries=${l.replaced}`),
...e.stageShortTerm ? [muted(`stagedShortTermEntries=${u} replacedShortTermEntries=${d}`)] : [],
muted(terminalText`dreamsPath=${shortenHomePath(l.dreamsPath)}`)
].join("\n"));
}
});
}
async function listHistoricalDailyFiles(e) {
const t = path.resolve(e);
let n;
try {
n = await fs.stat(t);
} catch (e) {
if (e?.code === "ENOENT") return [];
throw e;
}
if (n.isFile()) return DAILY_MEMORY_FILENAME_RE.test(path.basename(t)) ? [t] : [];
if (!n.isDirectory()) return [];
return (await fs.readdir(t, { withFileTypes: true })).filter((e) => e.isFile() && DAILY_MEMORY_FILENAME_RE.test(e.name)).map((e) => path.join(t, e.name)).toSorted((e, t) => path.basename(e).localeCompare(path.basename(t)));
}
async function withHistoricalMemoryWorkspace(e, t, n) {
const r = await listHistoricalDailyFiles(t);
if (r.length === 0) throw new Error(`Memory ${e} found no YYYY-MM-DD.md files at ${shortenHomePath(path.resolve(t))}.`);
const i = await fs.mkdtemp(path.join(resolvePreferredOpenClawTmpDir(), `openclaw-${e}-`));
try {
const e = path.join(i, "memory");
await fs.mkdir(e, { recursive: true });
const t = [];
for (const n of r) {
const r = path.join(e, path.basename(n));
await fs.copyFile(n, r);
t.push(r);
}
return await n({
workspaceDir: i,
sourceFiles: r,
workspaceSourceFiles: t
});
} finally {
await fs.rm(i, {
recursive: true,
force: true
});
}
}
function extractIsoDayFromPath(e) {
return path.basename(e).match(DAILY_MEMORY_FILENAME_RE)?.[1] ?? null;
}
function groundedMarkdownToDiaryLines(e) {
return e.split(/\r?\n/).map((e) => e.replace(/^##\s+/, "").trimEnd()).filter((e, t, n) => !(e.length === 0 && n[t - 1]?.length === 0));
}
function parseGroundedRef(e, t) {
const n = t.trim().match(/^(.*?):(\d+)(?:-(\d+))?$/);
if (!n) return null;
return {
path: (n[1] ?? e).replaceAll("\\", "/").replace(/^\.\//, ""),
startLine: Math.max(1, Number(n[2])),
endLine: Math.max(1, Number(n[3] ?? n[2]))
};
}
function collectGroundedShortTermSeedItems(e) {
const t = [];
const n = /* @__PURE__ */ new Set();
for (const r of e) {
const e = extractIsoDayFromPath(r.path) ?? void 0;
for (const [i, a, o, s] of [[
r.memoryImplications,
.92,
"__dreaming_grounded_backfill__:lasting-update",
2
], [
r.candidates.filter((e) => e.lean === "likely_durable"),
.82,
"__dreaming_grounded_backfill__:candidate",
1
]]) for (const c of i) {
if (!c.text.trim()) continue;
const i = c.refs.find((e) => e.trim().length > 0);
const l = i ? parseGroundedRef(r.path, i) : null;
if (!l) continue;
const u = `${l.path}:${l.startLine}:${l.endLine}:${o}:${c.text.toLowerCase()}`;
if (n.has(u)) continue;
n.add(u);
t.push({
source: "memory",
path: l.path,
startLine: l.startLine,
endLine: l.endLine,
snippet: c.text,
score: a,
query: o,
signalCount: s,
...e ? { dayBucket: e } : {}
});
}
}
return t;
}
//#endregion
export { emitMemoryCoreSidecarNotice as a, formatMemoryIndexOutcome as c, resolveMemoryPluginConfig as d, scanMemoryManagerSources as f, resolveForeignMemorySlotOwner as g, readSelectedMemoryProviderStatus as h, runMemorySessionBackfill as i, resolveMemoryAgent as l, withMemoryCommand as m, runMemoryRemBackfill as n, formatAuditCounts as o, syncMemoryWithProgress as p, runMemoryRemHarness as r, formatExtraPaths as s, printSessionBackfillResult as t, resolveMemoryAgentIds as u };