UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

327 lines (326 loc) • 16.1 kB
import { createHash } from "node:crypto"; import { keepBytesWith, mediaTypeEcho } from "./tool-result-bytes.js"; import { readMember } from "./thrown-value.js"; import { describeRejectedValue } from "./tool-search-setting.js"; export const PDF_TARGET_RAW_SIZE = 20 * 1024 * 1024; const spells = (b, at, text) => { if (b.length < at + text.length) return false; for (let i = 0; i < text.length; i++) if (b[at + i] !== text.charCodeAt(i)) return false; return true; }; const u32be = (b, at) => ((b[at] << 24) >>> 0) + (b[at + 1] << 16) + (b[at + 2] << 8) + b[at + 3]; const u16le = (b, at) => b[at] + (b[at + 1] << 8); const u16be = (b, at) => (b[at] << 8) + b[at + 1]; const u24le = (b, at) => b[at] + (b[at + 1] << 8) + (b[at + 2] << 16); const u32le = (b, at) => (u24le(b, at) + (b[at + 3] << 24)) >>> 0; const IMAGE_HEADER_CHECKS = Object.freeze({ "image/png": (b) => b.length >= 24 && spells(b, 0, "\x89PNG\r\n\x1a\n") && u32be(b, 8) === 13 && spells(b, 12, "IHDR") && u32be(b, 16) > 0 && u32be(b, 20) > 0, "image/jpeg": (b) => b.length >= 4 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff && b[3] >= 0xc0, "image/gif": (b) => b.length >= 13 && (spells(b, 0, "GIF87a") || spells(b, 0, "GIF89a")) && u16le(b, 6) > 0 && u16le(b, 8) > 0, "image/webp": (b) => b.length >= 16 && spells(b, 0, "RIFF") && spells(b, 8, "WEBP") && (spells(b, 12, "VP8 ") || spells(b, 12, "VP8L") || spells(b, 12, "VP8X")), }); const MiB = 1024 * 1024; const IMAGE_BASE64_CHARS = 5 * MiB; const IMAGE_BASE64_RAW_BYTES = (IMAGE_BASE64_CHARS * 3) / 4; export const IMAGE_ADMISSION = Object.freeze({ hard: Object.freeze({ formats: IMAGE_HEADER_CHECKS, readBytes: Object.freeze({ withoutProcessor: IMAGE_BASE64_RAW_BYTES, withProcessor: 64 * MiB }), urlBytes: 20 * MiB, rejectEdge: 2000, imageBase64Chars: IMAGE_BASE64_CHARS, }), soft: Object.freeze({ frameEdge: 2000, rawBytes: IMAGE_BASE64_RAW_BYTES, targetBytes: 512_000 }), request: Object.freeze({ maxItems: 100, largeWindow: Object.freeze({ fromContextWindow: 1_000_000, maxItems: 600 }), margin: 20, budgetBase64Chars: 40 * MiB, hysteresisBase64Chars: 10 * MiB, refusalRungs: Object.freeze([510, 255, 127]), }), }); const smallestRequestMediaBudget = () => 2 * IMAGE_ADMISSION.request.hysteresisBase64Chars; export function requestMediaBudget(knob) { const budget = knob ?? IMAGE_ADMISSION.request.budgetBase64Chars; return budget === 0 ? Infinity : budget; } export function requestMediaLimits(model, knob, learned) { const { maxItems, largeWindow, margin, hysteresisBase64Chars } = IMAGE_ADMISSION.request; const window = model.contextWindow; const declared = model.mediaItemLimit; const items = Math.min(typeof declared === "number" ? declared : typeof window === "number" && window >= largeWindow.fromContextWindow ? largeWindow.maxItems : maxItems, learned ?? Infinity); return { maxItems: items, margin: Math.min(margin, Math.floor(items / 2)), budgetBase64Chars: requestMediaBudget(knob), hysteresisBase64Chars }; } export function checkedRequestMediaBudget(value, seat) { if (value === undefined || value === 0 || value === Infinity || (Number.isInteger(value) && value >= smallestRequestMediaBudget())) return; const e = new Error(`${seat} ${describeRejectedValue(value)} is not a request media budget — expected a whole number of base64 characters of at least ${smallestRequestMediaBudget()} (twice the ${IMAGE_ADMISSION.request.hysteresisBase64Chars}-character margin a cut leaves under the budget), 0 or Infinity for no budget, or omit it for the default ${IMAGE_ADMISSION.request.budgetBase64Chars}`); e.code = "config.invalid_argument"; throw e; } export function imageMagicMatches(bytes, mimeType) { const admitted = admittedImageMime(mimeType); return admitted !== undefined && IMAGE_ADMISSION.hard.formats[admitted](bytes); } function jpegFrameAt(b) { if (b.length < 4 || b[0] !== 0xff || b[1] !== 0xd8) return undefined; let at = 2; while (at + 9 < b.length) { if (b[at] !== 0xff) { at++; continue; } const marker = b[at + 1]; if (marker === 0xff) { at++; continue; } if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) return at; if ((marker >= 0xd0 && marker <= 0xd9) || marker === 0x01) { at += 2; continue; } const length = u16be(b, at + 2); if (length < 2) return undefined; at += 2 + length; } return undefined; } export function readImageHeaderDimensions(b) { if (b.length < 10) return undefined; if (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) return b.length >= 24 ? { width: u32be(b, 16), height: u32be(b, 20) } : undefined; if (b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46) return { width: u16le(b, 6), height: u16le(b, 8) }; const frame = jpegFrameAt(b); if (frame !== undefined) return { height: u16be(b, frame + 5), width: u16be(b, frame + 7) }; if (b[0] === 0xff && b[1] === 0xd8) return undefined; if (b.length >= 30 && spells(b, 0, "RIFF") && spells(b, 8, "WEBP")) { if (spells(b, 12, "VP8 ")) return { width: u16le(b, 26) & 0x3fff, height: u16le(b, 28) & 0x3fff }; if (spells(b, 12, "VP8L")) { const bits = u32le(b, 21); return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 }; } if (spells(b, 12, "VP8X")) return { width: u24le(b, 24) + 1, height: u24le(b, 27) + 1 }; } return undefined; } export function pdfMagicMatches(bytes) { return bytes.length >= 5 && bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46 && bytes[4] === 0x2d; } export const ADMITTED_IMAGE_MIME_TYPES = Object.freeze(["image/png", "image/jpeg", "image/gif", "image/webp"]); function mediaTypeEssence(mime) { const semicolon = mime.indexOf(";"); return (semicolon < 0 ? mime : mime.slice(0, semicolon)).replace(/[A-Z]+/g, (letters) => letters.toLowerCase()); } function memberOfSet(set, mime) { if (typeof mime !== "string") return undefined; const essence = mediaTypeEssence(mime); return set.find((member) => member === essence); } export function admittedImageMime(mime) { return memberOfSet(ADMITTED_IMAGE_MIME_TYPES, mime); } export function imageReadCap(processor) { const { readBytes } = IMAGE_ADMISSION.hard; return processor === "none" ? readBytes.withoutProcessor : readBytes.withProcessor; } export function unprocessedSizeClause(a) { return a.reason === "dimensions_unreadable" ? "it could not be processed and its header states no pixel size — convert it to PNG, JPEG, GIF, or WebP" : `at ${a.width}x${a.height}px it is over the ${a.limit}x${a.limit}px limit and could not be shrunk — resize it to fit within ${a.limit}x${a.limit}px`; } export async function admitImageBytes(bytes, claimedMime, processor) { const rawBytes = bytes.byteLength; const mime = admittedImageMime(claimedMime); if (mime === undefined) return { ok: false, reason: "mime_unsupported", rawBytes }; const cap = imageReadCap(processor); if (rawBytes > cap) return { ok: false, reason: "raw_too_large", rawBytes, cap }; if (!imageMagicMatches(bytes, mime)) return { ok: false, reason: "magic_mismatch", rawBytes }; let shipped; const memory = processor !== "none" ? producedBy(processor) : undefined; const inputDigest = memory !== undefined ? digestOf(bytes) : undefined; const known = memory !== undefined && inputDigest !== undefined && memory.has(inputDigest); if (processor !== "none" && !known) { const out = await Promise.resolve() .then(() => processor(Buffer.from(bytes), mime)) .catch(() => undefined); const outBytes = out !== undefined ? Buffer.from(out.base64, "base64") : undefined; const outMime = outBytes !== undefined ? sniffImageMime(outBytes) : undefined; if (out !== undefined && outBytes !== undefined && outMime !== undefined) shipped = { bytes: outBytes, base64: out.base64, mimeType: outMime, ...(out.dimensions !== undefined ? { dimensions: out.dimensions } : {}) }; } const fromProcessor = shipped !== undefined; shipped ??= { bytes, base64: Buffer.from(bytes).toString("base64"), mimeType: mime }; const header = readImageHeaderDimensions(shipped.bytes); if (header === undefined) return { ok: false, reason: "dimensions_unreadable", rawBytes }; const limit = IMAGE_ADMISSION.hard.rejectEdge; if (header.width > limit || header.height > limit) return { ok: false, reason: "dimensions_too_large", rawBytes, width: header.width, height: header.height, limit }; const { base64, mimeType, dimensions } = shipped; if (base64.length > IMAGE_ADMISSION.hard.imageBase64Chars) return { ok: false, reason: "base64_too_large", rawBytes, base64 }; const resized = dimensions !== undefined && dimensions.displayWidth > 0 && dimensions.displayHeight > 0 && (dimensions.originalWidth !== dimensions.displayWidth || dimensions.originalHeight !== dimensions.displayHeight); if (memory !== undefined && (fromProcessor || known)) memory.add(fromProcessor ? digestOf(shipped.bytes) : inputDigest); return { ok: true, block: { type: "image", data: base64, mimeType }, originalSize: rawBytes, ...(dimensions !== undefined ? { dimensions } : {}), resized }; } const PRODUCED_KEPT = 256; const produced = new WeakMap(); function producedBy(processor) { let kept = produced.get(processor); if (kept === undefined) produced.set(processor, (kept = new Set())); const set = kept; return { has: (digest) => set.has(digest), add: (digest) => { set.delete(digest); set.add(digest); if (set.size > PRODUCED_KEPT) set.delete(set.values().next().value); }, }; } const digestOf = (bytes) => createHash("sha256").update(bytes).digest("base64"); export function sniffImageMime(bytes) { return ADMITTED_IMAGE_MIME_TYPES.find((mime) => imageMagicMatches(bytes, mime)); } export const ADMITTED_DOCUMENT_MIME_TYPES = Object.freeze(["application/pdf"]); export function admitDocumentBytes(bytes, claimedMime) { const rawBytes = bytes.byteLength; const mime = memberOfSet(ADMITTED_DOCUMENT_MIME_TYPES, claimedMime); if (mime === undefined) return { ok: false, reason: "mime_unsupported", rawBytes }; if (rawBytes > PDF_TARGET_RAW_SIZE) return { ok: false, reason: "raw_too_large", rawBytes, cap: PDF_TARGET_RAW_SIZE }; if (!pdfMagicMatches(bytes)) return { ok: false, reason: "magic_mismatch", rawBytes }; return { ok: true, block: { type: "document", data: Buffer.from(bytes).toString("base64"), mimeType: mime }, originalSize: rawBytes }; } const ADMITTED_FOR = { image: ADMITTED_IMAGE_MIME_TYPES, document: ADMITTED_DOCUMENT_MIME_TYPES }; export function mediaBlockTypeOf(mime) { return Object.keys(ADMITTED_FOR).find((type) => memberOfSet(ADMITTED_FOR[type], mime) !== undefined); } const KEPT_FOR_SIZE = new Set(["raw_too_large", "dimensions_too_large", "base64_too_large"]); const REFUSAL_CLAUSE = { undecodable: () => "it carried no base64 payload", mime_unsupported: (r) => `${r.mimeType ?? "its media type"} is not a ${r.type} type the model accepts (${ADMITTED_FOR[r.type].join(", ")})`, raw_too_large: (r) => `its ${r.bytes} bytes exceed the ${r.limit}-byte cap`, magic_mismatch: (r) => `its ${r.bytes} bytes do not open with a valid ${r.mimeType ?? `${r.type}`} header`, dimensions_unreadable: () => unprocessedSizeClause({ reason: "dimensions_unreadable" }), dimensions_too_large: (r) => unprocessedSizeClause({ reason: "dimensions_too_large", width: r.width, height: r.height, limit: r.limit }), base64_too_large: (r) => `its base64 encoding exceeds the ${r.limit}-character provider limit (${r.bytes} bytes)`, }; const placeholderOf = (toolName, r, keptClause) => ({ type: "text", text: `[${r.type} from the ${JSON.stringify(toolName)} tool not shown: ${REFUSAL_CLAUSE[r.reason](r)} (media admission: ${r.reason})${keptClause !== undefined ? `; ${keptClause}` : ""}]`, }); const MEDIA_BLOCK_TYPES = new Set(["image", "document"]); export function claimedMediaType(block) { const type = readMember(block, "type"); return MEDIA_BLOCK_TYPES.has(type) ? type : undefined; } const claimsMedia = (block) => claimedMediaType(block) !== undefined; async function admitBlock(block, processor, keep) { const type = claimedMediaType(block); if (type === undefined) return { block }; const data = readMember(block, "data"); const mime = readMember(block, "mimeType"); const echo = mediaTypeEcho(mime); const refusal = (reason, bytes, limit, size) => ({ refusal: { type, reason, bytes, ...(limit !== undefined ? { limit } : {}), ...(size ?? {}), ...(echo !== undefined ? { mimeType: echo } : {}) }, }); if (typeof data !== "string") return refusal("undecodable", 0); let a; let bytes; try { bytes = Buffer.from(data, "base64"); const claimed = typeof mime === "string" ? mime : ""; a = type === "image" ? await admitImageBytes(bytes, claimed, processor) : admitDocumentBytes(bytes, claimed); } catch { return refusal("undecodable", 0); } if (a.ok) return { block: a.block }; const refused = a.reason === "raw_too_large" ? refusal(a.reason, a.rawBytes, a.cap) : a.reason === "dimensions_too_large" ? refusal(a.reason, a.rawBytes, a.limit, { width: a.width, height: a.height }) : a.reason === "base64_too_large" ? refusal(a.reason, a.rawBytes, IMAGE_ADMISSION.hard.imageBase64Chars) : refusal(a.reason, a.rawBytes); if (!KEPT_FOR_SIZE.has(refused.refusal.reason)) return refused; const { kept, clause } = await keepBytesWith(keep, bytes, mime); const where = "ref" in kept ? { ref: kept.ref } : { notKept: kept.notKept, ...("saveError" in kept && kept.saveError !== undefined ? { saveError: kept.saveError } : {}) }; return { refusal: { ...refused.refusal, ...where }, keptClause: clause }; } export function firstUnprocessedOverTarget(blocks, processor) { if (processor !== "none") return undefined; for (const b of blocks) { if (claimedMediaType(b) !== "image") continue; const data = readMember(b, "data"); if (typeof data !== "string") continue; const bytes = Buffer.byteLength(data, "base64"); if (bytes > IMAGE_ADMISSION.soft.targetBytes) return bytes; } return undefined; } export function toolResultMediaBlocks(content) { try { if (!Array.isArray(content)) return undefined; const blocks = Array.from(content); return blocks.some(claimsMedia) ? blocks : undefined; } catch { return undefined; } } export async function admitToolResultMediaBlocks(blocks, toolName, processor, keep) { const refused = []; const out = []; for (const b of blocks) { const r = await admitBlock(b, processor, keep); if ("block" in r) { out.push(r.block); } else { refused.push(r.refusal); out.push(placeholderOf(toolName, r.refusal, r.keptClause)); } } return { content: out, refused }; } export function admitToolResultMedia(content, toolName, processor, keep) { const blocks = toolResultMediaBlocks(content); return blocks === undefined ? undefined : admitToolResultMediaBlocks(blocks, toolName, processor, keep); }