openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
246 lines (245 loc) • 10.1 kB
JavaScript
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs";
import { i as asOptionalObjectRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { w as root } from "./fs-safe-BbWvmdVn.mjs";
import { i as getPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs";
import { a as copyAgentToolMetadata } from "./agent-tool-metadata-nrQgRaqv.mjs";
import { n as recordModelFallbackStop } from "./model-fallback-stop-BN_k3Te_.mjs";
import { i as logWarn } from "./logger-CIwfuhOU.mjs";
import { s as resolveToolPathAgainstWorkspaceRoot } from "./path-policy-CyYRyWre.mjs";
import { a as normalizeFileToolPathParamsFromKeys, n as assertRequiredParams, t as REQUIRED_PARAM_GROUPS } from "./agent-tools.params-D3Fjhk01.mjs";
import { n as isToolResultError } from "./tool-result-error-B2GHe83l.mjs";
import { r as captureAgentToolSourceExecutionGuard, s as runWithAgentToolSourceExecutionScope } from "./agent-tool-source-execution-guard-CD-ezY7E.mjs";
import { n as withFileMutationQueueKeyResolution } from "./file-mutation-queue-C-FUKJ7m.mjs";
import { r as resolveSandboxFileMutationQueueKey } from "./file-mutation-identity-B9yq_vIv.mjs";
import path from "node:path";
import fs from "node:fs/promises";
//#region src/agents/agent-tools.message-provider-policy.ts
/**
* Channels can restrict tool names after runtime assembly when the active
* transport cannot safely render or execute a class of tools.
*/
const TOOL_DENY_BY_MESSAGE_PROVIDER = {
"discord-voice": ["tts"],
voice: ["tts"]
};
const TOOL_ALLOW_BY_MESSAGE_PROVIDER = { node: [
"canvas",
"pdf",
"tts",
"view_image",
"web_fetch",
"web_search"
] };
/**
* True when a provider's allowlist removes the tool by design rather than by an
* operator's policy. Callers that diagnose a missing tool use this to stay quiet about
* transports that were never meant to carry it.
*/
function messageProviderExcludesTool(e, t) {
const n = normalizeOptionalLowercaseString(e);
if (!n) return false;
const r = TOOL_ALLOW_BY_MESSAGE_PROVIDER[n];
return r !== void 0 && r.length > 0 && !r.includes(t);
}
/** Applies message-provider filtering while preserving duplicate tool entries. */
function filterToolsByMessageProvider(e, t) {
const n = normalizeOptionalLowercaseString(t);
if (!n) return [...e];
const r = TOOL_ALLOW_BY_MESSAGE_PROVIDER[n];
if (r && r.length > 0) {
const t = new Set(r);
return e.filter((e) => t.has(e.name));
}
const i = TOOL_DENY_BY_MESSAGE_PROVIDER[n];
if (!i || i.length === 0) return [...e];
const a = new Set(i);
return e.filter((e) => !a.has(e.name));
}
//#endregion
//#region src/agents/memory-flush-content.ts
/** Reject replayed notes without editing either the saved bytes or the proposed delta. */
function assertNewMemoryFlushContent(e, t) {
const n = e.replaceAll("\r\n", "\n").trim();
if (!n) return;
const r = t.replaceAll("\r\n", "\n").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.");
}
//#endregion
//#region src/agents/agent-tools.memory-flush.ts
/** Validate the memory trigger's persistence arm and expose its plugin identity. */
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
};
}
/** Warn when policy removes the append-only writer from a file-arm flush. */
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.`);
}
/** A pre-inference skip when the provider has no authorized persistence tool. */
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;
}
});
}
/** Project a memory flush onto its file writer or selected provider-owned persistence tools. */
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)] : [];
});
}
/** Reject a tools-arm flush before inference when policy removed every declared writer. */
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("\n") && !e.content.startsWith("\n") ? "\n" : "";
e.assertCurrent();
await t.bridge.writeFile({
filePath: e.relativePath,
cwd: t.root,
data: `${n}${r}${e.content}`,
mkdir: true,
signal: e.signal
});
});
});
}
/** Restrict a write tool to appending memory-flush content to one path. */
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("\n") && !d.startsWith("\n") ? "\n" : "";
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 }
};
}
};
}
//#endregion
export { warnIfMemoryFlushFileWriterUnavailable as a, resolveMemoryFlushToolSetup as i, assertMemoryFlushPersistenceToolAvailable as n, filterToolsByMessageProvider as o, projectMemoryFlushTools as r, MemoryFlushToolsUnavailableError as t };