UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

136 lines (135 loc) • 6.23 kB
import { IMAGE_ADMISSION } from "./image-admission.js"; import { describeRejectedValue } from "./tool-search-setting.js"; const toJpeg = (ops, quality) => ops.flatten({ background: "#ffffff" }).jpeg({ quality }); async function toByteTarget(sharp, input, target) { const jpeg = (quality) => toJpeg(sharp(input.buf), quality).toBuffer(); const asJpeg = (buf) => ({ buf, mimeType: "image/jpeg", ...(input.dimensions !== undefined ? { dimensions: input.dimensions } : {}) }); let smallest = input; let hi = 90; if (input.mimeType !== "image/jpeg") { const q90 = await jpeg(90); if (q90.length < smallest.buf.length) smallest = asJpeg(q90); if (q90.length <= target) return asJpeg(q90); hi = 89; } let lo = 1; let best; for (let probe = 0; probe < 5; probe++) { const quality = Math.floor((lo + hi) / 2); const buf = await jpeg(quality); if (buf.length < smallest.buf.length) smallest = asJpeg(buf); if (buf.length <= target) { best = buf; lo = quality + 1; } else hi = quality - 1; if (lo > hi) break; } return best !== undefined ? asJpeg(best) : smallest; } export function createImageDownsampler(sharp) { const BOX = { fit: "inside", withoutEnlargement: true }; const { frameEdge, rawBytes, targetBytes } = IMAGE_ADMISSION.soft; const upright = async (input) => ((await sharp(input).metadata()).orientation ?? 1) >= 2 ? sharp(input).rotate().toBuffer() : input; const ladder = async (input, mimeType) => { const meta = await sharp(input).metadata(); const fmt = meta.format === "jpg" ? "jpeg" : meta.format; const passMime = fmt ? `image/${fmt}` : mimeType; const originalSize = input.length; if (!meta.width || !meta.height) { if (originalSize > rawBytes) return { buf: await toJpeg(sharp(input), 80).toBuffer(), mimeType: "image/jpeg" }; return { buf: input, mimeType: passMime }; } const originalWidth = meta.width; const originalHeight = meta.height; let width = originalWidth; let height = originalHeight; const dims = (dw, dh) => ({ originalWidth, originalHeight, displayWidth: dw, displayHeight: dh }); if (originalSize <= rawBytes && width <= frameEdge && height <= frameEdge) return { buf: input, mimeType: passMime, dimensions: dims(width, height) }; const needsDimensionResize = width > frameEdge || height > frameEdge; const isPng = fmt === "png"; if (!needsDimensionResize) { if (isPng) { const png = await sharp(input).png({ compressionLevel: 9, palette: true }).toBuffer(); if (png.length <= rawBytes) return { buf: png, mimeType: "image/png", dimensions: dims(width, height) }; } for (const quality of [80, 60, 40, 20]) { const buf = await toJpeg(sharp(input), quality).toBuffer(); if (buf.length <= rawBytes) return { buf, mimeType: "image/jpeg", dimensions: dims(width, height) }; } } if (width > frameEdge) { height = Math.round((height * frameEdge) / width); width = frameEdge; } if (height > frameEdge) { width = Math.round((width * frameEdge) / height); height = frameEdge; } const resized = await sharp(input).resize(width, height, BOX).toBuffer(); if (resized.length <= rawBytes) return { buf: resized, mimeType: passMime, dimensions: dims(width, height) }; if (isPng) { const png = await sharp(input).resize(width, height, BOX).png({ compressionLevel: 9, palette: true }).toBuffer(); if (png.length <= rawBytes) return { buf: png, mimeType: "image/png", dimensions: dims(width, height) }; } for (const quality of [80, 60, 40, 20]) { const buf = await toJpeg(sharp(input).resize(width, height, BOX), quality).toBuffer(); if (buf.length <= rawBytes) return { buf, mimeType: "image/jpeg", dimensions: dims(width, height) }; } const smallerWidth = Math.min(width, 1000); const smallerHeight = Math.round((height * smallerWidth) / Math.max(width, 1)); const last = await toJpeg(sharp(input).resize(smallerWidth, smallerHeight, BOX), 20).toBuffer(); return { buf: last, mimeType: "image/jpeg", dimensions: dims(smallerWidth, smallerHeight) }; }; return async (input, mimeType) => { if (input.length === 0) return undefined; let framed; try { framed = await ladder(await upright(input), mimeType); } catch { return undefined; } const out = framed.buf.length > targetBytes ? await toByteTarget(sharp, framed, targetBytes).catch(() => framed) : framed; return { base64: out.buf.toString("base64"), mimeType: out.mimeType, ...(out.dimensions !== undefined ? { dimensions: out.dimensions } : {}) }; }; } const SHARP_LIMIT_INPUT_PIXELS = 100_000_000; export async function sharpImageDownsampler() { try { const mod = (await import("sharp")); const real = (mod.default ?? mod); return createImageDownsampler((input) => real(input, { limitInputPixels: SHARP_LIMIT_INPUT_PIXELS })); } catch { return undefined; } } export function checkedImageProcessorSeat(value, seat) { if (value === undefined || value === false || typeof value === "function") return; const e = new Error(`${seat} ${describeRejectedValue(value)} is not an image processor — expected an ImageDownsampler function, or false for none, or omit it to detect sharp`); e.code = "config.invalid_argument"; throw e; } let detected; export async function resolveImageProcessor(seat) { if (typeof seat === "function") return seat; if (seat === false) return "none"; return (await (detected ??= sharpImageDownsampler())) ?? "none"; }