char-slop/berry

multipurpose self-modifiable agentic harness

git clone https://git.t4t.associates/char-slop/berry

Charlotte Somslop: merge remote ssh reworkd800a2b

main
1.8 KiB39 linesraw
1import type { ImageContent, UserMessage } from "@earendil-works/pi-ai";
2
3export const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
4export const MAX_IMAGES = 4;
5export const MAX_MESSAGE_BYTES = 30 * 1024 * 1024;
6export const IMAGE_MIME_TYPES = ["image/png", "image/jpeg", "image/webp"] as const;
7
8/** Check an image's declared format against its file signature and bounded size. */
9export function validateImage(bytes: Uint8Array, mimeType: string, size = bytes.length): void {
10  if (size === 0 || size > MAX_IMAGE_BYTES) {
11    throw new Error("Images must be between 1 byte and 5 MiB");
12  }
13  if (!IMAGE_MIME_TYPES.some((type) => type === mimeType)) {
14    throw new Error("Supported image formats are PNG, JPEG, and WebP");
15  }
16  const matches = (offset: number, signature: readonly number[]) =>
17    signature.every((byte, index) => bytes[offset + index] === byte);
18  const valid = mimeType === "image/png"
19    ? matches(0, [137, 80, 78, 71, 13, 10, 26, 10])
20    : mimeType === "image/jpeg"
21    ? matches(0, [255, 216, 255])
22    : matches(0, [82, 73, 70, 70]) && matches(8, [87, 69, 66, 80]);
23  if (!valid) throw new Error("Image bytes do not match their declared format");
24}
25
26/** Text-only submissions retain their original shape; attachments become image content blocks. */
27export function userContent(text: string, images: readonly ImageContent[]): UserMessage["content"] {
28  return images.length === 0
29    ? text
30    : [...(text ? [{ type: "text" as const, text }] : []), ...images];
31}
32
33/** A compact label for images in places without thumbnails. */
34export function imageSummary(content: UserMessage["content"]): string {
35  const count = typeof content === "string"
36    ? 0
37    : content.filter((block) => block.type === "image").length;
38  return count === 0 ? "" : `[${count} image${count === 1 ? "" : "s"}]`;
39}