UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

108 lines (107 loc) • 5.38 kB
import { isTextBlock, renderContentBlock } from "../../internal/llm.js"; import { requestMediaBudget } from "../image-admission.js"; import { isMediaBlock, mediaBlockDescriptor, omittedMediaDescriptor } from "../media-byte-cap.js"; import { cardSkeletonMembers, engineCardTypes } from "../tool-registry.js"; import { readMember } from "../thrown-value.js"; import { cardOnFrame, MAX_TOOL_END_OUTPUT_CHARS } from "../tool-card-bound.js"; import { codePointLength, sliceHeadSafe } from "../surrogate-safe-slice.js"; const marker = (n) => `…[+${n} chars truncated]`; const blockSize = (b, count) => isTextBlock(b) ? count(b.text) + count(JSON.stringify({ ...b, type: undefined, text: undefined }) ?? "{}") - 2 : isMediaBlock(b) ? b.data.length : count(JSON.stringify(b) ?? ""); export const toolOutputBlockChars = (b) => blockSize(b, (s) => s.length); const boundTextLane = (blocks, lane) => { const sized = lane.map((i) => ({ i, size: toolOutputBlockChars(blocks[i]) })); const forms = new Map(); let used = 0; for (const [k, { i, size }] of sized.entries()) { const sep = k > 0 ? 1 : 0; if (used + sep + size <= MAX_TOOL_END_OUTPUT_CHARS) { used += sep + size; forms.set(i, blocks[i]); continue; } const shown = sliceHeadSafe(renderContentBlock(blocks[i]), Math.max(0, MAX_TOOL_END_OUTPUT_CHARS - used - sep)); const chars = sized.map((s) => blockSize(blocks[s.i], codePointLength)), sum = (xs) => xs.reduce((n, x) => n + x, 0); const stream = sum(chars) + sized.length - 1; const before = sum(chars.slice(0, k)) + k - (used + sep > MAX_TOOL_END_OUTPUT_CHARS ? sep : 0); forms.set(i, { type: "text", text: shown + marker(stream - before - (isTextBlock(blocks[i]) ? codePointLength(shown) : 0)) }); return { forms, cut: true }; } return { forms, cut: false }; }; const wireBytes = (b) => Buffer.byteLength(JSON.stringify(b)) + 1; const SUMMARY_RESERVE = wireBytes({ type: "omitted", blocks: Number.MAX_SAFE_INTEGER, bytes: Number.MAX_SAFE_INTEGER, truncated: true }) + 2; const fitMedia = (media, budget) => { let used = 0; let degraded = false; const blocks = []; for (const [i, m] of media.entries()) { const cost = used + m.data.length >= budget ? Infinity : wireBytes(m); const kept = used + cost <= budget; const out = kept ? m : mediaBlockDescriptor(m); const outCost = kept ? cost : wireBytes(out); degraded ||= !kept; if (used + outCost > budget) { blocks.push(omittedMediaDescriptor(media.slice(i))); break; } used += outCost; blocks.push(out); } return { blocks, degraded }; }; const project = (content, mediaBudgetBase64Chars) => { if (!Array.isArray(content)) { const s = typeof content === "string" ? content : (JSON.stringify(content) ?? ""); if (s.length <= MAX_TOOL_END_OUTPUT_CHARS) return { output: content, truncated: false }; const shown = sliceHeadSafe(s, MAX_TOOL_END_OUTPUT_CHARS); return { output: shown + marker(codePointLength(s.slice(shown.length))), truncated: true, totalChars: s.length }; } const media = content.map(isMediaBlock); const text = boundTextLane(content, content.flatMap((_, i) => (media[i] ? [] : [i]))); const limit = requestMediaBudget(mediaBudgetBase64Chars); const textBytes = [...text.forms.values()].reduce((n, f) => n + wireBytes(f), 0); const fit = fitMedia(content.filter((_, i) => media[i]), limit - SUMMARY_RESERVE - textBytes); if (!text.cut && !fit.degraded) return { output: content, truncated: false }; let next = 0; const output = content.flatMap((_, i) => (media[i] ? (fit.blocks[next++] ?? []) : text.forms.has(i) ? [text.forms.get(i)] : [])); return { output, truncated: true, totalChars: content.reduce((n, b) => n + toolOutputBlockChars(b), 0) }; }; export const toolOutputFrom = (result, mediaBudgetBase64Chars) => { try { const content = result !== null && typeof result === "object" ? result.content : result; return content === undefined ? undefined : project(content, mediaBudgetBase64Chars); } catch { return { output: "[unserializable tool output]", truncated: true }; } }; const CC_DETAIL_TYPES = engineCardTypes(); export function createStructuredProjector(opts = {}) { const project = createCardProjector(opts); return (result) => { const on = project(result); return on !== undefined && "structured" in on ? on.structured : undefined; }; } export function createCardProjector(opts = {}) { const allowed = new Set([...CC_DETAIL_TYPES, ...(opts.declaredCards ?? [])]); const announced = new Set(); return (result) => { const details = readMember(result, "details"); if (details === null || typeof details !== "object") return undefined; const t = readMember(details, "type"); if (typeof t !== "string") return undefined; if (!allowed.has(t)) { if (opts.onUndeclared !== undefined && !announced.has(t)) { announced.add(t); opts.onUndeclared(t); } return undefined; } return cardOnFrame(details, t, cardSkeletonMembers(t)); }; }