UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

378 lines (377 loc) • 13.8 kB
import { r as formatUncaughtError, t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-CoHTemu-.mjs"; import { a as WorkerTaskError } from "./src-Dkfkl2Oz.mjs"; import { t as WorkerTaskPool } from "./worker-task-pool-BshJjv1P.mjs"; import { r as inspectBase64 } from "./base64-CnKpkbff.mjs"; import { t as SessionMutationAuthorizationChangedError } from "./session-mutation-authorization-error-0K0ZVV7q.mjs"; import { r as MAX_IMAGE_BYTES } from "./constants-ChkaB-HW.mjs"; import { d as normalizeMimeType, l as kindFromMime, r as extensionForMime, u as mimeTypeFromFilePath } from "./mime-D2wVBzpa.mjs"; import { n as registerMediaCleanupDrain } from "./server-media-cleanup-lifecycle-CLvUNPN_.mjs"; import { t as formatForLog } from "./ws-log-CbOV6uhk.mjs"; import { f as readImageMetadataFromHeader } from "./image-ops-zeupBxnN.mjs"; import { t as probeMediaFilesWithinBudget } from "./media-probe-_SAoK4Iu.mjs"; import { d as saveMediaBuffer, i as deleteMediaBuffer } from "./store-zsTAVy24.mjs"; import { n as classifyAttachmentBytes } from "./attachment-classify-DFSZjMac.mjs"; import { t as DEFAULT_CHAT_ATTACHMENT_MAX_BYTES } from "./chat-attachment-policy-7g-oMINW.mjs"; import { t as sniffMimeFromBase64 } from "./sniff-mime-from-base64-IFkz2jJd.mjs"; //#region src/media/attachment-processor.runtime.ts const ATTACHMENT_OFFLOAD_THRESHOLD_BYTES = 2e6; function isGenericContainerMime(e) { return e === "application/zip" || e === "application/octet-stream"; } function readAttachmentImageMetadata(e) { if (e.startsWith("iVBORw0KGgoAAAAN")) return readImageMetadataFromHeader(Buffer.from(e.slice(0, 32), "base64")); if (e.startsWith("R0lGODdh") || e.startsWith("R0lGODlh")) return readImageMetadataFromHeader(Buffer.from(e.slice(0, 16), "base64")); const t = Buffer.from(e.slice(0, 40), "base64"); if (t.toString("ascii", 0, 4) === "RIFF" && t.toString("ascii", 8, 12) === "WEBP") return readImageMetadataFromHeader(t); if (t[0] === 255 && t[1] === 216) { let t = 2; for (let n = 4096; n <= 262144; n *= 4) { const r = Math.ceil(n / 3) * 4; const i = Buffer.from(e.slice(0, r), "base64"); if (r >= e.length) return readImageMetadataFromHeader(i); while (t + 4 < i.length && i[t] === 255) { const e = i[t + 1]; if (e === 255) { t++; continue; } if (e === 218 || e === 217) { const e = readImageMetadataFromHeader(i); if (e) return e; break; } const n = i.readUInt16BE(t + 2); if (n < 2 || t + 2 + n > i.length) break; t += 2 + n; } } } return readImageMetadataFromHeader(Buffer.from(e, "base64")); } async function prepareAttachment(e) { const t = inspectBase64(e.base64, "attachment"); if (!t) throw new Error(`attachment ${e.label}: invalid base64 content`); let n = e.imageStorage !== "inline" && t.decodedBytes > 2e6 && t.decodedBytes <= 6291456 ? Buffer.from(e.base64, "base64") : void 0; const r = normalizeMimeType(e.mime); const i = [r, mimeTypeFromFilePath(e.label)]; let a = await sniffMimeFromBase64({ ...t, buffer: n }, { additionalMimeHints: [...i.filter((e) => !isGenericContainerMime(e)), ...i] }) ?? "application/octet-stream"; if (!n && !a.startsWith("image/")) n = Buffer.from(e.base64, "base64"); if (n && a.startsWith("text/") && (!r || r === "application/octet-stream")) { const t = await classifyAttachmentBytes({ buffer: n, name: e.label }); if (t.class === "text" && t.charset) a = `${a}; charset=${t.charset}`; } const o = a.startsWith("image/") && t.decodedBytes <= 6291456 ? n ? readImageMetadataFromHeader(n) : readAttachmentImageMetadata(e.base64) : null; return { sizeBytes: t.decodedBytes, mime: a, buffer: n, ...o }; } //#endregion //#region src/media/attachment-processor.ts const pool = new WorkerTaskPool({ workerUrl: resolveRuntimeProcessEntrypointUrl("attachmentProcessor"), workerClass: "compute", sharedCompute: true }); async function prepareMediaAttachment(e, t, n) { n?.throwIfAborted(); const r = Math.floor(e.base64.length * 3 / 4) - (e.base64.endsWith("==") ? 2 : e.base64.endsWith("=") ? 1 : 0); if (r > t) throw new Error(`attachment ${e.label}: exceeds size limit (${r} > ${t} bytes)`); const i = e.base64.length < 262144 ? await prepareAttachment(e) : await pool.run(e, { inputBytes: e.base64.length * 2, signal: n, timeoutMs: 18e4 }); n?.throwIfAborted(); return i; } //#endregion //#region src/gateway/chat-attachments.ts const inlineImageMetadata = /* @__PURE__ */ new WeakMap(); function projectOffloadedMediaFact(e, t) { const n = { ...t ? {} : { path: e.path }, url: t ? `media://inbound/${e.id}` : e.mediaRef, contentType: e.mimeType, kind: e.kind, fileName: e.label, ...e.origin ? { origin: e.origin } : {}, sizeBytes: e.sizeBytes }; for (const r of [ "durationMs", "width", "height" ]) if (t ? e[r] !== void 0 : e[r]) n[r] = e[r]; if (t && !e.mimeType.startsWith("image/")) n.hydrationSuppressed = true; return n; } /** Deletes prepared inbound files that never reached a durable owner. */ async function discardPreparedInboundMedia(e, t) { const n = Promise.allSettled(e.map((e) => deleteMediaBuffer(e.id, "inbound"))); registerMediaCleanupDrain(n.then(() => void 0)); const r = await n; for (const [n, i] of r.entries()) if (i.status === "rejected" && t) t.warn(`failed to discard prepared inbound media ${e[n]?.id}: ${formatErrorMessage(i.reason)}`); } const INLINE_IMAGE_DURABLE_OMISSION_MARKER = "[image attachment omitted: durable managed media claim unavailable]"; const TEXT_ONLY_OFFLOAD_LIMIT = 10; const MAX_CHAT_ATTACHMENT_MEDIA_PROBES = 8; const CHAT_ATTACHMENT_MEDIA_PROBE_CONCURRENCY = 2; const CHAT_ATTACHMENT_MEDIA_PROBE_BUDGET_MS = 3e3; async function enrichOffloadedMediaMetadata(e) { const t = e.flatMap((e) => { const t = kindFromMime(e.mimeType); return t === "audio" || t === "video" ? [{ kind: t, ref: e }] : []; }); const n = await probeMediaFilesWithinBudget(t.map(({ kind: e, ref: t }) => ({ filePath: t.path, kind: e })), { budgetMs: CHAT_ATTACHMENT_MEDIA_PROBE_BUDGET_MS, concurrency: CHAT_ATTACHMENT_MEDIA_PROBE_CONCURRENCY, maxProbes: MAX_CHAT_ATTACHMENT_MEDIA_PROBES }); for (const [e, r] of t.entries()) Object.assign(r.ref, n[e]); } function logAttachmentFailure(e, t, n) { const r = formatUncaughtError(n); const i = n instanceof Error ? n.cause : void 0; const a = i === void 0 ? "" : formatUncaughtError(i); e.error(t, { error: !a || a === r ? r : `${r}\nCaused by: ${a}`, consoleMessage: `${t}: ${formatForLog(n)}` }); } function stripImageMediaMarkers(e, t) { return t.reduce((e, t) => { const n = t.mimeType.startsWith("image/") ? `\n[media attached: ${t.mediaRef}]` : ""; const r = n ? e.lastIndexOf(n) : -1; return r < 0 ? e : e.slice(0, r) + e.slice(r + n.length); }, e); } async function persistInboundImagesForTranscript(e) { const t = []; let n = "none"; try { for (const [r, i] of e.images.entries()) { const a = inlineImageMetadata.get(i); try { e.assertCurrent?.(); const n = await saveMediaBuffer(Buffer.from(i.data, "base64"), i.mimeType, "inbound", void 0, a?.fileName, void 0, { assertCommitAllowed: e.assertCurrent }); t.push({ id: n.id, path: n.path, sourceIndex: a?.sourceIndex ?? r, imageKind: "inline", fact: { url: `media://inbound/${n.id}`, contentType: n.contentType ?? i.mimeType, kind: "image", ...a?.fileName ? { fileName: a.fileName } : {}, sizeBytes: n.size, width: a?.width, height: a?.height } }); } catch (t) { if (t instanceof SessionMutationAuthorizationChangedError) throw t; e.assertCurrent?.(); n = "inline-image-save-failed"; e.log.warn(`${e.logContext}: failed to persist inbound image (${i.mimeType}): ${formatErrorMessage(t)}`); } } e.assertCurrent?.(); } catch (n) { await discardPreparedInboundMedia(t, e.log); throw n; } for (const n of e.offloadedRefs) { const e = projectOffloadedMediaFact(n, true); t.push({ id: n.id, path: n.path, sourceIndex: n.sourceIndex, ...n.mimeType.startsWith("image/") ? { imageKind: "offloaded" } : {}, fact: e }); } t.sort((e, t) => e.sourceIndex - t.sourceIndex); return { entries: t, omission: n }; } var UnsupportedAttachmentError = class extends Error { constructor(e, t) { super(t); this.name = "UnsupportedAttachmentError"; this.reason = e; } }; var MediaOffloadError = class extends Error { constructor(e, t) { super(e, t); this.name = "MediaOffloadError"; this.cause = t?.cause; } }; function ensureExtension(e, t) { if (/\.[a-zA-Z0-9]+$/.test(e)) return e; const n = extensionForMime(t) ?? ""; return n ? `${e}${n}` : e; } function normalizeAttachment(e, t) { const n = e.mimeType ?? ""; const r = e.content; const i = e.fileName || e.type || `attachment-${t + 1}`; if (typeof r !== "string") throw new Error(`attachment ${i}: content must be base64 string`); let a = r.trim(); const o = a.startsWith("data:") ? a.indexOf(",") : -1; if (o >= 0 && /^data:[^;,]+;base64$/.test(a.slice(0, o))) a = a.slice(o + 1); return { label: i, mime: n, base64: a }; } async function parseMessageWithAttachments(e, t, n) { const r = n?.maxBytes ?? 20971520; const i = n?.log; const a = n?.supportsInlineImages !== false; const o = n?.acceptNonImage !== false; const s = n?.supportsImages; let c = typeof s === "boolean" ? s : void 0; const resolveSupportsImages = async () => { if (c !== void 0) return c; c = typeof s === "function" ? await s() : true; return c; }; if (!t || t.length === 0) return { message: e, images: [], imageOrder: [], media: [], offloadedRefs: [] }; const l = []; const u = []; const d = []; let f = e; let p = 0; const m = []; try { n?.assertCurrent?.(); for (const [e, s] of t.entries()) { if (!s) continue; const { base64: t, label: c, mime: h } = normalizeAttachment(s, e); if (t.length === 0) throw new UnsupportedAttachmentError("empty-payload", `attachment ${c}: empty payload`); const g = await prepareMediaAttachment({ base64: t, label: c, mime: h, imageStorage: n?.imageStorage }, r, n?.signal); const { sizeBytes: _, mime: v } = g; const y = normalizeMimeType(h); if (y && !isGenericContainerMime(y) && v !== y) i?.warn(`attachment ${c}: mime mismatch (${y} -> ${v})`); const b = v.startsWith("image/"); const x = b && !await resolveSupportsImages(); n?.signal?.throwIfAborted(); n?.assertCurrent?.(); if (b && !a && !x) throw new UnsupportedAttachmentError("text-only-image", `attachment ${c}: active model does not accept image inputs`); if (!b && !o) throw new UnsupportedAttachmentError("unsupported-non-image", `attachment ${c}: non-image attachments (${v}) are not supported on this entrypoint`); if (b && _ > 6291456) throw new Error(`attachment ${c}: image exceeds size limit (${_} > ${MAX_IMAGE_BYTES} bytes)`); if (x && p >= TEXT_ONLY_OFFLOAD_LIMIT) { i?.warn(`attachment ${c}: dropping image because text-only offload limit ${TEXT_ONLY_OFFLOAD_LIMIT} was reached`); f += "\n[image attachment omitted: text-only attachment limit reached]"; continue; } if (!(x || !b || n?.imageStorage !== "inline" && _ > 2e6)) { const n = { type: "image", data: t, mimeType: v }; inlineImageMetadata.set(n, { ...s.fileName ? { fileName: s.fileName } : {}, sourceIndex: e, width: g.width, height: g.height }); l.push(n); u.push("inline"); continue; } const S = g.buffer; const C = S ? Buffer.from(S.buffer, S.byteOffset, S.byteLength) : Buffer.from(t, "base64"); let w; let T; try { const e = ensureExtension(c, v); w = await saveMediaBuffer(C, v, "inbound", r, e, void 0, { assertCommitAllowed: n?.assertCurrent }); T = `media://inbound/${w.id}`; } catch (e) { if (e instanceof SessionMutationAuthorizationChangedError) throw e; n?.assertCurrent?.(); throw new MediaOffloadError(`[Gateway Error] Failed to save intercepted media to disk: ${formatErrorMessage(e)}`, { cause: e }); } m.push(w.id); f += `\n[media attached: ${T}]`; i?.info?.(x ? `[Gateway] Offloaded image for text-only model. Saved: ${T}` : `[Gateway] Offloaded attachment (${v}). Saved: ${T}`); const E = { mediaRef: T, id: w.id, path: w.path, kind: kindFromMime(v) ?? "unknown", mimeType: v, label: c, sizeBytes: _, sourceIndex: e, ...s.origin === "paste" || s.origin === "file" ? { origin: s.origin } : {} }; for (const e of [ "durationMs", "width", "height" ]) { const t = b && e !== "durationMs" ? g[e] : s[e]; if (typeof t === "number" && Number.isFinite(t) && t >= 0) E[e] = t; } d.push(E); if (b) { u.push("offloaded"); if (x) p++; } } await enrichOffloadedMediaMetadata(d); n?.assertCurrent?.(); } catch (e) { if (m.length > 0) await Promise.allSettled(m.map((e) => deleteMediaBuffer(e, "inbound"))); if (e instanceof WorkerTaskError && e !== n?.signal?.reason) { if (e.code === "failed") throw new Error(e.message, { cause: e }); throw new MediaOffloadError(`[Gateway Error] Failed to prepare attachments: ${formatErrorMessage(e)}`, { cause: e }); } throw e; } return { message: f !== e ? f.trimEnd() : e, images: l, imageOrder: u, media: d.map((e) => projectOffloadedMediaFact(e, false)), offloadedRefs: d }; } //#endregion export { parseMessageWithAttachments as a, logAttachmentFailure as i, MediaOffloadError as n, persistInboundImagesForTranscript as o, discardPreparedInboundMedia as r, stripImageMediaMarkers as s, INLINE_IMAGE_DURABLE_OMISSION_MARKER as t };