Skip to content

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

Merge origin/main; keep the video's file tag and sample frames without new turn races

milind-sonia6d146160b74
diff --cc server/index.ts
index c10da0e50e,e8729ef9c1..74633b28dd
--- a/server/index.ts
+++ b/server/index.ts
@@@ -328,8 -324,7 +324,7 @@@ import { turnStartLogLine } from "./tur
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 { extractReplayImages, extractTurnImages } from "./turn-images.ts";
- import { videoFrameImages } from "./turn-video.ts";
++import { extractReplayImages, extractTurnImages, videoFramesWithin } from "./turn-images.ts";
import { callTitleExcerpt } from "./thread-title.ts";
import { generateThreadTitle, llmThreadTitlesEnabled } from "./thread-title-generate.ts";
import { stallLimitMs, TurnWatchdog } from "./turn-watchdog.ts";
@@@ -7921,6 -7819,6 +7819,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));
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");
@@@ -9917,15 -9825,14 +9826,13 @@@ async function runClaimedGroupMemberTur
if (!message.queueId || !burstIds.has(message.queueId)) continue;
const resolved = extractTurnImages(message.text);
burstOverrides.push({ messageId: message.id, text: resolved.text });
-- burstImages.push(...resolved.images);
- burstVideos.push(...resolved.videos);
++ burstImages.push(...resolved.images, ...await videoFramesWithin(burstImages.length + resolved.images.length, resolved.videos));
}
}
// The latest line is usually the burst's last: extracting it again would double-count its attachments.
const latestInBurst = latestUser?.queueId !== undefined && burstIds.has(latestUser.queueId);
const resolvedLatestImages = latestUser?.text && !cardContinuation && !latestInBurst
-- ? extractTurnImages(latestUser.text)
- : { text: latestUser?.text ?? "", images: [], videos: [] };
- : { text: latestUser?.text ?? "", images: [] };
++ ? extractTurnImages(latestUser.text) : { text: latestUser?.text ?? "", images: [], videos: [] };
const roomWindow = roomTranscript.window(
threadId,
userName,
@@@ -9938,9 -9845,7 +9845,7 @@@
bot.id,
);
const roomContext = roomWindow.text;
- const turnImages = usesNativeImageInput
- ? [...burstImages, ...resolvedLatestImages.images, ...(await videoFrameImages([...burstVideos, ...resolvedLatestImages.videos]))]
- : [];
- const turnImages = usesNativeImageInput ? [...burstImages, ...resolvedLatestImages.images] : [];
++ const turnImages = usesNativeImageInput ? [...burstImages, ...resolvedLatestImages.images, ...await videoFramesWithin(burstImages.length + resolvedLatestImages.images.length, resolvedLatestImages.videos)] : [];
const skills = availableSkills(), phoneOffered = usbPhoneOffered(instance, skills);
const selectedSkills = mergeSkills(
selectBundledSkills(
diff --cc server/turn-images.test.ts
index 45aae980c7,c95427f3dd..53e389a1e9
--- a/server/turn-images.test.ts
+++ b/server/turn-images.test.ts
@@@ -92,53 -86,7 +92,57 @@@ describe("turn image admission", () =>
expect(extractTurnImages(`<attached-image path="${encoded}" />`, { attachmentsDir: root })).toEqual({
text: "",
images: [{ path, mime: "image/webp", bytes: 5 }],
+ videos: [],
+ });
+ });
+
- it("resolves a video delivered through the generic <attached-file> tag and strips it from the prompt", () => {
++ it("resolves a video delivered through the generic <attached-file> tag and keeps the tag for engines that read files", () => {
+ const root = store();
+ const clip = video(root, 0, ".mp4", 9);
+ const source = `watch this\n\n<attached-file path="${clip}" name="clip.mp4" />`;
+
+ expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({
- text: "watch this\n\n",
++ text: source,
+ images: [],
+ videos: [{ path: clip, mime: "video/mp4", bytes: 9 }],
+ });
+ });
+
+ it("leaves a non-video <attached-file> tag untouched, since other file kinds still need it intact", () => {
+ const root = store();
+ const doc = join(root, `${IDS[0]}.pdf`);
+ writeFileSync(doc, "not a video");
+ const source = `see the brief\n\n<attached-file path="${doc}" name="brief.pdf" />`;
+
+ expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({ text: source, images: [], videos: [] });
+ });
+
+ it("admits both an image and a video from the same message", () => {
+ const root = store();
+ const png = image(root, 0, ".png", 4);
+ const clip = video(root, 1, ".webm", 6);
+ const source = [
+ `<attached-image path="${png}" name="a.png" />`,
+ `<attached-file path="${clip}" name="clip.webm" />`,
+ ].join("\n\n");
+
+ const result = extractTurnImages(source, { attachmentsDir: root });
- expect(result.text).toBe("\n\n");
++ expect(result.text).toBe(`\n\n<attached-file path="${clip}" name="clip.webm" />`);
+ expect(result.images).toEqual([{ path: png, mime: "image/png", bytes: 4 }]);
+ expect(result.videos).toEqual([{ path: clip, mime: "video/webm", bytes: 6 }]);
+ });
+
- it("rejects more than one video at a time", () => {
++ it("samples only the first video and leaves every video's tag in place", () => {
+ const root = store();
+ const first = video(root, 0, ".mp4", 4);
+ const second = video(root, 1, ".mov", 4);
+ const source = `<attached-file path="${first}" />\n\n<attached-file path="${second}" />`;
+
- expect(() => extractTurnImages(source, { attachmentsDir: root })).toThrow("Send no more than 1 video at a time");
++ expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({
++ text: source,
++ images: [],
++ videos: [{ path: first, mime: "video/mp4", bytes: 4 }],
+ });
});
it("rejects count and aggregate limits before partially stripping the prompt", () => {
diff --cc server/turn-images.ts
index 8e9333ffdf,82f199f86a..9b37333fe7
--- a/server/turn-images.ts
+++ b/server/turn-images.ts
@@@ -3,15 -3,13 +3,16 @@@ import { dirname, extname, resolve } fr
import { fromMarkdown } from "mdast-util-from-markdown";
-import { ATTACHMENTS_DIR, IMAGE_MAX_BYTES } from "./attachments.ts";
-import type { TurnImageInput } from "./contracts.ts";
+import { ATTACHMENTS_DIR, FILE_MAX_BYTES, IMAGE_MAX_BYTES } from "./attachments.ts";
+import type { TurnImageInput, TurnVideoInput } from "./contracts.ts";
import { decodeAttachmentAttribute } from "./message-file.ts";
++import { videoFrameImages } from "./turn-video.ts";
- export const TURN_IMAGE_MAX_COUNT = 4;
- export const TURN_IMAGE_MAX_BYTES = TURN_IMAGE_MAX_COUNT * IMAGE_MAX_BYTES;
- // A video is sampled into several frames before it reaches a model, so only one is admitted per turn.
+ export const TURN_IMAGE_MAX_COUNT = 10;
+ /** Total image bytes one turn may carry: the 40 MB it was when a turn took four images, so engine requests don't grow. */
+ export const TURN_IMAGE_MAX_BYTES = 4 * IMAGE_MAX_BYTES;
++// A video is sampled into several frames before it reaches a model, so only the first one in a message is sampled.
+export const TURN_VIDEO_MAX_COUNT = 1;
- export const TURN_VIDEO_MAX_BYTES = FILE_MAX_BYTES;
type MarkdownNode = {
type: string;
@@@ -118,11 -96,9 +119,13 @@@ export interface ExtractTurnImagesOptio
attachmentsDir?: string;
maxCount?: number;
maxBytes?: number;
+ maxVideoCount?: number;
- maxVideoBytes?: number;
}
- /** Invalid tags stay visible as ordinary text and never become native image or video input. */
-/** Invalid tags stay visible as ordinary text and never become native image input. */
++/**
++ * Invalid tags stay visible as ordinary text and never become native image input. A video's <attached-file> tag
++ * always stays in the text, so an engine that reads files still gets its path; sampled frames only add to it.
++ */
export function extractTurnImages(
text: string,
options: ExtractTurnImagesOptions = {},
@@@ -132,44 -108,23 +135,37 @@@
const attachmentsDir = options.attachmentsDir ?? ATTACHMENTS_DIR;
const maxCount = options.maxCount ?? TURN_IMAGE_MAX_COUNT;
const maxBytes = options.maxBytes ?? TURN_IMAGE_MAX_BYTES;
- const admitted = imageTagCandidates(text)
+ const maxVideoCount = options.maxVideoCount ?? TURN_VIDEO_MAX_COUNT;
- const maxVideoBytes = options.maxVideoBytes ?? TURN_VIDEO_MAX_BYTES;
+ const candidates = attachmentTagCandidates(text);
+
+ const admittedImages = candidates
+ .filter((tag) => tag.kind === "image")
.map((tag) => ({ tag, image: ownedImage(tag.path, attachmentsDir) }))
.filter((item): item is { tag: TagCandidate; image: TurnImageInput } => item.image !== null);
-
- if (admitted.length > maxCount) {
+ if (admittedImages.length > maxCount) {
throw statusError(413, `Send no more than ${maxCount} images at a time`);
}
- const aggregateBytes = admitted.reduce((total, item) => total + item.image.bytes, 0);
+ const aggregateBytes = admittedImages.reduce((total, item) => total + item.image.bytes, 0);
if (aggregateBytes > maxBytes) {
throw statusError(413, `Attached images exceed ${Math.floor(maxBytes / (1024 * 1024))} MB total`);
}
- const admittedVideos = candidates
++ const videos = candidates
+ .filter((tag) => tag.kind === "file")
- .map((tag) => ({ tag, video: ownedVideo(tag.path, attachmentsDir) }))
- .filter((item): item is { tag: TagCandidate; video: TurnVideoInput } => item.video !== null);
- if (admittedVideos.length > maxVideoCount) {
- throw statusError(413, `Send no more than ${maxVideoCount} video${maxVideoCount === 1 ? "" : "s"} at a time`);
- }
- const aggregateVideoBytes = admittedVideos.reduce((total, item) => total + item.video.bytes, 0);
- if (aggregateVideoBytes > maxVideoBytes) {
- throw statusError(413, `Attached videos exceed ${Math.floor(maxVideoBytes / (1024 * 1024))} MB total`);
- }
++ .map((tag) => ownedVideo(tag.path, attachmentsDir))
++ .filter((video): video is TurnVideoInput => video !== null)
++ .slice(0, maxVideoCount);
+
let providerText = text;
- const removedTags = [...admittedImages.map((item) => item.tag), ...admittedVideos.map((item) => item.tag)]
- .sort((a, b) => b.start - a.start);
- for (const { tag } of admitted.toReversed()) {
- providerText = providerText.slice(0, tag.start) + providerText.slice(tag.end);
- }
- return { text: providerText, images: admitted.map((item) => item.image) };
++ const removedTags = admittedImages.map((item) => item.tag).sort((a, b) => b.start - a.start);
+ for (const tag of removedTags) providerText = providerText.slice(0, tag.start) + providerText.slice(tag.end);
+
- return {
- text: providerText,
- images: admittedImages.map((item) => item.image),
- videos: admittedVideos.map((item) => item.video),
- };
++ return { text: providerText, images: admittedImages.map((item) => item.image), videos };
++}
++
++/** Stills sampled from a message's video, never taking a turn that already carries `earlier` images past its image count. */
++export function videoFramesWithin(earlier: number, videos: readonly TurnVideoInput[]): Promise<TurnImageInput[]> {
++ return videoFrameImages(videos, TURN_IMAGE_MAX_COUNT - earlier);
}
export function extractSteerImages(
diff --cc server/turn-video.test.ts
index 84cb76f037,0000000000..de182944a9
mode 100644,000000..100644
--- a/server/turn-video.test.ts
+++ b/server/turn-video.test.ts
@@@ -1,95 -1,0 +1,103 @@@
+import { execFileSync, spawnSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import type { TurnVideoInput } from "./contracts.ts";
+import { videoFrameImages } from "./turn-video.ts";
+
+function hasFfmpeg(): boolean {
+ try {
+ execFileSync("ffmpeg", ["-version"], { stdio: "ignore" });
+ execFileSync("ffprobe", ["-version"], { stdio: "ignore" });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// These exercise the real ffmpeg/ffprobe on PATH (the same local build OpenMausBot would find), not a fake: this
+// module has nothing to fake ffmpeg's behaviour against. Skipped wherever neither is installed.
+describe.skipIf(!hasFfmpeg())("video frame sampling", () => {
+ const temporary: string[] = [];
+
+ const store = () => {
+ const root = mkdtempSync(join(tmpdir(), "omb-turn-video-"));
+ temporary.push(root);
+ return root;
+ };
+
+ // A generated test pattern, not a sample file in the repo: duration and a readable-by-ffmpeg guarantee come free.
+ const syntheticClip = (root: string, seconds: number): TurnVideoInput => {
+ const path = join(root, "clip.mp4");
+ const result = spawnSync("ffmpeg", [
+ "-f", "lavfi", "-i", `testsrc=duration=${seconds}:size=320x240:rate=5`,
+ "-pix_fmt", "yuv420p", "-y", path,
+ ]);
+ if (result.status !== 0) throw new Error(`fixture ffmpeg failed: ${result.stderr?.toString()}`);
+ return { path, mime: "video/mp4", bytes: 0 };
+ };
+
+ afterEach(() => {
+ for (const path of temporary.splice(0)) rmSync(path, { recursive: true, force: true });
+ });
+
+ it("returns no frames when there is no video", async () => {
+ expect(await videoFrameImages(undefined)).toEqual([]);
+ expect(await videoFrameImages([])).toEqual([]);
+ });
+
+ it("samples frames spaced across the clip, each a valid JPEG tagged as a video frame", async () => {
+ const root = store();
+ const clip = syntheticClip(root, 5);
+
+ const frames = await videoFrameImages([clip]);
+
+ expect(frames).toHaveLength(4);
+ for (const frame of frames) {
+ expect(frame.mime).toBe("image/jpeg");
+ expect(frame.source).toBe("video-frame");
+ const bytes = readFileSync(frame.path);
+ expect(bytes.length).toBe(frame.bytes);
+ expect(bytes.subarray(0, 3)).toEqual(Buffer.from([0xff, 0xd8, 0xff]));
+ }
+ // Each frame is its own file, not the same still repeated.
+ expect(new Set(frames.map((frame) => frame.path)).size).toBe(4);
+ });
+
+ it("samples fewer frames from a clip shorter than the usual frame count", async () => {
+ const root = store();
+ const clip = syntheticClip(root, 2);
+
+ const frames = await videoFrameImages([clip]);
+
+ expect(frames).toHaveLength(2);
+ });
+
++ it("stops at the frame limit, and samples nothing when the turn has no room left", async () => {
++ const root = store();
++ const clip = syntheticClip(root, 5);
++
++ expect(await videoFrameImages([clip], 3)).toHaveLength(3);
++ expect(await videoFrameImages([clip], 0)).toEqual([]);
++ });
++
+ it("never follows a playlist named as a video to the files it points at", async () => {
+ const root = store();
+ const clip = spawnSync("ffmpeg", ["-f", "lavfi", "-i", "testsrc=duration=2:size=320x240:rate=5", "-pix_fmt", "yuvj420p", "-y", join(root, "clip.mp4")]);
+ if (clip.status !== 0) throw new Error(`fixture ffmpeg failed: ${clip.stderr?.toString()}`);
+ const path = join(root, "disguised.mp4");
+ writeFileSync(path, "ffconcat version 1.0\nfile 'clip.mp4'\nduration 2\n");
+
+ await expect(videoFrameImages([{ path, mime: "video/mp4", bytes: 0 }])).resolves.toEqual([]);
+ });
+
+ it("drops a video ffmpeg cannot read instead of failing the turn", async () => {
+ const root = store();
+ const notAVideo: TurnVideoInput = { path: join(root, "missing.mp4"), mime: "video/mp4", bytes: 0 };
+
+ await expect(videoFrameImages([notAVideo])).resolves.toEqual([]);
+ });
+});
diff --cc server/turn-video.ts
index e6a863c062,0000000000..53a4cfa01c
mode 100644,000000..100644
--- a/server/turn-video.ts
+++ b/server/turn-video.ts
@@@ -1,108 -1,0 +1,110 @@@
+// No model here speaks video natively (OpenAI's chat-completions content parts are only "text" and "image_url",
+// and a local vision model takes the same two); ffmpeg on PATH stands in by sampling stills from the clip.
+import { spawn } from "node:child_process";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import type { TurnImageInput, TurnVideoInput } from "./contracts.ts";
+
+export const VIDEO_SAMPLE_FRAME_COUNT = 4;
+const FFPROBE_TIMEOUT_MS = 10_000;
+const FFMPEG_TIMEOUT_MS = 20_000;
+// Generous past any driver's turn timeout, so a slow tool loop still finds its frames; this is a leak bound, not a lease.
+const FRAME_CLEANUP_DELAY_MS = 10 * 60 * 1000;
+
+// Security invariant: an attachment comes from anyone who can reach a bot, and ffmpeg otherwise picks its reader from the
+// file's contents, so a playlist named .mp4 could read other files or the network into a frame the model sees.
+const VIDEO_READER: Record<TurnVideoInput["mime"], readonly string[]> = {
+ "video/mp4": ["-protocol_whitelist", "file", "-f", "mov"],
+ "video/quicktime": ["-protocol_whitelist", "file", "-f", "mov"],
+ "video/webm": ["-protocol_whitelist", "file", "-f", "matroska"],
+};
+
+function run(command: string, args: readonly string[], timeoutMs: number): Promise<string> {
+ return new Promise((resolvePromise, reject) => {
+ const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
+ let stdout = "";
+ let stderr = "";
+ let settled = false;
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ child.kill();
+ reject(new Error(`${command} timed out`));
+ }, timeoutMs);
+ child.stdout.on("data", (chunk: Buffer) => { stdout += chunk; });
+ child.stderr.on("data", (chunk: Buffer) => { stderr += chunk; });
+ child.on("error", (error) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ reject(error);
+ });
+ child.on("close", (code) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (code === 0) resolvePromise(stdout);
+ else reject(new Error(`${command} exited with code ${code}: ${stderr.trim().slice(-500)}`));
+ });
+ });
+}
+
+async function videoDurationSeconds(video: TurnVideoInput): Promise<number> {
+ const stdout = await run(
+ "ffprobe",
+ ["-v", "error", ...VIDEO_READER[video.mime], "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", video.path],
+ FFPROBE_TIMEOUT_MS,
+ );
+ const seconds = Number(stdout.trim());
+ if (!Number.isFinite(seconds) || seconds <= 0) throw new Error("ffprobe could not read this video's duration");
+ return seconds;
+}
+
+async function extractFrame(video: TurnVideoInput, atSeconds: number, outPath: string): Promise<void> {
+ await run("ffmpeg", [
+ "-ss", atSeconds.toFixed(3),
+ ...VIDEO_READER[video.mime],
+ "-i", video.path,
+ "-frames:v", "1",
+ "-q:v", "4",
+ "-vf", "scale='min(1024,iw)':-2",
+ "-y", outPath,
+ ], FFMPEG_TIMEOUT_MS);
+}
+
+/**
+ * Samples a handful of evenly spaced stills from an attached video so a model with only image input can see what
+ * it contains. Frames live in their own temp directory, cleaned up on a delay rather than right after this call,
- * since the caller's driver still has to read each frame's path off disk later in the same turn.
++ * since the caller's driver still has to read each frame's path off disk later in the same turn. `limit` caps the
++ * frames returned, so a turn's pictures plus frames never pass its image count.
+ */
- export async function videoFrameImages(videos: readonly TurnVideoInput[] | undefined): Promise<TurnImageInput[]> {
- if (!videos?.length) return [];
++export async function videoFrameImages(videos: readonly TurnVideoInput[] | undefined, limit = Infinity): Promise<TurnImageInput[]> {
++ if (!videos?.length || limit <= 0) return [];
+ const frames: TurnImageInput[] = [];
+ for (const video of videos) {
++ if (frames.length >= limit) break;
+ let dir: string | undefined;
+ try {
+ const duration = await videoDurationSeconds(video);
- const count = Math.min(VIDEO_SAMPLE_FRAME_COUNT, Math.max(1, Math.ceil(duration)));
++ const count = Math.min(VIDEO_SAMPLE_FRAME_COUNT, Math.max(1, Math.ceil(duration)), limit - frames.length);
+ dir = await mkdtemp(join(tmpdir(), "omb-video-frame-"));
+ for (let index = 0; index < count; index += 1) {
+ const atSeconds = (duration * (index + 0.5)) / count;
+ const outPath = join(dir, `frame-${index}.jpg`);
+ await extractFrame(video, atSeconds, outPath);
+ const bytes = await readFile(outPath);
+ frames.push({ path: outPath, mime: "image/jpeg", bytes: bytes.byteLength, source: "video-frame" });
+ }
+ } catch {
+ // ffmpeg/ffprobe missing, or a container this build cannot decode: the turn proceeds without this video's frames.
+ } finally {
+ if (dir) {
+ const cleanup = dir;
+ setTimeout(() => { void rm(cleanup, { recursive: true, force: true }); }, FRAME_CLEANUP_DELAY_MS);
+ }
+ }
+ }
+ return frames;
+}