Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

Bound attach_image payloads for inline rendering (#340)

Seth Karten68634afd0ed7
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 2b8baf4d63..1dd9d0d663 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -2,6 +2,7 @@
## [Unreleased]
+- Changed `attach_image` to resize and compress large inline image attachments before storing them for rendering and replay ([#340](https://github.com/PrimeIntellect-ai/prime-agent/pull/340) by [@sethkarten](https://github.com/sethkarten)).
- Fixed heartbeat and goal continuation prompts rendering like ordinary user messages ([ENG-4482](https://linear.app/primeintellect/issue/ENG-4482/heartbeat-message-should-have-a-different-ui-from-user-message)).
- Fixed `/heartbeat` guidance to show `stop` and the `every <duration> <instruction>` interval syntax ([ENG-4484](https://linear.app/primeintellect/issue/ENG-4484/improve-heartbeat-command-syntax-guidance-in-ui)).
- Fixed login dialogs in fullscreen so sign-in URLs can be selected natively ([ENG-4480](https://linear.app/primeintellect/issue/ENG-4480/new-fullscreen-tui-makes-it-impossible-to-copy-login-url)).
diff --git a/packages/coding-agent/skills/attach-image/SKILL.md b/packages/coding-agent/skills/attach-image/SKILL.md
index 25ab42980f..8c3fb8bcfa 100644
--- a/packages/coding-agent/skills/attach-image/SKILL.md
+++ b/packages/coding-agent/skills/attach-image/SKILL.md
@@ -39,5 +39,11 @@ print(await attach_image("diagram.png"))
print(await attach_image("a.png", "b.jpg"))
```
+The skill automatically resizes and compresses large images before loading them
+into context. Animated images that need compression are flattened to their first
+frame. Transparent images that need compression are composited onto a neutral
+gray background. Extremely large images are rejected by pixel count before full
+processing. The original file is left untouched.
+
Supported formats: PNG, JPEG, GIF, WebP. The skill errors if a file is not a
supported image, or if the current model is not vision-capable.
diff --git a/packages/coding-agent/skills/attach-image/pyproject.toml b/packages/coding-agent/skills/attach-image/pyproject.toml
index a9a516c49b..aacfce5718 100644
--- a/packages/coding-agent/skills/attach-image/pyproject.toml
+++ b/packages/coding-agent/skills/attach-image/pyproject.toml
@@ -3,7 +3,7 @@ name = "prime-agent-skill-attach-image"
version = "0.1.0"
description = "Load on-disk images into the model's context as viewable attachments."
requires-python = ">=3.10"
-dependencies = ["prime-agent-runtime"]
+dependencies = ["pillow>=10.0.0", "prime-agent-runtime"]
[project.scripts]
attach_image = "rlm.skill:cli"
diff --git a/packages/coding-agent/skills/attach-image/src/attach_image/attach_image.py b/packages/coding-agent/skills/attach-image/src/attach_image/attach_image.py
index 4a930f4f8b..692e568b6d 100644
--- a/packages/coding-agent/skills/attach-image/src/attach_image/attach_image.py
+++ b/packages/coding-agent/skills/attach-image/src/attach_image/attach_image.py
@@ -3,15 +3,20 @@
from __future__ import annotations
import base64
+import io
from pathlib import Path
# Keep in sync with ATTACHMENT_DISPLAY_MIME in src/core/kernel/index.ts.
_ATTACHMENT_DISPLAY_MIME = "application/vnd.prime-agent.attachment+json"
-# Base64 expands by ~4/3, so this stays well under MAX_ATTACHMENT_DATA_CHARS in
-# src/core/kernel/index.ts; an emit over that ceiling fails the cell rather than
-# being dropped, so a reported-loaded image always reaches the model.
-_MAX_IMAGE_BYTES = 3_500_000
+# Keep emitted attachments small enough that daemon clients can render and replay
+# image-heavy sessions without compressing megabytes of base64 on every update.
+_MAX_SOURCE_IMAGE_BYTES = 20_000_000
+_MAX_SOURCE_IMAGE_PIXELS = 36_000_000
+_MAX_ATTACHMENT_DATA_CHARS = 350_000
+_MAX_ATTACHMENT_DIMENSION = 1200
+_TRANSPARENCY_BACKGROUND = "#888888"
+_JPEG_QUALITIES = (82, 72, 60, 48, 36)
# Matches IMAGE_MIME_TYPES in src/utils/mime.ts.
_IMAGE_SIGNATURES = (
@@ -31,16 +36,49 @@ def _detect_image_mime(data: bytes) -> str | None:
return None
-def _validate_image(path: str) -> tuple[Path, str]:
+def _image_dimensions(filepath: Path) -> tuple[int, int]:
+ try:
+ from PIL import Image
+ except ImportError as error:
+ raise RuntimeError(
+ "attach_image needs Pillow to inspect this image before loading it into context."
+ ) from error
+
+ try:
+ with Image.open(filepath) as image:
+ return image.size
+ except Exception as error:
+ raise ValueError(
+ f"{filepath} is not a readable supported image (PNG, JPEG, GIF, WebP)."
+ ) from error
+
+
+def _validate_decodable_image(filepath: Path) -> None:
+ try:
+ from PIL import Image
+
+ with Image.open(filepath) as image:
+ if getattr(image, "is_animated", False):
+ image.seek(0)
+ image.load()
+ except Exception as error:
+ raise ValueError(
+ f"{filepath} is not a readable supported image (PNG, JPEG, GIF, WebP)."
+ ) from error
+
+
+def _validate_image(path: str) -> tuple[Path, str, int, tuple[int, int]]:
filepath = Path(path).expanduser()
if not filepath.is_file():
raise FileNotFoundError(f"{path} is not an existing regular file")
+
size = filepath.stat().st_size
- if size > _MAX_IMAGE_BYTES:
+ if size > _MAX_SOURCE_IMAGE_BYTES:
raise ValueError(
f"{path} is {size // 1_000_000}MB; images must be under "
- f"{_MAX_IMAGE_BYTES // 1_000_000}MB. Resize it (e.g. with PIL) first."
+ f"{_MAX_SOURCE_IMAGE_BYTES // 1_000_000}MB. Resize it first."
)
+
with filepath.open("rb") as f:
head = f.read(16)
mime = _detect_image_mime(head)
@@ -49,20 +87,122 @@ def _validate_image(path: str) -> tuple[Path, str]:
f"{path} is not a supported image (PNG, JPEG, GIF, WebP). "
"Only images can be loaded into context; open other files in the kernel instead."
)
- return filepath, mime
+
+ dimensions = _image_dimensions(filepath)
+ pixel_count = dimensions[0] * dimensions[1]
+ if pixel_count > _MAX_SOURCE_IMAGE_PIXELS:
+ raise ValueError(
+ f"{path} is {dimensions[0]}x{dimensions[1]} ({pixel_count // 1_000_000}MP); "
+ f"images must be at most {_MAX_SOURCE_IMAGE_PIXELS // 1_000_000}MP. Resize it first."
+ )
+ _validate_decodable_image(filepath)
+
+ return filepath, mime, size, dimensions
+
+
+def _base64_chars(data: bytes) -> int:
+ return ((len(data) + 2) // 3) * 4
+
+
+def _load_image_for_attachment(data: bytes):
+ from PIL import Image, ImageOps
+
+ image = Image.open(io.BytesIO(data))
+ is_animated = getattr(image, "is_animated", False)
+ if is_animated:
+ image.seek(0)
+ image = ImageOps.exif_transpose(image)
+ is_transparent = image.mode in {"RGBA", "LA"} or (image.mode == "P" and "transparency" in image.info)
+ conversion_notes = []
+ if is_animated:
+ conversion_notes.append("animated image flattened to first frame")
+ if is_transparent:
+ conversion_notes.append(f"transparent pixels composited on {_TRANSPARENCY_BACKGROUND} background")
+ conversion_note = "; ".join(conversion_notes) or None
+
+ if is_transparent:
+ rgba = image.convert("RGBA")
+ background = Image.new("RGB", rgba.size, _TRANSPARENCY_BACKGROUND)
+ background.paste(rgba, mask=rgba.split()[-1])
+ return background, conversion_note
+ return image.convert("RGB"), conversion_note
+
+
+def _encode_jpeg(image, quality: int) -> bytes:
+ buffer = io.BytesIO()
+ image.save(buffer, format="JPEG", quality=quality, optimize=True, progressive=True)
+ return buffer.getvalue()
+
+
+def _resize_image(filepath: Path, mime_type: str, size: int, dimensions: tuple[int, int]) -> tuple[str, str, str | None]:
+ data = filepath.read_bytes()
+ encoded_chars = _base64_chars(data)
+
+ if (
+ size <= _MAX_ATTACHMENT_DATA_CHARS * 3 // 4
+ and max(dimensions) <= _MAX_ATTACHMENT_DIMENSION
+ and encoded_chars <= _MAX_ATTACHMENT_DATA_CHARS
+ ):
+ return base64.b64encode(data).decode("ascii"), mime_type, None
+
+ try:
+ from PIL import Image
+ except ImportError as error:
+ raise RuntimeError(
+ "attach_image needs Pillow to resize this image before loading it into context."
+ ) from error
+
+ image, conversion_note = _load_image_for_attachment(data)
+ original_width, original_height = image.size
+
+ scale = min(1.0, _MAX_ATTACHMENT_DIMENSION / max(original_width, original_height))
+ target_width = max(1, round(original_width * scale))
+ target_height = max(1, round(original_height * scale))
+ last_data: bytes | None = None
+ last_width = target_width
+ last_height = target_height
+
+ while target_width >= 1 and target_height >= 1:
+ resized = image.resize((target_width, target_height), Image.Resampling.LANCZOS)
+ for quality in _JPEG_QUALITIES:
+ candidate = _encode_jpeg(resized, quality)
+ last_data = candidate
+ last_width = target_width
+ last_height = target_height
+ if _base64_chars(candidate) <= _MAX_ATTACHMENT_DATA_CHARS:
+ note = (
+ f"original {original_width}x{original_height}; attached "
+ f"{target_width}x{target_height} JPEG at quality {quality}"
+ )
+ if conversion_note:
+ note += f"; {conversion_note}"
+ return base64.b64encode(candidate).decode("ascii"), "image/jpeg", note
+
+ next_width = max(1, int(target_width * 0.75))
+ next_height = max(1, int(target_height * 0.75))
+ if next_width == target_width and next_height == target_height:
+ break
+ target_width, target_height = next_width, next_height
+
+ raise ValueError(
+ f"{filepath} could not be compressed below "
+ f"{_MAX_ATTACHMENT_DATA_CHARS // 1000}KB base64 payload "
+ f"(smallest was {_base64_chars(last_data or b'') // 1000}KB at {last_width}x{last_height})."
+ )
-def _emit_attachment(filepath: Path, mime_type: str) -> None:
+def _emit_attachment(filepath: Path, mime_type: str, size: int, dimensions: tuple[int, int]) -> str | None:
from IPython.display import display
- data_b64 = base64.b64encode(filepath.read_bytes()).decode("ascii")
+ data_b64, emitted_mime_type, resize_note = _resize_image(filepath, mime_type, size, dimensions)
display(
{
- _ATTACHMENT_DISPLAY_MIME: {"mime_type": mime_type, "data": data_b64, "path": str(filepath)},
+ _ATTACHMENT_DISPLAY_MIME: {"mime_type": emitted_mime_type, "data": data_b64, "path": str(filepath)},
"text/plain": f"Loaded image into context: {filepath}",
},
raw=True,
)
+ return resize_note
async def run(*paths: str) -> str:
@@ -86,7 +226,8 @@ async def run(*paths: str) -> str:
Raises:
FileNotFoundError: If a path does not exist or is not a regular file.
- ValueError: If a file is not a supported image or is too large.
+ ValueError: If a file is not a supported image, is too large, or cannot
+ be compressed enough for safe inline rendering and replay.
RuntimeError: If the current model cannot accept images.
"""
if not paths:
@@ -102,11 +243,16 @@ async def run(*paths: str) -> str:
"Tell the user to switch to a vision-capable model to load images into context."
)
- # Validate every path before emitting anything (so a later failure never
- # leaves a partial subset injected), but read+encode one image at a time to
- # avoid holding every base64 payload in memory at once.
+ # Validate every path before emitting anything, so a later failure never
+ # leaves a partial subset injected.
validated = [_validate_image(path) for path in paths]
- for filepath, mime in validated:
- _emit_attachment(filepath, mime)
+ resize_notes = []
+ for filepath, mime, size, dimensions in validated:
+ note = _emit_attachment(filepath, mime, size, dimensions)
+ if note:
+ resize_notes.append(f"{filepath}: {note}")
- return f"Loaded {len(validated)} image(s) into context: {', '.join(paths)}"
+ message = f"Loaded {len(validated)} image(s) into context: {', '.join(paths)}"
+ if resize_notes:
+ message += "\nResized for efficient inline rendering/replay:\n- " + "\n- ".join(resize_notes)
+ return message
diff --git a/packages/coding-agent/test/kernel-attach-image-skill.test.ts b/packages/coding-agent/test/kernel-attach-image-skill.test.ts
index 9c6b1fbd43..ee2110231c 100644
--- a/packages/coding-agent/test/kernel-attach-image-skill.test.ts
+++ b/packages/coding-agent/test/kernel-attach-image-skill.test.ts
@@ -58,6 +58,161 @@ describe("attach-image skill over the kernel host bridge", () => {
expect(blocks).toEqual([{ type: "image", data: PNG_BASE64, mimeType: "image/png" }]);
});
+ it("compresses large attached images before storing them in the tool result", async () => {
+ const imagePath = join(tempDir, "large.png");
+
+ provisioner = new IpythonKernelProvisioner(tempDir, {
+ pythonSkills: [bundledAttachImageSkill()],
+ hostHandlers: {
+ "model.info": async () => ({ id: "anthropic/claude-haiku-4.5", input: ["text", "image"] }),
+ },
+ });
+
+ const manager = await provisioner.ensure();
+ const result = await manager.execute(`
+from PIL import Image
+img = Image.new("RGB", (2400, 1800))
+pixels = img.load()
+for y in range(img.height):
+ for x in range(img.width):
+ pixels[x, y] = ((x * 17 + y * 3) % 256, (x * 5 + y * 11) % 256, (x * 13 + y * 7) % 256)
+img.save(${JSON.stringify(imagePath)})
+print(await attach_image(${JSON.stringify(imagePath)}))
+`);
+
+ expect(result.status).toBe("ok");
+ expect(result.stdout).toContain("Resized for efficient inline rendering/replay");
+ expect(result.attachments).toHaveLength(1);
+ expect(result.attachments?.[0]?.mimeType).toBe("image/jpeg");
+ expect(result.attachments?.[0]?.data.length).toBeLessThanOrEqual(350_000);
+ });
+
+ it("reports when compressed animated images are flattened to their first frame", async () => {
+ const imagePath = join(tempDir, "animated.gif");
+
+ provisioner = new IpythonKernelProvisioner(tempDir, {
+ pythonSkills: [bundledAttachImageSkill()],
+ hostHandlers: {
+ "model.info": async () => ({ id: "anthropic/claude-haiku-4.5", input: ["text", "image"] }),
+ },
+ });
+
+ const manager = await provisioner.ensure();
+ const result = await manager.execute(`
+from PIL import Image
+frames = [Image.new("RGB", (1300, 10), color) for color in ("red", "blue")]
+frames[0].save(${JSON.stringify(imagePath)}, save_all=True, append_images=frames[1:], duration=50, loop=0)
+print(await attach_image(${JSON.stringify(imagePath)}))
+`);
+
+ expect(result.status).toBe("ok");
+ expect(result.stdout).toContain("animated image flattened to first frame");
+ expect(result.attachments).toHaveLength(1);
+ expect(result.attachments?.[0]?.mimeType).toBe("image/jpeg");
+ expect(result.attachments?.[0]?.data.length).toBeLessThanOrEqual(350_000);
+ });
+
+ it("uses a neutral background when compressing transparent images", async () => {
+ const imagePath = join(tempDir, "transparent.png");
+
+ provisioner = new IpythonKernelProvisioner(tempDir, {
+ pythonSkills: [bundledAttachImageSkill()],
+ hostHandlers: {
+ "model.info": async () => ({ id: "anthropic/claude-haiku-4.5", input: ["text", "image"] }),
+ },
+ });
+
+ const manager = await provisioner.ensure();
+ const result = await manager.execute(`
+from PIL import Image, ImageDraw
+img = Image.new("RGBA", (1300, 10), (0, 0, 0, 0))
+draw = ImageDraw.Draw(img)
+draw.rectangle((0, 0, 1299, 9), fill=(255, 255, 255, 255))
+img.save(${JSON.stringify(imagePath)})
+print(await attach_image(${JSON.stringify(imagePath)}))
+`);
+
+ expect(result.status).toBe("ok");
+ expect(result.stdout).toContain("transparent pixels composited on #888888 background");
+ expect(result.attachments).toHaveLength(1);
+ expect(result.attachments?.[0]?.mimeType).toBe("image/jpeg");
+ expect(result.attachments?.[0]?.data.length).toBeLessThanOrEqual(350_000);
+ });
+
+ it("rejects oversized pixel counts before loading an image into context", async () => {
+ const imagePath = join(tempDir, "huge.png");
+
+ provisioner = new IpythonKernelProvisioner(tempDir, {
+ pythonSkills: [bundledAttachImageSkill()],
+ hostHandlers: {
+ "model.info": async () => ({ id: "anthropic/claude-haiku-4.5", input: ["text", "image"] }),
+ },
+ });
+
+ const manager = await provisioner.ensure();
+ const result = await manager.execute(`
+import struct
+import zlib
+
+
+def png_chunk(kind, data):
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
+
+
+png = bytes([137, 80, 78, 71, 13, 10, 26, 10])
+png += png_chunk(b"IHDR", struct.pack(">IIBBBBB", 6001, 6001, 8, 2, 0, 0, 0))
+png += png_chunk(b"IEND", b"")
+with open(${JSON.stringify(imagePath)}, "wb") as file:
+ file.write(png)
+try:
+ await attach_image(${JSON.stringify(imagePath)})
+except ValueError as error:
+ print(f"ValueError: {error}")
+`);
+
+ expect(result.status).toBe("ok");
+ expect(result.stdout).toContain("images must be at most 36MP");
+ expect(result.attachments).toBeUndefined();
+ });
+
+ it("rejects undecodable images before emitting any attachment", async () => {
+ const validImagePath = join(tempDir, "valid.png");
+ const corruptImagePath = join(tempDir, "corrupt.png");
+ writeFileSync(validImagePath, Buffer.from(PNG_BASE64, "base64"));
+
+ provisioner = new IpythonKernelProvisioner(tempDir, {
+ pythonSkills: [bundledAttachImageSkill()],
+ hostHandlers: {
+ "model.info": async () => ({ id: "anthropic/claude-haiku-4.5", input: ["text", "image"] }),
+ },
+ });
+
+ const manager = await provisioner.ensure();
+ const result = await manager.execute(`
+import struct
+import zlib
+
+
+def png_chunk(kind, data):
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
+
+
+png = bytes([137, 80, 78, 71, 13, 10, 26, 10])
+png += png_chunk(b"IHDR", struct.pack(">IIBBBBB", 10, 10, 8, 2, 0, 0, 0))
+png += png_chunk(b"IEND", b"")
+with open(${JSON.stringify(corruptImagePath)}, "wb") as file:
+ file.write(png)
+try:
+ await attach_image(${JSON.stringify(validImagePath)}, ${JSON.stringify(corruptImagePath)})
+except ValueError as error:
+ print(f"ValueError: {error}")
+`);
+
+ expect(result.status).toBe("ok");
+ expect(result.stdout).toContain("is not a readable supported image");
+ expect(result.attachments).toBeUndefined();
+ });
+
it("errors without emitting an attachment when the model is not vision-capable", async () => {
const imagePath = join(tempDir, "sample.png");
writeFileSync(imagePath, Buffer.from(PNG_BASE64, "base64"));