From a7e7487978387a46343b94831402447785f21813 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sat, 7 Nov 2026 21:37:31 +0300 Subject: [PATCH 01/24] feat(memory): take the memory block render off the turn's critical path Read beliefs and learnings concurrently, log elapsed_ms for each render, bound a generation start's wait with [memory] memory_block_deadline_ms (deferred renders land in a process-wide store taken by the next generation start), and add OpenHumanSessionHost::prewarm_memory_block and embed Agent::prewarm_memory_block plus MemoryBinding::memory_block_deadline. Co-authored-by: Medulla --- crates/openhuman-core/src/agent/mod.rs | 4 +- .../src/agent/session_host/mod.rs | 2 +- .../src/agent/session_host/runtime_session.rs | 2 + .../runtime_session/memory_block.rs | 84 ++++++- .../runtime_session/memory_block_ready.rs | 234 ++++++++++++++++++ .../memory_block_ready_tests.rs | 85 +++++++ .../runtime_session/memory_block_tests.rs | 213 +++++++++++++++- .../src/agent_runs/agent_chat/compact.rs | 30 ++- .../src/agent_runs/agent_chat/mod.rs | 2 +- .../src/config/schema/memory.rs | 10 + .../src/config/schema/memory_tests.rs | 16 ++ crates/openhuman-core/src/memory/README.md | 8 + .../src/memory/lifecycle/memory_block.rs | 44 +++- .../memory/lifecycle/memory_block_tests.rs | 21 +- .../src/memory/lifecycle/session_hooks.rs | 17 ++ .../src/memory/test_fixtures.rs | 103 ++++++++ crates/openhuman-embed/src/agent/README.md | 2 +- crates/openhuman-embed/src/agent/build.rs | 3 + crates/openhuman-embed/src/agent/compact.rs | 75 +++++- crates/openhuman-embed/src/agent/mod.rs | 2 +- crates/openhuman-embed/src/agent/spec.rs | 23 ++ .../openhuman-embed/src/agent/spec_tests.rs | 11 + crates/openhuman-embed/src/lib.rs | 4 +- .../openhuman-embed/tests/runtime_agents.rs | 8 +- 24 files changed, 966 insertions(+), 37 deletions(-) create mode 100644 crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready.rs create mode 100644 crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready_tests.rs diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rs index d3f1fde2efa..564c0ca15de 100644 --- a/crates/openhuman-core/src/agent/mod.rs +++ b/crates/openhuman-core/src/agent/mod.rs @@ -75,6 +75,6 @@ pub(crate) mod turn_policy; pub(crate) mod turn_progress; #[allow(unused_imports)] pub use session_host::{ - CompactOptions, CompactOutcome, HostTools, HostTurnTools, OpenHumanSessionHost, - SessionHostBuilder, TurnContext, TurnOverrides, + CompactOptions, CompactOutcome, HostTools, HostTurnTools, MemoryBlockPrewarm, + OpenHumanSessionHost, SessionHostBuilder, TurnContext, TurnOverrides, }; diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rs index 41861b6dd2e..e3bb84f29ae 100644 --- a/crates/openhuman-core/src/agent/session_host/mod.rs +++ b/crates/openhuman-core/src/agent/session_host/mod.rs @@ -55,7 +55,7 @@ pub(crate) mod test_support; pub use codec::OpenHumanTranscriptCodec; pub type OpenHumanSessionHooks = tinyagents_runtime::FnSessionHooks; -pub use runtime_session::{CompactOptions, CompactOutcome}; +pub use runtime_session::{CompactOptions, CompactOutcome, MemoryBlockPrewarm}; pub use types::{OpenHumanSessionHost, SessionHostBuilder, TurnOverrides}; // Re-export the duplicate-tool-spec guard for sibling harness modules 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 33888059da0..0e9269b742b 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs @@ -9,6 +9,8 @@ pub use compact::{CompactOptions, CompactOutcome}; #[path = "runtime_session_enrichment.rs"] mod enrichment; pub(super) mod memory_block; +mod memory_block_ready; +pub use memory_block_ready::MemoryBlockPrewarm; 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 a47daf2056c..182eb597870 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 @@ -37,11 +37,25 @@ //! [`with_memory_block`]. Doing nothing is also correct: the next turn finds //! the inherited block and renders a fresh one. //! -//! Logs: `[memory_block] rendered|kept|empty|error` with the thread and agent -//! ids and the block's token count; never its content. +//! **Off the critical path.** With `[memory] memory_block_deadline_ms` a +//! generation start waits that long for its render: when the deadline lapses +//! the turn keeps the recorded block (a cold thread sends none), logs +//! `[memory_block] deferred`, and the render finishes in the background into +//! `memory_block_ready.rs`, where the next generation start takes it. A host +//! can fill the same store ahead of a turn with +//! [`OpenHumanSessionHost::prewarm_memory_block`]. +//! +//! Logs: `[memory_block] rendered|ready|kept|empty|deferred|error` with the +//! thread and agent ids, the block's token count and, for a render, its +//! `elapsed_ms` (the per-step breakdown is `[memory_block] read` at debug); +//! never its content. + +use std::sync::Arc; +use std::time::Instant; use tinyagents_runtime::{PrefixSnapshot, SessionStateView, TranscriptCodec, TurnPreparation}; use tinyinference_llm::message::Message; +use tinymemory_tools::layout::identity::ResolvedIdentity; use super::super::types::OpenHumanSessionHost; use super::OpenHumanTurnPrelude; @@ -82,6 +96,20 @@ pub(super) enum RenderedBlock { Empty, /// The read failed. Failed, + /// The deadline lapsed before the render finished (see + /// `memory_block_ready.rs`): the render goes on in the background. + Deferred, + /// A block rendered ahead of this generation start; `None` when that + /// render found nothing known. + Ready(Option), +} + +/// What a read of memory is made as: the session's config and acting +/// identity. +#[derive(Clone)] +pub(super) struct MemoryScope { + pub(super) config: Arc, + pub(super) identity: ResolvedIdentity, } impl OpenHumanTurnPrelude { @@ -93,31 +121,55 @@ impl OpenHumanTurnPrelude { .map(|block| block.max_tokens) } - /// Reads memory as this session's identity and renders the block. - pub(super) async fn render_memory_block(&self, max_tokens: u32, reason: &str) -> RenderedBlock { - let thread_id = self.thread_id.as_deref().unwrap_or(""); - let agent_id = self.agent_definition_id.as_str(); + /// The config and identity this session reads memory as; `None` when it + /// cannot read memory at all. + pub(super) async fn memory_scope(&self, reason: &str) -> Option { let config = match self.memory_config().await { Some(config) if self.memory_readable() => config, _ => { tracing::debug!( - thread_id, - agent_id, + thread_id = self.thread_id.as_deref().unwrap_or(""), + agent_id = self.agent_definition_id.as_str(), reason, tokens = 0, "[memory_block] empty: memory unavailable to this session" ); - return RenderedBlock::Empty; + return None; } }; let identity = self.memory_identity(&config); - match render::read(&config, &identity, max_tokens).await { + Some(MemoryScope { config, identity }) + } + + /// Reads memory as this session's identity and renders the block. + pub(super) async fn render_memory_block(&self, max_tokens: u32, reason: &str) -> RenderedBlock { + match self.memory_scope(reason).await { + Some(scope) => self.render_in(&scope, max_tokens, reason).await, + None => RenderedBlock::Empty, + } + } + + /// Reads memory within `scope` and renders the block, logging how long it + /// took. + pub(super) async fn render_in( + &self, + scope: &MemoryScope, + max_tokens: u32, + reason: &str, + ) -> RenderedBlock { + let thread_id = self.thread_id.as_deref().unwrap_or(""); + let agent_id = self.agent_definition_id.as_str(); + let started = Instant::now(); + let read = render::read(&scope.config, &scope.identity, max_tokens).await; + let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + match read { Ok(Some(text)) => { tracing::info!( thread_id, agent_id, reason, tokens = tinymemory_tools::recall::estimate_tokens(&text), + elapsed_ms, "[memory_block] rendered" ); RenderedBlock::Block(Message::system(text)) @@ -128,6 +180,7 @@ impl OpenHumanTurnPrelude { agent_id, reason, tokens = 0, + elapsed_ms, "[memory_block] empty" ); RenderedBlock::Empty @@ -138,6 +191,7 @@ impl OpenHumanTurnPrelude { agent_id, reason, %error, + elapsed_ms, "[memory_block] error: keeping the recorded block" ); RenderedBlock::Failed @@ -183,10 +237,11 @@ impl OpenHumanTurnPrelude { None }; let block = match reason { - Some(reason) => match self.render_memory_block(max_tokens, reason).await { + Some(reason) => match self.block_for_generation(max_tokens, reason).await { RenderedBlock::Block(block) => Some(block), + RenderedBlock::Ready(block) => block, RenderedBlock::Empty => None, - RenderedBlock::Failed => recorded.clone(), + RenderedBlock::Failed | RenderedBlock::Deferred => recorded.clone(), }, None => { tracing::debug!( @@ -262,7 +317,10 @@ impl OpenHumanSessionHost { .await { RenderedBlock::Block(block) => Some(block), - RenderedBlock::Empty | RenderedBlock::Failed => None, + RenderedBlock::Empty + | RenderedBlock::Failed + | RenderedBlock::Deferred + | RenderedBlock::Ready(_) => None, } } } diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready.rs new file mode 100644 index 00000000000..f25ef78db2b --- /dev/null +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready.rs @@ -0,0 +1,234 @@ +//! Memory blocks rendered ahead of the generation that uses them. +//! +//! A render that finished away from a turn's critical path waits here until +//! the next transcript generation starts: one the deadline lapsed on (see +//! `memory_block.rs`) or one a host asked for ahead of its turn +//! ([`OpenHumanSessionHost::prewarm_memory_block`]). Sessions are built per +//! turn, so the store is process-wide, keyed by what the block was read for: +//! workspace, memory identity and token budget. +//! +//! A block is taken at most once, and only by a generation start, so a +//! generation in flight keeps the prefix it was sent. One older than +//! [`READY_MAX_AGE`] is dropped as stale, and the store holds at most +//! [`READY_CAPACITY`] blocks, the oldest making room. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use tinymemory_tools::layout::identity::ResolvedIdentity; + +use tinyinference_llm::message::Message; + +use super::super::types::OpenHumanSessionHost; +use super::memory_block::{MemoryScope, RenderedBlock}; +use super::OpenHumanTurnPrelude; + +/// What [`OpenHumanSessionHost::prewarm_memory_block`] did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MemoryBlockPrewarm { + /// A block was rendered and is waiting for the next generation start. + Ready, + /// A fresh block was already waiting; nothing was read. + AlreadyReady, + /// The agent has no memory block, or memory is not readable by this + /// session. + Unavailable, + /// The read failed; nothing is waiting. + Failed, +} + +impl OpenHumanSessionHost { + /// Renders the memory block ahead of a turn, for the next generation + /// start of this session's memory identity to take instead of reading + /// memory on the turn's own path. A host calls it when a message arrives + /// and the turn is still some way off. Nothing is read when a fresh block + /// already waits. + pub async fn prewarm_memory_block(&self) -> MemoryBlockPrewarm { + let prelude = self.create_turn_prelude(false); + let Some(max_tokens) = prelude.memory_block_budget() else { + return MemoryBlockPrewarm::Unavailable; + }; + let Some(scope) = prelude.memory_scope("prewarm").await else { + return MemoryBlockPrewarm::Unavailable; + }; + let key = ready_key(&scope, max_tokens); + if contains(&key) { + return MemoryBlockPrewarm::AlreadyReady; + } + match prelude.render_in(&scope, max_tokens, "prewarm").await { + RenderedBlock::Block(block) => put(key, Some(block.text())), + RenderedBlock::Empty => put(key, None), + _ => return MemoryBlockPrewarm::Failed, + } + MemoryBlockPrewarm::Ready + } +} + +impl OpenHumanTurnPrelude { + /// The block a generation start sends: one rendered ahead of it, else a + /// render, within `[memory] memory_block_deadline_ms` when set. A render + /// that outlasts the deadline is [`RenderedBlock::Deferred`] and ends in + /// the store for the next generation start. + pub(super) async fn block_for_generation( + &self, + max_tokens: u32, + reason: &str, + ) -> RenderedBlock { + let Some(scope) = self.memory_scope(reason).await else { + return RenderedBlock::Empty; + }; + let key = ready_key(&scope, max_tokens); + if let Some(ready) = take(&key) { + tracing::info!( + thread_id = self.thread_id.as_deref().unwrap_or(""), + agent_id = self.agent_definition_id.as_str(), + reason, + tokens = ready + .as_deref() + .map_or(0, tinymemory_tools::recall::estimate_tokens), + "[memory_block] ready" + ); + return RenderedBlock::Ready(ready.map(Message::system)); + } + let Some(deadline) = scope + .config + .memory + .memory_block_deadline_ms + .map(Duration::from_millis) + else { + return self.render_in(&scope, max_tokens, reason).await; + }; + let (sender, mut receiver) = tokio::sync::oneshot::channel(); + let prelude = self.clone(); + let reason_owned = reason.to_string(); + let scope_owned = scope.clone(); + self.spawn_memory_work(async move { + let rendered = prelude + .render_in(&scope_owned, max_tokens, &reason_owned) + .await; + // Nobody waiting any more: the render is for the next start. + if let Err(rendered) = sender.send(rendered) { + match rendered { + RenderedBlock::Block(block) => put(key, Some(block.text())), + RenderedBlock::Empty => put(key, None), + _ => {} + } + } + }); + match tokio::time::timeout(deadline, &mut receiver).await { + Ok(Ok(rendered)) => rendered, + // The work was dropped (a retired profile). + Ok(Err(_)) => RenderedBlock::Failed, + Err(_) => { + // Close first, so a render landing now is either received + // here or sent to the store, never lost between the two. + receiver.close(); + if let Ok(rendered) = receiver.try_recv() { + return rendered; + } + tracing::info!( + thread_id = self.thread_id.as_deref().unwrap_or(""), + agent_id = self.agent_definition_id.as_str(), + reason, + deadline_ms = deadline.as_millis() as u64, + "[memory_block] deferred: the render goes on in the background" + ); + RenderedBlock::Deferred + } + } + } +} + +/// What a block read in `scope` with `max_tokens` is stored under. +fn ready_key(scope: &MemoryScope, max_tokens: u32) -> ReadyKey { + ReadyKey { + workspace: scope.config.workspace_dir.clone(), + identity: scope.identity.clone(), + max_tokens, + } +} + +/// How long a rendered block stays usable. +pub(super) const READY_MAX_AGE: Duration = Duration::from_secs(60 * 60); + +/// Most blocks held at once. +pub(super) const READY_CAPACITY: usize = 256; + +/// What a block was read for. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(super) struct ReadyKey { + pub(super) workspace: PathBuf, + pub(super) identity: ResolvedIdentity, + pub(super) max_tokens: u32, +} + +/// Blocks waiting for a generation start. `None` is a render that found +/// nothing known. +#[derive(Default)] +pub(super) struct ReadyBlocks { + entries: Mutex, Instant)>>, +} + +impl ReadyBlocks { + /// Holds `block` for `key`, replacing an earlier one. + pub(super) fn put_at(&self, key: ReadyKey, block: Option, now: Instant) { + let mut entries = self.lock(); + entries.retain(|_, (_, at)| fresh(*at, now)); + if entries.len() >= READY_CAPACITY && !entries.contains_key(&key) { + let oldest = entries + .iter() + .min_by_key(|(_, (_, at))| *at) + .map(|(key, _)| key.clone()); + if let Some(oldest) = oldest { + entries.remove(&oldest); + } + } + entries.insert(key, (block, now)); + } + + /// The block ready for `key`, removed; `None` when there is none or it is + /// stale. `Some(None)` is a ready render that found nothing known. + pub(super) fn take_at(&self, key: &ReadyKey, now: Instant) -> Option> { + let (block, at) = self.lock().remove(key)?; + fresh(at, now).then_some(block) + } + + /// Whether a fresh block is ready for `key`. + pub(super) fn contains_at(&self, key: &ReadyKey, now: Instant) -> bool { + self.lock().get(key).is_some_and(|(_, at)| fresh(*at, now)) + } + + fn lock(&self) -> std::sync::MutexGuard<'_, HashMap, Instant)>> { + self.entries + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +/// Whether a block put at `at` is still usable at `now`. +fn fresh(at: Instant, now: Instant) -> bool { + now.saturating_duration_since(at) <= READY_MAX_AGE +} + +static READY: LazyLock = LazyLock::new(ReadyBlocks::default); + +/// Holds `block` for `key` in the process-wide store. +pub(super) fn put(key: ReadyKey, block: Option) { + READY.put_at(key, block, Instant::now()); +} + +/// Takes the block ready for `key` from the process-wide store. +pub(super) fn take(key: &ReadyKey) -> Option> { + READY.take_at(key, Instant::now()) +} + +/// Whether the process-wide store holds a fresh block for `key`. +pub(super) fn contains(key: &ReadyKey) -> bool { + READY.contains_at(key, Instant::now()) +} + +#[cfg(test)] +#[path = "memory_block_ready_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready_tests.rs new file mode 100644 index 00000000000..33fa19acb2d --- /dev/null +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready_tests.rs @@ -0,0 +1,85 @@ +use super::*; + +use crate::config::Config; + +fn key(agent: &str, max_tokens: u32) -> ReadyKey { + ReadyKey { + workspace: PathBuf::from("/workspace"), + identity: tinymemory_tools::layout::identity::Identity::agent(agent) + .resolve(&crate::memory::scope::identity_pins(&Config::default())), + max_tokens, + } +} + +#[test] +fn a_ready_block_is_taken_once() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key("a", 500), Some("block".into()), now); + assert!(ready.contains_at(&key("a", 500), now)); + assert_eq!( + ready.take_at(&key("a", 500), now), + Some(Some("block".into())) + ); + assert_eq!(ready.take_at(&key("a", 500), now), None); + assert!(!ready.contains_at(&key("a", 500), now)); +} + +#[test] +fn a_render_that_found_nothing_is_ready_too() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key("a", 500), None, now); + assert_eq!(ready.take_at(&key("a", 500), now), Some(None)); +} + +#[test] +fn a_block_is_not_taken_for_another_identity_or_budget() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key("a", 500), Some("block".into()), now); + assert_eq!(ready.take_at(&key("b", 500), now), None); + assert_eq!(ready.take_at(&key("a", 400), now), None); + assert!(ready.contains_at(&key("a", 500), now)); +} + +#[test] +fn a_stale_block_is_dropped() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key("a", 500), Some("block".into()), now); + let later = now + READY_MAX_AGE + Duration::from_secs(1); + assert!(!ready.contains_at(&key("a", 500), later)); + assert_eq!(ready.take_at(&key("a", 500), later), None); + assert_eq!( + ready.take_at(&key("a", 500), now), + None, + "and gone for good" + ); +} + +#[test] +fn a_newer_block_replaces_an_older_one() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key("a", 500), Some("old".into()), now); + ready.put_at(key("a", 500), Some("new".into()), now); + assert_eq!(ready.take_at(&key("a", 500), now), Some(Some("new".into()))); +} + +#[test] +fn the_oldest_block_makes_room_at_capacity() { + let ready = ReadyBlocks::default(); + let start = Instant::now(); + for n in 0..=READY_CAPACITY { + let at = start + Duration::from_millis(n as u64); + ready.put_at(key(&format!("agent-{n}"), 500), Some("block".into()), at); + } + let now = start + Duration::from_secs(1); + assert!( + !ready.contains_at(&key("agent-0", 500), now), + "the oldest left" + ); + assert!(ready.contains_at(&key("agent-1", 500), now)); + assert!(ready.contains_at(&key(&format!("agent-{READY_CAPACITY}"), 500), now)); +} 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 4ab0bf5589c..62bcdfd713c 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 @@ -2,11 +2,12 @@ use super::*; use std::sync::Arc; use super::super::prompt_refresh::PROMPT_UPDATE_NOTE; +use super::super::MemoryBlockPrewarm; use crate::agent::prompts::SystemPromptBuilder; use crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshotSink; use crate::agent_registry::host_definition::{AgentDefinitionRegistry, MemoryBlock}; use crate::config::Config; -use crate::memory::test_fixtures::{bind_reference, config_in, RefusingEngine}; +use crate::memory::test_fixtures::{bind_reference, config_in, RefusingEngine, SlowEngine}; use crate::storage::sessions::splice_fixture_tests::memory_locator; use tinyagents_definition::PromptSource; use tinyagents_runtime::{SessionTurnRequest, TranscriptTarget}; @@ -425,3 +426,213 @@ async fn a_generation_opened_outside_a_turn_can_take_a_fresh_block() { without.definition = Some(Arc::new(definition)); assert_eq!(without.memory_block_for_new_generation().await, None); } + +/// `config` with the memory-block deadline set to `ms`. +fn with_deadline(mut config: Config, ms: u64) -> Config { + config.memory.memory_block_deadline_ms = Some(ms); + config +} + +const SLOW: std::time::Duration = std::time::Duration::from_secs(5); + +/// A resumed thread whose recorded prefix carries a block and whose prompt is +/// replaced: its turn opens a generation and so renders a fresh block. +fn generation_start() -> (PrefixSnapshot, Vec) { + ( + PrefixSnapshot::new(vec![Message::system(PROMPT), block("- teal")]), + vec![ + Message::system(PROMPT), + block("- teal"), + Message::user("hello"), + ], + ) +} + +#[tokio::test(start_paused = true)] +async fn memory_block_render_respects_deadline() { + let tmp = tempfile::tempdir().unwrap(); + let config = with_deadline(config_in(&tmp), 300); + let engine = SlowEngine::new(SLOW); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + let prelude = prelude(&config, "You are blocky, v2.", true); + let (recorded, history) = generation_start(); + + let started = tokio::time::Instant::now(); + let (prepared, _) = prepare(&prelude, false, &view(&recorded, &history, None)).await; + + assert!( + started.elapsed() <= std::time::Duration::from_millis(400), + "{:?}", + started.elapsed() + ); + let offered = prepared.prefix.expect("a refreshed prefix"); + assert_eq!(offered.messages()[0].text(), "You are blocky, v2."); + assert_eq!(offered.messages().last(), Some(&block("- teal"))); +} + +#[tokio::test(start_paused = true)] +async fn a_cold_thread_sends_no_block_when_the_render_lapses() { + let tmp = tempfile::tempdir().unwrap(); + let config = with_deadline(config_in(&tmp), 300); + let engine = SlowEngine::new(SLOW); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + let prelude = prelude(&config, PROMPT, false); + let empty = PrefixSnapshot::default(); + + let started = tokio::time::Instant::now(); + let (prepared, _) = prepare(&prelude, true, &view(&empty, &[], None)).await; + + assert!(started.elapsed() <= std::time::Duration::from_millis(400)); + let messages = sent(&prepared, &empty); + assert!(!messages.iter().any(is_memory_block), "{messages:?}"); + assert_eq!(messages.first().map(Message::text).as_deref(), Some(PROMPT)); +} + +#[tokio::test(start_paused = true)] +async fn deferred_memory_block_is_used_next_generation() { + let tmp = tempfile::tempdir().unwrap(); + let config = with_deadline(config_in(&tmp), 300); + let engine = SlowEngine::new(SLOW); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + let prelude = prelude(&config, "You are blocky, v2.", true); + let (recorded, history) = generation_start(); + + let (current, _) = prepare(&prelude, false, &view(&recorded, &history, None)).await; + let current = current.prefix.expect("a refreshed prefix"); + assert_eq!(current.messages().last(), Some(&block("- teal"))); + assert!( + !current + .messages() + .iter() + .any(|m| m.text().contains("Lisbon")), + "the render that lapsed never reaches the generation in flight" + ); + + // The render finishes in the background; the next generation start takes it. + tokio::time::sleep(SLOW).await; + let reads = engine.reads(); + let started = tokio::time::Instant::now(); + let (next, _) = prepare(&prelude, false, &view(&recorded, &history, None)).await; + let next = next.prefix.expect("a refreshed prefix"); + assert!( + next.messages() + .last() + .expect("a block") + .text() + .contains("Lisbon"), + "{next:?}" + ); + assert_eq!(started.elapsed(), std::time::Duration::ZERO); + assert_eq!(engine.reads(), reads, "taken, not read again"); +} + +#[tokio::test(start_paused = true)] +async fn a_render_inside_the_deadline_is_used_and_not_kept_for_later() { + let tmp = tempfile::tempdir().unwrap(); + let config = with_deadline(config_in(&tmp), 300); + let engine = SlowEngine::new(std::time::Duration::from_millis(100)); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + let prelude = prelude(&config, PROMPT, false); + let empty = PrefixSnapshot::default(); + + let (prepared, _) = prepare(&prelude, true, &view(&empty, &[], None)).await; + let messages = sent(&prepared, &empty); + assert!(messages.last().expect("a block").text().contains("Lisbon")); + assert_eq!(engine.reads(), 2); + + // Nothing was left over, so the next generation start reads again. + prepare(&prelude, true, &view(&empty, &[], None)).await; + assert_eq!(engine.reads(), 4); +} + +#[tokio::test(start_paused = true)] +async fn prewarmed_memory_block_skips_render_on_turn() { + let tmp = tempfile::tempdir().unwrap(); + // No deadline: the turn must not render at all. + let config = config_in(&tmp); + let engine = SlowEngine::new(SLOW); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + + let host = host(&config, PROMPT, false); + assert_eq!(host.prewarm_memory_block().await, MemoryBlockPrewarm::Ready); + assert_eq!(engine.reads(), 2); + assert_eq!( + host.prewarm_memory_block().await, + MemoryBlockPrewarm::AlreadyReady + ); + assert_eq!( + engine.reads(), + 2, + "a block already waiting is not read again" + ); + + let prelude = prelude(&config, PROMPT, false); + let empty = PrefixSnapshot::default(); + let started = tokio::time::Instant::now(); + let (prepared, _) = prepare(&prelude, true, &view(&empty, &[], None)).await; + + assert_eq!(started.elapsed(), std::time::Duration::ZERO); + assert_eq!(engine.reads(), 2, "the turn read nothing"); + let messages = sent(&prepared, &empty); + assert!(messages.last().expect("a block").text().contains("Lisbon")); +} + +#[tokio::test(start_paused = true)] +async fn a_prewarm_is_taken_by_one_generation_start_only() { + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + let engine = SlowEngine::new(std::time::Duration::from_millis(10)); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + host(&config, PROMPT, false).prewarm_memory_block().await; + let prelude = prelude(&config, PROMPT, false); + let empty = PrefixSnapshot::default(); + + prepare(&prelude, true, &view(&empty, &[], None)).await; + assert_eq!(engine.reads(), 2); + prepare(&prelude, true, &view(&empty, &[], None)).await; + assert_eq!(engine.reads(), 4, "the second start renders for itself"); +} + +#[tokio::test] +async fn a_failed_prewarm_leaves_the_turn_to_render() { + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + RefusingEngine::out_of_credits().bind(&config); + assert_eq!( + host(&config, PROMPT, false).prewarm_memory_block().await, + MemoryBlockPrewarm::Failed + ); + + learn( + &bind_reference(&config), + &config, + "The user lives in Lisbon", + ) + .await; + let prelude = prelude(&config, PROMPT, false); + let empty = PrefixSnapshot::default(); + let (prepared, _) = prepare(&prelude, true, &view(&empty, &[], None)).await; + let messages = sent(&prepared, &empty); + assert!(messages.last().expect("a block").text().contains("Lisbon")); +} + +#[tokio::test] +async fn an_agent_without_a_memory_block_has_nothing_to_prewarm() { + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + bind_reference(&config); + let mut without = host(&config, PROMPT, false); + let mut definition = (**without.definition.as_ref().expect("a definition")).clone(); + definition.extensions.memory_block = None; + without.definition = Some(Arc::new(definition)); + assert_eq!( + without.prewarm_memory_block().await, + MemoryBlockPrewarm::Unavailable + ); +} diff --git a/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs b/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs index 6158437cd9e..21f05b39066 100644 --- a/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs +++ b/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs @@ -1,6 +1,6 @@ //! Compacting a thread's stored conversation with no model turn. -use crate::agent::session_host::{CompactOptions, CompactOutcome}; +use crate::agent::session_host::{CompactOptions, CompactOutcome, MemoryBlockPrewarm}; use crate::config::Config; use super::session_turn::{apply_turn_overrides, build_turn_agent, AgentChatTarget}; @@ -49,3 +49,31 @@ pub fn compact_thread_for<'a>( session.compact_bound_history(options).await }) } + +/// Render `thread_id`'s memory block now, on `target`'s session built as a +/// turn's is, for that thread's next generation start to take. See +/// [`OpenHumanSessionHost::prewarm_memory_block`] +/// (crate::agent::OpenHumanSessionHost::prewarm_memory_block). +/// +/// # Errors +/// +/// When `thread_id` is blank or the session cannot be built. +#[inline(never)] +pub fn prewarm_memory_block_for<'a>( + config: &'a mut Config, + target: AgentChatTarget<'a>, + thread_id: &'a str, +) -> futures::future::BoxFuture<'a, anyhow::Result> { + Box::pin(async move { + let thread_id = thread_id.trim(); + if thread_id.is_empty() { + anyhow::bail!("prewarm_memory_block needs a thread id"); + } + let ctx = crate::core::runtime::DispatchCtx::from_weak(None); + let mut session = build_turn_agent(&ctx, config, &target, Some(thread_id), None, None) + .await + .map_err(anyhow::Error::msg)?; + session.set_thread_id(Some(thread_id)); + Ok(session.prewarm_memory_block().await) + }) +} diff --git a/crates/openhuman-core/src/agent_runs/agent_chat/mod.rs b/crates/openhuman-core/src/agent_runs/agent_chat/mod.rs index 7609444a90c..daf2e5fdf9a 100644 --- a/crates/openhuman-core/src/agent_runs/agent_chat/mod.rs +++ b/crates/openhuman-core/src/agent_runs/agent_chat/mod.rs @@ -8,7 +8,7 @@ pub(crate) mod guards; pub(crate) mod params; mod session_turn; -pub use compact::compact_thread_for; +pub use compact::{compact_thread_for, prewarm_memory_block_for}; pub use envelope::AgentChatReply; pub use session_turn::{ agent_chat, agent_chat_for, agent_chat_reply_for, agent_chat_reply_for_controlled, diff --git a/crates/openhuman-core/src/config/schema/memory.rs b/crates/openhuman-core/src/config/schema/memory.rs index 6fd7f20cc57..e09e1162001 100644 --- a/crates/openhuman-core/src/config/schema/memory.rs +++ b/crates/openhuman-core/src/config/schema/memory.rs @@ -6,6 +6,7 @@ //! # agent_id = "writer-7" # host binding: every agent on this config is this memory agent //! # root = "team:acme" # host binding: the layout root (one per tenant) //! # recall_each_turn_ms = 1500 # host binding: recall the current message, waiting this long +//! # memory_block_deadline_ms = 300 # host binding: render the memory block for at most this long //! //! [memory.engines.cortexdb] //! endpoint = "https://api-v1.cortexdb.ai" # key in the keychain as "memory-cortexdb" @@ -122,6 +123,14 @@ pub struct MemoryConfig { /// background for an earlier turn. #[serde(skip_serializing_if = "Option::is_none")] pub recall_each_turn_ms: Option, + /// Host binding: wait at most this many milliseconds for the memory block + /// a new transcript generation renders before the first model call. When + /// the deadline lapses the turn keeps the block its thread recorded (a + /// cold thread sends none), and the render finishes in the background + /// for the next generation's start. Unset (the default), a generation + /// start waits for the render however long it takes. + #[serde(skip_serializing_if = "Option::is_none")] + pub memory_block_deadline_ms: Option, /// Where memory sits on the engine: `legacy` (the shared /// `app:tinymemory` tree, the default) or `v3` (the signed-in person's /// own `org:` subtree, chats pooled at `ws:main`). Switched by the @@ -233,6 +242,7 @@ impl Default for MemoryConfig { agent_id: None, root: None, recall_each_turn_ms: None, + memory_block_deadline_ms: None, layout: MemoryLayoutMode::Legacy, conversations: MemoryConversationsConfig::default(), recall: RecallSettings::default(), diff --git a/crates/openhuman-core/src/config/schema/memory_tests.rs b/crates/openhuman-core/src/config/schema/memory_tests.rs index 7bbedc44763..5198d7b876f 100644 --- a/crates/openhuman-core/src/config/schema/memory_tests.rs +++ b/crates/openhuman-core/src/config/schema/memory_tests.rs @@ -415,3 +415,19 @@ fn recall_each_turn_is_an_optional_host_binding_in_milliseconds() { let written = toml::to_string(&config).expect("serializes"); assert!(written.contains("recall_each_turn_ms = 1500"), "{written}"); } + +#[test] +fn memory_block_deadline_is_an_optional_host_binding_in_milliseconds() { + assert_eq!(MemoryConfig::default().memory_block_deadline_ms, None); + let unset = toml::to_string(&MemoryConfig::default()).expect("serializes"); + assert!(!unset.contains("memory_block_deadline_ms"), "{unset}"); + + let config: MemoryConfig = + toml::from_str("memory_block_deadline_ms = 300").expect("the binding parses"); + assert_eq!(config.memory_block_deadline_ms, Some(300)); + let written = toml::to_string(&config).expect("serializes"); + assert!( + written.contains("memory_block_deadline_ms = 300"), + "{written}" + ); +} diff --git a/crates/openhuman-core/src/memory/README.md b/crates/openhuman-core/src/memory/README.md index b603641184c..5cfe044cbc7 100644 --- a/crates/openhuman-core/src/memory/README.md +++ b/crates/openhuman-core/src/memory/README.md @@ -179,6 +179,14 @@ host already puts in the system prompt: a pack whose every cited hit it excludes is left out (TinyMemory renders the pack, so single lines cannot be dropped yet). +The memory block a new transcript generation renders (see +`agent/session_host/runtime_session/memory_block.rs`) can likewise be taken off +the turn's path: `[memory] memory_block_deadline_ms` (embed: +`MemoryBinding::memory_block_deadline`) bounds the wait, a render that lapses +is kept for the next generation start (`[memory_block] deferred`), and +`Agent::prewarm_memory_block(thread_id)` renders it ahead of a turn. Its +beliefs and learnings are read concurrently. + The live prelude and compaction summarizer call the underlying work directly from the scoped prefetch workers. Their background deadlines bound engine I/O without a second manual timeout wrapper. diff --git a/crates/openhuman-core/src/memory/lifecycle/memory_block.rs b/crates/openhuman-core/src/memory/lifecycle/memory_block.rs index 36c4480386e..2c8e7e1bb4f 100644 --- a/crates/openhuman-core/src/memory/lifecycle/memory_block.rs +++ b/crates/openhuman-core/src/memory/lifecycle/memory_block.rs @@ -14,6 +14,9 @@ //! 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 std::future::Future; +use std::time::Instant; + use tinymemory_api::{BeliefsRequest, Error, Hit, ListRequest, Reach, Result, BELIEF_TAG}; use tinymemory_tools::layout::identity::ResolvedIdentity; use tinymemory_tools::recall::estimate_tokens; @@ -80,6 +83,7 @@ pub(crate) async fn read( identity: &ResolvedIdentity, max_tokens: u32, ) -> Result> { + let started = Instant::now(); let memory = match super::agent_memory(config, identity).await { Ok(memory) => memory, Err(Error::Off(reason)) => { @@ -88,21 +92,41 @@ pub(crate) async fn read( } Err(error) => return Err(error), }; + let resolve_ms = elapsed_ms(started); let engine = memory.engine(); - let beliefs = engine - .beliefs(BeliefsRequest::new( + // Two independent round trips: overlapped, a hosted engine's latency is + // paid once. + let (beliefs, facts) = futures::try_join!( + timed(engine.beliefs(BeliefsRequest::new( Reach::subtree(identity.root().clone()), BELIEFS_LIMIT, - )) - .await?; - let facts = engine - .list(ListRequest::new( + ))), + timed(engine.list(ListRequest::new( identity.layout.learnings_filter(), FACTS_LIMIT, - )) - .await? - .items; - Ok(render(&beliefs, &facts, max_tokens)) + ))), + )?; + tracing::debug!( + resolve_ms, + beliefs_ms = beliefs.1, + list_ms = facts.1, + beliefs = beliefs.0.len(), + facts = facts.0.items.len(), + "[memory_block] read" + ); + Ok(render(&beliefs.0, &facts.0.items, max_tokens)) +} + +/// Whole milliseconds since `started`. +fn elapsed_ms(started: Instant) -> u64 { + u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX) +} + +/// `read`'s answer with the milliseconds it took. +async fn timed(read: impl Future>) -> Result<(T, u64)> { + let started = Instant::now(); + let answer = read.await?; + Ok((answer, elapsed_ms(started))) } #[cfg(test)] 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 f207fe54ea5..ac9cf78200d 100644 --- a/crates/openhuman-core/src/memory/lifecycle/memory_block_tests.rs +++ b/crates/openhuman-core/src/memory/lifecycle/memory_block_tests.rs @@ -1,6 +1,6 @@ use super::*; -use crate::memory::test_fixtures::{bind_reference, config_in, RefusingEngine}; +use crate::memory::test_fixtures::{bind_reference, config_in, RefusingEngine, SlowEngine}; use tinymemory_api::{LearningKind, MemoryEngine, MemoryMeta, StoreItem}; fn hit(text: &str, tags: &[&str]) -> Hit { @@ -140,3 +140,22 @@ async fn an_engine_failure_is_an_error() { let identity = identity(&config, "block-refused"); assert!(read(&config, &identity, 500).await.is_err()); } + +#[tokio::test(start_paused = true)] +async fn the_beliefs_and_learnings_are_read_together() { + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + let engine = SlowEngine::new(std::time::Duration::from_secs(3)); + SlowEngine::bind(&engine, &config); + let identity = identity(&config, "block-parallel"); + + let started = tokio::time::Instant::now(); + read(&config, &identity, 500).await.expect("a read"); + + assert_eq!(engine.reads(), 2); + assert_eq!( + started.elapsed(), + std::time::Duration::from_secs(3), + "two reads of 3 s overlap instead of adding up to 6 s" + ); +} diff --git a/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs b/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs index 855b3a06d16..6653b847cc2 100644 --- a/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs +++ b/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs @@ -147,6 +147,23 @@ impl OpenHumanTurnPrelude { ) } + /// Spawns `work` under the context this session's memory work runs in, so + /// it can outlive the turn that started it. Work of a retired profile is + /// dropped, like a deferred commit. + pub(super) fn spawn_memory_work( + &self, + work: impl std::future::Future + Send + 'static, + ) { + let profile_context = capture_profile_context( + &self.dispatch_ctx(), + crate::profiles::host::host().as_deref(), + ); + drop( + self.dispatch_ctx() + .spawn(deferred_memory_work(profile_context, work)), + ); + } + /// Takes completed memory and queues a user-authored turn's log and recall. /// Remembers the turn so the reply is logged under the same identity and /// index, and returns its memory for the run context without engine I/O. diff --git a/crates/openhuman-core/src/memory/test_fixtures.rs b/crates/openhuman-core/src/memory/test_fixtures.rs index 6f8a9574486..0a78b6ef497 100644 --- a/crates/openhuman-core/src/memory/test_fixtures.rs +++ b/crates/openhuman-core/src/memory/test_fixtures.rs @@ -308,3 +308,106 @@ impl MemoryEngine for RecordingEngine { self.inner.erase(req).await } } + +/// The reference engine with every memory-block read (`beliefs` and `list`) +/// taking `delay` first, the way the hosted engine's round trips do. It counts +/// the reads it served, so a test can tell a render from a reused block. +pub(crate) struct SlowEngine { + inner: Arc, + delay: std::time::Duration, + reads: std::sync::atomic::AtomicUsize, +} + +impl SlowEngine { + /// A slow engine over a fresh reference engine. + pub(crate) fn new(delay: std::time::Duration) -> Arc { + Arc::new(Self { + inner: Arc::new(ReferenceEngine::new()), + delay, + reads: std::sync::atomic::AtomicUsize::new(0), + }) + } + + /// The engine underneath, to store through without the delay. + pub(crate) fn inner(&self) -> &Arc { + &self.inner + } + + /// Binds the engine to `config`'s workspace. + pub(crate) fn bind(engine: &Arc, config: &Config) { + crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone()); + } + + /// How many `beliefs` and `list` reads were served. + pub(crate) fn reads(&self) -> usize { + self.reads.load(std::sync::atomic::Ordering::SeqCst) + } + + async fn slow(&self) { + self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + tokio::time::sleep(self.delay).await; + } +} + +#[async_trait::async_trait] +impl MemoryEngine for SlowEngine { + fn descriptor(&self) -> &tinymemory_api::EngineDescriptor { + self.inner.descriptor() + } + + async fn health(&self) -> tinymemory_api::EngineHealth { + self.inner.health().await + } + + async fn recall( + &self, + req: tinymemory_api::RecallRequest, + ) -> tinymemory_api::Result { + self.inner.recall(req).await + } + + async fn fetch( + &self, + req: tinymemory_api::FetchRequest, + ) -> tinymemory_api::Result { + self.inner.fetch(req).await + } + + async fn store( + &self, + item: tinymemory_api::StoreItem, + ) -> tinymemory_api::Result { + self.inner.store(item).await + } + + async fn forget( + &self, + target: tinymemory_api::ForgetTarget, + ) -> tinymemory_api::Result { + self.inner.forget(target).await + } + + async fn list(&self, req: ListRequest) -> tinymemory_api::Result { + self.slow().await; + self.inner.list(req).await + } + + async fn export(&self, req: ListRequest) -> tinymemory_api::Result { + self.inner.export(req).await + } + + async fn consolidate( + &self, + req: tinymemory_api::ConsolidateRequest, + ) -> tinymemory_api::Result { + self.inner.consolidate(req).await + } + + async fn beliefs( + &self, + req: tinymemory_api::BeliefsRequest, + ) -> tinymemory_api::Result> { + self.slow().await; + self.inner.beliefs(req).await + } +} diff --git a/crates/openhuman-embed/src/agent/README.md b/crates/openhuman-embed/src/agent/README.md index 99faa3354a7..5a1869342fd 100644 --- a/crates/openhuman-embed/src/agent/README.md +++ b/crates/openhuman-embed/src/agent/README.md @@ -31,7 +31,7 @@ with the same id cannot both pass the duplicate check), then calls 5. provider model route stays per turn, never written to config 6. MCP servers appended to mcp_client.servers (mcp feature) 7. Composio credential pinned for this agent only - 8. memory binding memory.agent_id, memory.root, memory.recall_each_turn_ms + 8. memory binding memory.agent_id, memory.root, memory.recall_each_turn_ms, memory.memory_block_deadline_ms 9. config escape hatch then config_path is reset to the runtime's 10. create dirs action_dir, agents//, agents//skills/ 11. copy skills (skills feature) diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rs index e5d26078664..0b88ff74e0d 100644 --- a/crates/openhuman-embed/src/agent/build.rs +++ b/crates/openhuman-embed/src/agent/build.rs @@ -178,6 +178,9 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result Result { + let inner = Arc::clone(&self.inner); + if !inner.ctx.domains().inference { + return Err(CoreError::Unavailable { + method: PREWARM_MEMORY_BLOCK, + } + .into()); + } + let ctx = inner.ctx.clone(); + let runtime = inner.runtime.clone(); + let thread_id = thread_id.to_owned(); + let agent = Arc::clone(&inner); + let prewarm = Box::pin(async move { + use openhuman_core::inference::host_runtime::ops::AgentChatTarget; + let host = agent.composed_host_tools(); + let target = AgentChatTarget::Definition { + definition: &agent.definition, + host: host.as_ref(), + seed: None, + usage: None, + host_only: agent.host_only, + untrusted_input: false, + shape: None, + observer: None, + attachments: &[], + }; + let mut config = agent.config.clone(); + openhuman_core::agent_runs::agent_chat::prewarm_memory_block_for( + &mut config, + target, + &thread_id, + ) + .await + .map_err(|error| CoreError::Rpc { + method: PREWARM_MEMORY_BLOCK, + message: error.to_string(), + }) + }); + inner + .lifecycle + .admit( + &inner.id, + PREWARM_MEMORY_BLOCK, + runtime.run_in(ctx, prewarm), + ) + .await + .map_err(Into::into) + } } diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rs index cf2a77cd1e9..9aac01ed4ed 100644 --- a/crates/openhuman-embed/src/agent/mod.rs +++ b/crates/openhuman-embed/src/agent/mod.rs @@ -19,7 +19,7 @@ mod approvals; pub use approval_handler::{ApprovalHandler, ApprovalSubscription}; mod attachments; mod compact; -pub use compact::{CompactOptions, CompactOutcome}; +pub use compact::{CompactOptions, CompactOutcome, MemoryBlockPrewarm}; pub(crate) mod lifecycle; pub(crate) mod mcp_cleanup; pub use approvals::{ApprovalDecision, Approvals, ApprovalsError, PendingApproval}; diff --git a/crates/openhuman-embed/src/agent/spec.rs b/crates/openhuman-embed/src/agent/spec.rs index bd89209daf2..755dbae604f 100644 --- a/crates/openhuman-embed/src/agent/spec.rs +++ b/crates/openhuman-embed/src/agent/spec.rs @@ -79,6 +79,7 @@ pub struct MemoryBinding { agent_id: String, root: Option, recall_each_turn: Option, + memory_block_deadline: Option, } impl MemoryBinding { @@ -88,6 +89,7 @@ impl MemoryBinding { agent_id: agent_id.into(), root: None, recall_each_turn: None, + memory_block_deadline: None, } } @@ -115,6 +117,21 @@ impl MemoryBinding { self } + /// Wait at most `deadline` for the memory block + /// ([`AgentDefinitionSpec::memory_block`]) a new transcript generation + /// renders before the turn's first model call. + /// + /// When it lapses, the turn goes on with the block its thread recorded (a + /// new thread with none), and the render finishes in the background for + /// the next generation start. Without this, a generation start waits for + /// the render however long the memory engine takes. + /// [`Agent::prewarm_memory_block`] renders it ahead of a turn instead. + #[must_use] + pub fn memory_block_deadline(mut self, deadline: std::time::Duration) -> Self { + self.memory_block_deadline = Some(deadline); + self + } + /// The memory agent id. pub fn agent_id(&self) -> &str { &self.agent_id @@ -125,6 +142,12 @@ impl MemoryBinding { self.root.as_deref() } + /// How long a generation start waits for its memory block, when + /// [`memory_block_deadline`](Self::memory_block_deadline) is set. + pub fn memory_block_deadline_timeout(&self) -> Option { + self.memory_block_deadline + } + /// How long a turn waits for its own recall, when /// [`recall_each_turn`](Self::recall_each_turn) is set. pub fn recall_each_turn_timeout(&self) -> Option { diff --git a/crates/openhuman-embed/src/agent/spec_tests.rs b/crates/openhuman-embed/src/agent/spec_tests.rs index 88a3493e0e8..e82fe429c39 100644 --- a/crates/openhuman-embed/src/agent/spec_tests.rs +++ b/crates/openhuman-embed/src/agent/spec_tests.rs @@ -70,3 +70,14 @@ fn a_memory_binding_recalls_each_turn_only_when_asked() { ); assert_eq!(binding.root_namespace(), Some("team:acme")); } + +#[test] +fn a_memory_binding_bounds_the_memory_block_only_when_asked() { + let binding = MemoryBinding::new("writer"); + assert_eq!(binding.memory_block_deadline_timeout(), None); + let binding = binding.memory_block_deadline(std::time::Duration::from_millis(300)); + assert_eq!( + binding.memory_block_deadline_timeout(), + Some(std::time::Duration::from_millis(300)) + ); +} diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs index 8a757f23c27..008c61c8798 100644 --- a/crates/openhuman-embed/src/lib.rs +++ b/crates/openhuman-embed/src/lib.rs @@ -177,8 +177,8 @@ pub use openhuman_core::voice::VOICE_COMPILED_IN; pub use agent::ToolAttachmentError; pub use agent::{ Agent, AgentDefinitionSpec, AgentError, AgentLayout, AgentSpec, ApprovalDecision, Approvals, - ApprovalsError, CompactOptions, CompactOutcome, DefinitionBase, MemoryBinding, MemoryBlockSpec, - PendingApproval, SandboxModeSpec, ToolScopeSpec, + ApprovalsError, CompactOptions, CompactOutcome, DefinitionBase, MemoryBinding, + MemoryBlockPrewarm, MemoryBlockSpec, PendingApproval, SandboxModeSpec, ToolScopeSpec, }; pub use auth::{Auth, AuthState, Session}; #[cfg(feature = "channels")] diff --git a/crates/openhuman-embed/tests/runtime_agents.rs b/crates/openhuman-embed/tests/runtime_agents.rs index 1d8025ac1fc..8dff86b44d5 100644 --- a/crates/openhuman-embed/tests/runtime_agents.rs +++ b/crates/openhuman-embed/tests/runtime_agents.rs @@ -560,10 +560,14 @@ fn one_runtime_hosts_independently_configured_agents() { // unbound agent keeps the runtime's defaults. let bound = runtime .agent( - AgentSpec::new("employee") - .memory(MemoryBinding::new("employee-7").root("team:acme")), + AgentSpec::new("employee").memory( + MemoryBinding::new("employee-7") + .root("team:acme") + .memory_block_deadline(std::time::Duration::from_millis(300)), + ), ) .expect("a bound agent instantiates"); + assert_eq!(bound.config().memory.memory_block_deadline_ms, Some(300)); assert_eq!( bound.config().memory.agent_id.as_deref(), Some("employee-7") From 0b19ca53f7fc53f4158220e67f25e37c672afafa Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sat, 7 Nov 2026 22:09:19 +0300 Subject: [PATCH 02/24] chore(deps): bump tinyagents to the epic-712 tool-tokens tip Takes tool sizes on ToolCompleted/TurnObservation::Tool and the discovery policy options (promote, compact, collapse, tool_call repair). The tool completion test literals gain input_bytes: None. Co-authored-by: Medulla --- .../src/agent/tinyagents/observability_projection_tests.rs | 1 + .../openhuman-core/src/agent/tinyagents/observability_tests.rs | 3 +++ .../src/agent/tinyagents/observability_tests_tool_rows.rs | 1 + .../src/core/observability/trace_export_adoption_tests.rs | 1 + vendor/tinyagents | 2 +- 5 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/agent/tinyagents/observability_projection_tests.rs b/crates/openhuman-core/src/agent/tinyagents/observability_projection_tests.rs index cc28c3cf725..9b9122bedc4 100644 --- a/crates/openhuman-core/src/agent/tinyagents/observability_projection_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/observability_projection_tests.rs @@ -109,6 +109,7 @@ async fn tool_call_events_use_the_tool_s_own_display_label_and_detail() { input: Some(serde_json::json!({"to": "steven@example.com"})), output: Some(serde_json::Value::String("sent".to_string())), duration_ms: Some(5), + input_bytes: None, output_bytes: Some(4), error: None, metadata: None, diff --git a/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs b/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs index 5bb240e14de..e02dc7010aa 100644 --- a/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs @@ -76,6 +76,7 @@ async fn bridge_forwards_tool_and_cost_progress() { input: None, output: None, duration_ms: None, + input_bytes: None, output_bytes: None, error: None, metadata: None, @@ -373,6 +374,7 @@ async fn tool_completed_projects_output_arguments_and_elapsed() { input: Some(serde_json::json!({"text": "ping"})), output: Some(serde_json::Value::String("pong".to_string())), duration_ms: None, + input_bytes: None, output_bytes: None, error: None, metadata: None, @@ -426,6 +428,7 @@ fn emit_recovered_unknown_tool_call(sink: &EventSink, call_id: &str) { input: Some(serde_json::json!({ "query": "config" })), output: Some(serde_json::Value::String(UNKNOWN_TOOL_ANSWER.to_string())), duration_ms: Some(0), + input_bytes: None, output_bytes: Some(UNKNOWN_TOOL_ANSWER.len() as u64), error: Some(UNKNOWN_TOOL_ANSWER.to_string()), metadata: None, diff --git a/crates/openhuman-core/src/agent/tinyagents/observability_tests_tool_rows.rs b/crates/openhuman-core/src/agent/tinyagents/observability_tests_tool_rows.rs index 9f11504e375..de376f98c5e 100644 --- a/crates/openhuman-core/src/agent/tinyagents/observability_tests_tool_rows.rs +++ b/crates/openhuman-core/src/agent/tinyagents/observability_tests_tool_rows.rs @@ -235,6 +235,7 @@ async fn tool_call_events_use_the_tool_s_own_display_label_and_detail() { input: Some(serde_json::json!({"to": "steven@example.com"})), output: Some(serde_json::Value::String("sent".to_string())), duration_ms: Some(5), + input_bytes: None, output_bytes: Some(4), error: None, metadata: None, diff --git a/crates/openhuman-core/src/core/observability/trace_export_adoption_tests.rs b/crates/openhuman-core/src/core/observability/trace_export_adoption_tests.rs index aebe3299392..464a8fe3490 100644 --- a/crates/openhuman-core/src/core/observability/trace_export_adoption_tests.rs +++ b/crates/openhuman-core/src/core/observability/trace_export_adoption_tests.rs @@ -87,6 +87,7 @@ fn parent_run() -> Vec { input: Some(serde_json::json!({"query":"CONTENT_SENTINEL_INPUT"})), output: Some(serde_json::json!({"result":"CONTENT_SENTINEL_OUTPUT"})), duration_ms: Some(70), + input_bytes: None, output_bytes: Some(33), error: None, metadata: None, diff --git a/vendor/tinyagents b/vendor/tinyagents index e096d8b8c86..3611644ff03 160000 --- a/vendor/tinyagents +++ b/vendor/tinyagents @@ -1 +1 @@ -Subproject commit e096d8b8c8609ded16681191fe20cddbf18986d3 +Subproject commit 3611644ff03bc6a6dab69ebf13cb1622074becae From 75270bedee846b95790d1d5d8ee535af06e56526 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sat, 7 Nov 2026 23:22:37 +0300 Subject: [PATCH 03/24] feat(tool-search): per-session discovery options, pinned on the thread Adds promote_found_tools, compact_search_results, collapse_search_results, repair_tool_call_wrapper and max_limit to [agent].tool_search (with env overrides), mapped onto the harness ToolDiscoveryPolicy. A session takes the four prompt-shaping options from the config when it creates a thread, records them on the thread's first transcript row when they differ from today's, and reads them back on resume, so a thread keeps the behaviour it started with. openhuman-embed gains AgentSpec::tool_discovery and Turn::tool_discovery (ToolDiscoveryOptions) and documents the tool sizes on observations. Co-authored-by: Medulla --- .../src/agent/session_host/codec.rs | 5 + .../session_host/codec_adoption_tests.rs | 36 ++++ .../agent/session_host/discovery_pin_tests.rs | 78 +++++++++ .../src/agent/session_host/mod.rs | 2 + .../session_host/runtime_session/ensure.rs | 25 +++ .../session_host/transcript_compat_tests.rs | 11 ++ .../src/agent/tinyagents/README.md | 6 +- .../tinyagents/discovery/discovery_tests.rs | 54 ++++++ .../src/agent/tinyagents/discovery/mod.rs | 10 ++ .../src/agent/tinyagents/discovery/pin.rs | 161 ++++++++++++++++++ .../agent/tinyagents/discovery/pin_tests.rs | 116 +++++++++++++ .../src/agent/tinyagents/host/run_context.rs | 5 + .../event_projection/tool_calls.rs | 13 +- .../openhuman-core/src/config/schema/agent.rs | 28 +++ .../src/config/schema/load/env_overlay.rs | 59 +++++++ .../config/schema/load_env_overlay_tests.rs | 33 ++++ crates/openhuman-embed/OBSERVERS.md | 3 + crates/openhuman-embed/src/agent/build.rs | 4 + .../openhuman-embed/src/agent/build_tests.rs | 60 +++++++ crates/openhuman-embed/src/agent/spec.rs | 21 +++ .../openhuman-embed/src/agent/spec_tests.rs | 12 ++ crates/openhuman-embed/src/lib.rs | 1 + crates/openhuman-embed/src/turn.rs | 27 +++ crates/openhuman-embed/src/turn_control.rs | 1 + .../openhuman-embed/tests/observed_turns.rs | 4 + docs/gitbooks/en/developing/jev.md | 10 ++ 26 files changed, 780 insertions(+), 5 deletions(-) create mode 100644 crates/openhuman-core/src/agent/session_host/discovery_pin_tests.rs create mode 100644 crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs create mode 100644 crates/openhuman-core/src/agent/tinyagents/discovery/pin_tests.rs diff --git a/crates/openhuman-core/src/agent/session_host/codec.rs b/crates/openhuman-core/src/agent/session_host/codec.rs index 7d532326aee..b123bbefe98 100644 --- a/crates/openhuman-core/src/agent/session_host/codec.rs +++ b/crates/openhuman-core/src/agent/session_host/codec.rs @@ -76,6 +76,11 @@ impl TranscriptCodec for OpenHumanTranscriptCodec { }); } } + // The turn that starts a thread writes down the discovery options it + // runs with, so every later turn reads them back instead of the config. + if let Some(options) = sidecar.discovery_record { + options.record_on(&mut reconciled.rows, &reconciled.fresh); + } attach_text_dialect_rounds( &mut reconciled.rows, &reconciled.fresh, diff --git a/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs b/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs index 0de3d6f8abf..ab77e2a7047 100644 --- a/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs @@ -193,3 +193,39 @@ fn failed_tool_outcome_does_not_mark_an_earlier_turns_result_with_the_same_call_ ); assert!(rows[3].tool_failure.as_ref().is_some_and(|f| f.failed)); } + +/// The turn that starts a thread records its discovery options on the first +/// row it writes; the turns after it neither add nor move the record. +#[test] +fn the_codec_records_discovery_options_on_the_first_new_row_only_once() { + use crate::agent::tinyagents::discovery::DiscoveryOptions; + + let options = |context| TranscriptTurnOptions { + request_id: Some("turn".into()), + thread_id: None, + stream: false, + resume: ResumeMode::Never, + context, + }; + let wanted = DiscoveryOptions { + promote_found_tools: false, + ..DiscoveryOptions::TODAY + }; + let context = OpenHumanRunContext::new(); + context.session_sidecar.lock().unwrap().discovery_record = Some(wanted); + let first = vec![Message::system("prompt"), Message::user("one")]; + let prior = OpenHumanTranscriptCodec + .reconcile(&[], &[], &first, &options(context)) + .unwrap(); + assert_eq!(DiscoveryOptions::recorded_in(&prior), Some(wanted)); + assert!(prior[1].extra_metadata.is_none()); + + // A later turn records nothing and leaves the stored row as it was. + let mut next = first.clone(); + next.push(Message::assistant("done")); + let rows = OpenHumanTranscriptCodec + .reconcile(&prior, &first, &next, &options(OpenHumanRunContext::new())) + .unwrap(); + assert_eq!(rows[0], prior[0]); + assert_eq!(DiscoveryOptions::recorded_in(&rows), Some(wanted)); +} diff --git a/crates/openhuman-core/src/agent/session_host/discovery_pin_tests.rs b/crates/openhuman-core/src/agent/session_host/discovery_pin_tests.rs new file mode 100644 index 00000000000..21d662ca4f4 --- /dev/null +++ b/crates/openhuman-core/src/agent/session_host/discovery_pin_tests.rs @@ -0,0 +1,78 @@ +//! A thread's `tool_search` options are chosen when it is created, recorded on +//! its first transcript row, and read back on resume: a config that changes +//! later reaches new threads only. + +use std::path::Path; + +use tinyinference_llm::model::ModelResponse; + +use super::transcript_compat_tests::{ + build_host_with_config, model, run_async, store_tree, thread_id, +}; +use crate::agent::tinyagents::discovery::DISCOVERY_METADATA_KEY; +use crate::config::schema::ToolSearchConfig; +use crate::config::AgentConfig; + +fn agent_config(tool_search: ToolSearchConfig) -> AgentConfig { + AgentConfig { + tool_search, + ..AgentConfig::default() + } +} + +fn no_promotion() -> ToolSearchConfig { + ToolSearchConfig { + promote_found_tools: false, + collapse_search_results: true, + ..ToolSearchConfig::default() + } +} + +/// Runs one turn of `thread` on a fresh host over `root`, as a new process +/// would, and returns how many stored rows carry the recorded options. +async fn turn_and_count_records(root: &Path, thread: &str, tool_search: ToolSearchConfig) -> usize { + let next = model(vec![ModelResponse::assistant("ok")], true); + let mut host = build_host_with_config(root, next, true, thread, agent_config(tool_search)); + host.turn("hello").await.expect("turn"); + let session = host.session.clone().expect("bound session"); + store_tree(root, thread, &session) + .values() + .map(|stored| stored.to_string().matches(DISCOVERY_METADATA_KEY).count()) + .sum() +} + +#[test] +fn a_new_thread_records_options_that_differ_from_today_once() { + run_async(async { + let root = tempfile::tempdir().expect("tempdir"); + let thread = thread_id("pinned-new"); + assert_eq!( + turn_and_count_records(root.path(), &thread, no_promotion()).await, + 1, + "the turn that creates the thread records its options" + ); + // A later process with a different config neither adds nor changes it. + assert_eq!( + turn_and_count_records(root.path(), &thread, ToolSearchConfig::default()).await, + 1, + "a resumed thread keeps the record it started with" + ); + }); +} + +#[test] +fn a_thread_created_with_todays_behaviour_records_nothing_and_stays_that_way() { + run_async(async { + let root = tempfile::tempdir().expect("tempdir"); + let thread = thread_id("legacy-new"); + assert_eq!( + turn_and_count_records(root.path(), &thread, ToolSearchConfig::default()).await, + 0 + ); + // The config changes afterwards; the thread is not pinned to it. + assert_eq!( + turn_and_count_records(root.path(), &thread, no_promotion()).await, + 0 + ); + }); +} diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rs index e3bb84f29ae..f4dcd28867a 100644 --- a/crates/openhuman-core/src/agent/session_host/mod.rs +++ b/crates/openhuman-core/src/agent/session_host/mod.rs @@ -62,6 +62,8 @@ pub use types::{OpenHumanSessionHost, SessionHostBuilder, TurnOverrides}; // (`session::runtime`, `subagent_host`) so all provider call sites // share one tested implementation. +#[cfg(all(test, feature = "legacy-import"))] +mod discovery_pin_tests; #[cfg(test)] #[path = "imported_history_tests.rs"] mod imported_history_tests; diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/ensure.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/ensure.rs index f83e7e7483b..d6cac989c3e 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session/ensure.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/ensure.rs @@ -150,6 +150,31 @@ impl OpenHumanSessionHost { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .context_window = context_window; + // The thread's discovery options: chosen from the config + // by the turn that prepares its first prompt and recorded + // with it, read back from the transcript on every other. + let discovery = crate::agent::tinyagents::discovery::resolve( + &prelude.config.tool_search, + view.raw_history, + super::turn::prepare_prefix_for_turn( + new_session, + view.prefix_is_frozen, + ), + ); + tracing::debug!( + thread_id = ?prelude.thread_id, + options = ?discovery.effective, + recorded_now = discovery.record.is_some(), + "[tool-search] discovery options for this turn" + ); + options.run_context.config.discovery = discovery.effective.overrides(); + options + .run_context + .data + .session_sidecar + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .discovery_record = discovery.record; let original_input = request.input.clone(); let original_user_message = user_text_with_markers(&original_input); prelude.begin_user_effects(request, &options.run_context.data); diff --git a/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs b/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs index 47e8596dc32..bd982a417c4 100644 --- a/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs @@ -196,9 +196,20 @@ pub(super) fn build_host( model: Arc, native: bool, thread: &str, +) -> crate::agent::OpenHumanSessionHost { + build_host_with_config(root, model, native, thread, Default::default()) +} + +pub(super) fn build_host_with_config( + root: &Path, + model: Arc, + native: bool, + thread: &str, + config: crate::config::AgentConfig, ) -> crate::agent::OpenHumanSessionHost { let chat_model: Arc> = model; let builder = crate::agent::SessionHostBuilder::new() + .config(config) .with_session_history_locator(store_locator(root)) .chat_model(chat_model) .model_name("test/session-fixture".to_string()) diff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.md index 91289c9958d..a2d1039bb8d 100644 --- a/crates/openhuman-core/src/agent/tinyagents/README.md +++ b/crates/openhuman-core/src/agent/tinyagents/README.md @@ -60,7 +60,11 @@ that installed ranker together with `agent.tool_search` `ToolDiscoveryPolicy` the harness runs with for that turn. The slot is process-wide, like the other host registrations, because the credential a decision-model ranker needs belongs to the process's signed-in user rather -than to any one agent config. See +than to any one agent config. The four prompt-shaping options +(`promote_found_tools`, `compact_search_results`, `collapse_search_results`, +`repair_tool_call_wrapper`) are the exception: `discovery/pin.rs` chooses them +per session, records them on a new thread's first transcript row and reads them +back on resume, so a thread keeps the behaviour it started with. See [the Jev page](../../../../../docs/gitbooks/en/developing/jev.md) for the ranking mechanism and its measured accuracy against plain BM25. diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/discovery_tests.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/discovery_tests.rs index 628316eed65..55fd6cbb199 100644 --- a/crates/openhuman-core/src/agent/tinyagents/discovery/discovery_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/discovery/discovery_tests.rs @@ -25,6 +25,60 @@ fn default_policy_is_jev_with_no_ranker_and_top_three() { assert!(policy.enabled); } +#[test] +fn an_agent_with_no_new_keys_runs_with_todays_policy() { + let _g = guard(); + apply_tool_search_config(&ToolSearchConfig::default()); + let policy = discovery_policy(); + assert!(policy.promote_found_tools); + assert!(!policy.compact_search_results); + assert!(!policy.collapse_search_results); + assert!(policy.repair_tool_call_wrapper); + assert_eq!(policy.max_limit, 20); +} + +#[test] +fn each_tool_search_key_maps_onto_the_harness_policy() { + let _g = guard(); + apply_tool_search_config(&ToolSearchConfig { + top_k: 9, + max_limit: 5, + promote_found_tools: false, + compact_search_results: true, + collapse_search_results: true, + repair_tool_call_wrapper: false, + ..ToolSearchConfig::default() + }); + let policy = discovery_policy(); + assert!(!policy.promote_found_tools); + assert!(policy.compact_search_results); + assert!(policy.collapse_search_results); + assert!(!policy.repair_tool_call_wrapper); + assert_eq!(policy.max_limit, 5); + assert_eq!(policy.default_limit, 5, "top_k is clamped to max_limit"); + apply_tool_search_config(&ToolSearchConfig::default()); +} + +#[test] +fn tool_search_keys_read_from_toml_and_default_when_absent() { + let absent: ToolSearchConfig = toml::from_str("top_k = 4").expect("parses"); + assert_eq!( + absent, + ToolSearchConfig { + top_k: 4, + ..ToolSearchConfig::default() + } + ); + let set: ToolSearchConfig = toml::from_str( + "max_limit = 8\npromote_found_tools = false\ncompact_search_results = true\n\ + collapse_search_results = true\nrepair_tool_call_wrapper = false", + ) + .expect("parses"); + assert_eq!(set.max_limit, 8); + assert!(!set.promote_found_tools && !set.repair_tool_call_wrapper); + assert!(set.compact_search_results && set.collapse_search_results); +} + #[test] fn settings_select_the_mode_and_clamp_top_k() { let _g = guard(); diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs index 0af7d7278f7..8ccfdb1e8ee 100644 --- a/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs +++ b/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs @@ -108,7 +108,14 @@ pub(crate) fn discovery_policy() -> ToolDiscoveryPolicy { // prompt's Connected Integrations / MCP sections already name what can be // searched for; the description keeps only the count. policy.manifest_token_budget = 0; + policy.max_limit = settings.max_limit.max(1); policy.default_limit = settings.top_k.clamp(1, policy.max_limit); + // The process-wide defaults for a run that has no session behind it. A + // session turn overrides all four per run with what its thread recorded. + policy.promote_found_tools = settings.promote_found_tools; + policy.compact_search_results = settings.compact_search_results; + policy.collapse_search_results = settings.collapse_search_results; + policy.repair_tool_call_wrapper = settings.repair_tool_call_wrapper; let mode = match settings.ranker.trim().to_ascii_lowercase().as_str() { "auto" | "jev" | "ranker" => DiscoveryRankMode::Ranker, "bm25" | "lexical" => DiscoveryRankMode::Bm25, @@ -234,6 +241,9 @@ impl ToolRanker for OverlapRanker { } mod embedding_ranker; +mod pin; + +pub use pin::{resolve, DiscoveryOptions, ResolvedDiscovery, DISCOVERY_METADATA_KEY}; pub use embedding_ranker::{ embedding_provider_is_usable, embedding_tool_ranker, embedding_tool_ranker_in, diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs new file mode 100644 index 00000000000..9504493d9fe --- /dev/null +++ b/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs @@ -0,0 +1,161 @@ +//! The discovery options a thread starts with, and keeps. +//! +//! Four `tool_search` options change what a thread's prompt looks like: +//! whether found tools join the request's `tools` list, whether a result is +//! printed on one line, whether a used result is collapsed afterwards, and +//! whether a `tool_call` wrapper is repaired. Switching one under a thread +//! that is already running changes the bytes of every later prompt (the +//! provider's cached prefix) and what the model has learned to imitate, so a +//! session decides them once, when it creates the thread, and records them on +//! the thread's first transcript row. A resumed thread reads them back; the +//! config and the embedder's options only choose them for the next thread. +//! +//! A thread that records nothing (every thread written before this existed, +//! and any thread created with today's behaviour) resolves to +//! [`DiscoveryOptions::TODAY`], the harness defaults, whatever the config says +//! now. +//! +//! The options reach the harness per run as +//! [`DiscoveryOverrides`](tinyagents_harness::tool::discover::DiscoveryOverrides) +//! on `RunConfig::discovery`, every field set, so the process-wide policy +//! never leaks into a session turn. + +use serde::{Deserialize, Serialize}; +use tinyagents_harness::tool::discover::DiscoveryOverrides; +use tinyagents_session::transcript::TranscriptMessage; + +use crate::config::schema::ToolSearchConfig; + +/// Key under a transcript row's `extra_metadata` that holds the recorded +/// options. +pub const DISCOVERY_METADATA_KEY: &str = "tool_discovery"; + +/// The prompt-shaping `tool_search` options of one thread. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct DiscoveryOptions { + /// A successful search adds its matches to the request's `tools` list. + pub promote_found_tools: bool, + /// A search result's JSON is printed on one line. + pub compact_search_results: bool, + /// A search result is rewritten, once its run ends, to the schemas of the + /// tools the run called. + pub collapse_search_results: bool, + /// A call buried in a `tool_call`-style wrapper is retargeted at the real + /// tool it names. + pub repair_tool_call_wrapper: bool, +} + +impl DiscoveryOptions { + /// Today's behaviour: the harness defaults, and what a thread that + /// recorded nothing has always run with. + pub const TODAY: Self = Self { + promote_found_tools: true, + compact_search_results: false, + collapse_search_results: false, + repair_tool_call_wrapper: true, + }; + + /// The options `[agent].tool_search` asks new threads to start with. + pub fn from_config(config: &ToolSearchConfig) -> Self { + Self { + promote_found_tools: config.promote_found_tools, + compact_search_results: config.compact_search_results, + collapse_search_results: config.collapse_search_results, + repair_tool_call_wrapper: config.repair_tool_call_wrapper, + } + } + + /// Writes these options into `config`, where a session reads them from. + pub fn apply_to(&self, config: &mut ToolSearchConfig) { + config.promote_found_tools = self.promote_found_tools; + config.compact_search_results = self.compact_search_results; + config.collapse_search_results = self.collapse_search_results; + config.repair_tool_call_wrapper = self.repair_tool_call_wrapper; + } + + /// The per-run overrides that make the harness use exactly these options. + pub fn overrides(&self) -> DiscoveryOverrides { + DiscoveryOverrides { + promote_found_tools: Some(self.promote_found_tools), + compact_search_results: Some(self.compact_search_results), + collapse_search_results: Some(self.collapse_search_results), + repair_tool_call_wrapper: Some(self.repair_tool_call_wrapper), + } + } + + /// The options a thread recorded on its transcript `rows`, if any. + pub fn recorded_in(rows: &[TranscriptMessage]) -> Option { + rows.iter() + .filter_map(|row| row.extra_metadata.as_ref()) + .find_map(|metadata| metadata.get(DISCOVERY_METADATA_KEY)) + .and_then(|value| serde_json::from_value(value.clone()).ok()) + } + + /// Records these options on the first fresh row of a transcript being + /// written, returning whether one was found. A row already in the + /// transcript is never touched: rewriting it would make the commit open a + /// new generation instead of extending the thread. + pub fn record_on(&self, rows: &mut [TranscriptMessage], fresh: &[bool]) -> bool { + let Some(index) = fresh.iter().position(|is_fresh| *is_fresh) else { + return false; + }; + let Some(row) = rows.get_mut(index) else { + return false; + }; + let value = serde_json::to_value(self).expect("plain booleans serialize"); + match row + .extra_metadata + .get_or_insert_with(|| serde_json::Value::Object(serde_json::Map::new())) + { + serde_json::Value::Object(map) => { + map.insert(DISCOVERY_METADATA_KEY.to_string(), value); + true + } + _ => false, + } + } +} + +impl Default for DiscoveryOptions { + fn default() -> Self { + Self::TODAY + } +} + +/// What a turn runs with, and what it must write down. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ResolvedDiscovery { + /// The options this turn runs with. + pub effective: DiscoveryOptions, + /// The options to record on the thread, set only for the turn that starts + /// it and only when they differ from [`DiscoveryOptions::TODAY`] (a thread + /// that records nothing already means today's behaviour). + pub record: Option, +} + +/// Decides a session turn's options. +/// +/// `generation_start` is true for the turn that prepares the thread's first +/// prompt: it takes the options `config` asks for and records them. Every +/// other turn reads what `rows` recorded, or [`DiscoveryOptions::TODAY`]. +pub fn resolve( + config: &ToolSearchConfig, + rows: &[TranscriptMessage], + generation_start: bool, +) -> ResolvedDiscovery { + if generation_start { + let effective = DiscoveryOptions::from_config(config); + return ResolvedDiscovery { + effective, + record: (effective != DiscoveryOptions::TODAY).then_some(effective), + }; + } + ResolvedDiscovery { + effective: DiscoveryOptions::recorded_in(rows).unwrap_or(DiscoveryOptions::TODAY), + record: None, + } +} + +#[cfg(test)] +#[path = "pin_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/pin_tests.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/pin_tests.rs new file mode 100644 index 00000000000..fd2f73a69ba --- /dev/null +++ b/crates/openhuman-core/src/agent/tinyagents/discovery/pin_tests.rs @@ -0,0 +1,116 @@ +use tinyagents_harness::tool::discover::ToolDiscoveryPolicy; + +use super::*; + +fn config(promote: bool, compact: bool, collapse: bool, repair: bool) -> ToolSearchConfig { + ToolSearchConfig { + promote_found_tools: promote, + compact_search_results: compact, + collapse_search_results: collapse, + repair_tool_call_wrapper: repair, + ..ToolSearchConfig::default() + } +} + +#[test] +fn today_is_the_harness_default_and_the_config_default() { + let policy = ToolDiscoveryPolicy::default(); + assert_eq!( + DiscoveryOptions::TODAY.overrides(), + DiscoveryOverrides { + promote_found_tools: Some(policy.promote_found_tools), + compact_search_results: Some(policy.compact_search_results), + collapse_search_results: Some(policy.collapse_search_results), + repair_tool_call_wrapper: Some(policy.repair_tool_call_wrapper), + } + ); + assert_eq!( + DiscoveryOptions::from_config(&ToolSearchConfig::default()), + DiscoveryOptions::TODAY + ); +} + +#[test] +fn config_options_map_onto_the_harness_policy_and_back() { + let wanted = DiscoveryOptions { + promote_found_tools: false, + compact_search_results: true, + collapse_search_results: true, + repair_tool_call_wrapper: false, + }; + let mut settings = ToolSearchConfig::default(); + wanted.apply_to(&mut settings); + assert_eq!(settings, config(false, true, true, false)); + assert_eq!(DiscoveryOptions::from_config(&settings), wanted); + + let policy = ToolDiscoveryPolicy::default().with_overrides(&wanted.overrides()); + assert!(!policy.promote_found_tools); + assert!(policy.compact_search_results); + assert!(policy.collapse_search_results); + assert!(!policy.repair_tool_call_wrapper); +} + +#[test] +fn a_new_thread_takes_the_config_and_records_only_a_change_from_today() { + let changed = resolve(&config(false, false, true, true), &[], true); + assert_eq!( + changed.effective, + DiscoveryOptions::from_config(&config(false, false, true, true)) + ); + assert_eq!(changed.record, Some(changed.effective)); + + let unchanged = resolve(&ToolSearchConfig::default(), &[], true); + assert_eq!(unchanged.effective, DiscoveryOptions::TODAY); + assert_eq!(unchanged.record, None); +} + +#[test] +fn a_resumed_thread_keeps_what_it_recorded_whatever_the_config_says_now() { + let started_with = DiscoveryOptions { + promote_found_tools: false, + collapse_search_results: true, + ..DiscoveryOptions::TODAY + }; + let mut rows = vec![ + TranscriptMessage::system("prompt"), + TranscriptMessage::new("user", "hi"), + ]; + assert!(started_with.record_on(&mut rows, &[true, true])); + + // A later config that asks for something else changes nothing. + let now = config(true, true, false, false); + let resumed = resolve(&now, &rows, false); + assert_eq!(resumed.effective, started_with); + assert_eq!(resumed.record, None); +} + +#[test] +fn a_thread_that_recorded_nothing_keeps_todays_behaviour_whatever_the_config_says() { + let rows = vec![TranscriptMessage::system("prompt")]; + let resumed = resolve(&config(false, true, true, false), &rows, false); + assert_eq!(resumed.effective, DiscoveryOptions::TODAY); + assert_eq!(resumed.record, None); +} + +#[test] +fn recording_touches_only_the_first_fresh_row_and_survives_serialization() { + let options = DiscoveryOptions { + promote_found_tools: false, + ..DiscoveryOptions::TODAY + }; + let mut rows = vec![ + TranscriptMessage::new("user", "imported"), + TranscriptMessage::system("prompt"), + TranscriptMessage::new("user", "hi"), + ]; + let before = rows[0].clone(); + assert!(options.record_on(&mut rows, &[false, true, true])); + assert_eq!(rows[0], before, "a row already stored is never rewritten"); + assert!(rows[2].extra_metadata.is_none()); + + let stored: Vec = + serde_json::from_str(&serde_json::to_string(&rows).unwrap()).unwrap(); + assert_eq!(DiscoveryOptions::recorded_in(&stored), Some(options)); + + assert!(!options.record_on(&mut rows, &[false, false, false])); +} diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs index 24f6325160b..5bef46f6606 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs @@ -148,6 +148,11 @@ pub(crate) struct SessionTurnSidecar { pub stop: Option, /// Deferred native terminal finalized after transcript durability. pub deferred_terminal: Option, + /// The discovery options this turn starts its thread with, to be recorded + /// on the first row the commit writes. Set by the turn that prepares the + /// thread's first prompt and only when they differ from today's + /// behaviour; see `tinyagents::discovery::DiscoveryOptions`. + pub discovery_record: Option, } #[path = "dispatch_control.rs"] diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection/tool_calls.rs b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection/tool_calls.rs index c65235e28b5..3cba98cacd5 100644 --- a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection/tool_calls.rs +++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection/tool_calls.rs @@ -67,10 +67,13 @@ impl OpenhumanEventBridge { input, output, error, - // `started_at_ms`/`duration_ms`/`output_bytes` ride the crate - // event, but the bridge reads the outcome-capture side channel - // below: it also carries the classified failure and the tool's - // structured metadata, which the crate event does not. + input_bytes, + output_bytes, + // `started_at_ms`/`duration_ms` ride the crate event, but the + // bridge reads the outcome-capture side channel below: it also + // carries the classified failure and the tool's structured + // metadata, which the crate event does not. The two sizes are + // logged with the projection, whatever payload capture is on. .. } = event { @@ -168,6 +171,8 @@ impl OpenhumanEventBridge { success, elapsed_ms, has_structured = structured.is_some(), + input_bytes = ?input_bytes, + output_bytes = ?output_bytes, "[tool-presentation] projecting ToolCallCompleted with resolved label/detail" ); match &self.scope { diff --git a/crates/openhuman-core/src/config/schema/agent.rs b/crates/openhuman-core/src/config/schema/agent.rs index a6870b4b95a..d1312549748 100644 --- a/crates/openhuman-core/src/config/schema/agent.rs +++ b/crates/openhuman-core/src/config/schema/agent.rs @@ -327,6 +327,29 @@ pub struct ToolSearchConfig { /// Three: enough for the model to choose, few enough that the schemas /// returned do not undo the saving deferral made. pub top_k: usize, + /// Most matches a single search may return, however many the model asks + /// for. `top_k` is clamped to it. Defaults to 20, the harness's own cap. + pub max_limit: usize, + /// Whether a successful search adds the matched tools to the request's + /// `tools` list for later calls (`true`, today's behaviour) or leaves the + /// list as it was, so the provider's cached prefix survives a search and + /// the model calls a found tool by name from the schema in the result. + /// + /// This and the three options below shape a thread's prompt, so a session + /// pins their values on its thread when it creates it and a resumed + /// thread keeps them whatever this file says later; see + /// `agent::tinyagents::discovery::DiscoveryPin`. + pub promote_found_tools: bool, + /// Render a search result's JSON on one line instead of pretty-printed. + /// Same content, fewer bytes. Defaults to `false`. + pub compact_search_results: bool, + /// Once the run that wrote a search result ends, rewrite it to the query + /// plus the schemas of the matched tools the run called. Defaults to + /// `false`. + pub collapse_search_results: bool, + /// Retarget a call a model buries inside a pseudo `tool_call` / `call_tool` + /// wrapper at the real tool it names. Defaults to `true`. + pub repair_tool_call_wrapper: bool, } impl Default for ToolSearchConfig { @@ -336,6 +359,11 @@ impl Default for ToolSearchConfig { jev_route: "auto".into(), jev_base_url: None, top_k: 3, + max_limit: 20, + promote_found_tools: true, + compact_search_results: false, + collapse_search_results: false, + repair_tool_call_wrapper: true, } } } diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay.rs b/crates/openhuman-core/src/config/schema/load/env_overlay.rs index edcfca9e541..001907232fd 100644 --- a/crates/openhuman-core/src/config/schema/load/env_overlay.rs +++ b/crates/openhuman-core/src/config/schema/load/env_overlay.rs @@ -232,6 +232,65 @@ impl Config { } } + // One-launch overrides of the `tool_search` discovery options. The + // four booleans pin on each thread a session creates (see + // `agent::tinyagents::discovery::DiscoveryPin`), so a changed value + // reaches new threads only. + type Flag = fn(&mut crate::config::schema::ToolSearchConfig) -> &mut bool; + let flags: [(&str, &str, Flag); 4] = [ + ( + "OPENHUMAN_TOOL_SEARCH_PROMOTE_FOUND_TOOLS", + "agent.tool_search.promote_found_tools", + |c| &mut c.promote_found_tools, + ), + ( + "OPENHUMAN_TOOL_SEARCH_COMPACT_SEARCH_RESULTS", + "agent.tool_search.compact_search_results", + |c| &mut c.compact_search_results, + ), + ( + "OPENHUMAN_TOOL_SEARCH_COLLAPSE_SEARCH_RESULTS", + "agent.tool_search.collapse_search_results", + |c| &mut c.collapse_search_results, + ), + ( + "OPENHUMAN_TOOL_SEARCH_REPAIR_TOOL_CALL_WRAPPER", + "agent.tool_search.repair_tool_call_wrapper", + |c| &mut c.repair_tool_call_wrapper, + ), + ]; + for (var, path, slot) in flags { + let Some(raw) = env.get(var) else { continue }; + match classify_shell_hide_window(&raw) { + ShellHideWindowParse::Set(value) => { + *slot(&mut self.agent.tool_search) = value; + tracing::debug!(var, value, "overrides {path}"); + self.record_env_override(env, path, &[var]); + } + ShellHideWindowParse::Unset => {} + ShellHideWindowParse::Unrecognized => { + tracing::warn!(var, "ignoring a value that is not a boolean"); + } + } + } + if let Some(raw) = env.get("OPENHUMAN_TOOL_SEARCH_MAX_LIMIT") { + match raw.trim().parse::() { + Ok(limit) if limit > 0 => { + self.agent.tool_search.max_limit = limit; + self.record_env_override( + env, + "agent.tool_search.max_limit", + &["OPENHUMAN_TOOL_SEARCH_MAX_LIMIT"], + ); + } + _ if raw.trim().is_empty() => {} + _ => tracing::warn!( + var = "OPENHUMAN_TOOL_SEARCH_MAX_LIMIT", + "ignoring a value that is not a positive integer" + ), + } + } + if let Some(workspace) = env.get("OPENHUMAN_WORKSPACE") { if !workspace.is_empty() { let (_, workspace_dir) = diff --git a/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs b/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs index ab91286d2cf..c1abf603472 100644 --- a/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs +++ b/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs @@ -481,6 +481,39 @@ fn env_overlay_jev_route_and_base_url_override_tool_search_when_non_blank() { ); } +#[test] +fn env_overlay_sets_the_tool_search_discovery_options() { + let mut cfg = Config::default(); + let today = cfg.agent.tool_search.clone(); + assert!(today.promote_found_tools && today.repair_tool_call_wrapper); + assert!(!today.compact_search_results && !today.collapse_search_results); + assert_eq!(today.max_limit, 20); + + cfg.apply_env_overlay_with( + &HashMapEnv::new() + .with("OPENHUMAN_TOOL_SEARCH_PROMOTE_FOUND_TOOLS", "off") + .with("OPENHUMAN_TOOL_SEARCH_COMPACT_SEARCH_RESULTS", " TRUE ") + .with("OPENHUMAN_TOOL_SEARCH_COLLAPSE_SEARCH_RESULTS", "1") + .with("OPENHUMAN_TOOL_SEARCH_REPAIR_TOOL_CALL_WRAPPER", "no") + .with("OPENHUMAN_TOOL_SEARCH_MAX_LIMIT", "5"), + ); + let set = &cfg.agent.tool_search; + assert!(!set.promote_found_tools && !set.repair_tool_call_wrapper); + assert!(set.compact_search_results && set.collapse_search_results); + assert_eq!(set.max_limit, 5); + + // Blank or unusable values leave the configured choice alone. + cfg.apply_env_overlay_with( + &HashMapEnv::new() + .with("OPENHUMAN_TOOL_SEARCH_PROMOTE_FOUND_TOOLS", " ") + .with("OPENHUMAN_TOOL_SEARCH_COMPACT_SEARCH_RESULTS", "maybe") + .with("OPENHUMAN_TOOL_SEARCH_MAX_LIMIT", "0"), + ); + assert!(!cfg.agent.tool_search.promote_found_tools); + assert!(cfg.agent.tool_search.compact_search_results); + assert_eq!(cfg.agent.tool_search.max_limit, 5); +} + /// Local model tier presets were removed: OpenHuman no longer picks models by /// RAM tier. A stale `OPENHUMAN_LOCAL_AI_TIER` in the environment must be /// ignored rather than rewriting the user's configured local models. diff --git a/crates/openhuman-embed/OBSERVERS.md b/crates/openhuman-embed/OBSERVERS.md index 48c0a0a5341..3be6ba09547 100644 --- a/crates/openhuman-embed/OBSERVERS.md +++ b/crates/openhuman-embed/OBSERVERS.md @@ -5,6 +5,9 @@ and a terminal `TurnTrace`. Callbacks run synchronously: enqueue export work in the host and return promptly. Model observations contain the answering model, finish reason, duration, and provider-reported usage/cost. Tool observations pair starts and completions by call ID and report failure without an error body. +A completed tool observation also carries `input_bytes` (the serialized +arguments) and `output_bytes` (the result text the model is shown) whatever the +capture mode, so tool cost can be attributed without capturing content. The terminal trace reports dispatch success, latency and final metadata. `TraceContent::MetadataOnly` is the default. It excludes model messages, replies, diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rs index 0b88ff74e0d..3bf43a04bd7 100644 --- a/crates/openhuman-embed/src/agent/build.rs +++ b/crates/openhuman-embed/src/agent/build.rs @@ -183,6 +183,10 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result openhuman_core::config::schema::ToolSearchConfig { + let tokio = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES) + .enable_all() + .build() + .unwrap(); + let test = tokio.spawn(async move { + let dir = tempfile::tempdir().unwrap(); + let config = openhuman_core::config::Config { + config_path: dir.path().join("config.toml"), + workspace_dir: dir.path().join("workspace"), + action_dir: dir.path().join("action"), + ..openhuman_core::config::Config::default() + }; + config.save().await.unwrap(); + let runtime = crate::runtime::RuntimeBuilder::new() + .config(config) + .services(openhuman_core::core::runtime::ServiceSet::none()) + .build() + .await + .expect("runtime"); + let agent = runtime.agent(spec).expect("agent builds"); + let keys = agent.inner.config.agent.tool_search.clone(); + drop(agent); + drop(runtime); + keys + }); + tokio.block_on(test).unwrap() +} + +#[test] +fn an_agent_with_promotion_off_and_collapse_on_hands_both_to_the_session_config() { + let keys = built_discovery_keys(crate::AgentSpec::new("discovery-set").tool_discovery( + crate::ToolDiscoveryOptions { + promote_found_tools: false, + collapse_search_results: true, + ..crate::ToolDiscoveryOptions::TODAY + }, + )); + assert!(!keys.promote_found_tools); + assert!(keys.collapse_search_results); + assert!(!keys.compact_search_results); + assert!(keys.repair_tool_call_wrapper); +} + +#[test] +fn an_agent_with_no_discovery_options_behaves_as_before() { + let keys = built_discovery_keys(crate::AgentSpec::new("discovery-unset")); + assert!(keys.promote_found_tools); + assert!(!keys.compact_search_results); + assert!(!keys.collapse_search_results); + assert!(keys.repair_tool_call_wrapper); + assert_eq!(keys.max_limit, 20); +} diff --git a/crates/openhuman-embed/src/agent/spec.rs b/crates/openhuman-embed/src/agent/spec.rs index 755dbae604f..874d94233d4 100644 --- a/crates/openhuman-embed/src/agent/spec.rs +++ b/crates/openhuman-embed/src/agent/spec.rs @@ -63,6 +63,7 @@ pub struct AgentSpec { tinyagents_harness::cost::TurnCost, >, memory: Option, + tool_discovery: Option, subagents: Vec<(String, AgentDefinitionSpec)>, } @@ -192,6 +193,7 @@ impl AgentSpec { host_tools: None, hooks: Default::default(), memory: None, + tool_discovery: None, subagents: Vec::new(), } } @@ -356,6 +358,23 @@ impl AgentSpec { self } + /// The `tool_search` options this agent's **new** threads start with: + /// whether found tools join the request's `tools` list, whether results + /// print on one line, whether a used result is collapsed afterwards, and + /// whether a `tool_call` wrapper is repaired. + /// + /// Without this the options come from the config's `[agent.tool_search]`, + /// which defaults to today's behaviour. They are recorded on each thread + /// with its first prompt and read back when it resumes, so changing them + /// here (or in the config) never alters a thread that already exists. + /// [`Turn::tool_discovery`](crate::Turn::tool_discovery) overrides them + /// for the thread one turn creates. + #[must_use] + pub fn tool_discovery(mut self, options: crate::ToolDiscoveryOptions) -> Self { + self.tool_discovery = Some(options); + self + } + /// Binds the agent's memory: the memory agent id its turns are logged /// under and, optionally, its layout root. See [`MemoryBinding`]. #[must_use] @@ -532,6 +551,7 @@ impl AgentSpec { host_tools: self.host_tools, hooks: self.hooks, memory: self.memory, + tool_discovery: self.tool_discovery, subagents: self.subagents, } } @@ -564,6 +584,7 @@ pub(crate) struct AgentSpecParts { pub(crate) trusted: Vec<(String, TrustedAccess)>, pub(crate) composio: Option, pub(crate) config_fn: Option, + pub(crate) tool_discovery: Option, pub(crate) host_tools: Option, pub(crate) hooks: tinyagents_hooks::scope::HookScope< openhuman_core::agent::tinyagents::host::OpenHumanRunContext, diff --git a/crates/openhuman-embed/src/agent/spec_tests.rs b/crates/openhuman-embed/src/agent/spec_tests.rs index e82fe429c39..196d229e843 100644 --- a/crates/openhuman-embed/src/agent/spec_tests.rs +++ b/crates/openhuman-embed/src/agent/spec_tests.rs @@ -81,3 +81,15 @@ fn a_memory_binding_bounds_the_memory_block_only_when_asked() { Some(std::time::Duration::from_millis(300)) ); } + +#[test] +fn an_agent_spec_carries_tool_discovery_options_only_when_set() { + assert_eq!(AgentSpec::new("alpha").into_parts().tool_discovery, None); + let wanted = crate::ToolDiscoveryOptions { + promote_found_tools: false, + collapse_search_results: true, + ..crate::ToolDiscoveryOptions::TODAY + }; + let parts = AgentSpec::new("alpha").tool_discovery(wanted).into_parts(); + assert_eq!(parts.tool_discovery, Some(wanted)); +} diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs index 008c61c8798..b4030d7cbb2 100644 --- a/crates/openhuman-embed/src/lib.rs +++ b/crates/openhuman-embed/src/lib.rs @@ -76,6 +76,7 @@ pub use openhuman_core::core::runtime::turn_origin::{AgentTurnOrigin, TrustedAut pub fn current_turn_origin() -> Option { openhuman_core::core::runtime::CoreContext::current_turn_origin() } +pub use openhuman_core::agent::tinyagents::discovery::DiscoveryOptions as ToolDiscoveryOptions; pub use openhuman_core::config::ComposioHostCredential; pub use openhuman_core::config::Config as RuntimeConfig; pub use openhuman_core::config::{SearchHostCredential, UnknownKeyedSearchProvider}; diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs index f23342effee..8e7c32bfb1e 100644 --- a/crates/openhuman-embed/src/turn.rs +++ b/crates/openhuman-embed/src/turn.rs @@ -105,6 +105,7 @@ pub struct Turn { >, tools: Option, tool_env: Option>>, + tool_discovery: Option, } impl Turn { @@ -138,6 +139,7 @@ impl Turn { observer: None, trace_content: crate::observe::TraceContent::MetadataOnly, hooks: Default::default(), + tool_discovery: None, tools: None, tool_env: None, } @@ -422,6 +424,21 @@ impl Turn { self } + /// The `tool_search` options for the thread this turn creates. + /// + /// They take the place of the agent's own + /// ([`AgentSpec::tool_discovery`](crate::AgentSpec::tool_discovery)) and + /// the config's `[agent.tool_search]` for a **new** session id, and are + /// recorded on the thread with its first prompt. A turn on an existing + /// session id ignores them: the thread keeps the options it started with, + /// and a thread created before any were recorded keeps today's behaviour. + /// That is how a host rolls a change out to new threads only. + #[must_use] + pub fn tool_discovery(mut self, options: crate::ToolDiscoveryOptions) -> Self { + self.tool_discovery = Some(options); + self + } + /// Pin this turn to a model id. pub fn model(mut self, model: impl Into) -> Self { self.request.model_override = Some(model.into()); @@ -563,6 +580,9 @@ struct AgentTurnOptions { Option>, untrusted_input: bool, attachments: Vec, + /// The `tool_search` options a new thread starts with; see + /// [`Turn::tool_discovery`]. + tool_discovery: Option, /// The explicit per-turn values the core honours: live progress and the /// host environment (budget, depth, cancellation, hooks, tool-belt authority). chat_env: openhuman_core::agent_runs::agent_chat::AgentChatEnv, @@ -621,6 +641,7 @@ async fn dispatch( } let ctx = std::sync::Arc::clone(rt.context()); let chat_env = options.chat_env; + let tool_discovery = options.tool_discovery; let dispatch = openhuman_core::core::runtime::DispatchCtx::new(std::sync::Arc::clone(&ctx)); let turn: futures_box::BoxFuture<'_, Result> = @@ -632,6 +653,9 @@ async fn dispatch( .load_config() .await .map_err(|raw| CoreError::from_rpc_string(AGENT_CHAT, raw))?; + if let Some(discovery) = tool_discovery { + discovery.apply_to(&mut config.agent.tool_search); + } let target = match request.agent_id.as_deref().map(str::trim) { Some(id) if !id.is_empty() => AgentChatTarget::AgentId(id), _ => AgentChatTarget::Orchestrator, @@ -682,6 +706,9 @@ async fn dispatch( agent_chat_reply_for_controlled, AgentChatTarget, }; let mut config = inner.config.clone(); + if let Some(discovery) = options.tool_discovery { + discovery.apply_to(&mut config.agent.tool_search); + } let route = inference_route(&request); let host = options.tools.or_else(|| inner.composed_host_tools()); let target = AgentChatTarget::Definition { diff --git a/crates/openhuman-embed/src/turn_control.rs b/crates/openhuman-embed/src/turn_control.rs index af14bc6026d..568a03478b3 100644 --- a/crates/openhuman-embed/src/turn_control.rs +++ b/crates/openhuman-embed/src/turn_control.rs @@ -409,6 +409,7 @@ impl Turn { untrusted_input: self.untrusted_input, tools: self.tools.take(), attachments: std::mem::take(&mut self.attachments), + tool_discovery: self.tool_discovery.take(), }; let dispatch = dispatch(self.target, self.request, self.seed.take(), usage, options); diff --git a/crates/openhuman-embed/tests/observed_turns.rs b/crates/openhuman-embed/tests/observed_turns.rs index 226012af33f..229937b4393 100644 --- a/crates/openhuman-embed/tests/observed_turns.rs +++ b/crates/openhuman-embed/tests/observed_turns.rs @@ -183,6 +183,10 @@ fn model_and_tool_observations_capture_payloads_only_with_consent() { let tools: Vec<_> = events.iter().filter(|event| matches!(event,TurnObservation::Tool {..})).collect(); assert_eq!(tools.len(),2); assert!(matches!(tools[1],TurnObservation::Tool {failed:Some(false),..})); + // Sizes ride the completion whatever the capture consent, so a + // host can attribute tool cost without capturing any content. + assert!(matches!(tools[0],TurnObservation::Tool {input_bytes:None,output_bytes:None,..})); + assert!(matches!(tools[1],TurnObservation::Tool {input_bytes:Some(arguments),output_bytes:Some(24),..} if *arguments > 0)); let debug = format!("{events:?}"); assert_eq!(debug.contains("SECRET-PATH"),capture==TraceContent::Include); assert_eq!(debug.contains("SECRET-PROMPT"),capture==TraceContent::Include); diff --git a/docs/gitbooks/en/developing/jev.md b/docs/gitbooks/en/developing/jev.md index a5cd46b4593..7fa18fc5d4a 100644 --- a/docs/gitbooks/en/developing/jev.md +++ b/docs/gitbooks/en/developing/jev.md @@ -84,6 +84,11 @@ ranker = "jev" # "jev" (default) | "auto" | "bm25" | "compare" jev_route = "auto" # "auto" (default) | "tinyhumans" | "typesafe" | "openrouter" # jev_base_url = "http://127.0.0.1:18080" # typesafe/openrouter origin override top_k = 3 +max_limit = 20 # most matches one search may return +promote_found_tools = true # found tools join the request's `tools` list +compact_search_results = false # print a result's JSON on one line +collapse_search_results = false # after the run, keep only the schemas it called +repair_tool_call_wrapper = true # retarget a call buried in a `tool_call` wrapper ``` - `ranker = "jev"`: use the installed decision-model ranker. It falls back to BM25 only when Jev fails or the process has no TinyHumans credential. @@ -94,6 +99,11 @@ top_k = 3 - `jev_base_url`: replaces the API origin of the `typesafe` and `openrouter` routes, for example a metering proxy or a mirror. Remote origins must be HTTPS. HTTP is accepted only for literal loopback IPs. Override per launch with `OPENHUMAN_JEV_BASE_URL`. - `top_k`: how many matches a search returns when the model does not ask for a number. The default is three, enough to choose from without returning so many schemas that deferring them loses its point. +- `max_limit`: the most matches a single search returns, however many the model asks for. `top_k` is clamped to it. Override per launch with `OPENHUMAN_TOOL_SEARCH_MAX_LIMIT`. +- `promote_found_tools`, `compact_search_results`, `collapse_search_results`, `repair_tool_call_wrapper`: how found tools reach the prompt and how their results are stored. The defaults are today's behaviour. Override per launch with `OPENHUMAN_TOOL_SEARCH_PROMOTE_FOUND_TOOLS`, `OPENHUMAN_TOOL_SEARCH_COMPACT_SEARCH_RESULTS`, `OPENHUMAN_TOOL_SEARCH_COLLAPSE_SEARCH_RESULTS` and `OPENHUMAN_TOOL_SEARCH_REPAIR_TOOL_CALL_WRAPPER` (`1/0`, `true/false`, `yes/no`, `on/off`). + +These four change the bytes of a thread's prompt (the provider's cached prefix), so a session does not apply them to a thread that is already running. The session that creates a thread takes the values in force then and, when they differ from today's behaviour, records them on the thread's first transcript row (`tool_discovery` in the row's `extra_metadata`). Every later turn reads the record back; a thread with no record keeps today's behaviour. Changing the config, or an embedder's options, therefore reaches new threads only. An embedder sets the options per agent with `AgentSpec::tool_discovery(ToolDiscoveryOptions)` and for the thread one turn creates with `Turn::tool_discovery(ToolDiscoveryOptions)`. + Without an embedding provider, or without a credential for the selected route, tool search falls back to BM25 automatically. `auto` and `jev` therefore cost nothing extra when no credential is set. A setup with no TinyHumans account needs an embedding provider that does not depend on one (for example `memory.embedding_provider = "custom:"`) and a TypeSafe or OpenRouter key. ## Running the benchmark From f76b2a9683dc5029211b12e243bcdc87d064eeeb Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sat, 7 Nov 2026 23:26:38 +0300 Subject: [PATCH 04/24] chore(deps): bump tinyagents and tinysearch to the epic-712 tool-tokens tip Co-authored-by: Medulla --- vendor/tinyagents | 2 +- vendor/tinysearch | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/vendor/tinyagents b/vendor/tinyagents index 3611644ff03..d8af36518c5 160000 --- a/vendor/tinyagents +++ b/vendor/tinyagents @@ -1 +1 @@ -Subproject commit 3611644ff03bc6a6dab69ebf13cb1622074becae +Subproject commit d8af36518c5d9618993cd4e3debc234f30e8d272 diff --git a/vendor/tinysearch b/vendor/tinysearch index bdb481577df..b99ebbb2b15 160000 --- a/vendor/tinysearch +++ b/vendor/tinysearch @@ -1 +1 @@ -Subproject commit bdb481577dff74f9475ce57db10e83c6e6a085b8 +Subproject commit b99ebbb2b159065cc62f20e94c045eef235f7bbe From fa2febbebe4cef0df2c6586e7fc00a763a9d8c97 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 00:03:47 +0300 Subject: [PATCH 05/24] fix(memory): apply the turn's route and model overrides when prewarming the memory block prewarm_memory_block built its session without the embedder's route and model, so a hosted-route-only embedder answered BACKEND_UNAVAILABLE. It now applies them through apply_turn_overrides, as compact_thread does. Co-authored-by: Medulla --- .../src/agent_runs/agent_chat/compact.rs | 14 +- .../agent_runs/agent_chat/compact_tests.rs | 121 ++++++++++++++++++ crates/openhuman-embed/src/agent/compact.rs | 18 ++- 3 files changed, 148 insertions(+), 5 deletions(-) create mode 100644 crates/openhuman-core/src/agent_runs/agent_chat/compact_tests.rs diff --git a/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs b/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs index 21f05b39066..6099f541229 100644 --- a/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs +++ b/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs @@ -51,7 +51,11 @@ pub fn compact_thread_for<'a>( } /// Render `thread_id`'s memory block now, on `target`'s session built as a -/// turn's is, for that thread's next generation start to take. See +/// turn's is, for that thread's next generation start to take. +/// +/// `model_override`, `temperature` and `route` are applied to `config` as +/// [`compact_thread_for`] applies them: an embedder on a hosted route has no +/// managed provider, so a session built without its route cannot be built. See /// [`OpenHumanSessionHost::prewarm_memory_block`] /// (crate::agent::OpenHumanSessionHost::prewarm_memory_block). /// @@ -63,8 +67,12 @@ pub fn prewarm_memory_block_for<'a>( config: &'a mut Config, target: AgentChatTarget<'a>, thread_id: &'a str, + model_override: Option, + temperature: Option, + route: Option, ) -> futures::future::BoxFuture<'a, anyhow::Result> { Box::pin(async move { + apply_turn_overrides(config, model_override, temperature, route); let thread_id = thread_id.trim(); if thread_id.is_empty() { anyhow::bail!("prewarm_memory_block needs a thread id"); @@ -77,3 +85,7 @@ pub fn prewarm_memory_block_for<'a>( Ok(session.prewarm_memory_block().await) }) } + +#[cfg(test)] +#[path = "compact_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/agent_runs/agent_chat/compact_tests.rs b/crates/openhuman-core/src/agent_runs/agent_chat/compact_tests.rs new file mode 100644 index 00000000000..d895b5b77bc --- /dev/null +++ b/crates/openhuman-core/src/agent_runs/agent_chat/compact_tests.rs @@ -0,0 +1,121 @@ +use super::*; +use crate::agent_registry::host_definition::MemoryBlock; +use crate::config::schema::EphemeralRoute; +use crate::memory::test_fixtures::bind_reference; +use tinymemory_api::{LearningKind, MemoryEngine, MemoryMeta, StoreItem}; + +const MODEL: &str = "turn-model"; + +/// A memory-block agent definition and a config whose memory holds one fact. +async fn memory_block_agent( + tmp: &tempfile::TempDir, +) -> ( + Config, + crate::agent_registry::host_definition::AgentDefinition, +) { + // Canonical, because the secrets store refuses a path through a symlink + // (macOS's temp directory is one). + let root = tmp.path().canonicalize().expect("canonical temp dir"); + let mut config = Config { + workspace_dir: root.join("workspace"), + action_dir: root.join("workspace"), + config_path: root.join("config.toml"), + ..Config::default() + }; + std::fs::create_dir_all(&config.workspace_dir).unwrap(); + config.secrets.encrypt = false; + // A signed-in app session, which any non-library host requires of a + // provider that is not the caller's own. + crate::credentials::api_key::store_api_key(&config, "test-session-key") + .await + .expect("store the session credential"); + let engine = bind_reference(&config); + let (_, identity) = crate::memory::lifecycle::current_agent_memory( + &config, + &tinymemory_tools::layout::identity::Identity::root(), + ) + .await + .expect("memory identity"); + engine + .store(StoreItem::learning( + "The user lives in Lisbon", + LearningKind::Fact, + 0.9, + MemoryMeta { + namespace: identity.layout.learnings().clone(), + ..MemoryMeta::default() + }, + )) + .await + .expect("stored"); + let mut definition = crate::agent::harness::test_support::test_main_def(); + definition.extensions.memory_block = Some(MemoryBlock { max_tokens: 500 }); + (config, definition) +} + +fn target( + definition: &crate::agent_registry::host_definition::AgentDefinition, +) -> AgentChatTarget<'_> { + AgentChatTarget::Definition { + definition, + host: None, + seed: None, + usage: None, + host_only: false, + untrusted_input: false, + shape: None, + observer: None, + attachments: &[], + } +} + +fn hosted_route() -> EphemeralRoute { + EphemeralRoute { + endpoint: "http://127.0.0.1:9/v1".into(), + api_key: "sk-test".into(), + ..EphemeralRoute::default() + } +} + +/// An embedder on a hosted route only has no managed provider to fall back +/// on: the prewarm must build its session with the turn's route and model, as +/// `compact_thread_for` does, or the build answers `BACKEND_UNAVAILABLE`. +#[tokio::test] +async fn prewarm_memory_block_uses_turn_overrides() { + let tmp = tempfile::tempdir().unwrap(); + let (mut config, definition) = memory_block_agent(&tmp).await; + + let prewarm = prewarm_memory_block_for( + &mut config, + target(&definition), + "thread-prewarm", + Some(MODEL.into()), + None, + Some(hosted_route()), + ) + .await + .expect("a session on the turn's route builds"); + + assert_eq!(prewarm, MemoryBlockPrewarm::Ready); +} + +/// Without the route the session cannot be built at all: the failure the +/// overrides above exist to avoid. +#[tokio::test] +async fn prewarm_memory_block_without_overrides_has_no_hosted_provider() { + let tmp = tempfile::tempdir().unwrap(); + let (mut config, definition) = memory_block_agent(&tmp).await; + + let error = prewarm_memory_block_for( + &mut config, + target(&definition), + "thread-prewarm", + None, + None, + None, + ) + .await + .expect_err("no hosted provider is registered"); + + assert!(error.to_string().contains("BACKEND_UNAVAILABLE"), "{error}"); +} diff --git a/crates/openhuman-embed/src/agent/compact.rs b/crates/openhuman-embed/src/agent/compact.rs index 1aac03f494b..e82cf3fb303 100644 --- a/crates/openhuman-embed/src/agent/compact.rs +++ b/crates/openhuman-embed/src/agent/compact.rs @@ -103,10 +103,11 @@ impl Agent { /// /// Call it when a message arrives and its turn is still some way off. The /// session is built as [`Turn::session`](crate::Turn::session) builds a - /// turn's, and the block is kept (for up to an hour, taken once) under the - /// agent's memory identity. Nothing is read when one already waits, and - /// an agent without a memory block does nothing - /// ([`MemoryBlockPrewarm::Unavailable`]). A failed read is + /// turn's, with the agent's provider route and model, and the block is + /// kept (for up to an hour, taken once) under the agent's memory + /// identity. Nothing is read when one already waits, and an agent without + /// a memory block does nothing ([`MemoryBlockPrewarm::Unavailable`]). A + /// failed read is /// [`MemoryBlockPrewarm::Failed`], never an error: the turn renders for /// itself. /// @@ -126,6 +127,12 @@ impl Agent { } .into()); } + // The provider route and model a turn on this agent runs with. + let turn = self.turn(String::new()); + let request = turn.request(); + let route = crate::turn::inference_route(request); + let model_override = request.model_override.clone(); + let temperature = request.temperature; let ctx = inner.ctx.clone(); let runtime = inner.runtime.clone(); let thread_id = thread_id.to_owned(); @@ -149,6 +156,9 @@ impl Agent { &mut config, target, &thread_id, + model_override, + temperature, + route, ) .await .map_err(|error| CoreError::Rpc { From 4772736055602afdd200c379a792bb3c624f5262 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 00:19:33 +0300 Subject: [PATCH 06/24] feat(context): per-session keep_recent_tokens, result expiry, reasoning replay and tool pruning Adds [context] keep_recent_tokens, tool_result_max_age_turns, tool_result_exempt_tools, replay_reasoning and prune_retired_tools with env overlays. Expiry and reasoning replay are pinned on each thread like the tool_search options (replay_pin.rs); prune_retired_tools chains onto the session builder and the granted snapshot names its deferred catalogue as offered. AgentSpec and Turn gain matching setters over ContextOverrides. Co-authored-by: Medulla --- .../src/agent/context/README.md | 2 +- .../src/agent/session_host/codec.rs | 4 + .../session_host/runtime_session/ensure.rs | 60 ++++++-- .../session_host/runtime_session/prelude.rs | 21 ++- .../runtime_session/prelude_tests.rs | 37 +++++ .../ops/graph/dispatch_helpers.rs | 1 + .../src/agent/tinyagents/context_wiring.rs | 27 +++- .../agent/tinyagents/context_wiring_tests.rs | 102 +++++++++++++ .../src/agent/tinyagents/discovery/mod.rs | 1 + .../src/agent/tinyagents/discovery/pin.rs | 58 +++++--- .../src/agent/tinyagents/host/run_context.rs | 3 + .../tinyagents/middleware/turn_context.rs | 4 + .../src/agent/tinyagents/mod.rs | 1 + .../src/agent/tinyagents/replay_pin.rs | 134 +++++++++++++++++ .../src/agent/tinyagents/replay_pin_tests.rs | 136 ++++++++++++++++++ .../src/agent/tinyagents/turn_middleware.rs | 2 + crates/openhuman-core/src/config/mod.rs | 2 +- .../src/config/schema/context.rs | 87 +++++++++++ .../config/schema/load/env_overlay/context.rs | 101 +++++++++++++ .../schema/load_env_overlay_context_tests.rs | 130 +++++++++++++++++ .../openhuman-core/src/config/schema/mod.rs | 3 +- crates/openhuman-embed/src/agent/build.rs | 1 + .../openhuman-embed/src/agent/build_tests.rs | 61 ++++++++ crates/openhuman-embed/src/agent/spec.rs | 53 +++++++ .../openhuman-embed/src/agent/spec_tests.rs | 25 ++++ crates/openhuman-embed/src/lib.rs | 1 + crates/openhuman-embed/src/turn.rs | 57 ++++++++ crates/openhuman-embed/src/turn_control.rs | 1 + 28 files changed, 1073 insertions(+), 42 deletions(-) create mode 100644 crates/openhuman-core/src/agent/tinyagents/replay_pin.rs create mode 100644 crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs diff --git a/crates/openhuman-core/src/agent/context/README.md b/crates/openhuman-core/src/agent/context/README.md index 6ef33d0fdaa..ff65cde001a 100644 --- a/crates/openhuman-core/src/agent/context/README.md +++ b/crates/openhuman-core/src/agent/context/README.md @@ -58,7 +58,7 @@ No `store.rs`. State is per-session and in-memory: ## Dependencies -- `crate::config`: `ContextSettings` ([`config/schema/context.rs`](../../config/schema/context.rs)), the whole `[context]` table: TinyAgents' `ContextConfig` flattened (reached through `Deref`, so `config.context.` reads it) plus OpenHuman's `summarizer_tool_rendering` (`full` | `markers`; env `OPENHUMAN_CONTEXT_SUMMARIZER_TOOL_RENDERING`: `markers` sends the summarizer one `[used : …]` line per call and no tool results, for small summarization models) and `summarizer_max_output_tokens` (env `OPENHUMAN_CONTEXT_SUMMARIZER_MAX_OUTPUT_TOKENS`, `0` clears: the summary request's `max_tokens`). The free-form (`summary`) strategy applies both; `task_state` ignores them. `ContextConfig`: `enabled`, `microcompact_enabled` / `microcompact_keep_recent`, `autocompact_enabled`, `compaction_trigger_tokens` (absolute summarization trigger for benchmarks; env `OPENHUMAN_COMPACTION_TRIGGER_TOKENS`), `compaction_strategy` (env `OPENHUMAN_COMPACTION_STRATEGY`), `compaction_enabled`, `tool_result_budget_bytes`, `prefer_markdown_tool_output`, `summarizer_model` (env `OPENHUMAN_CONTEXT_SUMMARIZER_MODEL`: the model the compaction summarizer calls on the turn's own provider route; unset or blank uses the turn's model), and the embedded `session_memory: SessionMemoryConfig`. +- `crate::config`: `ContextSettings` ([`config/schema/context.rs`](../../config/schema/context.rs)), the whole `[context]` table: TinyAgents' `ContextConfig` flattened (reached through `Deref`, so `config.context.` reads it) plus OpenHuman's `keep_recent_tokens` (env `OPENHUMAN_CONTEXT_KEEP_RECENT_TOKENS`, `0` clears: the verbatim tail an in-turn compaction keeps; unset keeps 20,000, capped at a fifth of a known context window; an embedder sets it per agent or turn with `AgentSpec::keep_recent_tokens` / `Turn::keep_recent_tokens`), `tool_result_max_age_turns` (env `OPENHUMAN_CONTEXT_TOOL_RESULT_MAX_AGE_TURNS`; unset or `0` keeps every tool result, a number replaces a result older than that many user turns with a one-line note) with `tool_result_exempt_tools` (env `OPENHUMAN_CONTEXT_TOOL_RESULT_EXEMPT_TOOLS`, comma separated), `replay_reasoning` (`all` | `current_turn`, env `OPENHUMAN_CONTEXT_REPLAY_REASONING`; `current_turn` leaves earlier turns' reasoning out of the request, the stored transcript keeps it), `prune_retired_tools` (env `OPENHUMAN_CONTEXT_PRUNE_RETIRED_TOOLS`; drops a recorded tool declaration the host no longer offers, live or deferred, instead of carrying it for the life of the thread), and `summarizer_tool_rendering` (`full` | `markers`; env `OPENHUMAN_CONTEXT_SUMMARIZER_TOOL_RENDERING`: `markers` sends the summarizer one `[used : …]` line per call and no tool results, for small summarization models) and `summarizer_max_output_tokens` (env `OPENHUMAN_CONTEXT_SUMMARIZER_MAX_OUTPUT_TOKENS`, `0` clears: the summary request's `max_tokens`). The free-form (`summary`) strategy applies the two summarizer keys; `task_state` ignores them. The expiry and reasoning-replay keys change the bytes of every later prompt, so a session pins them on a thread when it creates it (`agent/tinyagents/replay_pin.rs`, recorded as `context_replay` on the first transcript row beside `tool_discovery`) and a resumed thread keeps them whatever the config says now; a thread that recorded nothing keeps today's behaviour. `ContextConfig`: `enabled`, `microcompact_enabled` / `microcompact_keep_recent`, `autocompact_enabled`, `compaction_trigger_tokens` (absolute summarization trigger for benchmarks; env `OPENHUMAN_COMPACTION_TRIGGER_TOKENS`), `compaction_strategy` (env `OPENHUMAN_COMPACTION_STRATEGY`), `compaction_enabled`, `tool_result_budget_bytes`, `prefer_markdown_tool_output`, `summarizer_model` (env `OPENHUMAN_CONTEXT_SUMMARIZER_MODEL`: the model the compaction summarizer calls on the turn's own provider route; unset or blank uses the turn's model), and the embedded `session_memory: SessionMemoryConfig`. - `crate::inference::provider::UsageInfo`: fed into `record_usage`. - `crate::agent::prompts`: owns prompt rendering; `channels_prompt.rs` uses `inject_inline_content`. - `crate::skills::Workflow`: `channels_prompt.rs` renders the available-skills section from a `&[Workflow]`. diff --git a/crates/openhuman-core/src/agent/session_host/codec.rs b/crates/openhuman-core/src/agent/session_host/codec.rs index b123bbefe98..a7bcadd7368 100644 --- a/crates/openhuman-core/src/agent/session_host/codec.rs +++ b/crates/openhuman-core/src/agent/session_host/codec.rs @@ -81,6 +81,10 @@ impl TranscriptCodec for OpenHumanTranscriptCodec { if let Some(options) = sidecar.discovery_record { options.record_on(&mut reconciled.rows, &reconciled.fresh); } + // Likewise the history-replay options (result expiry, reasoning replay). + if let Some(options) = &sidecar.replay_record { + options.record_on(&mut reconciled.rows, &reconciled.fresh); + } attach_text_dialect_rounds( &mut reconciled.rows, &reconciled.fresh, diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/ensure.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/ensure.rs index d6cac989c3e..b1b1338850a 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session/ensure.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/ensure.rs @@ -34,6 +34,11 @@ impl OpenHumanSessionHost { microcompact_keep_recent, autocompact_enabled, compaction, + keep_recent_tokens: self + .runtime_config + .as_deref() + .and_then(|config| config.context.keep_recent_tokens) + .map(u64::from), transcript_snapshot: None, }; let driver = Arc::new(OpenHumanSessionDriver::new( @@ -153,13 +158,14 @@ impl OpenHumanSessionHost { // The thread's discovery options: chosen from the config // by the turn that prepares its first prompt and recorded // with it, read back from the transcript on every other. + let generation_start = super::turn::prepare_prefix_for_turn( + new_session, + view.prefix_is_frozen, + ); let discovery = crate::agent::tinyagents::discovery::resolve( &prelude.config.tool_search, view.raw_history, - super::turn::prepare_prefix_for_turn( - new_session, - view.prefix_is_frozen, - ), + generation_start, ); tracing::debug!( thread_id = ?prelude.thread_id, @@ -168,13 +174,36 @@ impl OpenHumanSessionHost { "[tool-search] discovery options for this turn" ); options.run_context.config.discovery = discovery.effective.overrides(); - options - .run_context - .data - .session_sidecar - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .discovery_record = discovery.record; + // Result expiry and reasoning replay are pinned the same + // way, from `[context]`. + let replay = crate::agent::tinyagents::replay_pin::resolve( + &prelude + .runtime_config + .as_deref() + .map_or_else(Default::default, |config| config.context.clone()), + view.raw_history, + generation_start, + ); + tracing::debug!( + thread_id = ?prelude.thread_id, + options = ?replay.effective, + recorded_now = replay.record.is_some(), + "[context] history replay options for this turn" + ); + options.run_context.config.result_expiry = + replay.effective.expiry_overrides(); + options.run_context.config.replay_reasoning = + Some(replay.effective.replay_reasoning); + { + let mut sidecar = options + .run_context + .data + .session_sidecar + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + sidecar.discovery_record = discovery.record; + sidecar.replay_record = replay.record; + } let original_input = request.input.clone(); let original_user_message = user_text_with_markers(&original_input); prelude.begin_user_effects(request, &options.run_context.data); @@ -313,7 +342,14 @@ impl OpenHumanSessionHost { channel: self.event_channel.clone(), }, })) - .retain_recorded_tools(!self.host_only && !self.host_env.fresh_tool_snapshot); + .retain_recorded_tools(!self.host_only && !self.host_env.fresh_tool_snapshot) + // `[context] prune_retired_tools`: a recorded declaration the host + // no longer offers (live or deferred) is dropped, not carried on. + .prune_retired_tools( + self.runtime_config + .as_deref() + .is_some_and(|config| config.context.prune_retired_tools), + ); let meta = self.runtime_transcript_meta(); builder = if let Some(locator) = injected_locator { match self.session.clone() { diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs index 6d68b542a70..063c3fcd7d7 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs @@ -52,12 +52,12 @@ impl OpenHumanTurnPrelude { // the deferred tools beside the advertised ones. The harness // still advertises only the `Direct` registrations and reaches // the rest through its `tool_search` bridge. - ToolSnapshot::new(granted_tool_specs( + granted_tool_snapshot( &surface.visible_tool_specs, &surface.tool_specs, &surface.deferred_tool_names, self.thread_id.is_some(), - )) + ) .map_err(|error| anyhow::anyhow!(error.to_string()))? }; let prefix = if cold { @@ -415,6 +415,23 @@ fn granted_tool_specs( .collect() } +/// The snapshot of [`granted_tool_specs`], naming every deferred tool as +/// offered. A deferred tool whose declaration the host has not rebuilt has +/// nothing to grant, yet the model can still discover it, so a session that +/// prunes retired tools (`[context] prune_retired_tools`) must not drop its +/// recorded declaration. +fn granted_tool_snapshot( + visible: &[Arc], + registered: &[Arc], + deferred: &std::collections::HashSet, + has_thread: bool, +) -> Result { + Ok(ToolSnapshot::new(granted_tool_specs( + visible, registered, deferred, has_thread, + ))? + .with_offered_names(deferred.iter().cloned())) +} + #[cfg(test)] #[path = "prelude_tests.rs"] mod tests; diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude_tests.rs index fab0bec458c..bf784b63f6e 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude_tests.rs @@ -44,3 +44,40 @@ fn a_tool_both_advertised_and_deferred_keeps_the_advertised_declaration() { assert_eq!(granted.len(), 1); assert_eq!(granted[0].description, "advertised copy"); } + +/// With pruning on, a recorded declaration survives only while the snapshot +/// offers its name. A deferred tool the host has not rebuilt yet has no +/// declaration to grant, but it is still offered through the catalogue. +#[test] +fn the_granted_snapshot_offers_every_deferred_name_even_without_a_declaration() { + let visible = vec![spec("shell", "built-in shell")]; + let registered = vec![spec("lookup", "deferred copy")]; + let deferred: HashSet = ["lookup".to_string(), "not_rebuilt_yet".to_string()].into(); + + let snapshot = granted_tool_snapshot(&visible, ®istered, &deferred, true).expect("freezes"); + + assert!(snapshot.offers("shell")); + assert!(snapshot.offers("lookup")); + assert!(snapshot.offers("not_rebuilt_yet")); + assert!(!snapshot.offers("retired_tool")); + assert!(snapshot + .specs() + .iter() + .all(|spec| spec.name != "not_rebuilt_yet")); + + let recorded = ToolSnapshot::new(vec![ + (*spec("not_rebuilt_yet", "recorded")).clone(), + (*spec("retired_tool", "recorded")).clone(), + ]) + .unwrap(); + let (merged, retained) = snapshot.with_retained_offered(&recorded).unwrap(); + assert_eq!(retained, 1, "only the still-offered declaration is kept"); + assert!(merged + .specs() + .iter() + .any(|spec| spec.name == "not_rebuilt_yet")); + assert!(merged + .specs() + .iter() + .all(|spec| spec.name != "retired_tool")); +} diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch_helpers.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch_helpers.rs index 6b6569d8c28..f0cc7629138 100644 --- a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch_helpers.rs +++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch_helpers.rs @@ -78,6 +78,7 @@ pub(super) fn build_subagent_context_mw( // opt-outs, same as `ContextConfig::enabled && autocompact_enabled`. mw.autocompact_enabled = ctx.enabled && ctx.autocompact_enabled; mw.compaction = ctx.compaction_settings(); + mw.keep_recent_tokens = config.context.keep_recent_tokens.map(u64::from); tracing::debug!( tokenjuice_compaction_enabled = mw.tokenjuice_compaction_enabled, compression = ?mw.tokenjuice_compression, diff --git a/crates/openhuman-core/src/agent/tinyagents/context_wiring.rs b/crates/openhuman-core/src/agent/tinyagents/context_wiring.rs index d69ae074ac1..8c907828130 100644 --- a/crates/openhuman-core/src/agent/tinyagents/context_wiring.rs +++ b/crates/openhuman-core/src/agent/tinyagents/context_wiring.rs @@ -28,6 +28,13 @@ use tinyagents_harness::turn_outcome::ToolOutcomeSink; const BUDGET_NOTICE_THRESHOLDS: [f64; 2] = [0.5, 0.8]; /// Longest verbatim tail of a task-state compaction (tokens). const TASK_STATE_KEEP_RECENT_TOKENS: u64 = 20_000; +/// The verbatim tail of a task-state compaction: `requested` (the `[context] +/// keep_recent_tokens` budget; unset keeps [`TASK_STATE_KEEP_RECENT_TOKENS`]), +/// held to a fifth of a known context window. +fn task_state_keep_recent_tokens(window: Option, requested: Option) -> u64 { + let budget = requested.unwrap_or(TASK_STATE_KEEP_RECENT_TOKENS); + window.map_or(budget, |w| (w / 5).min(budget)) +} /// Store the artifact index is registered under on the run context. const ARTIFACT_INDEX_STORE: &str = crate::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE; @@ -112,6 +119,7 @@ pub(super) fn install_context_ladder( autocompact_enabled: bool, compaction_trigger_tokens: Option, compaction_strategy: crate::config::CompactionStrategy, + keep_recent_tokens: Option, microcompact_keep_recent: usize, summarizer: CompactionSummarizer, wrap_up_at_cap: bool, @@ -131,6 +139,7 @@ pub(super) fn install_context_ladder( policy, compaction_strategy, context_window, + keep_recent_tokens, summarizer, model, memory_turn, @@ -181,11 +190,14 @@ pub(super) fn install_context_ladder( /// The compression middleware for `strategy`: `TaskState` writes a typed /// checkpoint over a token-budgeted tail, `Summary` is the free-form summarizer, /// rendering tool activity and capping its output as `summarizer.settings` -/// say. `model` is the turn's. +/// say. `model` is the turn's. `keep_recent_tokens` is the `[context]` tail +/// budget: unset, a task-state compaction keeps 20k tokens and a free-form one +/// keeps its count-based tail. pub(crate) fn compression_middleware( policy: SummarizationPolicy, strategy: crate::config::CompactionStrategy, context_window: Option, + keep_recent_tokens: Option, summarizer: CompactionSummarizer, model: &str, memory_turn: Option>, @@ -194,9 +206,7 @@ pub(crate) fn compression_middleware( let window = context_window.filter(|w| *w > 0); match strategy { crate::config::CompactionStrategy::TaskState => { - let keep_recent = window.map_or(TASK_STATE_KEEP_RECENT_TOKENS, |w| { - (w / 5).min(TASK_STATE_KEEP_RECENT_TOKENS) - }); + let keep_recent = task_state_keep_recent_tokens(window, keep_recent_tokens); let chunk = window.map_or(DEFAULT_TASK_STATE_CHUNK_TOKENS, |w| { (w * 2 / 5).clamp(4_000, DEFAULT_TASK_STATE_CHUNK_TOKENS) }); @@ -234,10 +244,14 @@ pub(crate) fn compression_middleware( announced(Box::new(model_summarizer), compaction_notice), &policy, ); - ContextCompressionMiddleware::with_summarizer( + let middleware = ContextCompressionMiddleware::with_summarizer( policy, MemoryRecallSummarizer::wrap(Box::new(summarizer), memory_turn), - ) + ); + match keep_recent_tokens { + Some(tokens) => middleware.with_keep_recent_tokens(tokens), + None => middleware, + } } } } @@ -290,6 +304,7 @@ pub(crate) async fn compact_history( policy, fold.strategy, fold.context_window, + None, summarizer, fold.model, None, 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 673860a111f..4a00e341018 100644 --- a/crates/openhuman-core/src/agent/tinyagents/context_wiring_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/context_wiring_tests.rs @@ -88,6 +88,7 @@ async fn a_compaction_records_the_summarizer_model_it_called() { SummarizationPolicy::default().with_trigger_override(200), crate::config::CompactionStrategy::TaskState, None, + None, CompactionSummarizer { model: state_model, model_id: "scaledown/summarize".into(), @@ -154,6 +155,7 @@ async fn a_markers_compaction_sends_no_tool_output_and_caps_the_summary() { SummarizationPolicy::default().with_trigger_override(200), crate::config::CompactionStrategy::Summary, None, + None, CompactionSummarizer { model: summarizer_model.clone(), model_id: "scaledown/summarize".into(), @@ -302,3 +304,103 @@ async fn an_idle_fold_with_nothing_old_enough_returns_none() { assert!(folded.is_none()); assert!(summarizer_model.requests().is_empty()); } + +/// Tokens of the conversation turns a compacted request still carries +/// verbatim: the `ask` / `answer` messages the test wrote, not the summary. +fn verbatim_tokens(request: &tinyinference_llm::model::ModelRequest) -> u64 { + request + .messages + .iter() + .filter(|message| { + let text = format!("{message:?}"); + text.contains("ask ") || text.contains("answer ") + }) + .map(tinyagents_harness::token_estimation::estimate_message_tokens) + .sum() +} + +/// Runs one compacting turn over a long history and returns the tokens the +/// turn's model call still saw verbatim. +async fn tail_after_compaction(keep_recent_tokens: Option) -> u64 { + use tinyagents_harness::context::{RunConfig, RunContext}; + use tinyagents_harness::testkit::ScriptedModel; + + let turn_model = Arc::new(ScriptedModel::replies(vec!["done"])); + let mw = Arc::new(compression_middleware( + SummarizationPolicy::default().with_trigger_override(60_000), + crate::config::CompactionStrategy::TaskState, + None, + keep_recent_tokens, + CompactionSummarizer { + model: Arc::new(ScriptedModel::replies(vec![ + "{\"goal\": \"keep going\"}"; + 4 + ])), + model_id: "summarizer".into(), + settings: Default::default(), + }, + "turn-model", + None, + None, + )); + let mut harness: AgentHarness<()> = AgentHarness::new(); + harness.with_model_resolver(Arc::new( + tinyagents_harness::host::FixedModelResolver::named("turn-model", turn_model.clone() as _), + )); + harness.push_middleware(mw.clone()); + harness.push_model_middleware(mw.clone()); + + let mut history = vec![Message::system("system")]; + for round in 0..120 { + history.push(Message::user(format!( + "ask {round}: {}", + "detail ".repeat(280) + ))); + history.push(Message::assistant(format!( + "answer {round}: {}", + "result ".repeat(280) + ))); + } + history.push(Message::user("continue")); + harness + .invoke_in_context( + &(), + RunContext::new(RunConfig::new("compaction"), ()), + history, + ) + .await + .expect("the turn runs"); + assert!(!mw.records().is_empty(), "the turn compacted"); + verbatim_tokens(turn_model.requests().last().expect("the model was called")) +} + +/// `[context] keep_recent_tokens` sets the tail an in-turn compaction keeps +/// verbatim; unset keeps the 20k it always had. +#[tokio::test] +async fn keep_recent_tokens_override_reaches_compaction() { + let default_tail = tail_after_compaction(None).await; + let short_tail = tail_after_compaction(Some(12_000)).await; + assert!( + (19_000..=21_000).contains(&default_tail), + "unset keeps about 20k tokens, kept {default_tail}" + ); + assert!( + (11_000..=13_000).contains(&short_tail), + "12k keeps about 12k tokens, kept {short_tail}" + ); +} + +#[test] +fn the_task_state_tail_is_the_override_capped_by_a_fifth_of_the_window() { + assert_eq!(task_state_keep_recent_tokens(None, None), 20_000); + assert_eq!(task_state_keep_recent_tokens(None, Some(12_000)), 12_000); + assert_eq!(task_state_keep_recent_tokens(Some(200_000), None), 20_000); + assert_eq!( + task_state_keep_recent_tokens(Some(200_000), Some(12_000)), + 12_000 + ); + assert_eq!( + task_state_keep_recent_tokens(Some(40_000), Some(12_000)), + 8_000 + ); +} diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs index 8ccfdb1e8ee..00bbed9e751 100644 --- a/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs +++ b/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs @@ -243,6 +243,7 @@ impl ToolRanker for OverlapRanker { mod embedding_ranker; mod pin; +pub(crate) use pin::{record_metadata, recorded_metadata}; pub use pin::{resolve, DiscoveryOptions, ResolvedDiscovery, DISCOVERY_METADATA_KEY}; pub use embedding_ranker::{ diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs index 9504493d9fe..000ab8d5558 100644 --- a/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs +++ b/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs @@ -85,10 +85,7 @@ impl DiscoveryOptions { /// The options a thread recorded on its transcript `rows`, if any. pub fn recorded_in(rows: &[TranscriptMessage]) -> Option { - rows.iter() - .filter_map(|row| row.extra_metadata.as_ref()) - .find_map(|metadata| metadata.get(DISCOVERY_METADATA_KEY)) - .and_then(|value| serde_json::from_value(value.clone()).ok()) + recorded_metadata(rows, DISCOVERY_METADATA_KEY) } /// Records these options on the first fresh row of a transcript being @@ -96,23 +93,46 @@ impl DiscoveryOptions { /// transcript is never touched: rewriting it would make the commit open a /// new generation instead of extending the thread. pub fn record_on(&self, rows: &mut [TranscriptMessage], fresh: &[bool]) -> bool { - let Some(index) = fresh.iter().position(|is_fresh| *is_fresh) else { - return false; - }; - let Some(row) = rows.get_mut(index) else { - return false; - }; let value = serde_json::to_value(self).expect("plain booleans serialize"); - match row - .extra_metadata - .get_or_insert_with(|| serde_json::Value::Object(serde_json::Map::new())) - { - serde_json::Value::Object(map) => { - map.insert(DISCOVERY_METADATA_KEY.to_string(), value); - true - } - _ => false, + record_metadata(rows, fresh, DISCOVERY_METADATA_KEY, value) + } +} + +/// The value a thread recorded under `key` on its transcript `rows`, if any. +pub(crate) fn recorded_metadata( + rows: &[TranscriptMessage], + key: &str, +) -> Option { + rows.iter() + .filter_map(|row| row.extra_metadata.as_ref()) + .find_map(|metadata| metadata.get(key)) + .and_then(|value| serde_json::from_value(value.clone()).ok()) +} + +/// Writes `value` under `key` in the `extra_metadata` of the first fresh row, +/// returning whether one was found. Other keys on the row are kept, so +/// several pins share the thread's first row. +pub(crate) fn record_metadata( + rows: &mut [TranscriptMessage], + fresh: &[bool], + key: &str, + value: serde_json::Value, +) -> bool { + let Some(index) = fresh.iter().position(|is_fresh| *is_fresh) else { + return false; + }; + let Some(row) = rows.get_mut(index) else { + return false; + }; + match row + .extra_metadata + .get_or_insert_with(|| serde_json::Value::Object(serde_json::Map::new())) + { + serde_json::Value::Object(map) => { + map.insert(key.to_string(), value); + true } + _ => false, } } diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs index 5bef46f6606..aa6b68c3eb0 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs @@ -153,6 +153,9 @@ pub(crate) struct SessionTurnSidecar { /// thread's first prompt and only when they differ from today's /// behaviour; see `tinyagents::discovery::DiscoveryOptions`. pub discovery_record: Option, + /// The history-replay options this turn starts its thread with, recorded + /// like `discovery_record`; see `tinyagents::replay_pin::ReplayOptions`. + pub replay_record: Option, } #[path = "dispatch_control.rs"] diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs index 56d0d14883d..1ae5adcda99 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs @@ -54,6 +54,9 @@ pub(crate) struct TurnContextMiddleware { /// the window is unknown; `None` keeps the window-relative default) and /// how a compaction writes its checkpoint. pub(crate) compaction: crate::config::CompactionSettings, + /// `[context].keep_recent_tokens`: the verbatim tail an in-turn compaction + /// keeps. `None` keeps the strategy's own default. + pub(crate) keep_recent_tokens: Option, /// Live transcript snapshot sink (#4466). When set, a /// [`TranscriptSnapshotMiddleware`] mirrors the running conversation into /// this shared buffer before every model call, so an erroring run can still @@ -361,6 +364,7 @@ impl TurnContextMiddleware { microcompact_keep_recent: 0, autocompact_enabled: true, compaction: Default::default(), + keep_recent_tokens: None, transcript_snapshot: None, } } diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rs index 81d757bc6b5..30dc1409f5a 100644 --- a/crates/openhuman-core/src/agent/tinyagents/mod.rs +++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs @@ -26,6 +26,7 @@ pub mod discovery; pub mod host; pub(crate) mod hosted_error; pub(crate) mod journal; +pub mod replay_pin; // The tool harness behind a live voice session (`voice::live`). #[cfg(feature = "voice")] pub(crate) mod live_harness; diff --git a/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs b/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs new file mode 100644 index 00000000000..ac222d93184 --- /dev/null +++ b/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs @@ -0,0 +1,134 @@ +//! The history-replay options a thread starts with, and keeps. +//! +//! Expiring old tool results and leaving earlier turns' reasoning out of a +//! request both change the bytes of every later prompt (the provider's cached +//! prefix), so a session decides them once, when it creates the thread, and +//! records them on the thread's first transcript row beside the discovery +//! options (`discovery/pin.rs` is the model). A resumed thread reads them back; +//! the config and the embedder's options only choose them for the next thread. +//! +//! A thread that records nothing (every thread written before this existed, +//! and any thread created with today's behaviour) resolves to +//! [`ReplayOptions::TODAY`] whatever the config says now. +//! +//! The options reach the harness per run as +//! [`ExpiryOverrides`] on `RunConfig::result_expiry` and as +//! `RunConfig::replay_reasoning`, every field set, so the harness-wide policy +//! never leaks into a session turn. + +use serde::{Deserialize, Serialize}; +use tinyagents_harness::reasoning_replay::ReasoningReplay; +use tinyagents_harness::result_expiry::{ExpiryOverrides, DEFAULT_EXPIRY_MAX_AGE_TURNS}; +use tinyagents_session::transcript::TranscriptMessage; + +use super::discovery::{record_metadata, recorded_metadata}; +use crate::config::ContextSettings; + +/// Key under a transcript row's `extra_metadata` that holds the recorded +/// options. +pub const REPLAY_METADATA_KEY: &str = "context_replay"; + +/// The history-replay options of one thread. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplayOptions { + /// A tool result with more than this many user turns after it is replaced + /// by a one-line note. `None` keeps every result. + pub tool_result_max_age_turns: Option, + /// Tools whose results never expire. Empty while expiry is off. + pub tool_result_exempt_tools: Vec, + /// Which turns' reasoning a request carries. + pub replay_reasoning: ReasoningReplay, +} + +impl ReplayOptions { + /// Today's behaviour: the harness defaults, and what a thread that + /// recorded nothing has always run with. + pub const TODAY: Self = Self { + tool_result_max_age_turns: None, + tool_result_exempt_tools: Vec::new(), + replay_reasoning: ReasoningReplay::All, + }; + + /// The options `[context]` asks new threads to start with. An age of `0` + /// means off, and an exempt list means nothing without an age, so both + /// normalize to what [`Self::TODAY`] holds. + pub fn from_config(config: &ContextSettings) -> Self { + let age = config.tool_result_max_age_turns.filter(|age| *age > 0); + Self { + tool_result_max_age_turns: age, + tool_result_exempt_tools: if age.is_some() { + config.tool_result_exempt_tools.clone() + } else { + Vec::new() + }, + replay_reasoning: config.replay_reasoning, + } + } + + /// The per-run overrides that make the harness expire results exactly as + /// these options say. + pub fn expiry_overrides(&self) -> ExpiryOverrides { + ExpiryOverrides { + enabled: Some(self.tool_result_max_age_turns.is_some()), + max_age_turns: Some( + self.tool_result_max_age_turns + .map_or(DEFAULT_EXPIRY_MAX_AGE_TURNS, |age| age as usize), + ), + exempt_tools: Some(self.tool_result_exempt_tools.clone()), + } + } + + /// The options a thread recorded on its transcript `rows`, if any. + pub fn recorded_in(rows: &[TranscriptMessage]) -> Option { + recorded_metadata(rows, REPLAY_METADATA_KEY) + } + + /// Records these options on the first fresh row of a transcript being + /// written, returning whether one was found. A row already stored is never + /// touched: rewriting it would make the commit open a new generation. + pub fn record_on(&self, rows: &mut [TranscriptMessage], fresh: &[bool]) -> bool { + let value = serde_json::to_value(self).expect("plain options serialize"); + record_metadata(rows, fresh, REPLAY_METADATA_KEY, value) + } +} + +impl Default for ReplayOptions { + fn default() -> Self { + Self::TODAY + } +} + +/// What a turn runs with, and what it must write down. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ResolvedReplay { + /// The options this turn runs with. + pub effective: ReplayOptions, + /// The options to record on the thread, set only for the turn that starts + /// it and only when they differ from [`ReplayOptions::TODAY`]. + pub record: Option, +} + +/// Decides a session turn's options. +/// +/// `generation_start` is true for the turn that prepares the thread's first +/// prompt: it takes the options `config` asks for and records them. Every +/// other turn reads what `rows` recorded, or [`ReplayOptions::TODAY`]. +pub fn resolve( + config: &ContextSettings, + rows: &[TranscriptMessage], + generation_start: bool, +) -> ResolvedReplay { + if generation_start { + let effective = ReplayOptions::from_config(config); + let record = (effective != ReplayOptions::TODAY).then(|| effective.clone()); + return ResolvedReplay { effective, record }; + } + ResolvedReplay { + effective: ReplayOptions::recorded_in(rows).unwrap_or(ReplayOptions::TODAY), + record: None, + } +} + +#[cfg(test)] +#[path = "replay_pin_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs b/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs new file mode 100644 index 00000000000..7785ac3a644 --- /dev/null +++ b/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs @@ -0,0 +1,136 @@ +use tinyagents_harness::reasoning_replay::ReasoningReplay; +use tinyagents_harness::result_expiry::{ExpiryOverrides, ToolResultExpiryPolicy}; + +use super::*; + +fn settings(age: Option, exempt: &[&str], replay: ReasoningReplay) -> ContextSettings { + let mut settings = ContextSettings::default(); + settings.tool_result_max_age_turns = age; + settings.tool_result_exempt_tools = exempt.iter().map(|name| (*name).to_owned()).collect(); + settings.replay_reasoning = replay; + settings +} + +#[test] +fn today_is_the_harness_default_and_the_config_default() { + let policy = ToolResultExpiryPolicy::default(); + let overrides = ReplayOptions::TODAY.expiry_overrides(); + assert_eq!(overrides.enabled, Some(policy.enabled)); + assert_eq!(overrides.exempt_tools, Some(policy.exempt_tools)); + assert_eq!( + ReplayOptions::TODAY.replay_reasoning, + ReasoningReplay::default() + ); + assert_eq!( + ReplayOptions::from_config(&ContextSettings::default()), + ReplayOptions::TODAY + ); +} + +#[test] +fn config_options_map_onto_the_harness_expiry_and_replay_options() { + let options = ReplayOptions::from_config(&settings( + Some(4), + &["tool_search"], + ReasoningReplay::CurrentTurn, + )); + assert_eq!( + options.expiry_overrides(), + ExpiryOverrides { + enabled: Some(true), + max_age_turns: Some(4), + exempt_tools: Some(vec!["tool_search".into()]), + } + ); + assert_eq!(options.replay_reasoning, ReasoningReplay::CurrentTurn); + + let policy = ToolResultExpiryPolicy::default().with_overrides(&options.expiry_overrides()); + assert!(policy.enabled); + assert_eq!(policy.max_age_turns, 4); + assert_eq!(policy.exempt_tools, ["tool_search"]); +} + +#[test] +fn an_age_of_zero_or_none_switches_expiry_off_and_drops_the_exempt_list() { + for age in [None, Some(0)] { + let options = + ReplayOptions::from_config(&settings(age, &["tool_search"], ReasoningReplay::All)); + assert_eq!(options, ReplayOptions::TODAY); + assert_eq!(options.expiry_overrides().enabled, Some(false)); + } +} + +#[test] +fn a_new_thread_takes_the_config_and_records_only_a_change_from_today() { + let wanted = settings(Some(6), &[], ReasoningReplay::All); + let changed = resolve(&wanted, &[], true); + assert_eq!(changed.effective, ReplayOptions::from_config(&wanted)); + assert_eq!(changed.record.as_ref(), Some(&changed.effective)); + + let unchanged = resolve(&ContextSettings::default(), &[], true); + assert_eq!(unchanged.effective, ReplayOptions::TODAY); + assert_eq!(unchanged.record, None); +} + +#[test] +fn a_resumed_thread_keeps_what_it_recorded_whatever_the_config_says_now() { + let started_with = + ReplayOptions::from_config(&settings(Some(3), &["a"], ReasoningReplay::CurrentTurn)); + let mut rows = vec![ + TranscriptMessage::system("prompt"), + TranscriptMessage::new("user", "hi"), + ]; + assert!(started_with.record_on(&mut rows, &[true, true])); + + let now = settings(None, &[], ReasoningReplay::All); + let resumed = resolve(&now, &rows, false); + assert_eq!(resumed.effective, started_with); + assert_eq!(resumed.record, None); +} + +#[test] +fn a_thread_that_recorded_nothing_keeps_todays_behaviour_whatever_the_config_says() { + let rows = vec![TranscriptMessage::system("prompt")]; + let resumed = resolve( + &settings(Some(2), &[], ReasoningReplay::CurrentTurn), + &rows, + false, + ); + assert_eq!(resumed.effective, ReplayOptions::TODAY); + assert_eq!(resumed.record, None); +} + +#[test] +fn recording_touches_only_the_first_fresh_row_and_survives_serialization() { + let options = ReplayOptions::from_config(&settings(Some(5), &[], ReasoningReplay::All)); + let mut rows = vec![ + TranscriptMessage::new("user", "imported"), + TranscriptMessage::system("prompt"), + TranscriptMessage::new("user", "hi"), + ]; + let before = rows[0].clone(); + assert!(options.record_on(&mut rows, &[false, true, true])); + assert_eq!(rows[0], before, "a row already stored is never rewritten"); + assert!(rows[2].extra_metadata.is_none()); + + let stored: Vec = + serde_json::from_str(&serde_json::to_string(&rows).unwrap()).unwrap(); + assert_eq!(ReplayOptions::recorded_in(&stored), Some(options.clone())); + assert!(!options.record_on(&mut rows, &[false, false, false])); +} + +#[test] +fn replay_and_discovery_records_share_a_row_without_clobbering_each_other() { + use crate::agent::tinyagents::discovery::DiscoveryOptions; + + let discovery = DiscoveryOptions { + promote_found_tools: false, + ..DiscoveryOptions::TODAY + }; + let replay = ReplayOptions::from_config(&settings(Some(5), &[], ReasoningReplay::All)); + let mut rows = vec![TranscriptMessage::system("prompt")]; + assert!(discovery.record_on(&mut rows, &[true])); + assert!(replay.record_on(&mut rows, &[true])); + assert_eq!(DiscoveryOptions::recorded_in(&rows), Some(discovery)); + assert_eq!(ReplayOptions::recorded_in(&rows), Some(replay)); +} diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs index 37de44e3a1a..b231d3fd320 100644 --- a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs +++ b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs @@ -266,6 +266,7 @@ pub(super) fn install_turn_middleware( // Capture context settings before `install` consumes `context_mw`. let autocompact_enabled = context_mw.autocompact_enabled; let compaction = context_mw.compaction; + let keep_recent_tokens = context_mw.keep_recent_tokens; // Captured for the same reason `autocompact_enabled` is — `install` consumes // `context_mw` — and used to site microcompact below, after compression. let microcompact_keep_recent = context_mw.microcompact_keep_recent; @@ -478,6 +479,7 @@ pub(super) fn install_turn_middleware( autocompact_enabled, compaction.trigger_tokens, compaction.strategy, + keep_recent_tokens, microcompact_keep_recent, summarizer, pause_at_cap && subagent_scope.is_none(), diff --git a/crates/openhuman-core/src/config/mod.rs b/crates/openhuman-core/src/config/mod.rs index 3c991fa54c9..840411b1f8b 100644 --- a/crates/openhuman-core/src/config/mod.rs +++ b/crates/openhuman-core/src/config/mod.rs @@ -71,7 +71,7 @@ pub use schema::{ // Kept as a separate re-export (issue #4117) so the large alphabetized group // above stays byte-identical and rustfmt-stable. pub use schema::RequiredOutputContract; -pub use schema::SummarizerSettings; +pub use schema::{ContextOverrides, ReasoningReplay, SummarizerSettings}; pub use schema::{InboundDebounceConfig, InboundDebounceOverride}; pub use schema::{SecurityMode, SecurityModeConfig}; pub use schemas::{ diff --git a/crates/openhuman-core/src/config/schema/context.rs b/crates/openhuman-core/src/config/schema/context.rs index b17eadf7a28..f5eccd9ee9d 100644 --- a/crates/openhuman-core/src/config/schema/context.rs +++ b/crates/openhuman-core/src/config/schema/context.rs @@ -11,6 +11,7 @@ use serde::{Deserialize, Serialize}; pub use tinyagents_harness::config::{CompactionSettings, CompactionStrategy, ContextConfig}; +pub use tinyagents_harness::reasoning_replay::ReasoningReplay; use tinyagents_harness::summarization::ToolRendering; /// The whole `[context]` table: TinyAgents' [`ContextConfig`] and the @@ -31,6 +32,33 @@ pub struct ContextSettings { /// `OPENHUMAN_CONTEXT_SUMMARIZER_MAX_OUTPUT_TOKENS` (`0` clears it). #[serde(default)] pub summarizer_max_output_tokens: Option, + /// Verbatim tail, in tokens, an in-turn compaction keeps after its + /// summary. Unset keeps 20,000 (capped at a fifth of the context window). + /// An embedder sets it per session (`AgentSpec::keep_recent_tokens`). Env: + /// `OPENHUMAN_CONTEXT_KEEP_RECENT_TOKENS` (`0` clears it). + #[serde(default)] + pub keep_recent_tokens: Option, + /// Replace a tool result older than this many user turns with a one-line + /// note, at the start of each run. Unset (or `0`) keeps every result, as + /// before. Pinned on each thread when it is created: a running thread keeps + /// the value it started with. Env: `OPENHUMAN_CONTEXT_TOOL_RESULT_MAX_AGE_TURNS`. + #[serde(default)] + pub tool_result_max_age_turns: Option, + /// Tools whose results never expire, by exact name. Only read while + /// `tool_result_max_age_turns` is set. Env: + /// `OPENHUMAN_CONTEXT_TOOL_RESULT_EXEMPT_TOOLS` (comma separated). + #[serde(default)] + pub tool_result_exempt_tools: Vec, + /// Which turns' reasoning a request replays: `all` (today's behaviour) or + /// `current_turn`. The stored transcript always keeps every block. Pinned + /// on each thread when it is created. Env: `OPENHUMAN_CONTEXT_REPLAY_REASONING`. + #[serde(default)] + pub replay_reasoning: ReasoningReplay, + /// Drop a recorded tool declaration the host no longer offers instead of + /// carrying it forward for the life of the thread. Env: + /// `OPENHUMAN_CONTEXT_PRUNE_RETIRED_TOOLS`. + #[serde(default)] + pub prune_retired_tools: bool, } impl ContextSettings { @@ -43,6 +71,43 @@ impl ContextSettings { } } +/// Per-session overrides of the `[context]` keys an embedder may set for one +/// agent or one thread. A field left `None` keeps the config's value. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ContextOverrides { + /// Replaces [`ContextSettings::keep_recent_tokens`]. + pub keep_recent_tokens: Option, + /// Replaces [`ContextSettings::tool_result_max_age_turns`]. + pub tool_result_max_age_turns: Option, + /// Replaces [`ContextSettings::tool_result_exempt_tools`]. + pub tool_result_exempt_tools: Option>, + /// Replaces [`ContextSettings::replay_reasoning`]. + pub replay_reasoning: Option, + /// Replaces [`ContextSettings::prune_retired_tools`]. + pub prune_retired_tools: Option, +} + +impl ContextOverrides { + /// Writes every override that is set into `settings`. + pub fn apply_to(&self, settings: &mut ContextSettings) { + if let Some(tokens) = self.keep_recent_tokens { + settings.keep_recent_tokens = Some(tokens); + } + if let Some(age) = self.tool_result_max_age_turns { + settings.tool_result_max_age_turns = Some(age); + } + if let Some(tools) = &self.tool_result_exempt_tools { + settings.tool_result_exempt_tools = tools.clone(); + } + if let Some(replay) = self.replay_reasoning { + settings.replay_reasoning = replay; + } + if let Some(prune) = self.prune_retired_tools { + settings.prune_retired_tools = prune; + } + } +} + impl std::ops::Deref for ContextSettings { type Target = ContextConfig; @@ -94,6 +159,21 @@ pub(crate) struct ContextConfigSchema { /// The summary's `max_tokens`; unset leaves the provider default. Env: /// `OPENHUMAN_CONTEXT_SUMMARIZER_MAX_OUTPUT_TOKENS`. summarizer_max_output_tokens: Option, + /// Verbatim tail an in-turn compaction keeps, in tokens; unset keeps + /// 20,000. Env: `OPENHUMAN_CONTEXT_KEEP_RECENT_TOKENS`. + keep_recent_tokens: Option, + /// Replace a tool result older than this many user turns with a one-line + /// note; unset or `0` keeps every result. Env: + /// `OPENHUMAN_CONTEXT_TOOL_RESULT_MAX_AGE_TURNS`. + tool_result_max_age_turns: Option, + /// Tools whose results never expire. Env: + /// `OPENHUMAN_CONTEXT_TOOL_RESULT_EXEMPT_TOOLS`. + tool_result_exempt_tools: Vec, + /// `all` or `current_turn`. Env: `OPENHUMAN_CONTEXT_REPLAY_REASONING`. + replay_reasoning: ReasoningReplaySchema, + /// Drop recorded tool declarations the host no longer offers. Env: + /// `OPENHUMAN_CONTEXT_PRUNE_RETIRED_TOOLS`. + prune_retired_tools: bool, prefer_markdown_tool_output: bool, compaction_enabled: bool, compaction_trigger_tokens: Option, @@ -107,6 +187,13 @@ enum CompactionStrategySchema { Summary, } +#[derive(schemars::JsonSchema)] +#[schemars(rename_all = "snake_case")] +enum ReasoningReplaySchema { + All, + CurrentTurn, +} + #[derive(schemars::JsonSchema)] #[schemars(rename_all = "snake_case")] enum ToolRenderingSchema { diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/context.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/context.rs index eabbf193fd1..be938a86b42 100644 --- a/crates/openhuman-core/src/config/schema/load/env_overlay/context.rs +++ b/crates/openhuman-core/src/config/schema/load/env_overlay/context.rs @@ -236,5 +236,106 @@ impl Config { ); } } + // `0` or an empty value clears a budget set in `config.toml`. + if let Some(val) = env.get("OPENHUMAN_CONTEXT_KEEP_RECENT_TOKENS") { + let budget = match val.trim() { + "" | "0" => Some(None), + raw => match raw.parse::() { + Ok(tokens) => Some(Some(tokens)), + Err(_) => { + tracing::warn!( + value = raw, + "[config] ignoring unparseable OPENHUMAN_CONTEXT_KEEP_RECENT_TOKENS" + ); + None + } + }, + }; + if let Some(budget) = budget { + self.context.keep_recent_tokens = budget; + self.record_env_override( + env, + "context.keep_recent_tokens", + &["OPENHUMAN_CONTEXT_KEEP_RECENT_TOKENS"], + ); + } + } + // `0` or an empty value switches expiry off again. + if let Some(val) = env.get("OPENHUMAN_CONTEXT_TOOL_RESULT_MAX_AGE_TURNS") { + let age = match val.trim() { + "" | "0" => Some(None), + raw => match raw.parse::() { + Ok(turns) => Some(Some(turns)), + Err(_) => { + tracing::warn!( + value = raw, + "[config] ignoring unparseable OPENHUMAN_CONTEXT_TOOL_RESULT_MAX_AGE_TURNS" + ); + None + } + }, + }; + if let Some(age) = age { + self.context.tool_result_max_age_turns = age; + self.record_env_override( + env, + "context.tool_result_max_age_turns", + &["OPENHUMAN_CONTEXT_TOOL_RESULT_MAX_AGE_TURNS"], + ); + } + } + if let Some(val) = env.get("OPENHUMAN_CONTEXT_TOOL_RESULT_EXEMPT_TOOLS") { + self.context.tool_result_exempt_tools = val + .split(',') + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(str::to_owned) + .collect(); + self.record_env_override( + env, + "context.tool_result_exempt_tools", + &["OPENHUMAN_CONTEXT_TOOL_RESULT_EXEMPT_TOOLS"], + ); + } + if let Some(val) = env.get("OPENHUMAN_CONTEXT_REPLAY_REASONING") { + let replay = match val.trim().to_ascii_lowercase().replace('-', "_").as_str() { + "" => None, + "all" => Some(crate::config::ReasoningReplay::All), + "current_turn" => Some(crate::config::ReasoningReplay::CurrentTurn), + _ => { + tracing::warn!( + value = %val.trim(), + "[config] ignoring unknown OPENHUMAN_CONTEXT_REPLAY_REASONING (all | current_turn)" + ); + None + } + }; + if let Some(replay) = replay { + self.context.replay_reasoning = replay; + self.record_env_override( + env, + "context.replay_reasoning", + &["OPENHUMAN_CONTEXT_REPLAY_REASONING"], + ); + } + } + if let Some(raw) = env.get("OPENHUMAN_CONTEXT_PRUNE_RETIRED_TOOLS") { + match super::classify_shell_hide_window(&raw) { + super::ShellHideWindowParse::Set(value) => { + self.context.prune_retired_tools = value; + self.record_env_override( + env, + "context.prune_retired_tools", + &["OPENHUMAN_CONTEXT_PRUNE_RETIRED_TOOLS"], + ); + } + super::ShellHideWindowParse::Unset => {} + super::ShellHideWindowParse::Unrecognized => { + tracing::warn!( + "[config] ignoring a non-boolean OPENHUMAN_CONTEXT_PRUNE_RETIRED_TOOLS" + ); + } + } + } } } 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 f7aaa17bc95..64e8141b074 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 @@ -293,3 +293,133 @@ fn summarizer_settings_read_from_the_context_table_beside_the_harness_settings() "{written}" ); } + +#[test] +fn keep_recent_tokens_defaults_to_unset_and_reads_from_the_context_table() { + assert_eq!(Config::default().context.keep_recent_tokens, None); + + let cfg: Config = toml::from_str("[context]\nkeep_recent_tokens = 12000\n").unwrap(); + assert_eq!(cfg.context.keep_recent_tokens, Some(12_000)); + let written = toml::to_string(&cfg.context).unwrap(); + assert!(written.contains("keep_recent_tokens = 12000"), "{written}"); +} + +#[test] +fn keep_recent_tokens_env_sets_clears_and_ignores_garbage() { + let mut cfg = Config::default(); + cfg.apply_env_overlay_with( + &HashMapEnv::new().with("OPENHUMAN_CONTEXT_KEEP_RECENT_TOKENS", " 12000 "), + ); + assert_eq!(cfg.context.keep_recent_tokens, Some(12_000)); + + cfg.apply_env_overlay_with( + &HashMapEnv::new().with("OPENHUMAN_CONTEXT_KEEP_RECENT_TOKENS", "plenty"), + ); + assert_eq!(cfg.context.keep_recent_tokens, Some(12_000)); + + // `0` or an empty value clears a budget set in `config.toml`. + cfg.apply_env_overlay_with( + &HashMapEnv::new().with("OPENHUMAN_CONTEXT_KEEP_RECENT_TOKENS", "0"), + ); + assert_eq!(cfg.context.keep_recent_tokens, None); +} + +#[test] +fn prompt_replay_options_default_to_todays_behaviour_and_read_from_the_context_table() { + use tinyagents_harness::reasoning_replay::ReasoningReplay; + let defaults = Config::default().context; + assert_eq!(defaults.tool_result_max_age_turns, None); + assert!(defaults.tool_result_exempt_tools.is_empty()); + assert_eq!(defaults.replay_reasoning, ReasoningReplay::All); + assert!(!defaults.prune_retired_tools); + + let cfg: Config = toml::from_str( + "[context]\n\ + tool_result_max_age_turns = 6\n\ + tool_result_exempt_tools = [\"tool_search\"]\n\ + replay_reasoning = \"current_turn\"\n\ + prune_retired_tools = true\n", + ) + .unwrap(); + assert_eq!(cfg.context.tool_result_max_age_turns, Some(6)); + assert_eq!(cfg.context.tool_result_exempt_tools, ["tool_search"]); + assert_eq!(cfg.context.replay_reasoning, ReasoningReplay::CurrentTurn); + assert!(cfg.context.prune_retired_tools); +} + +#[test] +fn prompt_replay_options_env_overlay_sets_clears_and_ignores_garbage() { + use tinyagents_harness::reasoning_replay::ReasoningReplay; + let mut cfg = Config::default(); + cfg.apply_env_overlay_with( + &HashMapEnv::new() + .with("OPENHUMAN_CONTEXT_TOOL_RESULT_MAX_AGE_TURNS", " 8 ") + .with( + "OPENHUMAN_CONTEXT_TOOL_RESULT_EXEMPT_TOOLS", + "tool_search, memory_recall ,", + ) + .with("OPENHUMAN_CONTEXT_REPLAY_REASONING", "Current-Turn") + .with("OPENHUMAN_CONTEXT_PRUNE_RETIRED_TOOLS", "on"), + ); + assert_eq!(cfg.context.tool_result_max_age_turns, Some(8)); + assert_eq!( + cfg.context.tool_result_exempt_tools, + ["tool_search", "memory_recall"] + ); + assert_eq!(cfg.context.replay_reasoning, ReasoningReplay::CurrentTurn); + assert!(cfg.context.prune_retired_tools); + + // Garbage leaves the earlier value alone. + cfg.apply_env_overlay_with( + &HashMapEnv::new() + .with("OPENHUMAN_CONTEXT_TOOL_RESULT_MAX_AGE_TURNS", "many") + .with("OPENHUMAN_CONTEXT_REPLAY_REASONING", "sometimes") + .with("OPENHUMAN_CONTEXT_PRUNE_RETIRED_TOOLS", "maybe"), + ); + assert_eq!(cfg.context.tool_result_max_age_turns, Some(8)); + assert_eq!(cfg.context.replay_reasoning, ReasoningReplay::CurrentTurn); + assert!(cfg.context.prune_retired_tools); + + // `0` switches expiry off again and `all` restores full replay. + cfg.apply_env_overlay_with( + &HashMapEnv::new() + .with("OPENHUMAN_CONTEXT_TOOL_RESULT_MAX_AGE_TURNS", "0") + .with("OPENHUMAN_CONTEXT_REPLAY_REASONING", "all") + .with("OPENHUMAN_CONTEXT_PRUNE_RETIRED_TOOLS", "off"), + ); + assert_eq!(cfg.context.tool_result_max_age_turns, None); + assert_eq!(cfg.context.replay_reasoning, ReasoningReplay::All); + assert!(!cfg.context.prune_retired_tools); +} + +#[test] +fn context_overrides_change_only_the_keys_they_set() { + use crate::config::ContextOverrides; + use tinyagents_harness::reasoning_replay::ReasoningReplay; + + let mut settings = Config::default().context; + settings.keep_recent_tokens = Some(9_000); + settings.tool_result_exempt_tools = vec!["kept".into()]; + let untouched = settings.clone(); + + ContextOverrides::default().apply_to(&mut settings); + assert_eq!( + toml::to_string(&settings).unwrap(), + toml::to_string(&untouched).unwrap(), + "no override set changes nothing" + ); + + ContextOverrides { + keep_recent_tokens: Some(12_000), + tool_result_max_age_turns: Some(5), + tool_result_exempt_tools: Some(vec!["tool_search".into()]), + replay_reasoning: Some(ReasoningReplay::CurrentTurn), + prune_retired_tools: Some(true), + } + .apply_to(&mut settings); + assert_eq!(settings.keep_recent_tokens, Some(12_000)); + assert_eq!(settings.tool_result_max_age_turns, Some(5)); + assert_eq!(settings.tool_result_exempt_tools, ["tool_search"]); + assert_eq!(settings.replay_reasoning, ReasoningReplay::CurrentTurn); + assert!(settings.prune_retired_tools); +} diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rs index c36dbe3b081..01d76d25ebf 100644 --- a/crates/openhuman-core/src/config/schema/mod.rs +++ b/crates/openhuman-core/src/config/schema/mod.rs @@ -123,7 +123,8 @@ pub use capability_providers::{CapabilityProviderConfig, CapabilityProviderTrust pub use channel_voice::{ChannelVoiceConfig, ChannelVoiceOverride, VoiceReplyMode}; pub(crate) use cli_overrides::set_cli_inference_overrides; pub use context::{ - CompactionSettings, CompactionStrategy, ContextConfig, ContextSettings, SummarizerSettings, + CompactionSettings, CompactionStrategy, ContextConfig, ContextOverrides, ContextSettings, + ReasoningReplay, SummarizerSettings, }; pub use cron::CronConfig; pub use dashboard::{DashboardConfig, DiagramViewerConfig, EventStreamConfig, ModelHealthConfig}; diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rs index 3bf43a04bd7..ac1cd704ce1 100644 --- a/crates/openhuman-embed/src/agent/build.rs +++ b/crates/openhuman-embed/src/agent/build.rs @@ -186,6 +186,7 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result openhuman_core::config::ContextSettings { + let tokio = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES) + .enable_all() + .build() + .unwrap(); + let test = tokio.spawn(async move { + let dir = tempfile::tempdir().unwrap(); + let config = openhuman_core::config::Config { + config_path: dir.path().join("config.toml"), + workspace_dir: dir.path().join("workspace"), + action_dir: dir.path().join("action"), + ..openhuman_core::config::Config::default() + }; + config.save().await.unwrap(); + let runtime = crate::runtime::RuntimeBuilder::new() + .config(config) + .services(openhuman_core::core::runtime::ServiceSet::none()) + .build() + .await + .expect("runtime"); + let agent = runtime.agent(spec).expect("agent builds"); + let context = agent.inner.config.context.clone(); + drop(agent); + drop(runtime); + context + }); + tokio.block_on(test).unwrap() +} + +#[test] +fn an_agent_with_context_overrides_hands_them_to_the_session_config() { + let context = built_context( + crate::AgentSpec::new("context-set") + .keep_recent_tokens(12_000) + .tool_result_max_age_turns(6) + .tool_result_exempt_tools(["tool_search"]) + .replay_reasoning(crate::ReasoningReplay::CurrentTurn) + .prune_retired_tools(true), + ); + assert_eq!(context.keep_recent_tokens, Some(12_000)); + assert_eq!(context.tool_result_max_age_turns, Some(6)); + assert_eq!(context.tool_result_exempt_tools, ["tool_search"]); + assert_eq!( + context.replay_reasoning, + crate::ReasoningReplay::CurrentTurn + ); + assert!(context.prune_retired_tools); +} + +#[test] +fn an_agent_with_no_context_overrides_behaves_as_before() { + let context = built_context(crate::AgentSpec::new("context-unset")); + assert_eq!(context.keep_recent_tokens, None); + assert_eq!(context.tool_result_max_age_turns, None); + assert!(context.tool_result_exempt_tools.is_empty()); + assert_eq!(context.replay_reasoning, crate::ReasoningReplay::All); + assert!(!context.prune_retired_tools); +} diff --git a/crates/openhuman-embed/src/agent/spec.rs b/crates/openhuman-embed/src/agent/spec.rs index 874d94233d4..4a7ef51c8a8 100644 --- a/crates/openhuman-embed/src/agent/spec.rs +++ b/crates/openhuman-embed/src/agent/spec.rs @@ -64,6 +64,7 @@ pub struct AgentSpec { >, memory: Option, tool_discovery: Option, + context: crate::ContextOverrides, subagents: Vec<(String, AgentDefinitionSpec)>, } @@ -194,6 +195,7 @@ impl AgentSpec { hooks: Default::default(), memory: None, tool_discovery: None, + context: Default::default(), subagents: Vec::new(), } } @@ -375,6 +377,55 @@ impl AgentSpec { self } + /// `[context] keep_recent_tokens` for this agent's sessions: the verbatim tail, in + /// tokens, an in-turn compaction keeps after its summary. Unset keeps the + /// config's value, which defaults to 20,000. + #[must_use] + pub fn keep_recent_tokens(mut self, tokens: u32) -> Self { + self.context.keep_recent_tokens = Some(tokens); + self + } + + /// `[context] tool_result_max_age_turns` for this agent's sessions: a tool result with + /// more than `turns` user turns after it is replaced by a one-line note. + /// Off unless set. Expiry and reasoning replay are recorded on each thread when it is created, so changing them never alters a thread that already exists. + #[must_use] + pub fn tool_result_max_age_turns(mut self, turns: u32) -> Self { + self.context.tool_result_max_age_turns = Some(turns); + self + } + + /// `[context] tool_result_exempt_tools` for this agent's sessions: tools whose results + /// never expire. Only read while a result age is set. + #[must_use] + pub fn tool_result_exempt_tools(mut self, tools: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.context.tool_result_exempt_tools = Some(tools.into_iter().map(Into::into).collect()); + self + } + + /// `[context] replay_reasoning` for this agent's sessions: whether requests replay every + /// turn's reasoning ([`ReasoningReplay::All`](crate::ReasoningReplay::All), + /// today's behaviour) or only the current turn's. The stored transcript + /// keeps every block either way. + #[must_use] + pub fn replay_reasoning(mut self, replay: crate::ReasoningReplay) -> Self { + self.context.replay_reasoning = Some(replay); + self + } + + /// `[context] prune_retired_tools` for this agent's sessions: drop a recorded tool + /// declaration the host no longer offers, live or deferred, instead of + /// carrying it forward for the life of the thread. + #[must_use] + pub fn prune_retired_tools(mut self, prune: bool) -> Self { + self.context.prune_retired_tools = Some(prune); + self + } + /// Binds the agent's memory: the memory agent id its turns are logged /// under and, optionally, its layout root. See [`MemoryBinding`]. #[must_use] @@ -552,6 +603,7 @@ impl AgentSpec { hooks: self.hooks, memory: self.memory, tool_discovery: self.tool_discovery, + context: self.context, subagents: self.subagents, } } @@ -585,6 +637,7 @@ pub(crate) struct AgentSpecParts { pub(crate) composio: Option, pub(crate) config_fn: Option, pub(crate) tool_discovery: Option, + pub(crate) context: crate::ContextOverrides, pub(crate) host_tools: Option, pub(crate) hooks: tinyagents_hooks::scope::HookScope< openhuman_core::agent::tinyagents::host::OpenHumanRunContext, diff --git a/crates/openhuman-embed/src/agent/spec_tests.rs b/crates/openhuman-embed/src/agent/spec_tests.rs index 196d229e843..ef788e0adb3 100644 --- a/crates/openhuman-embed/src/agent/spec_tests.rs +++ b/crates/openhuman-embed/src/agent/spec_tests.rs @@ -93,3 +93,28 @@ fn an_agent_spec_carries_tool_discovery_options_only_when_set() { let parts = AgentSpec::new("alpha").tool_discovery(wanted).into_parts(); assert_eq!(parts.tool_discovery, Some(wanted)); } + +#[test] +fn an_agent_spec_carries_context_overrides_only_when_set() { + assert_eq!( + AgentSpec::new("alpha").into_parts().context, + crate::ContextOverrides::default() + ); + let parts = AgentSpec::new("alpha") + .keep_recent_tokens(12_000) + .tool_result_max_age_turns(6) + .tool_result_exempt_tools(["tool_search"]) + .replay_reasoning(crate::ReasoningReplay::CurrentTurn) + .prune_retired_tools(true) + .into_parts(); + assert_eq!( + parts.context, + crate::ContextOverrides { + keep_recent_tokens: Some(12_000), + tool_result_max_age_turns: Some(6), + tool_result_exempt_tools: Some(vec!["tool_search".into()]), + replay_reasoning: Some(crate::ReasoningReplay::CurrentTurn), + prune_retired_tools: Some(true), + } + ); +} diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs index b4030d7cbb2..795524ea84a 100644 --- a/crates/openhuman-embed/src/lib.rs +++ b/crates/openhuman-embed/src/lib.rs @@ -79,6 +79,7 @@ pub fn current_turn_origin() -> Option { pub use openhuman_core::agent::tinyagents::discovery::DiscoveryOptions as ToolDiscoveryOptions; pub use openhuman_core::config::ComposioHostCredential; pub use openhuman_core::config::Config as RuntimeConfig; +pub use openhuman_core::config::{ContextOverrides, ReasoningReplay}; pub use openhuman_core::config::{SearchHostCredential, UnknownKeyedSearchProvider}; /// The exact ambient tenant, inherited across profile turns and their scoped tasks. pub use openhuman_core::core::runtime::{current_tenant, NoTenant, Tenant}; diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs index 8e7c32bfb1e..05a0ed94016 100644 --- a/crates/openhuman-embed/src/turn.rs +++ b/crates/openhuman-embed/src/turn.rs @@ -106,6 +106,7 @@ pub struct Turn { tools: Option, tool_env: Option>>, tool_discovery: Option, + context: crate::ContextOverrides, } impl Turn { @@ -140,6 +141,7 @@ impl Turn { trace_content: crate::observe::TraceContent::MetadataOnly, hooks: Default::default(), tool_discovery: None, + context: Default::default(), tools: None, tool_env: None, } @@ -439,6 +441,55 @@ impl Turn { self } + /// `[context] keep_recent_tokens` for the thread this turn creates: the verbatim tail, in + /// tokens, an in-turn compaction keeps after its summary. Unset keeps the + /// config's value, which defaults to 20,000. + #[must_use] + pub fn keep_recent_tokens(mut self, tokens: u32) -> Self { + self.context.keep_recent_tokens = Some(tokens); + self + } + + /// `[context] tool_result_max_age_turns` for the thread this turn creates: a tool result with + /// more than `turns` user turns after it is replaced by a one-line note. + /// Off unless set. A turn on an existing session id ignores the pinned options (expiry and reasoning replay): the thread keeps what it started with. + #[must_use] + pub fn tool_result_max_age_turns(mut self, turns: u32) -> Self { + self.context.tool_result_max_age_turns = Some(turns); + self + } + + /// `[context] tool_result_exempt_tools` for the thread this turn creates: tools whose results + /// never expire. Only read while a result age is set. + #[must_use] + pub fn tool_result_exempt_tools(mut self, tools: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.context.tool_result_exempt_tools = Some(tools.into_iter().map(Into::into).collect()); + self + } + + /// `[context] replay_reasoning` for the thread this turn creates: whether requests replay every + /// turn's reasoning ([`ReasoningReplay::All`](crate::ReasoningReplay::All), + /// today's behaviour) or only the current turn's. The stored transcript + /// keeps every block either way. + #[must_use] + pub fn replay_reasoning(mut self, replay: crate::ReasoningReplay) -> Self { + self.context.replay_reasoning = Some(replay); + self + } + + /// `[context] prune_retired_tools` for the thread this turn creates: drop a recorded tool + /// declaration the host no longer offers, live or deferred, instead of + /// carrying it forward for the life of the thread. + #[must_use] + pub fn prune_retired_tools(mut self, prune: bool) -> Self { + self.context.prune_retired_tools = Some(prune); + self + } + /// Pin this turn to a model id. pub fn model(mut self, model: impl Into) -> Self { self.request.model_override = Some(model.into()); @@ -583,6 +634,9 @@ struct AgentTurnOptions { /// The `tool_search` options a new thread starts with; see /// [`Turn::tool_discovery`]. tool_discovery: Option, + /// The `[context]` overrides for the session this turn runs; see + /// [`Turn::keep_recent_tokens`] and its siblings. + context: crate::ContextOverrides, /// The explicit per-turn values the core honours: live progress and the /// host environment (budget, depth, cancellation, hooks, tool-belt authority). chat_env: openhuman_core::agent_runs::agent_chat::AgentChatEnv, @@ -642,6 +696,7 @@ async fn dispatch( let ctx = std::sync::Arc::clone(rt.context()); let chat_env = options.chat_env; let tool_discovery = options.tool_discovery; + let context = options.context; let dispatch = openhuman_core::core::runtime::DispatchCtx::new(std::sync::Arc::clone(&ctx)); let turn: futures_box::BoxFuture<'_, Result> = @@ -656,6 +711,7 @@ async fn dispatch( if let Some(discovery) = tool_discovery { discovery.apply_to(&mut config.agent.tool_search); } + context.apply_to(&mut config.context); let target = match request.agent_id.as_deref().map(str::trim) { Some(id) if !id.is_empty() => AgentChatTarget::AgentId(id), _ => AgentChatTarget::Orchestrator, @@ -709,6 +765,7 @@ async fn dispatch( if let Some(discovery) = options.tool_discovery { discovery.apply_to(&mut config.agent.tool_search); } + options.context.apply_to(&mut config.context); let route = inference_route(&request); let host = options.tools.or_else(|| inner.composed_host_tools()); let target = AgentChatTarget::Definition { diff --git a/crates/openhuman-embed/src/turn_control.rs b/crates/openhuman-embed/src/turn_control.rs index 568a03478b3..49f14ec560b 100644 --- a/crates/openhuman-embed/src/turn_control.rs +++ b/crates/openhuman-embed/src/turn_control.rs @@ -410,6 +410,7 @@ impl Turn { tools: self.tools.take(), attachments: std::mem::take(&mut self.attachments), tool_discovery: self.tool_discovery.take(), + context: std::mem::take(&mut self.context), }; let dispatch = dispatch(self.target, self.request, self.seed.take(), usage, options); From 714a3bf3720c6e7cec882164b1346e8d75ca005a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 00:30:31 +0300 Subject: [PATCH 07/24] feat(search): compact result rendering and a page-contents cap Adds [search] compact_results (RenderOptions::compact via render_*_with) and contents_max_chars (ProviderConfig.contents_max_chars), both off by default, with env overlays. Co-authored-by: Medulla --- .../config/schema/load/env_overlay/search.rs | 41 ++++++++++++++++++ .../config/schema/load_env_overlay_tests.rs | 41 ++++++++++++++++++ .../src/config/schema/tools/search.rs | 14 ++++++ .../src/modules/search/config_tests.rs | 14 ++++++ .../openhuman-core/src/modules/search/mod.rs | 1 + crates/openhuman-core/src/search/render.rs | 43 +++++++++++++++++-- .../openhuman-core/src/search/render_tests.rs | 35 +++++++++++++++ crates/openhuman-core/src/search/tools.rs | 3 +- 8 files changed, 188 insertions(+), 4 deletions(-) diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs index a7b7cc9ce01..a5e011db735 100644 --- a/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs +++ b/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs @@ -402,6 +402,47 @@ impl Config { } } } + if let Some(raw) = env.get("OPENHUMAN_SEARCH_COMPACT_RESULTS") { + match super::classify_shell_hide_window(&raw) { + super::ShellHideWindowParse::Set(value) => { + self.search.compact_results = value; + self.record_env_override( + env, + "search.compact_results", + &["OPENHUMAN_SEARCH_COMPACT_RESULTS"], + ); + } + super::ShellHideWindowParse::Unset => {} + super::ShellHideWindowParse::Unrecognized => { + tracing::warn!( + "[config] ignoring a non-boolean OPENHUMAN_SEARCH_COMPACT_RESULTS" + ); + } + } + } + // `0` or an empty value removes a cap set in `config.toml`. + if let Some(raw) = env.get("OPENHUMAN_SEARCH_CONTENTS_MAX_CHARS") { + let cap = match raw.trim() { + "" | "0" => Some(None), + value => match value.parse::() { + Ok(chars) => Some(Some(chars)), + Err(_) => { + tracing::warn!( + "[config] ignoring unparseable OPENHUMAN_SEARCH_CONTENTS_MAX_CHARS" + ); + None + } + }, + }; + if let Some(cap) = cap { + self.search.contents_max_chars = cap; + self.record_env_override( + env, + "search.contents_max_chars", + &["OPENHUMAN_SEARCH_CONTENTS_MAX_CHARS"], + ); + } + } if let Some(t) = env.get_any(&["OPENHUMAN_SEARCH_TIMEOUT_SECS", "SEARCH_TIMEOUT_SECS"]) { if let Ok(n) = t.parse::() { if n > 0 { diff --git a/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs b/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs index c1abf603472..190e2c39011 100644 --- a/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs +++ b/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs @@ -662,3 +662,44 @@ fn env_overlay_inbound_debounce_applies_and_ignores_garbage() { cfg.apply_env_overlay_with(&HashMapEnv::new().with("OPENHUMAN_INBOUND_DEBOUNCE_ENABLED", "on")); assert!(cfg.inbound_debounce.enabled); } + +#[test] +fn search_compact_results_and_contents_cap_default_to_today_and_read_from_the_table() { + let defaults = Config::default().search; + assert!(!defaults.compact_results); + assert_eq!(defaults.contents_max_chars, None); + + let cfg: Config = + toml::from_str("[search]\ncompact_results = true\ncontents_max_chars = 1200\n").unwrap(); + assert!(cfg.search.compact_results); + assert_eq!(cfg.search.contents_max_chars, Some(1_200)); +} + +#[test] +fn search_compact_results_and_contents_cap_env_set_clear_and_ignore_garbage() { + let mut cfg = Config::default(); + cfg.apply_env_overlay_with( + &HashMapEnv::new() + .with("OPENHUMAN_SEARCH_COMPACT_RESULTS", "yes") + .with("OPENHUMAN_SEARCH_CONTENTS_MAX_CHARS", " 1200 "), + ); + assert!(cfg.search.compact_results); + assert_eq!(cfg.search.contents_max_chars, Some(1_200)); + + cfg.apply_env_overlay_with( + &HashMapEnv::new() + .with("OPENHUMAN_SEARCH_COMPACT_RESULTS", "sometimes") + .with("OPENHUMAN_SEARCH_CONTENTS_MAX_CHARS", "lots"), + ); + assert!(cfg.search.compact_results); + assert_eq!(cfg.search.contents_max_chars, Some(1_200)); + + // `0` removes the cap and `off` restores the default rendering. + cfg.apply_env_overlay_with( + &HashMapEnv::new() + .with("OPENHUMAN_SEARCH_COMPACT_RESULTS", "off") + .with("OPENHUMAN_SEARCH_CONTENTS_MAX_CHARS", "0"), + ); + assert!(!cfg.search.compact_results); + assert_eq!(cfg.search.contents_max_chars, None); +} diff --git a/crates/openhuman-core/src/config/schema/tools/search.rs b/crates/openhuman-core/src/config/schema/tools/search.rs index d60dda86551..80bdbb18b94 100644 --- a/crates/openhuman-core/src/config/schema/tools/search.rs +++ b/crates/openhuman-core/src/config/schema/tools/search.rs @@ -287,6 +287,18 @@ pub struct SearchConfig { #[serde(default = "default_search_timeout_secs")] pub timeout_secs: u64, + /// Render results compactly for the model: citations that repeat a listed + /// result are left out and a page's text is kept to 1,500 characters + /// instead of 500. Defaults to `false`. Env: `OPENHUMAN_SEARCH_COMPACT_RESULTS`. + #[serde(default)] + pub compact_results: bool, + + /// Cap, in characters, on each page an Exa contents call returns. Unset + /// asks for whole pages; the module lowers anything above 1,500 to 1,500. + /// Env: `OPENHUMAN_SEARCH_CONTENTS_MAX_CHARS` (`0` clears it). + #[serde(default)] + pub contents_max_chars: Option, + /// Brave Search key (direct route). #[serde(default)] pub brave: SearchEngineCredentials, @@ -345,6 +357,8 @@ impl Default for SearchConfig { presentation_provider: None, max_results: default_search_max_results(), timeout_secs: default_search_timeout_secs(), + compact_results: false, + contents_max_chars: None, brave: SearchEngineCredentials::default(), querit: SearchEngineCredentials::default(), exa: SearchEngineCredentials::default(), diff --git a/crates/openhuman-core/src/modules/search/config_tests.rs b/crates/openhuman-core/src/modules/search/config_tests.rs index 33b44a3d14d..4c5ac1479c1 100644 --- a/crates/openhuman-core/src/modules/search/config_tests.rs +++ b/crates/openhuman-core/src/modules/search/config_tests.rs @@ -235,3 +235,17 @@ async fn a_stored_key_keeps_the_public_endpoint() { assert_eq!(brave.credential.as_deref(), Some("stored-brave")); assert_eq!(brave.base_url, None); } + +#[tokio::test] +async fn the_contents_cap_reaches_every_provider_and_is_unset_by_default() { + let dir = tempfile::tempdir().unwrap(); + let mut config = config_in(dir.path()); + select(&mut config, &[("tavily", SearchProviderSettings::direct())]); + config.search.tavily.api_key = Some("test-secret".into()); + let payload = module_config(&config).await; + assert_eq!(payload.providers["tavily"].contents_max_chars, None); + + config.search.contents_max_chars = Some(1_200); + let payload = module_config(&config).await; + assert_eq!(payload.providers["tavily"].contents_max_chars, Some(1_200)); +} diff --git a/crates/openhuman-core/src/modules/search/mod.rs b/crates/openhuman-core/src/modules/search/mod.rs index 57e742c9741..eeb47ece585 100644 --- a/crates/openhuman-core/src/modules/search/mod.rs +++ b/crates/openhuman-core/src/modules/search/mod.rs @@ -91,6 +91,7 @@ fn provider_config(config: &Config, provider: &ResolvedProvider) -> ProviderConf ProviderRoute::Direct => direct_settings(config, provider.id), }; settings.enabled = provider.usable; + settings.contents_max_chars = config.search.contents_max_chars; settings } diff --git a/crates/openhuman-core/src/search/render.rs b/crates/openhuman-core/src/search/render.rs index f4fb522af7e..6b070e618c5 100644 --- a/crates/openhuman-core/src/search/render.rs +++ b/crates/openhuman-core/src/search/render.rs @@ -8,6 +8,7 @@ use serde_json::{json, Value}; use tinysearch_bus::labels::provider_label; +use tinysearch_bus::render::RenderOptions; use tinysearch_bus::{render as bus_render, ExecuteToolResponse, SearchStatus}; use tinytools::ToolResult; @@ -16,6 +17,16 @@ const METADATA_EXCERPT_CHARS: usize = 300; pub use tinysearch_bus::render::subject; +/// The rendering `[search] compact_results` asks for: the compact rendering +/// when on, the module's original output when off. +pub fn render_options(compact: bool) -> RenderOptions { + if compact { + RenderOptions::compact() + } else { + RenderOptions::default() + } +} + /// Build the tool result: text for the model, optional markdown, and the /// structured payload for the UI. pub fn render( @@ -23,12 +34,38 @@ pub fn render( subject: &str, max_results: usize, prefer_markdown: bool, +) -> ToolResult { + render_with( + response, + subject, + max_results, + prefer_markdown, + &RenderOptions::default(), + ) +} + +/// [`render`] with explicit [`RenderOptions`] for the model's text. +pub fn render_with( + response: &ExecuteToolResponse, + subject: &str, + max_results: usize, + prefer_markdown: bool, + options: &RenderOptions, ) -> ToolResult { let provider = provider_label(&response.provider); - let mut result = ToolResult::success(bus_render::render_text(response, subject, max_results)); + let mut result = ToolResult::success(bus_render::render_text_with( + response, + subject, + max_results, + options, + )); if prefer_markdown { - result.markdown_formatted = - Some(bus_render::render_markdown(response, subject, max_results)); + result.markdown_formatted = Some(bus_render::render_markdown_with( + response, + subject, + max_results, + options, + )); } result.metadata = Some(metadata(response, subject, &provider, max_results)); result diff --git a/crates/openhuman-core/src/search/render_tests.rs b/crates/openhuman-core/src/search/render_tests.rs index 01e521bfc37..77dfda7db23 100644 --- a/crates/openhuman-core/src/search/render_tests.rs +++ b/crates/openhuman-core/src/search/render_tests.rs @@ -123,3 +123,38 @@ fn model_text_is_the_bus_rendering_byte_for_byte() { Some(tinysearch_bus::render::render_markdown(&r, "q", 5).as_str()) ); } + +#[test] +fn compact_rendering_keeps_more_of_a_page_and_off_changes_nothing() { + let mut page = response(Some(Role::Contents)); + page.results[0].snippet = Some("z".repeat(3_000)); + + let plain = render(&page, "q", 5, false); + let off = render_with(&page, "q", 5, false, &render_options(false)); + assert_eq!( + off.output(), + plain.output(), + "compact off is the default rendering" + ); + assert_eq!(render_options(false), RenderOptions::default()); + + let compact = render_with(&page, "q", 5, false, &render_options(true)); + assert_eq!(render_options(true), RenderOptions::compact()); + let kept = |text: &str| text.matches('z').count(); + assert!(kept(&plain.output()) <= RenderOptions::default().contents_chars); + assert!(kept(&compact.output()) > kept(&plain.output())); + assert!(kept(&compact.output()) <= RenderOptions::compact().contents_chars); +} + +#[test] +fn compact_rendering_leaves_out_sources_that_repeat_a_listed_result() { + let mut repeated = response(Some(Role::Search)); + repeated.citations = vec![Citation { + url: "https://tokio.rs/select".into(), + title: Some("Tokio select".into()), + }]; + let plain = render(&repeated, "q", 5, false); + let compact = render_with(&repeated, "q", 5, false, &render_options(true)); + assert!(plain.output().contains("Sources:")); + assert!(!compact.output().contains("Sources:")); +} diff --git a/crates/openhuman-core/src/search/tools.rs b/crates/openhuman-core/src/search/tools.rs index 146fc824f73..2617e12f71c 100644 --- a/crates/openhuman-core/src/search/tools.rs +++ b/crates/openhuman-core/src/search/tools.rs @@ -308,11 +308,12 @@ impl Tool for TinySearchTool { results = response.results.len(), "[search][tool] completed" ); - Ok(super::render::render( + Ok(super::render::render_with( &response, &subject, max_results, options.prefer_markdown, + &super::render::render_options(config.search.compact_results), )) } Err(error) => { From aa067f4bcfd9b3344d84817c162a16add788b7a4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 00:49:44 +0300 Subject: [PATCH 08/24] docs(embed): regenerate the embed API docs and describe the search render options Co-authored-by: Medulla --- crates/openhuman-core/src/search/README.md | 9 +++ .../en/developing/embed/api-index.json | 68 +++++++++++-------- .../gitbooks/en/developing/embed/api-index.md | 4 ++ .../en/developing/embed/builder-setters.md | 59 ++++++++-------- llms-full.txt | 63 +++++++++-------- 5 files changed, 116 insertions(+), 87 deletions(-) diff --git a/crates/openhuman-core/src/search/README.md b/crates/openhuman-core/src/search/README.md index 79b3259de56..b115c99e3ff 100644 --- a/crates/openhuman-core/src/search/README.md +++ b/crates/openhuman-core/src/search/README.md @@ -113,6 +113,15 @@ each has its own message from `user_facing_error`. "citations"?, "fallback_from"?, "results":[...]}`, with excerpts capped at 300 chars, which the chat UI renders as a search card. +`render::render_with` takes the module's `RenderOptions` for the model text. +`[search] compact_results = true` (env `OPENHUMAN_SEARCH_COMPACT_RESULTS`) +selects `RenderOptions::compact()`: citations that repeat a listed result are +left out and a page's text keeps 1,500 chars instead of 500. It defaults to +`false`, the rendering above. `[search] contents_max_chars` (env +`OPENHUMAN_SEARCH_CONTENTS_MAX_CHARS`, `0` clears) asks Exa for at most that +many characters per page (`ProviderConfig::contents_max_chars`); unset asks for +whole pages. + ### Configuration and presentation Config lives in `[search]` (`config/schema/tools/search.rs`): `providers`, diff --git a/docs/gitbooks/en/developing/embed/api-index.json b/docs/gitbooks/en/developing/embed/api-index.json index 5c29f5df8d7..9651580fec7 100644 --- a/docs/gitbooks/en/developing/embed/api-index.json +++ b/docs/gitbooks/en/developing/embed/api-index.json @@ -37,6 +37,7 @@ "Config", "ConfigSource", "ConfigurationInfo", + "ContextOverrides", "ControllerSchema", "CoreAgent", "CoreBootMode", @@ -82,6 +83,7 @@ "McpAuthConfig", "McpServer", "MemoryBinding", + "MemoryBlockPrewarm", "MemoryBlockSpec", "ModelDefaults", "NoTenant", @@ -107,6 +109,7 @@ "Provider", "Provisioned", "ReasoningEffort", + "ReasoningReplay", "RelayAccepted", "RelayMessage", "RemoveAgent", @@ -140,6 +143,7 @@ "TokenSource", "Tool", "ToolAttachmentError", + "ToolDiscoveryOptions", "ToolExposure", "ToolGroups", "ToolPolicy", @@ -196,13 +200,13 @@ "name": "access", "signature": "pub fn access(mut self, access: Access) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 445 + "line": 460 }, { "name": "action_dir", "signature": "pub fn action_dir(mut self, dir: impl Into) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 390 + "line": 405 }, { "name": "agent_defaults", @@ -214,7 +218,7 @@ "name": "api_key", "signature": "pub fn api_key(mut self, key: impl Into) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 422 + "line": 437 }, { "name": "autonomy", @@ -226,25 +230,25 @@ "name": "backend_url", "signature": "pub fn backend_url(mut self, url: impl Into) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 432 + "line": 447 }, { "name": "boot_mode", "signature": "pub fn boot_mode(mut self, mode: CoreBootMode) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 410 + "line": 425 }, { "name": "config", "signature": "pub fn config(mut self, config: Config) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 562 + "line": 577 }, { "name": "config_source", "signature": "pub fn config_source(mut self, source: ConfigSource) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 398 + "line": 413 }, { "name": "configure_core_extensions", @@ -262,25 +266,25 @@ "name": "cron", "signature": "pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 257 + "line": 272 }, { "name": "cron_delivery", "signature": "pub fn cron_delivery( mut self, delivery: Arc, ) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 302 + "line": 317 }, { "name": "cron_job_handler", "signature": "pub fn cron_job_handler( mut self, kind: crate::cron::JobKind, handler: Arc, ) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 316 + "line": 331 }, { "name": "defer_services", "signature": "pub fn defer_services(mut self) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 480 + "line": 495 }, { "name": "definition_base", @@ -292,37 +296,37 @@ "name": "domains", "signature": "pub fn domains(mut self, domains: DomainSet) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 492 + "line": 507 }, { "name": "host_kind", "signature": "pub fn host_kind(mut self, host_kind: HostKind) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 509 + "line": 524 }, { "name": "learning", "signature": "pub fn learning(mut self, value: super::LearningSettings) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 252 + "line": 267 }, { "name": "listen", "signature": "pub fn listen(self, host: impl Into, port: u16) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 531 + "line": 546 }, { "name": "listen_host", "signature": "pub fn listen_host(mut self, host: impl Into) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 536 + "line": 551 }, { "name": "listen_port", "signature": "pub fn listen_port(mut self, port: u16) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 542 + "line": 557 }, { "name": "live_policy", @@ -334,7 +338,7 @@ "name": "max_agents", "signature": "pub fn max_agents(mut self, limit: usize) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 353 + "line": 368 }, { "name": "mcp_baseline", @@ -346,7 +350,7 @@ "name": "memory_engine", "signature": "pub fn memory_engine(mut self, engine: Arc) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 271 + "line": 286 }, { "name": "model_defaults", @@ -364,7 +368,7 @@ "name": "on_missing_agent", "signature": "pub fn on_missing_agent(mut self, opener: F) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 340 + "line": 355 }, { "name": "post_turn_hook", @@ -388,7 +392,7 @@ "name": "provider", "signature": "pub fn provider(mut self, provider: Provider) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 438 + "line": 453 }, { "name": "sandbox", @@ -400,7 +404,7 @@ "name": "secrets", "signature": "pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 247 + "line": 262 }, { "name": "security", @@ -408,6 +412,12 @@ "source": "crates/openhuman-embed/src/runtime/builder.rs", "line": 242 }, + { + "name": "security_judge", + "signature": "pub fn security_judge( mut self, value: openhuman_core::config::schema::SecurityJudgeRoute, ) -> Self", + "source": "crates/openhuman-embed/src/runtime/builder.rs", + "line": 254 + }, { "name": "server_launcher", "signature": "pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self", @@ -418,19 +428,19 @@ "name": "services", "signature": "pub fn services(mut self, services: ServiceSet) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 464 + "line": 479 }, { "name": "session", "signature": "pub fn session(mut self, session: Session) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 552 + "line": 567 }, { "name": "session_store", "signature": "pub fn session_store(mut self, provider: Arc) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 286 + "line": 301 }, { "name": "skills", @@ -448,13 +458,13 @@ "name": "token", "signature": "pub fn token(mut self, token: TokenSource) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 519 + "line": 534 }, { "name": "tool_groups", "signature": "pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 501 + "line": 516 }, { "name": "tool_hook", @@ -478,13 +488,13 @@ "name": "workspace", "signature": "pub fn workspace(mut self, workspace: Workspace) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 363 + "line": 378 }, { "name": "workspace_dir", "signature": "pub fn workspace_dir(mut self, dir: impl Into) -> Self", "source": "crates/openhuman-embed/src/runtime/builder.rs", - "line": 377 + "line": 392 } ], "capabilities": { diff --git a/docs/gitbooks/en/developing/embed/api-index.md b/docs/gitbooks/en/developing/embed/api-index.md index 87d97c39047..aa7f6ae01dc 100644 --- a/docs/gitbooks/en/developing/embed/api-index.md +++ b/docs/gitbooks/en/developing/embed/api-index.md @@ -40,6 +40,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe - [`Config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ConfigSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ConfigurationInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) +- [`ContextOverrides`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ControllerSchema`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`CoreAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`CoreBootMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) @@ -85,6 +86,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe - [`McpAuthConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`McpServer`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`MemoryBinding`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) +- [`MemoryBlockPrewarm`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`MemoryBlockSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ModelDefaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`NoTenant`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) @@ -110,6 +112,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe - [`Provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`Provisioned`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ReasoningEffort`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) +- [`ReasoningReplay`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`RelayAccepted`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`RelayMessage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`RemoveAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) @@ -143,6 +146,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe - [`TokenSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`Tool`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ToolAttachmentError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) +- [`ToolDiscoveryOptions`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ToolExposure`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ToolGroups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ToolPolicy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) diff --git a/docs/gitbooks/en/developing/embed/builder-setters.md b/docs/gitbooks/en/developing/embed/builder-setters.md index 5977721bad1..a2d5188df6a 100644 --- a/docs/gitbooks/en/developing/embed/builder-setters.md +++ b/docs/gitbooks/en/developing/embed/builder-setters.md @@ -4,52 +4,53 @@ Public consuming methods that return `Self`, extracted from the RuntimeBuilder implementations. Static host and weight presets, inspection methods and build/run methods are excluded. -- [`access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L445): `pub fn access(mut self, access: Access) -> Self` -- [`action_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L390): `pub fn action_dir(mut self, dir: impl Into) -> Self` +- [`access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L460): `pub fn access(mut self, access: Access) -> Self` +- [`action_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L405): `pub fn action_dir(mut self, dir: impl Into) -> Self` - [`agent_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L161): `pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self` -- [`api_key`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L422): `pub fn api_key(mut self, key: impl Into) -> Self` +- [`api_key`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L437): `pub fn api_key(mut self, key: impl Into) -> Self` - [`autonomy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L196): `pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self` -- [`backend_url`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L432): `pub fn backend_url(mut self, url: impl Into) -> Self` -- [`boot_mode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L410): `pub fn boot_mode(mut self, mode: CoreBootMode) -> Self` -- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L562): `pub fn config(mut self, config: Config) -> Self` -- [`config_source`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L398): `pub fn config_source(mut self, source: ConfigSource) -> Self` +- [`backend_url`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L447): `pub fn backend_url(mut self, url: impl Into) -> Self` +- [`boot_mode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L425): `pub fn boot_mode(mut self, mode: CoreBootMode) -> Self` +- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L577): `pub fn config(mut self, config: Config) -> Self` +- [`config_source`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L413): `pub fn config_source(mut self, source: ConfigSource) -> Self` - [`configure_core_extensions`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L451): `pub fn configure_core_extensions(self, configure: impl FnOnce(&Extensions)) -> Self` - [`controller_extension`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L463): `pub fn controller_extension(mut self, extension: ControllerExtension) -> Self` -- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L257): `pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self` -- [`cron_delivery`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L302): `pub fn cron_delivery( mut self, delivery: Arc, ) -> Self` -- [`cron_job_handler`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L316): `pub fn cron_job_handler( mut self, kind: crate::cron::JobKind, handler: Arc, ) -> Self` -- [`defer_services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L480): `pub fn defer_services(mut self) -> Self` +- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L272): `pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self` +- [`cron_delivery`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L317): `pub fn cron_delivery( mut self, delivery: Arc, ) -> Self` +- [`cron_job_handler`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L331): `pub fn cron_job_handler( mut self, kind: crate::cron::JobKind, handler: Arc, ) -> Self` +- [`defer_services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L495): `pub fn defer_services(mut self) -> Self` - [`definition_base`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L180): `pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self` -- [`domains`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L492): `pub fn domains(mut self, domains: DomainSet) -> Self` -- [`host_kind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L509): `pub fn host_kind(mut self, host_kind: HostKind) -> Self` -- [`learning`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L252): `pub fn learning(mut self, value: super::LearningSettings) -> Self` -- [`listen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L531): `pub fn listen(self, host: impl Into, port: u16) -> Self` -- [`listen_host`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L536): `pub fn listen_host(mut self, host: impl Into) -> Self` -- [`listen_port`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L542): `pub fn listen_port(mut self, port: u16) -> Self` +- [`domains`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L507): `pub fn domains(mut self, domains: DomainSet) -> Self` +- [`host_kind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L524): `pub fn host_kind(mut self, host_kind: HostKind) -> Self` +- [`learning`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L267): `pub fn learning(mut self, value: super::LearningSettings) -> Self` +- [`listen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L546): `pub fn listen(self, host: impl Into, port: u16) -> Self` +- [`listen_host`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L551): `pub fn listen_host(mut self, host: impl Into) -> Self` +- [`listen_port`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L557): `pub fn listen_port(mut self, port: u16) -> Self` - [`live_policy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L512): `pub fn live_policy(mut self, policy: Arc) -> Self` -- [`max_agents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L353): `pub fn max_agents(mut self, limit: usize) -> Self` +- [`max_agents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L368): `pub fn max_agents(mut self, limit: usize) -> Self` - [`mcp_baseline`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L191): `pub fn mcp_baseline(mut self, servers: impl IntoIterator) -> Self` -- [`memory_engine`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L271): `pub fn memory_engine(mut self, engine: Arc) -> Self` +- [`memory_engine`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L286): `pub fn memory_engine(mut self, engine: Arc) -> Self` - [`model_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L170): `pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self` - [`modules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/selection.rs#L155): `pub fn modules(mut self, modules: impl IntoIterator) -> Self` -- [`on_missing_agent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L340): `pub fn on_missing_agent(mut self, opener: F) -> Self` +- [`on_missing_agent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L355): `pub fn on_missing_agent(mut self, opener: F) -> Self` - [`post_turn_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L478): `pub fn post_turn_hook(mut self, hook: Arc) -> Self` - [`privacy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L206): `pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self` - [`prompt_screen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L221): `pub fn prompt_screen( mut self, value: openhuman_core::config::schema::PromptScreenConfig, ) -> Self` -- [`provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L438): `pub fn provider(mut self, provider: Provider) -> Self` +- [`provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L453): `pub fn provider(mut self, provider: Provider) -> Self` - [`sandbox`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L175): `pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self` -- [`secrets`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L247): `pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self` +- [`secrets`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L262): `pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self` - [`security`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L242): `pub fn security(mut self, value: openhuman_core::config::schema::SecurityModeConfig) -> Self` +- [`security_judge`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L254): `pub fn security_judge( mut self, value: openhuman_core::config::schema::SecurityJudgeRoute, ) -> Self` - [`server_launcher`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L492): `pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self` -- [`services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L464): `pub fn services(mut self, services: ServiceSet) -> Self` -- [`session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L552): `pub fn session(mut self, session: Session) -> Self` -- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L286): `pub fn session_store(mut self, provider: Arc) -> Self` +- [`services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L479): `pub fn services(mut self, services: ServiceSet) -> Self` +- [`session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L567): `pub fn session(mut self, session: Session) -> Self` +- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L301): `pub fn session_store(mut self, provider: Arc) -> Self` - [`skills`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L185): `pub fn skills(mut self, policy: super::SkillsPolicy) -> Self` - [`storage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L505): `pub fn storage(mut self, source: impl Into) -> Self` -- [`token`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L519): `pub fn token(mut self, token: TokenSource) -> Self` -- [`tool_groups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L501): `pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self` +- [`token`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L534): `pub fn token(mut self, token: TokenSource) -> Self` +- [`tool_groups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L516): `pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self` - [`tool_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L485): `pub fn tool_hook(mut self, hook: Arc>) -> Self` - [`tool_ranker`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L470): `pub fn tool_ranker(mut self, ranker: Arc) -> Self` - [`tool_rules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L201): `pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self` -- [`workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L363): `pub fn workspace(mut self, workspace: Workspace) -> Self` -- [`workspace_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L377): `pub fn workspace_dir(mut self, dir: impl Into) -> Self` +- [`workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L378): `pub fn workspace(mut self, workspace: Workspace) -> Self` +- [`workspace_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L392): `pub fn workspace_dir(mut self, dir: impl Into) -> Self` diff --git a/llms-full.txt b/llms-full.txt index 6edb1a3deaa..ad4a3f07e61 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -2845,55 +2845,56 @@ This matrix comes from the default-feature compiled capability-report example. R Public consuming methods that return `Self`, extracted from the RuntimeBuilder implementations. Static host and weight presets, inspection methods and build/run methods are excluded. -- [`access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L445): `pub fn access(mut self, access: Access) -> Self` -- [`action_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L390): `pub fn action_dir(mut self, dir: impl Into) -> Self` +- [`access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L460): `pub fn access(mut self, access: Access) -> Self` +- [`action_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L405): `pub fn action_dir(mut self, dir: impl Into) -> Self` - [`agent_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L161): `pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self` -- [`api_key`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L422): `pub fn api_key(mut self, key: impl Into) -> Self` +- [`api_key`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L437): `pub fn api_key(mut self, key: impl Into) -> Self` - [`autonomy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L196): `pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self` -- [`backend_url`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L432): `pub fn backend_url(mut self, url: impl Into) -> Self` -- [`boot_mode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L410): `pub fn boot_mode(mut self, mode: CoreBootMode) -> Self` -- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L562): `pub fn config(mut self, config: Config) -> Self` -- [`config_source`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L398): `pub fn config_source(mut self, source: ConfigSource) -> Self` +- [`backend_url`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L447): `pub fn backend_url(mut self, url: impl Into) -> Self` +- [`boot_mode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L425): `pub fn boot_mode(mut self, mode: CoreBootMode) -> Self` +- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L577): `pub fn config(mut self, config: Config) -> Self` +- [`config_source`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L413): `pub fn config_source(mut self, source: ConfigSource) -> Self` - [`configure_core_extensions`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L451): `pub fn configure_core_extensions(self, configure: impl FnOnce(&Extensions)) -> Self` - [`controller_extension`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L463): `pub fn controller_extension(mut self, extension: ControllerExtension) -> Self` -- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L257): `pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self` -- [`cron_delivery`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L302): `pub fn cron_delivery( mut self, delivery: Arc, ) -> Self` -- [`cron_job_handler`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L316): `pub fn cron_job_handler( mut self, kind: crate::cron::JobKind, handler: Arc, ) -> Self` -- [`defer_services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L480): `pub fn defer_services(mut self) -> Self` +- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L272): `pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self` +- [`cron_delivery`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L317): `pub fn cron_delivery( mut self, delivery: Arc, ) -> Self` +- [`cron_job_handler`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L331): `pub fn cron_job_handler( mut self, kind: crate::cron::JobKind, handler: Arc, ) -> Self` +- [`defer_services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L495): `pub fn defer_services(mut self) -> Self` - [`definition_base`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L180): `pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self` -- [`domains`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L492): `pub fn domains(mut self, domains: DomainSet) -> Self` -- [`host_kind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L509): `pub fn host_kind(mut self, host_kind: HostKind) -> Self` -- [`learning`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L252): `pub fn learning(mut self, value: super::LearningSettings) -> Self` -- [`listen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L531): `pub fn listen(self, host: impl Into, port: u16) -> Self` -- [`listen_host`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L536): `pub fn listen_host(mut self, host: impl Into) -> Self` -- [`listen_port`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L542): `pub fn listen_port(mut self, port: u16) -> Self` +- [`domains`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L507): `pub fn domains(mut self, domains: DomainSet) -> Self` +- [`host_kind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L524): `pub fn host_kind(mut self, host_kind: HostKind) -> Self` +- [`learning`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L267): `pub fn learning(mut self, value: super::LearningSettings) -> Self` +- [`listen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L546): `pub fn listen(self, host: impl Into, port: u16) -> Self` +- [`listen_host`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L551): `pub fn listen_host(mut self, host: impl Into) -> Self` +- [`listen_port`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L557): `pub fn listen_port(mut self, port: u16) -> Self` - [`live_policy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L512): `pub fn live_policy(mut self, policy: Arc) -> Self` -- [`max_agents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L353): `pub fn max_agents(mut self, limit: usize) -> Self` +- [`max_agents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L368): `pub fn max_agents(mut self, limit: usize) -> Self` - [`mcp_baseline`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L191): `pub fn mcp_baseline(mut self, servers: impl IntoIterator) -> Self` -- [`memory_engine`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L271): `pub fn memory_engine(mut self, engine: Arc) -> Self` +- [`memory_engine`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L286): `pub fn memory_engine(mut self, engine: Arc) -> Self` - [`model_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L170): `pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self` - [`modules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/selection.rs#L155): `pub fn modules(mut self, modules: impl IntoIterator) -> Self` -- [`on_missing_agent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L340): `pub fn on_missing_agent(mut self, opener: F) -> Self` +- [`on_missing_agent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L355): `pub fn on_missing_agent(mut self, opener: F) -> Self` - [`post_turn_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L478): `pub fn post_turn_hook(mut self, hook: Arc) -> Self` - [`privacy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L206): `pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self` - [`prompt_screen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L221): `pub fn prompt_screen( mut self, value: openhuman_core::config::schema::PromptScreenConfig, ) -> Self` -- [`provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L438): `pub fn provider(mut self, provider: Provider) -> Self` +- [`provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L453): `pub fn provider(mut self, provider: Provider) -> Self` - [`sandbox`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L175): `pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self` -- [`secrets`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L247): `pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self` +- [`secrets`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L262): `pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self` - [`security`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L242): `pub fn security(mut self, value: openhuman_core::config::schema::SecurityModeConfig) -> Self` +- [`security_judge`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L254): `pub fn security_judge( mut self, value: openhuman_core::config::schema::SecurityJudgeRoute, ) -> Self` - [`server_launcher`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L492): `pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self` -- [`services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L464): `pub fn services(mut self, services: ServiceSet) -> Self` -- [`session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L552): `pub fn session(mut self, session: Session) -> Self` -- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L286): `pub fn session_store(mut self, provider: Arc) -> Self` +- [`services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L479): `pub fn services(mut self, services: ServiceSet) -> Self` +- [`session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L567): `pub fn session(mut self, session: Session) -> Self` +- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L301): `pub fn session_store(mut self, provider: Arc) -> Self` - [`skills`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L185): `pub fn skills(mut self, policy: super::SkillsPolicy) -> Self` - [`storage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L505): `pub fn storage(mut self, source: impl Into) -> Self` -- [`token`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L519): `pub fn token(mut self, token: TokenSource) -> Self` -- [`tool_groups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L501): `pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self` +- [`token`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L534): `pub fn token(mut self, token: TokenSource) -> Self` +- [`tool_groups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L516): `pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self` - [`tool_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L485): `pub fn tool_hook(mut self, hook: Arc>) -> Self` - [`tool_ranker`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L470): `pub fn tool_ranker(mut self, ranker: Arc) -> Self` - [`tool_rules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L201): `pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self` -- [`workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L363): `pub fn workspace(mut self, workspace: Workspace) -> Self` -- [`workspace_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L377): `pub fn workspace_dir(mut self, dir: impl Into) -> Self` +- [`workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L378): `pub fn workspace(mut self, workspace: Workspace) -> Self` +- [`workspace_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L392): `pub fn workspace_dir(mut self, dir: impl Into) -> Self` # API index @@ -2938,6 +2939,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe - [`Config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ConfigSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ConfigurationInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) +- [`ContextOverrides`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ControllerSchema`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`CoreAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`CoreBootMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) @@ -2983,6 +2985,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe - [`McpAuthConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`McpServer`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`MemoryBinding`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) +- [`MemoryBlockPrewarm`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`MemoryBlockSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ModelDefaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`NoTenant`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) @@ -3008,6 +3011,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe - [`Provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`Provisioned`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ReasoningEffort`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) +- [`ReasoningReplay`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`RelayAccepted`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`RelayMessage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`RemoveAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) @@ -3041,6 +3045,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe - [`TokenSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`Tool`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ToolAttachmentError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) +- [`ToolDiscoveryOptions`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ToolExposure`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ToolGroups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) - [`ToolPolicy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) From 44dbae5208e6786ba0e05507938081404878242b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 02:54:13 +0300 Subject: [PATCH 09/24] test(session): the codec records replay options on the first new row once Co-authored-by: Medulla --- .../session_host/codec_adoption_tests.rs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs b/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs index ab77e2a7047..0c62cd91d74 100644 --- a/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs @@ -229,3 +229,42 @@ fn the_codec_records_discovery_options_on_the_first_new_row_only_once() { assert_eq!(rows[0], prior[0]); assert_eq!(DiscoveryOptions::recorded_in(&rows), Some(wanted)); } + +/// The turn that starts a thread records its history-replay options on the +/// first row it writes, beside any discovery record; later turns neither add +/// nor move it. +#[test] +fn the_codec_records_replay_options_on_the_first_new_row_only_once() { + use crate::agent::tinyagents::replay_pin::ReplayOptions; + use tinyagents_harness::reasoning_replay::ReasoningReplay; + + let options = |context| TranscriptTurnOptions { + request_id: Some("turn".into()), + thread_id: None, + stream: false, + resume: ResumeMode::Never, + context, + }; + let wanted = ReplayOptions { + tool_result_max_age_turns: Some(6), + tool_result_exempt_tools: vec!["tool_search".into()], + replay_reasoning: ReasoningReplay::CurrentTurn, + }; + let context = OpenHumanRunContext::new(); + context.session_sidecar.lock().unwrap().replay_record = Some(wanted.clone()); + let first = vec![Message::system("prompt"), Message::user("one")]; + let prior = OpenHumanTranscriptCodec + .reconcile(&[], &[], &first, &options(context)) + .unwrap(); + assert_eq!(ReplayOptions::recorded_in(&prior), Some(wanted.clone())); + assert!(prior[1].extra_metadata.is_none()); + + // A later turn records nothing and leaves the stored row as it was. + let mut next = first.clone(); + next.push(Message::assistant("done")); + let rows = OpenHumanTranscriptCodec + .reconcile(&prior, &first, &next, &options(OpenHumanRunContext::new())) + .unwrap(); + assert_eq!(rows[0], prior[0]); + assert_eq!(ReplayOptions::recorded_in(&rows), Some(wanted)); +} From ba2a32af6e6093fd51be79d6d38de65e72be3ee1 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 03:08:56 +0300 Subject: [PATCH 10/24] chore(deps): bump vendor/tinyagents to the epic-712 tip with TurnObservation::Setup Co-authored-by: Medulla --- vendor/tinyagents | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/tinyagents b/vendor/tinyagents index d8af36518c5..bdf8f4b7ae3 160000 --- a/vendor/tinyagents +++ b/vendor/tinyagents @@ -1 +1 @@ -Subproject commit d8af36518c5d9618993cd4e3debc234f30e8d272 +Subproject commit bdf8f4b7ae3c4a5707efe1ec96a0bbe51b9b3045 From 22df2f6ff51edd4e5ab8c1f20035e1e4c2749f7f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 03:48:37 +0300 Subject: [PATCH 11/24] fix(tool-output): exempt tool_search results from TinyJuice reshaping Co-authored-by: Medulla --- .../tinyagents/middleware/tool_output.rs | 13 +++++++- ...middleware_tool_output_compaction_tests.rs | 32 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs index 66a2118cccf..b097a92e635 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs @@ -109,7 +109,18 @@ pub(crate) const SAMPLING_TOOLS: &[&str] = &["get_tool_output_sample", "get_tool /// on is not cheaper, it is just wrong more quietly — but a host that wants a /// bound should bound the *catalogue* (serve fewer tools, or page the listing), /// not cut the bytes underneath it. -pub(crate) const DISCOVERY_TOOLS: &[&str] = &["mcp_list_tools", "mcp_list_servers"]; +/// +/// `tool_search` is the same kind of listing: its answer is the schemas of the +/// tools it found, and the harness's collapse step later rewrites a *used* +/// answer down to the schemas of the tools the run called. That rewrite +/// recognises the answer by its shape, so a tabulated, summarised or cut one +/// is skipped and keeps its full weight for the rest of the thread. The size +/// is bounded by the search itself (`[agent.tool_search] max_limit`). +pub(crate) const DISCOVERY_TOOLS: &[&str] = &[ + "mcp_list_tools", + "mcp_list_servers", + tinytools::TOOL_SEARCH_NAME, +]; /// Steps 1 (TinyJuice summary) + 2 (tokenjuice compaction) exemption: /// proposal tools (final-output contract, see [`COMPACTION_EXEMPT_TOOLS`]), diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_compaction_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_compaction_tests.rs index 5f5d01a81c0..efdd7829cca 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_compaction_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_compaction_tests.rs @@ -198,6 +198,38 @@ async fn get_tool_output_sample_is_compaction_exempt() { ); } +/// `tool_search` answers are the model's only way to learn a deferred tool's +/// schema, and the harness's collapse step rewrites a *used* result to those +/// schemas afterwards. Tabulating, summarising or cutting one beforehand +/// leaves collapse nothing it recognises, so the result is skipped. +#[tokio::test] +async fn tool_search_result_is_not_reshaped_by_tool_output_middleware() { + // The byte budget sits far below the payload, so a result that was not + // exempt from the cap would be cut as well as compacted. + let mw = ToolOutputMiddleware { + budget_bytes: 2_000, + ..compaction_enabled_mw() + }; + let payload = large_sample_response_json(40); + assert!(payload.len() > 2 * mw.budget_bytes); + let mut result = tool_result(tinytools::TOOL_SEARCH_NAME, &payload); + mw.after_tool( + &mut ctx(), + &(), + &invocation("search", tinytools::TOOL_SEARCH_NAME), + &mut result, + ) + .await + .unwrap(); + assert_eq!( + result_text(&result), + payload, + "a tool_search result must reach the transcript as the tool wrote it" + ); + assert!(is_compaction_exempt(tinytools::TOOL_SEARCH_NAME)); + assert!(is_truncation_exempt(tinytools::TOOL_SEARCH_NAME)); +} + #[tokio::test] async fn get_tool_contract_is_compaction_exempt() { let mw = compaction_enabled_mw(); From abc2c671b011980a3869ed179b25580be053379e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 03:48:37 +0300 Subject: [PATCH 12/24] fix(session): carry the tool_discovery pin into a compacted generation Co-authored-by: Medulla --- .../src/agent/session_host/codec.rs | 7 ++ .../session_host/codec_adoption_tests.rs | 69 +++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/crates/openhuman-core/src/agent/session_host/codec.rs b/crates/openhuman-core/src/agent/session_host/codec.rs index a7bcadd7368..326ebc24ef9 100644 --- a/crates/openhuman-core/src/agent/session_host/codec.rs +++ b/crates/openhuman-core/src/agent/session_host/codec.rs @@ -81,6 +81,13 @@ impl TranscriptCodec for OpenHumanTranscriptCodec { if let Some(options) = sidecar.discovery_record { options.record_on(&mut reconciled.rows, &reconciled.fresh); } + // A compaction writes the retained rows into a new generation, and the + // stored row that carried the record may not be among them (a + // refreshed system prompt, a summary). Carry the thread's options onto + // the new generation's first row. An ordinary turn keeps the row that + // holds them, so this does nothing there. Out-of-band compaction + // (`compact_bound_history`) and an in-turn one both come through here. + crate::agent::tinyagents::discovery::carry_forward(&prior, &mut reconciled.rows); // Likewise the history-replay options (result expiry, reasoning replay). if let Some(options) = &sidecar.replay_record { options.record_on(&mut reconciled.rows, &reconciled.fresh); diff --git a/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs b/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs index 0c62cd91d74..de50856d2fd 100644 --- a/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs @@ -268,3 +268,72 @@ fn the_codec_records_replay_options_on_the_first_new_row_only_once() { assert_eq!(rows[0], prior[0]); assert_eq!(ReplayOptions::recorded_in(&rows), Some(wanted)); } + +/// A compaction writes the retained rows into a new generation. Its first row +/// is the refreshed system prompt, so the stored row that carried the +/// discovery record is gone; the codec records it again. +#[test] +fn discovery_pin_survives_compaction() { + use crate::agent::tinyagents::discovery::DiscoveryOptions; + + let options = |context| TranscriptTurnOptions { + request_id: Some("turn".into()), + thread_id: None, + stream: false, + resume: ResumeMode::Never, + context, + }; + let wanted = DiscoveryOptions { + collapse_search_results: true, + ..DiscoveryOptions::TODAY + }; + let context = OpenHumanRunContext::new(); + context.session_sidecar.lock().unwrap().discovery_record = Some(wanted); + let history = vec![ + Message::system("prompt"), + Message::user("one"), + Message::assistant("first answer"), + Message::user("two"), + Message::assistant("second answer"), + ]; + let prior = OpenHumanTranscriptCodec + .reconcile(&[], &[], &history, &options(context)) + .unwrap(); + assert_eq!(DiscoveryOptions::recorded_in(&prior), Some(wanted)); + + // The compacted generation: a prompt with a freshly rendered memory block, + // a summary for the folded turn, and the verbatim tail. + let compacted = vec![ + Message::system("prompt with a fresh memory block"), + Message::user("summary of the first turn"), + history[3].clone(), + history[4].clone(), + ]; + let rows = OpenHumanTranscriptCodec + .reconcile( + &prior, + &history, + &compacted, + &options(OpenHumanRunContext::new()), + ) + .unwrap(); + assert_eq!(DiscoveryOptions::recorded_in(&rows), Some(wanted)); + assert!( + rows[1..].iter().all(|row| row.extra_metadata.is_none()), + "only the first row carries it" + ); + + // A thread that recorded nothing still records nothing. + let bare = OpenHumanTranscriptCodec + .reconcile(&[], &[], &history, &options(OpenHumanRunContext::new())) + .unwrap(); + let rows = OpenHumanTranscriptCodec + .reconcile( + &bare, + &history, + &compacted, + &options(OpenHumanRunContext::new()), + ) + .unwrap(); + assert_eq!(DiscoveryOptions::recorded_in(&rows), None); +} From 231fcaaba3511607d164780bc4f0eb3d22360b09 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 03:48:37 +0300 Subject: [PATCH 13/24] feat(embed): force tool_search options onto an existing thread Turn::tool_discovery_force runs the turn with the options and records them on a later row; the latest record wins. Default behaviour is unchanged. Co-authored-by: Medulla --- .../src/agent/tinyagents/discovery/mod.rs | 4 +- .../src/agent/tinyagents/discovery/pin.rs | 52 ++++++- .../agent/tinyagents/discovery/pin_tests.rs | 127 ++++++++++++++++++ .../openhuman-core/src/config/schema/agent.rs | 11 ++ crates/openhuman-embed/src/turn.rs | 58 +++++++- crates/openhuman-embed/src/turn_control.rs | 1 + crates/openhuman-embed/src/turn_tests.rs | 26 ++++ docs/gitbooks/en/developing/jev.md | 2 +- 8 files changed, 269 insertions(+), 12 deletions(-) diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs index 00bbed9e751..821b77053b7 100644 --- a/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs +++ b/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs @@ -243,8 +243,10 @@ impl ToolRanker for OverlapRanker { mod embedding_ranker; mod pin; +pub use pin::{ + carry_forward, resolve, DiscoveryOptions, ResolvedDiscovery, DISCOVERY_METADATA_KEY, +}; pub(crate) use pin::{record_metadata, recorded_metadata}; -pub use pin::{resolve, DiscoveryOptions, ResolvedDiscovery, DISCOVERY_METADATA_KEY}; pub use embedding_ranker::{ embedding_provider_is_usable, embedding_tool_ranker, embedding_tool_ranker_in, diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs index 000ab8d5558..be0a3744589 100644 --- a/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs +++ b/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs @@ -10,6 +10,11 @@ //! the thread's first transcript row. A resumed thread reads them back; the //! config and the embedder's options only choose them for the next thread. //! +//! A host can force new options onto a thread that exists +//! (`ToolSearchConfig::force_pin`): the turn records them on a later row and +//! the latest record wins. A compaction carries the record onto the first row +//! of the generation it opens ([`carry_forward`]). +//! //! A thread that records nothing (every thread written before this existed, //! and any thread created with today's behaviour) resolves to //! [`DiscoveryOptions::TODAY`], the harness defaults, whatever the config says @@ -99,11 +104,14 @@ impl DiscoveryOptions { } /// The value a thread recorded under `key` on its transcript `rows`, if any. +/// The latest record wins: a host that forces new options onto a thread +/// records them on a later row, since a stored row is never rewritten. pub(crate) fn recorded_metadata( rows: &[TranscriptMessage], key: &str, ) -> Option { rows.iter() + .rev() .filter_map(|row| row.extra_metadata.as_ref()) .find_map(|metadata| metadata.get(key)) .and_then(|value| serde_json::from_value(value.clone()).ok()) @@ -136,6 +144,26 @@ pub(crate) fn record_metadata( } } +/// Carries the options recorded on `prior` onto the first of `rows`, a +/// transcript about to open a compacted generation, when `rows` lost them. +/// Returns whether it recorded them. +/// +/// A compaction writes the retained rows into a fresh generation. The record +/// lives on a row, so it survives only if that row is retained unchanged; a +/// refreshed system prompt, or a summary standing in for the folded rows, +/// drops it, and the thread would fall back to today's behaviour. Writing it +/// onto the first row is free here: the generation is new, so no stored row +/// is rewritten. +pub fn carry_forward(prior: &[TranscriptMessage], rows: &mut [TranscriptMessage]) -> bool { + if DiscoveryOptions::recorded_in(rows).is_some() { + return false; + } + let Some(options) = DiscoveryOptions::recorded_in(prior) else { + return false; + }; + options.record_on(rows, &[true]) +} + impl Default for DiscoveryOptions { fn default() -> Self { Self::TODAY @@ -156,22 +184,38 @@ pub struct ResolvedDiscovery { /// Decides a session turn's options. /// /// `generation_start` is true for the turn that prepares the thread's first -/// prompt: it takes the options `config` asks for and records them. Every -/// other turn reads what `rows` recorded, or [`DiscoveryOptions::TODAY`]. +/// prompt: it takes the options `config` asks for and records them, unless +/// `rows` already record some (a compacted head whose prefix is prepared +/// again keeps its pin). Every other turn reads what `rows` recorded, or +/// [`DiscoveryOptions::TODAY`]. +/// +/// With `config.force_pin` a turn on an existing thread takes the options +/// `config` asks for instead, and records them when they differ from what the +/// thread runs with. A change back to [`DiscoveryOptions::TODAY`] is recorded +/// too: a thread with no record means today's behaviour only until it has one. pub fn resolve( config: &ToolSearchConfig, rows: &[TranscriptMessage], generation_start: bool, ) -> ResolvedDiscovery { - if generation_start { + let recorded = DiscoveryOptions::recorded_in(rows); + if generation_start && recorded.is_none() { let effective = DiscoveryOptions::from_config(config); return ResolvedDiscovery { effective, record: (effective != DiscoveryOptions::TODAY).then_some(effective), }; } + let current = recorded.unwrap_or(DiscoveryOptions::TODAY); + if config.force_pin { + let effective = DiscoveryOptions::from_config(config); + return ResolvedDiscovery { + effective, + record: (effective != current).then_some(effective), + }; + } ResolvedDiscovery { - effective: DiscoveryOptions::recorded_in(rows).unwrap_or(DiscoveryOptions::TODAY), + effective: current, record: None, } } diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/pin_tests.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/pin_tests.rs index fd2f73a69ba..dead4e8973f 100644 --- a/crates/openhuman-core/src/agent/tinyagents/discovery/pin_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/discovery/pin_tests.rs @@ -114,3 +114,130 @@ fn recording_touches_only_the_first_fresh_row_and_survives_serialization() { assert!(!options.record_on(&mut rows, &[false, false, false])); } + +fn forced(config: ToolSearchConfig) -> ToolSearchConfig { + ToolSearchConfig { + force_pin: true, + ..config + } +} + +/// `rows` of a thread that started with `options`. +fn thread_started_with(options: DiscoveryOptions) -> Vec { + let mut rows = vec![ + TranscriptMessage::system("prompt"), + TranscriptMessage::new("user", "hi"), + ]; + assert!(options.record_on(&mut rows, &[true, true])); + rows +} + +#[test] +fn forced_discovery_options_apply_to_existing_thread() { + let started_with = DiscoveryOptions { + promote_found_tools: false, + collapse_search_results: true, + ..DiscoveryOptions::TODAY + }; + let rows = thread_started_with(started_with); + let wanted = config(true, true, false, true); + + // Without the override the thread keeps what it started with. + assert_eq!(resolve(&wanted, &rows, false).effective, started_with); + + // With it, this turn runs with the new options and records them. + let resolved = resolve(&forced(wanted.clone()), &rows, false); + let new_options = DiscoveryOptions::from_config(&wanted); + assert_eq!(resolved.effective, new_options); + assert_eq!(resolved.record, Some(new_options)); + + // Recorded on a later row, they are what every later turn reads back. + let mut rows = rows; + rows.push(TranscriptMessage::new("user", "next")); + assert!(new_options.record_on(&mut rows, &[false, false, true])); + assert_eq!(DiscoveryOptions::recorded_in(&rows), Some(new_options)); + assert_eq!(resolve(&wanted, &rows, false).effective, new_options); +} + +#[test] +fn forcing_todays_behaviour_replaces_a_recorded_pin() { + let rows = thread_started_with(DiscoveryOptions { + collapse_search_results: true, + ..DiscoveryOptions::TODAY + }); + let resolved = resolve(&forced(ToolSearchConfig::default()), &rows, false); + assert_eq!(resolved.effective, DiscoveryOptions::TODAY); + assert_eq!( + resolved.record, + Some(DiscoveryOptions::TODAY), + "today's behaviour must be written down, or the old pin would win" + ); +} + +#[test] +fn forcing_what_the_thread_already_runs_with_records_nothing() { + let wanted = config(false, false, true, true); + let rows = thread_started_with(DiscoveryOptions::from_config(&wanted)); + let resolved = resolve(&forced(wanted), &rows, false); + assert_eq!(resolved.record, None); + + // A thread that recorded nothing already runs with today's behaviour. + let legacy = vec![TranscriptMessage::system("prompt")]; + assert_eq!( + resolve(&forced(ToolSearchConfig::default()), &legacy, false).record, + None + ); +} + +#[test] +fn the_latest_record_on_a_thread_wins() { + let first = DiscoveryOptions { + collapse_search_results: true, + ..DiscoveryOptions::TODAY + }; + let second = DiscoveryOptions { + compact_search_results: true, + ..DiscoveryOptions::TODAY + }; + let mut rows = thread_started_with(first); + rows.push(TranscriptMessage::new("user", "later")); + assert!(second.record_on(&mut rows, &[false, false, true])); + assert_eq!(DiscoveryOptions::recorded_in(&rows), Some(second)); +} + +#[test] +fn a_prompt_that_already_records_its_options_keeps_them_when_it_is_prepared_again() { + let started_with = DiscoveryOptions { + collapse_search_results: true, + ..DiscoveryOptions::TODAY + }; + let rows = thread_started_with(started_with); + let resolved = resolve(&ToolSearchConfig::default(), &rows, true); + assert_eq!(resolved.effective, started_with); + assert_eq!(resolved.record, None); +} + +#[test] +fn compaction_carries_the_record_onto_the_first_row_of_the_new_generation() { + let options = DiscoveryOptions { + collapse_search_results: true, + ..DiscoveryOptions::TODAY + }; + let prior = thread_started_with(options); + let mut next = vec![ + TranscriptMessage::system("refreshed prompt"), + TranscriptMessage::new("user", "summary"), + ]; + assert!(carry_forward(&prior, &mut next)); + assert_eq!(DiscoveryOptions::recorded_in(&next), Some(options)); + assert!(next[1].extra_metadata.is_none()); + + // Already there, or nothing to carry: nothing is rewritten. + let before = next.clone(); + assert!(!carry_forward(&prior, &mut next)); + assert_eq!(next, before); + let mut bare = vec![TranscriptMessage::system("prompt")]; + assert!(!carry_forward(&[TranscriptMessage::system("p")], &mut bare)); + assert!(bare[0].extra_metadata.is_none()); + assert!(!carry_forward(&prior, &mut [])); +} diff --git a/crates/openhuman-core/src/config/schema/agent.rs b/crates/openhuman-core/src/config/schema/agent.rs index d1312549748..32de0cd49c5 100644 --- a/crates/openhuman-core/src/config/schema/agent.rs +++ b/crates/openhuman-core/src/config/schema/agent.rs @@ -350,6 +350,16 @@ pub struct ToolSearchConfig { /// Retarget a call a model buries inside a pseudo `tool_call` / `call_tool` /// wrapper at the real tool it names. Defaults to `true`. pub repair_tool_call_wrapper: bool, + /// Apply the four options above to a thread that already exists, not only + /// to the thread this session creates. The session then runs the turn with + /// them and records them on the thread, where every later turn reads them + /// back; a thread that already runs with exactly these options records + /// nothing. An embedding host sets it per turn with + /// `Turn::tool_discovery_force`, which is why it is neither read from the + /// config file nor written to it. + #[serde(skip)] + #[schemars(skip)] + pub force_pin: bool, } impl Default for ToolSearchConfig { @@ -364,6 +374,7 @@ impl Default for ToolSearchConfig { compact_search_results: false, collapse_search_results: false, repair_tool_call_wrapper: true, + force_pin: false, } } } diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs index 05a0ed94016..5a780a734d1 100644 --- a/crates/openhuman-embed/src/turn.rs +++ b/crates/openhuman-embed/src/turn.rs @@ -106,6 +106,7 @@ pub struct Turn { tools: Option, tool_env: Option>>, tool_discovery: Option, + tool_discovery_force: bool, context: crate::ContextOverrides, } @@ -141,6 +142,7 @@ impl Turn { trace_content: crate::observe::TraceContent::MetadataOnly, hooks: Default::default(), tool_discovery: None, + tool_discovery_force: false, context: Default::default(), tools: None, tool_env: None, @@ -438,6 +440,29 @@ impl Turn { #[must_use] pub fn tool_discovery(mut self, options: crate::ToolDiscoveryOptions) -> Self { self.tool_discovery = Some(options); + self.tool_discovery_force = false; + self + } + + /// Like [`tool_discovery`](Self::tool_discovery), but also for a thread + /// that already exists. + /// + /// The turn runs with `options` and records them on the thread, the way + /// the turn that creates a thread does, so later turns keep them without + /// being forced again. A thread that already runs with exactly these + /// options records nothing, so a host can force on every turn at no cost. + /// This is how a host applies a change to the threads it already has: a + /// rollout to all threads, not only to new ones. Forcing the options that + /// equal today's behaviour ([`ToolDiscoveryOptions::TODAY`](crate::ToolDiscoveryOptions::TODAY)) + /// is a change like any other and takes a thread off its earlier pin. + /// + /// The thread's earlier turns keep the bytes they were sent with; the + /// provider's cached prefix is lost once, at the turn that changes the + /// options. + #[must_use] + pub fn tool_discovery_force(mut self, options: crate::ToolDiscoveryOptions) -> Self { + self.tool_discovery = Some(options); + self.tool_discovery_force = true; self } @@ -634,6 +659,9 @@ struct AgentTurnOptions { /// The `tool_search` options a new thread starts with; see /// [`Turn::tool_discovery`]. tool_discovery: Option, + /// Whether they also apply to a thread that exists; see + /// [`Turn::tool_discovery_force`]. + tool_discovery_force: bool, /// The `[context]` overrides for the session this turn runs; see /// [`Turn::keep_recent_tokens`] and its siblings. context: crate::ContextOverrides, @@ -696,6 +724,7 @@ async fn dispatch( let ctx = std::sync::Arc::clone(rt.context()); let chat_env = options.chat_env; let tool_discovery = options.tool_discovery; + let tool_discovery_force = options.tool_discovery_force; let context = options.context; let dispatch = openhuman_core::core::runtime::DispatchCtx::new(std::sync::Arc::clone(&ctx)); @@ -708,9 +737,11 @@ async fn dispatch( .load_config() .await .map_err(|raw| CoreError::from_rpc_string(AGENT_CHAT, raw))?; - if let Some(discovery) = tool_discovery { - discovery.apply_to(&mut config.agent.tool_search); - } + apply_tool_discovery( + &mut config.agent.tool_search, + tool_discovery, + tool_discovery_force, + ); context.apply_to(&mut config.context); let target = match request.agent_id.as_deref().map(str::trim) { Some(id) if !id.is_empty() => AgentChatTarget::AgentId(id), @@ -762,9 +793,11 @@ async fn dispatch( agent_chat_reply_for_controlled, AgentChatTarget, }; let mut config = inner.config.clone(); - if let Some(discovery) = options.tool_discovery { - discovery.apply_to(&mut config.agent.tool_search); - } + apply_tool_discovery( + &mut config.agent.tool_search, + options.tool_discovery, + options.tool_discovery_force, + ); options.context.apply_to(&mut config.context); let route = inference_route(&request); let host = options.tools.or_else(|| inner.composed_host_tools()); @@ -927,6 +960,19 @@ pub fn absolute(dir: impl AsRef) -> std::io::Result { Ok(std::env::current_dir()?.join(dir)) } +/// Writes a turn's `tool_search` options into the config its session reads, +/// with the instruction to apply them to an existing thread when `force`. +fn apply_tool_discovery( + config: &mut openhuman_core::config::schema::ToolSearchConfig, + options: Option, + force: bool, +) { + if let Some(options) = options { + options.apply_to(config); + config.force_pin = force; + } +} + #[cfg(test)] #[path = "turn_tests.rs"] mod tests; diff --git a/crates/openhuman-embed/src/turn_control.rs b/crates/openhuman-embed/src/turn_control.rs index 49f14ec560b..20115b5d605 100644 --- a/crates/openhuman-embed/src/turn_control.rs +++ b/crates/openhuman-embed/src/turn_control.rs @@ -410,6 +410,7 @@ impl Turn { tools: self.tools.take(), attachments: std::mem::take(&mut self.attachments), tool_discovery: self.tool_discovery.take(), + tool_discovery_force: std::mem::take(&mut self.tool_discovery_force), context: std::mem::take(&mut self.context), }; let dispatch = dispatch(self.target, self.request, self.seed.take(), usage, options); diff --git a/crates/openhuman-embed/src/turn_tests.rs b/crates/openhuman-embed/src/turn_tests.rs index a76277ce6e8..744d16a4f1e 100644 --- a/crates/openhuman-embed/src/turn_tests.rs +++ b/crates/openhuman-embed/src/turn_tests.rs @@ -355,3 +355,29 @@ async fn runtime_tool_events_preserve_order_and_discard_tool_payloads() { assert!(!serde_json::to_string(&event).unwrap().contains(private)); } } + +/// A turn's `tool_search` options reach the session's config, and only a +/// forced turn asks for them to apply to a thread that already exists. +#[test] +fn a_forced_discovery_turn_asks_for_the_options_on_existing_threads() { + use openhuman_core::config::schema::ToolSearchConfig; + + let wanted = crate::ToolDiscoveryOptions { + collapse_search_results: true, + ..crate::ToolDiscoveryOptions::TODAY + }; + + let mut untouched = ToolSearchConfig::default(); + apply_tool_discovery(&mut untouched, None, true); + assert_eq!(untouched, ToolSearchConfig::default()); + + let mut new_threads = ToolSearchConfig::default(); + apply_tool_discovery(&mut new_threads, Some(wanted), false); + assert!(new_threads.collapse_search_results); + assert!(!new_threads.force_pin); + + let mut every_thread = ToolSearchConfig::default(); + apply_tool_discovery(&mut every_thread, Some(wanted), true); + assert!(every_thread.collapse_search_results); + assert!(every_thread.force_pin); +} diff --git a/docs/gitbooks/en/developing/jev.md b/docs/gitbooks/en/developing/jev.md index 7fa18fc5d4a..f27f12ffd55 100644 --- a/docs/gitbooks/en/developing/jev.md +++ b/docs/gitbooks/en/developing/jev.md @@ -102,7 +102,7 @@ repair_tool_call_wrapper = true # retarget a call buried in a `tool_call` wrap - `max_limit`: the most matches a single search returns, however many the model asks for. `top_k` is clamped to it. Override per launch with `OPENHUMAN_TOOL_SEARCH_MAX_LIMIT`. - `promote_found_tools`, `compact_search_results`, `collapse_search_results`, `repair_tool_call_wrapper`: how found tools reach the prompt and how their results are stored. The defaults are today's behaviour. Override per launch with `OPENHUMAN_TOOL_SEARCH_PROMOTE_FOUND_TOOLS`, `OPENHUMAN_TOOL_SEARCH_COMPACT_SEARCH_RESULTS`, `OPENHUMAN_TOOL_SEARCH_COLLAPSE_SEARCH_RESULTS` and `OPENHUMAN_TOOL_SEARCH_REPAIR_TOOL_CALL_WRAPPER` (`1/0`, `true/false`, `yes/no`, `on/off`). -These four change the bytes of a thread's prompt (the provider's cached prefix), so a session does not apply them to a thread that is already running. The session that creates a thread takes the values in force then and, when they differ from today's behaviour, records them on the thread's first transcript row (`tool_discovery` in the row's `extra_metadata`). Every later turn reads the record back; a thread with no record keeps today's behaviour. Changing the config, or an embedder's options, therefore reaches new threads only. An embedder sets the options per agent with `AgentSpec::tool_discovery(ToolDiscoveryOptions)` and for the thread one turn creates with `Turn::tool_discovery(ToolDiscoveryOptions)`. +These four change the bytes of a thread's prompt (the provider's cached prefix), so a session does not apply them to a thread that is already running. The session that creates a thread takes the values in force then and, when they differ from today's behaviour, records them on the thread's first transcript row (`tool_discovery` in the row's `extra_metadata`). Every later turn reads the record back; a thread with no record keeps today's behaviour. Changing the config, or an embedder's options, therefore reaches new threads only. An embedder sets the options per agent with `AgentSpec::tool_discovery(ToolDiscoveryOptions)` and for the thread one turn creates with `Turn::tool_discovery(ToolDiscoveryOptions)`. A host that wants a change to reach threads that already exist (a rollout to all threads) uses `Turn::tool_discovery_force(ToolDiscoveryOptions)` instead: the turn runs with the options and records them on a later row of the thread (the latest record wins), so later turns keep them; a thread that already runs with exactly those options records nothing, so forcing on every turn is free. A compaction, in a turn or out of band, carries the record onto the first row of the generation it opens, so a pinned thread keeps its options after it compacts. `tool_search` results are exempt from TinyJuice reshaping (compaction, summary and the byte cap), so the collapse step above always sees them whole. Without an embedding provider, or without a credential for the selected route, tool search falls back to BM25 automatically. `auto` and `jev` therefore cost nothing extra when no credential is set. A setup with no TinyHumans account needs an embedding provider that does not depend on one (for example `memory.embedding_provider = "custom:"`) and a TypeSafe or OpenRouter key. From fae7aaac1d12513cd7670bbe8ed54603dd329d23 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 04:03:42 +0300 Subject: [PATCH 14/24] feat(observe): report turn-setup phases through TurnObservation::Setup Agent open, transcript resume, prompt refresh and the memory block each report their duration and outcome to the turn's observer before the first model request. A memory block that missed its deadline is Skipped and a failed read is Failed. SetupPhase and SetupOutcome are re-exported from openhuman_embed::observe. Co-authored-by: Medulla --- .../src/agent/session_host/mod.rs | 1 + .../runtime_session/memory_block.rs | 14 +- .../session_host/runtime_session/prelude.rs | 11 ++ .../session_host/runtime_session_turn.rs | 18 ++- .../src/agent/session_host/setup_report.rs | 34 ++++ .../agent/session_host/setup_report_tests.rs | 76 +++++++++ .../src/agent_runs/agent_chat/session_turn.rs | 38 +++-- crates/openhuman-embed/src/observe.rs | 2 +- .../openhuman-embed/tests/observed_turns.rs | 2 + crates/openhuman-embed/tests/setup_phases.rs | 152 ++++++++++++++++++ 10 files changed, 327 insertions(+), 21 deletions(-) create mode 100644 crates/openhuman-core/src/agent/session_host/setup_report.rs create mode 100644 crates/openhuman-core/src/agent/session_host/setup_report_tests.rs create mode 100644 crates/openhuman-embed/tests/setup_phases.rs diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rs index f4dcd28867a..241cc111814 100644 --- a/crates/openhuman-core/src/agent/session_host/mod.rs +++ b/crates/openhuman-core/src/agent/session_host/mod.rs @@ -45,6 +45,7 @@ mod live_tools; mod runtime; mod runtime_session; mod session_key; +pub(crate) mod setup_report; pub(crate) mod stop_policy; mod types; 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 182eb597870..6f9449e6956 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 @@ -53,12 +53,14 @@ use std::sync::Arc; use std::time::Instant; +use tinyagents_harness::observability::turn_observer::{SetupOutcome, SetupPhase}; use tinyagents_runtime::{PrefixSnapshot, SessionStateView, TranscriptCodec, TurnPreparation}; use tinyinference_llm::message::Message; use tinymemory_tools::layout::identity::ResolvedIdentity; use super::super::types::OpenHumanSessionHost; use super::OpenHumanTurnPrelude; +use crate::agent::session_host::setup_report::reported; use crate::memory::lifecycle::memory_block as render; pub(crate) use crate::memory::lifecycle::memory_block::MEMORY_BLOCK_MARKER; @@ -237,7 +239,17 @@ impl OpenHumanTurnPrelude { None }; let block = match reason { - Some(reason) => match self.block_for_generation(max_tokens, reason).await { + Some(reason) => match reported( + SetupPhase::MemoryBlock, + self.block_for_generation(max_tokens, reason), + |rendered| match rendered { + RenderedBlock::Failed => SetupOutcome::Failed, + RenderedBlock::Deferred => SetupOutcome::Skipped, + _ => SetupOutcome::Completed, + }, + ) + .await + { RenderedBlock::Block(block) => Some(block), RenderedBlock::Ready(block) => block, RenderedBlock::Empty => None, diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs index 063c3fcd7d7..1404f1a5265 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs @@ -1,6 +1,8 @@ //! Host-specific model/tool/prompt preparation for one runtime turn. use super::*; +use crate::agent::session_host::setup_report::{reported, result_outcome}; +use tinyagents_harness::observability::turn_observer::SetupPhase; impl OpenHumanTurnPrelude { #[allow(clippy::type_complexity)] @@ -77,6 +79,15 @@ impl OpenHumanTurnPrelude { /// (`prompt_refresh.rs`) renders it here too, so an unchanged prompt /// compares equal to the one its transcript recorded. pub(super) async fn cold_prompt_prefix(&self) -> Result { + reported( + SetupPhase::PromptRefresh, + self.render_prompt_prefix(), + result_outcome, + ) + .await + } + + async fn render_prompt_prefix(&self) -> Result { let flow_archetype_text = super::prompt::flow_archetype_text(self, true).await?; let connected_identities_md = crate::integrations::render_connected_identities_async(&self.dispatch_ctx()).await; diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs index 9e2e95e7104..5ba1564b790 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs @@ -1,9 +1,14 @@ use anyhow::Result; +use tinyagents_harness::observability::turn_observer::SetupPhase; use tinyagents_runtime::{ResumeMode, SessionTurnRequest, TurnOptions}; use tinyinference_llm::message::Message; use crate::agent::{ - message_convert::user_message_from_text, session_host::types::OpenHumanSessionHost, + message_convert::user_message_from_text, + session_host::{ + setup_report::{reported, result_outcome}, + types::OpenHumanSessionHost, + }, tinyagents::host::OpenHumanRunContext, }; @@ -179,10 +184,13 @@ impl OpenHumanSessionHost { .runtime_session .as_mut() .expect("runtime session initialized"); - let resumed = runtime - .resume(&options) - .await - .map_err(|error| anyhow::anyhow!(error.to_string()))?; + let resumed = reported( + SetupPhase::TranscriptResume, + runtime.resume(&options), + result_outcome, + ) + .await + .map_err(|error| anyhow::anyhow!(error.to_string()))?; if resumed.loaded { let recorded_tools = runtime.recorded_tools().cloned(); if let Some(prelude) = self diff --git a/crates/openhuman-core/src/agent/session_host/setup_report.rs b/crates/openhuman-core/src/agent/session_host/setup_report.rs new file mode 100644 index 00000000000..e59d8f97ebe --- /dev/null +++ b/crates/openhuman-core/src/agent/session_host/setup_report.rs @@ -0,0 +1,34 @@ +//! Reports the steps a turn runs before its first model request to the host's +//! observer (`TurnObservation::Setup`), so a host can see which step cost the +//! time. Reporting is a no-op when no observer is scoped around the turn. + +use std::future::Future; +use std::time::Instant; + +use tinyagents_harness::observability::turn_observer::{report_setup, SetupOutcome, SetupPhase}; + +/// Runs `work`, then reports `phase` with how long it took and what +/// `outcome_of` makes of its result. +pub(crate) async fn reported( + phase: SetupPhase, + work: impl Future, + outcome_of: impl FnOnce(&T) -> SetupOutcome, +) -> T { + let started = Instant::now(); + let result = work.await; + report_setup(phase, started.elapsed(), outcome_of(&result)); + result +} + +/// `Completed` for `Ok`, `Failed` for `Err`. +pub(crate) fn result_outcome(result: &Result) -> SetupOutcome { + if result.is_ok() { + SetupOutcome::Completed + } else { + SetupOutcome::Failed + } +} + +#[cfg(test)] +#[path = "setup_report_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/agent/session_host/setup_report_tests.rs b/crates/openhuman-core/src/agent/session_host/setup_report_tests.rs new file mode 100644 index 00000000000..a381d75e7b8 --- /dev/null +++ b/crates/openhuman-core/src/agent/session_host/setup_report_tests.rs @@ -0,0 +1,76 @@ +use std::sync::{Arc, Mutex}; + +use tinyagents_harness::observability::turn_observer::{ + with_observer, Observer, ObserverScope, SetupOutcome, SetupPhase, TraceContent, TurnObservation, +}; + +use super::*; + +#[derive(Default)] +struct Recorder(Mutex>); + +impl Observer for Recorder { + fn on_event(&self, event: &TurnObservation) { + self.0.lock().unwrap().push(event.clone()); + } +} + +async fn observed(work: impl Future) -> (T, Vec) { + let recorder = Arc::new(Recorder::default()); + let scope = ObserverScope::new(recorder.clone(), TraceContent::MetadataOnly); + let out = with_observer(scope, work).await; + let events = recorder.0.lock().unwrap().clone(); + (out, events) +} + +#[tokio::test] +async fn a_scoped_observer_hears_each_phase_with_its_outcome_and_elapsed_time() { + let (_, events) = observed(async { + reported( + SetupPhase::PromptRefresh, + async { tokio::time::sleep(std::time::Duration::from_millis(20)).await }, + |_| SetupOutcome::Completed, + ) + .await; + reported( + SetupPhase::MemoryBlock, + async { Err::<(), &str>("down") }, + result_outcome, + ) + .await + .unwrap_err(); + reported(SetupPhase::MemoryBlock, async {}, |_| SetupOutcome::Skipped).await; + }) + .await; + + let shape: Vec<_> = events + .iter() + .map(|event| match event { + TurnObservation::Setup { + phase, + failed, + skipped, + duration_ms, + .. + } => (phase.as_str(), *failed, *skipped, *duration_ms >= 20), + other => panic!("only setup phases are reported here: {other:?}"), + }) + .collect(); + assert_eq!( + shape, + vec![ + ("prompt_refresh", false, false, true), + ("memory_block", true, false, false), + ("memory_block", false, true, false), + ] + ); +} + +#[tokio::test] +async fn reporting_without_a_scoped_observer_returns_the_result_untouched() { + let value = reported(SetupPhase::AgentOpen, async { 7 }, |_| { + SetupOutcome::Completed + }) + .await; + assert_eq!(value, 7); +} diff --git a/crates/openhuman-core/src/agent_runs/agent_chat/session_turn.rs b/crates/openhuman-core/src/agent_runs/agent_chat/session_turn.rs index ff9bec00e38..fb6cea9df8d 100644 --- a/crates/openhuman-core/src/agent_runs/agent_chat/session_turn.rs +++ b/crates/openhuman-core/src/agent_runs/agent_chat/session_turn.rs @@ -1,9 +1,11 @@ //! Agent chat turns with the full tool-using harness. use super::envelope::AgentChatReply; +use crate::agent::session_host::setup_report::{reported, result_outcome}; use crate::agent::OpenHumanSessionHost; use crate::config::Config; use crate::core::Outcome; +use tinyagents_harness::observability::turn_observer::SetupPhase; use super::guards::{ effective_agent_chat_origin, enforce_user_prompt_or_reject, grant_turn_cwd, @@ -544,13 +546,17 @@ pub(super) async fn agent_chat_reply_for_inner( "[inference] agent_chat rooting turn tools at cwd={}", root.display() ); - let mut agent = build_turn_agent( - &turn_ctx, - &scoped, - &target, - turn_session_id, - temperature, - turn_model_source.clone(), + let mut agent = reported( + SetupPhase::AgentOpen, + build_turn_agent( + &turn_ctx, + &scoped, + &target, + turn_session_id, + temperature, + turn_model_source.clone(), + ), + result_outcome, ) .await .map_err(anyhow::Error::msg)?; @@ -560,13 +566,17 @@ pub(super) async fn agent_chat_reply_for_inner( agent.set_workspace_descriptor(Some(tinytools::WorkspaceDescriptor::new(root.clone()))); agent } - None => build_turn_agent( - &turn_ctx, - config, - &target, - turn_session_id, - temperature, - turn_model_source, + None => reported( + SetupPhase::AgentOpen, + build_turn_agent( + &turn_ctx, + config, + &target, + turn_session_id, + temperature, + turn_model_source, + ), + result_outcome, ) .await .map_err(anyhow::Error::msg)?, diff --git a/crates/openhuman-embed/src/observe.rs b/crates/openhuman-embed/src/observe.rs index e30e083083e..136145d7332 100644 --- a/crates/openhuman-embed/src/observe.rs +++ b/crates/openhuman-embed/src/observe.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use tinyagents_harness::observability::turn_observer::{self, Observer, ObserverScope}; pub use tinyagents_harness::observability::turn_observer::{ - ObservedUsage, TraceContent, TurnObservation, + ObservedUsage, SetupOutcome, SetupPhase, TraceContent, TurnObservation, }; /// Sanitized failure classification; no controller or provider error text. diff --git a/crates/openhuman-embed/tests/observed_turns.rs b/crates/openhuman-embed/tests/observed_turns.rs index 229937b4393..b4fb1e7ad81 100644 --- a/crates/openhuman-embed/tests/observed_turns.rs +++ b/crates/openhuman-embed/tests/observed_turns.rs @@ -175,6 +175,8 @@ fn model_and_tool_observations_capture_payloads_only_with_consent() { TurnObservation::Model {run_id,..} => Some(run_id) == terminal[0].1.as_ref(), TurnObservation::ModelDispatch {run_id,..} => Some(run_id) == terminal[0].1.as_ref(), TurnObservation::Tool {run_id,..} => run_id == &terminal[0].1, + // Setup precedes the run, so it has no run id to correlate. + TurnObservation::Setup {..} => true, })); assert_eq!(models[1].0.as_deref(),Some("actual-model")); assert_eq!(models[1].1.as_deref(),Some("stop")); diff --git a/crates/openhuman-embed/tests/setup_phases.rs b/crates/openhuman-embed/tests/setup_phases.rs new file mode 100644 index 00000000000..68a9acefff7 --- /dev/null +++ b/crates/openhuman-embed/tests/setup_phases.rs @@ -0,0 +1,152 @@ +//! The steps a turn runs before its first model request are reported to the +//! host observer as `TurnObservation::Setup`, in the order they ran, so a +//! host can split its setup time into what each step cost. +//! +//! One `#[test]` because a runtime claims a process-wide slot, and the host +//! engine it installs is process-wide too. + +mod common; + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use common::{offline_config, provider, runtime, stub_backend}; +use openhuman_embed::memory::api::conformance::ReferenceEngine; +use openhuman_embed::memory::LearnParams; +use openhuman_embed::observe::{observe_turn, SetupPhase, TraceContent, TurnObservation}; +use openhuman_embed::{ + Access, AgentDefinitionSpec, AgentSpec, MemoryBinding, MemoryBlockSpec, Provider, Runtime, + Workspace, +}; +use tinyagents_session::port::InMemorySessionStores; + +const ROOT: &str = "team:acme"; +const TURN_BUDGET: Duration = Duration::from_secs(120); + +#[derive(Default)] +struct Records { + events: Mutex>, +} + +impl openhuman_embed::observe::TurnObserver for Records { + fn on_event(&self, event: &TurnObservation) { + self.events.lock().unwrap().push(event.clone()); + } + fn on_turn(&self, _: &openhuman_embed::observe::TurnTrace<'_>) {} +} + +/// What each observation was, in order: a setup phase by its stable name, or +/// `model` for a model call. Tool and dispatch events are not under test. +fn timeline(records: &Records) -> Vec<(&'static str, bool, bool)> { + records + .events + .lock() + .unwrap() + .iter() + .filter_map(|event| match event { + TurnObservation::Setup { + phase, + failed, + skipped, + .. + } => Some((phase.as_str(), *failed, *skipped)), + TurnObservation::Model { .. } => Some(("model", false, false)), + _ => None, + }) + .collect() +} + +#[test] +fn setup_phases_are_reported_in_order() { + runtime().block_on(async { + tokio::spawn(async move { + let backend = stub_backend().await; + let mut config = offline_config(); + config.modules.allow_download = false; + let runtime = Runtime::builder() + .config(config) + .workspace(Workspace::stateless()) + .backend_url(backend.uri()) + .session_store(Arc::new(InMemorySessionStores::new())) + .memory_engine(Arc::new(ReferenceEngine::new())) + .build() + .await + .expect("a stateless runtime over the reference engine"); + let params: LearnParams = + serde_json::from_value(serde_json::json!({"text": "A fact worth a block"})) + .expect("learn params"); + runtime + .memory(ROOT) + .expect("the tenant's memory") + .learn(params) + .await + .expect("a learning"); + + let model = provider("ok").await; + let agent = runtime + .agent( + AgentSpec::new("setup-reporter") + .provider( + Provider::openai_compatible(format!("{}/v1", model.uri()), "sk-test") + .model("setup-model"), + ) + .access(Access::readonly()) + .definition( + AgentDefinitionSpec::new() + .bare_prompt("You report setup.") + .refresh_prompt_on_resume(true) + .memory_block(MemoryBlockSpec { max_tokens: 400 }), + ) + .memory(MemoryBinding::new("setup-reporter").root(ROOT)), + ) + .expect("the agent instantiates"); + + // A cold turn on a new thread opens the agent, resumes nothing, + // renders the prompt and then the memory block, all before the + // model is called. + let cold = Arc::new(Records::default()); + tokio::time::timeout( + TURN_BUDGET, + observe_turn( + cold.clone(), + TraceContent::MetadataOnly, + "setup-thread", + "hello", + agent.turn("hello").session("setup-thread").send(), + ), + ) + .await + .expect("the turn finishes") + .expect("the turn succeeds"); + assert_eq!( + timeline(&cold), + vec![ + ("agent_open", false, false), + ("transcript_resume", false, false), + ("prompt_refresh", false, false), + ("memory_block", false, false), + ("model", false, false), + ] + ); + assert!( + cold.events.lock().unwrap().iter().any(|event| matches!( + event, + TurnObservation::Setup { + phase: SetupPhase::MemoryBlock, + .. + } + )), + "hosts match on the phase enum the facade re-exports" + ); + + runtime + .remove_agent("setup-reporter") + .await + .expect("removed"); + drop(agent); + drop(runtime); + }) + .await + .expect("the test task"); + }); +} From d1bec9e8e9c1e079001e48f4293a49b18d661492 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 04:03:56 +0300 Subject: [PATCH 15/24] docs(embed): describe the setup observations in OBSERVERS.md Co-authored-by: Medulla --- crates/openhuman-embed/OBSERVERS.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/openhuman-embed/OBSERVERS.md b/crates/openhuman-embed/OBSERVERS.md index 3be6ba09547..7d7f7f94672 100644 --- a/crates/openhuman-embed/OBSERVERS.md +++ b/crates/openhuman-embed/OBSERVERS.md @@ -47,6 +47,15 @@ including raw provider errors. Unknown per-model charges stay `None`. Terminal `LastTurnUsage` retains the core cost-source classification, which can distinguish provider charges from catalogue estimates. +`TurnObservation::Setup` reports a step the turn ran before its first model +request, in the order the steps ran: `SetupPhase::AgentOpen`, +`TranscriptResume`, `PromptRefresh` and `MemoryBlock`, each with its duration +in milliseconds and whether it failed or was skipped (a memory block that +missed its `memory_block_deadline_ms`). A step the turn did not need (no +resume on a new thread, no refresh on a prompt that stays) reports nothing. +Setup events carry no text or identifiers, and `run_id` is usually `None` +because the run has not started; correlate by order within the observed turn. + The terminal callback runs after the supplied dispatch future completes, including its cleanup, and handles failures that have no `TurnOutcome`. Dropping the entire future cannot promise a terminal callback; use the turn cancellation From c1e99945f1066770efceea69e1a49ca08d53a155 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 04:09:20 +0300 Subject: [PATCH 16/24] fix(session): carry the context replay pin into a compacted generation Mirrors discovery::carry_forward for the [context] options pinned by replay_pin, so a thread keeps its result expiry and reasoning replay after compaction drops the row that recorded them. Co-authored-by: Medulla --- .../src/agent/session_host/codec.rs | 1 + .../session_host/codec_adoption_tests.rs | 71 +++++++++++++++++++ .../src/agent/tinyagents/replay_pin.rs | 20 ++++++ 3 files changed, 92 insertions(+) diff --git a/crates/openhuman-core/src/agent/session_host/codec.rs b/crates/openhuman-core/src/agent/session_host/codec.rs index 326ebc24ef9..3c599f9de77 100644 --- a/crates/openhuman-core/src/agent/session_host/codec.rs +++ b/crates/openhuman-core/src/agent/session_host/codec.rs @@ -92,6 +92,7 @@ impl TranscriptCodec for OpenHumanTranscriptCodec { if let Some(options) = &sidecar.replay_record { options.record_on(&mut reconciled.rows, &reconciled.fresh); } + crate::agent::tinyagents::replay_pin::carry_forward(&prior, &mut reconciled.rows); attach_text_dialect_rounds( &mut reconciled.rows, &reconciled.fresh, diff --git a/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs b/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs index de50856d2fd..caf1d6b0e6b 100644 --- a/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs @@ -337,3 +337,74 @@ fn discovery_pin_survives_compaction() { .unwrap(); assert_eq!(DiscoveryOptions::recorded_in(&rows), None); } + +/// The history-replay pin rides the same compaction path as the discovery pin: +/// a thread created with expiry off but reasoning limited to the current turn +/// keeps both after a compacted generation drops the row that recorded them, +/// instead of falling back to whatever `[context]` says now. +#[test] +fn replay_pin_survives_compaction() { + use crate::agent::tinyagents::replay_pin::ReplayOptions; + use tinyagents_harness::reasoning_replay::ReasoningReplay; + + let options = |context| TranscriptTurnOptions { + request_id: Some("turn".into()), + thread_id: None, + stream: false, + resume: ResumeMode::Never, + context, + }; + let wanted = ReplayOptions { + replay_reasoning: ReasoningReplay::CurrentTurn, + ..ReplayOptions::TODAY + }; + let context = OpenHumanRunContext::new(); + context.session_sidecar.lock().unwrap().replay_record = Some(wanted.clone()); + let history = vec![ + Message::system("prompt"), + Message::user("one"), + Message::assistant("first answer"), + Message::user("two"), + Message::assistant("second answer"), + ]; + let prior = OpenHumanTranscriptCodec + .reconcile(&[], &[], &history, &options(context)) + .unwrap(); + assert_eq!(ReplayOptions::recorded_in(&prior), Some(wanted.clone())); + + // The compacted generation: a prompt with a freshly rendered memory block, + // a summary for the folded turn, and the verbatim tail. + let compacted = vec![ + Message::system("prompt with a fresh memory block"), + Message::user("summary of the first turn"), + history[3].clone(), + history[4].clone(), + ]; + let rows = OpenHumanTranscriptCodec + .reconcile( + &prior, + &history, + &compacted, + &options(OpenHumanRunContext::new()), + ) + .unwrap(); + assert_eq!(ReplayOptions::recorded_in(&rows), Some(wanted)); + assert!( + rows[1..].iter().all(|row| row.extra_metadata.is_none()), + "only the first row carries it" + ); + + // A thread that recorded nothing still records nothing. + let bare = OpenHumanTranscriptCodec + .reconcile(&[], &[], &history, &options(OpenHumanRunContext::new())) + .unwrap(); + let rows = OpenHumanTranscriptCodec + .reconcile( + &bare, + &history, + &compacted, + &options(OpenHumanRunContext::new()), + ) + .unwrap(); + assert_eq!(ReplayOptions::recorded_in(&rows), None); +} diff --git a/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs b/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs index ac222d93184..55ebf2eccb0 100644 --- a/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs +++ b/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs @@ -7,6 +7,10 @@ //! options (`discovery/pin.rs` is the model). A resumed thread reads them back; //! the config and the embedder's options only choose them for the next thread. //! +//! A compaction carries the record onto the first row of the generation it +//! opens ([`carry_forward`]), so a thread keeps its options after the row that +//! held them is folded away. +//! //! A thread that records nothing (every thread written before this existed, //! and any thread created with today's behaviour) resolves to //! [`ReplayOptions::TODAY`] whatever the config says now. @@ -92,6 +96,22 @@ impl ReplayOptions { } } +/// Carries the options recorded on `prior` onto the first of `rows`, a +/// transcript about to open a compacted generation, when `rows` lost them. +/// Returns whether it recorded them. See `discovery::carry_forward`: the +/// record lives on a row, and a refreshed system prompt or a summary standing +/// in for the folded rows drops it. The generation is new, so writing onto its +/// first row rewrites no stored row. +pub fn carry_forward(prior: &[TranscriptMessage], rows: &mut [TranscriptMessage]) -> bool { + if ReplayOptions::recorded_in(rows).is_some() { + return false; + } + let Some(options) = ReplayOptions::recorded_in(prior) else { + return false; + }; + options.record_on(rows, &[true]) +} + impl Default for ReplayOptions { fn default() -> Self { Self::TODAY From d1877f9f412d0e8ed0c516e1e1bfcf2fbefeefb9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 04:22:32 +0300 Subject: [PATCH 17/24] fix(session): keep a recorded replay pin on a generation-start turn replay_pin::resolve let the config override a pin the rows already record when the turn prepared the thread's first prompt again (a compacted head). Mirror the recorded.is_none() guard in discovery::resolve. Co-authored-by: Medulla --- .../src/agent/tinyagents/replay_pin.rs | 11 +++++++---- .../src/agent/tinyagents/replay_pin_tests.rs | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs b/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs index 55ebf2eccb0..608c3e92f4a 100644 --- a/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs +++ b/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs @@ -131,20 +131,23 @@ pub struct ResolvedReplay { /// Decides a session turn's options. /// /// `generation_start` is true for the turn that prepares the thread's first -/// prompt: it takes the options `config` asks for and records them. Every -/// other turn reads what `rows` recorded, or [`ReplayOptions::TODAY`]. +/// prompt: it takes the options `config` asks for and records them, unless +/// `rows` already record some (a compacted head whose prefix is prepared +/// again keeps its pin). Every other turn reads what `rows` recorded, or +/// [`ReplayOptions::TODAY`]. pub fn resolve( config: &ContextSettings, rows: &[TranscriptMessage], generation_start: bool, ) -> ResolvedReplay { - if generation_start { + let recorded = ReplayOptions::recorded_in(rows); + if generation_start && recorded.is_none() { let effective = ReplayOptions::from_config(config); let record = (effective != ReplayOptions::TODAY).then(|| effective.clone()); return ResolvedReplay { effective, record }; } ResolvedReplay { - effective: ReplayOptions::recorded_in(rows).unwrap_or(ReplayOptions::TODAY), + effective: recorded.unwrap_or(ReplayOptions::TODAY), record: None, } } diff --git a/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs b/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs index 7785ac3a644..3a0fac43c35 100644 --- a/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs @@ -88,6 +88,24 @@ fn a_resumed_thread_keeps_what_it_recorded_whatever_the_config_says_now() { assert_eq!(resumed.record, None); } +#[test] +fn a_generation_start_over_recorded_rows_keeps_the_recorded_pin() { + // A compacted head whose prefix is prepared again is a generation-start + // turn, but its rows still record the thread's options. + let started_with = + ReplayOptions::from_config(&settings(None, &[], ReasoningReplay::CurrentTurn)); + let mut rows = vec![ + TranscriptMessage::system("prompt"), + TranscriptMessage::new("user", "hi"), + ]; + assert!(started_with.record_on(&mut rows, &[true, true])); + + let now = settings(Some(6), &["a"], ReasoningReplay::All); + let resolved = resolve(&now, &rows, true); + assert_eq!(resolved.effective, started_with); + assert_eq!(resolved.record, None); +} + #[test] fn a_thread_that_recorded_nothing_keeps_todays_behaviour_whatever_the_config_says() { let rows = vec![TranscriptMessage::system("prompt")]; From 227862ed42a935ffe760febcad801f32615c7f41 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 06:00:52 +0300 Subject: [PATCH 18/24] fix(session): hand the session's expiry, reasoning-replay and discovery options to the turn's run config The session prepares result_expiry, replay_reasoning and discovery overrides on the RunConfig it gives its driver, but the driver builds a fresh RunConfig for the turn, so the harness read them empty and never expired old tool results. Co-authored-by: Medulla --- .../src/agent/session_host/driver/execute.rs | 9 +- .../src/agent/session_host/mod.rs | 2 + .../session_host/result_expiry_wire_tests.rs | 145 ++++++++++++++++++ .../src/agent/tinyagents/host/run_context.rs | 44 ++++++ .../tinyagents/host/run_context/behavior.rs | 3 + .../tinyagents/host/run_context_tests.rs | 41 +++++ .../agent/tinyagents/turn_exec/drive/setup.rs | 3 + 7 files changed, 246 insertions(+), 1 deletion(-) create mode 100644 crates/openhuman-core/src/agent/session_host/result_expiry_wire_tests.rs diff --git a/crates/openhuman-core/src/agent/session_host/driver/execute.rs b/crates/openhuman-core/src/agent/session_host/driver/execute.rs index d894edb2e5f..b1231dd75eb 100644 --- a/crates/openhuman-core/src/agent/session_host/driver/execute.rs +++ b/crates/openhuman-core/src/agent/session_host/driver/execute.rs @@ -124,9 +124,16 @@ impl SessionDriver for OpenHumanSessionDriver { &request.run_context.data.recorded_tool_names, )?; // Text dialects need the positional registry to recover P-Format and code-style calls. - let run_context = request.run_context.data.clone().with_tool_dialect( + let mut run_context = request.run_context.data.clone().with_tool_dialect( tinyagents_harness::dialect::dispatcher_for_format(self.dispatcher.tool_call_format()), ); + // The turn builds its own `RunConfig`, so the options the session set on + // this request's config (result expiry, reasoning replay, discovery) + // have to be handed over here. + run_context.session_run_options = + crate::agent::tinyagents::host::run_context::SessionRunOptions::of( + &request.run_context.config, + ); let cancellation = request.run_context.cancellation.clone(); // Boxing avoids worker-stack overflow in debug builds. let turn = Box::pin(async move { diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rs index 241cc111814..d9adde5cf54 100644 --- a/crates/openhuman-core/src/agent/session_host/mod.rs +++ b/crates/openhuman-core/src/agent/session_host/mod.rs @@ -72,6 +72,8 @@ mod imported_history_tests; mod orphaned_head_resume_tests; #[cfg(test)] mod response_shape_turn_tests; +#[cfg(all(test, feature = "legacy-import"))] +mod result_expiry_wire_tests; #[cfg(test)] mod runtime_adapter_session_state_tests; #[cfg(test)] diff --git a/crates/openhuman-core/src/agent/session_host/result_expiry_wire_tests.rs b/crates/openhuman-core/src/agent/session_host/result_expiry_wire_tests.rs new file mode 100644 index 00000000000..6c0b5cc8739 --- /dev/null +++ b/crates/openhuman-core/src/agent/session_host/result_expiry_wire_tests.rs @@ -0,0 +1,145 @@ +//! The `[context]` history-replay options a session pins reach the model's +//! request: a thread with tool result expiry on sends an old tool result as a +//! one-line note, not in full. The session prepares the options on its run +//! config; the driver has to hand them to the run loop that reads them. + +use std::sync::Arc; + +use serde_json::{json, Value}; +use tinyagents_harness::testkit::ScriptedModel; +use tinyinference_llm::message::Message; +use tinyinference_llm::model::{ChatModel, ModelProfile, ModelResponse}; + +use super::transcript_compat_tests::{call, response, run_async, store_locator, thread_id}; + +const TOOL_BODY: &str = "the echoed lines of a long listing"; + +struct EchoTool; + +#[async_trait::async_trait] +impl tinytools::Tool for EchoTool { + fn name(&self) -> &str { + "echo" + } + fn description(&self) -> &str { + "echoes" + } + fn parameters_schema(&self) -> Value { + json!({"type": "object", "properties": {"q": {"type": "string"}}}) + } + async fn execute(&self, _args: Value) -> anyhow::Result { + Ok(tinytools::ToolResult::success(TOOL_BODY)) + } +} + +fn host_with_context( + root: &std::path::Path, + model: Arc, + thread: &str, + context: crate::config::ContextSettings, +) -> crate::agent::OpenHumanSessionHost { + let mut config = crate::config::Config::default(); + config.workspace_dir = root.join("workspace"); + config.action_dir = root.to_path_buf(); + config.config_path = root.join("config.toml"); + config.modules.enabled = false; + config.context = context; + // No TinySecurity module runs in a unit test, so the screen would hold the input. + config.prompt_screen.mode = crate::config::schema::PromptScreenMode::Off; + let chat_model: Arc> = model; + let mut host = crate::agent::SessionHostBuilder::new() + .with_session_history_locator(store_locator(root)) + .model_name("test/session-fixture".to_string()) + .chat_model_with_config(chat_model, Arc::new(config)) + .tools(vec![Box::new(EchoTool)]) + .tool_dispatcher(Box::new(tinytools_agent::dialect::NativeDialect)) + .build() + .expect("session build"); + host.set_thread_id(Some(thread)); + host +} + +/// The text of every tool result in the request, oldest first. +fn tool_results(request: &tinyinference_llm::model::ModelRequest) -> Vec { + request + .messages + .iter() + .filter(|message| matches!(message, Message::Tool(_))) + .map(Message::text) + .collect() +} + +/// Runs a tool-using first turn and `later` plain turns on one thread, and +/// returns the tool results each later turn's request carried. +async fn tool_results_per_later_turn( + context: crate::config::ContextSettings, + later: usize, +) -> Vec> { + // No TinySecurity module runs in a unit test: with it enabled the redactor + // would replace every tool result. + let _off = crate::security::switch::off_for_this_thread(); + let root = tempfile::tempdir().expect("tempdir"); + let thread = thread_id("expiry-wire"); + let mut script = vec![ + response(Vec::new(), vec![call("call-1", "echo", json!({"q": "x"}))]), + ModelResponse::assistant("first done"), + ]; + script.extend((0..later).map(|_| ModelResponse::assistant("ok"))); + let model = Arc::new(ScriptedModel::new(script).with_profile(ModelProfile { + tool_calling: true, + ..Default::default() + })); + let mut host = host_with_context(root.path(), model.clone(), &thread, context); + host.turn("first").await.expect("first turn"); + let mut per_turn = Vec::new(); + for turn in 0..later { + let before = model.requests().len(); + host.turn(&format!("later {turn}")) + .await + .expect("later turn"); + let requests = model.requests(); + per_turn.push(tool_results(&requests[before])); + } + per_turn +} + +/// One result, carried whole: the tool's body, not a note. +fn assert_full(results: &[String]) { + assert_eq!(results.len(), 1); + assert!( + results[0].contains(TOOL_BODY) && !results[0].starts_with("[used "), + "the result must ride along in full, got {:?}", + results[0] + ); +} + +#[test] +fn an_old_tool_result_goes_out_as_a_note_once_it_is_past_max_age_turns() { + run_async(async { + let mut context = crate::config::ContextSettings::default(); + context.tool_result_max_age_turns = Some(2); + let per_turn = tool_results_per_later_turn(context, 3).await; + + // Two user turns after the result is within the age: sent in full. + assert_full(&per_turn[0]); + assert_full(&per_turn[1]); + // A third later turn puts it past `max_age_turns = 2`. + assert_eq!(per_turn[2].len(), 1); + assert!( + per_turn[2][0].starts_with("[used echo:"), + "the old result must be replaced by a note, got {:?}", + per_turn[2][0] + ); + }); +} + +#[test] +fn a_tool_result_is_sent_in_full_while_expiry_is_off() { + run_async(async { + let per_turn = + tool_results_per_later_turn(crate::config::ContextSettings::default(), 3).await; + for results in &per_turn { + assert_full(results); + } + }); +} diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs index aa6b68c3eb0..08f0c452ec9 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs @@ -158,6 +158,46 @@ pub(crate) struct SessionTurnSidecar { pub replay_record: Option, } +/// The per-run harness options a session sets on the `RunConfig` it hands its +/// driver. The driver builds its own run config, so it copies these across, or +/// the harness reads them empty and falls back to the process-wide policy. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct SessionRunOptions { + pub discovery: tinyagents_harness::tool::discover::DiscoveryOverrides, + pub result_expiry: tinyagents_harness::result_expiry::ExpiryOverrides, + pub replay_reasoning: Option, +} + +impl SessionRunOptions { + /// The options `config` carries. + pub(crate) fn of(config: &tinyagents_harness::context::RunConfig) -> Self { + Self { + discovery: config.discovery, + result_expiry: config.result_expiry.clone(), + replay_reasoning: config.replay_reasoning, + } + } + + /// Whether no option is set. + pub(crate) fn is_empty(&self) -> bool { + *self == Self::default() + } + + /// `config` with these options set. A config is left as it is when none are + /// set, so a run that carries its own (a sub-agent) keeps them. + pub(crate) fn apply_to( + &self, + mut config: tinyagents_harness::context::RunConfig, + ) -> tinyagents_harness::context::RunConfig { + if !self.is_empty() { + config.discovery = self.discovery; + config.result_expiry = self.result_expiry.clone(); + config.replay_reasoning = self.replay_reasoning; + } + config + } +} + #[path = "dispatch_control.rs"] mod dispatch_control; pub use dispatch_control::{decide_dispatch, DispatchDecision, DispatchInputs, TurnDispatchState}; @@ -311,6 +351,10 @@ pub struct OpenHumanRunContext { pub(crate) context_middleware: Option, /// Model/harness sidecars consumed only after a durable commit. pub(crate) session_sidecar: Arc>, + /// The per-run harness options the owning session prepared on its + /// `RunConfig` (discovery, result expiry, reasoning replay), carried to the + /// `RunConfig` the turn driver builds. Empty for any turn without a session. + pub(crate) session_run_options: SessionRunOptions, /// Required structured-output contract for this exact host turn. The /// driver repairs it before returning a candidate to runtime validation. pub(crate) required_output: Option, diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context/behavior.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context/behavior.rs index e90ab7532cf..29b5115272f 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/run_context/behavior.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context/behavior.rs @@ -60,6 +60,7 @@ impl OpenHumanRunContext { tool_rules: None, context_middleware: None, session_sidecar: Arc::new(Mutex::new(SessionTurnSidecar::default())), + session_run_options: SessionRunOptions::default(), required_output: None, tool_dialect: tinyagents_harness::config::ToolDispatcher::Auto, memory_turn: None, @@ -230,6 +231,8 @@ impl OpenHumanRunContext { child.subagent_usage = Arc::new(Mutex::new(Vec::new())); child.resolved_route = Arc::new(Mutex::new(None)); child.memory_turn = None; + // The options belong to the session's thread; a child runs its own. + child.session_run_options = SessionRunOptions::default(); child.native_staged_parts.clear(); child.native_staged_lease = None; child.native_message_id = None; diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs index 171f5daec0c..26b9baabe5a 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs @@ -746,3 +746,44 @@ fn the_turns_still_in_the_prompt_reach_the_runs_tools() { assert_eq!(memory_in_prompt_for_tool(Some(&call)), None); assert_eq!(memory_in_prompt_for_tool(None), None); } + +#[test] +fn session_run_options_carry_expiry_reasoning_and_discovery_onto_a_fresh_config() { + use tinyagents_harness::context::RunConfig; + use tinyagents_harness::reasoning_replay::ReasoningReplay; + use tinyagents_harness::result_expiry::ExpiryOverrides; + use tinyagents_harness::tool::discover::DiscoveryOverrides; + + let session = RunConfig::new("session") + .with_result_expiry_overrides(ExpiryOverrides { + enabled: Some(true), + max_age_turns: Some(2), + exempt_tools: Some(vec!["tool_search".into()]), + }) + .with_replay_reasoning(ReasoningReplay::CurrentTurn) + .with_discovery_overrides(DiscoveryOverrides { + collapse_search_results: Some(true), + ..DiscoveryOverrides::default() + }); + let options = SessionRunOptions::of(&session); + + let carried = options.apply_to(RunConfig::new("turn")); + assert_eq!(carried.result_expiry, session.result_expiry); + assert_eq!(carried.replay_reasoning, Some(ReasoningReplay::CurrentTurn)); + assert_eq!(carried.discovery, session.discovery); + assert_eq!(carried.run_id.as_str(), "turn"); +} + +#[test] +fn empty_session_run_options_leave_a_config_that_carries_its_own_untouched() { + use tinyagents_harness::context::RunConfig; + use tinyagents_harness::reasoning_replay::ReasoningReplay; + + let own = RunConfig::new("child").with_replay_reasoning(ReasoningReplay::CurrentTurn); + let kept = SessionRunOptions::default().apply_to(own); + assert_eq!(kept.replay_reasoning, Some(ReasoningReplay::CurrentTurn)); + assert!(OpenHumanRunContext::new() + .child() + .session_run_options + .is_empty()); +} diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_exec/drive/setup.rs b/crates/openhuman-core/src/agent/tinyagents/turn_exec/drive/setup.rs index c733ffd72c6..642c05d7260 100644 --- a/crates/openhuman-core/src/agent/tinyagents/turn_exec/drive/setup.rs +++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec/drive/setup.rs @@ -26,6 +26,9 @@ pub(super) fn run_config( .with_max_depth(super::super::super::budget::depth(run_context)) .with_tag("openhuman") .with_tag(if observed { "observed" } else { "unobserved" }); + // The session's discovery, result-expiry and reasoning-replay options ride + // the run context; without them the harness reads its empty overrides. + config = run_context.session_run_options.apply_to(config); // The loop stamps this cap onto every model request; it does not bake into // the primary or routed models. if let Some(cap) = max_output_tokens { From 7b39befcb3aeb7ab7f01fbdb2a970e53719eb311 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 07:18:43 +0300 Subject: [PATCH 19/24] fix(ci): satisfy rust-layout, process-statics and runtime-boundary guards for epic 712 Split run_context_tests.rs below the 750-line limit, record ownership for the memory-block READY static, and give the config schema its own ReasoningReplay enum (same TOML/env names) that converts to the harness type where replay options are built, so config no longer re-exports a TinyAgents type. The embed API (openhuman_embed::ReasoningReplay) is unchanged. Co-authored-by: Medulla --- .../src/agent/tinyagents/host/run_context.rs | 4 + .../host/run_context_carried_state_tests.rs | 204 ++++++++++++++++++ .../tinyagents/host/run_context_tests.rs | 203 ----------------- .../src/agent/tinyagents/replay_pin.rs | 2 +- .../src/agent/tinyagents/replay_pin_tests.rs | 7 +- .../src/config/schema/context.rs | 27 ++- .../schema/load_env_overlay_context_tests.rs | 28 ++- scripts/ci/process-statics.json | 10 + 8 files changed, 274 insertions(+), 211 deletions(-) create mode 100644 crates/openhuman-core/src/agent/tinyagents/host/run_context_carried_state_tests.rs diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs index 08f0c452ec9..682f3e97176 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs @@ -403,3 +403,7 @@ mod behavior; #[cfg(test)] #[path = "run_context_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "run_context_carried_state_tests.rs"] +mod carried_state_tests; diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_carried_state_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_carried_state_tests.rs new file mode 100644 index 00000000000..a627bc0d549 --- /dev/null +++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_carried_state_tests.rs @@ -0,0 +1,204 @@ +use super::*; + +/// The memory identity is explicit on the run: a child inherits it (the +/// sub-agent runner then narrows it with `child()`), and a host +/// environment that carries one — the team runtime's member — applies it, while +/// an environment without one leaves the run's own alone. +#[test] +fn the_memory_identity_rides_the_run_and_its_children() { + let mut context = OpenHumanRunContext::new(); + assert_eq!(context.memory_identity, None); + + let env = crate::agent::turn_env::HostTurnEnv { + memory_identity: Some(tinymemory_tools::layout::identity::Identity::team_member( + "acme", "lead", + )), + ..Default::default() + }; + context = context.with_host_env(&env); + assert_eq!( + context.memory_identity, + Some(tinymemory_tools::layout::identity::Identity::team_member( + "acme", "lead" + )) + ); + + let child = context.child(); + assert_eq!(child.memory_identity, context.memory_identity); + assert_eq!( + child.memory_identity.unwrap().child("scout"), + tinymemory_tools::layout::identity::Identity::team_member("acme", "scout") + ); + + let unchanged = context.with_host_env(&crate::agent::turn_env::HostTurnEnv::default()); + assert_eq!( + unchanged.memory_identity, + Some(tinymemory_tools::layout::identity::Identity::team_member( + "acme", "lead" + )) + ); +} + +fn tool_context_for(run: OpenHumanRunContext) -> tinyagents_harness::tool::ToolExecutionContext { + let run = run.into_tinyagents(tinyagents_harness::context::RunConfig::new("core-carrier")); + tinyagents_harness::tool::ToolExecutionContext::from_run_context( + &run, + tinyagents_harness::ids::CallId::new("core-carrier-call"), + ) +} + +#[tokio::test] +async fn a_tool_reads_the_runs_core_not_the_ambient_scope() { + use crate::core::runtime::{CoreContext, DomainSet}; + + let runs = CoreContext::for_test(DomainSet::full(), None); + let ambient = CoreContext::for_test(DomainSet::full(), None); + let context = tool_context_for(OpenHumanRunContext::new().with_core(Some(runs.clone()))); + + CoreContext::scope(ambient.clone(), async { + let ctx = dispatch_ctx_for_tool(Some(&context)); + assert!(Arc::ptr_eq(ctx.core().expect("bound"), &runs)); + assert!(!Arc::ptr_eq(ctx.core().expect("bound"), &ambient)); + }) + .await; +} + +#[tokio::test] +async fn concurrent_runs_keep_their_own_core_across_awaits_and_spawns() { + use crate::core::runtime::{CoreContext, DomainSet}; + + let a = CoreContext::for_test(DomainSet::full(), None); + let b = CoreContext::for_test(DomainSet::full(), None); + let ctx_a = tool_context_for(OpenHumanRunContext::new().with_core(Some(a.clone()))); + let ctx_b = tool_context_for(OpenHumanRunContext::new().with_core(Some(b.clone()))); + + let read = |context: tinyagents_harness::tool::ToolExecutionContext| async move { + tokio::task::yield_now().await; + // A plain spawn loses every task-local; the carrier does not. + tokio::spawn(async move { dispatch_ctx_for_tool(Some(&context)).into_core() }) + .await + .unwrap() + }; + let (got_a, got_b) = tokio::join!(read(ctx_a), read(ctx_b)); + assert!(Arc::ptr_eq(&got_a.expect("a bound"), &a)); + assert!(Arc::ptr_eq(&got_b.expect("b bound"), &b)); +} + +#[test] +fn the_core_rides_the_host_env_and_survives_child_and_detached_child() { + use crate::core::runtime::{CoreContext, DomainSet}; + + let core = CoreContext::for_test(DomainSet::full(), None); + let env = crate::agent::turn_env::HostTurnEnv { + core: Some(Arc::downgrade(&core)), + ..Default::default() + }; + let run = OpenHumanRunContext::new().with_host_env(&env); + let bound = |run: &OpenHumanRunContext| run.core.as_ref().and_then(std::sync::Weak::upgrade); + assert!(Arc::ptr_eq(&bound(&run).unwrap(), &core)); + assert!(Arc::ptr_eq(&bound(&run.child()).unwrap(), &core)); + assert!(Arc::ptr_eq(&bound(&run.detached_child()).unwrap(), &core)); + // An env with no core leaves the run's own in place. + let kept = run.with_host_env(&crate::agent::turn_env::HostTurnEnv::default()); + assert!(Arc::ptr_eq(&bound(&kept).unwrap(), &core)); +} + +#[test] +fn a_run_kept_past_its_turn_does_not_pin_the_tenant() { + use crate::core::runtime::{CoreContext, DomainSet}; + + let core = CoreContext::for_test(DomainSet::full(), None); + let run = OpenHumanRunContext::new().with_core(Some(core.clone())); + let env = crate::agent::turn_env::HostTurnEnv { + core: Some(Arc::downgrade(&core)), + ..Default::default() + }; + let _kept_run = run.child(); + let _kept_env = env.clone(); + // Only the handle in this test holds the context: sessions and runs that + // outlive a turn reference it weakly. + assert!(!core.tenant_in_use()); +} + +#[test] +fn the_turns_still_in_the_prompt_reach_the_runs_tools() { + let config = crate::config::Config::default(); + let mut host = OpenHumanRunContext::new(); + host.memory_turn = Some(std::sync::Arc::new( + crate::memory::lifecycle::hooks::MemoryTurn { + identity: tinymemory_tools::layout::identity::Identity::agent("a") + .resolve(&crate::memory::scope::identity_pins(&config)), + config: std::sync::Arc::new(config), + thread_id: "thread-long".into(), + pack: None, + in_prompt_from: std::sync::Arc::new( + tinymemory_tools::lifecycle::window::InPromptFrom::new(12, 20), + ), + core: None, + }, + )); + let run = host.into_tinyagents(tinyagents_harness::context::RunConfig::new("memory-window")); + let call = tinyagents_harness::tool::ToolExecutionContext::from_run_context( + &run, + tinyagents_harness::ids::CallId::new("memory-window-call"), + ); + assert_eq!( + memory_in_prompt_for_tool(Some(&call)), + Some(tinymemory_api::ThreadWindow { + thread_id: "thread-long".into(), + from_turn: 12, + }) + ); + + // A run without the turn's memory (a sub-agent's, a direct dispatch) + // knows no window. + let bare = OpenHumanRunContext::new() + .into_tinyagents(tinyagents_harness::context::RunConfig::new("no-memory")); + let call = tinyagents_harness::tool::ToolExecutionContext::from_run_context( + &bare, + tinyagents_harness::ids::CallId::new("no-memory-call"), + ); + assert_eq!(memory_in_prompt_for_tool(Some(&call)), None); + assert_eq!(memory_in_prompt_for_tool(None), None); +} + +#[test] +fn session_run_options_carry_expiry_reasoning_and_discovery_onto_a_fresh_config() { + use tinyagents_harness::context::RunConfig; + use tinyagents_harness::reasoning_replay::ReasoningReplay; + use tinyagents_harness::result_expiry::ExpiryOverrides; + use tinyagents_harness::tool::discover::DiscoveryOverrides; + + let session = RunConfig::new("session") + .with_result_expiry_overrides(ExpiryOverrides { + enabled: Some(true), + max_age_turns: Some(2), + exempt_tools: Some(vec!["tool_search".into()]), + }) + .with_replay_reasoning(ReasoningReplay::CurrentTurn) + .with_discovery_overrides(DiscoveryOverrides { + collapse_search_results: Some(true), + ..DiscoveryOverrides::default() + }); + let options = SessionRunOptions::of(&session); + + let carried = options.apply_to(RunConfig::new("turn")); + assert_eq!(carried.result_expiry, session.result_expiry); + assert_eq!(carried.replay_reasoning, Some(ReasoningReplay::CurrentTurn)); + assert_eq!(carried.discovery, session.discovery); + assert_eq!(carried.run_id.as_str(), "turn"); +} + +#[test] +fn empty_session_run_options_leave_a_config_that_carries_its_own_untouched() { + use tinyagents_harness::context::RunConfig; + use tinyagents_harness::reasoning_replay::ReasoningReplay; + + let own = RunConfig::new("child").with_replay_reasoning(ReasoningReplay::CurrentTurn); + let kept = SessionRunOptions::default().apply_to(own); + assert_eq!(kept.replay_reasoning, Some(ReasoningReplay::CurrentTurn)); + assert!(OpenHumanRunContext::new() + .child() + .session_run_options + .is_empty()); +} diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs index 26b9baabe5a..d995339aa8d 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs @@ -584,206 +584,3 @@ async fn the_approval_context_survives_await_points_and_a_move_between_tasks() { Some("t-await") ); } - -/// The memory identity is explicit on the run: a child inherits it (the -/// sub-agent runner then narrows it with `child()`), and a host -/// environment that carries one — the team runtime's member — applies it, while -/// an environment without one leaves the run's own alone. -#[test] -fn the_memory_identity_rides_the_run_and_its_children() { - let mut context = OpenHumanRunContext::new(); - assert_eq!(context.memory_identity, None); - - let env = crate::agent::turn_env::HostTurnEnv { - memory_identity: Some(tinymemory_tools::layout::identity::Identity::team_member( - "acme", "lead", - )), - ..Default::default() - }; - context = context.with_host_env(&env); - assert_eq!( - context.memory_identity, - Some(tinymemory_tools::layout::identity::Identity::team_member( - "acme", "lead" - )) - ); - - let child = context.child(); - assert_eq!(child.memory_identity, context.memory_identity); - assert_eq!( - child.memory_identity.unwrap().child("scout"), - tinymemory_tools::layout::identity::Identity::team_member("acme", "scout") - ); - - let unchanged = context.with_host_env(&crate::agent::turn_env::HostTurnEnv::default()); - assert_eq!( - unchanged.memory_identity, - Some(tinymemory_tools::layout::identity::Identity::team_member( - "acme", "lead" - )) - ); -} - -fn tool_context_for(run: OpenHumanRunContext) -> tinyagents_harness::tool::ToolExecutionContext { - let run = run.into_tinyagents(tinyagents_harness::context::RunConfig::new("core-carrier")); - tinyagents_harness::tool::ToolExecutionContext::from_run_context( - &run, - tinyagents_harness::ids::CallId::new("core-carrier-call"), - ) -} - -#[tokio::test] -async fn a_tool_reads_the_runs_core_not_the_ambient_scope() { - use crate::core::runtime::{CoreContext, DomainSet}; - - let runs = CoreContext::for_test(DomainSet::full(), None); - let ambient = CoreContext::for_test(DomainSet::full(), None); - let context = tool_context_for(OpenHumanRunContext::new().with_core(Some(runs.clone()))); - - CoreContext::scope(ambient.clone(), async { - let ctx = dispatch_ctx_for_tool(Some(&context)); - assert!(Arc::ptr_eq(ctx.core().expect("bound"), &runs)); - assert!(!Arc::ptr_eq(ctx.core().expect("bound"), &ambient)); - }) - .await; -} - -#[tokio::test] -async fn concurrent_runs_keep_their_own_core_across_awaits_and_spawns() { - use crate::core::runtime::{CoreContext, DomainSet}; - - let a = CoreContext::for_test(DomainSet::full(), None); - let b = CoreContext::for_test(DomainSet::full(), None); - let ctx_a = tool_context_for(OpenHumanRunContext::new().with_core(Some(a.clone()))); - let ctx_b = tool_context_for(OpenHumanRunContext::new().with_core(Some(b.clone()))); - - let read = |context: tinyagents_harness::tool::ToolExecutionContext| async move { - tokio::task::yield_now().await; - // A plain spawn loses every task-local; the carrier does not. - tokio::spawn(async move { dispatch_ctx_for_tool(Some(&context)).into_core() }) - .await - .unwrap() - }; - let (got_a, got_b) = tokio::join!(read(ctx_a), read(ctx_b)); - assert!(Arc::ptr_eq(&got_a.expect("a bound"), &a)); - assert!(Arc::ptr_eq(&got_b.expect("b bound"), &b)); -} - -#[test] -fn the_core_rides_the_host_env_and_survives_child_and_detached_child() { - use crate::core::runtime::{CoreContext, DomainSet}; - - let core = CoreContext::for_test(DomainSet::full(), None); - let env = crate::agent::turn_env::HostTurnEnv { - core: Some(Arc::downgrade(&core)), - ..Default::default() - }; - let run = OpenHumanRunContext::new().with_host_env(&env); - let bound = |run: &OpenHumanRunContext| run.core.as_ref().and_then(std::sync::Weak::upgrade); - assert!(Arc::ptr_eq(&bound(&run).unwrap(), &core)); - assert!(Arc::ptr_eq(&bound(&run.child()).unwrap(), &core)); - assert!(Arc::ptr_eq(&bound(&run.detached_child()).unwrap(), &core)); - // An env with no core leaves the run's own in place. - let kept = run.with_host_env(&crate::agent::turn_env::HostTurnEnv::default()); - assert!(Arc::ptr_eq(&bound(&kept).unwrap(), &core)); -} - -#[test] -fn a_run_kept_past_its_turn_does_not_pin_the_tenant() { - use crate::core::runtime::{CoreContext, DomainSet}; - - let core = CoreContext::for_test(DomainSet::full(), None); - let run = OpenHumanRunContext::new().with_core(Some(core.clone())); - let env = crate::agent::turn_env::HostTurnEnv { - core: Some(Arc::downgrade(&core)), - ..Default::default() - }; - let _kept_run = run.child(); - let _kept_env = env.clone(); - // Only the handle in this test holds the context: sessions and runs that - // outlive a turn reference it weakly. - assert!(!core.tenant_in_use()); -} - -#[test] -fn the_turns_still_in_the_prompt_reach_the_runs_tools() { - let config = crate::config::Config::default(); - let mut host = OpenHumanRunContext::new(); - host.memory_turn = Some(std::sync::Arc::new( - crate::memory::lifecycle::hooks::MemoryTurn { - identity: tinymemory_tools::layout::identity::Identity::agent("a") - .resolve(&crate::memory::scope::identity_pins(&config)), - config: std::sync::Arc::new(config), - thread_id: "thread-long".into(), - pack: None, - in_prompt_from: std::sync::Arc::new( - tinymemory_tools::lifecycle::window::InPromptFrom::new(12, 20), - ), - core: None, - }, - )); - let run = host.into_tinyagents(tinyagents_harness::context::RunConfig::new("memory-window")); - let call = tinyagents_harness::tool::ToolExecutionContext::from_run_context( - &run, - tinyagents_harness::ids::CallId::new("memory-window-call"), - ); - assert_eq!( - memory_in_prompt_for_tool(Some(&call)), - Some(tinymemory_api::ThreadWindow { - thread_id: "thread-long".into(), - from_turn: 12, - }) - ); - - // A run without the turn's memory (a sub-agent's, a direct dispatch) - // knows no window. - let bare = OpenHumanRunContext::new() - .into_tinyagents(tinyagents_harness::context::RunConfig::new("no-memory")); - let call = tinyagents_harness::tool::ToolExecutionContext::from_run_context( - &bare, - tinyagents_harness::ids::CallId::new("no-memory-call"), - ); - assert_eq!(memory_in_prompt_for_tool(Some(&call)), None); - assert_eq!(memory_in_prompt_for_tool(None), None); -} - -#[test] -fn session_run_options_carry_expiry_reasoning_and_discovery_onto_a_fresh_config() { - use tinyagents_harness::context::RunConfig; - use tinyagents_harness::reasoning_replay::ReasoningReplay; - use tinyagents_harness::result_expiry::ExpiryOverrides; - use tinyagents_harness::tool::discover::DiscoveryOverrides; - - let session = RunConfig::new("session") - .with_result_expiry_overrides(ExpiryOverrides { - enabled: Some(true), - max_age_turns: Some(2), - exempt_tools: Some(vec!["tool_search".into()]), - }) - .with_replay_reasoning(ReasoningReplay::CurrentTurn) - .with_discovery_overrides(DiscoveryOverrides { - collapse_search_results: Some(true), - ..DiscoveryOverrides::default() - }); - let options = SessionRunOptions::of(&session); - - let carried = options.apply_to(RunConfig::new("turn")); - assert_eq!(carried.result_expiry, session.result_expiry); - assert_eq!(carried.replay_reasoning, Some(ReasoningReplay::CurrentTurn)); - assert_eq!(carried.discovery, session.discovery); - assert_eq!(carried.run_id.as_str(), "turn"); -} - -#[test] -fn empty_session_run_options_leave_a_config_that_carries_its_own_untouched() { - use tinyagents_harness::context::RunConfig; - use tinyagents_harness::reasoning_replay::ReasoningReplay; - - let own = RunConfig::new("child").with_replay_reasoning(ReasoningReplay::CurrentTurn); - let kept = SessionRunOptions::default().apply_to(own); - assert_eq!(kept.replay_reasoning, Some(ReasoningReplay::CurrentTurn)); - assert!(OpenHumanRunContext::new() - .child() - .session_run_options - .is_empty()); -} diff --git a/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs b/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs index 608c3e92f4a..d4f7ff2dd03 100644 --- a/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs +++ b/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs @@ -65,7 +65,7 @@ impl ReplayOptions { } else { Vec::new() }, - replay_reasoning: config.replay_reasoning, + replay_reasoning: config.replay_reasoning.into(), } } diff --git a/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs b/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs index 3a0fac43c35..181d3534426 100644 --- a/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs @@ -1,7 +1,8 @@ -use tinyagents_harness::reasoning_replay::ReasoningReplay; +use tinyagents_harness::reasoning_replay::ReasoningReplay as HarnessReplay; use tinyagents_harness::result_expiry::{ExpiryOverrides, ToolResultExpiryPolicy}; use super::*; +use crate::config::ReasoningReplay; fn settings(age: Option, exempt: &[&str], replay: ReasoningReplay) -> ContextSettings { let mut settings = ContextSettings::default(); @@ -19,7 +20,7 @@ fn today_is_the_harness_default_and_the_config_default() { assert_eq!(overrides.exempt_tools, Some(policy.exempt_tools)); assert_eq!( ReplayOptions::TODAY.replay_reasoning, - ReasoningReplay::default() + HarnessReplay::default() ); assert_eq!( ReplayOptions::from_config(&ContextSettings::default()), @@ -42,7 +43,7 @@ fn config_options_map_onto_the_harness_expiry_and_replay_options() { exempt_tools: Some(vec!["tool_search".into()]), } ); - assert_eq!(options.replay_reasoning, ReasoningReplay::CurrentTurn); + assert_eq!(options.replay_reasoning, HarnessReplay::CurrentTurn); let policy = ToolResultExpiryPolicy::default().with_overrides(&options.expiry_overrides()); assert!(policy.enabled); diff --git a/crates/openhuman-core/src/config/schema/context.rs b/crates/openhuman-core/src/config/schema/context.rs index f5eccd9ee9d..096ebf1f801 100644 --- a/crates/openhuman-core/src/config/schema/context.rs +++ b/crates/openhuman-core/src/config/schema/context.rs @@ -11,9 +11,34 @@ use serde::{Deserialize, Serialize}; pub use tinyagents_harness::config::{CompactionSettings, CompactionStrategy, ContextConfig}; -pub use tinyagents_harness::reasoning_replay::ReasoningReplay; use tinyagents_harness::summarization::ToolRendering; +/// Which turns' reasoning a request replays (`[context] replay_reasoning`). +/// +/// The config's own copy of the runtime policy, so the schema does not +/// re-export a TinyAgents type. It serializes with the same names +/// (`all` | `current_turn`), and the runtime reads it through +/// `From` where a run is configured. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReasoningReplay { + /// Every assistant message keeps its reasoning blocks (today's behaviour). + #[default] + All, + /// Only the current turn's reasoning is sent; reasoning from completed + /// user turns is omitted from the request. + CurrentTurn, +} + +impl From for tinyagents_harness::reasoning_replay::ReasoningReplay { + fn from(replay: ReasoningReplay) -> Self { + match replay { + ReasoningReplay::All => Self::All, + ReasoningReplay::CurrentTurn => Self::CurrentTurn, + } + } +} + /// The whole `[context]` table: TinyAgents' [`ContextConfig`] and the /// compaction summarizer's OpenHuman-side settings. #[derive(Debug, Clone, Default, Serialize, Deserialize)] 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 64e8141b074..41ab3052659 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 @@ -326,7 +326,7 @@ fn keep_recent_tokens_env_sets_clears_and_ignores_garbage() { #[test] fn prompt_replay_options_default_to_todays_behaviour_and_read_from_the_context_table() { - use tinyagents_harness::reasoning_replay::ReasoningReplay; + use crate::config::ReasoningReplay; let defaults = Config::default().context; assert_eq!(defaults.tool_result_max_age_turns, None); assert!(defaults.tool_result_exempt_tools.is_empty()); @@ -349,7 +349,7 @@ fn prompt_replay_options_default_to_todays_behaviour_and_read_from_the_context_t #[test] fn prompt_replay_options_env_overlay_sets_clears_and_ignores_garbage() { - use tinyagents_harness::reasoning_replay::ReasoningReplay; + use crate::config::ReasoningReplay; let mut cfg = Config::default(); cfg.apply_env_overlay_with( &HashMapEnv::new() @@ -395,7 +395,7 @@ fn prompt_replay_options_env_overlay_sets_clears_and_ignores_garbage() { #[test] fn context_overrides_change_only_the_keys_they_set() { use crate::config::ContextOverrides; - use tinyagents_harness::reasoning_replay::ReasoningReplay; + use crate::config::ReasoningReplay; let mut settings = Config::default().context; settings.keep_recent_tokens = Some(9_000); @@ -423,3 +423,25 @@ fn context_overrides_change_only_the_keys_they_set() { assert_eq!(settings.replay_reasoning, ReasoningReplay::CurrentTurn); assert!(settings.prune_retired_tools); } + +#[test] +fn reasoning_replay_converts_to_the_harness_policy_with_the_same_wire_names() { + use crate::config::ReasoningReplay; + use tinyagents_harness::reasoning_replay::ReasoningReplay as HarnessReplay; + for (config, harness, name) in [ + (ReasoningReplay::All, HarnessReplay::All, "all"), + ( + ReasoningReplay::CurrentTurn, + HarnessReplay::CurrentTurn, + "current_turn", + ), + ] { + assert_eq!(HarnessReplay::from(config), harness); + assert_eq!(serde_json::to_value(config).unwrap(), name); + assert_eq!(serde_json::to_value(harness).unwrap(), name); + assert_eq!( + serde_json::from_value::(name.into()).unwrap(), + config + ); + } +} diff --git a/scripts/ci/process-statics.json b/scripts/ci/process-statics.json index f0af756a788..9f49bd19247 100644 --- a/scripts/ci/process-statics.json +++ b/scripts/ci/process-statics.json @@ -748,5 +748,15 @@ "category": "A", "reason": "cfg(test) only: a per-thread stand-in for CONFIGURED_OFF so a test that turns security off cannot reach a test on another thread. Holds one flag, no tenant data, and is not compiled into any shipped build.", "verification": "security/switch_tests.rs: the_test_guard_does_not_reach_another_thread" + }, + { + "file": "crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready.rs", + "scope": "", + "name": "READY", + "type": "LazyLock", + "count": 1, + "category": "B", + "reason": "Rendered memory blocks wait here for the next generation start. Every key combines the session's workspace directory, its resolved memory identity (profile and agent) and the token budget, so a block is only ever taken by the identity it was read for; the store holds at most READY_CAPACITY entries, each dropped after READY_MAX_AGE.", + "verification": "agent/session_host/runtime_session/memory_block_ready_tests.rs: a_block_is_not_taken_for_another_identity_or_budget" } ] From b3a6f1349350bbda89d6fc33b31ab3b413e502ea Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 11:55:40 +0300 Subject: [PATCH 20/24] docs(embed): link memory_block_deadline to Agent::prewarm_memory_block by path The bare intra-doc link did not resolve under -D rustdoc::broken-intra-doc-links and failed the embed-rustdoc lane. Co-authored-by: Medulla --- crates/openhuman-embed/src/agent/spec.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-embed/src/agent/spec.rs b/crates/openhuman-embed/src/agent/spec.rs index 4a7ef51c8a8..e2b0b7da289 100644 --- a/crates/openhuman-embed/src/agent/spec.rs +++ b/crates/openhuman-embed/src/agent/spec.rs @@ -127,7 +127,8 @@ impl MemoryBinding { /// new thread with none), and the render finishes in the background for /// the next generation start. Without this, a generation start waits for /// the render however long the memory engine takes. - /// [`Agent::prewarm_memory_block`] renders it ahead of a turn instead. + /// [`Agent::prewarm_memory_block`](super::Agent::prewarm_memory_block) + /// renders it ahead of a turn instead. #[must_use] pub fn memory_block_deadline(mut self, deadline: std::time::Duration) -> Self { self.memory_block_deadline = Some(deadline); From 4389c0bd662cd9cb9f628f08002c56285536839d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 12:07:03 +0300 Subject: [PATCH 21/24] chore(deps): bump vendor/tinysearch to 111a9526 Fast-forward from b99ebbb2 (now upstream via tinysearch#49); carries the render review fixes pending in tinysearch#50. Co-authored-by: Medulla --- vendor/tinysearch | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/tinysearch b/vendor/tinysearch index b99ebbb2b15..111a95268ee 160000 --- a/vendor/tinysearch +++ b/vendor/tinysearch @@ -1 +1 @@ -Subproject commit b99ebbb2b159065cc62f20e94c045eef235f7bbe +Subproject commit 111a95268ee7848967093d3081bff221e8d9ea07 From caa32b60fc50451776237559fd2de5075d69bf60 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 12:48:59 +0300 Subject: [PATCH 22/24] chore(deps): point vendor/tinyagents and vendor/tinysearch at their upstream merge commits tinyagents b6ed4606 (#596) and tinysearch 82e540bb (#50); both are fast-forwards of the previous gitlinks (bdf8f4b7, 111a9526). Co-authored-by: Medulla --- vendor/tinyagents | 2 +- vendor/tinysearch | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/vendor/tinyagents b/vendor/tinyagents index bdf8f4b7ae3..b6ed4606e80 160000 --- a/vendor/tinyagents +++ b/vendor/tinyagents @@ -1 +1 @@ -Subproject commit bdf8f4b7ae3c4a5707efe1ec96a0bbe51b9b3045 +Subproject commit b6ed4606e80c6249bac9bb7cd12063f8c7056ed7 diff --git a/vendor/tinysearch b/vendor/tinysearch index 111a95268ee..82e540bb165 160000 --- a/vendor/tinysearch +++ b/vendor/tinysearch @@ -1 +1 @@ -Subproject commit 111a95268ee7848967093d3081bff221e8d9ea07 +Subproject commit 82e540bb165622c37fc1dff5ae010bc8ebf1e49c From 33cea3aeb08d1ad3978bacd2de71a3e35f671b82 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 13:51:12 +0300 Subject: [PATCH 23/24] chore(modules): re-pin tinysearch to 0.5.7 Co-authored-by: Medulla --- .../src/modules/registry/records_search.rs | 72 +++++++++---------- vendor/tinysearch | 2 +- 2 files changed, 37 insertions(+), 37 deletions(-) diff --git a/crates/openhuman-core/src/modules/registry/records_search.rs b/crates/openhuman-core/src/modules/registry/records_search.rs index 2c8d82a89d1..78d269370ff 100644 --- a/crates/openhuman-core/src/modules/registry/records_search.rs +++ b/crates/openhuman-core/src/modules/registry/records_search.rs @@ -8,111 +8,111 @@ pub(crate) const TINYSEARCH: ModuleRecord = ModuleRecord { "Web search, grounded answers and page contents across providers through TinySearch", bus_name: tinysearch_bus::names::INTERFACE, object_path: tinysearch_bus::names::OBJECT_PATH, - version: "0.5.6", - release_url: "https://github.com/tinyhumansai/tinysearch/releases/tag/v0.5.6", + version: "0.5.7", + release_url: "https://github.com/tinyhumansai/tinysearch/releases/tag/v0.5.7", // Verbatim from the published v0.5.6 checksum.toml; the same host set as // the other native modules (macOS, Ubuntu, Windows). assets: &[ PlatformAsset { host_key: "archlinux-arm64", - archive: "tinysearch-0.5.6-archlinux-arm64.tar.gz", - sha256: "0ca7234f29073cdb9d04c045cbcdf129704aac2a56fef01aa9b03dc2001eff41", + archive: "tinysearch-0.5.7-archlinux-arm64.tar.gz", + sha256: "89bc202c0aed9da5614027072b25d100316500ad47d4ea4c7855bec0a3573e97", library_sha256: None, }, PlatformAsset { host_key: "archlinux-x86_64", - archive: "tinysearch-0.5.6-archlinux-x86_64.tar.gz", - sha256: "c423d5371ab388f8174b412de8e1fe16e342dd99cfc39075bcf4663db3a2f42a", + archive: "tinysearch-0.5.7-archlinux-x86_64.tar.gz", + sha256: "b08cdaa026de879f2f5b475c876ba7aa97452d0e21e5afff81e908d924997f04", library_sha256: None, }, PlatformAsset { host_key: "fedora-43-arm64", - archive: "tinysearch-0.5.6-fedora-43-arm64.tar.gz", - sha256: "047631f61b978cc335e90d74ab5258a8f450096b833a405309e455eceecc9c66", + archive: "tinysearch-0.5.7-fedora-43-arm64.tar.gz", + sha256: "40a01b7894c5624a6684efdd3bedeebbe069c3e1e7d4486da8e7745ed441ab15", library_sha256: None, }, PlatformAsset { host_key: "fedora-43-x86_64", - archive: "tinysearch-0.5.6-fedora-43-x86_64.tar.gz", - sha256: "d574f27e5ae610878bc21712e16ef46df71406daba818c2986023ee0a067ce13", + archive: "tinysearch-0.5.7-fedora-43-x86_64.tar.gz", + sha256: "269d1a0dc715a71d840605bf8b5d6346d84358dbaed7fc23eed0bd76cb6010ad", library_sha256: None, }, PlatformAsset { host_key: "fedora-44-arm64", - archive: "tinysearch-0.5.6-fedora-44-arm64.tar.gz", - sha256: "bdb0cb4d934f377e1f2998905297dc24377b8554b856b4738cf7cd30878d7d26", + archive: "tinysearch-0.5.7-fedora-44-arm64.tar.gz", + sha256: "f919014992a530b01b195f02f7658c93316a900c501928edd3df83b350dc1ea2", library_sha256: None, }, PlatformAsset { host_key: "fedora-44-x86_64", - archive: "tinysearch-0.5.6-fedora-44-x86_64.tar.gz", - sha256: "0c91811c7529ed8d7ccde65029c6c548c6fa22472a18f329fc4fbc480fa66eee", + archive: "tinysearch-0.5.7-fedora-44-x86_64.tar.gz", + sha256: "006c0afce4199f378b1ac0d19f6be81a936d738719a055e5f6c0da5bcfb100bf", library_sha256: None, }, PlatformAsset { host_key: "macos-15-arm64", - archive: "tinysearch-0.5.6-macos-15-arm64.tar.gz", - sha256: "71fd0fbd18eb708339dd5e7d4b9ff9bf3e7d8099d486600946968f1c96f4ad1c", + archive: "tinysearch-0.5.7-macos-15-arm64.tar.gz", + sha256: "6fb4f3771451017e19d71c1890a53a7a7ffc30eec5561dda34f0cb0f0283e3ff", library_sha256: None, }, PlatformAsset { host_key: "macos-15-x86_64", - archive: "tinysearch-0.5.6-macos-15-x86_64.tar.gz", - sha256: "164e961085145d00017233f08635f7256d17a212cfe44798320beabd77ba470b", + archive: "tinysearch-0.5.7-macos-15-x86_64.tar.gz", + sha256: "a77aba9bbdcf6538dbfcbc52be2d25a9b85444c3e71b8ebb02077029b92eeb8a", library_sha256: None, }, PlatformAsset { host_key: "macos-26-arm64", - archive: "tinysearch-0.5.6-macos-26-arm64.tar.gz", - sha256: "4ee87355ead3825d00e786c166105a839e87793f631df8d820dc255624c3ffba", + archive: "tinysearch-0.5.7-macos-26-arm64.tar.gz", + sha256: "0a232532ce3492c12a7ca4632a30f0e3b0612a319ad42e7dd1b5fa574d918f9c", library_sha256: None, }, PlatformAsset { host_key: "macos-26-x86_64", - archive: "tinysearch-0.5.6-macos-26-x86_64.tar.gz", - sha256: "3f5c08072493ce252208be53c7da7776615e8eb26e29214cb16a3565801fae27", + archive: "tinysearch-0.5.7-macos-26-x86_64.tar.gz", + sha256: "8cddfa5dea4d1bdfc8c3279e995869cae00d9be93552c05f0e9cf6e4b65602a5", library_sha256: None, }, PlatformAsset { host_key: "ubuntu-22.04-arm64", - archive: "tinysearch-0.5.6-ubuntu-22.04-arm64.tar.gz", - sha256: "5e133addabef60e5cb8f317527a3b6eff056a4793284135a372c4fe3d01f8d39", + archive: "tinysearch-0.5.7-ubuntu-22.04-arm64.tar.gz", + sha256: "96d8b9024ab13f6b36bfcbc7875f5084ee0b724f6d433b8c2cedaba6464e961e", library_sha256: None, }, PlatformAsset { host_key: "ubuntu-22.04-x86_64", - archive: "tinysearch-0.5.6-ubuntu-22.04-x86_64.tar.gz", - sha256: "5478db74ca1ff351ccde956fa202fb8b253a63f44c09f5229d346a7fc895f64f", + archive: "tinysearch-0.5.7-ubuntu-22.04-x86_64.tar.gz", + sha256: "28aeeeb66376ae1efa6260b25a3c6f8e29f60744c1dfcaf3858dcdf60b1e8619", library_sha256: None, }, PlatformAsset { host_key: "ubuntu-24.04-arm64", - archive: "tinysearch-0.5.6-ubuntu-24.04-arm64.tar.gz", - sha256: "cada1784a55361f04c1ce6504f599b0abefb60a631eb273348af6131ab2b508b", + archive: "tinysearch-0.5.7-ubuntu-24.04-arm64.tar.gz", + sha256: "364df629c689a7da4a5c4e9f553df947032f129bb8a6879fdf0f2906f2fef4c8", library_sha256: None, }, PlatformAsset { host_key: "ubuntu-24.04-x86_64", - archive: "tinysearch-0.5.6-ubuntu-24.04-x86_64.tar.gz", - sha256: "75e517367ddc3f4e76c7632566498e8abf5f317b7b84c115ce9f1287c65dca85", + archive: "tinysearch-0.5.7-ubuntu-24.04-x86_64.tar.gz", + sha256: "80b3eff3095160b126f44949c500818a1765ea41512c2ca1ea9c3b361875ecb8", library_sha256: None, }, PlatformAsset { host_key: "windows-11-arm64", - archive: "tinysearch-0.5.6-windows-11-arm64.zip", - sha256: "814b702e24eed2cb7795678f361293f2d14ce3bae5a46d8c1a976c8bab81f3d6", + archive: "tinysearch-0.5.7-windows-11-arm64.zip", + sha256: "1d406d05a5d7631614cf8de4251cc933f332aaf84ffec71fbeb5067bbede7a00", library_sha256: None, }, PlatformAsset { host_key: "windows-2022-x86_64", - archive: "tinysearch-0.5.6-windows-2022-x86_64.zip", - sha256: "db643ca392b7a90ffb30e3cfcae11630061ec750548bd67410ae21e4e51affee", + archive: "tinysearch-0.5.7-windows-2022-x86_64.zip", + sha256: "0e4e3cf49ebf1c71f1be1b78d8390c937d5c2e2e10e008516006fe5b8dd1a9e0", library_sha256: None, }, PlatformAsset { host_key: "windows-2025-x86_64", - archive: "tinysearch-0.5.6-windows-2025-x86_64.zip", - sha256: "2fc0a71d2f6a3b5ac02207fe73dee48a53060f407a8c7dc543a721a5f5305fca", + archive: "tinysearch-0.5.7-windows-2025-x86_64.zip", + sha256: "eb40f64fc0c54f5699b4fd400457b93d5e766e73a553d13b97c2d4570cff6ce6", library_sha256: None, }, ], diff --git a/vendor/tinysearch b/vendor/tinysearch index 82e540bb165..576fd34f967 160000 --- a/vendor/tinysearch +++ b/vendor/tinysearch @@ -1 +1 @@ -Subproject commit 82e540bb165622c37fc1dff5ae010bc8ebf1e49c +Subproject commit 576fd34f967fdbe532b3375d62df3864b5b7a43c From 7932f10b9d13283e1e5348105df2a00271c2f44e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 8 Nov 2026 13:51:24 +0300 Subject: [PATCH 24/24] chore(deps): refresh Cargo.lock for tinysearch 0.5.7 Co-authored-by: Medulla --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c1345be1d26..8775d95797c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10337,7 +10337,7 @@ dependencies = [ [[package]] name = "tinysearch" -version = "0.5.6" +version = "0.5.7" dependencies = [ "reqwest 0.12.28", "serde", @@ -10351,7 +10351,7 @@ dependencies = [ [[package]] name = "tinysearch-bus" -version = "0.5.6" +version = "0.5.7" dependencies = [ "schemars", "serde",