Skip to content

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

Merge upstream main and resolve Claude Code test conflict

Steven Enamakelf1a45b4e9187
diff --cc src/openhuman/inference/provider/claude_code/driver.rs
index 4b9cb7e64a,60fb2a0422..870919ca6e
--- a/src/openhuman/inference/provider/claude_code/driver.rs
+++ b/src/openhuman/inference/provider/claude_code/driver.rs
@@@ -16,30 -16,62 +16,84 @@@ use tokio::sync::mpsc
/// Hard timeout per turn (PLAN §8). If the CLI hangs (network stall,
/// infinite loop, MCP deadlock) we kill the child and surface a timeout.
- const TURN_TIMEOUT: Duration = Duration::from_secs(300);
+ const DEFAULT_TURN_TIMEOUT_SECS: u64 = 900;
+
+ /// Hard timeout per turn, overridable with
+ /// `OPENHUMAN_CLAUDE_CODE_TURN_TIMEOUT_SECS`.
+ ///
+ /// The default matches the harness's own 900s wall-clock backstop. It used to
+ /// be 300s, which is shorter than a turn the CLI is *expected* to take once
+ /// full access lets it run its own tools: the child was killed mid-work and the
+ /// turn surfaced as a provider timeout rather than a slow answer.
+ fn turn_timeout() -> Duration {
+ let secs = std::env::var("OPENHUMAN_CLAUDE_CODE_TURN_TIMEOUT_SECS")
+ .ok()
+ .and_then(|raw| raw.trim().parse::<u64>().ok())
+ .filter(|secs| *secs > 0)
+ .unwrap_or(DEFAULT_TURN_TIMEOUT_SECS);
+ Duration::from_secs(secs)
+ }
+
+ /// Classify the shape of an unparsable stream line without quoting it.
+ ///
+ /// This says whether Claude spoke JSON at all - the one thing that tells a
+ /// crashed CLI apart from a protocol change - and nothing about what the line
+ /// said.
+ fn parse_error_line_shape(line: &str) -> &'static str {
+ match line.trim_start().chars().next() {
+ Some('{') => "json object",
+ Some('[') => "json array",
+ Some('"') => "json string",
+ Some(_) => "non-json",
+ None => "blank",
+ }
+ }
+
+ /// Render the log line for a `ParseError` event, or `None` for anything else.
+ ///
+ /// The parser keeps `ParseError` precisely so an unparsable line is reported
+ /// instead of vanishing, but the event mapper turns it into no deltas - so the
+ /// driver loop is the only place left that can say anything about it.
+ ///
+ /// The line itself is never quoted. It is whatever Claude Code wrote to
+ /// stdout (a malformed event, or a well-formed one of an unknown type), so it
+ /// can carry the user's prompt, the model's reply, or a credential, and the
+ /// desktop build routes `log` into rotating support logs and Sentry
+ /// breadcrumbs. Shape, size, and the parser's own reason are enough to act on;
+ /// content is not.
+ fn parse_error_log_line(ev: &ClaudeCodeEvent) -> Option<String> {
+ let ClaudeCodeEvent::ParseError { line, reason } = ev else {
+ return None;
+ };
+ Some(format!(
+ "[claude-code][driver] dropping unparsable stream line ({reason}): {} of {} bytes",
+ parse_error_line_shape(line),
+ line.len()
+ ))
+ }
+/// How much of the child's stderr we keep for diagnostics.
+const STDERR_DIAGNOSTIC_CAP: usize = 16_384;
+
+/// Append `chunk` to `acc`, keeping at most `max_bytes` and never splitting a
+/// character.
+///
+/// `String::truncate` takes a *byte* index and panics when it is not a character
+/// boundary, so bounding this accumulator with `acc.truncate(16_384)` aborted the
+/// task the moment a multi-byte character straddled the cap. The panic happened
+/// inside `tokio::spawn`, and the join is `unwrap_or_default()`, so it surfaced as
+/// an empty stderr string: the operator lost the whole error output for that turn
+/// and saw `exit Some(1) stderr=`.
+fn push_bounded(acc: &mut String, chunk: &str, max_bytes: usize) {
+ acc.push_str(chunk);
+ if acc.len() > max_bytes {
+ let keep = utf8_safe_prefix_at_byte_boundary(acc, max_bytes).len();
+ acc.truncate(keep);
+ }
+}
+
+use crate::openhuman::util::text::utf8_safe_prefix_at_byte_boundary;
+
use super::event_mapper::EventMapper;
use super::input_builder::build_stdin;
use super::session_store::{generate_uuid_v4, is_uuid_v4, SessionStore};
diff --cc src/openhuman/inference/provider/claude_code/driver_tests.rs
index de3951a74d,5a63bb8df6..e3bfa47a23
--- a/src/openhuman/inference/provider/claude_code/driver_tests.rs
+++ b/src/openhuman/inference/provider/claude_code/driver_tests.rs
@@@ -1,3 -1,3 +1,4 @@@
++
use super::*;
#[test]
@@@ -179,46 -179,62 +180,103 @@@ fn full_access_reads_persisted_toggle_w
let _ = std::fs::remove_dir_all(&ws);
}
+/// `String::truncate` takes a byte index and panics when it is not a character
+/// boundary, so bounding the stderr accumulator with `acc.truncate(16_384)`
+/// aborted the drain task whenever a multi-byte character straddled the cap.
+/// The join is `unwrap_or_default()`, so the operator saw `stderr=` and lost
+/// the whole error output for that turn.
+#[test]
+fn push_bounded_never_splits_a_character() {
+ // "aéb" is 4 bytes: a=0, é=1..2, b=3. A cap of 2 lands *inside* 'é', so the
+ // helper must back up to byte 1 -- `String::truncate(2)` would panic here.
+ let mut acc = String::new();
- push_bounded(&mut acc, "aéb", 2);
++ super::push_bounded(&mut acc, "aéb", 2);
+ assert_eq!(acc, "a", "must back up to the boundary, not split it");
+
+ // A cap of 3 lands exactly on a boundary, so nothing is given up needlessly.
+ let mut acc = String::new();
- push_bounded(&mut acc, "aéb", 3);
++ super::push_bounded(&mut acc, "aéb", 3);
+ assert_eq!(acc, "aé");
+ assert!(acc.len() <= 3);
+
+ // The same, driven the way the reader does it: many small chunks over the cap.
+ let mut acc = String::new();
+ for _ in 0..600 {
- push_bounded(&mut acc, "日本語テキスト", 1024);
++ super::push_bounded(&mut acc, "日本語テキスト", 1024);
+ }
+ assert!(acc.len() <= 1024);
+ // The real assertion: it is still valid UTF-8 and did not panic getting here.
+ assert!(std::str::from_utf8(acc.as_bytes()).is_ok());
+}
+
+#[test]
+fn push_bounded_keeps_everything_below_the_cap() {
+ let mut acc = String::new();
- push_bounded(&mut acc, "hello ", 64);
- push_bounded(&mut acc, "world", 64);
++ super::push_bounded(&mut acc, "hello ", 64);
++ super::push_bounded(&mut acc, "world", 64);
+ assert_eq!(acc, "hello world");
+}
+
+#[test]
+fn push_bounded_handles_an_ascii_cap_exactly() {
+ let mut acc = String::new();
- push_bounded(&mut acc, "abcdef", 3);
++ super::push_bounded(&mut acc, "abcdef", 3);
+ assert_eq!(acc, "abc");
+}
+ #[test]
+ fn parse_error_events_produce_a_log_line() {
+ let ev = ClaudeCodeEvent::ParseError {
+ line: "{not json".to_string(),
+ reason: "expected value at line 1 column 2".to_string(),
+ };
+ let msg = parse_error_log_line(&ev).expect("a ParseError must be reported");
+ assert!(msg.contains("expected value at line 1 column 2"), "{msg}");
+ assert!(msg.contains("9 bytes"), "{msg}");
+ }
+
+ #[test]
+ fn other_events_produce_nothing() {
+ let ev = ClaudeCodeEvent::Error {
+ message: "boom".to_string(),
+ };
+ assert!(parse_error_log_line(&ev).is_none());
+ }
+
+ /// An unparsable line can be a well-formed event of an unknown type, so it
+ /// can hold the prompt, the reply, or a credential. None of it is quoted.
+ #[test]
+ fn the_line_itself_is_never_quoted() {
+ let ev = ClaudeCodeEvent::ParseError {
+ line: r#"{"type":"secret_leak","api_key":"sk-ant-not-in-the-log"}"#.to_string(),
+ reason: "unknown event type `secret_leak`".to_string(),
+ };
+ let msg = parse_error_log_line(&ev).unwrap();
+ assert!(!msg.contains("sk-ant-not-in-the-log"), "{msg}");
+ assert!(!msg.contains("api_key"), "{msg}");
+ }
+
+ /// Size is reported instead of content, so a truncated stream still reads
+ /// differently from a chatty one.
+ #[test]
+ fn the_size_of_the_line_is_reported() {
+ let ev = ClaudeCodeEvent::ParseError {
+ line: "x".repeat(5_000),
+ reason: "trailing characters".to_string(),
+ };
+ assert!(parse_error_log_line(&ev).unwrap().contains("5000 bytes"));
+ }
+
+ #[test]
+ fn the_shape_of_the_line_is_reported() {
+ let shape = |line: &str| {
+ parse_error_log_line(&ClaudeCodeEvent::ParseError {
+ line: line.to_string(),
+ reason: "r".to_string(),
+ })
+ .unwrap()
+ };
+ assert!(shape(r#" {"type":"x"}"#).contains("json object"));
+ assert!(shape("[1,2]").contains("json array"));
+ assert!(shape("panic: claude-code crashed").contains("non-json"));
+ assert!(shape(" ").contains("blank"));
+ }
-
-use super::*;