openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
163 lines (162 loc) • 6.01 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { n as createLazyPromise } from "./lazy-promise-DiCvjz9w.mjs";
import { u as mimeTypeFromFilePath } from "./mime-D2wVBzpa.mjs";
import { r as logVerbose } from "./globals-CgepmiqE.mjs";
import { n as hasInboundMedia } from "./inbound-media-BJ8l1Cri.mjs";
//#region src/auto-reply/reply/history-media.ts
const RECENT_HISTORY_IMAGE_TTL_MS = 18e5;
const RECENT_HISTORY_IMAGE_LIMIT = 4;
function isRemotePath(e) {
if (/^[a-z]:[\\/]/i.test(e)) return false;
const t = URL.parse(e);
return t !== null && t.protocol !== "file:";
}
function resolveRecentInboundHistoryImages(e) {
const t = asFiniteNumber(e.ctx.Timestamp) ?? Date.now();
const n = [];
const r = /* @__PURE__ */ new Set();
const i = e.ctx.InboundHistory ?? [];
for (let a = i.length - 1; a >= 0 && n.length < RECENT_HISTORY_IMAGE_LIMIT; a -= 1) {
const o = expectDefined(i[a], "entries entry at index");
const s = asFiniteNumber(o.timestamp);
if (s === void 0 || Math.abs(t - s) > RECENT_HISTORY_IMAGE_TTL_MS) continue;
const c = o.media ?? [];
for (let t = c.length - 1; t >= 0 && n.length < RECENT_HISTORY_IMAGE_LIMIT; t -= 1) {
const l = c[t];
if (!l || !e.isImageAttachment({
path: l.path,
url: l.url,
mime: l.contentType,
kind: l.kind,
index: t
})) continue;
const u = normalizeOptionalString(l.path);
if (!u || isRemotePath(u)) continue;
const d = normalizeOptionalString(l.contentType) ?? mimeTypeFromFilePath(u);
const f = normalizeOptionalString(l.messageId) ?? o.messageId;
const p = [f ?? "", u].join("\0");
if (r.has(p)) continue;
r.add(p);
n.push({
path: u,
...d ? { contentType: d } : {},
...l.kind ? { kind: l.kind } : {},
sender: o.sender,
sentAtMs: s,
messagePosition: a + 1,
messageCount: i.length,
...f ? { messageId: f } : {}
});
}
}
return n.toReversed();
}
function formatRecentHistoryImageSentAt(e) {
const t = new Date(e);
return Number.isFinite(t.getTime()) ? t.toISOString() : `${e}ms since epoch`;
}
function appendRecentHistoryImageContext(e) {
if (e.images.length === 0) return e.promptText;
const t = e.images.map((e, t) => {
const n = e.messageId ? `, message ${e.messageId}` : "";
const r = formatRecentHistoryImageSentAt(e.sentAtMs);
return `[Recent image ${t + 1} from ${e.sender}${n}, sent at ${r}, message ${e.messagePosition} of ${e.messageCount} in available history, attached as media.]`;
});
return [e.promptText, t.join("\n")].filter((e) => e.trim().length > 0).join("\n\n");
}
//#endregion
//#region src/auto-reply/reply/agent-turn-attachments.ts
const loadAgentTurnMediaRuntime = createLazyPromise(() => import("./dispatch-acp-media.runtime.js"));
const AGENT_TURN_ATTACHMENT_MAX_BYTES = 10485760;
const AGENT_TURN_ATTACHMENT_TIMEOUT_MS = 1e3;
function hasInboundHistoryMedia(e) {
return e.InboundHistory?.some((e) => (e.media?.length ?? 0) > 0) ?? false;
}
/** Current-turn image indexes already represented by media-understanding text. */
function collectDescribedImageAttachmentIndexes(e) {
return new Set(e.MediaUnderstanding?.filter((e) => e.kind === "image.description").map((e) => e.attachmentIndex) ?? []);
}
async function resolveAgentTurnAttachments(e) {
const t = e.includeRecentHistoryImages ?? true;
if (!hasInboundMedia(e.ctx) && !(t && hasInboundHistoryMedia(e.ctx))) return {
attachments: [],
recentHistoryImages: []
};
const n = await loadAgentTurnMediaRuntime();
const r = n.normalizeAttachments(e.ctx).map((e) => normalizeOptionalString(e.path) ? Object.assign({}, e, { url: void 0 }) : e);
const i = t ? resolveRecentInboundHistoryImages({
ctx: e.ctx,
isImageAttachment: n.isImageAttachment
}) : [];
const a = (r.at(-1)?.index ?? -1) + 1;
const o = i.map((e, t) => ({
path: e.path,
mime: e.contentType,
kind: e.kind,
index: a + t
}));
const s = [...r, ...o];
const c = new n.MediaAttachmentCache(s, {
localPathRoots: n.resolveMediaAttachmentLocalRoots({
cfg: e.cfg,
ctx: e.ctx
}),
includeDefaultLocalPathRoots: false
});
const l = [];
const u = [];
const d = [];
const resolveImageAttachment = async (e) => {
if (!n.isImageAttachment(e) || !normalizeOptionalString(e.path)) return false;
try {
const { buffer: t, mime: n } = await c.getBuffer({
attachmentIndex: e.index,
maxBytes: AGENT_TURN_ATTACHMENT_MAX_BYTES,
timeoutMs: AGENT_TURN_ATTACHMENT_TIMEOUT_MS
});
if (!n?.startsWith("image/")) return false;
l.push({
mediaType: n,
data: t.toString("base64")
});
u.push(e.index);
const r = i[e.index - a];
if (r) d.push(r);
return true;
} catch (t) {
if (n.isMediaUnderstandingSkipError(t)) logVerbose(`agent-turn-attachments: skipping attachment #${e.index + 1} (${t.reason})`);
else {
const n = t instanceof Error ? t.name : typeof t;
logVerbose(`agent-turn-attachments: failed to read attachment #${e.index + 1} (${n})`);
}
return false;
}
};
const f = collectDescribedImageAttachmentIndexes(e.ctx);
let p = false;
const m = r.some(n.isImageAttachment);
for (const e of r) {
if (f.has(e.index) && n.isImageAttachment(e)) {
p = true;
continue;
}
p = await resolveImageAttachment(e) || p;
}
if (t && !p && (r.length === 0 || m)) for (const e of o) await resolveImageAttachment(e);
return {
attachments: l,
attachmentIndexes: u,
recentHistoryImages: d
};
}
function resolveInlineAgentImageAttachments(e) {
return (e ?? []).map((e) => ({
mediaType: e.mimeType,
data: e.data
})).filter((e) => e.mediaType.startsWith("image/") && e.data.trim().length > 0);
}
//#endregion
export { appendRecentHistoryImageContext as a, resolveInlineAgentImageAttachments as i, loadAgentTurnMediaRuntime as n, resolveAgentTurnAttachments as r, collectDescribedImageAttachmentIndexes as t };