Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): detect sandbox images from file bytes (#4328)

Bryan Hunter738c8de7bf2b
diff --git a/.changeset/read-image-bytes.md b/.changeset/read-image-bytes.md
new file mode 100644
index 000000000..a36904694
--- /dev/null
+++ b/.changeset/read-image-bytes.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Detect PNG, JPEG, GIF, and WebP files from their bytes in `read_file`, so images with missing or incorrect filename extensions remain viewable. Text files are always read as text, even with an image extension, and unreadable binary files now get a clear error.
diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.md
index 04116f3d6..67889d325 100644
--- a/docs/concepts/built-in-tools.md
+++ b/docs/concepts/built-in-tools.md
@@ -81,7 +81,7 @@ export default disableTool();
### `read_file`
-`read_file` reads text files from the sandbox with line-numbered output, and shows PNG, JPEG, GIF, and WebP images up to 3 MiB to the model as images. It accepts absolute paths and paths beginning with `$HOME/`.
+`read_file` reads text files from the sandbox with line-numbered output, and shows PNG, JPEG, GIF, and WebP images up to 3 MiB to the model as images. Images are detected from their bytes, so a missing or mismatched filename extension does not matter, and text files are always read as text. It accepts absolute paths and paths beginning with `$HOME/`.
```sh
eve add tool/read_file
diff --git a/packages/eve/src/execution/sandbox/read-file.test.ts b/packages/eve/src/execution/sandbox/read-file.test.ts
index b2f071973..d509288e5 100644
--- a/packages/eve/src/execution/sandbox/read-file.test.ts
+++ b/packages/eve/src/execution/sandbox/read-file.test.ts
@@ -42,38 +42,42 @@ function stagedPath(message: ModelMessage | undefined): string | undefined {
}
describe("read_file images", () => {
- it("keeps image bytes out of the raw output and shows them to the model", async () => {
- const png = pngBytes(32, 32, 64);
- const sandbox = mockSandbox();
- await sandbox.session.writeBinaryFile({ content: png, path: "/workspace/chart.png" });
+ it.each(["chart.png", "chart", "chart.bin", "chart.jpg"])(
+ "keeps image bytes out of raw output and shows %s with its detected media type",
+ async (filename) => {
+ const png = pngBytes(32, 32, 64);
+ const sandbox = mockSandbox();
+ const path = `/workspace/${filename}`;
+ await sandbox.session.writeBinaryFile({ content: png, path });
- const output = await executeReadFileOnSandbox(sandbox.session, {
- filePath: "/workspace/chart.png",
- });
- const modelOutput = await contextStorage.run(sandboxContext(sandbox), async () =>
- readFile.toModelOutput?.(output),
- );
+ const output = await executeReadFileOnSandbox(sandbox.session, {
+ filePath: path,
+ });
+ const modelOutput = await contextStorage.run(sandboxContext(sandbox), async () =>
+ readFile.toModelOutput?.(output),
+ );
- // The raw output feeds action.result, so it carries metadata only.
- expect(output.image).toEqual({
- height: 32,
- mediaType: "image/png",
- size: png.byteLength,
- width: 32,
- });
- expect(modelOutput).toEqual({
- type: "content",
- value: [
- { text: `Image /workspace/chart.png (image/png, ${png.byteLength} bytes).`, type: "text" },
- {
- data: { data: png.toString("base64"), type: "data" },
- filename: "chart.png",
- mediaType: "image/png",
- type: "file",
- },
- ],
- });
- });
+ // The raw output feeds action.result, so it carries metadata only.
+ expect(output.image).toEqual({
+ height: 32,
+ mediaType: "image/png",
+ size: png.byteLength,
+ width: 32,
+ });
+ expect(modelOutput).toEqual({
+ type: "content",
+ value: [
+ { text: `Image ${path} (image/png, ${png.byteLength} bytes).`, type: "text" },
+ {
+ data: { data: png.toString("base64"), type: "data" },
+ filename,
+ mediaType: "image/png",
+ type: "file",
+ },
+ ],
+ });
+ },
+ );
it("reopens a nameless tool image from the path its compaction stub names", async () => {
const png = pngBytes(16, 16);
@@ -96,15 +100,89 @@ describe("read_file images", () => {
expect(output.image).toMatchObject({ mediaType: "image/png" });
});
- it("rejects images too large to show inline", async () => {
+ it.each([
+ ["JPEG", Buffer.from([255, 216, 255, 217]), "image/jpeg"],
+ ["GIF87a", Buffer.from("GIF87a\x01\0\x01\0", "latin1"), "image/gif"],
+ ["GIF89a", Buffer.from("GIF89a\x01\0\x01\0", "latin1"), "image/gif"],
+ ["WebP", Buffer.from("RIFF\0\0\0\0WEBP"), "image/webp"],
+ ])("detects %s without a filename suffix", async (_label, bytes, mediaType) => {
+ const sandbox = mockSandbox();
+ await sandbox.session.writeBinaryFile({ path: "/workspace/image", content: bytes });
+ const output = await executeReadFileOnSandbox(sandbox.session, {
+ filePath: "/workspace/image",
+ });
+ expect(output.image).toMatchObject({ mediaType, size: bytes.byteLength });
+ });
+
+ it("reads text with an image suffix using normal pagination", async () => {
+ const sandbox = mockSandbox();
+ await sandbox.session.writeTextFile({
+ path: "/workspace/notes.png",
+ content: "hello\nworld\n",
+ });
+ const output = await contextStorage.run(sandboxContext(sandbox), () =>
+ executeReadFileOnSandbox(sandbox.session, { filePath: "/workspace/notes.png", limit: 1 }),
+ );
+ expect(output).toEqual({
+ content: "1: hello",
+ nextOffset: 2,
+ path: "/workspace/notes.png",
+ totalLines: 2,
+ truncated: true,
+ });
+ });
+
+ it.each([
+ ["an empty file", ""],
+ ["a truncated WebP header", "RIFF"],
+ ["text that starts with a GIF signature", "GIF89a is the most common GIF version.\n"],
+ ])("reads %s as text", async (_label, content) => {
+ const sandbox = mockSandbox();
+ await sandbox.session.writeTextFile({ path: "/workspace/file", content });
+ const output = await contextStorage.run(sandboxContext(sandbox), () =>
+ executeReadFileOnSandbox(sandbox.session, { filePath: "/workspace/file" }),
+ );
+ expect(output.image).toBeUndefined();
+ expect(output.totalLines).toBe(content === "" ? 0 : 1);
+ });
+
+ it("rejects unsupported binary files instead of rendering them as images", async () => {
+ const sandbox = mockSandbox();
+ await sandbox.session.writeBinaryFile({
+ path: "/workspace/audio.png",
+ content: Buffer.from("RIFF\0\0\0\0WAVE"),
+ });
+ await expect(
+ executeReadFileOnSandbox(sandbox.session, { filePath: "/workspace/audio.png" }),
+ ).rejects.toThrow("binary file");
+ });
+
+ it("withholds an image replaced between execute and toModelOutput", async () => {
+ const sandbox = mockSandbox();
+ const path = "/workspace/chart.png";
+ await sandbox.session.writeBinaryFile({ content: pngBytes(8, 8), path });
+ const output = await executeReadFileOnSandbox(sandbox.session, { filePath: path });
+
+ await sandbox.session.writeBinaryFile({ content: pngBytes(8, 8, 1024), path });
+ const modelOutput = await contextStorage.run(sandboxContext(sandbox), async () =>
+ readFile.toModelOutput?.(output),
+ );
+
+ expect(modelOutput).toEqual({
+ type: "text",
+ value: `${output.content} The image changed after it was read; read it again.`,
+ });
+ });
+
+ it.each(["photo.png", "photo"])("rejects oversized images named %s", async (filename) => {
const sandbox = mockSandbox();
await sandbox.session.writeBinaryFile({
content: pngBytes(4000, 4000, 3 * 1024 * 1024),
- path: "/workspace/photo.png",
+ path: `/workspace/${filename}`,
});
await expect(
- executeReadFileOnSandbox(sandbox.session, { filePath: "/workspace/photo.png" }),
+ executeReadFileOnSandbox(sandbox.session, { filePath: `/workspace/${filename}` }),
).rejects.toThrow("read_file shows images up to 3 MiB");
});
});
diff --git a/packages/eve/src/execution/sandbox/read-file.ts b/packages/eve/src/execution/sandbox/read-file.ts
index 26f06d49b..8d2444ff7 100644
--- a/packages/eve/src/execution/sandbox/read-file.ts
+++ b/packages/eve/src/execution/sandbox/read-file.ts
@@ -6,7 +6,11 @@ import {
setReadFileStamp,
} from "#execution/tools/file-state.js";
import { resolveAbsoluteFilePath } from "#execution/sandbox/require-sandbox.js";
-import { readMediaMetadata, type MediaMetadata } from "#internal/attachments/media-metadata.js";
+import {
+ detectImageMediaType,
+ readMediaMetadata,
+ type MediaMetadata,
+} from "#internal/attachments/media-metadata.js";
import type { SandboxSession } from "#shared/sandbox-session.js";
import { capLineLength, MAX_OUTPUT_BYTES } from "#execution/sandbox/truncate-output.js";
@@ -19,14 +23,6 @@ const DEFAULT_LIMIT = 2000;
// Matches the inline cap for inbound image attachments.
const MAX_IMAGE_BYTES = 3 * 1024 * 1024;
-const IMAGE_MEDIA_TYPES: Readonly<Record<string, string>> = {
- gif: "image/gif",
- jpeg: "image/jpeg",
- jpg: "image/jpeg",
- png: "image/png",
- webp: "image/webp",
-};
-
// ---------------------------------------------------------------------------
// Input / result shapes
// ---------------------------------------------------------------------------
@@ -78,9 +74,26 @@ export async function executeReadFileOnSandbox(
const resolvedPath = await resolveAbsoluteFilePath(sandbox, filePath);
const normalizedPath = normalizeModelPath(resolvedPath);
- const imageMediaType = IMAGE_MEDIA_TYPES[normalizedPath.split(".").pop()?.toLowerCase() ?? ""];
- if (imageMediaType !== undefined) {
- return await readImageFile(sandbox, resolvedPath, normalizedPath, imageMediaType);
+ const bytes = await sandbox.readBinaryFile({ path: resolvedPath });
+ if (bytes === null) {
+ throw new Error(
+ `File not found: ${filePath}. Verify the path exists and is accessible in the sandbox.`,
+ );
+ }
+
+ // ── Classify as text, image, or unsupported binary ──────────────────
+ // Clean text stays text even behind an ASCII image signature such as
+ // `GIF89a`; real images always carry NUL or non-UTF-8 bytes.
+ const rawContent = decodeUtf8(bytes);
+ if (rawContent === undefined || rawContent.includes("\0")) {
+ const imageMediaType = detectImageMediaType(bytes);
+ if (imageMediaType !== undefined) {
+ return buildImageReadResult(bytes, normalizedPath, imageMediaType);
+ }
+ throw new Error(
+ `File "${filePath}" appears to be a binary file. ` +
+ "read_file only supports text files and PNG, JPEG, GIF, or WebP images.",
+ );
}
// ── Validate offset / limit ─────────────────────────────────────────
@@ -91,23 +104,6 @@ export async function executeReadFileOnSandbox(
throw new Error(`offset must be >= 1. Received: ${effectiveOffset}.`);
}
- // ── Read full file for fingerprinting ───────────────────────────────
- const rawContent = await sandbox.readTextFile({ path: resolvedPath });
-
- if (rawContent === null) {
- throw new Error(
- `File not found: ${filePath}. Verify the path exists and is accessible in the sandbox.`,
- );
- }
-
- // ── Reject non-text (NUL bytes) ─────────────────────────────────────
- if (rawContent.includes("\0")) {
- throw new Error(
- `File "${filePath}" contains NUL bytes and appears to be a binary file. ` +
- "read_file only supports text files.",
- );
- }
-
// ── Split into lines ────────────────────────────────────────────────
// Uses a simple newline split (not the ending-preserving variant in
// session.ts) because the model-facing output re-joins with plain `\n`
@@ -202,18 +198,17 @@ export async function executeReadFileOnSandbox(
};
}
-async function readImageFile(
- sandbox: SandboxSession,
- resolvedPath: string,
- path: string,
- mediaType: string,
-): Promise<ReadFileResult> {
- const bytes = await sandbox.readBinaryFile({ path: resolvedPath });
- if (bytes === null) {
- throw new Error(
- `File not found: ${path}. Verify the path exists and is accessible in the sandbox.`,
- );
+// Decodes exactly like `readTextFile` so write_file's stale-write check
+// fingerprints the same text this read stamps.
+function decodeUtf8(bytes: Uint8Array): string | undefined {
+ try {
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
+ } catch {
+ return undefined;
}
+}
+
+function buildImageReadResult(bytes: Uint8Array, path: string, mediaType: string): ReadFileResult {
if (bytes.byteLength > MAX_IMAGE_BYTES) {
throw new Error(
`Image "${path}" is ${bytes.byteLength} bytes; read_file shows images up to 3 MiB. ` +
diff --git a/packages/eve/src/internal/attachments/media-metadata.ts b/packages/eve/src/internal/attachments/media-metadata.ts
index 627028df9..0a8d5abae 100644
--- a/packages/eve/src/internal/attachments/media-metadata.ts
+++ b/packages/eve/src/internal/attachments/media-metadata.ts
@@ -55,13 +55,32 @@ export function estimateMediaTokens(metadata: MediaMetadata): number {
return Math.ceil(metadata.size / 3);
}
+/** Names the PNG, GIF, JPEG, or WebP format its leading bytes identify. */
+export function detectImageMediaType(bytes: Uint8Array): string | undefined {
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const ascii = (start: number, end: number) => readAscii(bytes, start, end);
+
+ if (
+ bytes.byteLength >= 8 &&
+ view.getUint32(0) === 0x89504e47 &&
+ view.getUint32(4) === 0x0d0a1a0a
+ ) {
+ return "image/png";
+ }
+ if (bytes.byteLength >= 3 && view.getUint16(0) === 0xffd8 && bytes[2] === 0xff) {
+ return "image/jpeg";
+ }
+ if (ascii(0, 6) === "GIF87a" || ascii(0, 6) === "GIF89a") return "image/gif";
+ if (ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP") return "image/webp";
+ return undefined;
+}
+
/** Reads PNG, GIF, JPEG, or WebP dimensions from the leading bytes. */
export function readImageDimensions(
bytes: Uint8Array,
): { readonly width: number; readonly height: number } | undefined {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- const ascii = (start: number, end: number) =>
- String.fromCharCode(...bytes.subarray(start, Math.min(end, bytes.byteLength)));
+ const ascii = (start: number, end: number) => readAscii(bytes, start, end);
if (bytes.byteLength >= 24 && view.getUint32(0) === 0x89504e47) {
return dimensions(view.getUint32(16), view.getUint32(20));
@@ -117,6 +136,10 @@ function countPdfPages(bytes: Uint8Array): number | undefined {
return pages > 0 ? pages : undefined;
}
+function readAscii(bytes: Uint8Array, start: number, end: number): string {
+ return String.fromCharCode(...bytes.subarray(start, Math.min(end, bytes.byteLength)));
+}
+
function readUint24(bytes: Uint8Array, offset: number): number {
return bytes[offset]! | (bytes[offset + 1]! << 8) | (bytes[offset + 2]! << 16);
}
diff --git a/packages/eve/src/tools/provided/read-file.ts b/packages/eve/src/tools/provided/read-file.ts
index 680b0104a..4ec60d832 100644
--- a/packages/eve/src/tools/provided/read-file.ts
+++ b/packages/eve/src/tools/provided/read-file.ts
@@ -119,6 +119,12 @@ export const readFile: ToolDefinition<ReadFileToolInput, ReadFileToolOutput> = d
path: await resolveAbsoluteFilePath(sandbox, output.path),
});
if (bytes === null) return toolOutput.text(`${output.content} The image could not be loaded.`);
+ // A file replaced after `execute` would otherwise skip its size cap.
+ if (bytes.byteLength !== output.image.size) {
+ return toolOutput.text(
+ `${output.content} The image changed after it was read; read it again.`,
+ );
+ }
return toolOutput.content([
toolOutputPart.text(output.content),
toolOutputPart.file(Buffer.from(bytes).toString("base64"), {
diff --git a/packages/eve/test/read-file-tool.test.ts b/packages/eve/test/read-file-tool.test.ts
index 93f623da5..3aff26f1d 100644
--- a/packages/eve/test/read-file-tool.test.ts
+++ b/packages/eve/test/read-file-tool.test.ts
@@ -30,8 +30,9 @@ function createFakeAccess(files: Record<string, string | null>): SandboxAccess {
async readFile() {
return null;
},
- async readBinaryFile() {
- return null;
+ async readBinaryFile({ path }: { path: string }) {
+ const content = files[path];
+ return content == null ? null : new TextEncoder().encode(content);
},
async readTextFile({ path }: { path: string }) {
const content = files[path];
@@ -272,7 +273,7 @@ describe("executeReadFileOnSandbox", () => {
runInContext({ "/workspace/binary.bin": "hello\0world" }, (sandbox) =>
executeReadFileOnSandbox(sandbox, { filePath: "/workspace/binary.bin" }),
),
- ).rejects.toThrow("contains NUL bytes");
+ ).rejects.toThrow("appears to be a binary file");
});
// ---------------------------------------------------------------------------
diff --git a/packages/eve/test/write-file-tool.test.ts b/packages/eve/test/write-file-tool.test.ts
index 3a9cb1d37..fd916518c 100644
--- a/packages/eve/test/write-file-tool.test.ts
+++ b/packages/eve/test/write-file-tool.test.ts
@@ -27,8 +27,9 @@ function createFakeAccess(files: Record<string, string>): {
async readFile() {
return null;
},
- async readBinaryFile() {
- return null;
+ async readBinaryFile({ path }: { path: string }) {
+ const content = files[path];
+ return content === undefined ? null : new TextEncoder().encode(content);
},
async readTextFile({ path }: { path: string }) {
const content = files[path];