UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

86 lines (85 loc) • 3.66 kB
import { hopRefusal } from "../host-floor.js"; import { callerText } from "../caller-text.js"; import { firstUnprocessedOverTarget, IMAGE_ADMISSION, sniffImageMime } from "../image-admission.js"; import { resolveImageProcessor } from "../image-downsample.js"; import { admitInlineImage } from "./inline-image.js"; export function defaultImageUrlGuard(raw, floor) { let u; try { u = new URL(raw); } catch { throw new Error(`invalid image url: ${callerText(raw)}`); } if (u.protocol !== "https:") { throw new Error(`image url must be https (got ${callerText(u.protocol)})`); } const refused = hopRefusal(u, floor, true); if (refused !== undefined) throw new Error(`image url not fetched — ${refused}`); } const IMAGE_FETCH_TIMEOUT_MS = 30_000; const IMAGE_MAX_BYTES = IMAGE_ADMISSION.hard.urlBytes; async function readImageBodyCapped(res) { const reader = res.body?.getReader(); if (!reader) { const ab = await res.arrayBuffer(); if (ab.byteLength > IMAGE_MAX_BYTES) throw new Error(`image too large (> ${IMAGE_MAX_BYTES} cap)`); return Buffer.from(ab); } const chunks = []; let total = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; if (!value) continue; total += value.byteLength; if (total > IMAGE_MAX_BYTES) { await reader.cancel().catch(() => undefined); throw new Error(`image exceeds ${IMAGE_MAX_BYTES}-byte cap (chunked/unbounded response)`); } chunks.push(value); } return Buffer.concat(chunks.map((c) => Buffer.from(c))); } async function fetchImageCapped(url) { const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(IMAGE_FETCH_TIMEOUT_MS) }); if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) { throw new Error(`image url redirected (status ${res.status}) — refusing to follow (the SSRF guard only validates the initial host)`); } if (!res.ok) { throw new Error(`failed to fetch image: HTTP ${res.status}`); } const declared = Number(res.headers.get("content-length")); if (Number.isFinite(declared) && declared > IMAGE_MAX_BYTES) { throw new Error(`image too large: ${declared} bytes > ${IMAGE_MAX_BYTES} cap`); } const headerMimeType = res.headers.get("content-type")?.split(";")[0]; const buf = await readImageBodyCapped(res); const sniffed = sniffImageMime(buf); if (!sniffed) { const claim = headerMimeType ? ` (server claimed Content-Type: ${headerMimeType})` : " and the response carried no Content-Type header"; throw new Error(`image url content is not a recognized image format (png/jpeg/gif/webp)${claim}: ${url}`); } return { buf, mimeType: sniffed }; } export async function toImageContent(img, floor, processor) { if ("url" in img) { const url = img.url; defaultImageUrlGuard(url, floor); const { buf, mimeType } = await fetchImageCapped(url); return admitInlineImage({ data: buf.toString("base64"), mimeType }, processor, "the image fetched from its url"); } return admitInlineImage(img, processor); } export async function toImageContents(images, floor, seat, unprocessed) { const processor = await resolveImageProcessor(seat); const blocks = await Promise.all(images.map((img) => toImageContent(img, floor, processor))); const over = firstUnprocessedOverTarget(blocks, processor); if (over !== undefined) unprocessed(over); return blocks; }