Skip to content

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

feat(video-input): sample attached videos into frames for vision models

nickl524ec79d6207
diff --git a/server/contracts.ts b/server/contracts.ts
index 73d583e41f..50fc0386c1 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -87,6 +87,15 @@ export interface TurnImageInput {
path: string;
mime: "image/png" | "image/jpeg" | "image/gif" | "image/webp";
bytes: number;
+ /** Set on a frame sampled from an attached video, so a content-type router can tell it apart from a person's own picture. */
+ source?: "video-frame";
+}
+
+/** A video already admitted to the private attachment store; resolved into TurnImageInput frames before any driver sees it. */
+export interface TurnVideoInput {
+ path: string;
+ mime: "video/mp4" | "video/webm" | "video/quicktime";
+ bytes: number;
}
// `driver` is any slug: an unknown driver round-trips as an unavailable shadow snapshot.
diff --git a/server/index.ts b/server/index.ts
index 6a9f2fae23..e418f72753 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -328,6 +328,7 @@ import { TurnStops, outwardActions, stoppedTurnOutcome, turnEvidence } from "./t
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 { callTitleExcerpt } from "./thread-title.ts";
import { generateThreadTitle, llmThreadTitlesEnabled } from "./thread-title-generate.ts";
import { stallLimitMs, TurnWatchdog } from "./turn-watchdog.ts";
@@ -7754,7 +7755,9 @@ async function startTurn(
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 : [];
+ const turnImages = usesNativeImageInput
+ ? [...resolvedImages.images, ...(await videoFrameImages(resolvedImages.videos))]
+ : [];
const commsDepth = opts?.commsDepth ?? 0;
if (commsDepth > 0) markInternalTurn(threadId);
else clearInternalTurn(threadId);
@@ -9896,6 +9899,7 @@ async function runClaimedGroupMemberTurn(
const burstIds = new Set(operation?.queuedQueueIds ?? []);
const burstOverrides: Array<{ messageId: string; text: string }> = [];
const burstImages: ReturnType<typeof extractTurnImages>["images"] = [];
+ const burstVideos: ReturnType<typeof extractTurnImages>["videos"] = [];
if (usesNativeImageInput && !cardContinuation) {
for (const message of store.activePath(threadId)) {
if (message.role !== "user" || message.kind !== "text" || !message.text) continue;
@@ -9903,13 +9907,14 @@ async function runClaimedGroupMemberTurn(
const resolved = extractTurnImages(message.text);
burstOverrides.push({ messageId: message.id, text: resolved.text });
burstImages.push(...resolved.images);
+ burstVideos.push(...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: [] };
+ : { text: latestUser?.text ?? "", images: [], videos: [] };
const roomWindow = roomTranscript.window(
threadId,
userName,
@@ -9922,7 +9927,9 @@ async function runClaimedGroupMemberTurn(
bot.id,
);
const roomContext = roomWindow.text;
- const turnImages = usesNativeImageInput ? [...burstImages, ...resolvedLatestImages.images] : [];
+ const turnImages = usesNativeImageInput
+ ? [...burstImages, ...resolvedLatestImages.images, ...(await videoFrameImages([...burstVideos, ...resolvedLatestImages.videos]))]
+ : [];
const skills = availableSkills(), phoneOffered = usbPhoneOffered(instance, skills);
const selectedSkills = mergeSkills(
selectBundledSkills(
diff --git a/server/turn-images.test.ts b/server/turn-images.test.ts
index 01f7b0d5dc..45aae980c7 100644
--- a/server/turn-images.test.ts
+++ b/server/turn-images.test.ts
@@ -29,6 +29,12 @@ describe("turn image admission", () => {
return path;
};
+ const video = (root: string, index: number, extension = ".mp4", bytes = 4) => {
+ const path = join(root, `${IDS[index]}${extension}`);
+ writeFileSync(path, Buffer.alloc(bytes, index + 1));
+ return path;
+ };
+
afterEach(() => {
for (const path of temporary.splice(0)) rmSync(path, { recursive: true, force: true });
});
@@ -73,7 +79,7 @@ describe("turn image admission", () => {
`<attached-image path="${ordinary}" />`,
].join("\n");
- expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({ text: source, images: [] });
+ expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({ text: source, images: [], videos: [] });
});
it("decodes composer entities once before validating the exact store path", () => {
@@ -86,9 +92,55 @@ 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", () => {
+ 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",
+ 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.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", () => {
+ 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");
+ });
+
it("rejects count and aggregate limits before partially stripping the prompt", () => {
const root = store();
const first = image(root, 0, ".png", 4);
@@ -111,7 +163,7 @@ describe("turn image admission", () => {
symlinkSync(target, link);
const source = `<attached-image path="${link}" />`;
- expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({ text: source, images: [] });
+ expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({ text: source, images: [], videos: [] });
});
it("resolves a steer's texts one by one and keeps its images in order", () => {
diff --git a/server/turn-images.ts b/server/turn-images.ts
index e06328cecd..8e9333ffdf 100644
--- a/server/turn-images.ts
+++ b/server/turn-images.ts
@@ -3,12 +3,15 @@ import { dirname, extname, resolve } from "node:path";
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";
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_VIDEO_MAX_COUNT = 1;
+export const TURN_VIDEO_MAX_BYTES = FILE_MAX_BYTES;
type MarkdownNode = {
type: string;
@@ -20,12 +23,16 @@ type MarkdownNode = {
};
};
-type TagCandidate = { start: number; end: number; path: string };
+type TagCandidate = { start: number; end: number; kind: "image" | "file"; path: string };
const OWNED_IMAGE_NAME =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.(png|jpg|gif|webp)$/;
-const IMAGE_TAG =
- /^<attached-image[\t ]+path="([^"\r\n]*)"(?:[\t ]+name="([^"\r\n]*)")?[\t ]*\/>$/;
+const OWNED_VIDEO_NAME =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.(mp4|webm|mov)$/;
+// Composer video attachments use the generic <attached-file> tag (the same one documents and audio use); only its
+// path decides whether it resolves to a video, so every other file kind keeps going through unexamined.
+const ATTACHMENT_TAG =
+ /^<attached-(image|file)[\t ]+path="([^"\r\n]*)"(?:[\t ]+name="([^"\r\n]*)")?[\t ]*\/>$/;
const MIME_BY_EXTENSION: Readonly<Record<string, TurnImageInput["mime"]>> = {
".png": "image/png",
@@ -33,6 +40,11 @@ const MIME_BY_EXTENSION: Readonly<Record<string, TurnImageInput["mime"]>> = {
".gif": "image/gif",
".webp": "image/webp",
};
+const VIDEO_MIME_BY_EXTENSION: Readonly<Record<string, TurnVideoInput["mime"]>> = {
+ ".mp4": "video/mp4",
+ ".webm": "video/webm",
+ ".mov": "video/quicktime",
+};
function statusError(status: number, message: string): Error & { status: number } {
return Object.assign(new Error(message), { status });
@@ -49,7 +61,7 @@ function walk(node: MarkdownNode, visit: (node: MarkdownNode) => void): void {
}
/** Standalone tags only: prose that contains a tag literal must not become an attachment capability. */
-function imageTagCandidates(text: string): TagCandidate[] {
+function attachmentTagCandidates(text: string): TagCandidate[] {
const candidates: TagCandidate[] = [];
walk(fromMarkdown(text) as MarkdownNode, (node) => {
if (node.type !== "html" || !node.value || !node.position) return;
@@ -60,70 +72,104 @@ function imageTagCandidates(text: string): TagCandidate[] {
const nextLine = text.indexOf("\n", end);
const lineEnd = nextLine < 0 ? text.length : nextLine;
if (text.slice(lineStart, start).trim() || text.slice(end, lineEnd).trim()) return;
- const match = IMAGE_TAG.exec(node.value);
+ const match = ATTACHMENT_TAG.exec(node.value);
if (!match) return;
- candidates.push({ start, end, path: decodeAttachmentAttribute(match[1]!) });
+ candidates.push({ start, end, kind: match[1] === "file" ? "file" : "image", path: decodeAttachmentAttribute(match[2]!) });
});
return candidates;
}
-function ownedImage(path: string, attachmentsDir: string): TurnImageInput | null {
+function ownedAttachment<Mime extends string>(
+ path: string,
+ attachmentsDir: string,
+ nameFormat: RegExp,
+ mimeByExtension: Readonly<Record<string, Mime>>,
+ maxBytes: number,
+): { path: string; mime: Mime; bytes: number } | null {
if (!path || path.includes("\0")) return null;
const name = path.split(/[\\/]/).at(-1) ?? "";
- if (!OWNED_IMAGE_NAME.test(name)) return null;
+ if (!nameFormat.test(name)) return null;
- // A basename match alone would let any /tmp/<uuid>.png pose as an app attachment: the path must point into this store.
+ // A basename match alone would let any /tmp/<uuid>.ext pose as an app attachment: the path must point into this store.
const expected = resolve(attachmentsDir, name);
if (resolve(path) !== expected) return null;
try {
const entry = lstatSync(expected);
- if (!entry.isFile() || entry.isSymbolicLink() || entry.size <= 0 || entry.size > IMAGE_MAX_BYTES) return null;
+ if (!entry.isFile() || entry.isSymbolicLink() || entry.size <= 0 || entry.size > maxBytes) return null;
const canonicalRoot = realpathSync(attachmentsDir);
const canonicalFile = realpathSync(expected);
if (dirname(canonicalFile) !== canonicalRoot) return null;
const finalEntry = statSync(canonicalFile);
if (!finalEntry.isFile() || finalEntry.size !== entry.size) return null;
- const mime = MIME_BY_EXTENSION[extname(name)];
+ const mime = mimeByExtension[extname(name)];
return mime ? { path: expected, mime, bytes: entry.size } : null;
} catch {
return null;
}
}
+const ownedImage = (path: string, attachmentsDir: string): TurnImageInput | null =>
+ ownedAttachment(path, attachmentsDir, OWNED_IMAGE_NAME, MIME_BY_EXTENSION, IMAGE_MAX_BYTES);
+const ownedVideo = (path: string, attachmentsDir: string): TurnVideoInput | null =>
+ ownedAttachment(path, attachmentsDir, OWNED_VIDEO_NAME, VIDEO_MIME_BY_EXTENSION, FILE_MAX_BYTES);
+
export interface ExtractTurnImagesOptions {
attachmentsDir?: string;
maxCount?: number;
maxBytes?: number;
+ maxVideoCount?: number;
+ maxVideoBytes?: number;
}
-/** 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 or video input. */
export function extractTurnImages(
text: string,
options: ExtractTurnImagesOptions = {},
-): { text: string; images: TurnImageInput[] } {
- if (!text.includes("<attached-image")) return { text, images: [] };
+): { text: string; images: TurnImageInput[]; videos: TurnVideoInput[] } {
+ if (!text.includes("<attached-image") && !text.includes("<attached-file")) return { text, images: [], videos: [] };
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`);
}
- let providerText = text;
- for (const { tag } of admitted.toReversed()) {
- providerText = providerText.slice(0, tag.start) + providerText.slice(tag.end);
+ const admittedVideos = 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`);
}
- return { text: providerText, images: admitted.map((item) => item.image) };
+ 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`);
+ }
+
+ 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 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),
+ };
}
export function extractSteerImages(
diff --git a/server/turn-video.test.ts b/server/turn-video.test.ts
new file mode 100644
index 0000000000..c7ad23c220
--- /dev/null
+++ b/server/turn-video.test.ts
@@ -0,0 +1,85 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import { mkdtempSync, readdirSync, readFileSync, rmSync } 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("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 --git a/server/turn-video.ts b/server/turn-video.ts
new file mode 100644
index 0000000000..6c755b8d3c
--- /dev/null
+++ b/server/turn-video.ts
@@ -0,0 +1,99 @@
+// 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;
+
+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"] });
+ 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(path: string): Promise<number> {
+ const stdout = await run(
+ "ffprobe",
+ ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", 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(videoPath: string, atSeconds: number, outPath: string): Promise<void> {
+ await run("ffmpeg", [
+ "-ss", atSeconds.toFixed(3),
+ "-i", videoPath,
+ "-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.
+ */
+export async function videoFrameImages(videos: readonly TurnVideoInput[] | undefined): Promise<TurnImageInput[]> {
+ if (!videos?.length) return [];
+ const frames: TurnImageInput[] = [];
+ for (const video of videos) {
+ let dir: string | undefined;
+ try {
+ const duration = await videoDurationSeconds(video.path);
+ const count = Math.min(VIDEO_SAMPLE_FRAME_COUNT, Math.max(1, Math.ceil(duration)));
+ 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.path, 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;
+}