Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Send an attached video to the Gemini API engine as the clip itself
AdityaUmale0162a45a7d95
diff --git a/server/contracts.ts b/server/contracts.tsindex 5b40b99f6b..0e50ee978d 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; resolved into TurnImageInput frames before any driver sees it. */+/** A video already admitted to the private attachment store; a driver gets it as the clip only within its `nativeVideoBytes`, otherwise as TurnImageInput frames. */export interface TurnVideoInput {path: string;mime: "video/mp4" | "video/webm" | "video/quicktime";@@ -142,6 +142,8 @@ export interface SendTurnInput {confinedWhy?: string;/** Images for this user turn only; kept out of replay transcripts. */images?: TurnImageInput[];+ /** Video clips for this user turn only, sent as they are; set only for a driver with `capabilities.nativeVideoBytes`. */+ videos?: TurnVideoInput[];model?: string;effort?: EffortLevel;variant?: string;@@ -275,6 +277,8 @@ 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. */+ nativeVideoBytes?: number;/** Effort levels the driver can pass to its CLI, ascending; absent hides the control. */effortLevels?: readonly EffortLevel[];/** The driver validates and applies model-specific variant IDs per session. */diff --git a/server/drivers/chat-images.ts b/server/drivers/chat-images.tsindex 1bad978fbb..272d23a3cb 100644--- a/server/drivers/chat-images.ts+++ b/server/drivers/chat-images.ts@@ -1,5 +1,5 @@import { readFileSync, statSync } from "node:fs";-import type { SendTurnInput } from "../contracts.ts";+import type { SendTurnInput, TurnVideoInput } from "../contracts.ts";export interface ChatImagePart { type: "image_url"; image_url: { url: string } }export interface ChatTextPart { type: "text"; text: string }@@ -43,15 +43,23 @@ export function chatImage(item: { mimeType?: unknown; data?: unknown }): ChatImareturn { type: "image_url", image_url: { url: `data:${mimeType};base64,${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" };+export function chatUserContent(turn: SendTurnInput): string | ChatContentPart[] {- if (!turn.images?.length) return turn.text;+ if (!turn.images?.length && !turn.videos?.length) return turn.text;const budget = chatImageBudget();- return [{ type: "text", text: turn.text }, ...turn.images.map(image => {+ const parts = [...(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")}` } };+ budget([part]);+ return part;})];+ return [{ type: "text", text: turn.text }, ...parts];}export function chatToolImages(callId: string, images?: ChatImagePart[]): ChatContentPart[] {diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 1b6b611a61..9b500f79da 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -113,7 +113,7 @@ interface RuntimeOptions<Config> {tools?: boolean;computerUse?: boolean;/** A text-only model keeps the computer and browser tools but never receives a screenshot or attachment. */- imageInput?: (model: string) => boolean;+ imageInput?: (model: string) => boolean; /** Bytes of video clips a turn may send as they are; unset sends frames. */ videoBytes?: number;/** Some models list `variants`; the picked one reaches `requestBody`. */ modelVariants?: boolean;/** False for a model its server says cannot call tools: its turns go without them instead of being refused. */ toolUse?: (model: string) => boolean;/** Why the server cannot answer now (not running, nothing to run), asked before the key is. */@@ -488,7 +488,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const volatile = halves.volatile.trim();const note = halves.stable === null || (!turn.mentionTurn && replay.volatile === volatile) ? "": volatileContextNote(volatile, Boolean(replay.volatile));- const textOnly = (text: string) => !options.computerUse || seesImages(turn) || !turn.images?.length ? text+ const textOnly = (text: string) => !options.computerUse || seesImages(turn) || !(turn.images?.length || turn.videos?.length) ? text: `${text}\n\n${TEXT_ONLY_ATTACHMENT_NOTE}`;const userTurn = note ? { ...turn, text: withContextNote(note, turn.text) } : turn;const content = options.computerUse && seesImages(turn) ? chatUserContent(userTurn) : textOnly(userTurn.text);@@ -948,9 +948,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)},adapter: {provider: options.driverKind,- capabilities: { ...(options.computerUse ? { computerMcp: options.tools !== false,- localComputerMcp: options.tools !== false,- browserMcp: options.tools !== false, nativeImageInput: true, images: true } : {}),+ capabilities: { ...(options.computerUse ? { computerMcp: options.tools !== false, localComputerMcp: options.tools !== false,+ browserMcp: options.tools !== false, nativeImageInput: true, images: true, ...(options.videoBytes ? { nativeVideoBytes: options.videoBytes } : {}) } : {}),...(options.modelVariants ? { modelVariants: true } : {}), sessionModelSwitch: "in-session", customMcp: options.tools !== false, agentsMcp: options.tools !== false, composioMcp: options.tools !== false,dataMcp: options.tools !== false,emailMcp: options.tools !== false,diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.tsindex 782726f0df..1a6c215f64 100644--- a/server/drivers/openai-compat.test.ts+++ b/server/drivers/openai-compat.test.ts@@ -1,3 +1,7 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { recordEvents } from "../testing/events.ts";import { buildTurnContext, replaysNatively } from "../turn-context.ts";@@ -157,6 +161,42 @@ describe("OpenAICompatDriver", () => {await inst.dispose();});+ it("sends an attached video to Gemini as the clip itself, and to no other server", async () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-gemini-video-"));+ const clip = join(dir, "clip.mp4");+ writeFileSync(clip, Buffer.from("00000018667479706d703432", "hex"));+ const bodies: string[] = [];+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ if (String(input).endsWith("/models")) return Response.json({ data: [{ id: "models/gemini-2.5-flash" }] });+ bodies.push(String(init?.body));+ return new Response('data: {"choices":[{"index":0,"delta":{"content":"seen"},"finish_reason":"stop"}]}\n\n', { headers: { "content-type": "text/event-stream" } });+ }));+ const gemini = await OpenAICompatDriver.create({+ instanceId: "gemini-video", displayName: "Google Gemini", enabled: true,+ config: OpenAICompatDriver.decodeConfig({ url: "https://generativelanguage.googleapis.com/v1beta/openai", key: "gemini-fixture" }),+ environment: {},+ });+ const proxy = await OpenAICompatDriver.create({+ instanceId: "proxy-video", displayName: "Proxy", enabled: true,+ config: OpenAICompatDriver.decodeConfig({ url: "https://llm.example.com/v1", key: "sk-fixture" }), environment: {},+ });+ try {+ expect(gemini.adapter.capabilities.nativeVideoBytes).toBeGreaterThan(0);+ expect(proxy.adapter.capabilities.nativeVideoBytes).toBeUndefined();+ const recorder = recordEvents(gemini.adapter);+ await gemini.adapter.sendTurn({ threadId: "video", text: "What happens in this clip?", model: "gemini-2.5-flash",+ videos: [{ path: clip, mime: "video/mp4", bytes: 12 }] });+ await recorder.until((event) => event.type === "turn.completed");+ recorder.stop();+ const content = JSON.parse(bodies[0]!).messages.at(-1).content;+ expect(content).toContainEqual({ type: "image_url", image_url: { url: `data:video/mp4;base64,${readFileSync(clip).toString("base64")}` } });+ } finally {+ await gemini.dispose();+ await proxy.dispose();+ rmSync(dir, { recursive: true, force: true });+ }+ });+it("keeps other servers' model IDs as they list them", async () => {vi.stubGlobal("fetch", vi.fn(async () => Response.json({ data: [{ id: "models/gemini-2.5-pro" }, { id: "text-embedding-3-small" }] })));const inst = await OpenAICompatDriver.create({diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex 8b02d46c67..8e93e89df0 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -67,6 +67,9 @@ const OPENAI_MODELS: ModelCatalog = {],};+/** Gemini takes a clip inline in the request; a larger one keeps going as sampled frames. */+const GEMINI_VIDEO_BYTES = 12 * 1024 * 1024;+/** Google's Gemini API, added as an OpenAI-compatible server (Settings → API keys → Other). */function isGeminiOrigin(url: string): boolean {try {@@ -402,6 +405,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {selectedReasoning: (model, variant) => Boolean(variant && fact(model)?.thinking?.choices.includes(variant)),refreshModels: fetchModels,imageInput: (model) => fact(model)?.vision ?? true,+ ...(gemini ? { videoBytes: GEMINI_VIDEO_BYTES } : {}),toolUse: (model) => fact(model)?.tools ?? true,...(ollamaCandidate ? {serverUnavailable: async () => {diff --git a/server/index.ts b/server/index.tsindex 36d0d7c3b8..a48ae28a0c 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, videoFramesWithin } from "./turn-images.ts";+import { extractReplayImages, extractTurnImages, nativeClips, 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 : [];+ const turnImages = usesNativeImageInput ? resolvedImages.images : [], turnVideos = opts?.compactOnly ? [] : nativeClips(resolvedImages.videos, instance.adapter.capabilities);const commsDepth = opts?.commsDepth ?? 0;if (commsDepth > 0) markInternalTurn(threadId);else { clearInternalTurn(threadId); doneNotice.personTurnStarted(threadId); }@@ -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));+ if (usesNativeImageInput && !opts?.compactOnly) turnImages.push(...await videoFramesWithin(turnImages.length, resolvedImages.videos, turnVideos));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");@@ -7844,7 +7844,7 @@ async function beginTurn(const windowIds = selection.representedIds;return {turnText: withUnseenMessages(unseenBlock, contextTurnText),- images: contextTurnText !== userTurnText ? [...replay.images, ...turnImages] : turnImages,+ images: contextTurnText !== userTurnText ? [...replay.images, ...turnImages] : turnImages, videos: turnVideos,resumeCursor, sessionReset: !resume, recoveryText,handoff: strictResume ? {botId: bot.id, instanceId, config, resumeCursor: typeof resumeCursor === "string" ? resumeCursor : undefined,@@ -8406,7 +8406,7 @@ async function beginTurn(startupRecovery,text: withTurnClock(clock, withRecalled(recalled, (posted?.text ?? "") + attachmentsForBox(dispatchContext.turnText, cwd) + shareNote.text + devsReports.note(threadId, Boolean(integrations.agents)) + settingNudges.note(threadId, { tools: Boolean(integrations.agents) && personLine && !opts?.unattended, owner: phones.turnOwner({ botId: bot.id, threadId, generation: dispatchClaimId }) !== null && !cloudGuestDriven(threadId), model: `${instanceId}/${model}` }))),...(recalled ? { recalled } : {}),- images: dispatchContext.images,+ images: dispatchContext.images, videos: dispatchContext.videos,approvalMode: approvalModeForTurn(bot, commsDepth > 0, threadId),approvalModeNow: () => liveApprovalMode(bot, threadId, commsDepth > 0),toolScope,@@ -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"] = [];+ const burstImages: ReturnType<typeof extractTurnImages>["images"] = [], 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;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, ...await videoFramesWithin(burstImages.length + resolved.images.length, resolved.videos));+ burstVideos.push(...nativeClips(resolved.videos, instance.adapter.capabilities, burstVideos)); burstImages.push(...resolved.images, ...await videoFramesWithin(burstImages.length + resolved.images.length, resolved.videos, burstVideos));}}// 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 turnImages = usesNativeImageInput ? [...burstImages, ...resolvedLatestImages.images, ...await videoFramesWithin(burstImages.length + resolvedLatestImages.images.length, resolvedLatestImages.videos)] : [];+ 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 skills = availableSkills(), phoneOffered = HAS_USB_PORT && usbPhoneOffered(instance, skills);const selectedSkills = mergeSkills(selectBundledSkills(@@ -10273,7 +10273,7 @@ async function runClaimedGroupMemberTurn(botId: readyBot.id,text: roomSession.text,...(roomRecalled ? { recalled: roomRecalled } : {}),- images: turnImages,+ images: turnImages, videos: turnVideos,approvalMode: turnApprovalMode,toolScope: roomToolScope,...(roomGuestConfined ? { guestConfined: true, confinedWhy: confinedWhy(threadId) } : {}),diff --git a/server/turn-images.test.ts b/server/turn-images.test.tsindex 2078ba58c5..c0ba2aa145 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, REPLAYED_IMAGE_NOTE } from "./turn-images.ts";+import { extractReplayImages, extractSteerImages, extractTurnImages, nativeClips, REPLAYED_IMAGE_NOTE } from "./turn-images.ts";const IDS = ["123e4567-e89b-42d3-a456-426614174000",@@ -268,3 +268,18 @@ describe("turn image admission", () => {expect(result.transcript.slice(0, 2)).toEqual(transcript.slice(0, 2));});});++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", () => {+ 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)]);+ });++ 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.tsindex a84a63fed0..9936974476 100644--- a/server/turn-images.ts+++ b/server/turn-images.ts@@ -4,7 +4,7 @@ import { dirname, extname, resolve } from "node:path";import { fromMarkdown } from "mdast-util-from-markdown";import { ATTACHMENTS_DIR, FILE_MAX_BYTES, IMAGE_MAX_BYTES } from "./attachments.ts";-import type { TurnImageInput, TurnVideoInput } from "./contracts.ts";+import type { ProviderAdapter, TurnImageInput, TurnVideoInput } from "./contracts.ts";import { decodeAttachmentAttribute } from "./message-file.ts";import { videoFrameImages } from "./turn-video.ts";@@ -173,9 +173,21 @@ export function extractTurnImages(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);+/** The clips an engine that takes video gets as they are: those that fit its byte limit alongside the `taken` ones. */+export function nativeClips(videos: readonly TurnVideoInput[], engine: Pick<ProviderAdapter["capabilities"], "nativeImageInput" | "nativeVideoBytes">,+ taken: readonly TurnVideoInput[] = []): TurnVideoInput[] {+ const limit = engine.nativeImageInput ? engine.nativeVideoBytes ?? 0 : 0;+ let used = taken.reduce((total, clip) => total + clip.bytes, 0);+ return videos.filter((clip) => {+ if (used + clip.bytes > limit) return false;+ used += clip.bytes;+ 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);}export function extractSteerImages(diff --git a/server/turn-video.ts b/server/turn-video.tsindex 0a1d21e73a..8154121e46 100644--- a/server/turn-video.ts+++ b/server/turn-video.ts@@ -1,5 +1,5 @@-// 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.+// 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.import { spawn } from "node:child_process";import { mkdtemp, readFile, rm } from "node:fs/promises";import { tmpdir } from "node:os";