The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(tinyagents): carry compaction to session driver for history persistence
Steven Enamakel08c14cb8a9fa
diff --git a/crates/openhuman-core/src/agent/session_host/driver.rs b/crates/openhuman-core/src/agent/session_host/driver.rsindex 6135a21cab..c171cd61eb 100644--- a/crates/openhuman-core/src/agent/session_host/driver.rs+++ b/crates/openhuman-core/src/agent/session_host/driver.rs@@ -123,11 +123,7 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {}let sidecar = request.run_context.data.session_sidecar.clone();let started = Instant::now();- let user_message = request- .history- .iter()- .rev()- .find(|message| matches!(message, Message::User(_)))+ let user_message = crate::agent::tinyagents::last_user_message(&request.history).map(crate::agent::message_convert::user_text_with_markers).unwrap_or_default();let context_window = self@@ -407,6 +403,14 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {observed.wrap_up_injected = outcome.wrap_up_injected;observed.resolved_route = outcome.resolved_route.clone();}+ // The turn compacted its context: persist the compacted history, so the+ // next turn starts from the checkpoint. The runtime session seals the+ // current generation and opens the next (the history no longer extends+ // it), so the full conversation stays on disk.+ let history = match &outcome.compaction {+ Some(carry) => carry.apply(history),+ None => history,+ };Ok(DriverOutcome {history,output: Some(output),diff --git a/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rsindex f935fd1ea6..12c628d2eb 100644--- a/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs@@ -29,6 +29,7 @@ fn classified_halt_returns_partial_work_without_provider_usage() {ToolCallOutcome { call_id: "a".into(), name: "list".into(), arguments: serde_json::json!({}), success: true, content: "three items".into(), duration_ms: 1 },ToolCallOutcome { call_id: "b".into(), name: "search".into(), arguments: serde_json::json!({}), success: false, content: "403 Forbidden".into(), duration_ms: 1 },],+ compaction: None,};let close = classified_halt_close(&outcome).expect("classified halt");assert_eq!(close.usage.model_calls, 0);diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rsindex a70f5c7967..38ff9b69e1 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs@@ -1723,14 +1723,12 @@ impl OpenHumanSessionHost {.count().max(1) as u32;let output = receipt.outcome.output.clone().unwrap_or_default();- let input = receipt- .outcome- .history- .iter()- .rev()- .find(|message| matches!(message, Message::User(_)))- .map(user_text_with_markers)- .unwrap_or_default();+ // Skips compaction checkpoints: user-role, not the+ // user's words.+ let input =+ crate::agent::tinyagents::last_user_message(&receipt.outcome.history)+ .map(user_text_with_markers)+ .unwrap_or_default();let sidecar = receipt.options.contextdiff --git a/crates/openhuman-core/src/agent/tinyagents/compaction_carry.rs b/crates/openhuman-core/src/agent/tinyagents/compaction_carry.rsnew file mode 100644index 0000000000..c4a05030a8--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/compaction_carry.rs@@ -0,0 +1,121 @@+//! Carrying a turn's context compaction into the history the session persists.+//!+//! The harness compacts by folding older messages into a checkpoint inside the+//! run (`ContextCompressionMiddleware`) and reports the folded transcript on+//! `AgentRun::compacted_history`. The session driver, though, does not persist+//! the harness transcript verbatim: it rebuilds the turn's history from the+//! request plus the post-processed conversation (grounded close, required+//! output repair). So the fold is carried as *what* replaced the old messages+//! (the checkpoint) and *how much* of the tail survived (`kept_tail`+//! non-system messages), and re-applied to that rebuilt history.+//!+//! Persisting the compacted history makes the next turn start from the+//! checkpoint instead of re-reading and re-summarizing everything this turn+//! already folded. The runtime session sees a history that no longer extends+//! the persisted one, so it seals the current transcript generation and opens+//! the next: the full conversation stays on disk.++use tinyagents_harness::summarization::{find_safe_cutoff_point, is_checkpoint};+use tinyinference_llm::message::Message;++/// A turn's compaction, in a form that can be re-applied to the history the+/// session driver assembles.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct CompactionCarry {+ /// The checkpoint message standing in for the folded history.+ pub checkpoint: Message,+ /// How many trailing non-system messages stay verbatim after it.+ pub kept_tail: usize,+}++impl CompactionCarry {+ /// The carry for a run's `compacted_history` (`None` when the run did not+ /// compact, or the history carries no checkpoint).+ pub(crate) fn from_compacted_history(compacted: &[Message]) -> Option<Self> {+ let at = compacted.iter().position(is_checkpoint)?;+ let kept_tail = compacted[at + 1..]+ .iter()+ .filter(|message| !matches!(message, Message::System(_)))+ .count();+ Some(Self {+ checkpoint: compacted[at].clone(),+ kept_tail,+ })+ }++ /// `history` with everything before its last `kept_tail` non-system+ /// messages folded into the checkpoint.+ ///+ /// Leading system messages stay first and the checkpoint follows them.+ /// System messages inside the folded range (mid-conversation notes) are+ /// kept; earlier checkpoints are dropped, since this one supersedes them.+ /// The cut is moved, if needed, so the kept tail never opens with a tool+ /// result whose call was folded. A history with nothing before the kept+ /// tail is returned unchanged.+ pub(crate) fn apply(&self, history: Vec<Message>) -> Vec<Message> {+ let lead = history+ .iter()+ .take_while(|message| matches!(message, Message::System(_)) && !is_checkpoint(message))+ .count();+ let body = &history[lead..];+ let non_system: Vec<usize> = body+ .iter()+ .enumerate()+ .filter(|(_, message)| !matches!(message, Message::System(_)))+ .map(|(index, _)| index)+ .collect();+ if self.kept_tail >= non_system.len() {+ tracing::debug!(+ kept_tail = self.kept_tail,+ messages = non_system.len(),+ "[compaction_carry] nothing to fold; persisting the history unchanged"+ );+ return history;+ }+ let requested = non_system[non_system.len() - self.kept_tail];+ let cut = find_safe_cutoff_point(body, requested);+ if cut != requested {+ tracing::debug!(+ requested,+ cut,+ "[compaction_carry] moved the cut to keep tool calls paired"+ );+ }++ let mut compacted = Vec::with_capacity(lead + 1 + body.len() - cut);+ compacted.extend(history[..lead].iter().cloned());+ compacted.push(self.checkpoint.clone());+ compacted.extend(+ body[..cut]+ .iter()+ .filter(|message| matches!(message, Message::System(_)) && !is_checkpoint(message))+ .cloned(),+ );+ compacted.extend(+ body[cut..]+ .iter()+ .filter(|message| !is_checkpoint(message))+ .cloned(),+ );+ tracing::info!(+ full = history.len(),+ compacted = compacted.len(),+ kept_tail = self.kept_tail,+ "[compaction_carry] persisting the compacted history"+ );+ compacted+ }+}++/// The text of the latest real user message in `history`, skipping+/// compaction checkpoints (which are user-role but not the user's words).+pub(crate) fn last_user_message(history: &[Message]) -> Option<&Message> {+ history+ .iter()+ .rev()+ .find(|message| matches!(message, Message::User(_)) && !is_checkpoint(message))+}++#[cfg(test)]+#[path = "compaction_carry_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/compaction_carry_tests.rs b/crates/openhuman-core/src/agent/tinyagents/compaction_carry_tests.rsnew file mode 100644index 0000000000..c62f0f4e29--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/compaction_carry_tests.rs@@ -0,0 +1,128 @@+use super::*;+use tinyagents_harness::summarization::{checkpoint_message, SummaryPlacement};+use tinyinference_llm::tool::ToolCall;++fn checkpoint(body: &str) -> Message {+ checkpoint_message(SummaryPlacement::User, body)+}++fn call(id: &str) -> Message {+ let mut message = Message::assistant("");+ if let Message::Assistant(assistant) = &mut message {+ assistant+ .tool_calls+ .push(ToolCall::new(id, "read", serde_json::json!({})));+ }+ message+}++#[test]+fn reads_the_checkpoint_and_the_kept_tail() {+ let compacted = vec![+ Message::system("sys"),+ checkpoint("summary"),+ call("c3"),+ Message::tool("c3", "out"),+ Message::assistant("done"),+ ];+ let carry = CompactionCarry::from_compacted_history(&compacted).expect("carry");+ assert_eq!(carry.checkpoint, checkpoint("summary"));+ assert_eq!(carry.kept_tail, 3);+ assert!(CompactionCarry::from_compacted_history(&[Message::user("hi")]).is_none());+}++#[test]+fn folds_everything_before_the_kept_tail() {+ let carry = CompactionCarry {+ checkpoint: checkpoint("summary"),+ kept_tail: 3,+ };+ let history = vec![+ Message::system("sys"),+ Message::user("task"),+ call("c1"),+ Message::tool("c1", "one"),+ call("c2"),+ Message::tool("c2", "two"),+ Message::assistant("done"),+ ];+ let compacted = carry.apply(history);+ assert_eq!(+ compacted,+ vec![+ Message::system("sys"),+ checkpoint("summary"),+ call("c2"),+ Message::tool("c2", "two"),+ Message::assistant("done"),+ ]+ );+}++#[test]+fn never_opens_the_kept_tail_with_an_orphan_tool_result() {+ // Two kept non-system messages would start at c2's result; the cut moves+ // back to include the call.+ let carry = CompactionCarry {+ checkpoint: checkpoint("summary"),+ kept_tail: 2,+ };+ let history = vec![+ Message::user("task"),+ call("c2"),+ Message::tool("c2", "two"),+ Message::assistant("done"),+ ];+ let compacted = carry.apply(history);+ assert_eq!(+ compacted,+ vec![+ checkpoint("summary"),+ call("c2"),+ Message::tool("c2", "two"),+ Message::assistant("done"),+ ]+ );+}++#[test]+fn replaces_an_older_checkpoint_and_keeps_mid_conversation_system_notes() {+ let carry = CompactionCarry {+ checkpoint: checkpoint("new"),+ kept_tail: 1,+ };+ let history = vec![+ Message::system("sys"),+ checkpoint("old"),+ Message::user("task"),+ Message::system("note"),+ Message::assistant("done"),+ ];+ let compacted = carry.apply(history);+ assert_eq!(+ compacted,+ vec![+ Message::system("sys"),+ checkpoint("new"),+ Message::system("note"),+ Message::assistant("done"),+ ]+ );+}++#[test]+fn a_history_shorter_than_the_tail_is_unchanged() {+ let carry = CompactionCarry {+ checkpoint: checkpoint("summary"),+ kept_tail: 5,+ };+ let history = vec![Message::system("sys"), Message::user("hi")];+ assert_eq!(carry.apply(history.clone()), history);+}++#[test]+fn the_last_user_message_skips_checkpoints() {+ let history = vec![Message::user("real"), checkpoint("summary"), call("c1")];+ assert_eq!(last_user_message(&history), Some(&Message::user("real")));+ assert_eq!(last_user_message(&[checkpoint("only")]), None);+}diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rsindex 63edf3d7f5..4ba9a69379 100644--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs@@ -21,6 +21,7 @@pub mod config;pub mod discovery;+mod compaction_carry;mod embeddings;mod harness_assembly;mod harness_context_ladder;@@ -77,6 +78,7 @@ pub(crate) use reasoning::{apply_requested_effort, parse_reasoning_effort};pub(crate) use topology::all_graph_topologies;pub use turn_models::TurnModelSource;pub(crate) use turn_models::TurnModels;+pub(crate) use compaction_carry::{last_user_message, CompactionCarry};pub(crate) use turn_outcome::{HaltSummarySlot, TinyagentsTurnOutcome, ToolCallOutcome, ToolOutcomeSink,};diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rsindex e1429f94c3..a80e41b64d 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs@@ -71,6 +71,10 @@ pub(crate) struct TinyagentsTurnOutcome {/// only place the caller can recover whether each call actually failed — used/// to build honest `ToolCallRecord`s for post-turn hooks + the cap checkpoint.pub tool_outcomes: Vec<ToolCallOutcome>,+ /// The run's context compaction, when it compacted: re-applied by the+ /// session driver to the history it persists, so the next turn starts+ /// from the checkpoint. `None` when the run did not compact.+ pub compaction: Option<super::CompactionCarry>,}/// One tool call's execution outcome, captured at the tool boundary before thediff --git a/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs b/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rsindex b042969e2b..32cbbf0239 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs@@ -271,6 +271,21 @@ pub(super) async fn finalize_turn_outcome("[tinyagents] turn prompt summary");+ // The run's compaction (`AgentRun::compacted_history`), carried to the+ // session driver so the persisted history starts from the checkpoint.+ let compaction = run+ .compacted_history+ .as_deref()+ .and_then(crate::agent::tinyagents::CompactionCarry::from_compacted_history);+ if let Some(carry) = &compaction {+ tracing::info!(+ model,+ kept_tail = carry.kept_tail,+ transcript_len = run.messages.len(),+ "[tinyagents] turn compacted; the persisted history will start from the checkpoint"+ );+ }+TinyagentsTurnOutcome {text,resolved_route,@@ -287,5 +302,6 @@ pub(super) async fn finalize_turn_outcome(wrap_up_injected,breaker_halt,tool_outcomes,+ compaction,}}