Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Count full data URLs, fallback frames and replayed images against a clip's media budget

AdityaUmaled7957edb24be
diff --git a/server/contracts.ts b/server/contracts.ts
index bbcfb6d0b5..fb4b2b47ad 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -93,7 +93,7 @@ export interface TurnImageInput {
source?: "video-frame";
}
-/** A video already admitted to the private attachment store; a driver with `nativeImageInput` gets it as the clip within its `nativeVideoBytes`, otherwise as TurnImageInput frames while the turn has image slots left. */
+/** A video already admitted to the private attachment store; a driver with `nativeImageInput` gets it as the clip within its `nativeVideoBytes`. Otherwise, best effort, a driver with `nativeImageInput` gets TurnImageInput frames when the turn has image slots left and ffprobe and ffmpeg can sample it, and none when they can't. */
export interface TurnVideoInput {
path: string;
mime: "video/mp4" | "video/webm" | "video/quicktime";
@@ -277,7 +277,7 @@ export interface ProviderAdapter {
images?: boolean;
/** sendTurn consumes `images` as structured input, so dispatch strips the attachment path from `text`. */
nativeImageInput?: boolean;
- /** With `nativeImageInput`, sendTurn also takes `videos` as the clips themselves, up to this many bytes per turn; any other clip arrives as frames only while the turn has image slots left. */
+ /** With `nativeImageInput`, sendTurn also takes `videos` as the clips themselves, up to this many bytes per turn; any other clip arrives, best effort, as frames only when the turn has image slots left and ffprobe and ffmpeg can sample it. */
nativeVideoBytes?: number;
/** Effort levels the driver can pass to its CLI, ascending; absent hides the control. */
effortLevels?: readonly EffortLevel[];
diff --git a/server/drivers/chat-images.ts b/server/drivers/chat-images.ts
index f8ad85fe55..f4d3230835 100644
--- a/server/drivers/chat-images.ts
+++ b/server/drivers/chat-images.ts
@@ -7,6 +7,12 @@ export type ChatContentPart = ChatTextPart | ChatImagePart;
const IMAGE_BYTES = 20 * 1024 * 1024;
const MIME = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
export const CHAT_IMAGE_BUDGET = 32 * 1024 * 1024;
+// Gemini, the one engine sent clips, names QuickTime video/mov.
+const VIDEO_MIME: Readonly<Record<TurnVideoInput["mime"], string>> = { "video/mp4": "video/mp4", "video/webm": "video/webm", "video/quicktime": "video/mov" };
+const urlPrefix = (mime: string) => `data:${VIDEO_MIME[mime as TurnVideoInput["mime"]] ?? mime};base64,`;
+
+/** Length of the data URL a turn's image or clip of `bytes` becomes, which is what `chatImageBudget` counts. */
+export const chatMediaUrlBytes = (media: { mime: string; bytes: number }) => urlPrefix(media.mime).length + Math.ceil(media.bytes / 3) * 4;
/** Bound retained base64 before JSON serialization or another model call. */
export function chatImageBudget() {
@@ -40,12 +46,9 @@ export function chatImage(item: { mimeType?: unknown; data?: unknown }): ChatIma
: mimeType === "image/gif" ? bytes.length >= 13 && ["GIF87a", "GIF89a"].includes(bytes.toString("ascii", 0, 6))
: bytes.length >= 16 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP";
if (bytes.length > IMAGE_BYTES || bytes.toString("base64") !== data || !matches) throw new Error("Image bytes do not match the declared MIME type");
- return { type: "image_url", image_url: { url: `data:${mimeType};base64,${data}` } };
+ return { type: "image_url", image_url: { url: urlPrefix(mimeType) + data } };
}
-// Gemini, the one engine sent clips, names QuickTime video/mov.
-const VIDEO_MIME: Readonly<Record<TurnVideoInput["mime"], string>> = { "video/mp4": "video/mp4", "video/webm": "video/webm", "video/quicktime": "video/mov" };
-
/** Stands in for a clip removed from disk after it was attached, so the rest of the turn still goes. */
export const UNREADABLE_CLIP_NOTE = "[An attached video could no longer be read and was left out. Tell the person to attach it again.]";
@@ -64,7 +67,7 @@ export function chatUserContent(turn: SendTurnInput): string | ChatContentPart[]
parts.push({ type: "text", text: UNREADABLE_CLIP_NOTE });
continue;
}
- const part: ChatImagePart = { type: "image_url", image_url: { url: `data:${VIDEO_MIME[video.mime]};base64,${data}` } };
+ const part: ChatImagePart = { type: "image_url", image_url: { url: urlPrefix(video.mime) + data } };
budget([part]);
parts.push(part);
}
diff --git a/server/index.ts b/server/index.ts
index 2a163153d0..4badb44d5c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -7751,7 +7751,7 @@ async function beginTurn(
if (!readiness.ready) throw new Error(readiness.reason ?? "The cloud computer is not ready");
}
await warmSummaries.beforeTurn(threadId, () => directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId));
- if (usesNativeImageInput && !opts?.compactOnly) turnImages.push(...await videoFramesWithin(turnImages.length, resolvedImages.videos, turnVideos));
+ if (usesNativeImageInput && !opts?.compactOnly) turnImages.push(...await videoFramesWithin(turnImages.length, resolvedImages.videos, turnVideos, turnImages));
await compactConversation({ bot, threadId, generation: dispatchClaimId, instance, model,
excludedIds: new Set([userMessage.id, ...(opts?.excludeMessageIds ?? [])]), manual: opts?.compactOnly === true });
if (!directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)) throw new DirectTurnSetupCancelled("turn stopped during context setup");
@@ -7818,7 +7818,7 @@ async function beginTurn(
userNameFor(threadId),
), personLine ? activeMessages : [], skipTranscript, userNameFor(threadId)), lineLabels(threadId));
const replay = usesNativeImageInput
- ? extractReplayImages(selection.inline, turnImages)
+ ? extractReplayImages(selection.inline, turnImages, {}, turnVideos)
: { transcript: selection.inline, images: [] };
const decideContext = (config: string) => {
// A Codex thread keeps the last effort it was sent and no turn can clear it, so one holding a level is rebuilt, not resumed.
diff --git a/server/turn-images.test.ts b/server/turn-images.test.ts
index 7c4513ba6b..5c3667f2dd 100644
--- a/server/turn-images.test.ts
+++ b/server/turn-images.test.ts
@@ -2,9 +2,16 @@ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { chatUserContent } from "./drivers/chat-images.ts";
import { extractReplayImages, extractSteerImages, extractTurnImages, nativeClips, REPLAYED_IMAGE_NOTE, turnMedia } from "./turn-images.ts";
+import { videoFrameImages } from "./turn-video.ts";
+
+vi.mock("./turn-video.ts", async (original) => {
+ const actual = await original<typeof import("./turn-video.ts")>();
+ return { ...actual, videoFrameImages: vi.fn(actual.videoFrameImages) };
+});
const IDS = [
"123e4567-e89b-42d3-a456-426614174000",
@@ -294,6 +301,53 @@ describe("native video clips", () => {
expect((await turnMedia([{ images: [image(MiB)], videos: [clip(10 * MiB)] }], gemini)).videos).toEqual([clip(10 * MiB)]);
});
+ const folder = () => mkdtempSync(join(tmpdir(), "omb-native-clips-"));
+ const png = (root: string, name: string, bytes: number) => {
+ const data = Buffer.alloc(bytes);
+ Buffer.from("89504e470d0a1a0a0000000d49484452", "hex").copy(data);
+ writeFileSync(join(root, name), data);
+ return { path: join(root, name), mime: "image/png" as const, bytes };
+ };
+
+ it("counts each picture's and clip's full data URL, so a chosen clip never breaks the request's budget", () => {
+ const root = folder();
+ try {
+ writeFileSync(join(root, "clip.mp4"), Buffer.alloc(12 * MiB));
+ const video = { path: join(root, "clip.mp4"), mime: "video/mp4" as const, bytes: 12 * MiB };
+ const full = [png(root, "a.png", 6 * MiB), png(root, "b.png", 6 * MiB)];
+ expect(nativeClips([video], gemini, full)).toEqual([]);
+ const fits = [png(root, "c.png", 6 * MiB - 30), png(root, "d.png", 6 * MiB - 30)];
+ const videos = nativeClips([video], gemini, fits);
+ expect(videos).toEqual([video]);
+ expect(() => chatUserContent({ text: "look", images: fits, videos } as Parameters<typeof chatUserContent>[0])).not.toThrow();
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+
+ it("leaves out replayed pictures that would push a turn with a clip past the request's budget", () => {
+ const root = folder();
+ try {
+ const earlier = png(root, `${IDS[0]}.png`, 5 * MiB);
+ const transcript = [{ role: "user" as const, text: `earlier\n\n<attached-image path="${earlier.path}" name="e.png" />` }];
+ expect(extractReplayImages(transcript, [], { attachmentsDir: root }, [clip(12 * MiB)]).images).toEqual([earlier]);
+ expect(extractReplayImages(transcript, [image(8 * MiB)], { attachmentsDir: root }, [clip(12 * MiB)]).images).toEqual([]);
+ expect(extractReplayImages(transcript, [image(8 * MiB)], { attachmentsDir: root }).images).toEqual([earlier]);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+
+ it("keeps only the frames that fit beside a sent clip, and every frame when no clip is sent", async () => {
+ const frame = (bytes: number) => ({ path: `/tmp/frame-${bytes}.jpg`, mime: "image/jpeg" as const, bytes, source: "video-frame" as const });
+ const frames = [frame(2 * MiB), frame(4 * MiB), frame(MiB)];
+ const sampler = vi.mocked(videoFrameImages), actual = sampler.getMockImplementation()!;
+ sampler.mockImplementation(async (videos) => videos?.length ? frames : []);
+ try {
+ const lines = [{ images: [], videos: [clip(12 * MiB)] }, { images: [image(8 * MiB)], videos: [clip(MiB)] }];
+ const media = await turnMedia(lines, gemini);
+ expect(media.videos).toEqual([clip(12 * MiB)]);
+ expect(media.images).toEqual([image(8 * MiB), frame(2 * MiB), frame(MiB)]);
+ expect((await turnMedia(lines, { nativeImageInput: true })).images).toEqual([...frames, image(8 * MiB), ...frames]);
+ } finally { sampler.mockImplementation(actual); }
+ });
+
it("gives no clip to an engine without a video limit, so it keeps getting frames", () => {
expect(nativeClips([clip(10)], { nativeImageInput: true })).toEqual([]);
expect(nativeClips([clip(10)], { nativeVideoBytes: 100 })).toEqual([]);
diff --git a/server/turn-images.ts b/server/turn-images.ts
index 9f2d3d499b..8e2723a521 100644
--- a/server/turn-images.ts
+++ b/server/turn-images.ts
@@ -5,7 +5,7 @@ import { fromMarkdown } from "mdast-util-from-markdown";
import { ATTACHMENTS_DIR, FILE_MAX_BYTES, IMAGE_MAX_BYTES } from "./attachments.ts";
import type { ProviderAdapter, TurnImageInput, TurnVideoInput } from "./contracts.ts";
-import { CHAT_IMAGE_BUDGET } from "./drivers/chat-images.ts";
+import { CHAT_IMAGE_BUDGET, chatMediaUrlBytes } from "./drivers/chat-images.ts";
import { decodeAttachmentAttribute } from "./message-file.ts";
import { videoFrameImages } from "./turn-video.ts";
@@ -174,33 +174,48 @@ export function extractTurnImages(
return { text: providerText, images: admittedImages.map((item) => item.image), videos };
}
-/** Base64 length of `bytes`, the size a clip or image takes in a chat request. */
-const encodedBytes = (bytes: number) => Math.ceil(bytes / 3) * 4;
+const mediaUrlBytes = (media: readonly { mime: string; bytes: number }[]) => media.reduce((total, item) => total + chatMediaUrlBytes(item), 0);
/** The clips an engine that takes video gets as they are: those within its byte limit that also keep the turn's `images` inside the request's media budget. */
export function nativeClips(videos: readonly TurnVideoInput[], engine: Pick<ProviderAdapter["capabilities"], "nativeImageInput" | "nativeVideoBytes">,
images: readonly TurnImageInput[] = []): TurnVideoInput[] {
const limit = engine.nativeImageInput ? engine.nativeVideoBytes ?? 0 : 0;
- let clipBytes = 0, encoded = images.reduce((total, image) => total + encodedBytes(image.bytes), 0);
+ let clipBytes = 0, encoded = mediaUrlBytes(images);
return videos.filter((clip) => {
- if (clipBytes + clip.bytes > limit || encoded + encodedBytes(clip.bytes) > CHAT_IMAGE_BUDGET) return false;
+ const url = chatMediaUrlBytes(clip);
+ if (clipBytes + clip.bytes > limit || encoded + url > CHAT_IMAGE_BUDGET) return false;
clipBytes += clip.bytes;
- encoded += encodedBytes(clip.bytes);
+ encoded += url;
return true;
});
}
-/** Stills sampled from a message's videos not `sent` as clips, never taking a turn that already carries `earlier` images past its image count. */
-export function videoFramesWithin(earlier: number, videos: readonly TurnVideoInput[], sent: readonly TurnVideoInput[] = []): Promise<TurnImageInput[]> {
- return videoFrameImages(videos.filter((video) => !sent.includes(video)), TURN_IMAGE_MAX_COUNT - earlier);
+/** Stills sampled from a message's videos not `sent` as clips, never taking a turn that already carries `earlier` images past its image count;
+ * beside a sent clip, only the frames that still fit the request's media budget with the clips and the turn's other pictures (`alongside`). */
+export async function videoFramesWithin(earlier: number, videos: readonly TurnVideoInput[], sent: readonly TurnVideoInput[] = [],
+ alongside: readonly TurnImageInput[] = []): Promise<TurnImageInput[]> {
+ const frames = await videoFrameImages(videos.filter((video) => !sent.includes(video)), TURN_IMAGE_MAX_COUNT - earlier);
+ if (!sent.length) return frames;
+ let room = CHAT_IMAGE_BUDGET - mediaUrlBytes([...sent, ...alongside]);
+ return frames.filter((frame) => {
+ const url = chatMediaUrlBytes(frame);
+ if (url > room) return false;
+ room -= url;
+ return true;
+ });
}
/** A burst's media: clips chosen once for all its lines against every line's pictures, so it fits one request, then each line's pictures and the frames of its clips not sent. */
export async function turnMedia(lines: readonly { images: readonly TurnImageInput[]; videos: readonly TurnVideoInput[] }[],
engine: Pick<ProviderAdapter["capabilities"], "nativeImageInput" | "nativeVideoBytes">): Promise<{ images: TurnImageInput[]; videos: TurnVideoInput[] }> {
- const videos = nativeClips(lines.flatMap((line) => line.videos), engine, lines.flatMap((line) => line.images));
- const images: TurnImageInput[] = [];
- for (const line of lines) images.push(...line.images, ...await videoFramesWithin(images.length + line.images.length, line.videos, videos));
+ const pictures = lines.flatMap((line) => line.images);
+ const videos = nativeClips(lines.flatMap((line) => line.videos), engine, pictures);
+ const images: TurnImageInput[] = [], frames: TurnImageInput[] = [];
+ for (const line of lines) {
+ const sampled = await videoFramesWithin(images.length + line.images.length, line.videos, videos, [...pictures, ...frames]);
+ frames.push(...sampled);
+ images.push(...line.images, ...sampled);
+ }
return { images, videos };
}
@@ -230,9 +245,11 @@ export function extractReplayImages<T extends { role: "user" | "assistant"; text
transcript: readonly T[],
current: readonly TurnImageInput[],
options: ExtractTurnImagesOptions = {},
+ clips: readonly TurnVideoInput[] = [],
): { transcript: T[]; images: TurnImageInput[] } {
let maxCount = (options.maxCount ?? TURN_IMAGE_MAX_COUNT) - current.length;
let maxBytes = (options.maxBytes ?? TURN_IMAGE_MAX_BYTES) - current.reduce((total, image) => total + image.bytes, 0);
+ let room = clips.length ? CHAT_IMAGE_BUDGET - mediaUrlBytes([...clips, ...current]) : Infinity;
const replayed = [...transcript];
const images: TurnImageInput[] = [];
for (let index = replayed.length - 1; index >= 0 && maxCount > 0; index -= 1) {
@@ -241,11 +258,13 @@ export function extractReplayImages<T extends { role: "user" | "assistant"; text
const item = extractTurnImages(entry.text, { ...options, maxCount: Infinity, maxBytes: Infinity, imageNote: REPLAYED_IMAGE_NOTE });
if (!item.images.length) continue;
const bytes = item.images.reduce((total, image) => total + image.bytes, 0);
- if (item.images.length > maxCount || bytes > maxBytes) break;
+ const encoded = mediaUrlBytes(item.images);
+ if (item.images.length > maxCount || bytes > maxBytes || encoded > room) break;
replayed[index] = { ...entry, text: item.text };
images.unshift(...item.images);
maxCount -= item.images.length;
maxBytes -= bytes;
+ room -= encoded;
}
return { transcript: replayed, images };
}