diff --git a/crates/openhuman-core/src/agent/session_host/codec.rs b/crates/openhuman-core/src/agent/session_host/codec.rs index 3c599f9de77..59d4a5f3ab4 100644 --- a/crates/openhuman-core/src/agent/session_host/codec.rs +++ b/crates/openhuman-core/src/agent/session_host/codec.rs @@ -87,7 +87,11 @@ impl TranscriptCodec for OpenHumanTranscriptCodec { // 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); + crate::agent::tinyagents::discovery::carry_forward( + &prior, + &mut reconciled.rows, + sidecar.discovery_record.as_ref(), + ); // 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 caf1d6b0e6b..f0ce12888da 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 @@ -249,6 +249,7 @@ fn the_codec_records_replay_options_on_the_first_new_row_only_once() { tool_result_max_age_turns: Some(6), tool_result_exempt_tools: vec!["tool_search".into()], replay_reasoning: ReasoningReplay::CurrentTurn, + keep_recent_tokens: None, }; let context = OpenHumanRunContext::new(); context.session_sidecar.lock().unwrap().replay_record = Some(wanted.clone()); @@ -408,3 +409,159 @@ fn replay_pin_survives_compaction() { .unwrap(); assert_eq!(ReplayOptions::recorded_in(&rows), None); } + +fn turn_options(context: OpenHumanRunContext) -> TranscriptTurnOptions { + TranscriptTurnOptions { + request_id: Some("turn".into()), + thread_id: None, + stream: false, + resume: ResumeMode::Never, + context, + } +} + +/// A host that forces new discovery options onto a thread records them on a +/// later row. A compaction that keeps the system row (and the older pin on it) +/// but folds that later row away must not hand the thread back to the older +/// pin. +#[test] +fn a_forced_discovery_pin_survives_compaction_that_folds_its_row_but_keeps_an_older_pin() { + use crate::agent::tinyagents::discovery::DiscoveryOptions; + + let first = DiscoveryOptions { + collapse_search_results: true, + ..DiscoveryOptions::TODAY + }; + let forced = DiscoveryOptions { + compact_search_results: true, + ..DiscoveryOptions::TODAY + }; + let started = OpenHumanRunContext::new(); + started.session_sidecar.lock().unwrap().discovery_record = Some(first); + let one = vec![ + Message::system("prompt"), + Message::user("one"), + Message::assistant("first answer"), + ]; + let prior = OpenHumanTranscriptCodec + .reconcile(&[], &[], &one, &turn_options(started)) + .unwrap(); + + // The host forces new options on the second turn: recorded on its user row. + let forcing = OpenHumanRunContext::new(); + forcing.session_sidecar.lock().unwrap().discovery_record = Some(forced); + let mut two = one.clone(); + two.push(Message::user("two")); + two.push(Message::assistant("second answer")); + let prior = OpenHumanTranscriptCodec + .reconcile(&prior, &one, &two, &turn_options(forcing)) + .unwrap(); + assert_eq!(DiscoveryOptions::recorded_in(&prior), Some(forced)); + + // The compaction keeps the system row, so the older pin survives on it, + // and folds the forced row into a summary. + let compacted = vec![ + Message::system("prompt"), + Message::user("summary of the first two turns"), + Message::assistant("second answer"), + ]; + let rows = OpenHumanTranscriptCodec + .reconcile( + &prior, + &two, + &compacted, + &turn_options(OpenHumanRunContext::new()), + ) + .unwrap(); + assert_eq!( + DiscoveryOptions::recorded_in(&rows), + Some(forced), + "the thread keeps the options it was last forced onto" + ); + assert_eq!( + rows[0], prior[0], + "the retained system row is not rewritten" + ); +} + +/// Forcing options on the turn that also compacts: the fresh rows come before +/// a retained row that still carries the old pin, which would win on every +/// later turn. +#[test] +fn a_forced_discovery_pin_beats_an_older_pin_on_a_row_the_compaction_retained() { + use crate::agent::tinyagents::discovery::DiscoveryOptions; + + let older = DiscoveryOptions { + collapse_search_results: true, + ..DiscoveryOptions::TODAY + }; + let forced = DiscoveryOptions { + compact_search_results: true, + ..DiscoveryOptions::TODAY + }; + let history = vec![ + Message::system("prompt"), + Message::user("one"), + Message::assistant("first answer"), + Message::user("two"), + Message::assistant("second answer"), + ]; + let mut prior = OpenHumanTranscriptCodec + .reconcile( + &[], + &[], + &history, + &turn_options(OpenHumanRunContext::new()), + ) + .unwrap(); + assert!(older.record_on(&mut prior, &[false, false, false, true, false])); + + let forcing = OpenHumanRunContext::new(); + forcing.session_sidecar.lock().unwrap().discovery_record = Some(forced); + 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, &turn_options(forcing)) + .unwrap(); + assert_eq!(DiscoveryOptions::recorded_in(&rows), Some(forced)); + assert_eq!(rows[2], prior[3], "the retained row is not rewritten"); +} + +/// A retry of an interrupted message can reach the codec before the model has +/// answered, so the turn has no fresh row. Forcing options then has nowhere to +/// be recorded, and the codec must not rewrite a stored row to make room: the +/// commit would stop extending the thread and open a new generation. +#[test] +fn a_forced_discovery_pin_never_rewrites_a_stored_row_when_the_turn_has_no_fresh_row() { + use crate::agent::tinyagents::discovery::DiscoveryOptions; + + let started = DiscoveryOptions { + collapse_search_results: true, + ..DiscoveryOptions::TODAY + }; + let forced = DiscoveryOptions { + compact_search_results: true, + ..DiscoveryOptions::TODAY + }; + let first = OpenHumanRunContext::new(); + first.session_sidecar.lock().unwrap().discovery_record = Some(started); + let history = vec![ + Message::system("prompt"), + Message::user("one"), + Message::assistant("first answer"), + ]; + let prior = OpenHumanTranscriptCodec + .reconcile(&[], &[], &history, &turn_options(first)) + .unwrap(); + + let forcing = OpenHumanRunContext::new(); + forcing.session_sidecar.lock().unwrap().discovery_record = Some(forced); + let rows = OpenHumanTranscriptCodec + .reconcile(&prior, &history, &history, &turn_options(forcing)) + .unwrap(); + assert_eq!(rows, prior, "no stored row is touched"); +} 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 index 21d662ca4f4..809c5122c6d 100644 --- a/crates/openhuman-core/src/agent/session_host/discovery_pin_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/discovery_pin_tests.rs @@ -76,3 +76,41 @@ fn a_thread_created_with_todays_behaviour_records_nothing_and_stays_that_way() { ); }); } + +/// A thread whose durable history was imported has rows but no frozen prefix +/// and no recorded options: it ran before they existed, so it keeps today's +/// behaviour whatever the config says now, like any other unrecorded thread. +#[test] +fn a_thread_with_imported_history_and_no_record_keeps_todays_behaviour() { + use tinyagents_session::transcript::TranscriptMessage; + + run_async(async { + // No TinySecurity module runs in a unit test, so the screen would hold the input. + let _off = crate::security::switch::off_for_this_thread(); + let root = tempfile::tempdir().expect("tempdir"); + let thread = thread_id("imported-unpinned"); + let next = model(vec![ModelResponse::assistant("ok")], true); + let mut host = build_host_with_config( + root.path(), + next, + true, + &thread, + agent_config(no_promotion()), + ); + let imported = [ + TranscriptMessage::user("legacy question"), + TranscriptMessage::assistant("legacy answer"), + ]; + assert!(host.adopt_imported_history(&imported).expect("adopt")); + host.turn("hello").await.expect("turn"); + let session = host.session.clone().expect("bound session"); + let records: usize = store_tree(root.path(), &thread, &session) + .values() + .map(|stored| stored.to_string().matches(DISCOVERY_METADATA_KEY).count()) + .sum(); + assert_eq!( + records, 0, + "the config of today must not be adopted by a thread that predates the pin" + ); + }); +} 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 b1231dd75eb..f681179e7a3 100644 --- a/crates/openhuman-core/src/agent/session_host/driver/execute.rs +++ b/crates/openhuman-core/src/agent/session_host/driver/execute.rs @@ -134,6 +134,9 @@ impl SessionDriver for OpenHumanSessionDriver { crate::agent::tinyagents::host::run_context::SessionRunOptions::of( &request.run_context.config, ); + // The close and the required-output repair run after the loop, outside + // the harness's request builder, so they apply the same options. + let replay = run_context.session_run_options.clone(); let cancellation = request.run_context.cancellation.clone(); // Boxing avoids worker-stack overflow in debug builds. let turn = Box::pin(async move { @@ -249,6 +252,7 @@ impl SessionDriver for OpenHumanSessionDriver { &outcome, close_by.map(|at| at.saturating_duration_since(Instant::now())), supplemental_trace.as_ref(), + &replay, ) => close, }; let mut output = close @@ -319,6 +323,7 @@ impl SessionDriver for OpenHumanSessionDriver { outcome.model_calls.saturating_add(1) as u32, &mut repair_usage, supplemental_trace.as_ref(), + &replay, ); tokio::pin!(repair); tokio::select! { diff --git a/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs b/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs index 1815a98133a..f13f8f10978 100644 --- a/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs +++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs @@ -17,7 +17,10 @@ use tinyagents_harness::middleware::wrap_harness_instruction; use crate::agent::{ session_host::{product_copy, stop_policy}, - tinyagents::{SupplementalTrace, TinyagentsTurnOutcome, TurnModelSource}, + tinyagents::{ + host::run_context::SessionRunOptions, SupplementalTrace, TinyagentsTurnOutcome, + TurnModelSource, + }, }; use tinyagents_harness::turn_policy::AGENT_TURN_MAX_OUTPUT_TOKENS; use tinyinference_llm::usage::BilledUsage; @@ -293,10 +296,12 @@ pub(super) async fn repair_required_output( iteration: u32, usage: &mut RepairUsage, trace: Option<&Arc>, + replay: &SessionRunOptions, ) -> Option { use tinyagents_harness::config as required; - let prompt_history: Vec = history + let prompt_history: Vec = replay + .replayed(history) .iter() .filter_map(message_to_native_chat_message) .map(|message| crate::agent::tinyagents::chat_message_to_message(&message)) @@ -407,6 +412,7 @@ pub(super) async fn close_if_needed( outcome: &TinyagentsTurnOutcome, budget: Option, trace: Option<&Arc>, + replay: &SessionRunOptions, ) -> Option { let needs_cap_close = outcome.hit_cap && !outcome.wrap_up_injected; let needs_final_close = outcome.text.trim().is_empty() @@ -422,7 +428,8 @@ pub(super) async fn close_if_needed( let records = product_copy::close_results(&outcome.tool_outcomes); let rendered = product_copy::render_close_results(&records, 16_000); let instruction = close_instruction(outcome, needs_cap_close, &rendered); - let history: Vec = base_history + let history: Vec = replay + .replayed(base_history) .iter() .filter_map(message_to_native_chat_message) .map(|message| crate::agent::tinyagents::chat_message_to_message(&message)) diff --git a/crates/openhuman-core/src/agent/session_host/driver/grounded_close_replay_tests.rs b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_replay_tests.rs new file mode 100644 index 00000000000..7ad69344976 --- /dev/null +++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_replay_tests.rs @@ -0,0 +1,136 @@ +//! The grounded close builds its own request after the run loop, so it has to +//! apply the thread's pinned replay options itself: a thread that expires old +//! tool results or replays only the current turn's reasoning must not send +//! either of them to the model in the close. + +use super::*; +use tinyagents_harness::reasoning_replay::ReasoningReplay; +use tinyagents_harness::result_expiry::ExpiryOverrides; +use tinyagents_harness::testkit::ScriptedModel; +use tinyinference_llm::message::{AssistantMessage, ContentBlock, Message, ToolMessage}; +use tinyinference_llm::tool::ToolCall; + +const OLD_RESULT: &str = "three crates, listed at length"; + +/// Three user turns, the first of which called a tool and reasoned about it. +fn history() -> Vec { + vec![ + Message::user("inspect the workspace"), + Message::Assistant(AssistantMessage { + id: Some("assistant-1".into()), + content: vec![ + ContentBlock::thinking("old reasoning"), + ContentBlock::Text("calling the tool".into()), + ], + tool_calls: vec![ToolCall { + id: "tool-call-1".into(), + name: "list_directory".into(), + arguments: serde_json::json!({"path": "."}), + invalid: None, + }], + usage: None, + origin: None, + }), + Message::Tool(ToolMessage { + tool_call_id: "tool-call-1".into(), + content: vec![ContentBlock::Text(OLD_RESULT.into())], + trusted_verbatim: false, + artifact: None, + }), + Message::assistant("three crates"), + Message::user("and now?"), + Message::assistant("nothing else"), + Message::user("summarize"), + Message::Assistant(AssistantMessage { + id: Some("assistant-2".into()), + content: vec![ + ContentBlock::thinking("current reasoning"), + ContentBlock::Text("looking again".into()), + ], + tool_calls: Vec::new(), + usage: None, + origin: None, + }), + ] +} + +fn pinned() -> SessionRunOptions { + SessionRunOptions { + result_expiry: ExpiryOverrides { + enabled: Some(true), + max_age_turns: Some(1), + exempt_tools: Some(Vec::new()), + }, + replay_reasoning: Some(ReasoningReplay::CurrentTurn), + ..SessionRunOptions::default() + } +} + +/// The close request's messages, as text, and every reasoning block it carries. +async fn close_request_under(replay: &SessionRunOptions) -> (Vec, Vec) { + let scripted = Arc::new(ScriptedModel::new(vec![ + tinyinference_llm::model::ModelResponse::assistant("The workspace holds three crates."), + tinyinference_llm::model::ModelResponse::assistant("ACCEPT"), + ])); + let source = TurnModelSource::from_model(scripted.clone()); + close_if_needed( + &source, + "host-selected-model", + 0.0, + None, + &tinytools_agent::dialect::NativeDialect, + &history(), + "summarize", + &super::blank_outcome(false), + None, + None, + replay, + ) + .await + .expect("a blank terminal reply needs a close"); + let request = scripted.requests().remove(0); + let reasoning = request + .messages + .iter() + .filter_map(|message| match message { + Message::Assistant(assistant) => Some(&assistant.content), + _ => None, + }) + .flatten() + .filter_map(|block| match block { + ContentBlock::Thinking { text, .. } => Some(text.clone()), + _ => None, + }) + .collect(); + ( + request.messages.iter().map(Message::text).collect(), + reasoning, + ) +} + +#[tokio::test] +async fn the_close_request_applies_the_pinned_expiry_and_reasoning_replay() { + let (texts, reasoning) = close_request_under(&pinned()).await; + assert!( + !texts.iter().any(|text| text == OLD_RESULT), + "an expired result must not reach the close request, got {texts:?}" + ); + assert!( + texts + .iter() + .any(|text| text.starts_with("[used list_directory:")), + "the expired result stands as a note, got {texts:?}" + ); + assert_eq!( + reasoning, + ["current reasoning"], + "a past turn's reasoning is left out and the current turn's kept" + ); +} + +#[tokio::test] +async fn the_close_request_of_a_thread_with_no_pinned_options_is_unchanged() { + let (texts, reasoning) = close_request_under(&SessionRunOptions::default()).await; + assert!(texts.iter().any(|text| text == OLD_RESULT)); + assert_eq!(reasoning, ["old reasoning", "current reasoning"]); +} diff --git a/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs index e1fad281d35..61b85817326 100644 --- a/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs @@ -152,6 +152,7 @@ async fn grounded_close_uses_the_selected_model_and_keeps_verifier_out_of_contex &outcome, None, None, + &SessionRunOptions::default(), ) .await .expect("blank terminal reply needs a close"); @@ -198,6 +199,7 @@ async fn terminal_failed_close_requests_are_counted_without_usage() { &blank_outcome(false), None, None, + &SessionRunOptions::default(), ) .await .expect("blank terminal reply needs a close"); @@ -244,6 +246,7 @@ async fn close_state_machine_calls_emit_correlated_native_model_events() { &blank_outcome(false), None, Some(&trace), + &SessionRunOptions::default(), ) .await .expect("blank terminal reply needs a close"); @@ -387,6 +390,7 @@ async fn close_stream_eof_and_timeout_emit_terminal_traces_without_timeout_usage &blank_outcome(false), pending.then_some(std::time::Duration::from_secs(1)), Some(&trace), + &SessionRunOptions::default(), ) .await .expect("blank terminal reply needs a close"); @@ -450,6 +454,7 @@ async fn required_output_repair_preserves_all_host_output_placements() { 1, &mut usage, None, + &SessionRunOptions::default(), ) .await .expect("reply lacks the required block"); @@ -575,6 +580,7 @@ async fn timed_out_repair_keeps_the_usage_of_its_answered_call() { 2, &mut usage, None, + &SessionRunOptions::default(), ), ) .await; @@ -683,3 +689,6 @@ fn supplemental_free_route_uses_zero_catalog_rates() { #[path = "grounded_close_typed_stop_tests.rs"] mod typed_stop; + +#[path = "grounded_close_replay_tests.rs"] +mod replay; diff --git a/crates/openhuman-core/src/agent/session_host/driver/grounded_close_typed_stop_tests.rs b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_typed_stop_tests.rs index 3a3681eb13d..68c4e737e46 100644 --- a/crates/openhuman-core/src/agent/session_host/driver/grounded_close_typed_stop_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_typed_stop_tests.rs @@ -186,6 +186,7 @@ async fn typed_cause_without_halt_note_still_closes_and_keeps_operation() { &outcome, None, None, + &SessionRunOptions::default(), ) .await .expect("typed cause closes without a note"); 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 index 6c0b5cc8739..b704427aa5b 100644 --- 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 @@ -37,8 +37,19 @@ fn host_with_context( model: Arc, thread: &str, context: crate::config::ContextSettings, +) -> crate::agent::OpenHumanSessionHost { + host_with_context_and_contract(root, model, thread, context, None) +} + +fn host_with_context_and_contract( + root: &std::path::Path, + model: Arc, + thread: &str, + context: crate::config::ContextSettings, + required_output: Option, ) -> crate::agent::OpenHumanSessionHost { let mut config = crate::config::Config::default(); + config.agent.required_output = required_output; config.workspace_dir = root.join("workspace"); config.action_dir = root.to_path_buf(); config.config_path = root.join("config.toml"); @@ -50,6 +61,7 @@ fn host_with_context( let mut host = crate::agent::SessionHostBuilder::new() .with_session_history_locator(store_locator(root)) .model_name("test/session-fixture".to_string()) + .config(config.agent.clone()) .chat_model_with_config(chat_model, Arc::new(config)) .tools(vec![Box::new(EchoTool)]) .tool_dispatcher(Box::new(tinytools_agent::dialect::NativeDialect)) @@ -143,3 +155,98 @@ fn a_tool_result_is_sent_in_full_while_expiry_is_off() { } }); } + +/// A thread whose durable history was imported has rows but no frozen prefix +/// and no recorded options: it predates the pin, so it keeps today's replay +/// (nothing expires) whatever `[context]` says now. +#[test] +fn a_thread_with_imported_history_and_no_record_keeps_todays_replay() { + use crate::agent::tinyagents::replay_pin::REPLAY_METADATA_KEY; + use tinyagents_session::transcript::TranscriptMessage; + + run_async(async { + let root = tempfile::tempdir().expect("tempdir"); + let thread = thread_id("imported-unpinned-replay"); + let model = Arc::new( + ScriptedModel::new(vec![ModelResponse::assistant("ok")]).with_profile(ModelProfile { + tool_calling: true, + ..Default::default() + }), + ); + let mut context = crate::config::ContextSettings::default(); + context.tool_result_max_age_turns = Some(2); + let mut host = host_with_context(root.path(), model, &thread, context); + let imported = [ + TranscriptMessage::user("legacy question"), + TranscriptMessage::assistant("legacy answer"), + ]; + assert!(host.adopt_imported_history(&imported).expect("adopt")); + host.turn("hello").await.expect("turn"); + let session = host.session.clone().expect("bound session"); + let records: usize = + super::transcript_compat_tests::store_tree(root.path(), &thread, &session) + .values() + .map(|stored| stored.to_string().matches(REPLAY_METADATA_KEY).count()) + .sum(); + assert_eq!( + records, 0, + "the config of today must not be adopted by a thread that predates the pin" + ); + }); +} + +/// A required-output repair is a tools-off request built after the loop. On a +/// thread with expiry at one user turn, a tool turn, a plain turn and a second +/// tool turn leave the first result stale when the third turn's reply, which +/// lacks the required block, is repaired. +#[test] +fn the_required_output_repair_request_carries_expired_results_as_notes() { + run_async(async { + let _off = crate::security::switch::off_for_this_thread(); + let root = tempfile::tempdir().expect("tempdir"); + let thread = thread_id("expiry-repair"); + let repaired = ModelResponse::assistant("{\"answer\":\"ok\"}"); + // Every reply lacks the block, so every turn is repaired once. + let script = vec![ + response(Vec::new(), vec![call("call-1", "echo", json!({"q": "x"}))]), + ModelResponse::assistant("first done"), + repaired.clone(), + ModelResponse::assistant("second done"), + repaired.clone(), + response(Vec::new(), vec![call("call-2", "echo", json!({"q": "y"}))]), + ModelResponse::assistant("third done"), + repaired, + ]; + let model = Arc::new(ScriptedModel::new(script).with_profile(ModelProfile { + tool_calling: true, + ..Default::default() + })); + let mut context = crate::config::ContextSettings::default(); + context.tool_result_max_age_turns = Some(1); + let mut host = host_with_context_and_contract( + root.path(), + model.clone(), + &thread, + context, + Some(crate::config::RequiredOutputContract::new("answer")), + ); + for turn in ["first", "second", "third"] { + host.turn(turn).await.expect("turn"); + } + let requests = model.requests(); + let repair = requests.last().expect("the third turn's repair request"); + assert!(repair.tools.is_empty(), "the last request is the repair"); + let results = tool_results(repair); + assert_eq!(results.len(), 2, "{results:?}"); + assert!( + results[0].starts_with("[used echo:"), + "the stale result must go out as a note, got {:?}", + results[0] + ); + assert!( + results[1].contains(TOOL_BODY), + "this turn's own result stays whole, got {:?}", + results[1] + ); + }); +} 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 b1b1338850a..6786cfbf05d 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 @@ -156,12 +156,13 @@ impl OpenHumanSessionHost { .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 generation_start = super::turn::prepare_prefix_for_turn( - new_session, - view.prefix_is_frozen, - ); + // by the turn that creates the thread and recorded with + // it, read back from the transcript on every other. A + // thread that has history but no frozen prefix (imported + // rows) is not new: it predates the pin and keeps + // today's behaviour, however its prefix gets prepared. + let generation_start = + super::turn::starts_thread(new_session, view.raw_history); let discovery = crate::agent::tinyagents::discovery::resolve( &prelude.config.tool_search, view.raw_history, @@ -273,6 +274,10 @@ impl OpenHumanSessionHost { ) })?; middleware.transcript_snapshot = Some(transcript_snapshot); + // A tail the thread pinned wins over the configured one. + middleware.keep_recent_tokens = replay + .effective + .keep_recent_tokens_or(middleware.keep_recent_tokens); options.run_context.data.context_middleware = Some(middleware); options.run_context.data.current_tools = Some(current_tools); if !turn.overrides.suppress_tools { 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 5ba1564b790..90c1a128c50 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 @@ -12,6 +12,18 @@ use crate::agent::{ tinyagents::host::OpenHumanRunContext, }; +/// Whether a turn creates its thread, so it chooses the thread's pinned options +/// from the config. A thread with durable rows (imported history) is not new +/// even before its prefix is frozen: it predates the pin. A session that was +/// resumed from a store but holds no rows yet is new, though `new_session` +/// (which also asks that nothing was loaded) says otherwise. +pub(super) fn starts_thread( + new_session: bool, + stored_rows: &[tinyagents_session::transcript::TranscriptMessage], +) -> bool { + new_session || stored_rows.is_empty() +} + pub(super) fn prepare_prefix_for_turn(new_session: bool, prefix_is_frozen: bool) -> bool { new_session || !prefix_is_frozen } diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_turn_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_turn_tests.rs index 943a8ca61ad..1c8ebc4380b 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session_turn_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session_turn_tests.rs @@ -60,3 +60,17 @@ fn a_later_runtime_cancellation_is_not_reclassified_from_a_stale_sidecar() { .is_none()); assert_eq!(error.to_string(), "session turn cancelled"); } + +#[test] +fn a_resumed_session_with_no_rows_starts_its_thread() { + // The store created the session but has written nothing to it. + assert!(starts_thread(false, &[])); + assert!(starts_thread(true, &[])); +} + +#[test] +fn a_session_with_imported_rows_does_not_start_a_thread() { + use tinyagents_session::transcript::TranscriptMessage; + let imported = [TranscriptMessage::user("legacy question")]; + assert!(!starts_thread(false, &imported)); +} diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs index be0a3744589..4dcc93119aa 100644 --- a/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs +++ b/crates/openhuman-core/src/agent/tinyagents/discovery/pin.rs @@ -13,7 +13,8 @@ //! 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`]). +//! of the generation it opens ([`carry_forward`]), or onto its last row when a +//! retained row holds an older record. //! //! A thread that records nothing (every thread written before this existed, //! and any thread created with today's behaviour) resolves to @@ -144,8 +145,9 @@ 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. +/// Carries the latest options recorded on `prior`, or the `forced` ones this +/// turn records, onto `rows`, a transcript about to open a compacted +/// generation, when `rows` does not end up with them as its latest record. /// Returns whether it recorded them. /// /// A compaction writes the retained rows into a fresh generation. The record @@ -154,14 +156,42 @@ pub(crate) fn record_metadata( /// 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() { +/// +/// A retained row can also hold an *older* record while a later row, folded +/// away, held the latest: a host that forced new options recorded them on a +/// later row, and the latest record wins. The latest options are then written +/// onto the last row, after every retained one, so the older record cannot win +/// again. `forced`, the options this turn records on its first fresh row, takes +/// precedence over `prior`, since a fresh row can precede a retained one. +/// `rows` that merely extend `prior` are left alone. +pub fn carry_forward( + prior: &[TranscriptMessage], + rows: &mut [TranscriptMessage], + forced: Option<&DiscoveryOptions>, +) -> bool { + // A turn that extends the stored rows appends; it never needs a record + // carried, and writing one onto a stored row would rewrite it, so the + // commit would open a new generation instead of extending the thread. + if rows.len() >= prior.len() && rows[..prior.len()] == *prior { return false; } - let Some(options) = DiscoveryOptions::recorded_in(prior) else { + let Some(latest) = forced + .copied() + .or_else(|| DiscoveryOptions::recorded_in(prior)) + else { return false; }; - options.record_on(rows, &[true]) + match DiscoveryOptions::recorded_in(rows) { + Some(held) if held == latest => false, + Some(_) => { + let mut last = vec![false; rows.len()]; + if let Some(slot) = last.last_mut() { + *slot = true; + } + latest.record_on(rows, &last) + } + None => latest.record_on(rows, &[true]), + } } impl Default for DiscoveryOptions { 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 dead4e8973f..4b86e599507 100644 --- a/crates/openhuman-core/src/agent/tinyagents/discovery/pin_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/discovery/pin_tests.rs @@ -228,16 +228,20 @@ fn compaction_carries_the_record_onto_the_first_row_of_the_new_generation() { TranscriptMessage::system("refreshed prompt"), TranscriptMessage::new("user", "summary"), ]; - assert!(carry_forward(&prior, &mut next)); + assert!(carry_forward(&prior, &mut next, None)); 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!(!carry_forward(&prior, &mut next, None)); assert_eq!(next, before); let mut bare = vec![TranscriptMessage::system("prompt")]; - assert!(!carry_forward(&[TranscriptMessage::system("p")], &mut bare)); + assert!(!carry_forward( + &[TranscriptMessage::system("p")], + &mut bare, + None + )); assert!(bare[0].extra_metadata.is_none()); - assert!(!carry_forward(&prior, &mut [])); + assert!(!carry_forward(&prior, &mut [], None)); } 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 682f3e97176..d66f03fe801 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs @@ -178,6 +178,30 @@ impl SessionRunOptions { } } + /// `history` as a model request under these options carries it: expired + /// tool results as notes, past turns' reasoning left out. For the requests + /// a driver builds after the run loop (a grounded close, a required-output + /// repair), which the harness's own request builder does not reach. + pub(crate) fn replayed( + &self, + history: &[tinyinference_llm::message::Message], + ) -> Vec { + let mut messages = history.to_vec(); + // Every field is set by a session that pinned options, so the + // harness-wide defaults only fill in for a run that pinned none. + let expiry = tinyagents_harness::result_expiry::ToolResultExpiryPolicy::default() + .with_overrides(&self.result_expiry); + if expiry.enabled { + tinyagents_harness::result_expiry::expire_tool_results(&mut messages, &expiry); + } + if self.replay_reasoning + == Some(tinyagents_harness::reasoning_replay::ReasoningReplay::CurrentTurn) + { + tinyagents_harness::reasoning_replay::drop_past_turn_reasoning(&mut messages); + } + messages + } + /// Whether no option is set. pub(crate) fn is_empty(&self) -> bool { *self == Self::default() diff --git a/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs b/crates/openhuman-core/src/agent/tinyagents/replay_pin.rs index d4f7ff2dd03..4d9c391c25e 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. //! +//! The compaction tail (`[context] keep_recent_tokens`) is pinned with them, +//! but only when the thread started with one: a thread that pinned none follows +//! the config, as every thread did before. +//! //! 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. @@ -42,6 +46,11 @@ pub struct ReplayOptions { pub tool_result_exempt_tools: Vec, /// Which turns' reasoning a request carries. pub replay_reasoning: ReasoningReplay, + /// The verbatim tail, in tokens, an in-turn compaction keeps after its + /// summary. `None` is not pinned: the config's value applies, as it does + /// for a thread that recorded nothing. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub keep_recent_tokens: Option, } impl ReplayOptions { @@ -51,6 +60,7 @@ impl ReplayOptions { tool_result_max_age_turns: None, tool_result_exempt_tools: Vec::new(), replay_reasoning: ReasoningReplay::All, + keep_recent_tokens: None, }; /// The options `[context]` asks new threads to start with. An age of `0` @@ -66,9 +76,16 @@ impl ReplayOptions { Vec::new() }, replay_reasoning: config.replay_reasoning.into(), + keep_recent_tokens: config.keep_recent_tokens, } } + /// The compaction tail a turn on this thread keeps: the pinned one, or + /// `configured` while the thread pinned none. + pub fn keep_recent_tokens_or(&self, configured: Option) -> Option { + self.keep_recent_tokens.map(u64::from).or(configured) + } + /// The per-run overrides that make the harness expire results exactly as /// these options say. pub fn expiry_overrides(&self) -> ExpiryOverrides { 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 181d3534426..f2dcb3ed86c 100644 --- a/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/replay_pin_tests.rs @@ -153,3 +153,70 @@ fn replay_and_discovery_records_share_a_row_without_clobbering_each_other() { assert_eq!(DiscoveryOptions::recorded_in(&rows), Some(discovery)); assert_eq!(ReplayOptions::recorded_in(&rows), Some(replay)); } + +fn with_keep_recent(tokens: Option) -> ContextSettings { + let mut settings = ContextSettings::default(); + settings.keep_recent_tokens = tokens; + settings +} + +#[test] +fn a_new_thread_pins_the_compaction_tail_it_starts_with() { + let created = resolve(&with_keep_recent(Some(12_000)), &[], true); + assert_eq!(created.effective.keep_recent_tokens, Some(12_000)); + assert_eq!( + created + .record + .as_ref() + .map(|options| options.keep_recent_tokens), + Some(Some(12_000)), + "a tail that differs from the default is written down" + ); + + // Not asking for one records nothing, as before. + let plain = resolve(&with_keep_recent(None), &[], true); + assert_eq!(plain.effective, ReplayOptions::TODAY); + assert_eq!(plain.record, None); +} + +#[test] +fn a_resumed_thread_keeps_its_pinned_compaction_tail_whatever_the_config_says_now() { + let started_with = ReplayOptions::from_config(&with_keep_recent(Some(12_000))); + let mut rows = vec![ + TranscriptMessage::system("prompt"), + TranscriptMessage::new("user", "hi"), + ]; + assert!(started_with.record_on(&mut rows, &[true, true])); + + for now in [None, Some(3_000)] { + let resumed = resolve(&with_keep_recent(now), &rows, false); + assert_eq!(resumed.effective.keep_recent_tokens, Some(12_000)); + assert_eq!(resumed.record, None, "a turn override never re-pins it"); + } +} + +#[test] +fn a_pinned_compaction_tail_beats_the_configured_one_and_an_unpinned_thread_follows_it() { + let pinned = ReplayOptions::from_config(&with_keep_recent(Some(12_000))); + assert_eq!(pinned.keep_recent_tokens_or(Some(3_000)), Some(12_000)); + assert_eq!(pinned.keep_recent_tokens_or(None), Some(12_000)); + + assert_eq!( + ReplayOptions::TODAY.keep_recent_tokens_or(Some(3_000)), + Some(3_000) + ); + assert_eq!(ReplayOptions::TODAY.keep_recent_tokens_or(None), None); +} + +#[test] +fn a_record_without_a_compaction_tail_reads_back_and_writes_the_same_bytes() { + // Written before the tail was pinned: no `keep_recent_tokens` key. + let stored = serde_json::json!({ + "tool_result_max_age_turns": 6, + "tool_result_exempt_tools": ["tool_search"], + "replay_reasoning": "current_turn", + }); + let read: ReplayOptions = serde_json::from_value(stored.clone()).unwrap(); + assert_eq!(read.keep_recent_tokens, None); + assert_eq!(serde_json::to_value(&read).unwrap(), stored); +} 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 a5e011db735..5311c58cef5 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 @@ -423,8 +423,10 @@ impl Config { // `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), + "" => Some(None), value => match value.parse::() { + // Every spelling of zero (`0`, `00`) clears the cap. + Ok(0) => Some(None), Ok(chars) => Some(Some(chars)), Err(_) => { tracing::warn!( @@ -435,6 +437,11 @@ impl Config { }, }; if let Some(cap) = cap { + if cap.is_none() { + tracing::debug!( + "[config] OPENHUMAN_SEARCH_CONTENTS_MAX_CHARS clears the search contents cap" + ); + } self.search.contents_max_chars = cap; self.record_env_override( env, 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 190e2c39011..dd25f96f82e 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 @@ -703,3 +703,24 @@ fn search_compact_results_and_contents_cap_env_set_clear_and_ignore_garbage() { assert!(!cfg.search.compact_results); assert_eq!(cfg.search.contents_max_chars, None); } + +#[test] +fn search_contents_cap_env_treats_every_zero_spelling_as_unset() { + for zero in ["0", "00", " 000 "] { + let mut cfg = Config::default(); + cfg.search.contents_max_chars = Some(1_200); + cfg.apply_env_overlay_with( + &HashMapEnv::new().with("OPENHUMAN_SEARCH_CONTENTS_MAX_CHARS", zero), + ); + assert_eq!( + cfg.search.contents_max_chars, None, + "{zero:?} must clear the cap, not become a one-character cap" + ); + } + // A leading zero on a positive value is still that value. + let mut cfg = Config::default(); + cfg.apply_env_overlay_with( + &HashMapEnv::new().with("OPENHUMAN_SEARCH_CONTENTS_MAX_CHARS", "01"), + ); + assert_eq!(cfg.search.contents_max_chars, Some(1)); +} diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rs index ac1cd704ce1..09ea817c8e2 100644 --- a/crates/openhuman-embed/src/agent/build.rs +++ b/crates/openhuman-embed/src/agent/build.rs @@ -178,9 +178,19 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result { + let ms = u64::try_from(deadline.as_millis()).unwrap_or(u64::MAX); + log::debug!("[embed][agent] id={id} binding sets memory_block_deadline_ms={ms}"); + config.memory.memory_block_deadline_ms = Some(ms); + } + None => log::debug!( + "[embed][agent] id={id} binding inherits memory_block_deadline_ms={:?}", + config.memory.memory_block_deadline_ms + ), + } } if let Some(options) = parts.tool_discovery { diff --git a/crates/openhuman-embed/src/agent/build_tests.rs b/crates/openhuman-embed/src/agent/build_tests.rs index 37fa428ee35..dd5fdef4fde 100644 --- a/crates/openhuman-embed/src/agent/build_tests.rs +++ b/crates/openhuman-embed/src/agent/build_tests.rs @@ -295,3 +295,63 @@ fn an_agent_with_no_context_overrides_behaves_as_before() { assert_eq!(context.replay_reasoning, crate::ReasoningReplay::All); assert!(!context.prune_retired_tools); } + +/// A built agent's `[memory]` table, for an agent built from `spec` on a +/// runtime whose own config sets `memory_block_deadline_ms = 250`. +fn built_memory_on_a_runtime_with_a_deadline( + spec: crate::AgentSpec, +) -> openhuman_core::config::MemoryConfig { + 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 mut 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.memory.memory_block_deadline_ms = Some(250); + 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 memory = agent.inner.config.memory.clone(); + drop(agent); + drop(runtime); + memory + }); + tokio.block_on(test).unwrap() +} + +#[test] +fn a_memory_binding_without_a_deadline_keeps_the_runtimes_memory_block_deadline() { + let memory = built_memory_on_a_runtime_with_a_deadline( + crate::AgentSpec::new("memory-identity-only").memory(crate::MemoryBinding::new("emp-1")), + ); + assert_eq!(memory.agent_id.as_deref(), Some("emp-1")); + assert_eq!( + memory.memory_block_deadline_ms, + Some(250), + "binding only an identity must not clear the inherited deadline" + ); +} + +#[test] +fn a_memory_binding_with_a_deadline_replaces_the_runtimes_memory_block_deadline() { + let memory = built_memory_on_a_runtime_with_a_deadline( + crate::AgentSpec::new("memory-with-deadline").memory( + crate::MemoryBinding::new("emp-2") + .memory_block_deadline(std::time::Duration::from_millis(900)), + ), + ); + assert_eq!(memory.memory_block_deadline_ms, Some(900)); +}