openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
205 lines (204 loc) • 10.1 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { b as uniqueStrings } from "./string-normalization-DLmfYZXI.mjs";
import { i as truncateWithMarker } from "./utf16-slice-CuDyEXgS.mjs";
import { g as labelRuntimeContextText } from "./types-iq-cNLsd.mjs";
import { a as annotateInterSessionPromptText } from "./input-provenance-DupvvURj.mjs";
import { t as basenameFromAnyPath } from "./file-name-PRG-HeBL.mjs";
import { s as escapeInternalRuntimeContextDelimiters } from "./internal-runtime-context-BEUlDNuI.mjs";
import { c as normalizeAgentRunRouteChange } from "./agent-run-terminal-reply-DXju8G9G.mjs";
import { d as hasGeneratedMediaCompletionEvent } from "./requester-tool-policy-BFuyRJjU.mjs";
import { i as wrapPromptDataBlock, r as sanitizeForPromptLiteral } from "./sanitize-for-prompt-CAahLekM.mjs";
//#region src/agents/generated-attachments.ts
function generatedAttachmentReference(e) {
return normalizeOptionalString(e.path ?? e.url ?? e.mediaUrl ?? e.filePath);
}
function mediaUrlsFromGeneratedAttachments(e) {
return uniqueStrings(e?.flatMap((e) => generatedAttachmentReference(e) ?? []) ?? []);
}
function nameFromGeneratedAttachment(e) {
return normalizeOptionalString(e.name) ?? basenameFromAnyPath(generatedAttachmentReference(e) ?? "");
}
function neutralizeEscapedGeneratedMediaDirective(e) {
return e.replace(/((?:\\r\\n|\\n|\\r)[^\S\r\n]*)(media):/giu, "$1$2:").replace(/((?:\\r\\n|\\n|\\r) {0,3})(`{3,}|~{3,})/gu, "$1>$2");
}
const GENERATED_MEDIA_ESCAPES = {
"\\": "\\\\",
"\r": "\\r",
"\n": "\\n",
" ": "\\t"
};
const GENERATED_MEDIA_ESCAPE_PATTERN = new RegExp(String.raw`[\\\u0000-\u001f\u007f\u2028\u2029]`, "g");
/** Escape provider-controlled summary text without changing its structured result. */
function sanitizeGeneratedMediaDisplayText(e) {
const t = e.replace(GENERATED_MEDIA_ESCAPE_PATTERN, (e) => GENERATED_MEDIA_ESCAPES[e] ?? `\\u${e.charCodeAt(0).toString(16).padStart(4, "0")}`);
return neutralizeEscapedGeneratedMediaDirective(sanitizeForPromptLiteral(t)).replaceAll("[[", "[[").replaceAll("![", "![");
}
function quoteGeneratedAttachmentDisplay(e) {
return neutralizeEscapedGeneratedMediaDirective(JSON.stringify(sanitizeForPromptLiteral(e))).replaceAll("[", "\\u005b");
}
/** Format generated attachment metadata as prompt-safe text lines. */
function formatGeneratedAttachmentLines(e) {
if (!e?.length) return [];
const t = ["Attachments:"];
for (const [n, r] of e.entries()) {
const e = [`${n + 1}.`];
const i = normalizeOptionalString(r.type);
const a = nameFromGeneratedAttachment(r);
const o = normalizeOptionalString(r.mimeType);
const s = normalizeOptionalString(r.path ?? r.filePath);
const c = normalizeOptionalString(r.url ?? r.mediaUrl);
if (i) e.push(`type=${quoteGeneratedAttachmentDisplay(i).slice(1, -1)}`);
if (a) e.push(`name=${quoteGeneratedAttachmentDisplay(a)}`);
if (o) e.push(`mimeType=${quoteGeneratedAttachmentDisplay(o).slice(1, -1)}`);
if (s) e.push(`path=${quoteGeneratedAttachmentDisplay(s)}`);
else if (c) e.push(`mediaUrl=${quoteGeneratedAttachmentDisplay(c)}`);
t.push(e.join(" "));
}
return t;
}
//#endregion
//#region src/agents/internal-events.ts
/**
* Internal runtime event prompt formatting.
* Sanitizes background task completion events into protected runtime-context
* blocks or plain prompt text.
*/
const MAX_TASK_COMPLETION_STATUS_LABEL_CHARS = 500;
const TASK_COMPLETION_STATUS_LABEL_TRUNCATION_MARKER = "…[truncated]";
const MEDIA_DIRECTIVE_CONTROL_CHARS = new RegExp(String.raw`[\u0000-\u001f\u007f]`, "g");
/** Collect ordered media descriptors and per-reference trust from internal events. */
function collectAgentInternalEventMedia(e) {
const t = /* @__PURE__ */ new Map();
const n = /* @__PURE__ */ new Map();
for (const r of e ?? []) {
const e = hasGeneratedMediaCompletionEvent([r]);
const i = new Map((r.attachments ?? []).flatMap((e) => {
const t = normalizeOptionalString(e.path ?? e.url ?? e.mediaUrl ?? e.filePath);
return t ? [[t, e]] : [];
}));
for (const a of [...r.mediaUrls ?? [], ...mediaUrlsFromGeneratedAttachments(r.attachments)]) {
const r = normalizeOptionalString(a);
if (!r) continue;
const o = i.get(r);
const s = t.get(r);
n.set(r, n.get(r) === true || e);
if (!s || o && Object.keys(s).length === 0) t.set(r, o ?? {});
}
}
return {
mediaUrls: [...t.keys()],
attachments: [...t.values()],
trustByUrl: n
};
}
function sanitizeSingleLineField(e, t, n = false) {
return (n ? e : escapeInternalRuntimeContextDelimiters(e)).replace(/\r?\n+/g, " ").trim() || t;
}
function sanitizeMultilineField(e) {
return escapeInternalRuntimeContextDelimiters(e).replace(/\r\n/g, "\n").trim();
}
function sanitizeMediaDirectiveValue(e, t = false) {
return (t ? e : escapeInternalRuntimeContextDelimiters(e)).replace(/\r?\n/g, " ").replace(MEDIA_DIRECTIVE_CONTROL_CHARS, " ").trim() || null;
}
function formatChildResultDataBlock(e) {
return wrapPromptDataBlock({
label: "Child result",
text: e,
encoding: "verbatim"
}) || "Child result: (no output)";
}
function formatGeneratedMediaDirectiveLines(e, t = false) {
const n = Array.from(new Set([...e.mediaUrls ?? [], ...mediaUrlsFromGeneratedAttachments(e.attachments)].map((e) => sanitizeMediaDirectiveValue(e, t)).filter((e) => e !== null)));
if (n.length === 0) return [];
return ["Generated media:", ...n.map((e) => {
return `MEDIA:${e.includes("\"") || /[`'\\})\],]$/u.test(e) ? `"${e}"` : e}`;
})];
}
function formatTaskCompletionEvent(e, t) {
const singleLine = (e, n) => sanitizeSingleLineField(e, n, t === "data");
const n = singleLine(e.childSessionKey, "unknown");
const r = singleLine(e.childSessionId ?? "unknown", "unknown");
const i = singleLine(e.announceType, "unknown");
const a = singleLine(e.taskLabel, "unnamed task");
const o = truncateWithMarker(singleLine(e.statusLabel, e.status), MAX_TASK_COMPLETION_STATUS_LABEL_CHARS, {
marker: TASK_COMPLETION_STATUS_LABEL_TRUNCATION_MARKER,
reserve: 12,
trimEnd: true
});
const s = t === "data" ? e.result || "(no output)" : formatChildResultDataBlock(e.result);
const c = normalizeAgentRunRouteChange(e.modelRouteChange);
const l = formatGeneratedAttachmentLines(e.attachments);
const u = formatGeneratedMediaDirectiveLines(e, t === "data");
const d = t !== "plain" ? ["[Internal task completion event]"] : ["A background task completed. Use this result to reply to the user in your normal assistant voice.", ""];
d.push(`source: ${e.source}`, `session_key: ${n}`, `session_id: ${r}`, `type: ${i}`, `task: ${a}`, `status: ${o}`, "", s);
if (c) d.push("", c);
if (l.length > 0) d.push("", ...l);
if (u.length > 0) d.push("", ...u);
if (e.statsLine?.trim()) d.push("", t === "data" ? e.statsLine : sanitizeMultilineField(e.statsLine));
if (t !== "data") d.push("", t === "protected" ? "Action:" : "Instruction:", sanitizeMultilineField(e.replyInstruction));
return d.join("\n");
}
/** Provenance comes from the producer event; child output and labels remain data. */
function buildAgentInternalEventContext(e, t = []) {
return [...(e ?? []).flatMap((e) => [
{
kind: "runtime-instruction",
text: "A background task completed. Keep internal details private and use its result to reply in your normal assistant voice."
},
{
kind: "conversation-data",
text: formatTaskCompletionEvent(e, "data")
},
{
kind: "runtime-instruction",
text: e.replyInstruction
}
]), ...t];
}
/** Format internal runtime events for the protected runtime-context prompt block. */
function formatAgentInternalEventsForPrompt(e) {
const t = (e ?? []).filter((e) => e.type === "task_completion").map((e) => formatTaskCompletionEvent(e, "protected"));
if (t.length === 0) return "";
return labelRuntimeContextText([
"This context is runtime-generated, not user-authored. Keep internal details private.",
"",
t.join("\n\n---\n\n")
].join("\n"));
}
/** Tell a completion turn which generated media the host already delivered. */
function formatGeneratedMediaDeliveredForPrompt(e) {
return labelRuntimeContextText([
"This context is runtime-generated, not user-authored. Keep internal details private.",
"",
"[Generated media delivered]",
"The host already sent this generated media to the original chat:",
...e.flatMap((e) => {
const t = sanitizeMediaDirectiveValue(e);
return t ? [`- ${t}`] : [];
}),
"",
"Do not send these files again. Your reply goes to the same chat after them."
].join("\n"));
}
/** Format internal runtime events for plain prompts that lack context delimiters. */
function formatAgentInternalEventsForPlainPrompt(e) {
return (e ?? []).filter((e) => e.type === "task_completion").map((e) => formatTaskCompletionEvent(e, "plain")).join("\n\n---\n\n");
}
/** Remove only the canonical duplicate carried by the existing internal-events API. */
function resolveInternalEventPromptBody(e, t, n, r = false) {
const i = formatAgentInternalEventsForPrompt(t);
if (i) {
for (const t of [i, annotateInterSessionPromptText(i, n)]) if (e === t || e.startsWith(`${t}\n\n`)) return [r ? t.slice(0, -i.length).trimEnd() : "", e.slice(t.length).trimStart()].filter(Boolean).join("\n\n");
}
return e;
}
/** Plain runtimes and transcripts retain the existing visible event representation. */
function resolveAcpPromptBody(e, t, n) {
const r = formatAgentInternalEventsForPlainPrompt(t);
return r ? [r, resolveInternalEventPromptBody(e, t, n, true)].filter(Boolean).join("\n\n") : e;
}
function resolveInternalEventTranscriptBody(e, t, n) {
return resolveInternalEventPromptBody(e, t, n) === e ? e : resolveAcpPromptBody(e, t, n);
}
//#endregion
export { resolveAcpPromptBody as a, formatGeneratedAttachmentLines as c, formatGeneratedMediaDeliveredForPrompt as i, mediaUrlsFromGeneratedAttachments as l, collectAgentInternalEventMedia as n, resolveInternalEventPromptBody as o, formatAgentInternalEventsForPrompt as r, resolveInternalEventTranscriptBody as s, buildAgentInternalEventContext as t, sanitizeGeneratedMediaDisplayText as u };