Skip to content

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

feat(memory): refresh memory block on prompt refresh

Steven Enamakel80f0c781e641
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
index 1c69ba0107..9460e189b7 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -4,9 +4,9 @@
//! transcripts, prefixes, snapshots, resume, and persistence.
mod bound_history;
-pub(super) mod memory_block;
#[path = "runtime_session_enrichment.rs"]
mod enrichment;
+pub(super) mod memory_block;
mod permanent;
mod post_commit;
#[path = "runtime_session/prelude.rs"]
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block.rs
index b161a02154..d3bd91f908 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block.rs
@@ -55,7 +55,10 @@ pub(super) fn is_memory_block(message: &Message) -> bool {
/// The memory block `prefix` carries, if any.
pub(super) fn recorded_block(prefix: &PrefixSnapshot) -> Option<&Message> {
- prefix.messages().iter().find(|message| is_memory_block(message))
+ prefix
+ .messages()
+ .iter()
+ .find(|message| is_memory_block(message))
}
/// `prefix` with `block` as its last message, in place of any block it
@@ -120,7 +123,13 @@ impl OpenHumanTurnPrelude {
RenderedBlock::Block(Message::system(text))
}
Ok(None) => {
- tracing::info!(thread_id, agent_id, reason, tokens = 0, "[memory_block] empty");
+ tracing::info!(
+ thread_id,
+ agent_id,
+ reason,
+ tokens = 0,
+ "[memory_block] empty"
+ );
RenderedBlock::Empty
}
Err(error) => {
@@ -183,9 +192,9 @@ impl OpenHumanTurnPrelude {
tracing::debug!(
thread_id = self.thread_id.as_deref().unwrap_or(""),
agent_id = self.agent_definition_id.as_str(),
- tokens = recorded
- .as_ref()
- .map_or(0, |block| tinymemory_tools::recall::estimate_tokens(&block.text())),
+ tokens = recorded.as_ref().map_or(0, |block| {
+ tinymemory_tools::recall::estimate_tokens(&block.text())
+ }),
"[memory_block] kept"
);
recorded.clone()
@@ -201,7 +210,11 @@ impl OpenHumanTurnPrelude {
/// from the generation it succeeded, and has not yet committed a turn of
/// its own past the one that opened it. Any read failure answers `false`:
/// the recorded block is kept.
- pub(super) fn memory_block_inherited(&self, view: &SessionStateView<'_>, block: &Message) -> bool {
+ pub(super) fn memory_block_inherited(
+ &self,
+ view: &SessionStateView<'_>,
+ block: &Message,
+ ) -> bool {
let Some(target) = view.transcript_target else {
return false;
};
@@ -219,7 +232,8 @@ impl OpenHumanTurnPrelude {
let Ok(Some(transcript)) = read.read_session() else {
return false;
};
- let Ok(messages) = super::super::OpenHumanTranscriptCodec.decode_history(&transcript) else {
+ let Ok(messages) = super::super::OpenHumanTranscriptCodec.decode_history(&transcript)
+ else {
return false;
};
let prefix_len = transcript.meta.prefix_message_count.unwrap_or_else(|| {
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_tests.rs
index e98bb81999..7ae2f709d8 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_tests.rs
@@ -24,9 +24,9 @@ fn host(config: &Config, prompt: &str, refresh: bool) -> OpenHumanSessionHost {
let mut host = crate::agent::SessionHostBuilder::new()
.with_session_history_locator(memory_locator())
.model_name("test/session-fixture".to_string())
- .chat_model(Arc::new(tinyagents_harness::testkit::ScriptedModel::replies(
- Vec::<&str>::new(),
- )))
+ .chat_model(Arc::new(
+ tinyagents_harness::testkit::ScriptedModel::replies(Vec::<&str>::new()),
+ ))
.tools(Vec::new())
.prompt_builder(SystemPromptBuilder::verbatim(prompt.to_string()))
.workspace_dir(config.workspace_dir.clone())
@@ -125,7 +125,12 @@ fn sent(prepared: &TurnPreparation, recorded: &PrefixSnapshot) -> Vec<Message> {
async fn a_new_thread_ends_its_prompt_with_the_memory_block() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
- learn(&bind_reference(&config), &config, "The user's favourite colour is teal").await;
+ learn(
+ &bind_reference(&config),
+ &config,
+ "The user's favourite colour is teal",
+ )
+ .await;
let prelude = prelude(&config, PROMPT, false);
let empty = PrefixSnapshot::default();
@@ -170,7 +175,12 @@ async fn a_memory_read_error_leaves_a_new_thread_without_a_block() {
async fn a_resumed_thread_keeps_its_recorded_block_when_memory_changes() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
- learn(&bind_reference(&config), &config, "The user lives in Lisbon").await;
+ learn(
+ &bind_reference(&config),
+ &config,
+ "The user lives in Lisbon",
+ )
+ .await;
// Refreshing the prompt renders it again on every turn: the block must
// still be the recorded one, and the unchanged prompt adds no note.
let prelude = prelude(&config, PROMPT, true);
@@ -191,7 +201,12 @@ async fn a_resumed_thread_keeps_its_recorded_block_when_memory_changes() {
async fn a_resumed_thread_recorded_without_a_block_takes_one_up() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
- learn(&bind_reference(&config), &config, "The user lives in Lisbon").await;
+ learn(
+ &bind_reference(&config),
+ &config,
+ "The user lives in Lisbon",
+ )
+ .await;
let prelude = prelude(&config, PROMPT, false);
let recorded = PrefixSnapshot::new(vec![Message::system(PROMPT)]);
let history = [Message::system(PROMPT), Message::user("hello")];
@@ -208,16 +223,28 @@ async fn a_resumed_thread_recorded_without_a_block_takes_one_up() {
async fn a_replaced_prompt_takes_a_fresh_block_and_still_carries_its_note() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
- learn(&bind_reference(&config), &config, "The user lives in Lisbon").await;
+ learn(
+ &bind_reference(&config),
+ &config,
+ "The user lives in Lisbon",
+ )
+ .await;
let prelude = prelude(&config, "You are blocky, v2.", true);
let recorded = PrefixSnapshot::new(vec![Message::system(PROMPT), block("- teal")]);
- let history = [Message::system(PROMPT), block("- teal"), Message::user("hello")];
+ let history = [
+ Message::system(PROMPT),
+ block("- teal"),
+ Message::user("hello"),
+ ];
let (prepared, request) = prepare(&prelude, false, &view(&recorded, &history, None)).await;
let offered = prepared.prefix.expect("a refreshed prefix");
assert_eq!(offered.messages()[0].text(), "You are blocky, v2.");
let last = offered.messages().last().expect("a block");
- assert!(is_memory_block(last) && last.text().contains("Lisbon"), "{offered:?}");
+ assert!(
+ is_memory_block(last) && last.text().contains("Lisbon"),
+ "{offered:?}"
+ );
assert!(request.input.text().starts_with(PROMPT_UPDATE_NOTE));
}
@@ -292,7 +319,12 @@ fn generations(
async fn a_generation_that_inherited_its_block_renders_a_fresh_one() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
- learn(&bind_reference(&config), &config, "The user lives in Lisbon").await;
+ learn(
+ &bind_reference(&config),
+ &config,
+ "The user lives in Lisbon",
+ )
+ .await;
let prelude = prelude(&config, PROMPT, false);
let locator = memory_locator();
let old = block("- teal");
@@ -312,7 +344,12 @@ async fn a_generation_that_inherited_its_block_renders_a_fresh_one() {
async fn a_generation_opened_by_a_block_refresh_keeps_its_block() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
- learn(&bind_reference(&config), &config, "The user lives in Lisbon").await;
+ learn(
+ &bind_reference(&config),
+ &config,
+ "The user lives in Lisbon",
+ )
+ .await;
let prelude = prelude(&config, PROMPT, false);
let locator = memory_locator();
let fresh = block("- teal");
@@ -328,7 +365,12 @@ async fn a_generation_opened_by_a_block_refresh_keeps_its_block() {
async fn an_inherited_block_is_kept_once_the_generation_has_moved_on() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
- learn(&bind_reference(&config), &config, "The user lives in Lisbon").await;
+ learn(
+ &bind_reference(&config),
+ &config,
+ "The user lives in Lisbon",
+ )
+ .await;
let prelude = prelude(&config, PROMPT, false);
let locator = memory_locator();
let old = block("- teal");
@@ -364,7 +406,12 @@ fn the_block_goes_after_every_other_prefix_message() {
async fn a_generation_opened_outside_a_turn_can_take_a_fresh_block() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
- learn(&bind_reference(&config), &config, "The user lives in Lisbon").await;
+ learn(
+ &bind_reference(&config),
+ &config,
+ "The user lives in Lisbon",
+ )
+ .await;
let block = host(&config, PROMPT, false)
.memory_block_for_new_generation()
.await
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_refresh.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_refresh.rs
index 6a0655ac9e..48d17e12fd 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_refresh.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_refresh.rs
@@ -100,7 +100,8 @@ impl OpenHumanTurnPrelude {
.is_some_and(|prefix| !prompt_messages(prefix).eq(prompt_messages(view.prefix)));
self.refresh_permanent_prefix(&mut preparation, view.prefix);
// Last, so the block follows everything else the prefix carries.
- self.refresh_memory_block(&mut preparation, view, cold).await;
+ self.refresh_memory_block(&mut preparation, view, cold)
+ .await;
if let Some(prefix) = preparation.prefix.as_ref() {
// The runtime sends `prefix` in place of the recorded one, so the
// rounds this run produces start that much further on (or back).
diff --git a/crates/openhuman-core/src/agent/tinyagents/context_wiring_tests.rs b/crates/openhuman-core/src/agent/tinyagents/context_wiring_tests.rs
index da852bd186..569e362f15 100644
--- a/crates/openhuman-core/src/agent/tinyagents/context_wiring_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/context_wiring_tests.rs
@@ -178,7 +178,10 @@ async fn a_markers_compaction_sends_no_tool_output_and_caps_the_summary() {
let mut history = vec![Message::system("system")];
for round in 0..12 {
- history.push(Message::user(format!("ask {round}: {}", "detail ".repeat(40))));
+ history.push(Message::user(format!(
+ "ask {round}: {}",
+ "detail ".repeat(40)
+ )));
history.push(Message::Assistant(AssistantMessage {
id: None,
content: Vec::new(),
@@ -215,3 +218,74 @@ async fn a_markers_compaction_sends_no_tool_output_and_caps_the_summary() {
assert_eq!(request.max_tokens, Some(4_000));
}
}
+
+fn idle_history() -> Vec<Message> {
+ let mut history = vec![Message::system("system prompt")];
+ for round in 0..8 {
+ history.push(Message::user(format!("ask {round}: {}", "detail ".repeat(60))));
+ history.push(Message::assistant(format!("answer {round}: {}", "result ".repeat(60))));
+ }
+ history
+}
+
+/// Outside a turn, the compression middleware folds the head into one
+/// user-role summary right after the system prompt and keeps the tail.
+#[tokio::test]
+async fn an_idle_fold_puts_the_summary_after_the_system_prompt() {
+ use tinyagents_harness::testkit::ScriptedModel;
+
+ let summarizer_model = Arc::new(ScriptedModel::replies(vec!["## Goal\nIDLE-SUMMARY"; 4]));
+ let history = idle_history();
+ let compacted = compact_history(
+ &history,
+ IdleFold {
+ min_tokens: 100,
+ keep_recent_tokens: Some(150),
+ strategy: crate::config::CompactionStrategy::Summary,
+ context_window: None,
+ model: "turn-model",
+ },
+ CompactionSummarizer {
+ model: summarizer_model.clone(),
+ model_id: "scaledown/summarize".into(),
+ settings: Default::default(),
+ },
+ )
+ .await
+ .expect("the fold runs")
+ .expect("the history is folded");
+
+ assert_eq!(compacted[0], history[0], "the system prompt is kept as is");
+ assert!(matches!(compacted[1], Message::User(_)));
+ assert!(compacted[1].text().contains("IDLE-SUMMARY"));
+ assert_eq!(compacted.last(), history.last(), "the tail is kept verbatim");
+ assert!(compacted.len() < history.len());
+ assert_eq!(summarizer_model.requests().len(), 1);
+}
+
+/// A tail that covers the whole conversation leaves nothing to fold.
+#[tokio::test]
+async fn an_idle_fold_with_nothing_old_enough_returns_none() {
+ use tinyagents_harness::testkit::ScriptedModel;
+
+ let summarizer_model = Arc::new(ScriptedModel::replies(vec!["unused"]));
+ let folded = compact_history(
+ &idle_history(),
+ IdleFold {
+ min_tokens: 100,
+ keep_recent_tokens: Some(1_000_000),
+ strategy: crate::config::CompactionStrategy::Summary,
+ context_window: None,
+ model: "turn-model",
+ },
+ CompactionSummarizer {
+ model: summarizer_model.clone(),
+ model_id: "m".into(),
+ settings: Default::default(),
+ },
+ )
+ .await
+ .expect("the fold runs");
+ assert!(folded.is_none());
+ assert!(summarizer_model.requests().is_empty());
+}
diff --git a/crates/openhuman-core/src/config/mod.rs b/crates/openhuman-core/src/config/mod.rs
index 659513f839..891a28cfd7 100644
--- a/crates/openhuman-core/src/config/mod.rs
+++ b/crates/openhuman-core/src/config/mod.rs
@@ -48,8 +48,8 @@ pub use schema::{
BudgetPeriod, BudgetPolicy, BudgetScope, CapabilityProviderConfig,
CapabilityProviderTrustState, ChannelVoiceConfig, ChannelVoiceOverride, ChannelsConfig,
CompactionSettings, CompactionStrategy, ComposioConfig, ComposioDirectBaseUrls,
- ComposioHostCredential, ComputerConfig, Config, ContextConfig, ContextSettings, CostConfig, CronConfig,
- CurlConfig, DashboardConfig, DecisionModel, DiagramViewerConfig, DiscordConfig,
+ ComposioHostCredential, ComputerConfig, Config, ContextConfig, ContextSettings, CostConfig,
+ CronConfig, CurlConfig, DashboardConfig, DecisionModel, DiagramViewerConfig, DiscordConfig,
DockerRuntimeConfig, EmailConfig, EmbeddingRouteConfig, GitbooksConfig, HttpHeader,
HttpRequestConfig, IMessageConfig, IntegrationToggle, IntegrationsConfig, LarkConfig,
LegacySearchInputs, LinqConfig, LocalAiConfig, LocalJailConfig, McpAuthConfig, McpClientConfig,
diff --git a/crates/openhuman-core/src/config/schema/load_env_overlay_context_tests.rs b/crates/openhuman-core/src/config/schema/load_env_overlay_context_tests.rs
index 2ed4215539..f7aaa17bc9 100644
--- a/crates/openhuman-core/src/config/schema/load_env_overlay_context_tests.rs
+++ b/crates/openhuman-core/src/config/schema/load_env_overlay_context_tests.rs
@@ -214,7 +214,10 @@ fn summarizer_tool_rendering_defaults_to_full_and_env_selects_markers() {
cfg.apply_env_overlay_with(
&HashMapEnv::new().with("OPENHUMAN_CONTEXT_SUMMARIZER_TOOL_RENDERING", " Markers "),
);
- assert_eq!(cfg.context.summarizer_tool_rendering, ToolRendering::Markers);
+ assert_eq!(
+ cfg.context.summarizer_tool_rendering,
+ ToolRendering::Markers
+ );
// Unknown and empty values leave the current rendering alone.
cfg.apply_env_overlay_with(
@@ -223,7 +226,10 @@ fn summarizer_tool_rendering_defaults_to_full_and_env_selects_markers() {
cfg.apply_env_overlay_with(
&HashMapEnv::new().with("OPENHUMAN_CONTEXT_SUMMARIZER_TOOL_RENDERING", ""),
);
- assert_eq!(cfg.context.summarizer_tool_rendering, ToolRendering::Markers);
+ assert_eq!(
+ cfg.context.summarizer_tool_rendering,
+ ToolRendering::Markers
+ );
cfg.apply_env_overlay_with(
&HashMapEnv::new().with("OPENHUMAN_CONTEXT_SUMMARIZER_TOOL_RENDERING", "full"),
@@ -278,6 +284,12 @@ fn summarizer_settings_read_from_the_context_table_beside_the_harness_settings()
// The written form keeps every key in the one `[context]` table.
let written = toml::to_string(&cfg.context).unwrap();
- assert!(written.contains("summarizer_tool_rendering = \"markers\""), "{written}");
- assert!(written.contains("compaction_strategy = \"summary\""), "{written}");
+ assert!(
+ written.contains("summarizer_tool_rendering = \"markers\""),
+ "{written}"
+ );
+ assert!(
+ written.contains("compaction_strategy = \"summary\""),
+ "{written}"
+ );
}
diff --git a/crates/openhuman-core/src/memory/lifecycle/memory_block.rs b/crates/openhuman-core/src/memory/lifecycle/memory_block.rs
index be7c56f688..35615010c1 100644
--- a/crates/openhuman-core/src/memory/lifecycle/memory_block.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/memory_block.rs
@@ -14,7 +14,7 @@
//! known renders no block at all, and memory switched off reads as nothing
//! known; an engine failure is an error the caller logs and survives.
-use tinymemory_api::{BELIEF_TAG, BeliefsRequest, Error, Hit, ListRequest, Reach, Result};
+use tinymemory_api::{BeliefsRequest, Error, Hit, ListRequest, Reach, Result, BELIEF_TAG};
use tinymemory_tools::layout::identity::ResolvedIdentity;
use tinymemory_tools::recall::estimate_tokens;
diff --git a/crates/openhuman-core/src/memory/lifecycle/memory_block_tests.rs b/crates/openhuman-core/src/memory/lifecycle/memory_block_tests.rs
index f9e020b9d8..f207fe54ea 100644
--- a/crates/openhuman-core/src/memory/lifecycle/memory_block_tests.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/memory_block_tests.rs
@@ -61,7 +61,12 @@ fn a_fact_that_repeats_a_belief_or_is_one_is_listed_once() {
#[test]
fn the_block_stays_within_its_token_budget() {
let facts: Vec<Hit> = (0..200)
- .map(|n| hit(&format!("Fact number {n} about the user's long history"), &[]))
+ .map(|n| {
+ hit(
+ &format!("Fact number {n} about the user's long history"),
+ &[],
+ )
+ })
.collect();
let block = render(&[], &facts, 120).expect("a block");
assert!(
diff --git a/crates/openhuman-embed/src/agent/definition.rs b/crates/openhuman-embed/src/agent/definition.rs
index c011dacb62..86456a735e 100644
--- a/crates/openhuman-embed/src/agent/definition.rs
+++ b/crates/openhuman-embed/src/agent/definition.rs
@@ -351,6 +351,13 @@ impl AgentDefinitionSpec {
if let Some(refresh) = self.refresh_prompt_on_resume {
def.extensions.refresh_prompt_on_resume = refresh;
}
+ if let Some(block) = self.memory_block {
+ def.extensions.memory_block = Some(
+ openhuman_core::agent_registry::host_definition::MemoryBlock {
+ max_tokens: block.max_tokens,
+ },
+ );
+ }
if custom_base {
if let Some(requested) = &self.tools {
let narrows = match (requested, &def.tools) {
@@ -414,7 +421,7 @@ impl AgentDefinitionSpec {
def.temperature = t;
}
log::debug!(
- "[embed][agent] definition id={id} prompt={} refresh_prompt_on_resume={} tools={:?} sandbox={:?} max_iterations={}",
+ "[embed][agent] definition id={id} prompt={} refresh_prompt_on_resume={} memory_block={:?} tools={:?} sandbox={:?} max_iterations={}",
match &def.system_prompt {
PromptSource::Inline(_) => "inline",
PromptSource::File { .. } => "file",
@@ -422,6 +429,7 @@ impl AgentDefinitionSpec {
PromptSource::Verbatim(_) => "verbatim",
},
def.extensions.refresh_prompt_on_resume,
+ def.extensions.memory_block.map(|block| block.max_tokens),
def.tools,
def.sandbox_mode,
def.max_iterations
diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs
index 7593724858..71fb751dcc 100644
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@ -176,7 +176,8 @@ pub use openhuman_core::voice::VOICE_COMPILED_IN;
pub use agent::ToolAttachmentError;
pub use agent::{
Agent, AgentDefinitionSpec, AgentError, AgentLayout, AgentSpec, ApprovalDecision, Approvals,
- ApprovalsError, DefinitionBase, MemoryBinding, MemoryBlockSpec, PendingApproval, SandboxModeSpec, ToolScopeSpec,
+ ApprovalsError, DefinitionBase, MemoryBinding, MemoryBlockSpec, PendingApproval,
+ SandboxModeSpec, ToolScopeSpec,
};
pub use auth::{Auth, AuthState, Session};
#[cfg(feature = "channels")]
diff --git a/crates/openhuman-embed/tests/compact_thread.rs b/crates/openhuman-embed/tests/compact_thread.rs
index 6a758cab36..0ac117039c 100644
--- a/crates/openhuman-embed/tests/compact_thread.rs
+++ b/crates/openhuman-embed/tests/compact_thread.rs
@@ -20,6 +20,7 @@ use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use common::{chat_completion, offline_config, runtime, stub_backend};
+use openhuman_embed::SessionStoreProvider as _;
use openhuman_embed::{
Access, AgentSpec, CompactOptions, CompactOutcome, Provider, Runtime, Workspace,
};
@@ -90,7 +91,10 @@ impl Respond for ScriptedProvider {
/// The messages a request sent.
fn messages(seen: &Seen) -> Vec<serde_json::Value> {
- seen.body["messages"].as_array().cloned().unwrap_or_default()
+ seen.body["messages"]
+ .as_array()
+ .cloned()
+ .unwrap_or_default()
}
/// The text of a request message, whether a string or content parts.
@@ -116,7 +120,8 @@ fn compact_thread_seals_the_head_and_the_next_turn_resends_the_summary() {
.await;
let store = Arc::new(InMemorySessionStores::new());
let mut config = offline_config();
- config.context.compaction_strategy = openhuman_core::config::CompactionStrategy::Summary;
+ config.context.compaction_strategy =
+ openhuman_core::config::CompactionStrategy::Summary;
config.context.summarizer_model = Some(SUMMARIZER_MODEL.into());
let runtime = Runtime::builder()
.config(config)
@@ -139,7 +144,10 @@ fn compact_thread_seals_the_head_and_the_next_turn_resends_the_summary() {
// ── a long conversation on one thread ─────────────────────────
let first = agent
- .turn(format!("we are planning a trip to Goa. {}", "detail ".repeat(300)))
+ .turn(format!(
+ "we are planning a trip to Goa. {}",
+ "detail ".repeat(300)
+ ))
.send()
.await
.expect("first turn");
@@ -216,7 +224,9 @@ fn compact_thread_seals_the_head_and_the_next_turn_resends_the_summary() {
.await;
let turn = agent.turn("so, what was the plan?").session(&thread).send();
let (outcome, reply) = tokio::join!(compacting, turn);
- let outcome = outcome.expect("the task ran").expect("the compaction succeeds");
+ let outcome = outcome
+ .expect("the task ran")
+ .expect("the compaction succeeds");
reply.expect("the racing turn");
let CompactOutcome::Compacted {
tokens_before,
@@ -225,14 +235,21 @@ fn compact_thread_seals_the_head_and_the_next_turn_resends_the_summary() {
else {
panic!("expected Compacted, got {outcome:?}");
};
- assert!(tokens_after < tokens_before, "{tokens_after} < {tokens_before}");
+ assert!(
+ tokens_after < tokens_before,
+ "{tokens_after} < {tokens_before}"
+ );
// The summary request went to the summarizer model alone.
assert_eq!(provider.summaries().len(), 1);
// The turn waited for the compaction: its request came after the
// summary was answered, and it resent the summary.
- let after = provider.turns().last().cloned().expect("the racing turn's request");
+ let after = provider
+ .turns()
+ .last()
+ .cloned()
+ .expect("the racing turn's request");
assert!(
after.at >= summary_asked + SLOW_SUMMARY,
"the turn ran after the compaction released the session"
@@ -249,7 +266,10 @@ fn compact_thread_seals_the_head_and_the_next_turn_resends_the_summary() {
before.body.get("tools"),
"the tool declarations are byte-identical"
);
- assert_eq!(after_messages[1]["role"], "user", "the summary is user-role");
+ assert_eq!(
+ after_messages[1]["role"], "user",
+ "the summary is user-role"
+ );
assert!(text(&after_messages[1]).contains("SUMMARY-MARKER"));
assert!(
after.body.to_string().len() < before.body.to_string().len(),
@@ -263,12 +283,13 @@ fn compact_thread_seals_the_head_and_the_next_turn_resends_the_summary() {
// ── the sealed generation is still readable ───────────────────
let chain = transcripts.session_chain(&session);
assert_eq!(chain.len(), 2, "the head was sealed and the next opened");
- assert_eq!(head_text(&chain[0]), original, "the sealed one is untouched");
+ assert_eq!(
+ head_text(&chain[0]),
+ original,
+ "the sealed one is untouched"
+ );
- runtime
- .remove_agent("asha")
- .await
- .expect("asha is removed");
+ runtime.remove_agent("asha").await.expect("asha is removed");
drop(agent);
drop(runtime);
})