Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(claude-code): preserve safe ordered image blocks

Steven Enamakel0f38bdb340e7
diff --cc src/openhuman/agent/multimodal.rs
index 92a03924e0,2f7b023735..d28d7e7c31
--- a/src/openhuman/agent/multimodal.rs
+++ b/src/openhuman/agent/multimodal.rs
@@@ -593,11 -586,11 +586,24 @@@ fn attachments_dir() -> PathBuf
.unwrap_or_else(fallback_attachments_dir)
}
- /// Per-user fallback attachments dir used only when [`init_attachments_dir`] was
- /// never called. Uses the OS user cache dir (e.g. `~/Library/Caches/...`,
- /// `~/.cache/...`) so persisted image bytes aren't dropped into a world-readable
- /// shared `temp_dir()` on multi-user hosts. Only falls back to `temp_dir()` when
- /// no user cache dir can be resolved at all.
++/// Whether a provider image reference points inside this process' managed
++/// attachment stash. Raw channel-supplied filesystem paths are never trusted.
++pub fn is_managed_attachment_path(path: &str) -> bool {
++ let candidate = Path::new(path);
++ let Ok(candidate) = candidate.canonicalize() else {
++ return false;
++ };
++ let Ok(root) = attachments_dir().canonicalize() else {
++ return false;
++ };
++ candidate.starts_with(root)
++}
++
+ /// Per-user fallback attachments dir used only when [`init_attachments_dir`]
+ /// was never called. Uses the OS user cache dir (e.g. `~/Library/Caches/…`,
+ /// `~/.cache/…`) so persisted image bytes aren't dropped into a world-readable
+ /// shared `temp_dir()` on multi-user hosts. Only falls back to `temp_dir()`
+ /// when no user cache dir can be resolved at all.
fn fallback_attachments_dir() -> PathBuf {
directories::BaseDirs::new()
.map(|d| d.cache_dir().join("openhuman-attachments"))
diff --cc src/openhuman/inference/provider/claude_code/input_builder.rs
index f59a223c93,25a7d90b63..22a8f7de44
--- a/src/openhuman/inference/provider/claude_code/input_builder.rs
+++ b/src/openhuman/inference/provider/claude_code/input_builder.rs
@@@ -15,17 -22,10 +23,15 @@@ use base64::Engine as _
use serde_json::{json, Value};
use crate::openhuman::agent::messages::ChatMessage;
- use crate::openhuman::agent::multimodal::{parse_image_markers, rehydrate_image_placeholders};
++use crate::openhuman::agent::multimodal::{
++ is_managed_attachment_path, rehydrate_image_placeholders,
++};
/// Build the bytes to write to claude's stdin. Returns an empty `Vec`
/// when there is nothing to send (caller should abort).
pub fn build_stdin(messages: &[ChatMessage], is_new_session: bool) -> Vec<u8> {
- // Resolve any `[Image: … #att:<id>]` placeholders to on-disk `[IMAGE:<path>]`
- // markers so pasted images can be inlined below. No-op for messages that
- // carry no image placeholder, so plain text turns are unaffected.
+ let rehydrated = rehydrate_image_placeholders(messages);
- let messages: &[ChatMessage] = &rehydrated;
-
++ let messages = &rehydrated;
let mut out = String::new();
let to_emit: Vec<&ChatMessage> = if is_new_session {
messages.iter().filter(|m| m.role != "system").collect()
@@@ -61,65 -62,46 +68,114 @@@
out.into_bytes()
}
- /// Split a message's text into stream-json content blocks: the prose as a
- /// `text` block, plus one native `image` block per `[IMAGE:<ref>]` marker (the
- /// `claude` CLI + Opus are vision-capable). An image that cannot be read
- /// degrades to a short text note rather than being silently dropped.
+ /// One stdin row. `role` is always `"user"` — see the module docs.
+ fn user_row(text: &str) -> Value {
+ json!({
+ "type": "user",
+ "message": {
+ "role": "user",
- "content": [{"type": "text", "text": text}],
++ "content": content_blocks(text),
+ },
+ })
+ }
+
+fn content_blocks(raw: &str) -> Vec<Value> {
- let (text, image_refs) = parse_image_markers(raw);
- let mut blocks: Vec<Value> = Vec::new();
- if !text.is_empty() {
- blocks.push(json!({"type": "text", "text": text}));
- }
- for reference in &image_refs {
- match image_block(reference) {
- Some(block) => blocks.push(block),
- None => blocks.push(json!({
- "type": "text",
- "text": "[an attached image could not be read]"
- })),
++ let mut blocks = Vec::new();
++ let mut cursor = 0;
++ while let Some(relative) = raw[cursor..].find("[IMAGE:") {
++ let start = cursor + relative;
++ if start > cursor {
++ blocks.push(json!({"type":"text", "text": &raw[cursor..start]}));
+ }
++ let Some(end_relative) = raw[start..].find(']') else {
++ blocks.push(json!({"type":"text", "text": &raw[start..]}));
++ cursor = raw.len();
++ break;
++ };
++ let end = start + end_relative + 1;
++ let reference = &raw[start + 7..end - 1];
++ blocks.push(image_block(reference).unwrap_or_else(|| {
++ json!({
++ "type":"text", "text":"[an attached image could not be read]"
++ })
++ }));
++ cursor = end;
++ }
++ if cursor < raw.len() {
++ blocks.push(json!({"type":"text", "text": &raw[cursor..]}));
+ }
+ if blocks.is_empty() {
- // Preserve prior behaviour for a genuinely empty message.
- blocks.push(json!({"type": "text", "text": raw}));
++ blocks.push(json!({"type":"text", "text": raw}));
+ }
+ blocks
+}
+
- /// Build an Anthropic `image` content block from an `[IMAGE:<ref>]` reference.
- /// `<ref>` is either a `data:` URI (inline base64) or an on-disk file path (a
- /// rehydrated attachment). Returns `None` when the ref cannot be resolved.
+fn image_block(reference: &str) -> Option<Value> {
- let (media_type, data_b64) = if let Some(rest) = reference.strip_prefix("data:") {
- let (mime, data) = rest.split_once(";base64,")?;
- (mime.to_string(), data.to_string())
++ let (media_type, data) = if let Some(rest) = reference.strip_prefix("data:") {
++ let (mime, encoded) = rest.split_once(";base64,")?;
++ let bytes = base64::engine::general_purpose::STANDARD
++ .decode(encoded)
++ .ok()?;
++ if bytes.len() > 20 * 1024 * 1024 {
++ return None;
++ }
++ (mime.to_string(), encoded.to_string())
+ } else {
++ if !is_managed_attachment_path(reference) {
++ return None;
++ }
++ let metadata = std::fs::metadata(reference).ok()?;
++ if metadata.len() > 20 * 1024 * 1024 {
++ return None;
++ }
+ let bytes = std::fs::read(reference).ok()?;
++ let lower = reference.to_ascii_lowercase();
++ let mime = if lower.ends_with(".png") {
++ "image/png"
++ } else if lower.ends_with(".gif") {
++ "image/gif"
++ } else if lower.ends_with(".webp") {
++ "image/webp"
++ } else {
++ "image/jpeg"
++ };
+ (
- media_type_from_path(reference),
++ mime.to_string(),
+ base64::engine::general_purpose::STANDARD.encode(bytes),
+ )
+ };
- Some(json!({
- "type": "image",
- "source": {"type": "base64", "media_type": media_type, "data": data_b64},
- }))
++ Some(json!({"type":"image", "source":{"type":"base64", "media_type":media_type, "data":data}}))
+}
+
- /// Best-effort media type from a file extension. Claude accepts jpeg/png/gif/webp.
- fn media_type_from_path(path: &str) -> String {
- let lower = path.to_ascii_lowercase();
- if lower.ends_with(".png") {
- "image/png"
- } else if lower.ends_with(".gif") {
- "image/gif"
- } else if lower.ends_with(".webp") {
- "image/webp"
- } else {
- "image/jpeg"
+ /// Fold prior turns into a single labelled transcript, or `None` when there
+ /// is nothing to carry.
+ ///
+ /// Labelling matters: without it the model receives what looks like several
+ /// consecutive user messages and can read its own past replies as fresh
+ /// instructions.
+ fn render_transcript(history: &[&ChatMessage]) -> Option<String> {
+ let mut body = String::new();
+ for msg in history {
+ let speaker = match msg.role.as_str() {
+ "user" => "User",
+ "assistant" => "Assistant",
+ // CC stdin doesn't accept `system` or `tool` rows. The system
+ // prompt is plumbed via `--append-system-prompt`; tool roles
+ // belong to the harness, not the CLI's input format.
+ _ => continue,
+ };
+ body.push_str(speaker);
+ body.push_str(": ");
+ body.push_str(&msg.content);
+ body.push('\n');
}
- .to_string()
+ if body.is_empty() {
+ return None;
+ }
+ Some(format!(
+ "Earlier conversation, for context only — do not answer it again:\n\n{}",
+ body.trim_end()
+ ))
}
fn push_json_line(buf: &mut String, v: &Value) {
diff --cc src/openhuman/inference/provider/claude_code/input_builder_tests.rs
index 0000000000,ba1d4188b7..d6084bb35c
mode 000000,100644..100644
--- a/src/openhuman/inference/provider/claude_code/input_builder_tests.rs
+++ b/src/openhuman/inference/provider/claude_code/input_builder_tests.rs
@@@ -1,0 -1,128 +1,158 @@@
+ use super::*;
+
+ fn msg(role: &str, content: &str) -> ChatMessage {
+ match role {
+ "system" => ChatMessage::system(content),
+ "user" => ChatMessage::user(content),
+ "assistant" => ChatMessage::assistant(content),
+ _ => ChatMessage::tool(content),
+ }
+ }
+
+ /// Every row's `message.role` must be `"user"`. The CLI validates this
+ /// before invoking the model and exits 1 with
+ /// `Expected message role 'user', got 'assistant'` otherwise (#5711).
+ /// Verified against Claude Code CLI 2.1.221.
+ fn assert_every_row_is_a_user_role(payload: &str) {
+ for (i, line) in payload.lines().enumerate() {
+ let row: Value = serde_json::from_str(line).unwrap_or_else(|e| {
+ panic!(
+ "row {i} is not valid JSON: {e}
+ {line}"
+ )
+ });
+ assert_eq!(
+ row["message"]["role"], "user",
+ "row {i} must carry role=user, the only role CC stdin accepts
+ {line}"
+ );
+ assert_eq!(row["type"], "user", "row {i} envelope type");
+ }
+ }
+
+ #[test]
+ fn new_session_never_emits_an_assistant_role() {
+ let history = vec![
+ msg("system", "you are helpful"),
+ msg("user", "first user"),
+ msg("assistant", "prior assistant"),
+ msg("user", "latest user"),
+ ];
+ let s = String::from_utf8(build_stdin(&history, true)).unwrap();
+ assert_every_row_is_a_user_role(&s);
+ assert!(
+ !s.contains("\"role\":\"assistant\""),
+ "an assistant role row is what the CLI rejects:
+ {s}"
+ );
+ }
+
+ #[test]
+ fn new_session_carries_prior_turns_as_one_labelled_transcript() {
+ let history = vec![
+ msg("system", "you are helpful"),
+ msg("user", "hi"),
+ msg("assistant", "hello"),
+ msg("user", "how are you?"),
+ ];
+ let s = String::from_utf8(build_stdin(&history, true)).unwrap();
+ let lines: Vec<_> = s.lines().collect();
+
+ // One transcript row + the latest user turn. The system row is still
+ // filtered out — it rides `--append-system-prompt`.
+ assert_eq!(
+ lines.len(),
+ 2,
+ "got:
+ {s}"
+ );
+ assert!(lines[0].contains("User: hi"));
+ assert!(lines[0].contains("Assistant: hello"));
+ assert!(
+ !lines[0].contains("you are helpful"),
+ "the system message must not leak into the transcript"
+ );
+
+ // The prompt itself is passed through untouched, not folded in.
+ let latest: Value = serde_json::from_str(lines[1]).unwrap();
+ assert_eq!(latest["message"]["content"][0]["text"], "how are you?");
+ }
+
+ #[test]
+ fn a_history_ending_on_an_assistant_turn_is_all_context() {
+ // Switching an existing conversation to the CC provider can leave the
+ // assistant speaking last; none of it is a fresh instruction.
+ let history = vec![msg("user", "hi"), msg("assistant", "hello")];
+ let s = String::from_utf8(build_stdin(&history, true)).unwrap();
+ let lines: Vec<_> = s.lines().collect();
+ assert_eq!(
+ lines.len(),
+ 1,
+ "got:
+ {s}"
+ );
+ assert_every_row_is_a_user_role(&s);
+ assert!(lines[0].contains("User: hi"));
+ assert!(lines[0].contains("Assistant: hello"));
+ }
+
+ #[test]
+ fn a_single_user_turn_is_sent_verbatim_with_no_transcript() {
+ let history = vec![msg("user", "just this")];
+ let s = String::from_utf8(build_stdin(&history, true)).unwrap();
+ let lines: Vec<_> = s.lines().collect();
+ assert_eq!(lines.len(), 1);
+ let row: Value = serde_json::from_str(lines[0]).unwrap();
+ assert_eq!(row["message"]["content"][0]["text"], "just this");
+ }
+
+ #[test]
+ fn resume_pipes_only_last_user_turn() {
+ let history = vec![
+ msg("user", "earlier turn"),
+ msg("assistant", "earlier reply"),
+ msg("user", "follow-up"),
+ ];
+ let bytes = build_stdin(&history, false);
+ let s = String::from_utf8(bytes).unwrap();
+ let lines: Vec<_> = s.lines().collect();
+ assert_eq!(lines.len(), 1);
+ assert!(lines[0].contains("\"follow-up\""));
+ assert_every_row_is_a_user_role(&s);
+ }
+
+ #[test]
+ fn empty_history_yields_empty_bytes() {
+ let bytes = build_stdin(&[], true);
+ assert!(bytes.is_empty());
+ }
++
++#[test]
++fn interleaved_text_and_images_keep_source_order() {
++ let s = String::from_utf8(build_stdin(
++ &[msg("user", "before [IMAGE:data:image/png;base64,QUJD] between [IMAGE:data:image/jpeg;base64,REVG] after")],
++ true,
++ )).unwrap();
++ let row: Value = serde_json::from_str(s.lines().next().unwrap()).unwrap();
++ let content = row["message"]["content"].as_array().unwrap();
++ assert_eq!(content.len(), 5);
++ assert_eq!(content[0]["text"], "before ");
++ assert_eq!(content[1]["type"], "image");
++ assert_eq!(content[2]["text"], " between ");
++ assert_eq!(content[3]["type"], "image");
++ assert_eq!(content[4]["text"], " after");
++}
++
++#[test]
++fn unmanaged_and_unreadable_images_degrade_without_reading_paths() {
++ let s = String::from_utf8(build_stdin(
++ &[msg(
++ "user",
++ "before [IMAGE:/etc/passwd] after [IMAGE:/definitely/missing.png]",
++ )],
++ true,
++ ))
++ .unwrap();
++ assert!(s.contains("before ") && s.contains(" after"));
++ assert_eq!(s.matches("an attached image could not be read").count(), 2);
++}