Skip to content

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

Merge remote-tracking branch 'upstream/main' into pr/5738

Steven Enamakel030ad13b5d82
diff --cc src/openhuman/inference/provider/claude_code/input_builder.rs
index 9e0676612d,92920608fa..b1c44f23b6
--- a/src/openhuman/inference/provider/claude_code/input_builder.rs
+++ b/src/openhuman/inference/provider/claude_code/input_builder.rs
@@@ -90,97 -66,29 +90,81 @@@ pub fn build_stdin(messages: &[ChatMess
out.into_bytes()
}
-/// One stdin row. `role` is always `"user"` — see the module docs.
-fn user_row(text: &str) -> Value {
- json!({
- "type": "user",
- "message": {
- "role": "user",
- "content": content_blocks(text),
- },
- })
+/// Render the turns before `end` (the latest user turn) as a plain-text preamble
+/// so a newly-created CC session inherits the thread's context — the CLI can't
+/// accept assistant-role input, so this is the only way to seed prior turns.
+///
+/// A user turn with no assistant reply after it is skipped: that is a failed or
+/// pending attempt (e.g. a message that errored and was then re-asked), not part
+/// of the conversation. Replaying it would duplicate the re-asked current turn
+/// and make the message look like it "came through twice". Image markers are
- /// stripped (only the latest turn re-sends its images). Returns `None` when
++/// preserved so a recreated session retains the same multimodal context. Returns `None` when
+/// there is nothing to carry over (a genuinely fresh conversation).
+fn prior_conversation_preamble(non_system: &[&ChatMessage], end: usize) -> Option<String> {
+ let mut turns = Vec::new();
+ for (i, m) in non_system.iter().take(end).enumerate() {
+ match m.role.as_str() {
+ "assistant" => {
+ let (text, _images) = parse_image_markers(&m.content);
+ if !text.is_empty() {
+ turns.push(format!("Assistant: {text}"));
+ }
+ }
+ "user" => {
+ // A consecutive group of user turns is answered when the
+ // assistant follows the group. This preserves queued
+ // steering messages while omitting a trailing attempt.
+ let mut next = i + 1;
+ while non_system
+ .get(next)
+ .is_some_and(|message| message.role == "user")
+ {
+ next += 1;
+ }
+ let answered = non_system
+ .get(next)
+ .is_some_and(|message| message.role == "assistant");
+ if answered && !m.content.is_empty() {
- let (text, _images) = parse_image_markers(&m.content);
- let text = strip_native_image_markers(&text);
- if !text.is_empty() {
- turns.push(format!("User: {text}"));
- }
++ // Keep native image markers in the labelled transcript.
++ // `content_blocks` below will convert real markers into
++ // image blocks while leaving literal marker text alone.
++ turns.push(format!("User: {}", m.content));
+ }
+ }
+ _ => {}
+ }
+ }
+ if turns.is_empty() {
+ return None;
+ }
+ Some(format!(
+ "[Earlier in this conversation]\n{}\n[End of earlier conversation]\n",
+ turns.join("\n")
+ ))
}
- fn strip_native_image_markers(mut text: &str) -> String {
- const PREFIX: &str = "[OH_IMAGE:";
- let mut cleaned = String::with_capacity(text.len());
- while let Some(start) = text.find(PREFIX) {
- cleaned.push_str(&text[..start]);
- let rest = &text[start + PREFIX.len()..];
- let Some(end) = rest.find(']') else {
- return cleaned;
- };
- text = &rest[end + 1..];
- }
- cleaned.push_str(text);
- cleaned
- }
-
+/// 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> {
- const MAX_IMAGES_PER_MESSAGE: usize = 16;
- let mut blocks = Vec::new();
+ const IMAGE_PREFIX: &str = "[IMAGE:";
+ const NATIVE_IMAGE_PREFIX: &str = "[OH_IMAGE:";
+ const LITERAL_NATIVE_IMAGE_PREFIX: &str = "[OH_IMAGE_LITERAL:";
+ let mut blocks: Vec<Value> = Vec::new();
let mut cursor = 0;
- let mut image_count = 0;
- while let Some(relative) = raw[cursor..].find("[IMAGE:") {
+ while let Some((relative, prefix)) = [
+ IMAGE_PREFIX,
+ NATIVE_IMAGE_PREFIX,
+ LITERAL_NATIVE_IMAGE_PREFIX,
+ ]
+ .iter()
+ .filter_map(|prefix| raw[cursor..].find(prefix).map(|offset| (offset, *prefix)))
+ .min_by_key(|(offset, _)| *offset)
+ {
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..]}));
+ blocks.push(json!({"type": "text", "text": &raw[cursor..]}));
cursor = raw.len();
break;
};
diff --cc src/openhuman/inference/provider/claude_code/input_builder_tests.rs
index 30b82753bb,98b8e399c5..0385deab36
--- a/src/openhuman/inference/provider/claude_code/input_builder_tests.rs
+++ b/src/openhuman/inference/provider/claude_code/input_builder_tests.rs
@@@ -157,22 -163,22 +157,22 @@@ fn literal_file_marker_is_not_read()
}
#[test]
-fn readable_managed_image_file_emits_an_image_block() {
- let dir = crate::openhuman::agent::multimodal::managed_attachments_dir_for_tests();
- std::fs::create_dir_all(&dir).unwrap();
- let path = dir.join(format!("input-builder-test-{}.png", std::process::id()));
- std::fs::write(&path, b"PNG").unwrap();
- let s = String::from_utf8(build_stdin(
- &[msg("user", &format!("file [IMAGE:{}]", path.display()))],
- true,
- ))
- .unwrap();
+fn new_session_history_preserves_answered_user_images() {
+ let history = vec![
+ ChatMessage::user("earlier [OH_IMAGE:data:image/png;base64,QUJD]"),
+ ChatMessage::assistant("old answer"),
+ ChatMessage::user("latest"),
+ ];
+ let s = String::from_utf8(build_stdin(&history, true)).unwrap();
let row: Value = serde_json::from_str(s.lines().next().unwrap()).unwrap();
let content = row["message"]["content"].as_array().unwrap();
- assert!(!content.iter().any(|block| block["type"] == "image"));
- assert!(content.len() >= 2, "expected text and image blocks: {s}");
- assert_eq!(content[1]["type"], "image");
- assert_eq!(content[1]["source"]["data"], "UE5H");
- let _ = std::fs::remove_file(path);
++ assert!(content.iter().any(|block| block["type"] == "image"));
+ assert!(content.iter().any(|block| {
+ block["text"]
+ .as_str()
+ .is_some_and(|text| text.contains("User: earlier "))
+ }));
+ assert!(s.contains("Assistant: old answer"));
}
#[test]