A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
load on-disk images into model context via attach-media skill (#274)
kt6e929e156014
diff --git a/packages/coding-agent/skills/attach-image/SKILL.md b/packages/coding-agent/skills/attach-image/SKILL.mdnew file mode 100644index 0000000000..25ab42980f--- /dev/null+++ b/packages/coding-agent/skills/attach-image/SKILL.md@@ -0,0 +1,43 @@+---+name: attach-image+description: Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it — for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.+---++# Attach Image++Load on-disk images into the model's context as multimodal attachments. The+image is sent to the model the same way a pasted image is, so the model can+actually look at it.++## When to use this++- The user points at an image file and wants you to look at it.+- You need to read text, a chart, a diagram, or a layout from an image.+- A screenshot needs visual interpretation.++## When NOT to use this++For *programmatic* work on an image — measuring pixels, cropping, resizing,+computing a hash, comparing files byte-by-byte — open it in the kernel with a+library instead:++```python+from PIL import Image+img = Image.open("diagram.png")+print(img.size)+```++That path does not put the image in the model's context; it only lets you+compute over it. Use `attach_image` when you need to *see* the image.++## Usage++Call the prepared `attach_image` import directly in the IPython kernel:++```python+print(await attach_image("diagram.png"))+print(await attach_image("a.png", "b.jpg"))+```++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.tomlnew file mode 100644index 0000000000..a9a516c49b--- /dev/null+++ b/packages/coding-agent/skills/attach-image/pyproject.toml@@ -0,0 +1,16 @@+[project]+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"]++[project.scripts]+attach_image = "rlm.skill:cli"++[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["src/attach_image"]diff --git a/packages/coding-agent/skills/attach-image/src/attach_image/__init__.py b/packages/coding-agent/skills/attach-image/src/attach_image/__init__.pynew file mode 100644index 0000000000..77228e552d--- /dev/null+++ b/packages/coding-agent/skills/attach-image/src/attach_image/__init__.py@@ -0,0 +1,5 @@+"""Load on-disk images into the model's context as viewable attachments."""++from .attach_image import run++__all__ = ["run"]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.pynew file mode 100644index 0000000000..4a930f4f8b--- /dev/null+++ b/packages/coding-agent/skills/attach-image/src/attach_image/attach_image.py@@ -0,0 +1,112 @@+"""Load on-disk images into the model's context as multimodal attachments."""++from __future__ import annotations++import base64+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++# Matches IMAGE_MIME_TYPES in src/utils/mime.ts.+_IMAGE_SIGNATURES = (+ ("image/png", b"\x89PNG\r\n\x1a\n"),+ ("image/jpeg", b"\xff\xd8\xff"),+ ("image/gif", b"GIF87a"),+ ("image/gif", b"GIF89a"),+)+++def _detect_image_mime(data: bytes) -> str | None:+ for mime, prefix in _IMAGE_SIGNATURES:+ if data.startswith(prefix):+ return mime+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":+ return "image/webp"+ return None+++def _validate_image(path: str) -> tuple[Path, str]:+ 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:+ 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."+ )+ with filepath.open("rb") as f:+ head = f.read(16)+ mime = _detect_image_mime(head)+ if mime is None:+ raise ValueError(+ 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+++def _emit_attachment(filepath: Path, mime_type: str) -> None:+ from IPython.display import display++ data_b64 = base64.b64encode(filepath.read_bytes()).decode("ascii")+ display(+ {+ _ATTACHMENT_DISPLAY_MIME: {"mime_type": mime_type, "data": data_b64, "path": str(filepath)},+ "text/plain": f"Loaded image into context: {filepath}",+ },+ raw=True,+ )+++async def run(*paths: str) -> str:+ """Load one or more on-disk images into the model's context as attachments.++ Use this when the model needs to actually SEE an image file — a screenshot,+ diagram, chart, photo, or scanned page. The image is sent to the model as a+ viewable attachment (the same way a pasted image is).++ Do NOT use this for programmatic image analysis (reading pixels, cropping,+ resizing, hashing, measuring colors). For that, open the file with PIL in+ the kernel instead.++ Args:+ *paths: One or more image paths. Relative, absolute, or `~`-prefixed.+ Supported formats: PNG, JPEG, GIF, WebP. Other types (PDF, audio,+ video) are not supported and raise an error.++ Returns:+ A short confirmation listing the images loaded into context.++ 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.+ RuntimeError: If the current model cannot accept images.+ """+ if not paths:+ raise ValueError("attach_image requires at least one image path")++ from rlm import host_request++ info = await host_request("model.info")+ if "image" not in info.get("input", []):+ model_id = info.get("id") or "the current model"+ raise RuntimeError(+ f"{model_id} does not support vision. "+ "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.+ validated = [_validate_image(path) for path in paths]+ for filepath, mime in validated:+ _emit_attachment(filepath, mime)++ return f"Loaded {len(validated)} image(s) into context: {', '.join(paths)}"diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 72e0f1a035..fc3c0e24d5 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -3754,6 +3754,11 @@ export class AgentSession {"rlm.run": createRlmRunHostHandler(({ prompt, kwargs, cellSourceCode }) =>this.runRlmChild(prompt, kwargs, cellSourceCode),),+ "model.info": async () => ({+ id: this.model?.id ?? null,+ provider: this.model?.provider ?? null,+ input: this.model?.input ?? [],+ }),};if (this._includeGoals) {for (const type of ["goal.get", "goal.create", "goal.complete"]) {diff --git a/packages/coding-agent/src/core/kernel/index.ts b/packages/coding-agent/src/core/kernel/index.tsindex d7dcee0413..1adb22cca2 100644--- a/packages/coding-agent/src/core/kernel/index.ts+++ b/packages/coding-agent/src/core/kernel/index.ts@@ -91,6 +91,17 @@ export interface ExecuteOptions {/** MIME tag the `edit` skill emits diff payloads under, via `display_data`. */export const DIFF_DISPLAY_MIME = "application/vnd.prime-agent.diff+json";+/** MIME tag the `attach-image` skill emits media payloads under, via `display_data`. */+export const ATTACHMENT_DISPLAY_MIME = "application/vnd.prime-agent.attachment+json";++/**+ * Hard ceiling on a single attachment's base64 payload, a defensive guard+ * against a runaway direct `display_data` emit. The `attach-image` skill caps+ * its own images well under this (see `_MAX_IMAGE_BYTES`), so a skill-produced+ * attachment is never dropped here — only a non-skill emit can hit this.+ */+const MAX_ATTACHMENT_DATA_CHARS = 10_000_000;+/** One file edit, captured from a {@link DIFF_DISPLAY_MIME} display payload. */export interface KernelDiffDisplay {path: string;@@ -100,6 +111,15 @@ export interface KernelDiffDisplay {startLine?: number;}+/** One media attachment, captured from an {@link ATTACHMENT_DISPLAY_MIME} display payload. */+export interface KernelAttachment {+ mimeType: string;+ /** base64-encoded bytes. */+ data: string;+ /** Source path, surfaced to the TUI renderer. */+ path?: string;+}+export interface ExecuteResult {stdout: string;stderr: string;@@ -107,6 +127,8 @@ export interface ExecuteResult {result?: string;/** Diffs emitted via display_data, in order. */diffs?: KernelDiffDisplay[];+ /** Media attachments emitted via display_data, in order. */+ attachments?: KernelAttachment[];status: "ok" | "error" | "aborted";error?: { ename: string; evalue: string; traceback: string[] };durationMs: number;@@ -124,6 +146,26 @@ function parseDiffDisplay(payload: unknown): KernelDiffDisplay | undefined {return { path, oldStr, newStr, startLine: typeof startLine === "number" ? startLine : undefined };}+/**+ * Parse an {@link ATTACHMENT_DISPLAY_MIME} payload. Malformed payloads are+ * tolerantly ignored (`undefined`); a well-formed payload exceeding+ * {@link MAX_ATTACHMENT_DATA_CHARS} is reported as `"oversized"` so the caller+ * can fail the cell loudly rather than silently dropping the image.+ */+function parseAttachmentDisplay(payload: unknown): KernelAttachment | "oversized" | undefined {+ if (!isRecord(payload)) {+ return undefined;+ }+ const { mime_type: mimeType, data, path } = payload;+ if (typeof mimeType !== "string" || typeof data !== "string") {+ return undefined;+ }+ if (data.length > MAX_ATTACHMENT_DATA_CHARS) {+ return "oversized";+ }+ return { mimeType, data, path: typeof path === "string" ? path : undefined };+}+interface ConnectionInfo {ip: string;transport: "tcp";@@ -164,6 +206,7 @@ interface ActiveExecution {stderrTruncated: boolean;result?: string;diffs: KernelDiffDisplay[];+ attachments: KernelAttachment[];error?: ExecuteResult["error"];status: ExecuteResult["status"];resolve: (result: ExecuteResult) => void;@@ -652,6 +695,7 @@ export class KernelManager {stdoutTruncated: false,stderrTruncated: false,diffs: [],+ attachments: [],status: "ok",resolve: result.resolve,reject: result.reject,@@ -747,6 +791,13 @@ export class KernelManager {const c = incoming.content as { data?: Record<string, unknown> };const diff = parseDiffDisplay(c.data?.[DIFF_DISPLAY_MIME]);if (diff) execution.diffs.push(diff);+ const attachment = parseAttachmentDisplay(c.data?.[ATTACHMENT_DISPLAY_MIME]);+ if (attachment === "oversized") {+ execution.stderr += `${execution.stderr ? "\n" : ""}attachment dropped: exceeds ${MAX_ATTACHMENT_DATA_CHARS} base64 chars`;+ execution.status = "error";+ } else if (attachment) {+ execution.attachments.push(attachment);+ }} else if (t === "error") {const c = incoming.content as { ename: string; evalue: string; traceback: string[] };execution.error = c;@@ -782,6 +833,7 @@ export class KernelManager {stderr,result,diffs: execution.diffs.length > 0 ? execution.diffs : undefined,+ attachments: execution.attachments.length > 0 ? execution.attachments : undefined,error: execution.error,status,durationMs: Date.now() - execution.started,diff --git a/packages/coding-agent/src/core/tools/ipython.ts b/packages/coding-agent/src/core/tools/ipython.tsindex be142b9139..404bfaa15b 100644--- a/packages/coding-agent/src/core/tools/ipython.ts+++ b/packages/coding-agent/src/core/tools/ipython.ts@@ -1,10 +1,17 @@// TODO: reconsider whether the persistent kernel is needed once RLM-1 weights land.import { existsSync } from "node:fs";import type { AgentTool } from "@earendil-works/pi-agent-core";+import type { ImageContent, TextContent } from "@earendil-works/pi-ai";import { type Static, Type } from "typebox";+import { IMAGE_MIME_TYPES } from "../../utils/mime.js";import type { ToolDefinition } from "../extensions/types.js";import type { KernelBootstrapProgressHandler } from "../kernel/bootstrap.js";-import { type HostRequestHandlers, type KernelDiffDisplay, KernelManager } from "../kernel/index.js";+import {+ type HostRequestHandlers,+ type KernelAttachment,+ type KernelDiffDisplay,+ KernelManager,+} from "../kernel/index.js";import { manifestPathIn, type RestoreResult, snapshotPathIn } from "../kernel/state-snapshot.js";import type { PythonSkillRuntimeInfo } from "../skills.js";import { wrapToolDefinition } from "./tool-definition-wrapper.js";@@ -128,6 +135,8 @@ export interface IpythonToolDetails {result?: string;/** Diffs streamed from file edits, rendered by the IPython cell. */diffs?: KernelDiffDisplay[];+ /** Media attachments loaded into context (e.g. by the attach-image skill). */+ attachments?: KernelAttachment[];error?: {ename: string;evalue: string;@@ -325,6 +334,14 @@ export class IpythonKernelProvisioner {}}+/** Turn kernel image attachments into `ImageContent` blocks; non-image types are dropped. */+export function imageBlocksFromAttachments(attachments: readonly KernelAttachment[] | undefined): ImageContent[] {+ if (!attachments) return [];+ return attachments+ .filter((a) => IMAGE_MIME_TYPES.has(a.mimeType))+ .map((a) => ({ type: "image", data: a.data, mimeType: a.mimeType }));+}+export function createIpythonToolDefinition(cwd: string,options?: IpythonToolOptions,@@ -370,8 +387,11 @@ export function createIpythonToolDefinition(text += (text ? "\n" : "") + r.error.traceback.join("\n");}+ const imageBlocks = imageBlocksFromAttachments(r.attachments);+ const content: (TextContent | ImageContent)[] = [{ type: "text", text: text || "" }, ...imageBlocks];+return {- content: [{ type: "text", text: text || "" }],+ content,details: {durationMs: r.durationMs,status: r.status,@@ -380,6 +400,7 @@ export function createIpythonToolDefinition(stderr: r.stderr,result: r.result,diffs: r.diffs,+ attachments: r.attachments,error: r.error,},isError: r.status === "error" || r.status === "aborted",diff --git a/packages/coding-agent/src/utils/mime.ts b/packages/coding-agent/src/utils/mime.tsindex f9ded46e24..401e76fbf7 100644--- a/packages/coding-agent/src/utils/mime.ts+++ b/packages/coding-agent/src/utils/mime.ts@@ -1,7 +1,7 @@import { open } from "node:fs/promises";import { fileTypeFromBuffer } from "file-type";-const IMAGE_MIME_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);+export const IMAGE_MIME_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);const FILE_TYPE_SNIFF_BYTES = 4100;diff --git a/packages/coding-agent/test/ipython-attachments.test.ts b/packages/coding-agent/test/ipython-attachments.test.tsnew file mode 100644index 0000000000..599a7e2df3--- /dev/null+++ b/packages/coding-agent/test/ipython-attachments.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from "vitest";+import type { KernelAttachment } from "../src/core/kernel/index.js";+import { imageBlocksFromAttachments } from "../src/core/tools/ipython.js";++describe("imageBlocksFromAttachments", () => {+ it("returns no blocks when there are no attachments", () => {+ expect(imageBlocksFromAttachments(undefined)).toEqual([]);+ expect(imageBlocksFromAttachments([])).toEqual([]);+ });++ it("converts supported image attachments to ImageContent blocks", () => {+ const attachments: KernelAttachment[] = [+ { mimeType: "image/png", data: "AAAA", path: "/tmp/a.png" },+ { mimeType: "image/jpeg", data: "BBBB" },+ ];+ expect(imageBlocksFromAttachments(attachments)).toEqual([+ { type: "image", data: "AAAA", mimeType: "image/png" },+ { type: "image", data: "BBBB", mimeType: "image/jpeg" },+ ]);+ });++ it("drops non-image attachments", () => {+ const attachments: KernelAttachment[] = [+ { mimeType: "application/pdf", data: "CCCC" },+ { mimeType: "image/webp", data: "DDDD" },+ ];+ expect(imageBlocksFromAttachments(attachments)).toEqual([+ { type: "image", data: "DDDD", mimeType: "image/webp" },+ ]);+ });+});diff --git a/packages/coding-agent/test/kernel-attach-image-skill.test.ts b/packages/coding-agent/test/kernel-attach-image-skill.test.tsnew file mode 100644index 0000000000..9c6b1fbd43--- /dev/null+++ b/packages/coding-agent/test/kernel-attach-image-skill.test.ts@@ -0,0 +1,126 @@+import { mkdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { getBundledSkillsDir } from "../src/config.js";+import type { PythonSkillRuntimeInfo } from "../src/core/skills.js";+import { IpythonKernelProvisioner, imageBlocksFromAttachments } from "../src/core/tools/ipython.js";++// 1x1 transparent PNG.+const PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";++function bundledAttachImageSkill(): PythonSkillRuntimeInfo {+ const packagePath = join(getBundledSkillsDir(), "attach-image");+ return {+ name: "attach-image",+ importName: "attach_image",+ packagePath,+ pyprojectPath: join(packagePath, "pyproject.toml"),+ };+}++describe("attach-image skill over the kernel host bridge", () => {+ let tempDir: string;+ let provisioner: IpythonKernelProvisioner | undefined;++ beforeEach(() => {+ tempDir = join(tmpdir(), `pi-attach-image-${Date.now()}-${Math.random().toString(36).slice(2)}`);+ mkdirSync(tempDir, { recursive: true });+ });++ afterEach(async () => {+ await provisioner?.dispose();+ provisioner = undefined;+ rmSync(tempDir, { recursive: true, force: true });+ });++ it("loads an on-disk image into the tool result as an ImageContent block", async () => {+ const imagePath = join(tempDir, "sample.png");+ writeFileSync(imagePath, 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(`print(await attach_image(${JSON.stringify(imagePath)}))`);++ expect(result.status).toBe("ok");+ expect(result.stdout.trim()).toContain("Loaded 1 image(s) into context");+ expect(result.attachments).toHaveLength(1);+ expect(result.attachments?.[0]?.mimeType).toBe("image/png");+ expect(result.attachments?.[0]?.data).toBe(PNG_BASE64);++ const blocks = imageBlocksFromAttachments(result.attachments);+ expect(blocks).toEqual([{ type: "image", data: PNG_BASE64, mimeType: "image/png" }]);+ });++ 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"));++ provisioner = new IpythonKernelProvisioner(tempDir, {+ pythonSkills: [bundledAttachImageSkill()],+ hostHandlers: {+ "model.info": async () => ({ id: "openai/gpt-oss-120b", input: ["text"] }),+ },+ });++ const manager = await provisioner.ensure();+ const result = await manager.execute(`+try:+ await attach_image(${JSON.stringify(imagePath)})+except RuntimeError as error:+ print(f"RuntimeError: {error}")+`);++ expect(result.status).toBe("ok");+ expect(result.stdout.trim()).toBe(+ "RuntimeError: openai/gpt-oss-120b does not support vision. " ++ "Tell the user to switch to a vision-capable model to load images into context.",+ );+ expect(result.attachments).toBeUndefined();+ });++ it("rejects a non-image file", async () => {+ const notImage = join(tempDir, "notes.txt");+ writeFileSync(notImage, "just text");++ 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(`+try:+ await attach_image(${JSON.stringify(notImage)})+except ValueError as error:+ print(f"ValueError: {error}")+`);++ expect(result.status).toBe("ok");+ expect(result.stdout.trim()).toContain("is not a supported image");+ expect(result.attachments).toBeUndefined();+ });++ it("fails the cell loudly when an emitted attachment exceeds the size cap", async () => {+ provisioner = new IpythonKernelProvisioner(tempDir, { pythonSkills: [] });+ const manager = await provisioner.ensure();+ // Emit an oversized attachment directly, bypassing the skill's own cap.+ const result = await manager.execute(`+from IPython.display import display+display({"application/vnd.prime-agent.attachment+json": {"mime_type": "image/png", "data": "A" * 10_000_001}}, raw=True)+print("done")+`);++ expect(result.status).toBe("error");+ expect(result.stderr).toContain("attachment dropped");+ expect(result.attachments).toBeUndefined();+ });+});