openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines (6 loc) • 7.54 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{_ as resolveDefaultAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{m as resolvePluginMetadataSnapshotAsync}from"./plugin-metadata-snapshot-CDKhemiT.mjs";import{a as withSessionContextAdmission}from"./session-transcript-read-fence-DE07xwTs.mjs";import{f as prepareSystemAgentRunAdmission}from"./admitted-run-context-xwC9VVgE.mjs";import{o as resolveSessionStorePathForScope}from"./session-store-path-Co-EGagp.mjs";import{r as resolveInternalSessionEffectsIdentity}from"./internal-session-key-D-nF_UyM.mjs";import{i as MAX_VISIBLE_MESSAGE_MAX_MESSAGES,r as MAX_VISIBLE_MESSAGE_MAX_BYTES}from"./session-accessor.sqlite-visible-cursor-CWhnCe4q.mjs";import{x as withSessionTranscriptHydrationCaller}from"./session-transcript-worker-resources-BCJ3nyGg.mjs";import{l as waitForSessionTranscriptProjection}from"./session-transcript-reconcile-BewE5zNm.mjs";import{t as prepareConversationCapabilityProfile}from"./conversation-capability-profile-DiRRWN6T.mjs";import{r as projectConversationToolNames}from"./conversation-tool-policy-pipeline-DYGf_lAW.mjs";import{o as getMemoryProviderRuntime}from"./memory-state-BSED9PTf.mjs";import{c as resolveMemoryAudienceFromEntry,i as delegateMemoryAudience}from"./memory-audience-BMnQwoeC.mjs";import{t as SessionManager}from"./session-manager-BPWwNp25.mjs";import{t as filterToolsByMessageProvider}from"./agent-tools.message-provider-policy-MAkEqa9I.mjs";import{i as resolveModelFallbackOptions}from"./agent-runner-run-params-iTBH2_n4.mjs";import{t as createSessionMaintenanceFollowup}from"./run-C7hzgpxI.mjs";import{t as buildEmbeddedRunContext}from"./agent-runner-utils-Ddz75_c7.mjs";import{t as isToolsMemoryFlushPlan}from"./memory-flush-plan-o13YImiu.mjs";import fs from"node:fs";import path from"node:path";import crypto from"node:crypto";
//!src/auto-reply/reply/memory-flush-session.ts
function deriveMemoryFlushId(e){const t=crypto.createHash(`sha256`).update(`openclaw-memory-flush\0${e.sourceSessionId}\0${e.sourceLifecycleRevision??``}\0${e.compactionCount}`).digest().subarray(0,16);t[6]=(t[6]??0)&15|128;t[8]=(t[8]??0)&63|128;const n=t.toString(`hex`);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}async function prepareMemoryFlushSession(e){e.signal?.throwIfAborted();await waitForSessionTranscriptProjection(e.source,e.signal);e.signal?.throwIfAborted();const t=await withSessionContextAdmission(e.source,e.admission,()=>withSessionTranscriptHydrationCaller(`memory-flush`,()=>SessionManager.openDetachedBoundedAsync(e.source,{signal:e.signal,cwd:e.workspaceDir,maxBytes:MAX_VISIBLE_MESSAGE_MAX_BYTES,maxEvents:MAX_VISIBLE_MESSAGE_MAX_MESSAGES,onTruncated:()=>{throw new Error(`Memory flush exceeds the bounded conversation view.`)}})));const n=resolveInternalSessionEffectsIdentity({agentId:e.source.agentId,runId:e.runId});return{...n,sessionFile:n.sessionKey,sessionTarget:{agentId:e.source.agentId,storePath:e.source.storePath,...n},sessionManager:t,sessionPersistence:`detached`,cleanupBundleMcpOnRunEnd:true}}async function ensureMemoryFlushTargetFile(e){const t=normalizeOptionalString(e.workspaceDir);const n=normalizeOptionalString(e.relativePath);if(!t||!n||path.isAbsolute(n))throw new Error(`Invalid memory flush target path`);const r=path.resolve(t);const i=path.resolve(r,n);const a=path.relative(r,i);if(!a||a.startsWith(`..`)||path.isAbsolute(a))throw new Error(`Memory flush target path must stay inside the workspace`);e.assertCurrent();await fs.promises.mkdir(path.dirname(i),{recursive:true});e.assertCurrent();const o=await fs.promises.open(i,`a`);try{e.assertCurrent()}finally{await o.close()}}
//!src/auto-reply/reply/memory-flush-prepare.ts
const log=createSubsystemLogger(`auto-reply/memory-flush`);async function prepareMemoryFlushAttempt(e){e.assertCurrent();const{resolution:t}=e;const{plan:n}=t;const{sessionKey:r,sessionEntry:i,followupRun:a}=e;if(!r||!i)throw new Error(`Memory flush has no current transcript target.`);const o=a.run.agentId??resolveDefaultAgentId(e.cfg);const s=resolveModelFallbackOptions(a.run,e.cfg);const c=e.runtimePolicySessionKey??a.run.runtimePolicySessionKey??r;const l=createSessionMaintenanceFollowup({run:a.run,sessionEntry:i,cfg:e.cfg,sessionKey:r,runtimePolicySessionKey:c,provider:s.provider,model:s.model,auth:a.run}).run;if(isToolsMemoryFlushPlan(n)){const i=buildEmbeddedRunContext({run:l,sessionCtx:{},hasRepliedRef:void 0});const o=await prepareConversationCapabilityProfile({...i,config:e.cfg,sessionKey:c,sandboxToolPolicy:e.sandboxToolPolicy,operatorAuthority:a.operatorAuthority,pluginMetadataSnapshot:await resolvePluginMetadataSnapshotAsync({config:e.cfg,workspaceDir:l.workspaceDir})});if(!projectConversationToolNames({capabilityProfile:o,toolNames:filterToolsByMessageProvider(n.persistenceToolNames.map(e=>({name:e})),i.messageProvider).map(e=>e.name),toolMeta:()=>({pluginId:t.pluginId}),warn:()=>{}}).some(e=>e!==`read`)){log.debug(`memory flush skipped: no declared persistence tool survived policy`,{event:`memory_flush_tools_unavailable`,sourceSessionKey:r,pluginId:t.pluginId});return null}}e.assertCurrent();const u=resolveSessionStorePathForScope({agentId:o,sessionKey:r,storePath:e.storePath},e.cfg);const d=isToolsMemoryFlushPlan(n)&&getMemoryProviderRuntime()?await resolveMemoryAudienceFromEntry({agentId:o,sessionKey:r,sessionId:i.sessionId,senderIsOwner:a.memoryAudienceSenderIsOwner??a.run.senderIsOwner,storePath:u,resolveAgentStorePath:t=>resolveSessionStorePathForScope({agentId:t},e.cfg),assertCallerCurrent:e.assertCurrent},i):void 0;if(d?.status===`denied`){log.debug(`memory flush skipped: source turn has no memory audience`,{event:`memory_flush_no_audience`,sourceSessionKey:r,sourceSessionId:i.sessionId,pluginId:t.pluginId,kind:d.kind,reason:d.reason});return null}let f;const release=()=>{f?.release();d?.release()};try{e.assertCurrent();const p=await prepareMemoryFlushSession({admission:e.preflightAdmission,source:{agentId:o,sessionId:i.sessionId,sessionKey:r,storePath:u},runId:e.flushRunId,workspaceDir:a.run.workspaceDir,signal:e.abortSignal});if(!isToolsMemoryFlushPlan(n))await ensureMemoryFlushTargetFile({workspaceDir:a.run.workspaceDir,relativePath:n.relativePath,assertCurrent:e.assertCurrent});const m=[a.run.extraSystemPrompt,n.systemPrompt].filter(Boolean).join(`
`);l.sessionId=p.sessionId;l.sessionKey=p.sessionKey;l.sessionFile=p.sessionFile;e.assertCurrent();f=d?await delegateMemoryAudience(d.audience,{sessionKey:p.sessionKey,storePath:p.sessionTarget.storePath,detached:true,assertCallerCurrent:e.assertCurrent}):void 0;const h=isToolsMemoryFlushPlan(n)?{flushId:deriveMemoryFlushId({sourceSessionId:i.sessionId,sourceLifecycleRevision:i.lifecycleRevision,compactionCount:i.compactionCount??0}),ownerPluginId:t.pluginId,persistenceToolNames:n.persistenceToolNames,lookupToolNames:n.lookupToolNames,recordPersistenceToolSuccess:e.recordPersistenceToolSuccess}:void 0;const g=prepareSystemAgentRunAdmission(e.cfg,e.flushRunId,a.run.agentId,`auto-reply.memory-flush`,void 0,a.operatorAuthority);return{writePath:isToolsMemoryFlushPlan(n)?void 0:n.relativePath,systemPrompt:m,selection:s,preparedRunAdmission:g,memorySession:{...p,...e.recoveryContextTokenBudget!==void 0?{disableCompactionRecovery:true}:{}},memoryAudience:f?.audience,memoryFlushTools:h,maintenanceRun:l,sourcePolicySessionKey:c,release}}catch(e){release();throw e}}export{prepareMemoryFlushAttempt};