Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a native clip inside the turn's media budget, and skip an unreadable one
AdityaUmalebf5d53af0076
diff --git a/server/contracts.ts b/server/contracts.tsindex 0e50ee978d..bbcfb6d0b5 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 gets it as the clip only within its `nativeVideoBytes`, otherwise as TurnImageInput frames. */+/** 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. */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;- /** sendTurn also takes `videos` as the clips themselves, up to this many bytes per turn; any other clip arrives as frames. */+ /** 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. */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.test.ts b/server/drivers/chat-images.test.tsindex f9d672b804..12301f1131 100644--- a/server/drivers/chat-images.test.ts+++ b/server/drivers/chat-images.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from "vitest";-import { assertImageTransport, CHAT_IMAGE_BUDGET, chatImageBudget, chatImage } from "./chat-images.ts";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { assertImageTransport, CHAT_IMAGE_BUDGET, chatImageBudget, chatImage, chatUserContent, UNREADABLE_CLIP_NOTE } from "./chat-images.ts";describe("chat image transport and retained budget", () => {it("rejects encoded text and mismatched MIME claims while preserving a PNG", () => {@@ -24,3 +28,23 @@ describe("chat image transport and retained budget", () => {expect(() => assertImageTransport(url)).toThrow("require HTTPS");});});++describe("chat user content with video clips", () => {+ it("still sends the turn when a clip was removed after it was attached, naming the gap", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-chat-clip-"));+ const kept = join(dir, "kept.mp4");+ writeFileSync(kept, Buffer.from("00000018667479706d703432", "hex"));+ try {+ const content = chatUserContent({ threadId: "t", text: "What happens here?", videos: [+ { path: join(dir, "gone.mp4"), mime: "video/mp4", bytes: 12 }, { path: kept, mime: "video/mp4", bytes: 12 },+ ] });+ expect(content).toEqual([+ { type: "text", text: "What happens here?" },+ { type: "text", text: UNREADABLE_CLIP_NOTE },+ { type: "image_url", image_url: { url: "data:video/mp4;base64,AAAAGGZ0eXBtcDQy" } },+ ]);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/server/drivers/chat-images.ts b/server/drivers/chat-images.tsindex 272d23a3cb..f8ad85fe55 100644--- a/server/drivers/chat-images.ts+++ b/server/drivers/chat-images.ts@@ -46,19 +46,28 @@ export function chatImage(item: { mimeType?: unknown; data?: unknown }): ChatIma// 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.]";+export function chatUserContent(turn: SendTurnInput): string | ChatContentPart[] {if (!turn.images?.length && !turn.videos?.length) return turn.text;const budget = chatImageBudget();- const parts = [...(turn.images ?? []).map(image => {+ const parts: ChatContentPart[] = (turn.images ?? []).map(image => {if (statSync(image.path).size > IMAGE_BYTES) throw new Error("Image exceeds 20 MB");const part = chatImage({ mimeType: image.mime, data: readFileSync(image.path).toString("base64") });budget([part]);return part;- }), ...(turn.videos ?? []).map((video): ChatImagePart => {- const part: ChatImagePart = { type: "image_url", image_url: { url: `data:${VIDEO_MIME[video.mime]};base64,${readFileSync(video.path).toString("base64")}` } };+ });+ for (const video of turn.videos ?? []) {+ let data: string;+ try { data = readFileSync(video.path).toString("base64"); } catch {+ 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}` } };budget([part]);- return part;- })];+ parts.push(part);+ }return [{ type: "text", text: turn.text }, ...parts];}diff --git a/server/index.ts b/server/index.tsindex a48ae28a0c..2a163153d0 100644--- a/server/index.ts+++ b/server/index.ts@@ -330,7 +330,7 @@ import { turnStartLogLine } from "./turn-log.ts";import { TurnStops, outwardActions, stoppedTurnOutcome, turnEvidence } from "./turn-outcome.ts";import { buildRecoveryText, buildTurnContext, engineIsFresh, replaysNatively } from "./turn-context.ts";import { Handoffs, handedStateUsable, isContextMessage, recordHanded, renderUnseen, sessionStart, unseenMessages, withUnseenMessages, type ContextMessage } from "./delta-context.ts"; import { isFreshStart, sinceFreshStart } from "./fresh-start.ts";-import { extractReplayImages, extractTurnImages, nativeClips, videoFramesWithin } from "./turn-images.ts";+import { extractReplayImages, extractTurnImages, nativeClips, turnMedia, videoFramesWithin } from "./turn-images.ts";import { callTitleExcerpt } from "./thread-title.ts";import { generateThreadTitle } from "./thread-title-generate.ts";import { engineCommandCpuMs, engineProcessExited, engineProcessGone, ENGINE_EXIT_STALL_MS, stallLimitMs, stallNotice, TurnWatchdog } from "./turn-watchdog.ts"; import { createIdleThreads } from "./host/idle-threads.ts";@@ -7590,7 +7590,7 @@ async function beginTurn(const resolvedImages = extractTurnImages(text);const usesNativeImageInput = instance.adapter.capabilities.nativeImageInput === true;let providerText = promptWithDataContext(usesNativeImageInput ? resolvedImages.text : text, opts?.dataContext);- const turnImages = usesNativeImageInput ? resolvedImages.images : [], turnVideos = opts?.compactOnly ? [] : nativeClips(resolvedImages.videos, instance.adapter.capabilities);+ const turnImages = usesNativeImageInput ? resolvedImages.images : [], turnVideos = opts?.compactOnly ? [] : nativeClips(resolvedImages.videos, instance.adapter.capabilities, turnImages);const commsDepth = opts?.commsDepth ?? 0;if (commsDepth > 0) markInternalTurn(threadId);else { clearInternalTurn(threadId); doneNotice.personTurnStarted(threadId); }@@ -9711,14 +9711,14 @@ async function runClaimedGroupMemberTurn(// A drained burst runs as one turn: recover its lines by queueId, not position.const burstIds = new Set(operation?.queuedQueueIds ?? []);const burstOverrides: Array<{ messageId: string; text: string }> = [];- const burstImages: ReturnType<typeof extractTurnImages>["images"] = [], burstVideos: ReturnType<typeof extractTurnImages>["videos"] = [];+ const burstLines: Array<ReturnType<typeof extractTurnImages>> = [];if (usesNativeImageInput && !cardContinuation) {for (const message of store.activePath(threadId)) {if (message.role !== "user" || message.kind !== "text" || !message.text) continue;if (!message.queueId || !burstIds.has(message.queueId)) continue;const resolved = extractTurnImages(message.text);burstOverrides.push({ messageId: message.id, text: resolved.text });- burstVideos.push(...nativeClips(resolved.videos, instance.adapter.capabilities, burstVideos)); burstImages.push(...resolved.images, ...await videoFramesWithin(burstImages.length + resolved.images.length, resolved.videos, burstVideos));+ burstLines.push(resolved);}}// The latest line is usually the burst's last: extracting it again would double-count its attachments.@@ -9737,7 +9737,7 @@ async function runClaimedGroupMemberTurn(bot.id,);const roomContext = roomWindow.text;- const turnVideos = [...burstVideos, ...nativeClips(resolvedLatestImages.videos, instance.adapter.capabilities, burstVideos)], turnImages = usesNativeImageInput ? [...burstImages, ...resolvedLatestImages.images, ...await videoFramesWithin(burstImages.length + resolvedLatestImages.images.length, resolvedLatestImages.videos, turnVideos)] : [];+ const { images: turnImages, videos: turnVideos } = usesNativeImageInput ? await turnMedia([...burstLines, resolvedLatestImages], instance.adapter.capabilities) : { images: [], videos: [] };const skills = availableSkills(), phoneOffered = HAS_USB_PORT && usbPhoneOffered(instance, skills);const selectedSkills = mergeSkills(selectBundledSkills(diff --git a/server/turn-images.test.ts b/server/turn-images.test.tsindex c0ba2aa145..7c4513ba6b 100644--- a/server/turn-images.test.ts+++ b/server/turn-images.test.ts@@ -4,7 +4,7 @@ import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { extractReplayImages, extractSteerImages, extractTurnImages, nativeClips, REPLAYED_IMAGE_NOTE } from "./turn-images.ts";+import { extractReplayImages, extractSteerImages, extractTurnImages, nativeClips, REPLAYED_IMAGE_NOTE, turnMedia } from "./turn-images.ts";const IDS = ["123e4567-e89b-42d3-a456-426614174000",@@ -272,10 +272,26 @@ describe("turn image admission", () => {describe("native video clips", () => {const clip = (bytes: number) => ({ path: `/attachments/${bytes}.mp4`, mime: "video/mp4" as const, bytes });- it("gives an engine that takes video the clips that fit its limit, counting clips already chosen", () => {+ it("gives an engine that takes video the clips that fit its limit", () => {const engine = { nativeImageInput: true, nativeVideoBytes: 100 };expect(nativeClips([clip(60), clip(50), clip(40)], engine)).toEqual([clip(60), clip(40)]);- expect(nativeClips([clip(50), clip(30)], engine, [clip(60)])).toEqual([clip(30)]);+ });++ const MiB = 1024 * 1024;+ const gemini = { nativeImageInput: true, nativeVideoBytes: 12 * MiB };+ const image = (bytes: number) => ({ path: `/attachments/${bytes}.png`, mime: "image/png" as const, bytes });++ it("leaves a clip to frames when the turn's pictures and clips would pass the request's media budget", () => {+ const engine = gemini;+ expect(nativeClips([clip(10 * MiB)], engine, [image(8 * MiB), image(8 * MiB)])).toEqual([]);+ expect(nativeClips([clip(10 * MiB), clip(2 * MiB)], engine, [image(8 * MiB)])).toEqual([clip(10 * MiB), clip(2 * MiB)]);+ });++ it("chooses a burst's clips against the pictures of every line, not only the lines before", async () => {+ const media = await turnMedia([{ images: [], videos: [clip(10 * MiB)] }, { images: [image(8 * MiB), image(8 * MiB)], videos: [] }], gemini);+ expect(media.videos).toEqual([]);+ expect(media.images.slice(-2)).toEqual([image(8 * MiB), image(8 * MiB)]);+ expect((await turnMedia([{ images: [image(MiB)], videos: [clip(10 * MiB)] }], gemini)).videos).toEqual([clip(10 * MiB)]);});it("gives no clip to an engine without a video limit, so it keeps getting frames", () => {diff --git a/server/turn-images.ts b/server/turn-images.tsindex 9936974476..9f2d3d499b 100644--- a/server/turn-images.ts+++ b/server/turn-images.ts@@ -5,6 +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 { decodeAttachmentAttribute } from "./message-file.ts";import { videoFrameImages } from "./turn-video.ts";@@ -173,14 +174,18 @@ export function extractTurnImages(return { text: providerText, images: admittedImages.map((item) => item.image), videos };}-/** The clips an engine that takes video gets as they are: those that fit its byte limit alongside the `taken` ones. */+/** Base64 length of `bytes`, the size a clip or image takes in a chat request. */+const encodedBytes = (bytes: number) => Math.ceil(bytes / 3) * 4;++/** 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">,- taken: readonly TurnVideoInput[] = []): TurnVideoInput[] {+ images: readonly TurnImageInput[] = []): TurnVideoInput[] {const limit = engine.nativeImageInput ? engine.nativeVideoBytes ?? 0 : 0;- let used = taken.reduce((total, clip) => total + clip.bytes, 0);+ let clipBytes = 0, encoded = images.reduce((total, image) => total + encodedBytes(image.bytes), 0);return videos.filter((clip) => {- if (used + clip.bytes > limit) return false;- used += clip.bytes;+ if (clipBytes + clip.bytes > limit || encoded + encodedBytes(clip.bytes) > CHAT_IMAGE_BUDGET) return false;+ clipBytes += clip.bytes;+ encoded += encodedBytes(clip.bytes);return true;});}@@ -190,6 +195,15 @@ export function videoFramesWithin(earlier: number, videos: readonly TurnVideoInpreturn videoFrameImages(videos.filter((video) => !sent.includes(video)), TURN_IMAGE_MAX_COUNT - earlier);}+/** 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));+ return { images, videos };+}+export function extractSteerImages(texts: readonly string[],options: ExtractTurnImagesOptions = {},diff --git a/server/turn-video.ts b/server/turn-video.tsindex 8154121e46..2bf857a0d2 100644--- a/server/turn-video.ts+++ b/server/turn-video.ts@@ -1,5 +1,4 @@-// Only an engine with `nativeVideoBytes` takes a clip as it is (OpenAI's chat-completions content parts are otherwise only-// "text" and "image_url", and a local vision model takes the same two); for every other one, ffmpeg on PATH samples stills.+// Samples stills from a clip with ffprobe and ffmpeg on PATH.import { spawn } from "node:child_process";import { mkdtemp, readFile, rm } from "node:fs/promises";import { tmpdir } from "node:os";