Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(antigravity): let Gemini bots see and hear media named in a message
kengnattakit100726d8c624
diff --git a/server/drivers/acp/acp.test.ts b/server/drivers/acp/acp.test.tsindex 31657c7493..62a9e0913a 100644--- a/server/drivers/acp/acp.test.ts+++ b/server/drivers/acp/acp.test.ts@@ -14,6 +14,7 @@ import { publishedMessages } from "../../harness/text-items.testkit.ts";import { promptSplitFingerprints, writePromptSplitReceipt } from "../prompt-split.ts";import { classifyError } from "../retry.ts";import { createAcpDriver, skipSubscriptionAuthForLocalInject, type AcpSupport } from "./core.ts";+import { acpMediaUri } from "./media-links.ts";import { DEFAULT_ACP_PROMPT_IDLE_MS } from "./quiet-status.ts";import { GrokAgentDriver, grokAcceptsUnadvertisedImages } from "./grok.ts";import { openCodePromptUnreachedModel } from "./opencode-go.ts";@@ -54,6 +55,13 @@ const NativeImageDriver = createAcpDriver({images: true,});+/** Media named in the turn text is a per-harness opt-in for agents that read a linked file themselves. */+const MediaLinksDriver = createAcpDriver({+ ...SELECT_MODEL_SUPPORT,+ driverKind: "mediaLinksTest",+ mediaLinks: true,+});+const EnvPolicyDriver = createAcpDriver({...SELECT_MODEL_SUPPORT,driverKind: "envPolicyTest",@@ -480,6 +488,27 @@ describe("ACP turns (fake CLI)", () => {expect(nativeLog).toContain(`[image data: ${base64.length} base64 chars]`);});+ it("links local media named in the turn text as resource_link blocks the agent reads itself", async () => {+ const dump = join(scratch, "media-link-prompt.json");+ const clipPath = join(scratch, "media link clip.mp4");+ writeFileSync(clipPath, Buffer.from("private-acp-video-bytes"));+ process.env.FAKE_ACP_DUMP = dump;+ process.env.FAKE_ACP_DUMP_PROMPT = "1";+ await create(MediaLinksDriver);++ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-acp-media-link", text: `What happens in ${clipPath}?` });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);++ const prompt = JSON.parse(readFileSync(`${dump}.prompt.json`, "utf8"));+ expect(prompt).toEqual([+ { type: "text", text: expect.stringContaining(`What happens in ${clipPath}?++(OpenMausBot attached these files`) },+ { type: "resource_link", uri: acpMediaUri(clipPath), name: "media link clip.mp4" },+ ]);+ expect(JSON.stringify(prompt)).not.toContain("private-acp-video-bytes");+ });+it("delivers the full prompt once per native session and rides volatile changes as notes", async () => {const dump = join(scratch, "acp-prompt-split.json");process.env.FAKE_ACP_DUMP = dump;diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 5e35ad53b7..1d15f776c7 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -21,7 +21,7 @@ import { deletePromptSplitReceipt, promptHalves, readPromptSplitReceipt, splitSeimport type { PromptSplitReceipt } from "../prompt-split.ts";import { boxAudienceKey, describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../../engine-stop.ts";import { runAcpOneShot } from "./background-text.ts"; import type { OpenCodeBackgroundWork } from "./opencode-background.ts";-import { acpCapabilities } from "./capabilities.ts";+import { acpCapabilities } from "./capabilities.ts"; import { readAcpMediaLinks } from "./media-links.ts";import { acpNativeLogMessage } from "./tool-log.ts";import { stripLeakedSystemHarnessMessages } from "../../../shared/system-message-guard.ts";import {@@ -1389,7 +1389,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>: promptInput.text;const imageBlocks = support.images === true && runtimeAcceptsImages? await readAcpImageBlocks(turn.images ?? [])- : [];+ : []; const media = await readAcpMediaLinks(support.mediaLinks === true && !turn.guestConfined ? promptTurn.text : "");if (support.modelVariants && !modelControls.confirms(cliTurn.model)) {throw new Error(`${support.displayName} changed model before the prompt`);}@@ -1403,7 +1403,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>const quiet = startQuietWatch(threadId, session, current);const result = await request("session/prompt",- { sessionId, prompt: [{ type: "text", text }, ...imageBlocks] },+ { sessionId, prompt: [{ type: "text", text: text + media.note }, ...imageBlocks, ...media.blocks] },undefined,undefined,promptIdleMs,diff --git a/server/drivers/acp/driver-hooks.ts b/server/drivers/acp/driver-hooks.tsindex 22f85d44ee..047d224693 100644--- a/server/drivers/acp/driver-hooks.ts+++ b/server/drivers/acp/driver-hooks.ts@@ -5,6 +5,9 @@ import type { ChildProcess } from "node:child_process";import type { AcpHost } from "./host.ts";export interface AcpDriverHooks {+ /** Local video, image, audio and PDF files named in the turn text go to the model as `resource_link` blocks+ * the agent reads itself, for an agent whose own file tool returns media as raw bytes (Antigravity). */+ mediaLinks?: boolean;/** An agent that asks for a sign-in no turn can give. Its turns fail at once with `loginNote`, its process is closed* and `required` is told, instead of the turn waiting on a sign-in nobody sees. */signInRequest?: {diff --git a/server/drivers/acp/media-links.test.ts b/server/drivers/acp/media-links.test.tsnew file mode 100644index 0000000000..6c4f9eece0--- /dev/null+++ b/server/drivers/acp/media-links.test.ts@@ -0,0 +1,51 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, describe, expect, it } from "vitest";++import { acpMediaUri, findMediaPaths, readAcpMediaLinks } from "./media-links.ts";++const scratch = mkdtempSync(join(tmpdir(), "omb-media-links-"));+const folder = join(scratch, "a folder");+mkdirSync(folder);+const clip = join(folder, "clip one.mp4");+const photo = join(scratch, "photo.png");+const big = join(scratch, "big.mov");+writeFileSync(clip, Buffer.alloc(300));+writeFileSync(photo, Buffer.alloc(200));+writeFileSync(big, Buffer.alloc(900));+afterAll(() => rmSync(scratch, { recursive: true, force: true }));++describe("acpMediaUri", () => {+ it("keeps the drive letter out of the path on Windows and percent-encodes the rest", () => {+ expect(acpMediaUri("D:\\a b\\c.mp4", "win32")).toBe("file:D:/a%20b/c.mp4");+ expect(acpMediaUri("/Users/k/a b.png", "darwin")).toBe("file:///Users/k/a%20b.png");+ });+});++describe("findMediaPaths", () => {+ it("finds existing files named in text, with spaces in the path, quoted or at a sentence end, once each", async () => {+ const text = `Watch ${clip} and summarize.\nAlso "${photo}", https://example.com/x.mp4, ${join(scratch, "missing.mp4")}.\nAgain ${clip}`;+ expect((await findMediaPaths(text)).map((file) => file.path)).toEqual([clip, photo]);+ });++ it("ignores text without media", async () => {+ expect(await findMediaPaths("see notes.md and https://example.com/a.png")).toEqual([]);+ });+});++describe("readAcpMediaLinks", () => {+ it("links files within the budget and names the ones left out", async () => {+ const { blocks, note } = await readAcpMediaLinks(`${clip}\n${big}\n${photo}`, 600);+ expect(blocks).toEqual([+ { type: "resource_link", uri: acpMediaUri(clip), name: "clip one.mp4" },+ { type: "resource_link", uri: acpMediaUri(photo), name: "photo.png" },+ ]);+ expect(note).toContain(`attached these files to this message so you can see and hear them directly; do not open them with a file tool: ${clip} | ${photo}`);+ expect(note).toContain(`Not attached: ${big} (0.0 MB)`);+ });++ it("adds nothing when the text names no media", async () => {+ expect(await readAcpMediaLinks("no media here")).toEqual({ blocks: [], note: "" });+ });+});diff --git a/server/drivers/acp/media-links.ts b/server/drivers/acp/media-links.tsnew file mode 100644index 0000000000..200d7b8146--- /dev/null+++ b/server/drivers/acp/media-links.ts@@ -0,0 +1,88 @@+// Antigravity's ACP server replaces the harness view_file with a text-only reader, so a bot that opens an mp4,+// png or mp3 from its tools gets raw bytes and the model sees nothing. A `resource_link` prompt block is read+// by the server itself (agy_acp_server types.from_file) and reaches the model as real video, image, audio or+// PDF. This finds existing local media files named in the turn text and returns those blocks plus a short note.+import { stat } from "node:fs/promises";++export interface AcpResourceLink {+ type: "resource_link";+ uri: string;+ name: string;+}++export interface AcpMediaLinks {+ blocks: AcpResourceLink[];+ /** Appended to the prompt text: what was attached, and what was too large to be. Empty when nothing was named. */+ note: string;+}++const MEDIA_EXTENSIONS = "mp4|m4v|mov|webm|mpeg|mpg|avi|wmv|flv|3gp|mp3|wav|aac|ogg|oga|flac|opus|jpg|jpeg|png|webp|bmp|pdf";+// A name ends at the extension, before whitespace, a quote, closing punctuation or a sentence's full stop.+const MEDIA_END = new RegExp(`\\.(?:${MEDIA_EXTENSIONS})(?=$|[\\s"'\`)\\]>,;:!?]|\\.(?:\\s|$))`, "giu");+// A path starts at a drive letter, or at a slash after whitespace, a quote or an opening bracket.+const PATH_START = /[A-Za-z]:[\\/]|(?<=^|[\s"'`(<[=])\//gu;++/** Measured against agy_acp_server 1.8: one 14.5 MB mp4 is answered; two in one prompt (29 MB) end the turn+ * with "trajectory converted to zero chat messages". */+export const ACP_MEDIA_MAX_BYTES = 19 * 1024 * 1024;+export const ACP_MEDIA_MAX_FILES = 8;++/** Google's server turns a link into a path with urlparse().path: on Windows `file:///D:/x` gives "/D:/x",+ * which does not open, while `file:D:/x` gives "D:/x". */+export function acpMediaUri(path: string, platform: NodeJS.Platform = process.platform): string {+ const encoded = path.replaceAll("\\", "/").split("/").map(encodeURIComponent).join("/");+ return platform === "win32" ? `file:${encoded.replace(/^([A-Za-z])%3A/u, "$1:")}` : `file://${encoded}`;+}++/** Existing local media files named in `text`, in order and without repeats. Spaces in a path are allowed:+ * each candidate start on the line is tried from the nearest, and the first that names a file wins. */+export async function findMediaPaths(text: string): Promise<Array<{ path: string; size: number }>> {+ const found: Array<{ path: string; size: number }> = [];+ const seen = new Set<string>();+ for (const match of text.matchAll(MEDIA_END)) {+ if (found.length >= ACP_MEDIA_MAX_FILES * 2) break;+ const end = match.index + match[0].length;+ const line = text.slice(text.lastIndexOf("\n", match.index) + 1, end);+ const starts = [...line.matchAll(PATH_START)].map((start) => start.index).reverse();+ for (const start of starts) {+ const path = line.slice(start).trim();+ const key = path.toLowerCase().replaceAll("\\", "/");+ if (seen.has(key)) break;+ const info = await stat(path).catch(() => null);+ if (info?.isFile()) {+ seen.add(key);+ found.push({ path, size: info.size });+ break;+ }+ }+ }+ return found;+}++/** Prompt blocks for the media named in `text`, within one prompt's budget, and a note saying what was and was not attached. */+export async function readAcpMediaLinks(text: string, budget = ACP_MEDIA_MAX_BYTES): Promise<AcpMediaLinks> {+ const blocks: AcpResourceLink[] = [];+ const attached: string[] = [];+ const skipped: Array<{ path: string; size: number }> = [];+ let total = 0;+ for (const file of await findMediaPaths(text)) {+ if (attached.length < ACP_MEDIA_MAX_FILES && total + file.size <= budget) {+ total += file.size;+ attached.push(file.path);+ blocks.push({ type: "resource_link", uri: acpMediaUri(file.path), name: file.path.split(/[\\/]/u).pop() ?? file.path });+ } else {+ skipped.push(file);+ }+ }+ let note = "";+ if (attached.length) {+ note += `\n\n(OpenMausBot attached these files to this message so you can see and hear them directly; do not open them with a file tool: ${attached.join(" | ")})`;+ }+ if (skipped.length) {+ const limitMb = Math.floor(budget / 1048576);+ note += `\n\n(Not attached: ${skipped.map((file) => `${file.path} (${(file.size / 1048576).toFixed(1)} MB)`).join(" | ")}.` ++ ` One message carries at most ${limitMb} MB of media and a file tool cannot show media, so you cannot see these.` ++ ` Say so plainly; to view one, shrink or split it into parts of ${limitMb} MB or less and ask to have each part sent in its own message.)`;+ }+ return { blocks, note };+}diff --git a/server/drivers/antigravity.ts b/server/drivers/antigravity.tsindex 931bbd7bf1..a88aae4695 100644--- a/server/drivers/antigravity.ts+++ b/server/drivers/antigravity.ts@@ -117,6 +117,7 @@ const support: AcpSupport = {: {}),},images: true,+ mediaLinks: true,spawnArgs: () => [],selectModel: { configId: "model" },modelVariants: true,