@sema-agent/core
Version:
Stateless, task-oriented AI agent core
243 lines (242 loc) • 15.4 kB
TypeScript
import type { DocumentContent, ImageContent } from "../internal/llm.js";
import type { ImageDimensions, ImageDownsampler } from "./image-downsample.js";
import type { MediaBlock } from "./media-byte-cap.js";
import { type BytesNotKeptReason, type ToolResultBytesKeeper } from "./tool-result-bytes.js";
/** Max raw size sent whole as a document block (CC `PDF_TARGET_RAW_SIZE`). */
export declare const PDF_TARGET_RAW_SIZE: number;
/**
* Every number an image passes on its way to the model, in one table — the admission and its processor read it, and so
* does every carrier that words a refusal; a downstream that bounds an image by the same limit reads the same field.
* - `hard`: what refuses. `formats` (the header rows above), `readBytes` (the raw read cap — without a processor the bytes
* ship as they are, so the cap is the raw size whose base64 fits `imageBase64Chars`, the one bound that binds there;
* with one it is larger, since the processor shrinks what was read, and the 64 MiB bound is an OOM sanity bound, CC
* reads the file whole), `urlBytes` (a fetched image's body), `rejectEdge` (the longest edge the bytes that ship may
* state — `fI` (cli309.js:253044), the 2000 box, its no-flag reject width), `imageBase64Chars` (the provider's
* single-image limit, on the base64 length — CC `fI` `maxBase64Size`).
* - `soft`: what the processor aims at, best effort. `frameEdge` and `rawBytes` are the frame ladder's box and byte rung
* (CC `fI` `maxWidth` / `targetRawSize`: 3.75 MB raw = 5 MiB base64); `targetBytes` is the byte-target step's goal
* (`SZ` (cli309.js:253044), the bytes `N$o` compresses toward).
* - `request`: what one provider request may carry of the media the conversation holds (CC `eSn` (cli309.js:265961) and
* its constants `Xai` / `Jai` (cli309.js:253044)), every size in base64 characters — the unit the provider counts. Over `maxItems`
* media blocks (images and documents together; `largeWindow.maxItems` for a model whose window is at least
* `largeWindow.fromContextWindow` tokens; the model's own `mediaItemLimit` when it declares one) the oldest go until
* `maxItems - margin` remain (the margin is half of a count under twice `margin`); over the budget the oldest go
* until `hysteresisBase64Chars` under it. `budgetBase64Chars` is the default budget a deployment may replace
* (`RunnerDeps.mediaBudgetBase64Chars`); it is not CC's first-party 24 MiB, because a sema deployment mostly serves
* endpoints CC treats as third-party, for which CC's own budget is 75 MiB. There is no document-only budget: CC holds
* one for its first-party endpoint alone. `refusalRungs` are the counts a session's limit for a model steps down through
* when its endpoint refuses a request over its media blocks (`errorKind: "media_items_refused"`, CC's ladder): the first
* rung under the count the refused request carried is the re-send's `maxItems`, and the session's once a re-send at it
* is answered (`core/runner/media-item-limit.ts`). A count at or under the last rung has none: such a refusal ends the
* turn, and an endpoint that takes fewer is declared on its model (`mediaItemLimit`).
*/
export declare const IMAGE_ADMISSION: Readonly<{
readonly hard: Readonly<{
formats: Readonly<Record<"image/png" | "image/jpeg" | "image/gif" | "image/webp", (b: Uint8Array) => boolean>>;
readBytes: Readonly<{
withoutProcessor: number;
withProcessor: number;
}>;
urlBytes: number;
rejectEdge: 2000;
imageBase64Chars: number;
}>;
readonly soft: Readonly<{
frameEdge: 2000;
rawBytes: number;
targetBytes: 512000;
}>;
readonly request: Readonly<{
maxItems: 100;
largeWindow: Readonly<{
fromContextWindow: 1000000;
maxItems: 600;
}>;
margin: 20;
budgetBase64Chars: number;
hysteresisBase64Chars: number;
refusalRungs: readonly [510, 255, 127];
}>;
}>;
/** What one request may carry, resolved for a model and a deployment's budget: the media-block count, the margin a count
* cut leaves under it, the base64 budget (`Infinity`: none) and the hysteresis a budget cut leaves under that. */
export interface RequestMediaLimits {
maxItems: number;
margin: number;
budgetBase64Chars: number;
hysteresisBase64Chars: number;
}
/** The one reading of a deployment's request media budget (`RunnerDeps.mediaBudgetBase64Chars`, screened by
* {@link checkedRequestMediaBudget} at `new Runner`), for both of its readers — the request trim and the `tool_end.output`
* projection: absent ⇒ `IMAGE_ADMISSION.request.budgetBase64Chars`; `0` or `Infinity` ⇒ no budget (`Infinity`). */
export declare function requestMediaBudget(knob: number | undefined): number;
/** The limits a request on `model` under the deployment's budget `knob` is trimmed to. The block count is the model's
* declared `mediaItemLimit` (judged at the model door), else the window default — and no more than `learned`, the rung its
* endpoint's refusal set for this session (`core/runner/media-item-limit.ts`), when there is one; the margin a count cut
* leaves is `min(margin, floor(count / 2))` — 20 for both defaults and every rung, half of a small declared count — so a cut
* always keeps the block that passed the count. */
export declare function requestMediaLimits(model: {
readonly contextWindow?: unknown;
readonly mediaItemLimit?: unknown;
}, knob: number | undefined, learned?: number): RequestMediaLimits;
/** The deployment's request media budget, screened once at `new Runner`: absent, `0` or `Infinity` (no budget), or a whole
* number of base64 characters no smaller than twice the hysteresis. Anything else — a non-number, `NaN`, a negative, a
* fraction, a budget a cut would empty — is refused (`config.invalid_argument`), never read as a default or as none. */
export declare function checkedRequestMediaBudget(value: unknown, seat: string): void;
/** Verify the raw bytes actually ARE the image format the claimed type names (`IMAGE_ADMISSION.hard.formats`). Extension
* alone is forgeable: a `.png` holding text / an empty file / a truncated blob / an Apple-optimized PNG would otherwise
* become a malformed `ImageContent` that makes the NEXT provider request fail (400). Pure — no I/O. */
export declare function imageMagicMatches(bytes: Uint8Array, mimeType: string): boolean;
/**
* The pixel size an image's own header states, read without decoding (`WN` (cli309.js:257745)): PNG's `IHDR`, GIF's screen
* descriptor, a JPEG's first start-of-frame segment, WebP's `VP8 ` / `VP8L` / `VP8X` header. `undefined` when the header
* states none this reader finds. Pure — the admission reads it for the bytes that ship.
*/
export declare function readImageHeaderDimensions(b: Uint8Array): {
width: number;
height: number;
} | undefined;
/** True when the bytes start with the `%PDF-` magic. Magic outranks extension both ways: a mis-named
* `.pdf` without it is refused, and a non-`.pdf` file carrying it is read AS a PDF. */
export declare function pdfMagicMatches(bytes: Uint8Array): boolean;
/** The image types the content API accepts — the only ones a signature check can verify. */
export declare const ADMITTED_IMAGE_MIME_TYPES: readonly ["image/png", "image/jpeg", "image/gif", "image/webp"];
/** The admitted image type a claimed type names (`IMAGE/PNG`, `image/png; charset=binary` → `image/png`), or `undefined` for
* any value outside the four. */
export declare function admittedImageMime(mime: unknown): (typeof ADMITTED_IMAGE_MIME_TYPES)[number] | undefined;
/** The raw-byte read cap for an image, with or without a processor (`IMAGE_ADMISSION.hard.readBytes`). */
export declare function imageReadCap(processor: ImageDownsampler | "none"): number;
export type ImageAdmission = {
ok: true;
block: ImageContent;
/** The raw byte count of the bytes checked (before any processing). */
originalSize: number;
/** Measured by the processor; absent when the bytes went on as they are (never fabricated). */
dimensions?: ImageDimensions;
/** True when the processor actually changed the pixel size. */
resized: boolean;
} | {
ok: false;
reason: "mime_unsupported" | "magic_mismatch";
rawBytes: number;
}
/** The bytes that would ship state no pixel size in their header. */
| {
ok: false;
reason: "dimensions_unreadable";
rawBytes: number;
} | {
ok: false;
reason: "raw_too_large";
rawBytes: number;
cap: number;
}
/** The bytes that would ship state an edge over `IMAGE_ADMISSION.hard.rejectEdge` (`limit`). */
| {
ok: false;
reason: "dimensions_too_large";
rawBytes: number;
width: number;
height: number;
limit: number;
}
/** `base64` is the encoding that failed the limit (the caller words the refusal from its length). */
| {
ok: false;
reason: "base64_too_large";
rawBytes: number;
base64: string;
};
/** Why the bytes that would have shipped were refused on their stated size (`dimensions_unreadable` / `dimensions_too_large`)
* — the one wording every carrier's refusal and the tool-result seat's placeholder read. */
export declare function unprocessedSizeClause(a: {
reason: "dimensions_unreadable";
} | {
reason: "dimensions_too_large";
width: number;
height: number;
limit: number;
}): string;
/** One image's bytes through the admission (see the module head). `processor` is the run's, resolved from its one seat
* (`resolveImageProcessor`), or `"none"`: it is never optional, so no carrier admits without saying which. */
export declare function admitImageBytes(bytes: Uint8Array, claimedMime: string, processor: ImageDownsampler | "none"): Promise<ImageAdmission>;
/** The admitted type the bytes' own header names (the first of the four header rows they open with), or `undefined`. */
export declare function sniffImageMime(bytes: Uint8Array): (typeof ADMITTED_IMAGE_MIME_TYPES)[number] | undefined;
/** The document types the content API accepts — the one a signature check can verify. */
export declare const ADMITTED_DOCUMENT_MIME_TYPES: readonly ["application/pdf"];
export type DocumentAdmission = {
ok: true;
block: DocumentContent;
originalSize: number;
} | {
ok: false;
reason: "mime_unsupported" | "magic_mismatch";
rawBytes: number;
} | {
ok: false;
reason: "raw_too_large";
rawBytes: number;
cap: number;
};
/** A document's bytes: the claimed type is `application/pdf`, the raw bytes are within the whole-send cap
* ({@link PDF_TARGET_RAW_SIZE}, the Read tool's), and they start with `%PDF-`. */
export declare function admitDocumentBytes(bytes: Uint8Array, claimedMime: string): DocumentAdmission;
/** Why the tool-result seat refused a media block: the admissions' own words (an image's four — a document's are among
* them), or `undecodable` — the block carried no base64 string to decode. */
export type MediaRefusalReason = "undecodable" | "mime_unsupported" | "raw_too_large" | "magic_mismatch" | "dimensions_unreadable" | "dimensions_too_large" | "base64_too_large";
/** One media block the seat refused: its type, the refusal, its decoded size, the bound it exceeded (the raw-byte cap for
* `raw_too_large`, the reject edge for `dimensions_too_large` — with the size its header states —, the base64 length
* limit for `base64_too_large`), and its media type when it can be one. A refusal for size also says under which ref of the
* run's tool-result store its bytes were kept (`ref`), or why they were not (`notKept`, with the store's own words in `saveError`
* whenever the store threw — its bound refusal too); no other refusal carries any of the three. */
export interface ToolResultMediaRefusal {
type: MediaBlock["type"];
reason: MediaRefusalReason;
bytes: number;
limit?: number;
width?: number;
height?: number;
mimeType?: string;
ref?: string;
notKept?: BytesNotKeptReason;
saveError?: string;
}
/** What the seat made of one result's content: every media block rebuilt from its checked bytes or replaced, in its slot,
* by its placeholder; and the refusals. */
export interface ToolResultMediaAdmission {
content: unknown[];
refused: ToolResultMediaRefusal[];
}
/** The media block a claimed type names, read off the admission's own sets (the claim read as {@link mediaTypeEssence}:
* its case and its parameters do not matter) — `image` for one of the four image types, `document` for `application/pdf`,
* `undefined` for any other value. A carrier that holds bytes under a claimed type and no block type (an MCP resource blob)
* reads its block here, so what it builds is judged by the same sets that judge it. */
export declare function mediaBlockTypeOf(mime: unknown): MediaBlock["type"] | undefined;
/** The media type a block claims — its `type`, read once, when that is a media type — or `undefined` for any other value. */
export declare function claimedMediaType(block: unknown): MediaBlock["type"] | undefined;
/**
* The decoded size of the first image block that goes to the model over `IMAGE_ADMISSION.soft.targetBytes` with no
* processor to bring it down — the one fact the run's operator notice reads (`config.image_processor_unavailable`), at
* every place images enter a run (the tool-result seat, the task's images, a person's attachments). `undefined` with a
* processor, or when none does.
*/
export declare function firstUnprocessedOverTarget(blocks: readonly unknown[], processor: ImageDownsampler | "none"): number | undefined;
/**
* The tool-result seat's one read of an executed call's content: its blocks, read once into a new array, when one claims a
* media type; `undefined` otherwise (the content stands as it is). Synchronous and total — a content whose blocks cannot be
* read is not media this seat can admit or refuse. A carrier resolves the run's processor only once this answers blocks,
* so a call with no media in its result awaits nothing.
*/
export declare function toolResultMediaBlocks(content: unknown): unknown[] | undefined;
/**
* The tool-result seat's admission over blocks {@link toolResultMediaBlocks} read: each media block admitted with the run's
* `processor` — rebuilt from the bytes it checked (an image a carrier already brought within the target and the frame passes
* unchanged), or replaced in its slot by a placeholder naming `toolName` and the refusal (and, for a refusal for size, the
* ref `keep` kept its bytes under, or why they were not kept — no `keep` keeps nothing).
*/
export declare function admitToolResultMediaBlocks(blocks: readonly unknown[], toolName: string, processor: ImageDownsampler | "none", keep?: ToolResultBytesKeeper): Promise<ToolResultMediaAdmission>;
/**
* The tool-result seat over one executed call's content with a processor in hand: {@link toolResultMediaBlocks}, then
* {@link admitToolResultMediaBlocks} — `undefined` when no block claims a media type (nothing is awaited).
*/
export declare function admitToolResultMedia(content: unknown, toolName: string, processor: ImageDownsampler | "none", keep?: ToolResultBytesKeeper): Promise<ToolResultMediaAdmission> | undefined;