openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,095 lines (1,094 loc) • 40.6 kB
JavaScript
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "../../string-coerce-CCIiB4H7.mjs";
import { t as asNonArrayRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { a as extractErrorCode } from "../../error-coercion-hDrHOSGy.mjs";
import { b as uniqueStrings } from "../../string-normalization-DLmfYZXI.mjs";
import { t as formatErrorMessage } from "../../errors-BKzCeTYb.mjs";
import { n as normalizeAgentId } from "../../agent-id-CQjtp2ft.mjs";
import { S as resolveSessionAgentIdStrict, _ as resolveDefaultAgentId } from "../../agent-scope-config-DmXgFGKP.mjs";
import { r as createLazyRuntimeModule } from "../../lazy-runtime-zGjszCtt.mjs";
import { n as createNormalizedPluginsConfig } from "../../config-state-B1JlHgba.mjs";
import { n as parseNonNegativeByteSize } from "../../byte-size-DzE8zt88.mjs";
import { n as SILENT_REPLY_TOKEN } from "../../tokens-CcE6ESvH.mjs";
import { t as ErrorCodes } from "../../gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "../../error-codes-BzF7aRQ0.mjs";
import { n as jsonResult } from "../../tool-results-CcV0sxnb.mjs";
import { c as readNonNegativeIntegerParam, m as readToolStringParam, u as readPositiveIntegerParam } from "../../common-njQNtpnW.mjs";
import { E as resolveMemoryRemDreamingConfig, _ as formatMemoryDreamingDay, c as LEGACY_MEMORY_LIGHT_DREAMING_CRON_NAME, d as LEGACY_MEMORY_REM_DREAMING_CRON_NAME, f as LEGACY_MEMORY_REM_DREAMING_CRON_TAG, g as MEMORY_DREAMING_SYSTEM_EVENT_TEXT, h as MANAGED_MEMORY_DREAMING_CRON_TAG, l as LEGACY_MEMORY_LIGHT_DREAMING_CRON_TAG, m as MANAGED_MEMORY_DREAMING_CRON_NAME, p as LEGACY_MEMORY_REM_DREAMING_EVENT_TEXT, u as LEGACY_MEMORY_LIGHT_DREAMING_EVENT_TEXT, w as resolveMemoryDreamingWorkspaces, x as resolveMemoryDreamingPluginConfig, y as resolveMemoryDeepDreamingConfig } from "../../dreaming-C72ZWZJr.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../error-runtime-BM740gJj.mjs";
import "../../routing-DmgGYTrU.mjs";
import { t as listAgentIdsCompatibility } from "../../agent-scope-runtime-CDpr-vor.mjs";
import { t as resolveEffectiveCompactionReserveTokens } from "../../agent-compaction-constants--sURQdcI.mjs";
import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.mjs";
import { i as resolvePluginConfigObject } from "../../plugin-config-runtime-CFUaG6iN.mjs";
import { n as resolveCronStyleNow } from "../../current-time-DitOGqc6.mjs";
import { t as DEFAULT_AGENT_COMPACTION_RESERVE_TOKENS_FLOOR } from "../../agent-settings-Chrl5MIo.mjs";
import { r as runWithLocalStateMutationOwner } from "../../local-state-owner-CnxUSfeW.mjs";
import "../../gateway-runtime-Du0olVch.mjs";
import "../../channel-actions-DxuDuzvg.mjs";
import "../../memory-core-host-status-B88S-xY5.mjs";
import "../../memory-core-host-runtime-core-vt7Kf2j2.mjs";
import { t as resolveMemoryBackendConfig } from "../../memory-core-host-runtime-files-D9uE5uTx.mjs";
import "../../param-readers-CVZN1591.mjs";
import { n as registerMemoryCoreCli } from "../../cli-metadata-CfZzgcWQ.mjs";
import { f as configureMemoryCoreDreamingState } from "../../dreaming-state-DzOG6jkz.mjs";
import { t as MANAGED_DREAMING_DECLARATION_KEY } from "../../dreaming-cron-contract-BaLk3g0c.mjs";
import { n as includesSystemEventToken, t as formatRecallRepairDetails } from "../../dreaming-shared-BXVwrm4P.mjs";
import { t as classifyDreamingCronJob } from "../../dreaming-cron-classifier-kpnYr6DC.mjs";
import { t as resolveMemoryCoreNowMs } from "../../time-C9K_N17D.mjs";
import { t as appendFailedDreamingEvent } from "../../dreaming-events-j1JNkKH0.mjs";
import { r as resolveMemoryPromotionFileMaxChars } from "../../memory-budget-Wo4Ecu71.mjs";
import { a as resolveMemoryToolContext, i as buildProjectMemoryWriteInstruction, n as MEMORY_SEARCH_TOOL_CONTRACT, r as buildMemoryPromptSection, t as MEMORY_GET_TOOL_CONTRACT } from "../../memory-tool-contract-C3hPFPsg.mjs";
import { a as retainMemoryIndexingAgents, i as prepareMemoryManagerReload } from "../../lifecycle-CCh9W0s9.mjs";
import { t as normalizeSessionBackfillSelection } from "../../session-backfill-selection-B7LMr3S_.mjs";
//#region extensions/memory-core/src/dreaming-cron.ts
/** Stateless convergence of the memory-core-owned dreaming cron job family. */
const dreamingCronIdentifiers = {
LEGACY_MEMORY_LIGHT_DREAMING_CRON_NAME,
LEGACY_MEMORY_LIGHT_DREAMING_CRON_TAG,
LEGACY_MEMORY_LIGHT_DREAMING_EVENT_TEXT,
LEGACY_MEMORY_REM_DREAMING_CRON_NAME,
LEGACY_MEMORY_REM_DREAMING_CRON_TAG,
LEGACY_MEMORY_REM_DREAMING_EVENT_TEXT,
MANAGED_MEMORY_DREAMING_CRON_NAME,
MANAGED_MEMORY_DREAMING_CRON_TAG,
MEMORY_DREAMING_SYSTEM_EVENT_TEXT
};
function resolveManagedCronDescription(e) {
const t = e.recencyHalfLifeDays;
return `${MANAGED_MEMORY_DREAMING_CRON_TAG} Promote weighted short-term recalls into MEMORY.md (limit=${e.limit}, minScore=${e.minScore.toFixed(3)}, minRecallCount=${e.minRecallCount}, minUniqueQueries=${e.minUniqueQueries}, recencyHalfLifeDays=${t}, maxAgeDays=${e.maxAgeDays ?? "none"}).`;
}
function buildManagedDreamingCronJob(e) {
return {
declarationKey: MANAGED_DREAMING_DECLARATION_KEY,
name: MANAGED_MEMORY_DREAMING_CRON_NAME,
description: resolveManagedCronDescription(e),
enabled: true,
schedule: {
kind: "cron",
expr: e.cron,
...e.timezone ? { tz: e.timezone } : {}
},
sessionTarget: "isolated",
wakeMode: "now",
payload: {
kind: "agentTurn",
message: MEMORY_DREAMING_SYSTEM_EVENT_TEXT,
lightContext: true
},
delivery: { mode: "none" }
};
}
function buildManagedDreamingPatch(e, t) {
const n = {};
if (normalizeOptionalString(e.name) !== t.name) n.name = t.name;
if (normalizeOptionalString(e.description) !== t.description) n.description = t.description;
const r = normalizeLowercaseStringOrEmpty(e.schedule?.kind);
const i = normalizeOptionalString(e.schedule?.expr);
const a = normalizeOptionalString(e.schedule?.tz);
if (r !== "cron" || i !== t.schedule.expr || a !== t.schedule.tz) n.schedule = t.schedule;
if (normalizeLowercaseStringOrEmpty(e.sessionTarget) !== t.sessionTarget) n.sessionTarget = t.sessionTarget;
if (normalizeLowercaseStringOrEmpty(e.wakeMode) !== "now") n.wakeMode = "now";
if (normalizeOptionalString(e.payload?.message) !== t.payload.message || e.payload?.lightContext !== t.payload.lightContext) n.payload = t.payload;
if (normalizeLowercaseStringOrEmpty(e.delivery?.mode) !== "none") n.delivery = t.delivery;
return Object.keys(n).length > 0 ? n : null;
}
async function reconcileShortTermDreamingCronJob(e) {
const t = e.cron;
if (!t) return {
status: "unavailable",
removed: 0
};
const n = await t.list({ includeDisabled: true });
const r = n.filter((e) => e.declarationKey === MANAGED_DREAMING_DECLARATION_KEY);
let i = false;
const a = [];
for (const e of n) {
const t = classifyDreamingCronJob(e, dreamingCronIdentifiers);
if (t === "ambiguous") a.push(e.id);
else if (t === "legacy" || t === "phase") i = true;
}
if (a.length > 0) e.logger.warn(`memory-core: cron jobs ${a.join(", ")} retain historical dreaming tags with authored payloads; rows left unchanged. Review their ownership manually.`);
const needsDoctor = (t) => {
e.logger.warn("memory-core: historical dreaming cron jobs require repair; run openclaw doctor --fix. Runtime reconciliation left legacy jobs unchanged.");
return {
status: "doctor-required",
removed: t
};
};
const removeJobs = async (n, r) => {
let i = 0;
for (const a of n) try {
if ((await t.remove(a.id)).removed === true) i += 1;
} catch (t) {
e.logger.warn(`memory-core: failed to ${r} managed dreaming cron job ${a.id}: ${formatErrorMessage(t)}`);
}
return i;
};
if (!e.config.enabled) {
const t = await removeJobs(r, "remove");
if (t > 0) e.logger.info(`memory-core: removed ${t} managed dreaming cron job(s).`);
return i ? needsDoctor(t) : {
status: "disabled",
removed: t
};
}
if (r.find((e) => e.payload?.kind !== "agentTurn") || i) return needsDoctor(0);
const o = buildManagedDreamingCronJob(e.config);
const s = r[0];
if (!s) {
try {
await t.add(o);
} catch (e) {
if (extractErrorCode(e) === "AGENT_SELECTION_REQUIRED") return {
status: "owner-required",
removed: 0
};
throw e;
}
e.logger.info("memory-core: created managed dreaming cron job.");
return {
status: "added",
removed: 0
};
}
const c = await removeJobs(r.filter((e) => e.id !== s.id), "prune duplicate");
const l = buildManagedDreamingPatch(s, o);
if (!l) {
if (c > 0) e.logger.info("memory-core: pruned duplicate managed dreaming cron jobs.");
return {
status: "noop",
removed: c
};
}
await t.update(s.id, l);
e.logger.info("memory-core: updated managed dreaming cron job.");
return {
status: "updated",
removed: c
};
}
//#endregion
//#region extensions/memory-core/src/dreaming.ts
const RUNTIME_CRON_RECONCILE_INTERVAL_MS = 6e4;
function formatRepairSummary(e) {
const t = [];
if (e.rewroteStore) {
const n = formatRecallRepairDetails(e);
t.push(`rewrote recall store${n ? ` (${n})` : ""}`);
}
if (e.removedStaleLock) t.push("removed stale promotion lock");
return t.join(", ");
}
async function runShortTermDreamingPromotion(e) {
const t = e.config.recencyHalfLifeDays;
const n = normalizeOptionalString(e.workspaceDir);
const r = normalizeLowercaseStringOrEmpty(e.agentId);
const i = e.cfg ? resolveMemoryDreamingWorkspaces(e.cfg, {
primaryWorkspaceDir: n,
...r ? { primaryAgentId: r } : {}
}).map(({ workspaceDir: e, agentIds: t }) => {
const n = r && t.includes(r) ? r : t.toSorted()[0] ?? r;
return n ? {
agentId: n,
agentIds: t,
workspaceDir: e
} : {
agentIds: t,
workspaceDir: e
};
}) : [];
if (i.length === 0 && n) i.push({
...r ? { agentId: r } : {},
agentIds: [r],
workspaceDir: n
});
if (i.length === 0) {
e.logger.warn("memory-core: dreaming promotion skipped because no memory workspace is available.");
return {
handled: true,
reason: "memory-core: short-term dreaming missing workspace"
};
}
if (e.config.limit === 0) {
e.logger.info("memory-core: dreaming promotion skipped because limit=0.");
return {
handled: true,
reason: "memory-core: short-term dreaming disabled by limit"
};
}
if (e.config.verboseLogging) e.logger.info(`memory-core: dreaming verbose enabled (cron=${e.config.cron}, limit=${e.config.limit}, minScore=${e.config.minScore.toFixed(3)}, minRecallCount=${e.config.minRecallCount}, minUniqueQueries=${e.config.minUniqueQueries}, recencyHalfLifeDays=${t}, maxAgeDays=${e.config.maxAgeDays ?? "none"}, workspaces=${i.length}).`);
let a = 0;
let o = 0;
let s = 0;
let c = 0;
let l = 0;
const u = e.cfg ? resolveMemoryDreamingPluginConfig(e.cfg) : void 0;
const [{ writeDeepDreamingReport: d }, { appendFallbackNarrativeEntry: f, runDreamNarrative: p }, { runDreamingSweepPhases: m }, { applyShortTermPromotions: h, repairShortTermPromotionArtifacts: g, rankShortTermPromotionCandidates: _ }] = await Promise.all([
import("../../dreaming-markdown-D3J-JrnK.mjs"),
import("../../dreaming-narrative-yUBhSlEQ.mjs"),
import("../../dreaming-phases-lieQJ-oZ.mjs"),
import("../../short-term-promotion-BK4ZwuHV.mjs")
]);
for (const { agentId: n, agentIds: r, workspaceDir: v } of i) {
const i = Date.now();
let y;
try {
y = await m({
agentId: n,
workspaceDir: v,
pluginConfig: u,
cfg: e.cfg,
logger: e.logger,
nowMs: i
});
} catch (t) {
s += 1;
e.logger.error(`memory-core: dreaming sweep failed for workspace ${v}: ${formatErrorMessage(t)}`);
continue;
}
const { narratives: b, failed: x } = y;
if (x) s += 1;
else try {
const s = [];
const c = await g({ workspaceDir: v });
if (c.changed) {
e.logger.info(`memory-core: normalized recall artifacts before dreaming (${formatRepairSummary(c)}) [workspace=${v}].`);
s.push(`- Repaired recall artifacts: ${formatRepairSummary(c)}.`);
}
const l = await _({
workspaceDir: v,
limit: e.config.limit,
minScore: e.config.minScore,
minRecallCount: e.config.minRecallCount,
minUniqueQueries: e.config.minUniqueQueries,
recencyHalfLifeDays: t,
maxAgeDays: e.config.maxAgeDays,
nowMs: i
});
a += l.length;
s.push(`- Ranked ${l.length} candidate(s) for durable promotion.`);
if (e.config.verboseLogging) {
const t = l.length > 0 ? l.map((e) => `${e.path}:${e.startLine}-${e.endLine} score=${e.score.toFixed(3)} signals=${e.signalCount} recalls=${e.recallCount} queries=${e.uniqueQueries} components={freq=${e.components.frequency.toFixed(3)},rel=${e.components.relevance.toFixed(3)},div=${e.components.diversity.toFixed(3)},rec=${e.components.recency.toFixed(3)},cons=${e.components.consolidation.toFixed(3)},concept=${e.components.conceptual.toFixed(3)}}`).join(" | ") : "none";
e.logger.info(`memory-core: dreaming candidate details [workspace=${v}] ${t}`);
}
const u = await h({
agentId: n,
workspaceAgentIds: r,
workspaceDir: v,
candidates: l,
limit: e.config.limit,
minScore: e.config.minScore,
minRecallCount: e.config.minRecallCount,
minUniqueQueries: e.config.minUniqueQueries,
maxAgeDays: e.config.maxAgeDays,
maxPromotedSnippetTokens: e.config.maxPromotedSnippetTokens,
maxPriorEntryLossFraction: e.config.maxPriorEntryLossFraction,
memoryFileMaxChars: resolveMemoryPromotionFileMaxChars({
cfg: e.cfg,
agentIds: r
}),
consolidation: {
...e.subagent ? { subagent: e.subagent } : {},
...e.config.execution?.model ? { model: e.config.execution.model } : {},
...e.consolidationTimeoutMs !== void 0 ? { timeoutMs: e.consolidationTimeoutMs } : {},
logger: e.logger
},
timezone: e.config.timezone,
nowMs: i
});
o += u.applied;
s.push(`- Promoted ${u.applied} candidate(s) into MEMORY.md.`);
if (u.rejectedCandidates.length > 0) {
const e = /* @__PURE__ */ new Map();
for (const { category: t } of u.rejectedCandidates) e.set(t, (e.get(t) ?? 0) + 1);
const t = [...e].toSorted(([e], [t]) => e.localeCompare(t)).map(([e, t]) => `${e}: ${t}`).join(", ");
s.push(`- Not promoted: ${u.rejectedCandidates.length} candidate(s) (${t}).`);
}
if (e.config.verboseLogging) {
const t = u.appliedCandidates.length > 0 ? u.appliedCandidates.map((e) => `${e.path}:${e.startLine}-${e.endLine} score=${e.score.toFixed(3)} signals=${e.signalCount} recalls=${e.recallCount}`).join(" | ") : "none";
e.logger.info(`memory-core: dreaming applied details [workspace=${v}] ${t}`);
}
if (u.applied > 0) {
const t = u.appliedCandidates.map((e) => e.snippet).filter(Boolean);
const n = {
phase: "deep",
snippets: t,
promotions: t,
sourceEntryKeys: [...new Set(u.appliedCandidates.map((e) => e.key))]
};
b.push({
data: n,
timezone: e.config.timezone,
model: e.config.execution?.model
});
}
const f = u.rejectedCandidates.some(({ category: e }) => e !== "memory budget");
await d({
workspaceDir: v,
bodyLines: s,
hasContent: c.changed || u.applied > 0 || f,
nowMs: i,
timezone: e.config.timezone,
storage: e.config.storage ?? {
mode: "separate",
separateReports: false
}
});
} catch (t) {
s += 1;
const n = formatErrorMessage(t);
e.logger.error(`memory-core: dreaming promotion failed for workspace ${v}: ${n}`);
await appendFailedDreamingEvent({
workspaceDir: v,
phase: "deep",
error: n,
storageMode: e.config.storage?.mode ?? "separate",
nowMs: i,
logger: e.logger
});
}
const S = b[0];
const C = b.at(-1);
if (!S || !C) continue;
const w = {
...S.data,
phase: C.data.phase,
snippets: uniqueStrings(b.flatMap(({ data: e }) => e.snippets)),
themes: uniqueStrings(b.flatMap(({ data: e }) => e.themes ?? [])),
promotions: uniqueStrings(b.flatMap(({ data: e }) => e.promotions ?? [])),
sourceEntryKeys: uniqueStrings(b.flatMap(({ data: e }) => e.sourceEntryKeys ?? []))
};
if (!e.subagent) await f({
workspaceDir: v,
data: w,
nowMs: i,
timezone: C.timezone,
logger: e.logger,
reason: "subagent runtime is unavailable"
});
else {
const t = await p({
agentId: n,
timeoutMs: e.narrativeTimeoutMs,
subagent: e.subagent,
workspaceDir: v,
data: w,
nowMs: i,
timezone: C.timezone,
model: C.model,
logger: e.logger,
runInBackground: e.runInBackground
});
if (t.status === "degraded") c += 1;
else if (t.status === "pending") l += 1;
}
}
const v = `memory-core: dreaming promotion complete (workspaces=${i.length}, candidates=${a}, applied=${o}, failed=${s}, degraded=${c}, narrativesPending=${l}).`;
if (s === i.length || c > 0) e.logger.warn(v);
else e.logger.info(v);
return {
handled: true,
reason: c > 0 ? "memory-core: short-term dreaming degraded" : "memory-core: short-term dreaming processed"
};
}
function registerShortTermPromotionDreaming(e) {
let resolveServiceCron = null;
let t = false;
let n = false;
let r = null;
const i = /* @__PURE__ */ new Set();
let a = null;
let o = true;
let s;
const resolveCurrentConfig = () => e.runtime.config?.current?.() ?? e.config;
const disposeDreaming = () => {
o = true;
if (r) {
clearTimeout(r);
r = null;
}
if (a) {
clearInterval(a);
a = null;
}
resolveServiceCron = null;
};
const reconcileManagedDreamingCron = async (r) => {
const i = r.reason === "startup" ? r.startupConfig ?? e.config : resolveCurrentConfig();
const a = r.reason === "startup" ? resolveMemoryDreamingPluginConfig(i) ?? resolveMemoryDreamingPluginConfig(e.config) ?? e.pluginConfig : resolveMemoryDreamingPluginConfig(i);
const o = resolveMemoryDeepDreamingConfig({
pluginConfig: a,
cfg: i
});
const s = resolveServiceCron?.() ?? null;
if (o.enabled && s?.isEnabled && !await s.isEnabled()) return;
if (!s && o.enabled && !t) {
if (r.reason === "startup") e.logger.debug?.("memory-core: cron service not yet available at service start; deferring to runtime reconciliation.");
else {
e.logger.warn("memory-core: managed dreaming cron could not be reconciled (cron service unavailable).");
t = true;
}
}
if (s) t = false;
const c = (await reconcileShortTermDreamingCronJob({
cron: s,
config: o,
logger: e.logger
})).status === "owner-required";
if (c && !n) e.logger.warn("memory-core: managed dreaming cron job was not created because no ambient agent owner is configured. Set agents.defaults.systemAgent.agentId to an existing agent to enable automatic dreaming.");
n = c;
};
const startRuntimeCronReconcileTimer = () => {
if (o || a) return;
a = setInterval(() => {
trackDreamingTask(() => reconcileManagedDreamingCron({ reason: "runtime" })).catch((t) => {
e.logger.error(`memory-core: dreaming cron reconcile failed: ${formatErrorMessage(t)}`);
});
}, RUNTIME_CRON_RECONCILE_INTERVAL_MS);
a.unref?.();
};
const trackDreamingTask = async (t) => {
const n = e.lifecycle.runInBackgroundContext ? e.lifecycle.runInBackgroundContext(t) : t();
i.add(n);
try {
return await n;
} finally {
i.delete(n);
}
};
const startDreamingSessionCleanup = async (t, n) => {
const { DREAMING_ORPHAN_MIN_AGE_MS: i, scrubDreamingNarrativeArtifacts: a } = await import("../../dreaming-session-cleanup-DV2fx-f6.mjs");
if (o) return;
const scrubConfiguredAgents = async (t, n) => {
const r = uniqueStrings(resolveMemoryDreamingWorkspaces(t).flatMap(({ agentIds: e }) => e));
for (const i of r) {
if (o) return;
try {
await a({
agentId: i,
config: t,
logger: e.logger,
...n === void 0 ? {} : { nowMs: n }
});
} catch (t) {
e.logger.warn(`memory-core: dreaming startup cleanup failed for agent ${i}: ${formatErrorMessage(t)}`);
}
}
};
await scrubConfiguredAgents(t, n);
if (o) return;
r = setTimeout(() => {
if (o) return;
r = null;
trackDreamingTask(() => scrubConfiguredAgents(resolveCurrentConfig(), n + i - 1)).catch((t) => {
e.logger.warn(`memory-core: deferred dreaming startup cleanup failed: ${formatErrorMessage(t)}`);
});
}, i);
r.unref?.();
};
e.registerService({
id: "memory-core-dreaming",
async start(t) {
if (!t.getCron) return;
s = Date.now();
o = false;
resolveServiceCron = () => t.getCron?.() ?? null;
trackDreamingTask(async () => {
try {
await reconcileManagedDreamingCron({
reason: "startup",
startupConfig: t.config
});
} catch (t) {
e.logger.error(`memory-core: dreaming startup reconciliation failed: ${formatErrorMessage(t)}`);
} finally {
startRuntimeCronReconcileTimer();
}
});
},
async stop() {
disposeDreaming();
await Promise.allSettled(i);
}
});
e.on("gateway_start", (t, n) => {
const i = s;
if (o || i === void 0) return;
if (r) {
clearTimeout(r);
r = null;
}
trackDreamingTask(() => startDreamingSessionCleanup(n.config ?? e.config, i)).catch((t) => {
e.logger.warn(`memory-core: dreaming startup cleanup failed: ${formatErrorMessage(t)}`);
});
});
e.on("before_agent_reply", async (t, n) => {
try {
if (n.trigger !== "heartbeat" && n.trigger !== "cron") return;
if (!includesSystemEventToken(t.cleanedBody, "__openclaw_memory_core_short_term_promotion_dream__")) return;
const r = resolveCurrentConfig();
const i = resolveMemoryDeepDreamingConfig({
pluginConfig: resolveMemoryDreamingPluginConfig(r),
cfg: r
});
if (!i.enabled) return n.trigger === "cron" ? {
handled: true,
reason: "memory-core: short-term dreaming disabled"
} : void 0;
return await runShortTermDreamingPromotion({
runInBackground: n.trigger === "cron" ? trackDreamingTask : void 0,
agentId: n.agentId,
workspaceDir: n.workspaceDir,
cfg: r,
config: i,
logger: e.logger,
subagent: e.runtime.subagent,
narrativeTimeoutMs: e.runtime.agent.resolveAgentTimeoutMs({ cfg: r }),
...typeof r.agents?.defaults?.timeoutSeconds === "number" ? { consolidationTimeoutMs: e.runtime.agent.resolveAgentTimeoutMs({ cfg: r }) } : {}
});
} catch (t) {
e.logger.error(`memory-core: dreaming trigger failed: ${formatErrorMessage(t)}`);
return;
}
}, { eligibleTriggers: ["heartbeat", "cron"] });
}
//#endregion
//#region extensions/memory-core/src/flush-plan.ts
const DEFAULT_MEMORY_FLUSH_SOFT_TOKENS = 4e3;
const DEFAULT_MEMORY_FLUSH_FORCE_TRANSCRIPT_BYTES = 2097152;
const MEMORY_FLUSH_TARGET_HINT = "Store durable memories only in memory/YYYY-MM-DD.md (create memory/ if needed).";
const MEMORY_FLUSH_APPEND_ONLY_HINT = "If memory/YYYY-MM-DD.md already exists, APPEND new content only and do not overwrite existing entries.";
const MEMORY_FLUSH_READ_ONLY_HINT = "Treat workspace bootstrap/reference files such as MEMORY.md, DREAMS.md, SOUL.md, and AGENTS.md as read-only during this flush; never overwrite, replace, or edit them.";
const DEFAULT_MEMORY_FLUSH_PROMPT = [
"Pre-compaction memory flush.",
MEMORY_FLUSH_TARGET_HINT,
MEMORY_FLUSH_READ_ONLY_HINT,
MEMORY_FLUSH_APPEND_ONLY_HINT,
"Do NOT create timestamped variant files (e.g., YYYY-MM-DD-HHMM.md); always use the standard YYYY-MM-DD.md filename.",
`If nothing to store, reply with ${SILENT_REPLY_TOKEN}.`
].join(" ");
const DEFAULT_MEMORY_FLUSH_SYSTEM_PROMPT = [
"Pre-compaction memory flush turn.",
"The session is near auto-compaction; capture durable memories to disk.",
MEMORY_FLUSH_TARGET_HINT,
MEMORY_FLUSH_READ_ONLY_HINT,
MEMORY_FLUSH_APPEND_ONLY_HINT,
`You may reply, but usually ${SILENT_REPLY_TOKEN} is correct.`
].join(" ");
function normalizeNonNegativeInt(e) {
if (typeof e !== "number" || !Number.isFinite(e)) return null;
const t = Math.floor(e);
return t >= 0 ? t : null;
}
function buildMemoryFlushPlan(e = {}) {
const t = resolveMemoryCoreNowMs(e.nowMs);
const n = e.cfg;
const r = n?.agents?.defaults?.compaction?.memoryFlush;
if (r?.enabled === false) return null;
let i = normalizeNonNegativeInt(r?.softThresholdTokens) ?? DEFAULT_MEMORY_FLUSH_SOFT_TOKENS;
const a = parseNonNegativeByteSize(r?.forceFlushTranscriptBytes) ?? DEFAULT_MEMORY_FLUSH_FORCE_TRANSCRIPT_BYTES;
let o = DEFAULT_AGENT_COMPACTION_RESERVE_TOKENS_FLOOR;
const s = normalizeNonNegativeInt(e.contextWindowTokens);
if (s !== null && s > 0) {
o = resolveEffectiveCompactionReserveTokens({
contextTokenBudget: s,
reserveTokens: o
});
i = Math.min(i, Math.floor((s - o) / 2));
}
const { timeLine: c, userTimezone: l } = resolveCronStyleNow(n ?? {}, t);
const u = formatMemoryDreamingDay(t, l);
const d = `memory/${u}.md`;
return {
softThresholdTokens: i,
forceFlushTranscriptBytes: a,
reserveTokensFloor: o,
prompt: `${DEFAULT_MEMORY_FLUSH_PROMPT.replaceAll("YYYY-MM-DD", u)}\n${c}`,
systemPrompt: DEFAULT_MEMORY_FLUSH_SYSTEM_PROMPT.replaceAll("YYYY-MM-DD", u),
relativePath: d
};
}
//#endregion
//#region extensions/memory-core/src/session-backfill-gateway.ts
var InvalidSessionBackfillRequestError = class extends Error {};
const loadSessionBackfillGatewayRuntime = createLazyRuntimeModule(() => import("../../session-backfill-gateway.runtime-mDbIYeA5.mjs"));
function paramsRecord(e) {
if (!e || typeof e !== "object" || Array.isArray(e)) throw new Error("params must be an object.");
return e;
}
function assertOnlyKeys(e, t) {
const n = Object.keys(e).filter((e) => !t.has(e));
if (n.length > 0) throw new Error(`unexpected parameter: ${n[0]}`);
}
function readOptionalSessionBoundary(e, t) {
const n = e[t];
if (n !== void 0 && typeof n !== "string") throw new Error(`${t} must be a string.`);
return readToolStringParam(e, t);
}
function readGatewayParams(e, t, n) {
const r = paramsRecord(e);
const i = r.cliResult === true;
const a = r.expectedOwnerId === void 0 ? void 0 : readToolStringParam(r, "expectedOwnerId", { required: true });
if (i && !a) throw new Error("CLI backfill results require a selected Gateway owner");
if (r.operationOwnerId !== void 0 && r.operationOwnerId !== a) throw new Error("Gateway owner changed during session backfill; inspect its result before retrying");
assertOnlyKeys(r, /* @__PURE__ */ new Set([
"expectedOwnerId",
"operationOwnerId",
"cliResult",
...t ? ["agentId"] : [
"agentId",
"from",
"to",
"limitDays"
]
]));
const o = normalizeAgentId(readToolStringParam(r, "agentId", { required: !i || r.agentId !== void 0 }) ?? n());
if (t) return {
agentId: o,
ownerId: a,
cliResult: i
};
return {
agentId: o,
...normalizeSessionBackfillSelection({
from: readOptionalSessionBoundary(r, "from"),
to: readOptionalSessionBoundary(r, "to"),
limitDays: readPositiveIntegerParam(r, "limitDays")
}, {
from: "from",
to: "to",
limitDays: "limitDays"
}),
ownerId: a,
cliResult: i
};
}
function resolveExecutionContext(e, t) {
const n = e.runtime.config.current();
if (!listAgentIdsCompatibility(n).includes(t)) throw new InvalidSessionBackfillRequestError(`Unknown agent id "${t}".`);
const r = e.runtime.agent.resolveAgentWorkspaceDir(n, t);
const i = resolvePluginConfigObject(n, "memory-core");
const a = resolveMemoryRemDreamingConfig({
cfg: n,
pluginConfig: i
});
return {
workspaceDir: r,
...i ? { pluginConfig: i } : {},
...a.timezone !== void 0 ? { timezone: a.timezone } : {}
};
}
function gatewayResult(e, t) {
return {
days: e.days.length,
candidates: e.candidateCount,
perDay: e.days.map((e) => ({
day: e.day,
candidateCount: e.candidateCount,
sample: e.topCandidates.slice(0, 3)
})),
staged: e.stagedEntries,
...!t.includeCursor ? { truncated: t.continuation.hasMore } : {},
...t.includeCursor ? { cursor: {
advanced: t.continuation.advanced,
exhausted: e.candidateCount === 0 && !t.continuation.hasMore,
hasMore: t.continuation.hasMore
} } : {}
};
}
function respondInvalid(e, t) {
const n = t instanceof Error ? t.message : String(t);
e(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, n));
}
function registerSessionBackfillGatewayMethods(e) {
for (const t of [
"preview",
"apply",
"rollback"
]) {
const n = t === "apply";
const r = t === "rollback";
for (const i of [false, true]) e.registerGatewayMethod(`memory.sessionBackfill.${t}${i ? ".owner" : ""}`, async (t) => {
const { params: a, respond: o } = t;
let s;
try {
if (i && (typeof a.expectedOwnerId !== "string" || !a.expectedOwnerId.trim())) throw new Error("expectedOwnerId must be a non-empty string");
s = readGatewayParams(a, r, () => resolveDefaultAgentId(t.context.getRuntimeConfig()));
} catch (e) {
respondInvalid(o, e);
return;
}
try {
const { ownerId: i, cliResult: a, ...c } = s;
let l;
const run = async (t) => {
l = t;
const o = resolveExecutionContext(e, s.agentId);
const { executeSessionBackfillBatch: u } = await loadSessionBackfillGatewayRuntime();
t?.();
const d = await u({
...c,
...o,
...t ? { assertCurrent: t } : {},
...n ? { apply: true } : {},
...r ? { rollback: true } : {}
});
const { result: f, continuation: p } = d;
t?.();
return a ? {
execution: d,
ownerId: i
} : r ? {
removedDiaryEntries: f.rollback?.removedDiaryEntries ?? 0,
removedStagedEntries: f.rollback?.removedStagedEntries ?? 0
} : gatewayResult(f, {
includeCursor: n,
continuation: p
});
};
const u = i ? await runWithLocalStateMutationOwner(i, t, run) : await run();
l?.();
o(true, u);
} catch (e) {
if (e instanceof InvalidSessionBackfillRequestError) respondInvalid(o, e);
else {
const t = e instanceof Error ? e.message : String(e);
o(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, t));
}
}
}, { scope: !i && t === "preview" ? "operator.read" : "operator.admin" });
}
}
//#endregion
//#region extensions/memory-core/index.ts
const loadMemoryToolsModule = createLazyRuntimeModule(() => import("../../tools-HJsqSy2u.mjs"));
const loadStandingIntentsModule = createLazyRuntimeModule(() => import("../../standing-intents-NvKHYHXn.mjs"));
const loadStandingIntentToolModule = createLazyRuntimeModule(() => import("../../standing-intents-tool-BbjfAYLS.mjs"));
const loadRuntimeProviderModule = createLazyRuntimeModule(() => import("../../runtime-provider-CUPgpbgc.mjs"));
function createLazyMemoryTool(e) {
const t = resolveMemoryToolContext(e.options);
if (!t) return null;
let n;
return {
label: e.contract.label,
name: e.contract.name,
description: e.contract.describe(t.sources),
parameters: e.contract.parameters,
prepareArguments: e.contract.prepareArguments,
execute: async (t, r, i, a) => {
n ??= loadMemoryToolsModule().then((t) => e.load(t, e.options));
const o = await n;
if (!o) return jsonResult({
disabled: true,
unavailable: true,
error: "memory search unavailable"
});
return await o.execute(t, r, i, a);
}
};
}
const StandingIntentSchema = {
type: "object",
properties: {
action: {
type: "string",
enum: [
"create",
"list",
"cancel"
]
},
id: { type: "string" },
description: { type: "string" },
triggerKeywords: {
type: "array",
items: { type: "string" }
},
scope: {
type: "string",
enum: [
"conversation",
"channel",
"anywhere"
],
default: "channel"
},
senderScope: {
type: "string",
enum: ["sender", "anyone"],
default: "sender"
},
expiresAt: { type: "string" },
maxFires: {
type: "integer",
minimum: 1
},
cooldownSeconds: {
type: "integer",
minimum: 0
},
status: {
type: "string",
enum: [
"pending",
"armed",
"fired",
"done",
"cancelled",
"expired"
]
}
},
required: ["action"],
additionalProperties: false
};
function createLazyStandingIntentTool(e, t) {
const n = e.getRuntimeConfig?.() ?? e.runtimeConfig ?? e.config;
const r = e.messageChannel?.trim();
const i = e.requesterSenderId?.trim();
if (!n) {
t("runtime config is unavailable for this turn");
return null;
}
const a = resolveSessionAgentIdStrict({
sessionKey: e.sessionKey,
config: n,
agentId: e.agentId
});
let o;
return {
label: "Standing Intent",
name: "intent",
description: "Create, list, or explicitly cancel event-conditioned standing intents. A created intent is armed; the system injects the reminder automatically when it triggers. Do not deliver it early or cancel it unless the user asks. Use scheduled tasks for time-based reminders.",
parameters: StandingIntentSchema,
prepareArguments: (e) => {
const t = asNonArrayRecord(e);
return {
...t,
maxFires: readPositiveIntegerParam(t, "maxFires"),
cooldownSeconds: readNonNegativeIntegerParam(t, "cooldownSeconds")
};
},
execute: async (t, n, s, c) => {
o ??= loadStandingIntentToolModule().then((t) => t.createStandingIntentExecutor({
agentId: a,
assertCurrent: e.assertInvocationCurrent,
...e.sessionId ? { sourceSessionId: e.sessionId } : {},
...e.nativeChannelId ? { conversationId: e.nativeChannelId } : {},
...r ? { provider: r } : {},
...e.agentAccountId ? { accountId: e.agentAccountId } : {},
...i ? { senderId: i } : {}
}));
return await (await o)(t, n, s, c);
}
};
}
function resolveMemoryToolOptions(e, t) {
const n = e.getRuntimeConfig ? () => e.getRuntimeConfig?.() : () => e.runtimeConfig ?? e.config;
return {
config: n(),
getConfig: n,
agentId: e.agentId,
agentSessionKey: e.sessionKey,
sandboxed: e.sandboxed,
oneShotCliRun: e.oneShotCliRun,
conversationRecall: e.conversationRecall,
activeProjectKeys: e.activeProjectKeys,
...t.acquireLocalService ? { acquireLocalService: t.acquireLocalService } : {},
runInBackgroundContext: t.runInBackgroundContext
};
}
function createLazyMemoryRuntime(e) {
return {
async searchForCli(t) {
const { createMemoryRuntime: n } = await loadRuntimeProviderModule();
return await n(e).searchForCli(t);
},
supportsWorkspaceMemoryReadSources: true,
prepareReload: prepareMemoryManagerReload,
async getMemorySearchManager(t) {
const { createMemoryRuntime: n } = await loadRuntimeProviderModule();
return await n(e).getMemorySearchManager(t);
},
async authorizeSearchHits(t) {
const { createMemoryRuntime: n } = await loadRuntimeProviderModule();
return await n(e).authorizeSearchHits(t);
},
async classifyWorkspaceMemoryPaths(e) {
const { classifyWorkspaceMemoryPaths: t } = await import("../../workspace-path-classifier-DBCinl_e.mjs");
return await t(e);
},
resolveMemoryBackendConfig,
async closeAllMemorySearchManagers() {
const { createMemoryRuntime: t } = await loadRuntimeProviderModule();
await t(e).closeAllMemorySearchManagers();
},
async closeMemorySearchManager(t) {
const { createMemoryRuntime: n } = await loadRuntimeProviderModule();
await n(e).closeMemorySearchManager(t);
}
};
}
var memory_core_default = definePluginEntry({
id: "memory-core",
name: "OpenClaw Memory",
description: "File-backed memory search tools and CLI",
kind: "memory",
register(e) {
const acquireLocalService = (...t) => e.runtime.llm.acquireLocalService(...t);
const openKeyedStore = (t) => e.runtime.state.openKeyedStore(t);
const t = {
acquireLocalService,
openKeyedStore,
runInBackgroundContext: e.lifecycle.runInBackgroundContext
};
configureMemoryCoreDreamingState(openKeyedStore);
const n = createLazyMemoryRuntime(t);
let r;
const stopIndex = async (e) => {
const t = [];
for (const n of [() => r, e]) try {
await n();
} catch (e) {
t.push(e);
}
if (t.length === 1) throw t[0];
if (t.length > 1) throw new AggregateError(t, "Memory index shutdown failed");
};
e.lifecycle.onDispose?.(async () => {
const e = prepareMemoryManagerReload({
retireRuntime: true,
retiringEmbeddingProviders: []
});
await stopIndex(async () => {
const t = await e.drain();
if (t?.errors.length) throw new AggregateError(t.errors, "Memory manager disposal failed");
});
});
if (createNormalizedPluginsConfig(e.config.plugins).slots.memory === e.id) e.registerService({
id: "memory-core-index",
reload: { configPrefixes: [
"memory.search",
"agents",
"models.providers"
] },
start({ config: t, logger: i }) {
const a = retainMemoryIndexingAgents(listAgentIdsCompatibility(t));
if (a.length === 0) return;
const activate = async () => {
await Promise.all(a.map(async (e) => {
const { error: r } = await n.getMemorySearchManager({
cfg: t,
agentId: e
}).catch((e) => ({ error: String(e) }));
if (r) i.warn(`memory-core: index startup failed for ${e}: ${r}`);
}));
};
r = e.lifecycle.runInBackgroundContext ? e.lifecycle.runInBackgroundContext(activate) : activate();
r.catch(() => {});
},
stop: () => stopIndex(() => n.closeAllMemorySearchManagers?.())
});
registerShortTermPromotionDreaming(e);
let i;
e.registerService({
apiVersion: 2,
id: "memory-core-standing-intents",
reload: { configPrefixes: ["agents"] },
async start({ config: e, scheduler: t, logger: n }) {
i = (await loadStandingIntentsModule()).startStandingIntentMaintenance({
agentIds: listAgentIdsCompatibility(e),
scheduler: t,
warn: (e) => n.warn(e)
});
},
stop() {
i?.();
i = void 0;
}
});
registerSessionBackfillGatewayMethods(e);
e.registerMemoryCapability({
recallToolNames: ["memory_search", "memory_get"],
deterministicRecallToolName: "memory_search",
supportsPrivateTranscriptRecall: true,
promptBuilder: (t) => {
const n = buildProjectMemoryWriteInstruction(t.projectKey);
if (!t.availableTools.has("memory_search") && !t.availableTools.has("memory_get")) return n;
const r = e.runtime.config?.current ? e.runtime.config.current() : e.config;
return [...resolveMemoryToolContext({
config: r,
agentId: t.agentId,
agentSessionKey: t.agentSessionKey
}) ? buildMemoryPromptSection(t) : [], ...n];
},
flushPlanResolver: buildMemoryFlushPlan,
runtime: n,
publicArtifacts: { async listArtifacts(e) {
const { listMemoryHostPublicArtifacts: t } = await import("../../plugin-sdk/memory-host-core.js");
return await t(e);
} }
});
for (const n of [MEMORY_SEARCH_TOOL_CONTRACT, MEMORY_GET_TOOL_CONTRACT]) e.registerTool((e) => createLazyMemoryTool({
options: resolveMemoryToolOptions(e, t),
contract: n,
load: (e, t) => n.name === "memory_search" ? e.createMemorySearchTool(t) : e.createMemoryGetTool(t)
}), {
names: [n.name],
workspaceAccess: "execute"
});
e.registerTool({
contextVersion: 2,
create: (t) => createLazyStandingIntentTool(t, (t) => {
e.logger.warn(`memory-core: intent tool unavailable: ${t}`);
})
}, {
names: ["intent"],
workspaceAccess: "execute"
});
e.on("before_prompt_build", async (t, n) => {
if (n.trigger !== "user") return;
try {
const r = n.hookInvocation;
if (!r) throw new Error("prompt hook invocation support is required; intent matching skipped");
const i = await loadStandingIntentsModule();
r.assertActive();
if (!i.isEligibleStandingIntentTurn(n)) return;
const a = e.runtime.config?.current?.() ?? e.config;
const o = resolveSessionAgentIdStrict({
sessionKey: n.sessionKey,
config: a,
agentId: n.agentId
});
const s = await i.matchStandingIntents({
agentId: o,
prompt: t.prompt,
assertCurrent: r.assertActive,
...n.chatId ?? n.channelId ? { channel: n.chatId ?? n.channelId } : {},
...n.channel ?? n.messageProvider ? { provider: n.channel ?? n.messageProvider } : {},
...n.accountId ? { accountId: n.accountId } : {},
...n.senderId ? { senderId: n.senderId } : {}
});
const c = i.buildStandingIntentContext(s);
return c ? { prependContext: c } : void 0;
} catch (t) {
e.logger.warn?.(`memory-core: standing intent matching failed: ${t instanceof Error ? t.message : String(t)}`);
return;
}
});
e.registerCommand({
name: "dreaming",
description: "Enable or disable memory dreaming.",
acceptsArgs: true,
exposeSenderIsOwner: true,
handler: async (t) => {
const { handleDreamingCommand: n } = await import("../../dreaming-command-D1pTc58C.mjs");
return await n(e, t);
}
});
registerMemoryCoreCli(e, t);
}
});
//#endregion
export { memory_core_default as default };