UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

257 lines (256 loc) • 8.46 kB
import { d as normalizeMimeType, u as mimeTypeFromFilePath } from "./mime-D2wVBzpa.mjs"; import { i as shouldLogVerbose, r as logVerbose } from "./globals-CgepmiqE.mjs"; import { t as classifyMediaReferenceSource } from "./media-reference-DDon-yG0.mjs"; import { a as resolveAttachmentKind } from "./attachments.normalize-_9E9xPsg.mjs"; import { t as attachmentClassFromMime } from "./attachment-classify-DFSZjMac.mjs"; import { a as renderFileContextBlock, i as sanitizeMimeType, n as renderFileAttachmentOutcome, r as resolveFileExtractionOutcome, t as isSkippedFileOutcome } from "./file-attachment-outcomes-BbO-VUyp.mjs"; import { i as extractFileContentFromBuffer } from "./input-files-DKoRlBjP.mjs"; import { t as resolveFileExtractionLimits } from "./file-extraction-limits-Dz8UGxWS.mjs"; import { n as createScopedMediaAttachmentCache, r as normalizeMediaAttachments } from "./runner.attachments-Dzrzdim3.mjs"; //#region src/media-understanding/media-attachment-outcomes.ts const MAX_SKIPPED_FILE_MARKERS = 5; function renderSkippedFileOverflowSummary(e) { return `[${e} more attachment${e === 1 ? "" : "s"} skipped]`; } function renderMediaAttachmentDisposition(e, t) { const n = `${e[0]?.toUpperCase()}${e.slice(1)}`; switch (t.kind) { case "handled": case "handed-to-native-vision": return null; case "not-selected": return `[${n} attachment not processed: attachment limit reached]`; case "capability-disabled": return `[${n} attachment not analyzed: ${e} understanding is disabled]`; case "no-model": return `[${n} attachment not analyzed: no ${e}-understanding model is configured]`; case "scope-denied": return `[${n} attachment not analyzed in this chat]`; case "failed": return `[${n} attachment could not be analyzed]`; default: return t; } } function applyAttachmentMarkerBudget(e) { const t = []; let n = 0; let r = 0; for (const i of e) { if (i.consumesMarkerBudget && n >= MAX_SKIPPED_FILE_MARKERS) { r += 1; continue; } n += Number(i.consumesMarkerBudget); t.push(i.text); } return r > 0 ? [...t, renderSkippedFileOverflowSummary(r)] : t; } //#endregion //#region src/media-understanding/file-context.ts function attachmentUrlDisplayName(e) { try { return new URL(e).pathname.split("/").findLast((e) => e.length > 0) || void 0; } catch { return; } } async function extractFileContext(e) { const { attachments: t, cache: n, cfg: r, limits: i, skipAttachmentIndexes: a } = e; async function classifyFileAttachment(t) { const o = e.assertCurrent; o?.(); const s = t.path ?? (t.url ? attachmentUrlDisplayName(t.url) : void 0); const c = t.fileName ?? s; if (a?.has(t.index)) return { outcome: { kind: "claimed-elsewhere" } }; const l = mimeTypeFromFilePath(s); const u = attachmentClassFromMime(l) === "text" ? l : void 0; const d = u ? "document" : resolveAttachmentKind(t); if (!u && (d === "image" || d === "video" || d === "audio")) return { outcome: { kind: "claimed-elsewhere" } }; if (!i.allowUrl && t.url && !t.path && !classifyMediaReferenceSource(t.url).isMediaStoreUrl) { if (shouldLogVerbose()) logVerbose(`media: file attachment skipped (url disabled) index=${t.index}`); return { outcome: { kind: "url-sources-disabled" }, filename: c }; } let f; try { f = await n.getBuffer({ attachmentIndex: t.index, maxBytes: i.maxBytes, timeoutMs: i.timeoutMs, signal: e.signal }); } catch (e) { if (shouldLogVerbose()) logVerbose(`media: file attachment skipped (buffer): ${String(e)}`); return { outcome: { kind: "read-failure" }, filename: c }; } o?.(); const p = t.fileName ?? f.fileName; const m = f.classification; const h = sanitizeMimeType(m.mime); const g = sanitizeMimeType(normalizeMimeType(t.mime)) ?? h; const _ = f.localPath; if (m.class !== "text" && !(m.class === "document" && m.mime === "application/pdf")) { if (i.allowedMimesConfigured && !(h && i.allowedMimes.has(h))) return { outcome: { kind: "policy-rejected", mime: h ?? g }, filename: p, mimeType: h ?? g }; return { outcome: { kind: "unsupported-format", mime: g, ..._ ? { localPath: _ } : {} }, filename: p, mimeType: g }; } if (m.class === "text" && t.mime && normalizeMimeType(t.mime) !== m.mime) logVerbose(`media: MIME override from "${t.mime}" to "${m.mime}" for index=${t.index}`); if (!h) { if (shouldLogVerbose()) logVerbose(`media: file attachment skipped (unknown mime) index=${t.index}`); return { outcome: { kind: "unsupported-format" }, filename: p }; } const v = new Set(i.allowedMimes); if (!i.allowedMimesConfigured && m.class === "text") v.add(h); if (!v.has(h)) { if (shouldLogVerbose()) logVerbose(`media: file attachment skipped (unsupported mime ${h}) index=${t.index}`); return { outcome: i.allowedMimesConfigured ? { kind: "policy-rejected", mime: h } : { kind: "unsupported-format", mime: h, ..._ ? { localPath: _ } : {} }, filename: p, mimeType: h }; } let y; try { const { allowedMimesConfigured: n, ...a } = i; y = await extractFileContentFromBuffer({ buffer: h === "application/pdf" ? Buffer.from(f.buffer) : f.buffer, filename: f.fileName, limits: { ...a, allowedMimes: v }, config: r, classification: m, mimeType: t.mime, signal: e.signal }); } catch (e) { if (shouldLogVerbose()) logVerbose(`media: file attachment skipped (extract): ${String(e)}`); return { outcome: { kind: "read-failure" }, filename: p, mimeType: h }; } o?.(); return { outcome: resolveFileExtractionOutcome({ text: y?.text?.trim(), images: y?.images, metadata: y?.metadata }), filename: p, mimeType: h }; } const o = []; const s = []; const c = []; for (const r of t) { const { outcome: t, filename: i, mimeType: a } = await classifyFileAttachment(r).finally(() => n.releaseBuffer(r.index)); e.assertCurrent?.(); if (t.kind === "extracted" || t.kind === "rendered-to-images") s.push(...t.images.map((e) => ({ ...e, attachmentIndex: r.index }))); const l = renderFileAttachmentOutcome(t, { selfServeLocalPath: e.selfServePathsEnabled ? void 0 : false }); if (l === null) continue; const renderBlock = (e) => renderFileContextBlock({ filename: i, fallbackName: `file-${r.index + 1}`, mimeType: a, content: e }); const u = renderBlock(l); o.push({ text: u, consumesMarkerBudget: isSkippedFileOutcome(t) }); if (t.kind === "unsupported-format" && t.localPath) { const e = renderFileAttachmentOutcome(t, { selfServeLocalPath: false }); const n = renderFileAttachmentOutcome(t); if (e && n) c.push({ attachmentIndex: r.index, fallback: renderBlock(e), render: (e) => { const n = renderFileAttachmentOutcome(t, e ? { selfServeLocalPath: e } : void 0); return n ? renderBlock(n) : void 0; } }); } } return { blocks: o, images: s, localPathSelfServeUpgrades: c }; } /** Prepares retained document context under the same admission policy as live attachments. */ async function prepareFileContextFromMedia(e) { return await renderInboundDocumentContext({ ctx: { media: [...e.media], Provider: e.channelId, AccountId: e.accountId }, cfg: e.config, workspaceDir: e.workspaceDir, maxChars: e.maxChars, assertCurrent: e.assertCurrent, signal: e.signal }); } /** Keep prompt expansion separate from inbound state so rejected steers can dispatch normally. */ async function renderInboundDocumentContext(e) { e.assertCurrent?.(); const { ctx: t, cfg: n } = e; const r = resolveFileExtractionLimits(n); const i = normalizeMediaAttachments(t); const a = createScopedMediaAttachmentCache(i, e); try { const t = await extractFileContext({ attachments: i, cache: a, cfg: n, limits: e.maxChars === void 0 ? r : { ...r, maxChars: Math.min(r.maxChars, e.maxChars) }, selfServePathsEnabled: false, assertCurrent: e.assertCurrent, signal: e.signal }); e.assertCurrent?.(); return { text: applyAttachmentMarkerBudget(t.blocks).join("\n\n"), images: t.images }; } finally { await a.cleanup(); } } //#endregion export { renderMediaAttachmentDisposition as a, applyAttachmentMarkerBudget as i, prepareFileContextFromMedia as n, renderInboundDocumentContext as r, extractFileContext as t };