UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

11 lines • 35.5 kB
import{l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"../../string-coerce-CpTFcSwY.mjs";import{o as resolveGlobalSingleton}from"../../global-singleton-DolL9xGt.mjs";import{a as extractErrorCode}from"../../error-coercion-DlKnt6w-.mjs";import{t as asNonArrayRecord}from"../../record-coerce-BTbqdJ3-.mjs";import{b as uniqueStrings}from"../../string-normalization-D_oBUpO3.mjs";import{n as createNormalizedPluginsConfig}from"../../config-state-C1eV6UWf.mjs";import{t as formatErrorMessage}from"../../errors-D37BJTfI.mjs";import{r as createLazyRuntimeModule}from"../../lazy-runtime-Ds6M7vp4.mjs";import{n as normalizeAgentId}from"../../agent-id-cOfqmfln.mjs";import{S as resolveSessionAgentIdStrict,_ as resolveDefaultAgentId,r as resolveAgentConfig}from"../../agent-scope-config-CG9CFpGX.mjs";import{n as parseNonNegativeByteSize}from"../../byte-size-DnoL45ia.mjs";import{t as KeyedAsyncQueue}from"../../keyed-async-queue-qBcorzrt.mjs";import{n as SILENT_REPLY_TOKEN}from"../../tokens-DD0Y_anD.mjs";import{i as ErrorCodes}from"../../missing-scope-error-CkgBgh6d.mjs";import{p as errorShape}from"../../error-codes-CQNGhXT-.mjs";import{n as jsonResult}from"../../tool-results-BkLNMSCi.mjs";import{a as readNonNegativeIntegerParam,d as readToolStringParam,s as readPositiveIntegerParam}from"../../common-DIgvX97L.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-DWa9EF3D.mjs";import"../../string-coerce-runtime-BYDH9Quw.mjs";import"../../error-runtime-DW-sj0iq.mjs";import"../../routing-BMFcTEzQ.mjs";import{t as listAgentIdsCompatibility}from"../../agent-scope-runtime-DKb8jQZx.mjs";import{t as resolveEffectiveCompactionReserveTokens}from"../../agent-compaction-constants-BjW90tur.mjs";import{t as definePluginEntry}from"../../plugin-entry-DhKiQ4Uu.mjs";import{i as resolvePluginConfigObject}from"../../plugin-config-runtime-BN1e1lm1.mjs";import{n as resolveCronStyleNow}from"../../current-time-DSJaF4TB.mjs";import{t as DEFAULT_AGENT_COMPACTION_RESERVE_TOKENS_FLOOR}from"../../agent-settings-ClTVpnWK.mjs";import{r as runWithLocalStateMutationOwner}from"../../local-state-owner-DweIAMz2.mjs";import"../../gateway-runtime-CCd3DVdi.mjs";import"../../channel-actions-DWbJI8_2.mjs";import"../../memory-core-host-status-mlVnC6Ei.mjs";import"../../memory-core-host-runtime-core-BfDf5NS1.mjs";import{t as resolveMemoryBackendConfig}from"../../memory-core-host-runtime-files-hoS8XR9g.mjs";import"../../param-readers-BpVB3RWF.mjs";import{n as registerMemoryCoreCli}from"../../cli-metadata-BbBKL_Te.mjs";import{f as configureMemoryCoreDreamingState}from"../../dreaming-state-CWg6oPZQ.mjs";import{t as MANAGED_DREAMING_DECLARATION_KEY}from"../../dreaming-cron-contract-D5v9Jx22.mjs";import{n as includesSystemEventToken,t as formatRecallRepairDetails}from"../../dreaming-shared-ea8L6m1m.mjs";import{t as classifyDreamingCronJob}from"../../dreaming-cron-classifier-DSAFHT2u.mjs";import{t as resolveMemoryCoreNowMs}from"../../time-BgopdjUE.mjs";import{t as appendFailedDreamingEvent}from"../../dreaming-events-BwpJcj30.mjs";import{t as resolveMemoryPromotionFileMaxChars}from"../../memory-budget-config-DJl1q42a.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-rzaNrxSv.mjs";import{a as retainMemoryIndexingAgents,i as prepareMemoryManagerReload}from"../../lifecycle-DGKSTlX5.mjs";import{t as closeAllMemorySearchManagers}from"../../manager-runtime-loader-7AioR6_j.mjs";import{t as normalizeSessionBackfillSelection}from"../../session-backfill-selection-qmqh5QBb.mjs"; //!extensions/memory-core/src/dreaming-cron.ts 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}} //!extensions/memory-core/src/dreaming.ts const RUNTIME_CRON_RECONCILE_INTERVAL_MS=6e4;const cronMaintenance=resolveGlobalSingleton(Symbol.for(`openclaw.memoryCore.dreamingCron`),()=>({queue:new KeyedAsyncQueue,owners:/* @__PURE__ */ new Map}));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-WHFRQyid.mjs`),import(`../../dreaming-narrative-Cquko1Cd.mjs`),import(`../../dreaming-phases-BahnHUTs.mjs`),import(`../../short-term-promotion-BwwNSGS-.mjs`)]);for(const{agentId:n,agentIds:r,workspaceDir:v}of i){const i=(e.cfg&&n?resolveAgentConfig(e.cfg,n)?.workspaceFileMode:void 0)??e.cfg?.agents?.defaults?.workspaceFileMode;const y=Date.now();let b;try{b=await m({agentId:n,workspaceDir:v,workspaceFileMode:i,pluginConfig:u,cfg:e.cfg,logger:e.logger,nowMs:y})}catch(t){s+=1;e.logger.error(`memory-core: dreaming sweep failed for workspace ${v}: ${formatErrorMessage(t)}`);continue}const{narratives:x,failed:S}=b;if(S)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:y});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,workspaceFileMode:i,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:y});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))]};x.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,workspaceFileMode:i,bodyLines:s,hasContent:c.changed||u.applied>0||f,nowMs:y,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:y,logger:e.logger})}const C=x[0];const w=x.at(-1);if(!C||!w)continue;const T={...C.data,phase:w.data.phase,snippets:uniqueStrings(x.flatMap(({data:e})=>e.snippets)),themes:uniqueStrings(x.flatMap(({data:e})=>e.themes??[])),promotions:uniqueStrings(x.flatMap(({data:e})=>e.promotions??[])),sourceEntryKeys:uniqueStrings(x.flatMap(({data:e})=>e.sourceEntryKeys??[]))};if(!e.subagent)await f({workspaceDir:v,workspaceFileMode:i,data:T,nowMs:y,timezone:w.timezone,logger:e.logger,reason:`subagent runtime is unavailable`});else{const t=await p({agentId:n,timeoutMs:e.narrativeTimeoutMs,subagent:e.subagent,workspaceDir:v,workspaceFileMode:i,data:T,nowMs:y,timezone:w.timezone,model:w.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;const i=/* @__PURE__ */ new Set;let a;let o=``;let s=true;let c;const resolveCurrentConfig=()=>e.runtime.config?.current?.()??e.config;const disposeDreaming=()=>{s=true;a?.beginClose();r=void 0;resolveServiceCron=null};const reconcileManagedDreamingCron=async r=>cronMaintenance.queue.enqueue(o,async()=>{if(s||[...cronMaintenance.owners.get(o)??[]].at(-1)!==requestCronReconcile)return;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 c=resolveMemoryDeepDreamingConfig({pluginConfig:a,cfg:i});const l=resolveServiceCron?.()??null;if(c.enabled&&l?.isEnabled&&!await l.isEnabled())return;if(!l&&c.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(l)t=false;const u=(await reconcileShortTermDreamingCronJob({cron:l,config:c,logger:e.logger})).status===`owner-required`;if(u&&!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=u});const scheduleCronReconcile=t=>{if(s||!a||a.signal.aborted)return;a.schedule({id:`dreaming-cron-reconcile`,delayMs:t,everyMs:RUNTIME_CRON_RECONCILE_INTERVAL_MS,async run(){try{await reconcileManagedDreamingCron({reason:`runtime`})}catch(t){e.logger.error(`memory-core: dreaming cron reconcile failed: ${formatErrorMessage(t)}`)}}})};const requestCronReconcile=()=>scheduleCronReconcile(0);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:o}=await import(`../../dreaming-session-cleanup-DdEQu1GC.mjs`);if(s)return;const scrubConfiguredAgents=async(t,n)=>{const r=uniqueStrings(resolveMemoryDreamingWorkspaces(t).flatMap(({agentIds:e})=>e));for(const i of r){if(s)return;try{await o({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(s||a?.signal.aborted)return;r=a?.schedule({id:`dreaming-startup-cleanup`,delayMs:i,async run(){r=void 0;try{await scrubConfiguredAgents(resolveCurrentConfig(),n+i-1)}catch(t){e.logger.warn(`memory-core: deferred dreaming startup cleanup failed: ${formatErrorMessage(t)}`)}}})};e.registerService({id:`memory-core-dreaming`,apiVersion:2,async start(t){if(!t.getCron)return;c=Date.now();s=false;a=t.scheduler.scope();o=t.stateDir;const n=cronMaintenance.owners.get(o)??/* @__PURE__ */ new Set;n.add(requestCronReconcile);cronMaintenance.owners.set(o,n);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{scheduleCronReconcile(RUNTIME_CRON_RECONCILE_INTERVAL_MS)}})},async stop(){const e=cronMaintenance.owners.get(o);const t=e&&[...e].at(-1)===requestCronReconcile;e?.delete(requestCronReconcile);if(e?.size===0)cronMaintenance.owners.delete(o);disposeDreaming();await Promise.allSettled(i);await a?.stop();if(t)[...cronMaintenance.owners.get(o)??[]].at(-1)?.()}});e.on(`gateway_start`,(t,n)=>{const i=c;if(s||i===void 0)return;r?.cancel();r=void 0;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`]})} //!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}} //!extensions/memory-core/src/session-backfill-gateway.ts var InvalidSessionBackfillRequestError=class extends Error{};const loadSessionBackfillGatewayRuntime=createLazyRuntimeModule(()=>import(`../../session-backfill-gateway.runtime-BBLXgo6a.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,workspaceFileMode:resolveAgentConfig(n,t)?.workspaceFileMode,...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`})}} //!extensions/memory-core/index.ts const loadMemoryToolsModule=createLazyRuntimeModule(()=>import(`../../tools-BjffXmAk.mjs`));const loadStandingIntentsModule=createLazyRuntimeModule(()=>import(`../../standing-intents-Df9SdNa2.mjs`));const loadStandingIntentToolModule=createLazyRuntimeModule(()=>import(`../../standing-intents-tool-DQxdZnPN.mjs`));const loadRuntimeProviderModule=createLazyRuntimeModule(()=>import(`../../runtime-provider-CIvsPhc9.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-OH8DcAqv.mjs`);return await t(e)},resolveMemoryBackendConfig,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=createNormalizedPluginsConfig(e.config.plugins).slots.memory===e.id;const r=createLazyMemoryRuntime(t);let i;const stopIndex=async e=>{const t=[];for(const n of[()=>i,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(n)e.registerService({id:`memory-core-index`,reload:{configPrefixes:[`memory.search`,`agents`,`models.providers`]},start({config:t,logger:n}){const a=retainMemoryIndexingAgents(listAgentIdsCompatibility(t));if(a.length===0)return;const activate=async()=>{await Promise.all(a.map(async e=>{const{error:i}=await r.getMemorySearchManager({cfg:t,agentId:e}).catch(e=>({error:String(e)}));if(i)n.warn(`memory-core: index startup failed for ${e}: ${i}`)}))};i=e.lifecycle.runInBackgroundContext?e.lifecycle.runInBackgroundContext(activate):activate();i.catch(()=>{})},stop:()=>stopIndex(()=>r.closeAllMemorySearchManagers?.())});registerShortTermPromotionDreaming(e);let a;e.registerService({apiVersion:2,id:`memory-core-standing-intents`,reload:{configPrefixes:[`agents`]},async start({config:e,scheduler:t,logger:n}){a=(await loadStandingIntentsModule()).startStandingIntentMaintenance({agentIds:listAgentIdsCompatibility(e),scheduler:t,warn:e=>n.warn(e)})},stop(){a?.();a=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:r,publicArtifacts:{async listArtifacts(e){const{listMemoryHostPublicArtifacts:t}=await import(`../../plugin-sdk/memory-host-core.js`);return await t(e)}}});if(n)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-QJd1TiLC.mjs`);return await n(e,t)}});registerMemoryCoreCli(e,t)}});export{memory_core_default as default};