UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

15 lines • 7.01 kB
import{i as asOptionalObjectRecord}from"./record-coerce-BTbqdJ3-.mjs";import{x as root}from"./fs-safe-Bxzu1j4h.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{n as recordModelFallbackStop}from"./model-fallback-stop-BR_49mUQ.mjs";import{i as getPluginToolMeta}from"./tool-metadata-Cb5nBZYD.mjs";import{o as copyAgentToolMetadata}from"./agent-tool-metadata-D7ctyGhj.mjs";import{t as isToolResultError}from"./tool-result-error-DAdEhHzf.mjs";import{i as logWarn}from"./logger-BHIcoxTH.mjs";import{c as runWithAgentToolSourceExecutionScope,i as captureAgentToolSourceExecutionGuard}from"./agent-tool-source-execution-guard-D2z6vTFX.mjs";import{s as resolveToolPathAgainstWorkspaceRoot}from"./path-policy-mjUsNXiY.mjs";import{a as normalizeFileToolPathParamsFromKeys,n as assertRequiredParams,t as REQUIRED_PARAM_GROUPS}from"./agent-tools.params-B4FAxIj6.mjs";import{r as resolveSandboxFileMutationQueueKey}from"./file-mutation-identity-nZwlS4qx.mjs";import{n as withFileMutationQueueKeyResolution}from"./file-mutation-queue-NMlAaYKz.mjs";import{n as messageProviderExcludesTool}from"./agent-tools.message-provider-policy-MAkEqa9I.mjs";import path from"node:path";import fs from"node:fs/promises"; //!src/agents/memory-flush-content.ts function assertNewMemoryFlushContent(e,t){const n=e.replaceAll(`\r `,` `).trim();if(!n)return;const r=t.replaceAll(`\r `,` `).trim();const i=new Set(r.split(/\n[\t ]*\n+/));if([n,...n.split(/\n[\t ]*\n+/)].some(e=>/[\p{L}\p{N}]/u.test(e)&&!/^#{1,6}[\t ]+[^\n]+$/.test(e)&&(i.has(e)||r.startsWith(`${e}\n`))))throw new Error(`Memory flush content repeats saved note text. Nothing was appended. Retry with only new content; do not include existing entries or a complete rewritten note.`)} //!src/agents/agent-tools.memory-flush.ts function resolveMemoryFlushToolSetup(e){const t=e?.trigger===`memory`;if(t&&!e?.memoryFlushWritePath&&!e?.memoryFlushTools)throw new Error(`Memory flush requires memoryFlushWritePath or memoryFlushTools`);return{isMemoryFlushRun:t,memoryFlushWritePath:t?e.memoryFlushWritePath:void 0,memoryFlush:t&&e?.memoryFlushTools?{flushId:e.memoryFlushTools.flushId}:void 0}}function warnIfMemoryFlushFileWriterUnavailable(e){if(e.relativePath&&!e.tools.some(e=>e.name===`write`)&&!messageProviderExcludesTool(e.messageProvider,`write`))logWarn(`memory flush cannot persist ${e.relativePath}: no write tool survived this agent's tool policy, so this run will not save anything.`)}var MemoryFlushToolsUnavailableError=class extends Error{constructor(e){const t=e.length>0?e.join(`, `):`<none declared>`;super(`memory flush skipped: no declared persistence tool survived policy (${t})`);this.missingToolNames=e;this.name=`MemoryFlushToolsUnavailableError`;recordModelFallbackStop(this)}};function wrapPersistenceTool(e,t){return copyAgentToolMetadata(e,{...e,execute:async(n,r,i,a)=>{const o=await e.execute(n,r,i,a);if(!isToolResultError(o)&&!(`isError`in o&&o.isError===true))t();return o}})}function projectMemoryFlushTools(e,t){if(!t)return e;if(`persistenceToolNames`in t){const n=new Set(t.persistenceToolNames);const r=new Set(t.lookupToolNames??[]);return e.flatMap(e=>{if(e.name===`read`)return[e];if(getPluginToolMeta(e)?.pluginId!==t.ownerPluginId)return[];if(n.has(e.name))return[wrapPersistenceTool(e,t.recordPersistenceToolSuccess)];return r.has(e.name)?[e]:[]})}return e.flatMap(e=>{if(e.name===`read`)return[e];return e.name===`write`?[wrapToolMemoryFlushAppendOnlyWrite(e,t)]:[]})}function assertMemoryFlushPersistenceToolAvailable(e,t){if(!t)return;const n=new Set(e.filter(e=>getPluginToolMeta(e)?.pluginId===t.ownerPluginId).map(e=>e.name));const isPersistenceToolAvailable=e=>e!==`read`&&n.has(e);if(!t.persistenceToolNames.some(isPersistenceToolAvailable))throw new MemoryFlushToolsUnavailableError(t.persistenceToolNames.filter(e=>!isPersistenceToolAvailable(e)));const r=[...new Set((t.lookupToolNames??[]).filter(e=>!n.has(e)))];if(r.length>0)logWarn(`plugin "${t.ownerPluginId}" flush cannot check for existing memory: ${r.join(`, `)} did not survive this agent's tool policy.`)}async function readOptionalUtf8File(e){try{if(e.sandbox){if(!await e.sandbox.bridge.stat({filePath:e.relativePath,cwd:e.sandbox.root,signal:e.signal}))return``;return(await e.sandbox.bridge.readFile({filePath:e.relativePath,cwd:e.sandbox.root,signal:e.signal})).toString(`utf-8`)}return await fs.readFile(e.absolutePath,`utf-8`)}catch(e){if(hasErrnoCode(e,`ENOENT`))return``;throw e}}async function appendMemoryFlushContent(e){await runWithAgentToolSourceExecutionScope(e.assertCurrent,async()=>{const t=e.sandbox;if(!t){const t=await root(e.root);e.assertCurrent();await t.append(e.relativePath,e.content,{mkdir:true,prependNewlineIfNeeded:true,assertBeforeMutation:e.assertCurrent});return}const n=resolveSandboxFileMutationQueueKey({...t,filePath:e.absolutePath,cwd:t.root,signal:e.signal});await withFileMutationQueueKeyResolution(n,async()=>{const n=await readOptionalUtf8File(e);const r=n.length>0&&!n.endsWith(` `)&&!e.content.startsWith(` `)?` `:``;e.assertCurrent();await t.bridge.writeFile({filePath:e.relativePath,cwd:t.root,data:`${n}${r}${e.content}`,mkdir:true,signal:e.signal})})})}function wrapToolMemoryFlushAppendOnlyWrite(e,t){const n=path.resolve(t.root,t.relativePath);return{...e,description:`Append new memory notes to ${t.relativePath}; creates parent directories. The content is appended verbatim. Send only new text, never existing entries or a rewritten file.`,execute:async(r,i,a,o)=>{const s=captureAgentToolSourceExecutionGuard(a);const c=asOptionalObjectRecord(i);const l=c?await normalizeFileToolPathParamsFromKeys(c,[`path`],t.root,t.sandbox?.bridge):void 0;assertRequiredParams(l,REQUIRED_PARAM_GROUPS.write,e.name);const u=typeof l?.path===`string`&&l.path.trim()?l.path:void 0;const d=typeof c?.content===`string`?c.content:void 0;if(!u||d===void 0)return e.execute(r,i,a,o);const f=resolveToolPathAgainstWorkspaceRoot({filePath:u,root:t.root,containerWorkdir:t.containerWorkdir});if(u.startsWith(`@`)||f!==n)throw new Error(`Memory flush writes are restricted to ${t.relativePath}; use that path only.`);const p=await runWithAgentToolSourceExecutionScope(s,async()=>{const e=await readOptionalUtf8File({absolutePath:n,relativePath:t.relativePath,sandbox:t.sandbox,signal:a});s();return e});assertNewMemoryFlushContent(p,d);const m=p.length>0&&!p.endsWith(` `)&&!d.startsWith(` `)?` `:``;const commit=()=>appendMemoryFlushContent({absolutePath:n,root:t.root,relativePath:t.relativePath,content:d,sandbox:t.sandbox,signal:a,assertCurrent:s});const h=t.memoryWriteProvenance;if(h&&await h.classifies(n))await h.write({absolutePath:n,contentBefore:p,contentAfter:`${p}${m}${d}`,commit});else await commit();return{content:[{type:`text`,text:`Appended content to ${t.relativePath}.`}],details:{changed:true}}}}}export{warnIfMemoryFlushFileWriterUnavailable as a,resolveMemoryFlushToolSetup as i,assertMemoryFlushPersistenceToolAvailable as n,projectMemoryFlushTools as r,MemoryFlushToolsUnavailableError as t};