Skip to content

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

fix(agent): keep tool-call groups whole when trimming session history

M3gA-Mindc9ac31eeca33
diff --git a/crates/openhuman-core/src/agent/session_host/driver.rs b/crates/openhuman-core/src/agent/session_host/driver.rs
index 34ea74284f..d5222132c7 100644
--- a/crates/openhuman-core/src/agent/session_host/driver.rs
+++ b/crates/openhuman-core/src/agent/session_host/driver.rs
@@ -81,8 +81,11 @@ impl OpenHumanSessionDriver {
impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {
async fn execute(
&self,
- request: DriverRequest<OpenHumanRunContext>,
+ mut request: DriverRequest<OpenHumanRunContext>,
) -> Result<DriverOutcome, DriverFailure> {
+ // Heal a head persisted before #6721 was fixed, before anything reads
+ // the history: this turn then commits a clean generation.
+ repair_orphaned_tool_head(&mut request.history);
// These two inputs are prepared by the OpenHuman lifecycle hook for
// this exact request. Falling back to the snapshots captured when the
// long-lived driver was constructed would let a later channel/tool
@@ -424,14 +427,44 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {
/// Preserve the stable system prefix while bounding durable conversational
/// history. The runtime owns history replacement, so this must happen before
/// its successful `DriverOutcome` is committed.
+///
+/// The cut never splits an assistant tool-call turn from its results (#6721):
+/// a history opening on an orphaned `tool` message is rejected by the provider
+/// on every later turn. `find_safe_cutoff_point` moves the cut back to keep the
+/// owning assistant turn (so the bound may be exceeded by one tool group).
fn trim_history(history: &mut Vec<Message>, max_history_messages: usize) {
- let prefix_len = history
- .iter()
- .take_while(|message| matches!(message, Message::System(_)))
- .count();
+ let prefix_len = system_prefix_len(history);
let retained = history.len().saturating_sub(prefix_len);
if retained > max_history_messages {
- history.drain(prefix_len..prefix_len + retained - max_history_messages);
+ let cut = tinyagents_harness::summarization::find_safe_cutoff_point(
+ &history[prefix_len..],
+ retained - max_history_messages,
+ );
+ history.drain(prefix_len..prefix_len + cut);
+ }
+}
+
+fn system_prefix_len(history: &[Message]) -> usize {
+ history
+ .iter()
+ .take_while(|message| matches!(message, Message::System(_)))
+ .count()
+}
+
+/// Drop `tool` messages that open the history right after the system prefix.
+/// Their assistant turn is gone (an old unpaired trim, #6721), and the provider
+/// rejects every request that carries them, so the thread can never recover
+/// without this. Later system rows (e.g. a steering nudge) are kept.
+fn repair_orphaned_tool_head(history: &mut Vec<Message>) {
+ let prefix_len = system_prefix_len(history);
+ let orphans =
+ tinyagents_harness::summarization::advance_past_orphan_tools(&history[prefix_len..], 0);
+ if orphans > 0 {
+ tracing::warn!(
+ orphans,
+ "[session_host::driver] repaired orphaned tool head: dropped {orphans} leading tool message(s)"
+ );
+ history.drain(prefix_len..prefix_len + orphans);
}
}
diff --git a/crates/openhuman-core/src/agent/session_host/driver_tests.rs b/crates/openhuman-core/src/agent/session_host/driver_tests.rs
index af235f8f6c..e9f3e4f5cf 100644
--- a/crates/openhuman-core/src/agent/session_host/driver_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/driver_tests.rs
@@ -163,3 +163,48 @@ fn tool_snapshot_with_no_executable_source_fails_closed_before_graph() {
.expect_err("a declared tool must have a request-scoped executable source");
assert!(error.error.to_string().contains("revoked_tool"));
}
+
+/// #6721: the req-029 → req-031 shape — an assistant issued 3 tool calls and
+/// the 50-message cut lands on the second result. The trimmed history must not
+/// open on an orphaned `tool` message.
+#[test]
+fn trim_history_keeps_tool_call_group_whole() {
+ let mut calling = Message::assistant("");
+ if let Message::Assistant(assistant) = &mut calling {
+ assistant.tool_calls = ["a", "b", "c"]
+ .iter()
+ .map(|id| tinyinference_llm::ToolCall::new(*id, "search", serde_json::json!({})))
+ .collect();
+ }
+ let mut history = vec![Message::system("s0"), Message::system("s1")];
+ history.extend([
+ Message::user("u0"),
+ calling,
+ Message::tool("a", "ra"),
+ Message::tool("b", "rb"),
+ Message::tool("c", "rc"),
+ Message::assistant("done"),
+ ]);
+ history.extend((0..47).map(|i| Message::user(format!("filler {i}"))));
+ // 53 non-system messages → the raw cut drops 3 and would land on tool "b".
+
+ trim_history(&mut history, 50);
+
+ assert!(
+ matches!(&history[2], Message::Assistant(a) if a.tool_calls.len() == 3),
+ "trimmed history must open on the tool-calling assistant, got {:?}",
+ history[2]
+ );
+ assert!(tinyagents_harness::summarization::tool_pairing_is_intact(
+ &history[2..]
+ ));
+}
+
+#[test]
+fn trim_history_without_tool_group_trims_to_the_bound() {
+ let mut history = vec![Message::system("s0")];
+ history.extend((0..60).map(|i| Message::user(format!("m{i}"))));
+ trim_history(&mut history, 50);
+ assert_eq!(history.len(), 51);
+ assert_eq!(history[1].text(), "m10");
+}
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
index fea4edc14c..1302700817 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
@@ -633,3 +633,134 @@ async fn artifact_store_falls_back_to_action_dir_without_a_descriptor() {
.expect("artifact store");
assert_eq!(store.root(), action_dir.path());
}
+
+/// #6721: a head persisted by the old unpaired `trim_history` opens
+/// `[system, system, tool, tool, system(nudge), assistant(calls), …]`. A failed
+/// turn commits nothing, so without a pre-request repair every later turn
+/// resends the orphans and the provider rejects it forever.
+#[test]
+fn a_resumed_orphaned_tool_head_is_repaired_before_the_request() {
+ std::thread::Builder::new()
+ .stack_size(crate::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .spawn(|| {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("test runtime")
+ .block_on(resumed_orphaned_tool_head_is_repaired_before_the_request());
+ })
+ .expect("test thread")
+ .join()
+ .expect("test thread panicked");
+}
+
+async fn resumed_orphaned_tool_head_is_repaired_before_the_request() {
+ const NUDGE: &str = "The last call failed validation. Fix the arguments and retry.";
+ let root = tempfile::tempdir().expect("tempdir");
+ let model = Arc::new(tinyagents_harness::testkit::ScriptedModel::replies(vec![
+ "first reply",
+ "second reply",
+ ]));
+ let chat_model: Arc<dyn tinyinference_llm::model::ChatModel<()>> = model.clone();
+ let new_host = || {
+ crate::agent::SessionHostBuilder::new()
+ .chat_model(chat_model.clone())
+ .tools(Vec::new())
+ .workspace_dir(root.path().join("workspace"))
+ .action_dir(root.path().to_path_buf())
+ .memory(crate::memory::test_support::noop_memory())
+ .tool_dispatcher(Box::new(tinytools_agent::dialect::NativeDialect))
+ .build()
+ .expect("session build")
+ };
+ let mut host = new_host();
+ host.set_thread_id(Some("thread-orphaned-head"));
+ assert_eq!(host.turn("first message").await.unwrap(), "first reply");
+ drop(host);
+
+ // Splice the stuck head into the transcript the real writer produced.
+ let transcripts: Vec<_> = walkdir::WalkDir::new(root.path().join("workspace/session_raw"))
+ .into_iter()
+ .filter_map(Result::ok)
+ .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "jsonl"))
+ .map(|entry| entry.into_path())
+ .collect();
+ assert_eq!(transcripts.len(), 1, "one head transcript: {transcripts:?}");
+ let rows: Vec<serde_json::Value> = std::fs::read_to_string(&transcripts[0])
+ .unwrap()
+ .lines()
+ .map(|line| serde_json::from_str(line).unwrap())
+ .collect();
+ let head_end = rows
+ .iter()
+ .position(|row| row.get("_meta").is_none() && row["role"] != "system")
+ .expect("turn 1 wrote a non-system row");
+ assert!(head_end >= 2, "fixture needs the persisted system prefix");
+ let stuck = [
+ serde_json::json!({"id": "call_orphan_a", "role": "tool", "content": "ra", "failure": true}),
+ serde_json::json!({"id": "call_orphan_b", "role": "tool", "content": "rb"}),
+ serde_json::json!({"role": "system", "content": NUDGE}),
+ // The writer's native form: the calls live in a `{content, tool_calls}`
+ // envelope serialised into `content`, mirrored at the top level.
+ serde_json::json!({"role": "assistant", "content": serde_json::json!({
+ "content": "", "tool_calls": [{"id": "call_kept", "name": "search", "arguments": "{}"}]
+ }).to_string(), "tool_calls": [
+ {"id": "call_kept", "name": "search", "arguments": "{}"}
+ ]}),
+ serde_json::json!({"id": "call_kept", "role": "tool", "content": "rk"}),
+ serde_json::json!({"role": "assistant", "content": "done"}),
+ ];
+ let spliced: Vec<String> = rows[..head_end]
+ .iter()
+ .chain(stuck.iter())
+ .chain(rows[head_end..].iter())
+ .map(|row| row.to_string())
+ .collect();
+ std::fs::write(&transcripts[0], spliced.join("\n") + "\n").unwrap();
+
+ let mut host = new_host();
+ host.set_thread_id(Some("thread-orphaned-head"));
+ assert_eq!(host.turn("second message").await.unwrap(), "second reply");
+
+ let requests = model.requests();
+ let sent = &requests
+ .last()
+ .expect("the resumed turn reached the model")
+ .messages;
+ let shape: Vec<String> = sent
+ .iter()
+ .map(|m| match m {
+ Message::System(_) => {
+ format!("system({})", m.text().chars().take(24).collect::<String>())
+ }
+ Message::User(_) => "user".into(),
+ Message::Assistant(a) => format!("assistant(calls={})", a.tool_calls.len()),
+ Message::Tool(t) => format!("tool({})", t.tool_call_id),
+ _ => "other".into(),
+ })
+ .collect();
+ // The fixture must have been read back, or the assertions below are vacuous.
+ assert!(
+ sent.iter()
+ .any(|m| matches!(m, Message::System(_)) && m.text() == NUDGE),
+ "the persisted nudge must survive the repair: {shape:?}"
+ );
+ assert!(
+ sent.iter().any(|m| matches!(
+ m,
+ Message::Assistant(a) if a.tool_calls.iter().any(|c| c.id == "call_kept")
+ )),
+ "the persisted tool-call group must be sent: {shape:?}"
+ );
+ let first_non_system = sent
+ .iter()
+ .find(|m| !matches!(m, Message::System(_)))
+ .expect("a non-system message");
+ assert!(
+ !matches!(first_non_system, Message::Tool(_)),
+ "the request must not open on an orphaned tool result, got {first_non_system:?}"
+ );
+ assert!(!sent
+ .iter()
+ .any(|m| matches!(m, Message::Tool(t) if t.tool_call_id.starts_with("call_orphan"))));
+}