Skip to content

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

fix(acp): attach media another bot handed on by its inbox/... path

AdityaUmaleaca62d47e649
diff --git a/server/drivers/acp/acp.test.ts b/server/drivers/acp/acp.test.ts
index 820923f88e..82623bd9f8 100644
--- a/server/drivers/acp/acp.test.ts
+++ b/server/drivers/acp/acp.test.ts
@@ -510,6 +510,25 @@ describe("ACP turns (fake CLI)", () => {
expect(JSON.stringify(prompt)).not.toContain("private-acp-video-bytes");
});
+ it("links media another bot handed on, named by its inbox/... path in the turn's own folder", async () => {
+ const dump = join(scratch, "media-link-inbox-prompt.json");
+ const folder = join(scratch, "media-link-thread-folder");
+ const handed = join(folder, "inbox", "bot-a", "task-1", "handed clip.mp4");
+ mkdirSync(dirname(handed), { recursive: true });
+ writeFileSync(handed, Buffer.from("private-acp-video-bytes"));
+ process.env.FAKE_ACP_DUMP = dump;
+ process.env.FAKE_ACP_DUMP_PROMPT = "1";
+ await create(MediaLinksDriver);
+
+ const named = join("inbox", "bot-a", "task-1", "handed clip.mp4");
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-acp-media-link-inbox", cwd: folder, text: `Describe the video.\n- ${named} (video/mp4, 1 KB)` });
+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
+
+ const prompt = JSON.parse(readFileSync(`${dump}.prompt.json`, "utf8"));
+ expect(prompt[1]).toEqual({ type: "resource_link", uri: acpMediaUri(handed), name: "handed 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.ts
index c0393b079e..4ce329a9d5 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -22,7 +22,7 @@ import { commitPromptSplitReceipt, deletePromptSplitReceipt, type PendingPromptS
import { liveSessionKey, sessionSystem, turnPrompt } from "./session-system.ts";
import { boxAudienceKey, describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../../engine-stop.ts";
import { applyOneShotEnv, oneShotTurnModel, runAcpOneShot } from "./background-text.ts"; import type { AcpBackgroundWork } from "./background-work.ts";
-import { acpCapabilities } from "./capabilities.ts"; import { readAcpMediaLinks } from "./media-links.ts";
+import { acpCapabilities } from "./capabilities.ts"; import { ACP_MEDIA_MAX_BYTES, readAcpMediaLinks } from "./media-links.ts";
import { acpNativeLogMessage } from "./tool-log.ts";
import { stripLeakedSystemHarnessMessages } from "../../../shared/system-message-guard.ts";
import { formatQuietLimit, lastSeenPhrase, LIMIT_WORDS, promptIdleTimeoutMs, type LogSignal } from "./quiet-status.ts"; import { startAcpQuietWatch } from "./quiet-watch.ts"; import { AppliedConfig } from "./applied-config.ts"; import { modelRefused, roomForReadBeside, startupRefresh } from "./startup-refresh.ts"; import { stderrFailureOf, watchStderrFailure, type StderrFailure } from "./harness-failure.ts"; import { timed, turnStartClock, type TurnStartClock } from "../../perf/turn-starts.ts";
@@ -1276,7 +1276,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 ? turn.text : "", imageBlocks.reduce((sum, block) => sum + Math.floor(block.data.length * 3 / 4), 0));
+ : []; const media = await readAcpMediaLinks(support.mediaLinks === true && !turn.guestConfined ? turn.text : "", imageBlocks.reduce((sum, block) => sum + Math.floor(block.data.length * 3 / 4), 0), ACP_MEDIA_MAX_BYTES, cwd);
if (support.modelVariants && !modelControls.confirms(cliTurn.model)) {
throw new Error(`${support.displayName} changed model before the prompt`);
}
diff --git a/server/drivers/acp/media-links.test.ts b/server/drivers/acp/media-links.test.ts
index c089671d0c..57cb5b0a68 100644
--- a/server/drivers/acp/media-links.test.ts
+++ b/server/drivers/acp/media-links.test.ts
@@ -1,6 +1,6 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { acpMediaUri, findMediaPaths, readAcpMediaLinks } from "./media-links.ts";
@@ -34,6 +34,16 @@ describe("findMediaPaths", () => {
expect((await findMediaPaths(`${photo} and ${other}`)).map((file) => file.path)).toEqual([photo]);
});
+ it("reads a handed-on inbox/... path from the turn's own folder, and only when that folder is given", async () => {
+ const handed = join(scratch, "inbox", "bot-a", "task one", "handed clip.mp4");
+ mkdirSync(dirname(handed), { recursive: true });
+ writeFileSync(handed, Buffer.alloc(100));
+ const text = `1 file, listed below as copies in your own folder.\n- ${join("inbox", "bot-a", "task one", "handed clip.mp4")} (video/mp4, 1 KB)`;
+ expect((await findMediaPaths(text, scratch)).map((file) => file.path)).toEqual([handed]);
+ expect(await findMediaPaths(text)).toEqual([]);
+ expect(await findMediaPaths(`- not${join("inbox", "bot-a", "task one", "handed clip.mp4")}`, scratch)).toEqual([]);
+ });
+
it("ignores text without media", async () => {
expect(await findMediaPaths("see notes.md and https://example.com/a.png")).toEqual([]);
});
diff --git a/server/drivers/acp/media-links.ts b/server/drivers/acp/media-links.ts
index b7e8b9ef4b..4d49dd2434 100644
--- a/server/drivers/acp/media-links.ts
+++ b/server/drivers/acp/media-links.ts
@@ -3,8 +3,10 @@
// 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";
+import { resolve } from "node:path";
import { productName } from "../../brand.ts";
+import { INBOX_FOLDER } from "../../host/handoff-inbox.ts";
export interface AcpResourceLink {
type: "resource_link";
@@ -23,6 +25,8 @@ const MEDIA_EXTENSIONS = "mp4|m4v|mov|webm|mpeg|mpg|avi|wmv|flv|3gp|mp3|wav|aac|
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;
+// A file another bot passed is named `inbox/...` when the turn runs in its conversation's own folder (handoff-files.ts).
+const INBOX_START = new RegExp(`(?<=^|[\\s"'\`(<[=])${INBOX_FOLDER}[\\\\/]`, "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". */
@@ -38,16 +42,19 @@ export function acpMediaUri(path: string, platform: NodeJS.Platform = process.pl
/** Existing local media files named in `text`, in order and without repeats (the same file named twice, by
* file identity, so case-sensitive file systems keep distinct names). 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 }>> {
+ * candidate start on the line is tried from the nearest, and the first that names a file wins. With `cwd`, the
+ * turn's folder, an `inbox/...` path is read from there and returned whole. */
+export async function findMediaPaths(text: string, cwd?: 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)) {
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();
+ const inbox = cwd === undefined ? [] : [...line.matchAll(INBOX_START)].map((start) => start.index);
+ const starts = [...line.matchAll(PATH_START)].map((start) => start.index).concat(inbox).sort((a, b) => b - a);
for (const start of starts) {
- const path = line.slice(start).trim();
+ const named = line.slice(start).trim();
+ const path = cwd !== undefined && inbox.includes(start) ? resolve(cwd, named) : named;
const info = await stat(path, { bigint: true }).catch(() => null);
if (!info?.isFile()) continue;
const key = `${info.dev}:${info.ino}`;
@@ -64,12 +71,12 @@ export async function findMediaPaths(text: string): Promise<Array<{ path: string
/** Prompt blocks for the media named in `text`, within one prompt's budget, and a note saying what was and was
* not attached. `usedBytes` is media the prompt already carries (composer images): it counts against the same
* budget, so when it alone fills the budget every named file is left out and named in the note. */
-export async function readAcpMediaLinks(text: string, usedBytes = 0, budget = ACP_MEDIA_MAX_BYTES): Promise<AcpMediaLinks> {
+export async function readAcpMediaLinks(text: string, usedBytes = 0, budget = ACP_MEDIA_MAX_BYTES, cwd?: string): Promise<AcpMediaLinks> {
const blocks: AcpResourceLink[] = [];
const attached: string[] = [];
const skipped: Array<{ path: string; size: number }> = [];
let total = usedBytes;
- for (const file of await findMediaPaths(text)) {
+ for (const file of await findMediaPaths(text, cwd)) {
if (attached.length < ACP_MEDIA_MAX_FILES && total + file.size <= budget) {
total += file.size;
attached.push(file.path);