Skip to content

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

Merge main and preserve native image ordering

Steven Enamakel0f2ee7100cc6
diff --cc src/openhuman/agent/multimodal.rs
index 3923d8711a,2f7b023735..d15c31a5da
--- a/src/openhuman/agent/multimodal.rs
+++ b/src/openhuman/agent/multimodal.rs
@@@ -548,6 -548,6 +548,19 @@@ pub fn rehydrate_image_placeholders(mes
.collect()
}
++/// Whether a path is an existing file inside the managed attachment stash.
++/// Provider input must never treat an arbitrary user-supplied marker as a
++/// filesystem read request.
++pub fn is_managed_attachment_path(path: &str) -> bool {
++ let Ok(candidate) = std::fs::canonicalize(path) else {
++ return false;
++ };
++ let Ok(root) = std::fs::canonicalize(attachments_dir()) else {
++ return false;
++ };
++ candidate.starts_with(root) && candidate.is_file()
++}
++
// ── The on-disk attachment stash ─────────────────────────────────────────
/// Soft cap on the on-disk attachments directory. After each write, oldest
diff --cc src/openhuman/inference/provider/claude_code/input_builder.rs
index 6195ac45d0,25a7d90b63..aca181186b
--- a/src/openhuman/inference/provider/claude_code/input_builder.rs
+++ b/src/openhuman/inference/provider/claude_code/input_builder.rs
@@@ -15,7 -22,6 +15,9 @@@ 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, parse_image_markers, 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).
@@@ -106,67 -104,6 +108,78 @@@ fn prior_conversation_preamble(non_syst
))
}
+/// 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.
+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 {
++ let mut cursor = 0;
++ while let Some(relative) = raw[cursor..].find("[IMAGE:") {
++ let start = cursor + relative;
++ let Some(end_relative) = raw[start..].find(']') else {
++ break;
++ };
++ let end = start + end_relative + 1;
++ if start > cursor {
++ blocks.push(json!({"type": "text", "text": &raw[cursor..start]}));
++ }
++ let reference = &raw[start + "[IMAGE:".len()..end - 1];
+ match image_block(reference) {
+ Some(block) => blocks.push(block),
- None => blocks.push(json!({
- "type": "text",
- "text": "[an attached image could not be read]"
- })),
++ None => blocks
++ .push(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
+}
+
+/// 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())
+ } else {
++ if !is_managed_attachment_path(reference) {
++ return None;
++ }
+ let bytes = std::fs::read(reference).ok()?;
+ (
+ media_type_from_path(reference),
+ base64::engine::general_purpose::STANDARD.encode(bytes),
+ )
+ };
+ Some(json!({
+ "type": "image",
+ "source": {"type": "base64", "media_type": media_type, "data": data_b64},
+ }))
+}
+
+/// 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"
+ }
+ .to_string()
+}
+
fn push_json_line(buf: &mut String, v: &Value) {
buf.push_str(&serde_json::to_string(v).unwrap_or_default());
buf.push('\n');
diff --cc src/openhuman/inference/provider/claude_code/input_builder_tests.rs
index 0000000000,ba1d4188b7..fd7c798e54
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 image_blocks_preserve_text_order() {
++ let s = String::from_utf8(build_stdin(
++ &[ChatMessage::user(
++ "before [IMAGE:data:image/png;base64,QUJD] between [IMAGE:data:image/gif;base64,R0lG] 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 literal_file_marker_is_not_read() {
++ let s = String::from_utf8(build_stdin(
++ &[ChatMessage::user("read [IMAGE:/etc/hostname]")],
++ true,
++ ))
++ .unwrap();
++ assert!(!s.contains("\"type\":\"image\""), "{s}");
++ assert!(s.contains("could not be read"), "{s}");
++}