Skip to content

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

fix(ci): align merged tests with runtime APIs

Steven Enamakelb80ad58f86e9
diff --git a/app/src/lib/commands/__tests__/globalActions.test.tsx b/app/src/lib/commands/__tests__/globalActions.test.tsx
index d5368da339..0905bb6599 100644
--- a/app/src/lib/commands/__tests__/globalActions.test.tsx
+++ b/app/src/lib/commands/__tests__/globalActions.test.tsx
@@ -102,7 +102,7 @@ describe('registerGlobalActions', () => {
});
it('exports GROUP_ORDER', () => {
- expect(GROUP_ORDER).toEqual(['Navigation', 'Profiles', 'Chat', 'View', 'General']);
+ expect(GROUP_ORDER).toEqual(['Navigation', 'Chat', 'View', 'General']);
});
it('wires profile-switch shortcuts but keeps them hidden (disabled) until profiles exist', () => {
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_exposure_tests.rs b/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_exposure_tests.rs
index 0269a34520..3f61c5ab81 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_exposure_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_exposure_tests.rs
@@ -7,7 +7,7 @@ fn visible_names(agent_id: &str) -> std::collections::HashSet<String> {
.get(agent_id)
.cloned()
.unwrap_or_else(|| panic!("built-in agent definition not found: {agent_id}"));
- let agent = crate::agent::Agent::from_config_with_definition(&config, &definition, None, None)
+ let agent = crate::agent::Agent::from_config_with_definition(&config, &definition)
.unwrap_or_else(|e| panic!("{agent_id} session build: {e}"));
agent
.visible_tool_specs_arc()
@@ -24,9 +24,8 @@ fn resetting_wildcard_visibility_keeps_collapsed_exposure() {
.get("tools_agent")
.cloned()
.expect("tools_agent built-in definition");
- let mut agent =
- crate::agent::Agent::from_config_with_definition(&config, &definition, None, None)
- .expect("build tools agent");
+ let mut agent = crate::agent::Agent::from_config_with_definition(&config, &definition)
+ .expect("build tools agent");
agent.set_visible_tool_names(std::collections::HashSet::new());
@@ -45,9 +44,8 @@ fn hiding_and_reseeding_wildcard_visibility_keeps_collapsed_exposure() {
.get("tools_agent")
.cloned()
.expect("tools_agent built-in definition");
- let mut agent =
- crate::agent::Agent::from_config_with_definition(&config, &definition, None, None)
- .expect("build tools agent");
+ let mut agent = crate::agent::Agent::from_config_with_definition(&config, &definition)
+ .expect("build tools agent");
agent.set_visible_tool_names(std::collections::HashSet::new());
agent.hide_tools(&[crate::memory::tools::MEMORY_TOOL_NAME]);
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_policy_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_policy_tests.rs
new file mode 100644
index 0000000000..3a91bb535a
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_policy_tests.rs
@@ -0,0 +1,295 @@
+use super::*;
+#[derive(Clone, Default)]
+struct WarnSink(Arc<std::sync::Mutex<Vec<String>>>);
+
+impl WarnSink {
+ /// Every captured message containing `marker`, in emission order.
+ fn matching(&self, marker: &str) -> Vec<String> {
+ self.0
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|line| line.contains(marker))
+ .cloned()
+ .collect()
+ }
+}
+
+struct WarnLayer(WarnSink);
+
+impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for WarnLayer {
+ /// Record the `message` field of every `WARN` event; ignore other levels.
+ fn on_event(
+ &self,
+ event: &tracing::Event<'_>,
+ _ctx: tracing_subscriber::layer::Context<'_, S>,
+ ) {
+ if *event.metadata().level() != tracing::Level::WARN {
+ return;
+ }
+ struct Message(Option<String>);
+ impl tracing::field::Visit for Message {
+ /// Keep the formatted `message` field and discard the rest.
+ fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
+ if field.name() == "message" {
+ self.0 = Some(format!("{value:?}"));
+ }
+ }
+ }
+ let mut message = Message(None);
+ event.record(&mut message);
+ if let Some(text) = message.0 {
+ self.0 .0.lock().unwrap().push(text);
+ }
+ }
+}
+
+/// Stands in for `spawn_subagent`: records whether it was ever dispatched, so a
+/// test can prove the tool was not merely absent from the advertisement but
+/// genuinely unreachable.
+struct SpawnProbeTool(Arc<std::sync::atomic::AtomicBool>);
+
+#[async_trait]
+impl Tool for SpawnProbeTool {
+ /// The exact name the #4452 strip must match.
+ fn name(&self) -> &str {
+ "spawn_subagent"
+ }
+ /// Irrelevant to the strip, which reads only the name.
+ fn description(&self) -> &str {
+ "spawn a sub-agent"
+ }
+ /// Irrelevant to the strip, which reads only the name.
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type": "object"})
+ }
+ /// Records the dispatch. Reaching this line means the test has failed.
+ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ self.0.store(true, Ordering::SeqCst);
+ Ok(ToolResult::success("spawned"))
+ }
+}
+
+/// Asks for `spawn_subagent` once, then finishes regardless of the answer.
+struct SpawnAttemptProvider {
+ calls: AtomicUsize,
+}
+
+#[async_trait]
+impl ChatModel<()> for SpawnAttemptProvider {
+ /// Native tool calling, so the harness advertises tools normally.
+ fn profile(&self) -> Option<&ModelProfile> {
+ Some(native_tool_profile())
+ }
+
+ /// Ask for `spawn_subagent` on the first turn, then finish on the second.
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ if self.calls.fetch_add(1, Ordering::SeqCst) == 0 {
+ Ok(tool_response("1", "spawn_subagent", serde_json::json!({})))
+ } else {
+ Ok(ModelResponse::assistant("all done"))
+ }
+ }
+}
+
+const REFUSAL: &str = "refusing to register spawn/delegate tool";
+
+/// Runs one sub-agent turn whose parent surface carries `spawn_subagent`, with
+/// `allowed` deciding whether the allowlist readmits it. Returns
+/// (spawn tool executed?, refusal warnings emitted).
+async fn run_with_spawn_tool_in_parent_surface(allowed: HashSet<String>) -> (bool, Vec<String>) {
+ use tracing_subscriber::layer::SubscriberExt;
+
+ let executed = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let sink = WarnSink::default();
+ let subscriber = tracing_subscriber::registry().with(WarnLayer(sink.clone()));
+ let _subscriber_guard = tracing::subscriber::set_default(subscriber);
+
+ let provider = Arc::new(SpawnAttemptProvider {
+ calls: AtomicUsize::new(0),
+ });
+ let parent_tools: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![
+ Box::new(EchoTool),
+ Box::new(SpawnProbeTool(executed.clone())),
+ ]);
+ let mut history = vec![ChatMessage::user("spawn a helper")];
+
+ run_subagent_via_graph(
+ crate::agent::tinyagents::TurnModelSource::from_model(provider),
+ "mock-model",
+ 0.0,
+ &mut history,
+ parent_tools,
+ vec![],
+ vec![],
+ allowed,
+ 10,
+ None,
+ None,
+ "researcher",
+ "task-6157",
+ false,
+ None,
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ None,
+ std::env::temp_dir(),
+ None,
+ 1024,
+ false,
+ "root-session__spawn_refusal",
+ "mock-channel",
+ None,
+ AgentTokenjuiceCompression::Off,
+ None,
+ )
+ .await
+ .expect("graph subagent runs");
+
+ (executed.load(Ordering::SeqCst), sink.matching(REFUSAL))
+}
+
+/// The real shape: `run_typed_mode` has already stripped `spawn_subagent` from
+/// the allowlist, so the registration-time backstop is re-refusing a name that
+/// was never admitted. That is the happy path and must not warn (#6157) — the
+/// old unconditional warn fired here on every sub-agent run.
+#[tokio::test]
+async fn a_sub_agent_cannot_reach_a_spawn_tool_and_the_healthy_run_is_quiet() {
+ let allowed = HashSet::from(["echo".to_string()]);
+ let (executed, warnings) = run_with_spawn_tool_in_parent_surface(allowed).await;
+
+ assert!(
+ !executed,
+ "a sub-agent must never be able to invoke spawn_subagent (#4452)"
+ );
+ assert!(
+ warnings.is_empty(),
+ "an already-excluded spawn tool is the happy path, not a warning: {warnings:?}"
+ );
+}
+
+/// The misbuilt-allowlist case the backstop exists for: `spawn_subagent` is
+/// admitted, so registration must still refuse it *and* say so — this is the one
+/// shape in which the warning carries information.
+#[tokio::test]
+async fn an_allowlist_that_readmits_a_spawn_tool_is_refused_loudly() {
+ let allowed = HashSet::from(["echo".to_string(), "spawn_subagent".to_string()]);
+ let (executed, warnings) = run_with_spawn_tool_in_parent_surface(allowed).await;
+
+ assert!(
+ !executed,
+ "the backstop must still refuse the tool, not merely log about it"
+ );
+ assert_eq!(
+ warnings.len(),
+ 1,
+ "the readmitted spawn tool warns exactly once: {warnings:?}"
+ );
+}
+
+/// #5934 (item 1): a mirrored sub-agent **tool result** must not be painted as
+/// something the human typed.
+///
+/// Both worker-thread mirrors write tool output with `sender: "user"`, and the
+/// renderer maps every non-`"agent"` sender to `role: 'user'`
+/// (`app/src/providers/assistantUiMessages.ts:536`) while keying visibility
+/// only on `extraMetadata.hidden` (`:664`, and the same flag in
+/// `ChatThreadView.tsx:312` / `timeline/selectors.ts:50`). Worker threads are
+/// openable chats — `create_worker_thread` stamps `labels: ["tasks"]` and
+/// `threadFilter.ts` lists that tab — so an unflagged mirror row shows the
+/// tool's raw output in a right-aligned user bubble.
+///
+/// The invariant: every non-`"agent"` row these mirrors write is `hidden`. The
+/// record stays in the log for the process rail; it just stops being chat.
+#[test]
+fn mirrored_tool_results_are_hidden_from_the_worker_thread_chat() {
+ use crate::memory::conversations::{self as store, CreateConversationThread};
+
+ let dir = std::env::temp_dir().join(format!("wt-5934-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let now = chrono::Utc::now().to_rfc3339();
+ for id in ["worker-typed", "worker-recovered"] {
+ store::ensure_thread(
+ dir.clone(),
+ CreateConversationThread {
+ id: id.to_string(),
+ title: "task".to_string(),
+ created_at: now.clone(),
+ parent_thread_id: Some("parent-1".to_string()),
+ labels: Some(vec!["tasks".to_string()]),
+ personality_id: None,
+ },
+ )
+ .unwrap();
+ }
+
+ const RAW: &str = "{\"events\":[{\"title\":\"raw tool output the human never typed\"}]}";
+
+ // The typed path (`ConversationMessage::ToolResults`), used on a normal run.
+ mirror_worker_thread(
+ &dir,
+ "worker-typed",
+ "researcher",
+ "task-1",
+ &[
+ ConversationMessage::AssistantToolCalls {
+ text: Some("checking the calendar".to_string()),
+ tool_calls: vec![crate::inference::provider::ToolCall {
+ id: "call-1".to_string(),
+ name: "list_events".to_string(),
+ arguments: "{}".to_string(),
+ extra_content: None,
+ }],
+ reasoning_content: None,
+ extra_metadata: None,
+ },
+ ConversationMessage::ToolResults(vec![crate::agent::messages::ToolResultMessage {
+ tool_call_id: "call-1".to_string(),
+ content: RAW.to_string(),
+ }]),
+ ],
+ Some("Here is your week."),
+ );
+
+ // The error-recovery path (`role: "tool"`), used when a run fails mid-turn.
+ mirror_worker_thread_from_history(
+ &dir,
+ "worker-recovered",
+ "researcher",
+ "task-1",
+ &[
+ ChatMessage::assistant("checking the calendar"),
+ ChatMessage::tool(RAW),
+ ],
+ Some("[subagent run failed before completion]"),
+ );
+
+ // Collected, not asserted per row: both mirrors must be reported, so a
+ // failure names every path that is still painting a tool result as chat.
+ let mut painted_as_user_chat: Vec<String> = Vec::new();
+ for thread_id in ["worker-typed", "worker-recovered"] {
+ let rows = store::get_messages(dir.clone(), thread_id).unwrap();
+ assert!(
+ rows.iter().any(|r| r.content == RAW),
+ "{thread_id}: the mirror wrote no tool-result row to assert on"
+ );
+ for row in rows.iter().filter(|r| r.sender != "agent") {
+ if row.extra_metadata.get("hidden").and_then(|v| v.as_bool()) != Some(true) {
+ painted_as_user_chat.push(format!(
+ "{thread_id}: sender={:?} not hidden: {}",
+ row.sender, row.content
+ ));
+ }
+ }
+ }
+ assert!(
+ painted_as_user_chat.is_empty(),
+ "mirrored tool results render in a user chat bubble:\n{}",
+ painted_as_user_chat.join("\n")
+ );
+
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs
index 352ce51ad0..f6294eec6c 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs
@@ -34,6 +34,8 @@ fn tool_response(id: &str, name: &str, arguments: serde_json::Value) -> ModelRes
resolved_model: None,
continue_turn: None,
served_from_cache: false,
+ correlation: None,
+ resolved_route: None,
}
}
@@ -224,7 +226,7 @@ impl ChatModel<()> for ThinkingStreamProvider {
_request: ModelRequest,
) -> tinyinference_llm::Result<ModelStream> {
let response = ModelResponse::assistant("Hello");
- Ok(Box::pin(futures::stream::iter(vec![
+ Ok(ModelStream::new(Box::pin(futures::stream::iter(vec![
ModelStreamItem::Started,
ModelStreamItem::MessageDelta(MessageDelta {
text: String::new(),
@@ -234,7 +236,7 @@ impl ChatModel<()> for ThinkingStreamProvider {
ModelStreamItem::MessageDelta(MessageDelta::text("Hel")),
ModelStreamItem::MessageDelta(MessageDelta::text("lo")),
ModelStreamItem::Completed(response),
- ])))
+ ]))))
}
}
@@ -522,297 +524,5 @@ async fn cap_hit_summarizes_a_resumable_checkpoint() {
/// Collects the messages of `WARN` events whose text contains a marker, so a
/// test can assert on a log line that has no other observable side effect.
-#[derive(Clone, Default)]
-struct WarnSink(Arc<std::sync::Mutex<Vec<String>>>);
-
-impl WarnSink {
- /// Every captured message containing `marker`, in emission order.
- fn matching(&self, marker: &str) -> Vec<String> {
- self.0
- .lock()
- .unwrap()
- .iter()
- .filter(|line| line.contains(marker))
- .cloned()
- .collect()
- }
-}
-
-struct WarnLayer(WarnSink);
-
-impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for WarnLayer {
- /// Record the `message` field of every `WARN` event; ignore other levels.
- fn on_event(
- &self,
- event: &tracing::Event<'_>,
- _ctx: tracing_subscriber::layer::Context<'_, S>,
- ) {
- if *event.metadata().level() != tracing::Level::WARN {
- return;
- }
- struct Message(Option<String>);
- impl tracing::field::Visit for Message {
- /// Keep the formatted `message` field and discard the rest.
- fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
- if field.name() == "message" {
- self.0 = Some(format!("{value:?}"));
- }
- }
- }
- let mut message = Message(None);
- event.record(&mut message);
- if let Some(text) = message.0 {
- self.0 .0.lock().unwrap().push(text);
- }
- }
-}
-
-/// Stands in for `spawn_subagent`: records whether it was ever dispatched, so a
-/// test can prove the tool was not merely absent from the advertisement but
-/// genuinely unreachable.
-struct SpawnProbeTool(Arc<std::sync::atomic::AtomicBool>);
-
-#[async_trait]
-impl Tool for SpawnProbeTool {
- /// The exact name the #4452 strip must match.
- fn name(&self) -> &str {
- "spawn_subagent"
- }
- /// Irrelevant to the strip, which reads only the name.
- fn description(&self) -> &str {
- "spawn a sub-agent"
- }
- /// Irrelevant to the strip, which reads only the name.
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type": "object"})
- }
- /// Records the dispatch. Reaching this line means the test has failed.
- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.0.store(true, Ordering::SeqCst);
- Ok(ToolResult::success("spawned"))
- }
-}
-
-/// Asks for `spawn_subagent` once, then finishes regardless of the answer.
-struct SpawnAttemptProvider {
- calls: AtomicUsize,
-}
-
-#[async_trait]
-impl ChatModel<()> for SpawnAttemptProvider {
- /// Native tool calling, so the harness advertises tools normally.
- fn profile(&self) -> Option<&ModelProfile> {
- Some(native_tool_profile())
- }
-
- /// Ask for `spawn_subagent` on the first turn, then finish on the second.
- async fn invoke(
- &self,
- _state: &(),
- _request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- if self.calls.fetch_add(1, Ordering::SeqCst) == 0 {
- Ok(tool_response("1", "spawn_subagent", serde_json::json!({})))
- } else {
- Ok(ModelResponse::assistant("all done"))
- }
- }
-}
-
-const REFUSAL: &str = "refusing to register spawn/delegate tool";
-
-/// Runs one sub-agent turn whose parent surface carries `spawn_subagent`, with
-/// `allowed` deciding whether the allowlist readmits it. Returns
-/// (spawn tool executed?, refusal warnings emitted).
-async fn run_with_spawn_tool_in_parent_surface(allowed: HashSet<String>) -> (bool, Vec<String>) {
- use tracing_subscriber::layer::SubscriberExt;
-
- let executed = Arc::new(std::sync::atomic::AtomicBool::new(false));
- let sink = WarnSink::default();
- let subscriber = tracing_subscriber::registry().with(WarnLayer(sink.clone()));
- let _subscriber_guard = tracing::subscriber::set_default(subscriber);
-
- let provider = Arc::new(SpawnAttemptProvider {
- calls: AtomicUsize::new(0),
- });
- let parent_tools: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![
- Box::new(EchoTool),
- Box::new(SpawnProbeTool(executed.clone())),
- ]);
- let mut history = vec![ChatMessage::user("spawn a helper")];
-
- run_subagent_via_graph(
- crate::agent::tinyagents::TurnModelSource::from_model(provider),
- "mock-model",
- 0.0,
- &mut history,
- parent_tools,
- vec![],
- vec![],
- allowed,
- 10,
- None,
- None,
- "researcher",
- "task-6157",
- false,
- None,
- crate::agent::tinyagents::host::OpenHumanRunContext::new(),
- None,
- std::env::temp_dir(),
- None,
- 1024,
- false,
- "root-session__spawn_refusal",
- "mock-channel",
- None,
- AgentTokenjuiceCompression::Off,
- None,
- )
- .await
- .expect("graph subagent runs");
-
- (executed.load(Ordering::SeqCst), sink.matching(REFUSAL))
-}
-
-/// The real shape: `run_typed_mode` has already stripped `spawn_subagent` from
-/// the allowlist, so the registration-time backstop is re-refusing a name that
-/// was never admitted. That is the happy path and must not warn (#6157) — the
-/// old unconditional warn fired here on every sub-agent run.
-#[tokio::test]
-async fn a_sub_agent_cannot_reach_a_spawn_tool_and_the_healthy_run_is_quiet() {
- let allowed = HashSet::from(["echo".to_string()]);
- let (executed, warnings) = run_with_spawn_tool_in_parent_surface(allowed).await;
-
- assert!(
- !executed,
- "a sub-agent must never be able to invoke spawn_subagent (#4452)"
- );
- assert!(
- warnings.is_empty(),
- "an already-excluded spawn tool is the happy path, not a warning: {warnings:?}"
- );
-}
-
-/// The misbuilt-allowlist case the backstop exists for: `spawn_subagent` is
-/// admitted, so registration must still refuse it *and* say so — this is the one
-/// shape in which the warning carries information.
-#[tokio::test]
-async fn an_allowlist_that_readmits_a_spawn_tool_is_refused_loudly() {
- let allowed = HashSet::from(["echo".to_string(), "spawn_subagent".to_string()]);
- let (executed, warnings) = run_with_spawn_tool_in_parent_surface(allowed).await;
-
- assert!(
- !executed,
- "the backstop must still refuse the tool, not merely log about it"
- );
- assert_eq!(
- warnings.len(),
- 1,
- "the readmitted spawn tool warns exactly once: {warnings:?}"
- );
-}
-
-/// #5934 (item 1): a mirrored sub-agent **tool result** must not be painted as
-/// something the human typed.
-///
-/// Both worker-thread mirrors write tool output with `sender: "user"`, and the
-/// renderer maps every non-`"agent"` sender to `role: 'user'`
-/// (`app/src/providers/assistantUiMessages.ts:536`) while keying visibility
-/// only on `extraMetadata.hidden` (`:664`, and the same flag in
-/// `ChatThreadView.tsx:312` / `timeline/selectors.ts:50`). Worker threads are
-/// openable chats — `create_worker_thread` stamps `labels: ["tasks"]` and
-/// `threadFilter.ts` lists that tab — so an unflagged mirror row shows the
-/// tool's raw output in a right-aligned user bubble.
-///
-/// The invariant: every non-`"agent"` row these mirrors write is `hidden`. The
-/// record stays in the log for the process rail; it just stops being chat.
-#[test]
-fn mirrored_tool_results_are_hidden_from_the_worker_thread_chat() {
- use crate::memory::conversations::{self as store, CreateConversationThread};
-
- let dir = std::env::temp_dir().join(format!("wt-5934-{}", uuid::Uuid::new_v4()));
- std::fs::create_dir_all(&dir).unwrap();
- let now = chrono::Utc::now().to_rfc3339();
- for id in ["worker-typed", "worker-recovered"] {
- store::ensure_thread(
- dir.clone(),
- CreateConversationThread {
- id: id.to_string(),
- title: "task".to_string(),
- created_at: now.clone(),
- parent_thread_id: Some("parent-1".to_string()),
- labels: Some(vec!["tasks".to_string()]),
- personality_id: None,
- },
- )
- .unwrap();
- }
-
- const RAW: &str = "{\"events\":[{\"title\":\"raw tool output the human never typed\"}]}";
-
- // The typed path (`ConversationMessage::ToolResults`), used on a normal run.
- mirror_worker_thread(
- &dir,
- "worker-typed",
- "researcher",
- "task-1",
- &[
- ConversationMessage::AssistantToolCalls {
- text: Some("checking the calendar".to_string()),
- tool_calls: vec![crate::inference::provider::ToolCall {
- id: "call-1".to_string(),
- name: "list_events".to_string(),
- arguments: "{}".to_string(),
- extra_content: None,
- }],
- reasoning_content: None,
- extra_metadata: None,
- },
- ConversationMessage::ToolResults(vec![crate::agent::messages::ToolResultMessage {
- tool_call_id: "call-1".to_string(),
- content: RAW.to_string(),
- }]),
- ],
- Some("Here is your week."),
- );
-
- // The error-recovery path (`role: "tool"`), used when a run fails mid-turn.
- mirror_worker_thread_from_history(
- &dir,
- "worker-recovered",
- "researcher",
- "task-1",
- &[
- ChatMessage::assistant("checking the calendar"),
- ChatMessage::tool(RAW),
- ],
- Some("[subagent run failed before completion]"),
- );
-
- // Collected, not asserted per row: both mirrors must be reported, so a
- // failure names every path that is still painting a tool result as chat.
- let mut painted_as_user_chat: Vec<String> = Vec::new();
- for thread_id in ["worker-typed", "worker-recovered"] {
- let rows = store::get_messages(dir.clone(), thread_id).unwrap();
- assert!(
- rows.iter().any(|r| r.content == RAW),
- "{thread_id}: the mirror wrote no tool-result row to assert on"
- );
- for row in rows.iter().filter(|r| r.sender != "agent") {
- if row.extra_metadata.get("hidden").and_then(|v| v.as_bool()) != Some(true) {
- painted_as_user_chat.push(format!(
- "{thread_id}: sender={:?} not hidden: {}",
- row.sender, row.content
- ));
- }
- }
- }
- assert!(
- painted_as_user_chat.is_empty(),
- "mirrored tool results render in a user chat bubble:\n{}",
- painted_as_user_chat.join("\n")
- );
-
- let _ = std::fs::remove_dir_all(&dir);
-}
+#[path = "graph_policy_tests.rs"]
+mod graph_policy_tests;
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/memory_fast_path.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/memory_fast_path.rs
new file mode 100644
index 0000000000..45135d2022
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/memory_fast_path.rs
@@ -0,0 +1,248 @@
+use super::*;
+
+/// Definition id of the pure-retrieval memory agent, reached from chat as the
+/// `retrieve_memory` delegate and from other agents as `call_memory_agent`.
+pub(super) const AGENT_MEMORY_ID: &str = "agent_memory";
+
+/// How many deterministic hits the memory fast path returns (#4677).
+pub(super) const MEMORY_FAST_PATH_LIMIT: usize = 8;
+
+/// Whether the deterministic memory fast path (#4677) is enabled. Default on;
+/// `OPENHUMAN_MEMORY_FAST_PATH=0` (or `false`/`no`/`off`) forces the full
+/// model-driven walk, e.g. to A/B the two paths without a rebuild.
+pub(super) fn memory_fast_path_enabled() -> bool {
+ parse_memory_fast_path_enabled(std::env::var("OPENHUMAN_MEMORY_FAST_PATH").ok().as_deref())
+}
+
+/// Pure core of [`memory_fast_path_enabled`], kept env-free for deterministic
+/// unit testing.
+pub(super) fn parse_memory_fast_path_enabled(env_value: Option<&str>) -> bool {
+ !matches!(
+ env_value.map(|v| v.trim().to_ascii_lowercase()).as_deref(),
+ Some("0") | Some("false") | Some("no") | Some("off")
+ )
+}
+
+/// Render deterministic retrieval hits into a compact, citable memory-context
+/// block for the parent turn. Returns `None` when there are no hits, so the
+/// caller falls back to the model-driven walk (the empty/degraded case is
+/// #4655's territory and still benefits from the model's judgement).
+pub(super) fn format_deterministic_memory_hits(resp: &RetrievalResponse) -> Option<String> {
+ use std::fmt::Write as _;
+ if resp.hits.is_empty() {
+ return None;
+ }
+ const PER_HIT_CHARS: usize = 600;
+ let mut out = format!(
+ "Retrieved {} relevant memor{} via deterministic memory search:\n",
+ resp.hits.len(),
+ if resp.hits.len() == 1 { "y" } else { "ies" }
+ );
+ for (i, hit) in resp.hits.iter().enumerate() {
+ let content = hit.content.trim();
+ let body: String = content.chars().take(PER_HIT_CHARS).collect();
+ let ellipsis = if content.chars().count() > PER_HIT_CHARS {
+ " …"
+ } else {
+ ""
+ };
+ let scope = if hit.tree_scope.trim().is_empty() {
+ "memory"
+ } else {
+ hit.tree_scope.trim()
+ };
+ let _ = writeln!(
+ out,
+ "{}. [{scope}] {body}{ellipsis} (relevance {:.2})",
+ i + 1,
+ hit.score
+ );
+ }
+ Some(out)
+}
+
+/// Truncate `output` in place to the definition's `max_result_chars` cap (when
+/// set), appending a `[...truncated]` marker. Char-count based (not byte-length)
+/// to avoid panicking on a multi-byte UTF-8 sequence at the boundary.
+///
+/// Shared by the normal sub-agent path and the deterministic memory fast path so
+/// both honour a definition's cap. `agent_memory` sets no cap today (its output
+/// is self-bounded at 8 hits × 600 chars), but routing the fast path through the
+/// same helper keeps the two paths from silently diverging if one is ever added
+/// (YellowSnnowmann review).
+pub(super) fn apply_max_result_chars(output: &mut String, cap: Option<usize>, agent_id: &str) {
+ let Some(cap) = cap else { return };
+ let original_chars = output.chars().count();
+ if original_chars <= cap {
+ return;
+ }
+ tracing::debug!(
+ agent_id = %agent_id,
+ original_chars,
+ cap,
+ "[subagent_runner] truncating oversized result to max_result_chars cap"
+ );
+ let byte_offset = output
+ .char_indices()
+ .nth(cap)
+ .map(|(i, _)| i)
+ .unwrap_or(output.len());
+ output.truncate(byte_offset);
+ output.push_str("\n[...truncated]");
+}
+
+/// Deterministic fast path for the pure-retrieval [`AGENT_MEMORY_ID`] sub-agent
+/// (#4677).
+///
+/// `agent_memory` otherwise runs a model-driven walk (≤ its `max_iterations`)
+/// whose per-iteration LLM round-trips dominate turn latency at ~30–40s per call
+/// *even when data is present*. [`fast_retrieve`] (E2GraphRAG: query-entity +
+/// dense/semantic recall over the same memory tree, no LLM in the loop) returns
+/// the same hits in a single deterministic pass. When it finds data we return
+/// those hits directly; when the fast path is disabled, errors, or finds nothing
+/// we return `None` so the caller runs the full sub-agent unchanged.
+///
+/// # Relevance guard (Codex review)
+///
+/// We only short-circuit for an **entity-grounded** query — one that yields at
+/// least one canonical entity or salient topic. Without grounding, `fast_retrieve`
+/// falls back to a pure global-dense pass that reranks/truncates whatever
+/// summaries exist, so a vague query against a populated profile would surface
+/// unrelated top-k memories as a "completed" retrieval instead of letting the
+/// model-driven agent judge relevance (or emit "no relevant memory found").
+/// Grounded queries keep the fast path; ungrounded ones defer to the full agent.
+pub(super) async fn try_deterministic_memory_retrieval(
+ task_prompt: &str,
+ definition: &AgentDefinition,
+ task_id: &str,
+ started: Instant,
+ loaded_config: &LoadedConfig,
+) -> Option<SubagentRunOutcome> {
+ let agent_id = definition.id.as_str();
+ if !memory_fast_path_enabled() {
+ return None;
+ }
+ let query = task_prompt.trim();
+ if query.is_empty() {
+ return None;
+ }
+ let config = match loaded_config.as_ref() {
+ Ok(config) => config.as_ref(),
+ Err(e) => {
+ tracing::warn!(
+ task_id = %task_id,
+ error = %e,
+ "[subagent_runner] agent_memory fast-path config load failed — falling back to model walk (#4677)"
+ );
+ return None;
+ }
+ };
+ // Relevance guard (Codex review): require entity/topic grounding before a
+ // deterministic pass stands in for the model's relevance judgement — the
+ // extraction is cheap (regex or one spaCy call) and `fast_retrieve` repeats
+ // it internally anyway. It goes through the provider's scoring family so
+ // the host no longer calls `tinymemory_core::` directly, and every failure
+ // (binding unavailable, scoring not exposed, extraction error) is fail-safe
+ // as entities_empty = true: the fast path is skipped and the model-driven
+ // walk runs — the same conservative outcome an unavailable extractor
+ // produced before scoring existed.
+ let entities_empty = match crate::memory::binding::for_config(config) {
+ Ok(binding) => match binding.provider().as_scoring() {
+ Some(scoring) => match scoring.extract_entities(query).await {
+ Ok(entities) => entities.is_empty(),
+ Err(e) => {
+ tracing::debug!(
+ task_id = %task_id,
+ error = %e,
+ "[subagent_runner] scoring extract_entities failed (non-fatal) — deferring to model walk (#4677)"
+ );
+ true
+ }
+ },
+ None => {
+ tracing::debug!(
+ task_id = %task_id,
+ "[subagent_runner] driver does not expose scoring (module not loaded or policy excluded) — deferring to model walk (#4677)"
+ );
+ true
+ }
+ },
+ Err(e) => {
+ tracing::debug!(
+ task_id = %task_id,
+ error = %e,
+ "[subagent_runner] memory binding unavailable (non-fatal) — deferring to model walk (#4677)"
+ );
+ true
+ }
+ };
+ if entities_empty {
+ tracing::debug!(
+ task_id = %task_id,
+ "[subagent_runner] agent_memory fast-path skipped — ungrounded query (no entities/topics); deferring to model walk (#4677)"
+ );
+ return None;
+ }
+ let opts = FastRetrieveQuery {
+ limit: MEMORY_FAST_PATH_LIMIT,
+ ..FastRetrieveQuery::default()
+ };
+ // Through the bound driver's `MemoryRetrieval`, not the engine (#5560).
+ // This is an agent turn, so `as_bus_scope()` carries the turn's own
+ // memory-source allowlist; `binding.provider()` is unguarded, which makes
+ // that argument the gate rather than a hint.
+ let scope = as_bus_scope();
+ let binding = match crate::memory::binding::for_config(config) {
+ Ok(binding) => binding,
+ Err(e) => {
+ tracing::warn!(
+ task_id = %task_id,
+ error = %e,
+ "[subagent_runner] agent_memory fast-path could not bind the memory driver — falling back to model walk (#4677)"
+ );
+ return None;
+ }
+ };
+ // A driver with no retrieval family has no summary tree to rank. Falling
+ // through to the model walk is the same answer this path already gives for
+ // an empty result, and strictly better than reporting a failure that is
+ // really an absent capability.
+ let retrieval = binding.provider().as_retrieval()?;
+ let resp = match retrieval.fast_retrieve(query, opts, scope.as_ref()).await {
+ Ok(resp) => resp,
+ Err(e) => {
+ tracing::warn!(
+ task_id = %task_id,
+ error = %format!("{e:#}"),
+ "[subagent_runner] agent_memory fast-path retrieval errored — falling back to model walk (#4677)"
+ );
+ return None;
+ }
+ };
+ let mut output = format_deterministic_memory_hits(&resp)?;
+ // Honour the definition's `max_result_chars` cap just like the model-driven
+ // path (YellowSnnowmann review). No-op for `agent_memory` (uncapped, and the
+ // block above is already self-bounded), but keeps the paths from diverging.
+ apply_max_result_chars(&mut output, definition.max_result_chars, agent_id);
+ tracing::info!(
+ task_id = %task_id,
+ hits = resp.hits.len(),
+ total = resp.total,
+ elapsed_ms = started.elapsed().as_millis() as u64,
+ "[subagent_runner] agent_memory deterministic fast-path hit — skipped the model walk (#4677)"
+ );
+ Some(SubagentRunOutcome {
+ task_id: task_id.to_string(),
+ agent_id: agent_id.to_string(),
+ output,
+ iterations: 0,
+ elapsed: started.elapsed(),
+ mode: SubagentMode::Typed,
+ status: SubagentRunStatus::Completed,
+ final_history: Vec::new(),
+ usage: SubagentUsage::default(),
+ // Deterministic memory hits are already bounded; nothing is offloaded
+ // on this path.
+ artifact_paths: Vec::new(),
+ })
+}
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs
index cf80225a70..a7338d5792 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs
@@ -105,269 +105,21 @@ pub(super) fn tier_gate_decision(
Ok(())
}
-/// Definition id of the pure-retrieval memory agent, reached from chat as the
-/// `retrieve_memory` delegate and from other agents as `call_memory_agent`.
-const AGENT_MEMORY_ID: &str = "agent_memory";
-
-/// How many deterministic hits the memory fast path returns (#4677).
-const MEMORY_FAST_PATH_LIMIT: usize = 8;
-
-/// Whether the deterministic memory fast path (#4677) is enabled. Default on;
-/// `OPENHUMAN_MEMORY_FAST_PATH=0` (or `false`/`no`/`off`) forces the full
-/// model-driven walk, e.g. to A/B the two paths without a rebuild.
-fn memory_fast_path_enabled() -> bool {
- parse_memory_fast_path_enabled(std::env::var("OPENHUMAN_MEMORY_FAST_PATH").ok().as_deref())
-}
-
-/// Pure core of [`memory_fast_path_enabled`], kept env-free for deterministic
-/// unit testing.
-fn parse_memory_fast_path_enabled(env_value: Option<&str>) -> bool {
- !matches!(
- env_value.map(|v| v.trim().to_ascii_lowercase()).as_deref(),
- Some("0") | Some("false") | Some("no") | Some("off")
- )
-}
-
-/// Render deterministic retrieval hits into a compact, citable memory-context
-/// block for the parent turn. Returns `None` when there are no hits, so the
-/// caller falls back to the model-driven walk (the empty/degraded case is
-/// #4655's territory and still benefits from the model's judgement).
-fn format_deterministic_memory_hits(resp: &RetrievalResponse) -> Option<String> {
- use std::fmt::Write as _;
- if resp.hits.is_empty() {
- return None;
- }
- const PER_HIT_CHARS: usize = 600;
- let mut out = format!(
- "Retrieved {} relevant memor{} via deterministic memory search:\n",
- resp.hits.len(),
- if resp.hits.len() == 1 { "y" } else { "ies" }
- );
- for (i, hit) in resp.hits.iter().enumerate() {
- let content = hit.content.trim();
- let body: String = content.chars().take(PER_HIT_CHARS).collect();
- let ellipsis = if content.chars().count() > PER_HIT_CHARS {
- " …"
- } else {
- ""
- };
- let scope = if hit.tree_scope.trim().is_empty() {
- "memory"
- } else {
- hit.tree_scope.trim()
- };
- let _ = writeln!(
- out,
- "{}. [{scope}] {body}{ellipsis} (relevance {:.2})",
- i + 1,
- hit.score
- );
- }
- Some(out)
-}
-
-/// Truncate `output` in place to the definition's `max_result_chars` cap (when
-/// set), appending a `[...truncated]` marker. Char-count based (not byte-length)
-/// to avoid panicking on a multi-byte UTF-8 sequence at the boundary.
-///
-/// Shared by the normal sub-agent path and the deterministic memory fast path so
-/// both honour a definition's cap. `agent_memory` sets no cap today (its output
-/// is self-bounded at 8 hits × 600 chars), but routing the fast path through the
-/// same helper keeps the two paths from silently diverging if one is ever added
-/// (YellowSnnowmann review).
-fn apply_max_result_chars(output: &mut String, cap: Option<usize>, agent_id: &str) {
- let Some(cap) = cap else { return };
- let original_chars = output.chars().count();
- if original_chars <= cap {
- return;
- }
- tracing::debug!(
- agent_id = %agent_id,
- original_chars,
- cap,
- "[subagent_runner] truncating oversized result to max_result_chars cap"
- );
- let byte_offset = output
- .char_indices()
- .nth(cap)
- .map(|(i, _)| i)
- .unwrap_or(output.len());
- output.truncate(byte_offset);
- output.push_str("\n[...truncated]");
-}
-
-/// Deterministic fast path for the pure-retrieval [`AGENT_MEMORY_ID`] sub-agent
-/// (#4677).
-///
-/// `agent_memory` otherwise runs a model-driven walk (≤ its `max_iterations`)
-/// whose per-iteration LLM round-trips dominate turn latency at ~30–40s per call
-/// *even when data is present*. [`fast_retrieve`] (E2GraphRAG: query-entity +
-/// dense/semantic recall over the same memory tree, no LLM in the loop) returns
-/// the same hits in a single deterministic pass. When it finds data we return
-/// those hits directly; when the fast path is disabled, errors, or finds nothing
-/// we return `None` so the caller runs the full sub-agent unchanged.
-///
-/// # Relevance guard (Codex review)
-///
-/// We only short-circuit for an **entity-grounded** query — one that yields at
-/// least one canonical entity or salient topic. Without grounding, `fast_retrieve`
-/// falls back to a pure global-dense pass that reranks/truncates whatever
-/// summaries exist, so a vague query against a populated profile would surface
-/// unrelated top-k memories as a "completed" retrieval instead of letting the
-/// model-driven agent judge relevance (or emit "no relevant memory found").
-/// Grounded queries keep the fast path; ungrounded ones defer to the full agent.
-async fn try_deterministic_memory_retrieval(
- task_prompt: &str,
- definition: &AgentDefinition,
- task_id: &str,
- started: Instant,
- loaded_config: &LoadedConfig,
-) -> Option<SubagentRunOutcome> {
- let agent_id = definition.id.as_str();
- if !memory_fast_path_enabled() {
- return None;
- }
- let query = task_prompt.trim();
- if query.is_empty() {
- return None;
- }
- let config = match loaded_config.as_ref() {
- Ok(config) => config.as_ref(),
- Err(e) => {
- tracing::warn!(
- task_id = %task_id,
- error = %e,
- "[subagent_runner] agent_memory fast-path config load failed — falling back to model walk (#4677)"
- );
- return None;
- }
- };
- // Relevance guard (Codex review): require entity/topic grounding before a
- // deterministic pass stands in for the model's relevance judgement — the
- // extraction is cheap (regex or one spaCy call) and `fast_retrieve` repeats
- // it internally anyway. It goes through the provider's scoring family so
- // the host no longer calls `tinymemory_core::` directly, and every failure
- // (binding unavailable, scoring not exposed, extraction error) is fail-safe
- // as entities_empty = true: the fast path is skipped and the model-driven
- // walk runs — the same conservative outcome an unavailable extractor
- // produced before scoring existed.
- let entities_empty = match crate::memory::binding::for_config(config) {
- Ok(binding) => match binding.provider().as_scoring() {
- Some(scoring) => match scoring.extract_entities(query).await {
- Ok(entities) => entities.is_empty(),
- Err(e) => {
- tracing::debug!(
- task_id = %task_id,
- error = %e,
- "[subagent_runner] scoring extract_entities failed (non-fatal) — deferring to model walk (#4677)"
- );
- true
- }
- },
- None => {
- tracing::debug!(
- task_id = %task_id,
- "[subagent_runner] driver does not expose scoring (module not loaded or policy excluded) — deferring to model walk (#4677)"
- );
- true
- }
- },
- Err(e) => {
- tracing::debug!(
- task_id = %task_id,
- error = %e,
- "[subagent_runner] memory binding unavailable (non-fatal) — deferring to model walk (#4677)"
- );
- true
- }
- };
- if entities_empty {
- tracing::debug!(
- task_id = %task_id,
- "[subagent_runner] agent_memory fast-path skipped — ungrounded query (no entities/topics); deferring to model walk (#4677)"
- );
- return None;
- }
- let opts = FastRetrieveQuery {
- limit: MEMORY_FAST_PATH_LIMIT,
- ..FastRetrieveQuery::default()
- };
- // Through the bound driver's `MemoryRetrieval`, not the engine (#5560).
- // This is an agent turn, so `as_bus_scope()` carries the turn's own
- // memory-source allowlist; `binding.provider()` is unguarded, which makes
- // that argument the gate rather than a hint.
- let scope = as_bus_scope();
- let binding = match crate::memory::binding::for_config(config) {
- Ok(binding) => binding,
- Err(e) => {
- tracing::warn!(
- task_id = %task_id,
- error = %e,
- "[subagent_runner] agent_memory fast-path could not bind the memory driver — falling back to model walk (#4677)"
- );
- return None;
- }
- };
- // A driver with no retrieval family has no summary tree to rank. Falling
- // through to the model walk is the same answer this path already gives for
- // an empty result, and strictly better than reporting a failure that is
- // really an absent capability.
- let retrieval = binding.provider().as_retrieval()?;
- let resp = match retrieval.fast_retrieve(query, opts, scope.as_ref()).await {
- Ok(resp) => resp,
- Err(e) => {
- tracing::warn!(
- task_id = %task_id,
- error = %format!("{e:#}"),
- "[subagent_runner] agent_memory fast-path retrieval errored — falling back to model walk (#4677)"
- );
- return None;
- }
- };
- let mut output = format_deterministic_memory_hits(&resp)?;
- // Honour the definition's `max_result_chars` cap just like the model-driven
- // path (YellowSnnowmann review). No-op for `agent_memory` (uncapped, and the
- // block above is already self-bounded), but keeps the paths from diverging.
- apply_max_result_chars(&mut output, definition.max_result_chars, agent_id);
- tracing::info!(
- task_id = %task_id,
- hits = resp.hits.len(),
- total = resp.total,
- elapsed_ms = started.elapsed().as_millis() as u64,
- "[subagent_runner] agent_memory deterministic fast-path hit — skipped the model walk (#4677)"
- );
- Some(SubagentRunOutcome {
- task_id: task_id.to_string(),
- agent_id: agent_id.to_string(),
- output,
- iterations: 0,
- elapsed: started.elapsed(),
- mode: SubagentMode::Typed,
- status: SubagentRunStatus::Completed,
- final_history: Vec::new(),
- usage: SubagentUsage::default(),
- // Deterministic memory hits are already bounded; nothing is offloaded
- // on this path.
- artifact_paths: Vec::new(),
- })
-}
+#[path = "memory_fast_path.rs"]
+mod memory_fast_path;
+use memory_fast_path::*;
/// Run a sub-agent based on its definition and a task prompt.
///
/// This is the primary entry point for agent delegation. It performs the following:
/// 1. Generates a unique `task_id` if one wasn't provided.
-/// 2. Asks the turn's
-/// explicit root-turn dispatch guard
-/// whether a delegation can still succeed, and refuses before spending
-/// anything if it cannot (#5804).
-/// 3. Reads the parent's explicit [`ParentExecutionContext`] from its run
-/// carrier.
+/// 2. Asks the turn's explicit root-turn dispatch guard whether a delegation
+/// can still succeed, and refuses before spending anything if it cannot.
+/// 3. Reads the parent's explicit [`ParentExecutionContext`] from its run carrier.
/// 4. Dispatches to `run_typed_mode`.
///
-/// On success returns a [`SubagentRunOutcome`] whose `output` is the
-/// final assistant text. On failure the error is suitable for stringifying
-/// into a `tool_result` block — including the two dispatch refusals, whose
-/// messages tell the model to summarise rather than delegate again.
+/// On success returns a [`SubagentRunOutcome`] whose `output` is the final
+/// assistant text. Failures are suitable for stringifying into a tool result.
pub async fn run_subagent(
definition: &AgentDefinition,
task_prompt: &str,
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests.rs
index a03b3e8351..704a3097e3 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests.rs
@@ -182,7 +182,9 @@ impl ChatModel<()> for ScriptedProvider {
items.push(ModelStreamItem::MessageDelta(MessageDelta::text(text)));
}
items.push(ModelStreamItem::Completed(response));
- Ok(Box::pin(futures::stream::iter(items)))
+ Ok(tinyinference_llm::model::ModelStream::new(Box::pin(
+ futures::stream::iter(items),
+ )))
}
}
@@ -210,6 +212,8 @@ fn text_response_with_reasoning(text: &str, reasoning: &str) -> ModelResponse {
resolved_model: None,
continue_turn: None,
served_from_cache: false,
+ correlation: None,
+ resolved_route: None,
}
}
@@ -231,6 +235,8 @@ fn tool_response(name: &str, args: &str) -> ModelResponse {
resolved_model: None,
continue_turn: None,
served_from_cache: false,
+ correlation: None,
+ resolved_route: None,
}
}
diff --git a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
index afa8a4a78d..6ddf2f4b48 100644
--- a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
@@ -88,18 +88,21 @@ async fn aggregate_spills_largest_until_under_budget() {
output: "a".repeat(100),
success: true,
tool_call_id: Some("small".into()),
+ trusted_verbatim: false,
},
ToolOutcome {
name: "largest".into(),
output: "b".repeat(2000),
success: true,
tool_call_id: Some("largest".into()),
+ trusted_verbatim: false,
},
ToolOutcome {
name: "medium".into(),
output: "c".repeat(900),
success: true,
tool_call_id: Some("medium".into()),
+ trusted_verbatim: false,
},
];
@@ -125,18 +128,21 @@ async fn aggregate_forces_budget_when_envelope_has_no_savings() {
output: "a".repeat(350),
success: true,
tool_call_id: Some("one".into()),
+ trusted_verbatim: false,
},
ToolOutcome {
name: "two".into(),
output: "b".repeat(350),
success: true,
tool_call_id: Some("two".into()),
+ trusted_verbatim: false,
},
ToolOutcome {
name: "three".into(),
output: "c".repeat(350),
success: true,
tool_call_id: Some("three".into()),
+ trusted_verbatim: false,
},
];
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context_tests.rs
index b2fe627ea0..3ca0e10d75 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context_tests.rs
@@ -405,10 +405,7 @@ async fn catalog_lists_the_parents_synthesised_delegates_from_its_visible_specs(
catalog_spec("agent_prepare_context", "this tool"),
],
);
- let catalog = crate::agent::harness::fork_context::with_parent_context(ctx, async {
- AgentPrepareContextTool::render_parent_tool_catalog()
- })
- .await;
+ let catalog = AgentPrepareContextTool::render_parent_tool_catalog(Some(&ctx));
assert!(
catalog.contains("- delegate_to_integrations_agent: route to a connected integration\n"),
"the parent's delegate must be recommendable: {catalog:?}"
@@ -433,9 +430,6 @@ async fn catalog_falls_back_to_all_tool_specs_when_visible_specs_are_absent() {
Vec::new(),
);
ctx.visible_tool_names = std::iter::once("echo".to_string()).collect();
- let catalog = crate::agent::harness::fork_context::with_parent_context(ctx, async {
- AgentPrepareContextTool::render_parent_tool_catalog()
- })
- .await;
+ let catalog = AgentPrepareContextTool::render_parent_tool_catalog(Some(&ctx));
assert_eq!(catalog, "- echo: durable\n");
}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
index 9f8f846e35..a098160bf4 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
@@ -571,6 +571,8 @@ fn tool_response(name: &str, arguments: serde_json::Value) -> ModelResponse {
resolved_model: None,
continue_turn: None,
served_from_cache: false,
+ correlation: None,
+ resolved_route: None,
}
}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent_tests.rs
index f638e26b6d..ff6fec98a3 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent_tests.rs
@@ -49,13 +49,13 @@ fn running_wait_message_includes_agent_id_and_tick_instruction() {
#[test]
fn timeout_policy_is_owned_not_inherited() {
let tool = WaitSubagentTool::new();
- assert!(matches!(
+ assert_eq!(
tool.timeout_policy(&json!({})),
- ToolTimeout::Secs(DEFAULT_TIMEOUT_SECS)
- ));
+ ToolTimeout::Millis(DEFAULT_TIMEOUT_SECS * 1000)
+ );
assert!(matches!(
tool.timeout_policy(&json!({"timeout_secs": 1800})),
- ToolTimeout::Secs(1800)
+ ToolTimeout::Millis(1_800_000)
));
}
@@ -72,10 +72,10 @@ fn policy_and_wait_resolve_the_same_seconds() {
json!({"timeout_secs": 99_999}),
json!({"timeout_secs": 0}),
] {
- let ToolTimeout::Secs(policy) = tool.timeout_policy(&args) else {
- panic!("wait_subagent must return an explicit Secs policy");
+ let ToolTimeout::Millis(policy) = tool.timeout_policy(&args) else {
+ panic!("wait_subagent must return an explicit Millis policy");
};
- assert_eq!(policy, requested_timeout_secs(&args));
+ assert_eq!(policy, requested_timeout_secs(&args) * 1000);
}
}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel.rs
index 1a2922046c..be306a636c 100644
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel.rs
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel.rs
@@ -104,28 +104,5 @@ pub(super) fn clear_cancel_signal(run_id: &str, signal: &WorkflowCancelSignal) {
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn resume_token_survives_old_cleanup_and_stop_cancels_the_successor() {
- let run_id = format!("workflow-cancel-race-{}", uuid::Uuid::new_v4());
- let old = register_cancel_signal(&run_id);
- let successor = replace_cancel_signal(&run_id);
-
- // Deterministic old-loop cleanup after resume must leave the newer
- // generation installed.
- clear_cancel_signal(&run_id, &old);
- assert!(is_current_cancel_signal(&run_id, &successor));
- assert!(!successor.token.is_cancelled());
-
- // stop_workflow_run calls this helper after its lifecycle CAS; it
- // reaches the current generation, not the old fenced-loop token.
- assert!(cancel_signal_if_current(&run_id, &successor));
- assert!(successor.token.is_cancelled());
- assert!(successor.flag.load(Ordering::SeqCst));
- assert!(!old.token.is_cancelled());
-
- clear_cancel_signal(&run_id, &successor);
- }
-}
+#[path = "cancel_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel_tests.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel_tests.rs
new file mode 100644
index 0000000000..6a6d060b48
--- /dev/null
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel_tests.rs
@@ -0,0 +1,19 @@
+use super::*;
+
+#[test]
+fn resume_token_survives_old_cleanup_and_stop_cancels_the_successor() {
+ let run_id = format!("workflow-cancel-race-{}", uuid::Uuid::new_v4());
+ let old = register_cancel_signal(&run_id);
+ let successor = replace_cancel_signal(&run_id);
+
+ clear_cancel_signal(&run_id, &old);
+ assert!(is_current_cancel_signal(&run_id, &successor));
+ assert!(!successor.token.is_cancelled());
+
+ assert!(cancel_signal_if_current(&run_id, &successor));
+ assert!(successor.token.is_cancelled());
+ assert!(successor.flag.load(Ordering::SeqCst));
+ assert!(!old.token.is_cancelled());
+
+ clear_cancel_signal(&run_id, &successor);
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/steering.rs b/crates/openhuman-core/src/agent/tinyagents/host/steering.rs
index bab7e98e0b..67b314ae22 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/steering.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/steering.rs
@@ -3,6 +3,13 @@
use std::sync::OnceLock;
use tinyagents_graph::orchestration::SteeringRegistry;
+#[cfg(test)]
+use tinyagents_graph::{
+ InMemoryTaskStore, OrchestrationTaskKind, OrchestrationTaskResult, OrchestrationTaskSpec,
+ OrchestrationTaskStatus, TaskStore,
+};
+#[cfg(test)]
+use tinyagents_harness::ids::TaskId;
use tinyagents_harness::steering::{SteeringCommandKind, SteeringHandle, SteeringPolicy};
static STEERING_REGISTRY: OnceLock<SteeringRegistry> = OnceLock::new();
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rs
index 7cdae1eb0a..7ad783641d 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rs
@@ -121,50 +121,5 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
}
#[cfg(test)]
-mod tests {
- use super::*;
- use tinyagents_harness::context::{RunConfig, RunContext};
-
- fn context() -> RunContext<crate::agent::tinyagents::host::OpenHumanRunContext> {
- RunContext::new(
- RunConfig::new("outcome-capture-test"),
- crate::agent::tinyagents::host::OpenHumanRunContext::new(),
- )
- }
-
- #[tokio::test]
- async fn same_tool_calls_keep_completion_and_failure_records_by_call_id() {
- let sink = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
- let failure_map = std::sync::Arc::new(std::sync::Mutex::new(Default::default()));
- let middleware = ToolOutcomeCaptureMiddleware::new(sink.clone(), failure_map.clone());
- let mut ctx = context();
-
- let success = ToolInvocationIdentity::new("echo-success", "echo");
- let mut success_result = TaToolResult::success("done");
- middleware
- .after_tool(&mut ctx, &(), &success, &mut success_result)
- .await
- .expect("successful result is captured");
-
- let failure = ToolInvocationIdentity::new("echo-failure", "echo");
- let mut failure_result = TaToolResult::error("request timed out");
- middleware
- .after_tool(&mut ctx, &(), &failure, &mut failure_result)
- .await
- .expect("failed result is captured");
-
- let outcomes = sink.lock().expect("outcome sink");
- assert_eq!(outcomes.len(), 2);
- assert_eq!(outcomes[0].call_id, "echo-success");
- assert!(outcomes[0].success);
- assert_eq!(outcomes[1].call_id, "echo-failure");
- assert!(!outcomes[1].success);
- drop(outcomes);
-
- let recorded = failure_map.lock().expect("failure lookup");
- assert_eq!(recorded.len(), 2, "same tool names cannot overwrite calls");
- assert_eq!(recorded["echo-success"].0, true);
- assert_eq!(recorded["echo-failure"].0, false);
- assert!(recorded["echo-failure"].1.is_some());
- }
-}
+#[path = "tool_outcome_capture_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture_tests.rs
new file mode 100644
index 0000000000..87623380a2
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture_tests.rs
@@ -0,0 +1,45 @@
+use super::*;
+use tinyagents_harness::context::{RunConfig, RunContext};
+
+fn context() -> RunContext<crate::agent::tinyagents::host::OpenHumanRunContext> {
+ RunContext::new(
+ RunConfig::new("outcome-capture-test"),
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ )
+}
+
+#[tokio::test]
+async fn same_tool_calls_keep_completion_and_failure_records_by_call_id() {
+ let sink = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let failure_map = std::sync::Arc::new(std::sync::Mutex::new(Default::default()));
+ let middleware = ToolOutcomeCaptureMiddleware::new(sink.clone(), failure_map.clone());
+ let mut ctx = context();
+
+ let success = ToolInvocationIdentity::new("echo-success", "echo");
+ let mut success_result = TaToolResult::success("done");
+ middleware
+ .after_tool(&mut ctx, &(), &success, &mut success_result)
+ .await
+ .expect("successful result is captured");
+
+ let failure = ToolInvocationIdentity::new("echo-failure", "echo");
+ let mut failure_result = TaToolResult::error("request timed out");
+ middleware
+ .after_tool(&mut ctx, &(), &failure, &mut failure_result)
+ .await
+ .expect("failed result is captured");
+
+ let outcomes = sink.lock().expect("outcome sink");
+ assert_eq!(outcomes.len(), 2);
+ assert_eq!(outcomes[0].call_id, "echo-success");
+ assert!(outcomes[0].success);
+ assert_eq!(outcomes[1].call_id, "echo-failure");
+ assert!(!outcomes[1].success);
+ drop(outcomes);
+
+ let recorded = failure_map.lock().expect("failure lookup");
+ assert_eq!(recorded.len(), 2, "same tool names cannot overwrite calls");
+ assert!(recorded["echo-success"].0);
+ assert!(!recorded["echo-failure"].0);
+ assert!(recorded["echo-failure"].1.is_some());
+}
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 7175c03570..4823817e37 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs
@@ -443,60 +443,5 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext> for Too
}
#[cfg(test)]
-mod tests {
- use super::*;
- use tinyagents_harness::context::{RunConfig, RunContext};
-
- fn context() -> RunContext<crate::agent::tinyagents::host::OpenHumanRunContext> {
- RunContext::new(
- RunConfig::new("tool-output-identity-test"),
- crate::agent::tinyagents::host::OpenHumanRunContext::new(),
- )
- }
-
- #[tokio::test]
- async fn same_tool_calls_persist_artifacts_under_distinct_call_ids() {
- let temp = tempfile::tempdir().expect("temporary artifact root");
- let middleware = ToolOutputMiddleware {
- budget_bytes: 8,
- payload_summarizer: None,
- task_hint: None,
- artifact_store: Some(ToolResultArtifactStore::new(
- temp.path().to_path_buf(),
- "identity-session",
- )),
- tokenjuice_compaction_enabled: false,
- tokenjuice_compression: AgentTokenjuiceCompression::Off,
- runtime_config: None,
- tool_policies: HashMap::new(),
- artifact_reads: Default::default(),
- };
- let mut ctx = context();
-
- let first = ToolInvocationIdentity::new("echo-1", "echo");
- let mut first_result = TaToolResult::success("first result is deliberately oversized");
- middleware
- .after_tool(&mut ctx, &(), &first, &mut first_result)
- .await
- .expect("first artifact is persisted");
-
- let second = ToolInvocationIdentity::new("echo-2", "echo");
- let mut second_result = TaToolResult::success("second result is deliberately oversized");
- middleware
- .after_tool(&mut ctx, &(), &second, &mut second_result)
- .await
- .expect("second artifact is persisted");
-
- let root = temp
- .path()
- .join("artifacts/tool-results/identity-session/echo");
- assert_eq!(
- std::fs::read_to_string(root.join("echo-1.txt")).expect("first artifact"),
- "first result is deliberately oversized"
- );
- assert_eq!(
- std::fs::read_to_string(root.join("echo-2.txt")).expect("second artifact"),
- "second result is deliberately oversized"
- );
- }
-}
+#[path = "tool_output_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output_tests.rs
new file mode 100644
index 0000000000..5a03a0f39d
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output_tests.rs
@@ -0,0 +1,55 @@
+use super::*;
+use tinyagents_harness::context::{RunConfig, RunContext};
+
+fn context() -> RunContext<crate::agent::tinyagents::host::OpenHumanRunContext> {
+ RunContext::new(
+ RunConfig::new("tool-output-identity-test"),
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ )
+}
+
+#[tokio::test]
+async fn same_tool_calls_persist_artifacts_under_distinct_call_ids() {
+ let temp = tempfile::tempdir().expect("temporary artifact root");
+ let middleware = ToolOutputMiddleware {
+ budget_bytes: 8,
+ payload_summarizer: None,
+ task_hint: None,
+ artifact_store: Some(ToolResultArtifactStore::new(
+ temp.path().to_path_buf(),
+ "identity-session",
+ )),
+ tokenjuice_compaction_enabled: false,
+ tokenjuice_compression: AgentTokenjuiceCompression::Off,
+ runtime_config: None,
+ tool_policies: HashMap::new(),
+ artifact_reads: Default::default(),
+ };
+ let mut ctx = context();
+
+ let first = ToolInvocationIdentity::new("echo-1", "echo");
+ let mut first_result = TaToolResult::success("first result is deliberately oversized");
+ middleware
+ .after_tool(&mut ctx, &(), &first, &mut first_result)
+ .await
+ .expect("first artifact is persisted");
+
+ let second = ToolInvocationIdentity::new("echo-2", "echo");
+ let mut second_result = TaToolResult::success("second result is deliberately oversized");
+ middleware
+ .after_tool(&mut ctx, &(), &second, &mut second_result)
+ .await
+ .expect("second artifact is persisted");
+
+ let root = temp
+ .path()
+ .join("artifacts/tool-results/identity-session/echo");
+ assert_eq!(
+ std::fs::read_to_string(root.join("echo-1.txt")).expect("first artifact"),
+ "first result is deliberately oversized"
+ );
+ assert_eq!(
+ std::fs::read_to_string(root.join("echo-2.txt")).expect("second artifact"),
+ "second result is deliberately oversized"
+ );
+}
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
new file mode 100644
index 0000000000..d431ebdc68
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_compaction_tests.rs
@@ -0,0 +1,310 @@
+use super::*;
+#[test]
+fn compaction_exempt_tools_contains_every_proposal_tool() {
+ for tool in [
+ "propose_workflow",
+ "revise_workflow",
+ "edit_workflow",
+ "save_workflow",
+ "create_workflow",
+ ] {
+ assert!(
+ COMPACTION_EXEMPT_TOOLS.contains(&tool),
+ "{tool} must be exempt from tokenjuice/summarizer compaction"
+ );
+ }
+}
+
+#[tokio::test]
+#[ignore = "requires a built TinyJuice module"]
+async fn tool_output_tabulates_a_large_graph_for_a_non_exempt_tool() {
+ // Sanity baseline proving this test's payload actually exercises real
+ // tinyjuice tabulation (and isn't just below-threshold): a tool name
+ // NOT in COMPACTION_EXEMPT_TOOLS loses the `"type"` marker.
+ // Resolve the explicit release fixture before `after_tool` performs
+ // ambient config initialisation. A pristine CI workspace otherwise
+ // exercises the production fail-open path before the test override is
+ // admitted, hiding a usable module behind unchanged output.
+ crate::inference::tokenjuice::install_from_config(&crate::config::Config::default())
+ .await
+ .expect("released TinyJuice module must load and accept host configuration");
+ let mw = compaction_enabled_mw();
+ let payload = large_workflow_proposal_json();
+ assert!(
+ payload.len()
+ >= crate::config::Config::default()
+ .tokenjuice
+ .min_bytes_to_compress,
+ "baseline payload must clear OpenHuman's configured compaction floor"
+ );
+ let mut result = tool_result("some_other_tool", &payload);
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation("other-compact", "some_other_tool"),
+ &mut result,
+ )
+ .await
+ .unwrap();
+ assert_ne!(
+ result_text(&result),
+ payload,
+ "a non-exempt tool's large uniform-array payload should be rewritten by tokenjuice"
+ );
+ let reparsed: Result<serde_json::Value, _> = serde_json::from_str(&result_text(&result));
+ let marker_survived = reparsed
+ .ok()
+ .and_then(|v| v.get("type").and_then(|t| t.as_str().map(str::to_string)))
+ == Some("workflow_proposal".to_string());
+ assert!(
+ !marker_survived,
+ "baseline expectation: tabulation strips the type marker for non-exempt tools"
+ );
+}
+
+#[tokio::test]
+async fn tool_output_leaves_propose_workflow_byte_for_byte_intact() {
+ let mw = compaction_enabled_mw();
+ let payload = large_workflow_proposal_json();
+ let mut result = tool_result("propose_workflow", &payload);
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation("proposal-compact", "propose_workflow"),
+ &mut result,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ result_text(&result),
+ payload,
+ "propose_workflow results must pass through compaction untouched"
+ );
+ let reparsed: serde_json::Value = serde_json::from_str(&result_text(&result)).unwrap();
+ assert_eq!(reparsed["type"], "workflow_proposal");
+ assert_eq!(reparsed["graph"]["nodes"].as_array().unwrap().len(), 20);
+}
+
+#[tokio::test]
+async fn tool_output_leaves_every_exempt_tool_name_intact() {
+ let mw = compaction_enabled_mw();
+ let payload = large_workflow_proposal_json();
+ for tool in COMPACTION_EXEMPT_TOOLS {
+ let mut result = tool_result(tool, &payload);
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation(format!("exempt-{tool}"), *tool),
+ &mut result,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ result_text(&result),
+ payload,
+ "{tool}'s result must pass through compaction untouched"
+ );
+ }
+}
+
+#[tokio::test]
+async fn tool_output_leaves_an_oversized_propose_workflow_byte_for_byte_intact() {
+ // Gap 1: a ≥10-node proposal routinely exceeds the ~16 KiB shared
+ // byte-budget backstop. Before the truncation exemption, step 4
+ // truncated it at a UTF-8 boundary — invalid JSON, so both
+ // `flows::ops::extract_workflow_proposal` and the frontend's
+ // `parseWorkflowProposal` silently fell back to `proposal: None` and a
+ // blank canvas. This must survive byte-for-byte regardless of size.
+ let mw = truncation_probe_mw();
+ let payload = oversized_workflow_proposal_json(30);
+ assert!(
+ payload.len() > DEFAULT_TOOL_RESULT_BUDGET_BYTES,
+ "test payload must exceed the shared byte budget to exercise step 4: {} bytes",
+ payload.len()
+ );
+ let mut result = tool_result("propose_workflow", &payload);
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation("proposal-truncate", "propose_workflow"),
+ &mut result,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ result_text(&result),
+ payload,
+ "an oversized propose_workflow result must not be truncated by the shared byte-budget backstop"
+ );
+ let reparsed: serde_json::Value = serde_json::from_str(&result_text(&result))
+ .expect("must still be valid JSON after passing through after_tool");
+ assert_eq!(reparsed["type"], "workflow_proposal");
+ assert_eq!(reparsed["graph"]["nodes"].as_array().unwrap().len(), 30);
+}
+
+#[tokio::test]
+async fn tool_output_truncates_the_same_oversized_payload_for_a_non_exempt_tool() {
+ // Baseline pairing with the test above: proves the identical oversized
+ // payload IS truncated (and consequently unparseable) for a tool that
+ // is NOT truncation-exempt, so the exemption test isn't vacuously true
+ // because the payload never actually crossed the budget.
+ let mw = truncation_probe_mw();
+ let payload = oversized_workflow_proposal_json(30);
+ let mut result = tool_result("some_other_tool", &payload);
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation("other-truncate", "some_other_tool"),
+ &mut result,
+ )
+ .await
+ .unwrap();
+ assert_ne!(
+ result_text(&result),
+ payload,
+ "a non-exempt tool's oversized payload should be truncated by the shared byte-budget backstop"
+ );
+ assert!(
+ result_text(&result).contains("truncated by tool_result_budget"),
+ "expected the byte-budget truncation marker: {}",
+ result_text(&result)
+ );
+ assert!(
+ serde_json::from_str::<serde_json::Value>(&result_text(&result)).is_err(),
+ "truncated JSON should no longer parse as a whole document"
+ );
+}
+
+#[tokio::test]
+async fn get_tool_output_sample_is_compaction_exempt() {
+ // Gap 2: tokenjuice tabulation elides the very array the model calls
+ // this tool to observe, so it would derive a wrong or nonexistent
+ // `split_out.path` from the tabulated summary instead of the real
+ // response shape. The sample must reach the model untabulated.
+ let mw = compaction_enabled_mw();
+ let payload = large_sample_response_json(10);
+ let mut result = tool_result("get_tool_output_sample", &payload);
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation("sample", "get_tool_output_sample"),
+ &mut result,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ result_text(&result),
+ payload,
+ "get_tool_output_sample's response must not be tokenjuice-tabulated"
+ );
+}
+
+#[tokio::test]
+async fn get_tool_contract_is_compaction_exempt() {
+ let mw = compaction_enabled_mw();
+ let payload = large_sample_response_json(10);
+ let mut result = tool_result("get_tool_contract", &payload);
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation("contract", "get_tool_contract"),
+ &mut result,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ result_text(&result),
+ payload,
+ "get_tool_contract's response must not be tokenjuice-tabulated"
+ );
+}
+
+/// #6283: the summarizer used to be called with a hard-coded `None` hint, so
+/// it compressed every payload blind to what the user asked for.
+#[tokio::test]
+async fn the_turns_task_hint_reaches_the_payload_summarizer() {
+ struct HintRecorder(std::sync::Mutex<Option<Option<String>>>);
+ #[async_trait]
+ impl PayloadSummarizer for HintRecorder {
+ async fn maybe_summarize_in_parent(
+ &self,
+ _parent_ctx: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ _tool_name: &str,
+ parent_task_hint: Option<&str>,
+ _raw: &str,
+ ) -> anyhow::Result<SummarizeOutcome> {
+ *self.0.lock().expect("recorder lock") = Some(parent_task_hint.map(str::to_owned));
+ Ok(SummarizeOutcome::NotNeeded)
+ }
+ }
+
+ let recorder = Arc::new(HintRecorder(std::sync::Mutex::new(None)));
+ let mut mw = summarizer_mw(recorder.clone());
+ mw.task_hint = Some("find the release notes for v2".to_string());
+ let mut result = tool_result("use_skill", "RAW-TOOL-OUTPUT");
+
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation("use-skill", "use_skill"),
+ &mut result,
+ )
+ .await
+ .expect("after_tool should not fail");
+
+ assert_eq!(
+ recorder.0.lock().expect("recorder lock").clone(),
+ Some(Some("find the release notes for v2".to_string())),
+ "the turn's task hint must be handed to the payload summarizer"
+ );
+}
+
+/// #6283 review: the authoritative size is stated after the output caps, so a
+/// tool cap shorter than the summary cannot cut it away.
+#[tokio::test]
+async fn the_summarized_size_survives_a_tool_cap_shorter_than_the_summary() {
+ let mut tool_policies = HashMap::new();
+ tool_policies.insert(
+ "terse".to_string(),
+ TaToolPolicy::classified().with_runtime(ToolRuntime {
+ timeout_ms: None,
+ timeout: ToolTimeout::Inherit,
+ max_retries: None,
+ idempotent: false,
+ cancelable: true,
+ sandbox: tinytools::SandboxMode::Inherit,
+ max_result_bytes: Some(12),
+ streaming: false,
+ }),
+ );
+ let summary = "summary ".repeat(50);
+ let mut mw = summarizer_mw(StubSummarizer::ok(SummarizeOutcome::Summarized(
+ crate::agent::tinyagents::payload_summarizer::SummarizedPayload {
+ summary_bytes: summary.len(),
+ summary,
+ original_bytes: 119_796,
+ },
+ )));
+ mw.tool_policies = tool_policies;
+ let mut result = tool_result("terse", &"payload ".repeat(200));
+
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation("terse-cap", "terse"),
+ &mut result,
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ result_text(&result)
+ .starts_with("[openhuman: summary of 119796 bytes of tool output, complete]"),
+ "the real size must lead the content whatever the caps did, got {:?}",
+ result_text(&result).chars().take(160).collect::<String>()
+ );
+ assert!(
+ result_text(&result).contains("[truncated by tool cap:"),
+ "the summary itself is still bound by the tool's cap"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs
index 57f3c5a432..69e1d9c00c 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs
@@ -536,312 +536,5 @@ async fn tool_output_honors_a_tools_own_cap() {
);
}
-#[test]
-fn compaction_exempt_tools_contains_every_proposal_tool() {
- for tool in [
- "propose_workflow",
- "revise_workflow",
- "edit_workflow",
- "save_workflow",
- "create_workflow",
- ] {
- assert!(
- COMPACTION_EXEMPT_TOOLS.contains(&tool),
- "{tool} must be exempt from tokenjuice/summarizer compaction"
- );
- }
-}
-
-#[tokio::test]
-#[ignore = "requires a built TinyJuice module"]
-async fn tool_output_tabulates_a_large_graph_for_a_non_exempt_tool() {
- // Sanity baseline proving this test's payload actually exercises real
- // tinyjuice tabulation (and isn't just below-threshold): a tool name
- // NOT in COMPACTION_EXEMPT_TOOLS loses the `"type"` marker.
- // Resolve the explicit release fixture before `after_tool` performs
- // ambient config initialisation. A pristine CI workspace otherwise
- // exercises the production fail-open path before the test override is
- // admitted, hiding a usable module behind unchanged output.
- crate::inference::tokenjuice::install_from_config(&crate::config::Config::default())
- .await
- .expect("released TinyJuice module must load and accept host configuration");
- let mw = compaction_enabled_mw();
- let payload = large_workflow_proposal_json();
- assert!(
- payload.len()
- >= crate::config::Config::default()
- .tokenjuice
- .min_bytes_to_compress,
- "baseline payload must clear OpenHuman's configured compaction floor"
- );
- let mut result = tool_result("some_other_tool", &payload);
- mw.after_tool(
- &mut ctx(),
- &(),
- &invocation("other-compact", "some_other_tool"),
- &mut result,
- )
- .await
- .unwrap();
- assert_ne!(
- result_text(&result),
- payload,
- "a non-exempt tool's large uniform-array payload should be rewritten by tokenjuice"
- );
- let reparsed: Result<serde_json::Value, _> = serde_json::from_str(&result_text(&result));
- let marker_survived = reparsed
- .ok()
- .and_then(|v| v.get("type").and_then(|t| t.as_str().map(str::to_string)))
- == Some("workflow_proposal".to_string());
- assert!(
- !marker_survived,
- "baseline expectation: tabulation strips the type marker for non-exempt tools"
- );
-}
-
-#[tokio::test]
-async fn tool_output_leaves_propose_workflow_byte_for_byte_intact() {
- let mw = compaction_enabled_mw();
- let payload = large_workflow_proposal_json();
- let mut result = tool_result("propose_workflow", &payload);
- mw.after_tool(
- &mut ctx(),
- &(),
- &invocation("proposal-compact", "propose_workflow"),
- &mut result,
- )
- .await
- .unwrap();
- assert_eq!(
- result_text(&result),
- payload,
- "propose_workflow results must pass through compaction untouched"
- );
- let reparsed: serde_json::Value = serde_json::from_str(&result_text(&result)).unwrap();
- assert_eq!(reparsed["type"], "workflow_proposal");
- assert_eq!(reparsed["graph"]["nodes"].as_array().unwrap().len(), 20);
-}
-
-#[tokio::test]
-async fn tool_output_leaves_every_exempt_tool_name_intact() {
- let mw = compaction_enabled_mw();
- let payload = large_workflow_proposal_json();
- for tool in COMPACTION_EXEMPT_TOOLS {
- let mut result = tool_result(tool, &payload);
- mw.after_tool(
- &mut ctx(),
- &(),
- &invocation(format!("exempt-{tool}"), *tool),
- &mut result,
- )
- .await
- .unwrap();
- assert_eq!(
- result_text(&result),
- payload,
- "{tool}'s result must pass through compaction untouched"
- );
- }
-}
-
-#[tokio::test]
-async fn tool_output_leaves_an_oversized_propose_workflow_byte_for_byte_intact() {
- // Gap 1: a ≥10-node proposal routinely exceeds the ~16 KiB shared
- // byte-budget backstop. Before the truncation exemption, step 4
- // truncated it at a UTF-8 boundary — invalid JSON, so both
- // `flows::ops::extract_workflow_proposal` and the frontend's
- // `parseWorkflowProposal` silently fell back to `proposal: None` and a
- // blank canvas. This must survive byte-for-byte regardless of size.
- let mw = truncation_probe_mw();
- let payload = oversized_workflow_proposal_json(30);
- assert!(
- payload.len() > DEFAULT_TOOL_RESULT_BUDGET_BYTES,
- "test payload must exceed the shared byte budget to exercise step 4: {} bytes",
- payload.len()
- );
- let mut result = tool_result("propose_workflow", &payload);
- mw.after_tool(
- &mut ctx(),
- &(),
- &invocation("proposal-truncate", "propose_workflow"),
- &mut result,
- )
- .await
- .unwrap();
- assert_eq!(
- result_text(&result),
- payload,
- "an oversized propose_workflow result must not be truncated by the shared byte-budget backstop"
- );
- let reparsed: serde_json::Value = serde_json::from_str(&result_text(&result))
- .expect("must still be valid JSON after passing through after_tool");
- assert_eq!(reparsed["type"], "workflow_proposal");
- assert_eq!(reparsed["graph"]["nodes"].as_array().unwrap().len(), 30);
-}
-
-#[tokio::test]
-async fn tool_output_truncates_the_same_oversized_payload_for_a_non_exempt_tool() {
- // Baseline pairing with the test above: proves the identical oversized
- // payload IS truncated (and consequently unparseable) for a tool that
- // is NOT truncation-exempt, so the exemption test isn't vacuously true
- // because the payload never actually crossed the budget.
- let mw = truncation_probe_mw();
- let payload = oversized_workflow_proposal_json(30);
- let mut result = tool_result("some_other_tool", &payload);
- mw.after_tool(
- &mut ctx(),
- &(),
- &invocation("other-truncate", "some_other_tool"),
- &mut result,
- )
- .await
- .unwrap();
- assert_ne!(
- result_text(&result),
- payload,
- "a non-exempt tool's oversized payload should be truncated by the shared byte-budget backstop"
- );
- assert!(
- result_text(&result).contains("truncated by tool_result_budget"),
- "expected the byte-budget truncation marker: {}",
- result_text(&result)
- );
- assert!(
- serde_json::from_str::<serde_json::Value>(&result_text(&result)).is_err(),
- "truncated JSON should no longer parse as a whole document"
- );
-}
-
-#[tokio::test]
-async fn get_tool_output_sample_is_compaction_exempt() {
- // Gap 2: tokenjuice tabulation elides the very array the model calls
- // this tool to observe, so it would derive a wrong or nonexistent
- // `split_out.path` from the tabulated summary instead of the real
- // response shape. The sample must reach the model untabulated.
- let mw = compaction_enabled_mw();
- let payload = large_sample_response_json(10);
- let mut result = tool_result("get_tool_output_sample", &payload);
- mw.after_tool(
- &mut ctx(),
- &(),
- &invocation("sample", "get_tool_output_sample"),
- &mut result,
- )
- .await
- .unwrap();
- assert_eq!(
- result_text(&result),
- payload,
- "get_tool_output_sample's response must not be tokenjuice-tabulated"
- );
-}
-
-#[tokio::test]
-async fn get_tool_contract_is_compaction_exempt() {
- let mw = compaction_enabled_mw();
- let payload = large_sample_response_json(10);
- let mut result = tool_result("get_tool_contract", &payload);
- mw.after_tool(
- &mut ctx(),
- &(),
- &invocation("contract", "get_tool_contract"),
- &mut result,
- )
- .await
- .unwrap();
- assert_eq!(
- result_text(&result),
- payload,
- "get_tool_contract's response must not be tokenjuice-tabulated"
- );
-}
-
-/// #6283: the summarizer used to be called with a hard-coded `None` hint, so
-/// it compressed every payload blind to what the user asked for.
-#[tokio::test]
-async fn the_turns_task_hint_reaches_the_payload_summarizer() {
- struct HintRecorder(std::sync::Mutex<Option<Option<String>>>);
- #[async_trait]
- impl PayloadSummarizer for HintRecorder {
- async fn maybe_summarize_in_parent(
- &self,
- _parent_ctx: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
- _tool_name: &str,
- parent_task_hint: Option<&str>,
- _raw: &str,
- ) -> anyhow::Result<SummarizeOutcome> {
- *self.0.lock().expect("recorder lock") = Some(parent_task_hint.map(str::to_owned));
- Ok(SummarizeOutcome::NotNeeded)
- }
- }
-
- let recorder = Arc::new(HintRecorder(std::sync::Mutex::new(None)));
- let mut mw = summarizer_mw(recorder.clone());
- mw.task_hint = Some("find the release notes for v2".to_string());
- let mut result = tool_result("use_skill", "RAW-TOOL-OUTPUT");
-
- mw.after_tool(
- &mut ctx(),
- &(),
- &invocation("use-skill", "use_skill"),
- &mut result,
- )
- .await
- .expect("after_tool should not fail");
-
- assert_eq!(
- recorder.0.lock().expect("recorder lock").clone(),
- Some(Some("find the release notes for v2".to_string())),
- "the turn's task hint must be handed to the payload summarizer"
- );
-}
-
-/// #6283 review: the authoritative size is stated after the output caps, so a
-/// tool cap shorter than the summary cannot cut it away.
-#[tokio::test]
-async fn the_summarized_size_survives_a_tool_cap_shorter_than_the_summary() {
- let mut tool_policies = HashMap::new();
- tool_policies.insert(
- "terse".to_string(),
- TaToolPolicy::classified().with_runtime(ToolRuntime {
- timeout_ms: None,
- timeout: ToolTimeout::Inherit,
- max_retries: None,
- idempotent: false,
- cancelable: true,
- sandbox: tinytools::SandboxMode::Inherit,
- max_result_bytes: Some(12),
- streaming: false,
- }),
- );
- let summary = "summary ".repeat(50);
- let mut mw = summarizer_mw(StubSummarizer::ok(SummarizeOutcome::Summarized(
- crate::agent::tinyagents::payload_summarizer::SummarizedPayload {
- summary_bytes: summary.len(),
- summary,
- original_bytes: 119_796,
- },
- )));
- mw.tool_policies = tool_policies;
- let mut result = tool_result("terse", &"payload ".repeat(200));
-
- mw.after_tool(
- &mut ctx(),
- &(),
- &invocation("terse-cap", "terse"),
- &mut result,
- )
- .await
- .unwrap();
-
- assert!(
- result_text(&result)
- .starts_with("[openhuman: summary of 119796 bytes of tool output, complete]"),
- "the real size must lead the content whatever the caps did, got {:?}",
- result_text(&result).chars().take(160).collect::<String>()
- );
- assert!(
- result_text(&result).contains("[truncated by tool cap:"),
- "the summary itself is still bound by the tool's cap"
- );
-}
+#[path = "middleware_tool_output_compaction_tests.rs"]
+mod compaction_tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_budget_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_budget_tests.rs
new file mode 100644
index 0000000000..7147d403f4
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_budget_tests.rs
@@ -0,0 +1,442 @@
+use super::*;
+#[tokio::test]
+async fn toc_is_absent_when_no_result_was_offloaded() {
+ let mw = ArtifactIndexTocMiddleware::new(0);
+ let mut ctx = ctx_with_artifacts(&[]).await;
+ let mut request = ModelRequest {
+ messages: vec![TaMessage::user("hi")],
+ ..Default::default()
+ };
+
+ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
+
+ assert_eq!(request.messages.len(), 1, "no artifacts, no contents list");
+}
+
+/// The paths reach the model even though nothing in the transcript carries
+/// them — which is the whole point: the pointer's old home (the tool body) is
+/// what the reduction steps act on.
+#[tokio::test]
+async fn toc_lists_every_persisted_artifact_as_a_system_message() {
+ let mw = ArtifactIndexTocMiddleware::new(0);
+ let mut ctx = ctx_with_artifacts(&[
+ ("call-1", "fetch_issues", "outputs/issues-p1.json", 240_000),
+ ("call-2", "web_search", "outputs/search-2.json", 91_000),
+ ])
+ .await;
+ // A transcript that has already lost both pointers: one body blanked by
+ // microcompact, the other never present.
+ let mut request = ModelRequest {
+ messages: vec![
+ TaMessage::user("what did you find?"),
+ TaMessage::tool("call-1", CLEARED_PLACEHOLDER),
+ ],
+ ..Default::default()
+ };
+
+ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
+
+ let last = request.messages.last().expect("a contents list");
+ assert!(
+ matches!(last, TaMessage::System(_)),
+ "must be a system message — compression keeps those verbatim and the trim never drops \
+ one, so the pointer cannot be reduced away: {last:?}"
+ );
+ let text = last.text();
+ assert!(
+ text.contains("outputs/issues-p1.json"),
+ "missing path: {text}"
+ );
+ assert!(
+ text.contains("outputs/search-2.json"),
+ "missing path: {text}"
+ );
+ assert!(text.contains("fetch_issues"), "missing tool name: {text}");
+}
+
+/// Rendered fresh per request, so repeated passes cannot stack stale lists.
+#[tokio::test]
+async fn toc_does_not_accumulate_across_calls() {
+ let mw = ArtifactIndexTocMiddleware::new(0);
+ let mut ctx = ctx_with_artifacts(&[("call-1", "fetch", "outputs/a.json", 100)]).await;
+
+ let mut first = ModelRequest {
+ messages: vec![TaMessage::user("hi")],
+ ..Default::default()
+ };
+ mw.before_model(&mut ctx, &(), &mut first).await.unwrap();
+
+ // The loop rebuilds the request from its own transcript each iteration, so
+ // the second call starts from the same base — not from the mutated first.
+ let mut second = ModelRequest {
+ messages: vec![TaMessage::user("hi")],
+ ..Default::default()
+ };
+ mw.before_model(&mut ctx, &(), &mut second).await.unwrap();
+
+ assert_eq!(first.messages.len(), 2);
+ assert_eq!(
+ second.messages.len(),
+ 2,
+ "exactly one contents list per request"
+ );
+}
+
+// ── the bounds CodeRabbit asked for on #6068 ────────────────────────────────
+
+/// Restoration stops at the input allowance instead of overflowing it.
+///
+/// It runs after compression and before the trim, so an unbounded restore
+/// pushes the request over and the trim evicts whole messages — strictly more
+/// destructive than the blanking being undone, and able to discard the very
+/// results just restored. Preventing the overflow beats repairing it.
+#[tokio::test]
+async fn wrap_up_stops_restoring_at_the_input_budget() {
+ let big = "x".repeat(4_000);
+ let mw = FinalCallWrapUpMiddleware::new(
+ "CONCLUDE NOW",
+ sink_with(&[("call-1", &big), ("call-2", &big), ("call-3", &big)]),
+ // Room for roughly one of them, not three.
+ 1_200,
+ );
+ let mut ctx = RunContext::new(
+ RunConfig::new("mw-test").with_max_model_calls(2),
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ );
+ ctx.limits.record_model_call().unwrap();
+ ctx.limits.record_model_call().unwrap();
+ let mut request = ModelRequest {
+ messages: vec![
+ TaMessage::tool("call-1", CLEARED_PLACEHOLDER),
+ TaMessage::tool("call-2", CLEARED_PLACEHOLDER),
+ TaMessage::tool("call-3", CLEARED_PLACEHOLDER),
+ ],
+ ..Default::default()
+ };
+
+ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
+
+ let restored = request
+ .messages
+ .iter()
+ .filter(|m| m.text().starts_with("xxx"))
+ .count();
+ assert!(
+ restored >= 1 && restored < 3,
+ "some restored, not all — budget 1200 cannot hold three 4k bodies, got {restored}"
+ );
+ // Newest-first: the last tool result is the one the model never saw (the
+ // cap is checked before the request is built). Not `messages.last()` —
+ // that is the wrap-up instruction this middleware just appended.
+ let newest_tool = request
+ .messages
+ .iter()
+ .rev()
+ .find(|m| matches!(m, TaMessage::Tool(_)))
+ .map(|m| m.text())
+ .unwrap_or_default();
+ assert!(
+ newest_tool.starts_with("xxx"),
+ "the newest cleared result is restored first, got: {}",
+ &newest_tool[..newest_tool.len().min(60)]
+ );
+}
+
+/// The contents list is capped, and says how many it left out.
+///
+/// It is a system message so the ladder cannot take it — which also means
+/// nothing downstream can shrink it, so it has to bound itself.
+#[tokio::test]
+async fn toc_is_capped_and_reports_what_it_omitted() {
+ let entries: Vec<(String, String, String, u64)> = (0..200)
+ .map(|i| {
+ (
+ format!("call-{i}"),
+ format!("tool_with_a_long_name_{i}"),
+ format!("outputs/a-fairly-long-artifact-path-{i}.json"),
+ 1_000,
+ )
+ })
+ .collect();
+ let borrowed: Vec<(&str, &str, &str, u64)> = entries
+ .iter()
+ .map(|(a, b, c, d)| (a.as_str(), b.as_str(), c.as_str(), *d))
+ .collect();
+ let mut ctx = ctx_with_artifacts(&borrowed).await;
+ // This middleware's share of the allowance, already split at the install
+ // site — not the whole turn allowance.
+ let mw = ArtifactIndexTocMiddleware::new(200);
+ let mut request = ModelRequest {
+ messages: vec![TaMessage::user("what did you find?")],
+ ..Default::default()
+ };
+
+ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
+
+ let text = request.messages.last().expect("a contents list").text();
+ assert!(
+ text.contains("not listed here"),
+ "an omitted count must be disclosed, not silently dropped: {text}"
+ );
+ // The nominal share, not a loose multiple of it: the cap now seeds `used`
+ // with the header and the reserved footer, so it bounds the whole message
+ // rather than the rows alone (CodeRabbit on #6068).
+ assert!(
+ estimate_text_tokens(&text) <= 200,
+ "the list must stay inside the share it was given: {}",
+ estimate_text_tokens(&text)
+ );
+}
+
+/// Neither share may ever be `0`, because `0` is the sentinel both middlewares
+/// read as "unbounded" — so the allowances that round down into it are the ones
+/// to pin (CodeRabbit on #6068, twice). A model advertising no window is the
+/// sharp case: no window means no `ImageAwareMessageTrimMiddleware` either, so
+/// these two additions are the ones nothing downstream would shrink.
+#[test]
+fn neither_share_is_ever_the_unbounded_sentinel() {
+ for trim_allowance in [0_u64, 1, 5, 9, 99, 100, 2_000, 100_000] {
+ let (toc, restore) = split_input_allowance(trim_allowance);
+ assert!(toc > 0, "allowance {trim_allowance} disabled the TOC cap");
+ assert!(
+ restore > 0,
+ "allowance {trim_allowance} left restoration unbounded"
+ );
+ // The same effective total the function computes — not
+ // `trim_allowance.max(NO_WINDOW_ALLOWANCE)`, which accepted any
+ // over-split below 5_120 (and whose `.min(u64::MAX)` was a no-op).
+ let total = if trim_allowance == 0 {
+ NO_WINDOW_ALLOWANCE
+ } else {
+ trim_allowance
+ };
+ // `1` stays excluded: the function deliberately keeps both shares
+ // positive, which costs one token at that degenerate size.
+ if trim_allowance > 1 {
+ assert!(
+ toc + restore <= total,
+ "allowance {trim_allowance} split into more than it had: {toc} + {restore}"
+ );
+ }
+ }
+ // With no window the split is taken from the fallback total, not from zero.
+ let (toc, restore) = split_input_allowance(0);
+ assert_eq!(toc, 512);
+ assert_eq!(toc + restore, NO_WINDOW_ALLOWANCE);
+ // Proportional sizing is untouched where there is something to divide.
+ assert_eq!(split_input_allowance(2_000), (200, 1_800));
+ assert_eq!(split_input_allowance(100_000), (10_000, 90_000));
+}
+
+/// The end of the same argument: with no window, a run holding far more
+/// artifacts than any list should carry still produces a bounded message.
+#[tokio::test]
+async fn the_contents_list_stays_bounded_when_no_window_is_advertised() {
+ let entries: Vec<(String, String, String, u64)> = (0..400)
+ .map(|i| {
+ (
+ format!("call-{i}"),
+ "file_read".to_string(),
+ format!("outputs/a-fairly-long-artifact-path-{i}.json"),
+ 1_000,
+ )
+ })
+ .collect();
+ let borrowed: Vec<(&str, &str, &str, u64)> = entries
+ .iter()
+ .map(|(a, b, c, d)| (a.as_str(), b.as_str(), c.as_str(), *d))
+ .collect();
+ let mut ctx = ctx_with_artifacts(&borrowed).await;
+ let mw = ArtifactIndexTocMiddleware::new(split_input_allowance(0).0);
+ let mut request = ModelRequest {
+ messages: vec![TaMessage::user("what did you find?")],
+ ..Default::default()
+ };
+
+ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
+
+ let text = request.messages.last().expect("a contents list").text();
+ assert!(
+ text.contains("not listed here"),
+ "an omitted count must be disclosed, not silently dropped: {text}"
+ );
+ assert!(
+ estimate_text_tokens(&text) <= split_input_allowance(0).0,
+ "the no-window fallback must bound the whole list message: {}",
+ estimate_text_tokens(&text)
+ );
+}
+
+/// The other half of the no-window split: restoration must stop too. Without a
+/// window there is no trim middleware behind it, so an unbounded wrap-up would
+/// hand the provider a request it rejects — losing the in-loop conclusion the
+/// whole cap-checkpoint path exists to deliver (CodeRabbit on #6068).
+#[tokio::test]
+async fn wrap_up_restoration_stays_bounded_when_no_window_is_advertised() {
+ let big = "x".repeat(8_000);
+ let entries: Vec<(String, String)> = (0..40)
+ .map(|i| (format!("call-{i}"), big.clone()))
+ .collect();
+ let borrowed: Vec<(&str, &str)> = entries
+ .iter()
+ .map(|(a, b)| (a.as_str(), b.as_str()))
+ .collect();
+ let (_toc, restore) = split_input_allowance(0);
+ let mw = FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&borrowed), restore);
+ let mut ctx = RunContext::new(
+ RunConfig::new("mw-test").with_max_model_calls(2),
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ );
+ ctx.limits.record_model_call().unwrap();
+ ctx.limits.record_model_call().unwrap();
+ let mut request = ModelRequest {
+ messages: borrowed
+ .iter()
+ .map(|(id, _)| TaMessage::tool(*id, CLEARED_PLACEHOLDER))
+ .collect(),
+ ..Default::default()
+ };
+
+ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
+
+ let used: u64 = request.messages.iter().map(estimate_message_tokens).sum();
+ assert!(
+ used <= NO_WINDOW_ALLOWANCE,
+ "the no-window fallback must bound the whole request, not just the list: {used}"
+ );
+ let restored = request
+ .messages
+ .iter()
+ .filter(|m| m.text().starts_with("xxx"))
+ .count();
+ assert!(
+ restored >= 1 && restored < 40,
+ "some restored, not all 40 — got {restored}"
+ );
+}
+
+/// The two consumers share one allowance, so the bound that matters is the one
+/// on the request they *both* wrote to (CodeRabbit on #6068). Runs them in
+/// registration order — wrap-up, then contents list — on the no-window path,
+/// where nothing downstream would trim what they overshoot by.
+#[tokio::test]
+async fn both_middlewares_together_stay_inside_the_no_window_allowance() {
+ let big = "x".repeat(8_000);
+ let outcomes: Vec<(String, String)> = (0..40)
+ .map(|i| (format!("call-{i}"), big.clone()))
+ .collect();
+ let borrowed: Vec<(&str, &str)> = outcomes
+ .iter()
+ .map(|(a, b)| (a.as_str(), b.as_str()))
+ .collect();
+ let artifacts: Vec<(String, String, String, u64)> = (0..400)
+ .map(|i| {
+ (
+ format!("call-{i}"),
+ "file_read".to_string(),
+ format!("outputs/a-fairly-long-artifact-path-{i}.json"),
+ 1_000,
+ )
+ })
+ .collect();
+ let artifact_refs: Vec<(&str, &str, &str, u64)> = artifacts
+ .iter()
+ .map(|(a, b, c, d)| (a.as_str(), b.as_str(), c.as_str(), *d))
+ .collect();
+
+ let mut ctx = ctx_with_artifacts_and_config(
+ &artifact_refs,
+ RunConfig::new("mw-test").with_max_model_calls(2),
+ )
+ .await;
+ ctx.limits.record_model_call().unwrap();
+ ctx.limits.record_model_call().unwrap();
+
+ let (toc_allowance, restore_allowance) = split_input_allowance(0);
+ let mut request = ModelRequest {
+ messages: borrowed
+ .iter()
+ .map(|(id, _)| TaMessage::tool(*id, CLEARED_PLACEHOLDER))
+ .collect(),
+ ..Default::default()
+ };
+
+ // Registration order at the install site: wrap-up first, contents list after.
+ FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&borrowed), restore_allowance)
+ .before_model(&mut ctx, &(), &mut request)
+ .await
+ .unwrap();
+ ArtifactIndexTocMiddleware::new(toc_allowance)
+ .before_model(&mut ctx, &(), &mut request)
+ .await
+ .unwrap();
+
+ let used: u64 = request.messages.iter().map(estimate_message_tokens).sum();
+ assert!(
+ used <= NO_WINDOW_ALLOWANCE,
+ "the combined request must stay inside the shared allowance: {used} > {NO_WINDOW_ALLOWANCE}"
+ );
+ // Both actually contributed — otherwise the bound is met vacuously.
+ assert!(
+ request.messages.iter().any(|m| m.text().starts_with("xxx")),
+ "the wrap-up restored nothing, so the bound proves nothing"
+ );
+ assert!(
+ request
+ .messages
+ .iter()
+ .any(|m| m.text().contains("Stored results from this turn")),
+ "the contents list is absent, so the bound proves nothing"
+ );
+}
+
+/// A share smaller than the fixed text renders no rows at all. Forcing one
+/// would push a message nothing downstream can shrink over its bound, and the
+/// header plus the omitted count already disclose that the results exist
+/// (CodeRabbit on #6068).
+#[tokio::test]
+async fn a_share_smaller_than_the_header_renders_no_rows() {
+ let entries: Vec<(String, String, String, u64)> = (0..10)
+ .map(|i| {
+ (
+ format!("call-{i}"),
+ "file_read".to_string(),
+ format!("outputs/artifact-{i}.json"),
+ 1_000,
+ )
+ })
+ .collect();
+ let borrowed: Vec<(&str, &str, &str, u64)> = entries
+ .iter()
+ .map(|(a, b, c, d)| (a.as_str(), b.as_str(), c.as_str(), *d))
+ .collect();
+ let mut ctx = ctx_with_artifacts(&borrowed).await;
+ // The floor a small window gets — below the header's own cost.
+ let mw = ArtifactIndexTocMiddleware::new(64);
+ let mut request = ModelRequest {
+ messages: vec![TaMessage::user("what did you find?")],
+ ..Default::default()
+ };
+
+ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
+
+ let text = request.messages.last().expect("a contents list").text();
+ assert!(
+ !text.contains("file_read"),
+ "no row fits the share, so none may be forced: {text}"
+ );
+ assert!(
+ text.contains("10 tool result(s) were written to disk"),
+ "the count must still be named so the results stay findable: {text}"
+ );
+ // The bound that matters: the whole rendered message inside the share.
+ // Truncating to zero rows was not enough — the header and footer alone are
+ // ~118 tokens against this 64-token floor, and the earlier form of this
+ // assertion (`< 64 + FOOTER_ALLOWANCE + 64`) was loose enough to accept
+ // exactly that overshoot (CodeRabbit on #6068).
+ assert!(
+ estimate_text_tokens(&text) <= 64,
+ "the message must fit the share it was given: {}",
+ estimate_text_tokens(&text)
+ );
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_tests.rs
index 7bef51b4a9..8b7247a6f6 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_tests.rs
@@ -329,444 +329,6 @@ async fn ctx_with_artifacts_and_config(
/// Nothing offloaded → no message. The contents list must not spend context
/// saying that there is nothing to point at.
-#[tokio::test]
-async fn toc_is_absent_when_no_result_was_offloaded() {
- let mw = ArtifactIndexTocMiddleware::new(0);
- let mut ctx = ctx_with_artifacts(&[]).await;
- let mut request = ModelRequest {
- messages: vec![TaMessage::user("hi")],
- ..Default::default()
- };
-
- mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
-
- assert_eq!(request.messages.len(), 1, "no artifacts, no contents list");
-}
-
-/// The paths reach the model even though nothing in the transcript carries
-/// them — which is the whole point: the pointer's old home (the tool body) is
-/// what the reduction steps act on.
-#[tokio::test]
-async fn toc_lists_every_persisted_artifact_as_a_system_message() {
- let mw = ArtifactIndexTocMiddleware::new(0);
- let mut ctx = ctx_with_artifacts(&[
- ("call-1", "fetch_issues", "outputs/issues-p1.json", 240_000),
- ("call-2", "web_search", "outputs/search-2.json", 91_000),
- ])
- .await;
- // A transcript that has already lost both pointers: one body blanked by
- // microcompact, the other never present.
- let mut request = ModelRequest {
- messages: vec![
- TaMessage::user("what did you find?"),
- TaMessage::tool("call-1", CLEARED_PLACEHOLDER),
- ],
- ..Default::default()
- };
-
- mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
-
- let last = request.messages.last().expect("a contents list");
- assert!(
- matches!(last, TaMessage::System(_)),
- "must be a system message — compression keeps those verbatim and the trim never drops \
- one, so the pointer cannot be reduced away: {last:?}"
- );
- let text = last.text();
- assert!(
- text.contains("outputs/issues-p1.json"),
- "missing path: {text}"
- );
- assert!(
- text.contains("outputs/search-2.json"),
- "missing path: {text}"
- );
- assert!(text.contains("fetch_issues"), "missing tool name: {text}");
-}
-
-/// Rendered fresh per request, so repeated passes cannot stack stale lists.
-#[tokio::test]
-async fn toc_does_not_accumulate_across_calls() {
- let mw = ArtifactIndexTocMiddleware::new(0);
- let mut ctx = ctx_with_artifacts(&[("call-1", "fetch", "outputs/a.json", 100)]).await;
-
- let mut first = ModelRequest {
- messages: vec![TaMessage::user("hi")],
- ..Default::default()
- };
- mw.before_model(&mut ctx, &(), &mut first).await.unwrap();
-
- // The loop rebuilds the request from its own transcript each iteration, so
- // the second call starts from the same base — not from the mutated first.
- let mut second = ModelRequest {
- messages: vec![TaMessage::user("hi")],
- ..Default::default()
- };
- mw.before_model(&mut ctx, &(), &mut second).await.unwrap();
-
- assert_eq!(first.messages.len(), 2);
- assert_eq!(
- second.messages.len(),
- 2,
- "exactly one contents list per request"
- );
-}
-
-// ── the bounds CodeRabbit asked for on #6068 ────────────────────────────────
-
-/// Restoration stops at the input allowance instead of overflowing it.
-///
-/// It runs after compression and before the trim, so an unbounded restore
-/// pushes the request over and the trim evicts whole messages — strictly more
-/// destructive than the blanking being undone, and able to discard the very
-/// results just restored. Preventing the overflow beats repairing it.
-#[tokio::test]
-async fn wrap_up_stops_restoring_at_the_input_budget() {
- let big = "x".repeat(4_000);
- let mw = FinalCallWrapUpMiddleware::new(
- "CONCLUDE NOW",
- sink_with(&[("call-1", &big), ("call-2", &big), ("call-3", &big)]),
- // Room for roughly one of them, not three.
- 1_200,
- );
- let mut ctx = RunContext::new(
- RunConfig::new("mw-test").with_max_model_calls(2),
- crate::agent::tinyagents::host::OpenHumanRunContext::new(),
- );
- ctx.limits.record_model_call().unwrap();
- ctx.limits.record_model_call().unwrap();
- let mut request = ModelRequest {
- messages: vec![
- TaMessage::tool("call-1", CLEARED_PLACEHOLDER),
- TaMessage::tool("call-2", CLEARED_PLACEHOLDER),
- TaMessage::tool("call-3", CLEARED_PLACEHOLDER),
- ],
- ..Default::default()
- };
-
- mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
- let restored = request
- .messages
- .iter()
- .filter(|m| m.text().starts_with("xxx"))
- .count();
- assert!(
- restored >= 1 && restored < 3,
- "some restored, not all — budget 1200 cannot hold three 4k bodies, got {restored}"
- );
- // Newest-first: the last tool result is the one the model never saw (the
- // cap is checked before the request is built). Not `messages.last()` —
- // that is the wrap-up instruction this middleware just appended.
- let newest_tool = request
- .messages
- .iter()
- .rev()
- .find(|m| matches!(m, TaMessage::Tool(_)))
- .map(|m| m.text())
- .unwrap_or_default();
- assert!(
- newest_tool.starts_with("xxx"),
- "the newest cleared result is restored first, got: {}",
- &newest_tool[..newest_tool.len().min(60)]
- );
-}
-
-/// The contents list is capped, and says how many it left out.
-///
-/// It is a system message so the ladder cannot take it — which also means
-/// nothing downstream can shrink it, so it has to bound itself.
-#[tokio::test]
-async fn toc_is_capped_and_reports_what_it_omitted() {
- let entries: Vec<(String, String, String, u64)> = (0..200)
- .map(|i| {
- (
- format!("call-{i}"),
- format!("tool_with_a_long_name_{i}"),
- format!("outputs/a-fairly-long-artifact-path-{i}.json"),
- 1_000,
- )
- })
- .collect();
- let borrowed: Vec<(&str, &str, &str, u64)> = entries
- .iter()
- .map(|(a, b, c, d)| (a.as_str(), b.as_str(), c.as_str(), *d))
- .collect();
- let mut ctx = ctx_with_artifacts(&borrowed).await;
- // This middleware's share of the allowance, already split at the install
- // site — not the whole turn allowance.
- let mw = ArtifactIndexTocMiddleware::new(200);
- let mut request = ModelRequest {
- messages: vec![TaMessage::user("what did you find?")],
- ..Default::default()
- };
-
- mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
-
- let text = request.messages.last().expect("a contents list").text();
- assert!(
- text.contains("not listed here"),
- "an omitted count must be disclosed, not silently dropped: {text}"
- );
- // The nominal share, not a loose multiple of it: the cap now seeds `used`
- // with the header and the reserved footer, so it bounds the whole message
- // rather than the rows alone (CodeRabbit on #6068).
- assert!(
- estimate_text_tokens(&text) <= 200,
- "the list must stay inside the share it was given: {}",
- estimate_text_tokens(&text)
- );
-}
-
-/// Neither share may ever be `0`, because `0` is the sentinel both middlewares
-/// read as "unbounded" — so the allowances that round down into it are the ones
-/// to pin (CodeRabbit on #6068, twice). A model advertising no window is the
-/// sharp case: no window means no `ImageAwareMessageTrimMiddleware` either, so
-/// these two additions are the ones nothing downstream would shrink.
-#[test]
-fn neither_share_is_ever_the_unbounded_sentinel() {
- for trim_allowance in [0_u64, 1, 5, 9, 99, 100, 2_000, 100_000] {
- let (toc, restore) = split_input_allowance(trim_allowance);
- assert!(toc > 0, "allowance {trim_allowance} disabled the TOC cap");
- assert!(
- restore > 0,
- "allowance {trim_allowance} left restoration unbounded"
- );
- // The same effective total the function computes — not
- // `trim_allowance.max(NO_WINDOW_ALLOWANCE)`, which accepted any
- // over-split below 5_120 (and whose `.min(u64::MAX)` was a no-op).
- let total = if trim_allowance == 0 {
- NO_WINDOW_ALLOWANCE
- } else {
- trim_allowance
- };
- // `1` stays excluded: the function deliberately keeps both shares
- // positive, which costs one token at that degenerate size.
- if trim_allowance > 1 {
- assert!(
- toc + restore <= total,
- "allowance {trim_allowance} split into more than it had: {toc} + {restore}"
- );
- }
- }
- // With no window the split is taken from the fallback total, not from zero.
- let (toc, restore) = split_input_allowance(0);
- assert_eq!(toc, 512);
- assert_eq!(toc + restore, NO_WINDOW_ALLOWANCE);
- // Proportional sizing is untouched where there is something to divide.
- assert_eq!(split_input_allowance(2_000), (200, 1_800));
- assert_eq!(split_input_allowance(100_000), (10_000, 90_000));
-}
-
-/// The end of the same argument: with no window, a run holding far more
-/// artifacts than any list should carry still produces a bounded message.
-#[tokio::test]
-async fn the_contents_list_stays_bounded_when_no_window_is_advertised() {
- let entries: Vec<(String, String, String, u64)> = (0..400)
- .map(|i| {
- (
- format!("call-{i}"),
- "file_read".to_string(),
- format!("outputs/a-fairly-long-artifact-path-{i}.json"),
- 1_000,
- )
- })
- .collect();
- let borrowed: Vec<(&str, &str, &str, u64)> = entries
- .iter()
- .map(|(a, b, c, d)| (a.as_str(), b.as_str(), c.as_str(), *d))
- .collect();
- let mut ctx = ctx_with_artifacts(&borrowed).await;
- let mw = ArtifactIndexTocMiddleware::new(split_input_allowance(0).0);
- let mut request = ModelRequest {
- messages: vec![TaMessage::user("what did you find?")],
- ..Default::default()
- };
-
- mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
-
- let text = request.messages.last().expect("a contents list").text();
- assert!(
- text.contains("not listed here"),
- "an omitted count must be disclosed, not silently dropped: {text}"
- );
- assert!(
- estimate_text_tokens(&text) <= split_input_allowance(0).0,
- "the no-window fallback must bound the whole list message: {}",
- estimate_text_tokens(&text)
- );
-}
-
-/// The other half of the no-window split: restoration must stop too. Without a
-/// window there is no trim middleware behind it, so an unbounded wrap-up would
-/// hand the provider a request it rejects — losing the in-loop conclusion the
-/// whole cap-checkpoint path exists to deliver (CodeRabbit on #6068).
-#[tokio::test]
-async fn wrap_up_restoration_stays_bounded_when_no_window_is_advertised() {
- let big = "x".repeat(8_000);
- let entries: Vec<(String, String)> = (0..40)
- .map(|i| (format!("call-{i}"), big.clone()))
- .collect();
- let borrowed: Vec<(&str, &str)> = entries
- .iter()
- .map(|(a, b)| (a.as_str(), b.as_str()))
- .collect();
- let (_toc, restore) = split_input_allowance(0);
- let mw = FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&borrowed), restore);
- let mut ctx = RunContext::new(
- RunConfig::new("mw-test").with_max_model_calls(2),
- crate::agent::tinyagents::host::OpenHumanRunContext::new(),
- );
- ctx.limits.record_model_call().unwrap();
- ctx.limits.record_model_call().unwrap();
- let mut request = ModelRequest {
- messages: borrowed
- .iter()
- .map(|(id, _)| TaMessage::tool(*id, CLEARED_PLACEHOLDER))
- .collect(),
- ..Default::default()
- };
-
- mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
-
- let used: u64 = request.messages.iter().map(estimate_message_tokens).sum();
- assert!(
- used <= NO_WINDOW_ALLOWANCE,
- "the no-window fallback must bound the whole request, not just the list: {used}"
- );
- let restored = request
- .messages
- .iter()
- .filter(|m| m.text().starts_with("xxx"))
- .count();
- assert!(
- restored >= 1 && restored < 40,
- "some restored, not all 40 — got {restored}"
- );
-}
-
-/// The two consumers share one allowance, so the bound that matters is the one
-/// on the request they *both* wrote to (CodeRabbit on #6068). Runs them in
-/// registration order — wrap-up, then contents list — on the no-window path,
-/// where nothing downstream would trim what they overshoot by.
-#[tokio::test]
-async fn both_middlewares_together_stay_inside_the_no_window_allowance() {
- let big = "x".repeat(8_000);
- let outcomes: Vec<(String, String)> = (0..40)
- .map(|i| (format!("call-{i}"), big.clone()))
- .collect();
- let borrowed: Vec<(&str, &str)> = outcomes
- .iter()
- .map(|(a, b)| (a.as_str(), b.as_str()))
- .collect();
- let artifacts: Vec<(String, String, String, u64)> = (0..400)
- .map(|i| {
- (
- format!("call-{i}"),
- "file_read".to_string(),
- format!("outputs/a-fairly-long-artifact-path-{i}.json"),
- 1_000,
- )
- })
- .collect();
- let artifact_refs: Vec<(&str, &str, &str, u64)> = artifacts
- .iter()
- .map(|(a, b, c, d)| (a.as_str(), b.as_str(), c.as_str(), *d))
- .collect();
-
- let mut ctx = ctx_with_artifacts_and_config(
- &artifact_refs,
- RunConfig::new("mw-test").with_max_model_calls(2),
- )
- .await;
- ctx.limits.record_model_call().unwrap();
- ctx.limits.record_model_call().unwrap();
-
- let (toc_allowance, restore_allowance) = split_input_allowance(0);
- let mut request = ModelRequest {
- messages: borrowed
- .iter()
- .map(|(id, _)| TaMessage::tool(*id, CLEARED_PLACEHOLDER))
- .collect(),
- ..Default::default()
- };
-
- // Registration order at the install site: wrap-up first, contents list after.
- FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&borrowed), restore_allowance)
- .before_model(&mut ctx, &(), &mut request)
- .await
- .unwrap();
- ArtifactIndexTocMiddleware::new(toc_allowance)
- .before_model(&mut ctx, &(), &mut request)
- .await
- .unwrap();
-
- let used: u64 = request.messages.iter().map(estimate_message_tokens).sum();
- assert!(
- used <= NO_WINDOW_ALLOWANCE,
- "the combined request must stay inside the shared allowance: {used} > {NO_WINDOW_ALLOWANCE}"
- );
- // Both actually contributed — otherwise the bound is met vacuously.
- assert!(
- request.messages.iter().any(|m| m.text().starts_with("xxx")),
- "the wrap-up restored nothing, so the bound proves nothing"
- );
- assert!(
- request
- .messages
- .iter()
- .any(|m| m.text().contains("Stored results from this turn")),
- "the contents list is absent, so the bound proves nothing"
- );
-}
-
-/// A share smaller than the fixed text renders no rows at all. Forcing one
-/// would push a message nothing downstream can shrink over its bound, and the
-/// header plus the omitted count already disclose that the results exist
-/// (CodeRabbit on #6068).
-#[tokio::test]
-async fn a_share_smaller_than_the_header_renders_no_rows() {
- let entries: Vec<(String, String, String, u64)> = (0..10)
- .map(|i| {
- (
- format!("call-{i}"),
- "file_read".to_string(),
- format!("outputs/artifact-{i}.json"),
- 1_000,
- )
- })
- .collect();
- let borrowed: Vec<(&str, &str, &str, u64)> = entries
- .iter()
- .map(|(a, b, c, d)| (a.as_str(), b.as_str(), c.as_str(), *d))
- .collect();
- let mut ctx = ctx_with_artifacts(&borrowed).await;
- // The floor a small window gets — below the header's own cost.
- let mw = ArtifactIndexTocMiddleware::new(64);
- let mut request = ModelRequest {
- messages: vec![TaMessage::user("what did you find?")],
- ..Default::default()
- };
-
- mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
-
- let text = request.messages.last().expect("a contents list").text();
- assert!(
- !text.contains("file_read"),
- "no row fits the share, so none may be forced: {text}"
- );
- assert!(
- text.contains("10 tool result(s) were written to disk"),
- "the count must still be named so the results stay findable: {text}"
- );
- // The bound that matters: the whole rendered message inside the share.
- // Truncating to zero rows was not enough — the header and footer alone are
- // ~118 tokens against this 64-token floor, and the earlier form of this
- // assertion (`< 64 + FOOTER_ALLOWANCE + 64`) was loose enough to accept
- // exactly that overshoot (CodeRabbit on #6068).
- assert!(
- estimate_text_tokens(&text) <= 64,
- "the message must fit the share it was given: {}",
- estimate_text_tokens(&text)
- );
-}
+#[path = "middleware_wrap_up_toc_budget_tests.rs"]
+mod budget_tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/routes_tests.rs b/crates/openhuman-core/src/agent/tinyagents/routes_tests.rs
index 403c6258c3..282647daa8 100644
--- a/crates/openhuman-core/src/agent/tinyagents/routes_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/routes_tests.rs
@@ -109,10 +109,12 @@ async fn run_recorded_route(
.await
.expect("unary route run succeeds");
}
- slot.lock()
+ let resolved = slot
+ .lock()
.expect("route slot")
.clone()
- .expect("middleware records canonical response route")
+ .expect("middleware records canonical response route");
+ resolved
}
fn scripted_success() -> Arc<dyn ChatModel<()>> {
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
index 12d6f6049d..e165340e58 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
@@ -345,531 +345,6 @@ pub(crate) async fn run_root_turn_via_hosted_agent(
}
#[allow(clippy::too_many_arguments)]
-async fn run_turn_via_tinyagents_inner(
- run_context: OpenHumanRunContext,
- turn_models: TurnModels,
- provider_id: String,
- model: &str,
- history: Vec<ChatMessage>,
- tool_sets: Vec<Arc<Vec<Box<dyn tinytools::Tool>>>>,
- allowed: Option<HashSet<String>>,
- max_iterations: usize,
- subagent_scope: Option<SubagentScope>,
- context_window: Option<u64>,
- run_queue: Option<Arc<RunQueue>>,
- early_exit_tools: &[&str],
- pause_at_cap: bool,
- max_output_tokens: Option<u32>,
- context_mw: TurnContextMiddleware,
- tool_policy: Option<ToolPolicyEnforcement>,
- deterministic_cacheable: bool,
- defer_turn_completed_to_caller: bool,
- hosted_root: Option<(
- Arc<crate::agent::tinyagents::host::OpenHumanHostBase>,
- String,
- )>,
-) -> Result<TinyagentsTurnOutcome> {
- // The host context is the sole turn carrier. Pulling the sender into this
- // local keeps the event bridge API compact without creating a second
- // parameter path for progress.
- let on_progress = run_context.progress.clone();
- // `0` means "unset" → the legacy default (a native-bus / test convention);
- // otherwise the harness model-call cap would be zero and abort the run before
- // the first provider call.
- let max_iterations = effective_max_iterations(max_iterations);
- // Hosted resolution must expose this turn's already-selected primary and
- // fallback models. Build the resolver before assembly consumes the model
- // bundle; it is installed only on the invocation-local host bundle.
- let hosted_model_resolver = hosted_root.as_ref().map(|_| {
- Arc::new(
- crate::agent::tinyagents::turn_models::TurnModelResolver::from_turn_models(
- &turn_models,
- ),
- ) as Arc<dyn tinyagents_harness::host::ModelResolver<()>>
- });
- // Assembly consumes the registry sets. The host security adapter must see
- // the exact same `Arc`-shared instances, so retain only the cheap Arc clone
- // for a hosted invocation (never clone the tools themselves).
- let hosted_tool_sets = hosted_root.as_ref().map(|_| tool_sets.clone());
- // The turn's crate `ChatModel` set (`turn_models`) and the provider telemetry
- // id are built by the caller via `build_turn_models` — the seam entry is
- // crate-native and no longer names `Provider` (issue #4249, Phase 5). The
- // telemetry id (`{provider_id}.{model}` in Langfuse) rides in as a param.
- let AssembledTurnHarness {
- harness,
- cursor,
- tool_names,
- failure_map,
- provider_usage_carry,
- error_slot,
- halt_summary,
- tool_outcome_sink,
- handle,
- early_exit_hook,
- wrap_up_fired,
- tool_count,
- registry_snapshot: _,
- registry_diagnostics,
- tool_result_artifact_index,
- compression_mw,
- prompt_cache_guard,
- } = assemble_turn_harness(
- turn_models,
- model,
- tool_sets,
- allowed,
- max_iterations,
- on_progress.clone(),
- subagent_scope.clone(),
- context_window,
- early_exit_tools,
- context_mw,
- run_context.stop_hooks.clone(),
- tool_policy.clone(),
- routes::turn_required_capabilities(model),
- deterministic_cacheable,
- hosted_root.is_some(),
- pause_at_cap,
- );
-
- // Fail-closed registry validation gate (issue #4249, Workstream 10 — registry).
- // The projected `CapabilityRegistry` produced these diagnostics during
- // assembly; enforce them here, *before* the first model dispatch, so an
- // ambiguous/broken tool surface (duplicate name across native/MCP/Composio/
- // generated tools, dangling alias, etc.) aborts the turn instead of silently
- // resolving to an unintended component while a provider call is in flight.
- if !registry_diagnostics.is_empty() {
- let (errors, warnings): (
- Vec<&tinyagents_registry::RegistryDiagnostic>,
- Vec<&tinyagents_registry::RegistryDiagnostic>,
- ) = registry_diagnostics
- .iter()
- .partition(|d| matches!(d.severity, DiagnosticSeverity::Error));
- for diag in &warnings {
- tracing::warn!(
- kind = diag.kind.as_str(),
- name = %diag.name,
- "[registry] non-fatal diagnostic: {}",
- diag.message
- );
- }
- if !errors.is_empty() {
- let messages: Vec<String> = errors
- .iter()
- .map(|d| format!("[{}] {}: {}", d.kind.as_str(), d.name, d.message))
- .collect();
- for msg in &messages {
- tracing::error!("[registry] error-severity diagnostic aborting turn: {msg}");
- }
- tracing::error!(
- error_count = messages.len(),
- warning_count = warnings.len(),
- "[registry] aborting turn before model dispatch: capability registry validation failed"
- );
- return Err(anyhow::Error::new(
- crate::agent::error::AgentError::RegistryValidationFailed {
- diagnostics: messages,
- },
- ));
- }
- tracing::debug!(
- warning_count = warnings.len(),
- "[registry] registry diagnostics present (warnings only); proceeding with turn"
- );
- }
-
- let mut config = RunConfig::new("agent_turn")
- .with_max_model_calls(max_iterations)
- .with_max_tool_calls(max_iterations.saturating_mul(8).max(8))
- .with_max_depth(MAX_SPAWN_DEPTH)
- .with_tag("openhuman")
- .with_tag(if subagent_scope.is_some() {
- "scope:subagent"
- } else {
- "scope:root"
- })
- .with_tag(if on_progress.is_some() {
- "observed"
- } else {
- "unobserved"
- });
- // Per-turn output cap rides RunConfig now (Phase 5 groundwork): the loop
- // stamps it onto every `ModelRequest.max_tokens` and the native model adapter
- // adapter honors it, so the cap no longer bakes into the primary + route
- // models. Mirrors the legacy `AGENT_TURN_MAX_OUTPUT_TOKENS` / sub-agent cap.
- if let Some(cap) = max_output_tokens {
- config = config.with_max_turn_output_tokens(cap);
- }
-
- tracing::info!(
- model,
- max_iterations,
- tools = tool_count,
- observed = on_progress.is_some(),
- "[tinyagents] routing turn through tinyagents harness (shared tools)"
- );
-
- let input = crate::agent::message_convert::history_to_messages(&history);
- // Explicit persistence boundary (issue #4455): the request transcript length,
- // captured *before* the run consumes `input`. The turn's persisted
- // `conversation` is everything appended past this index — assistant/tool
- // rounds plus any mid-turn steer/collect messages injected as user turns.
- // Anchoring here (instead of the last-user-message suffix) keeps injected
- // steers from moving the boundary and truncating persisted history on both
- // the parent (`session/turn/core.rs`) and subagent (`subagent_runner`) paths.
- let request_base_len = input.len();
-
- // Build the run context: an optional event sink feeds the progress/cost
- // bridge (streaming) and/or the model-call-cap pauser; the shared steering
- // handle carries mid-flight, early-exit, and cap pauses.
- let mut run_context = run_context;
- run_context.tool_result_artifact_index = tool_result_artifact_index.clone();
- run_context.tool_outcomes = Some(tool_outcome_sink.clone());
- let mut ctx = run_context.clone().into_tinyagents(config);
- // Assemble the run's store registry: the tool-result artifact index (when
- // present) and — behind the default-ON session dual-write flag — the
- // session KV store, so the harness carries a handle to the same
- // `{workspace}/tinyagents_store/kv` tree the live dual-write mirrors into
- // (issue #4249, 04.1). Both stores share one registry so neither clobbers
- // the other. Reads stay legacy until 04.2; this registration is additive
- // and best-effort (a workspace-resolve failure just skips it).
- let mut stores: Option<StoreRegistry> = None;
- if let Some(index) = tool_result_artifact_index {
- stores
- .get_or_insert_with(StoreRegistry::new)
- .register(TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE, index);
- }
- // `session_kv_store` self-gates on the dual-write flag (config default ON +
- // env kill switch), returning `None` when disabled or unresolvable.
- if let Some(session_kv) = crate::agent::session_import::live::session_kv_store().await {
- stores.get_or_insert_with(StoreRegistry::new).register(
- crate::agent::session_import::live::TINYAGENTS_SESSION_KV_STORE,
- session_kv,
- );
- tracing::debug!(
- "[session-store] registered session kv store on RunContext.stores under '{}'",
- crate::agent::session_import::live::TINYAGENTS_SESSION_KV_STORE
- );
- }
- if let Some(stores) = stores {
- ctx = ctx.with_stores(stores);
- }
-
- let streaming = on_progress.is_some();
- // Retain a clone of the progress sink so the turn can emit a terminal
- // `TurnCompleted` after the run (the harness event stream the bridge mirrors
- // has no run-completed event). Parent turns only — a sub-agent turn reports
- // via its `Subagent*` events, not a top-level `TurnCompleted`.
- //
- // #4457 (defect C): suppressed entirely when `defer_turn_completed_to_caller`
- // is set — the caller (chat/session path) emits the single terminal
- // `TurnCompleted` itself, after its post-run wrap-up finishes streaming.
- let turn_completed_sink = (subagent_scope.is_none() && !defer_turn_completed_to_caller)
- .then(|| on_progress.clone())
- .flatten();
- // A sink is needed to mirror progress (bridge), to observe model-call
- // completions for the cap pauser, or to persist a durable event journal
- // (issue #4249, 05.1). The journal must attach even for an unobserved
- // (`on_progress = None`) turn so the run stays reconstructable, so the
- // EventSink is now created unconditionally — cheap (an empty sink) and, if
- // no consumer subscribes, inert.
- //
- // Mint the durable run id *before* the sink and seed the sink stream prefix
- // with it (`with_stream_id`), so every persisted observation's `event_id` is
- // the restart-stable `{run_id}-evt-{offset}` a late-attach replay
- // reconstructs the timeline from (05.1). The same id keys the journal + status.
- let journal_run_id = journal::mint_run_id();
- let events = Some(EventSink::with_stream_id(journal_run_id.as_str()));
-
- // Attach the event bridge for EVERY turn — including an unobserved
- // (`on_progress = None`) background/cron turn (#4467, item 3). The bridge's
- // `record_usage` feeds the global cost tracker on each `UsageRecorded` event
- // *during* the run, so a run that burns N model calls and then fails still
- // contributes that spend to the wallet/cost surfaces — the post-run
- // `record_unobserved_turn_usage` fallback below only runs on the success path
- // and never sees a failed run's usage. With `on_progress = None` the bridge
- // still records cost but its progress `send`s are inert no-ops, so there is
- // no spurious streaming. `events` is created unconditionally above, so the
- // bridge is always present.
- let bridge = events.as_ref().map(|events| {
- let bridge = OpenhumanEventBridge::with_scope(
- on_progress,
- model,
- provider_id.clone(),
- max_iterations,
- subagent_scope.clone(),
- cursor.clone(),
- tool_names.clone(),
- failure_map.clone(),
- provider_usage_carry.clone(),
- );
- events.subscribe(bridge.clone());
- bridge
- });
-
- // Cap pauser: stop gracefully at the model-call budget (returning the partial
- // transcript) so the caller can summarize a checkpoint instead of erroring.
- //
- // It is also handed the turn's dispatch guard, so the pause is *recorded* and
- // not merely requested. `SteeringCommand::Pause` is advisory — honoured at the
- // loop boundary — and nothing consulted it before dispatching a new sub-agent,
- // so a dispatch issued in the same instant raced it and took the whole turn
- // down with the run's remaining wall-clock budget (#5804). The guard is
- // resolved here rather than inside the listener because this future runs on
- // the turn's task, where the task-local is in scope; the listener need not.
- if pause_at_cap {
- if let (Some(events), Some(handle)) = (&events, &handle) {
- // Only the TOP-LEVEL turn's cap pause is binding on dispatch. A
- // sub-agent reaching its own model-call cap is a routine outcome —
- // it summarises and hands its result back (`hit_cap`) — and the
- // parent may legitimately keep delegating afterwards. Recording a
- // child's cap here would stop the whole turn's fan-out on a signal
- // that says nothing about the parent's budget, so `subagent_scope`
- // gates it: `None` is the chat turn, `Some` is a delegated child.
- // The child still gets its advisory `Pause` either way.
- let dispatch_guard = subagent_scope
- .is_none()
- .then(|| run_context.dispatch.clone())
- .flatten();
- events.subscribe(CapPauser::new(
- handle.clone(),
- max_iterations,
- ctx.run_id().as_str(),
- dispatch_guard,
- ));
- }
- }
-
- // Durable event journal + status store (issue #4249, 05.1). Attached *in
- // addition to* the bridge above: the EventSink fans out to both, so the
- // existing progress/global-bus path is untouched. Best-effort and non-fatal
- // — a failure to open/attach the journal returns `None` and the turn runs
- // unaffected. The handle stamps the terminal status once the run returns.
- // A sub-agent turn records under its task scope as the status thread id, so
- // `list_by_thread` can enumerate a task's runs (full parent/root lineage is
- // a 05.2/05.3 follow-up).
- let journal_thread_id = subagent_scope
- .as_ref()
- .map(|scope| tinyagents_harness::ids::ThreadId::new(scope.task_id.clone()));
- let turn_journal = match &events {
- Some(events) => {
- journal::attach_turn_journal(events, model, journal_run_id.clone(), journal_thread_id)
- .await
- }
- None => None,
- };
- if subagent_scope.is_none() {
- if let Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat {
- request_id: Some(request_id),
- ..
- }) = run_context.origin.as_ref()
- {
- journal::register_request_journal_run(request_id, journal_run_id.as_str());
- }
- }
-
- if let Some(events) = &events {
- ctx = ctx.with_events(events.clone());
- }
-
- // Steering: attach the shared handle (when present), drain any already-queued
- // steer messages into it (so a pre-run steer lands before the first model
- // call), and forward mid-flight steers via a poll loop. The same handle
- // carries the early-exit `Pause`.
- //
- // Best-effort thread label for the delivery/requeue observability events and
- // the metadata on any requeued steer: a sub-agent uses its task id; the
- // interactive/channel parent turn reads the task-local turn origin.
- let steer_thread_label = subagent_scope
- .as_ref()
- .map(|s| s.task_id.clone())
- .or_else(|| match run_context.origin.as_ref() {
- Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat { thread_id, .. }) => {
- Some(thread_id.clone())
- }
- Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
- reply_target,
- ..
- }) => Some(reply_target.clone()),
- _ => None,
- })
- .unwrap_or_default();
-
- // The forwarder is wrapped in an abort-on-drop RAII guard (issue #4456): its
- // `Drop` aborts the poll task, deregisters the sub-agent steering handle, and
- // drains residual (delivered-but-unapplied) steers back into the session run
- // queue. Because the guard is held across the drive future, that cleanup runs
- // identically on normal return, error, AND drop-cancellation — the previous
- // manual `forwarder.abort()` after the drive future only ran on normal
- // return, so a cancelled turn (web interrupt / sub-agent abort, both
- // drop-based) leaked a forwarder task that looped forever and raced the next
- // turn for the shared run queue.
- let steering_forwarder_guard = if let Some(handle) = handle {
- let registry_task_id = if let Some(scope) = &subagent_scope {
- let task_id = TaskId::new(scope.task_id.clone());
- shared_steering_registry().register(task_id.clone(), handle.clone());
- tracing::debug!(
- task_id = scope.task_id.as_str(),
- "[tinyagents] registered subagent steering handle"
- );
- Some(task_id)
- } else {
- None
- };
- // Pre-run drain so a steer/collect queued before the turn started lands
- // ahead of the first model call.
- if let Some(queue) = run_queue.clone() {
- steering_forwarder::forward_steers(&queue, &handle, &steer_thread_label).await;
- steering_forwarder::forward_collects(&queue, &handle, &steer_thread_label).await;
- }
- ctx = ctx.with_steering(handle.clone());
- Some(steering_forwarder::SteeringForwarderGuard::new(
- handle,
- run_queue,
- registry_task_id,
- steer_thread_label.clone(),
- ))
- } else {
- None
- };
-
- // Heap-allocate the harness drive future. It is large (it owns the whole run
- // context, middleware stack, and loop state), and a sub-agent turn runs
- // nested inside its parent's drive future — leaving it inline on the stack
- // overflows when the parent + child drives compose. Boxing keeps only a
- // pointer on the stack at each level.
- let resolved_route_slot = run_context.resolved_route.clone();
- let run_result = if let Some((base, agent_id)) = hosted_root {
- let tool_sets = hosted_tool_sets.expect("hosted root retained its tool sets");
- let mut host_bundle =
- crate::agent::tinyagents::host::OpenHumanHostBundleFactory::build_for_invocation(
- crate::agent::tinyagents::host::OpenHumanHostInvocationInputs {
- base,
- tool_sets,
- tool_policy: tool_policy
- .as_ref()
- .map(|policy| Arc::new(policy.session.clone())),
- model_resolver: hosted_model_resolver,
- },
- &run_context,
- );
- // The root session has already assembled its exact system prompt,
- // learned context and history before this graph runs. Keep those bytes
- // as the hosted request rather than composing/recalling a second copy;
- // the host still owns definition resolution, security, model routing,
- // budgets, progress and outcome classification for this invocation.
- host_bundle.capabilities.context = Arc::new(PrecomposedRootContext);
- host_bundle.capabilities.memory = None;
- host_bundle.capabilities.experience = None;
- // Session finalization owns the full-fidelity hook payload (including
- // sanitized per-tool outcomes). The generic names-only summary would
- // otherwise fire the same hooks a second time.
- host_bundle.capabilities.learning = None;
-
- let invocation = AgentInvocation::new(
- host_bundle.capabilities,
- AgentTurnRequest::new(agent_id, input),
- ctx,
- )
- .with_runtime(InvocationRuntime::new(harness));
- let state = ();
- if streaming {
- let stream = root_hosted_harness()
- .invoke_agent_stream(invocation, &state)
- .await;
- match stream {
- Ok(mut stream) => {
- let mut terminal = None;
- while let Some(item) = stream.next().await {
- match item {
- AgentStreamItem::Event(_) => {}
- AgentStreamItem::Completed(run) => {
- terminal = Some(Ok(*run));
- break;
- }
- AgentStreamItem::Failed { error, .. } => {
- terminal =
- Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));
- break;
- }
- }
- }
- terminal.unwrap_or_else(|| {
- Err(tinyagents_harness::TinyAgentsError::Model(
- "hosted agent stream ended without terminal run".to_string(),
- ))
- })
- }
- Err(error) => Err(error),
- }
- } else {
- root_hosted_harness().invoke_agent(invocation, &state).await
- }
- } else if streaming {
- let mut stream = Box::pin(harness.invoke_stream_in_context(&(), ctx, input));
- let mut terminal = None;
- while let Some(item) = stream.next().await {
- match item {
- AgentStreamItem::Event(_) => {}
- AgentStreamItem::Completed(run) => {
- terminal = Some(Ok(*run));
- break;
- }
- AgentStreamItem::Failed { error, .. } => {
- terminal = Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));
- break;
- }
- }
- }
- terminal.unwrap_or_else(|| {
- Err(tinyagents_harness::TinyAgentsError::Model(
- "tinyagents stream ended without terminal run".to_string(),
- ))
- })
- } else {
- Box::pin(harness.invoke_in_context(&(), ctx, input)).await
- };
- // Drive future returned: run cleanup now (abort poll task + deregister +
- // requeue residual steers) rather than deferring to end-of-scope so the poll
- // loop cannot deliver into the no-longer-drained handle during post-run
- // journal/mapping work. On a *cancelled* turn this line is never reached; the
- // guard's `Drop` fires as the turn future unwinds, giving identical cleanup.
- drop(steering_forwarder_guard);
- let run = match run_result {
- Ok(run) => run,
- Err(e) => {
- return Err(map_turn_run_error(
- e,
- model,
- max_iterations,
- &error_slot,
- turn_journal.as_ref(),
- )
- .await);
- }
- };
-
- let resolved_route = resolved_route_slot
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .clone();
- Ok(finalize_turn_outcome(
- run,
- model,
- max_iterations,
- &subagent_scope,
- pause_at_cap,
- turn_journal.as_ref(),
- compression_mw.as_ref(),
- prompt_cache_guard.as_ref(),
- turn_completed_sink,
- bridge,
- early_exit_hook,
- &halt_summary,
- &wrap_up_fired,
- &tool_outcome_sink,
- resolved_route,
- request_base_len,
- )
- .await)
-}
+#[path = "turn_runner_inner.rs"]
+mod turn_runner_inner;
+use turn_runner_inner::run_turn_via_tinyagents_inner;
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner_inner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner_inner.rs
new file mode 100644
index 0000000000..062b683ad8
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner_inner.rs
@@ -0,0 +1,529 @@
+use super::*;
+pub(super) async fn run_turn_via_tinyagents_inner(
+ run_context: OpenHumanRunContext,
+ turn_models: TurnModels,
+ provider_id: String,
+ model: &str,
+ history: Vec<ChatMessage>,
+ tool_sets: Vec<Arc<Vec<Box<dyn tinytools::Tool>>>>,
+ allowed: Option<HashSet<String>>,
+ max_iterations: usize,
+ subagent_scope: Option<SubagentScope>,
+ context_window: Option<u64>,
+ run_queue: Option<Arc<RunQueue>>,
+ early_exit_tools: &[&str],
+ pause_at_cap: bool,
+ max_output_tokens: Option<u32>,
+ context_mw: TurnContextMiddleware,
+ tool_policy: Option<ToolPolicyEnforcement>,
+ deterministic_cacheable: bool,
+ defer_turn_completed_to_caller: bool,
+ hosted_root: Option<(
+ Arc<crate::agent::tinyagents::host::OpenHumanHostBase>,
+ String,
+ )>,
+) -> Result<TinyagentsTurnOutcome> {
+ // The host context is the sole turn carrier. Pulling the sender into this
+ // local keeps the event bridge API compact without creating a second
+ // parameter path for progress.
+ let on_progress = run_context.progress.clone();
+ // `0` means "unset" → the legacy default (a native-bus / test convention);
+ // otherwise the harness model-call cap would be zero and abort the run before
+ // the first provider call.
+ let max_iterations = effective_max_iterations(max_iterations);
+ // Hosted resolution must expose this turn's already-selected primary and
+ // fallback models. Build the resolver before assembly consumes the model
+ // bundle; it is installed only on the invocation-local host bundle.
+ let hosted_model_resolver = hosted_root.as_ref().map(|_| {
+ Arc::new(
+ crate::agent::tinyagents::turn_models::TurnModelResolver::from_turn_models(
+ &turn_models,
+ ),
+ ) as Arc<dyn tinyagents_harness::host::ModelResolver<()>>
+ });
+ // Assembly consumes the registry sets. The host security adapter must see
+ // the exact same `Arc`-shared instances, so retain only the cheap Arc clone
+ // for a hosted invocation (never clone the tools themselves).
+ let hosted_tool_sets = hosted_root.as_ref().map(|_| tool_sets.clone());
+ // The turn's crate `ChatModel` set (`turn_models`) and the provider telemetry
+ // id are built by the caller via `build_turn_models` — the seam entry is
+ // crate-native and no longer names `Provider` (issue #4249, Phase 5). The
+ // telemetry id (`{provider_id}.{model}` in Langfuse) rides in as a param.
+ let AssembledTurnHarness {
+ harness,
+ cursor,
+ tool_names,
+ failure_map,
+ provider_usage_carry,
+ error_slot,
+ halt_summary,
+ tool_outcome_sink,
+ handle,
+ early_exit_hook,
+ wrap_up_fired,
+ tool_count,
+ registry_snapshot: _,
+ registry_diagnostics,
+ tool_result_artifact_index,
+ compression_mw,
+ prompt_cache_guard,
+ } = assemble_turn_harness(
+ turn_models,
+ model,
+ tool_sets,
+ allowed,
+ max_iterations,
+ on_progress.clone(),
+ subagent_scope.clone(),
+ context_window,
+ early_exit_tools,
+ context_mw,
+ run_context.stop_hooks.clone(),
+ tool_policy.clone(),
+ routes::turn_required_capabilities(model),
+ deterministic_cacheable,
+ hosted_root.is_some(),
+ pause_at_cap,
+ );
+
+ // Fail-closed registry validation gate (issue #4249, Workstream 10 — registry).
+ // The projected `CapabilityRegistry` produced these diagnostics during
+ // assembly; enforce them here, *before* the first model dispatch, so an
+ // ambiguous/broken tool surface (duplicate name across native/MCP/Composio/
+ // generated tools, dangling alias, etc.) aborts the turn instead of silently
+ // resolving to an unintended component while a provider call is in flight.
+ if !registry_diagnostics.is_empty() {
+ let (errors, warnings): (
+ Vec<&tinyagents_registry::RegistryDiagnostic>,
+ Vec<&tinyagents_registry::RegistryDiagnostic>,
+ ) = registry_diagnostics
+ .iter()
+ .partition(|d| matches!(d.severity, DiagnosticSeverity::Error));
+ for diag in &warnings {
+ tracing::warn!(
+ kind = diag.kind.as_str(),
+ name = %diag.name,
+ "[registry] non-fatal diagnostic: {}",
+ diag.message
+ );
+ }
+ if !errors.is_empty() {
+ let messages: Vec<String> = errors
+ .iter()
+ .map(|d| format!("[{}] {}: {}", d.kind.as_str(), d.name, d.message))
+ .collect();
+ for msg in &messages {
+ tracing::error!("[registry] error-severity diagnostic aborting turn: {msg}");
+ }
+ tracing::error!(
+ error_count = messages.len(),
+ warning_count = warnings.len(),
+ "[registry] aborting turn before model dispatch: capability registry validation failed"
+ );
+ return Err(anyhow::Error::new(
+ crate::agent::error::AgentError::RegistryValidationFailed {
+ diagnostics: messages,
+ },
+ ));
+ }
+ tracing::debug!(
+ warning_count = warnings.len(),
+ "[registry] registry diagnostics present (warnings only); proceeding with turn"
+ );
+ }
+
+ let mut config = RunConfig::new("agent_turn")
+ .with_max_model_calls(max_iterations)
+ .with_max_tool_calls(max_iterations.saturating_mul(8).max(8))
+ .with_max_depth(MAX_SPAWN_DEPTH)
+ .with_tag("openhuman")
+ .with_tag(if subagent_scope.is_some() {
+ "scope:subagent"
+ } else {
+ "scope:root"
+ })
+ .with_tag(if on_progress.is_some() {
+ "observed"
+ } else {
+ "unobserved"
+ });
+ // Per-turn output cap rides RunConfig now (Phase 5 groundwork): the loop
+ // stamps it onto every `ModelRequest.max_tokens` and the native model adapter
+ // adapter honors it, so the cap no longer bakes into the primary + route
+ // models. Mirrors the legacy `AGENT_TURN_MAX_OUTPUT_TOKENS` / sub-agent cap.
+ if let Some(cap) = max_output_tokens {
+ config = config.with_max_turn_output_tokens(cap);
+ }
+
+ tracing::info!(
+ model,
+ max_iterations,
+ tools = tool_count,
+ observed = on_progress.is_some(),
+ "[tinyagents] routing turn through tinyagents harness (shared tools)"
+ );
+
+ let input = crate::agent::message_convert::history_to_messages(&history);
+ // Explicit persistence boundary (issue #4455): the request transcript length,
+ // captured *before* the run consumes `input`. The turn's persisted
+ // `conversation` is everything appended past this index — assistant/tool
+ // rounds plus any mid-turn steer/collect messages injected as user turns.
+ // Anchoring here (instead of the last-user-message suffix) keeps injected
+ // steers from moving the boundary and truncating persisted history on both
+ // the parent (`session/turn/core.rs`) and subagent (`subagent_runner`) paths.
+ let request_base_len = input.len();
+
+ // Build the run context: an optional event sink feeds the progress/cost
+ // bridge (streaming) and/or the model-call-cap pauser; the shared steering
+ // handle carries mid-flight, early-exit, and cap pauses.
+ let mut run_context = run_context;
+ run_context.tool_result_artifact_index = tool_result_artifact_index.clone();
+ run_context.tool_outcomes = Some(tool_outcome_sink.clone());
+ let mut ctx = run_context.clone().into_tinyagents(config);
+ // Assemble the run's store registry: the tool-result artifact index (when
+ // present) and — behind the default-ON session dual-write flag — the
+ // session KV store, so the harness carries a handle to the same
+ // `{workspace}/tinyagents_store/kv` tree the live dual-write mirrors into
+ // (issue #4249, 04.1). Both stores share one registry so neither clobbers
+ // the other. Reads stay legacy until 04.2; this registration is additive
+ // and best-effort (a workspace-resolve failure just skips it).
+ let mut stores: Option<StoreRegistry> = None;
+ if let Some(index) = tool_result_artifact_index {
+ stores
+ .get_or_insert_with(StoreRegistry::new)
+ .register(TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE, index);
+ }
+ // `session_kv_store` self-gates on the dual-write flag (config default ON +
+ // env kill switch), returning `None` when disabled or unresolvable.
+ if let Some(session_kv) = crate::agent::session_import::live::session_kv_store().await {
+ stores.get_or_insert_with(StoreRegistry::new).register(
+ crate::agent::session_import::live::TINYAGENTS_SESSION_KV_STORE,
+ session_kv,
+ );
+ tracing::debug!(
+ "[session-store] registered session kv store on RunContext.stores under '{}'",
+ crate::agent::session_import::live::TINYAGENTS_SESSION_KV_STORE
+ );
+ }
+ if let Some(stores) = stores {
+ ctx = ctx.with_stores(stores);
+ }
+
+ let streaming = on_progress.is_some();
+ // Retain a clone of the progress sink so the turn can emit a terminal
+ // `TurnCompleted` after the run (the harness event stream the bridge mirrors
+ // has no run-completed event). Parent turns only — a sub-agent turn reports
+ // via its `Subagent*` events, not a top-level `TurnCompleted`.
+ //
+ // #4457 (defect C): suppressed entirely when `defer_turn_completed_to_caller`
+ // is set — the caller (chat/session path) emits the single terminal
+ // `TurnCompleted` itself, after its post-run wrap-up finishes streaming.
+ let turn_completed_sink = (subagent_scope.is_none() && !defer_turn_completed_to_caller)
+ .then(|| on_progress.clone())
+ .flatten();
+ // A sink is needed to mirror progress (bridge), to observe model-call
+ // completions for the cap pauser, or to persist a durable event journal
+ // (issue #4249, 05.1). The journal must attach even for an unobserved
+ // (`on_progress = None`) turn so the run stays reconstructable, so the
+ // EventSink is now created unconditionally — cheap (an empty sink) and, if
+ // no consumer subscribes, inert.
+ //
+ // Mint the durable run id *before* the sink and seed the sink stream prefix
+ // with it (`with_stream_id`), so every persisted observation's `event_id` is
+ // the restart-stable `{run_id}-evt-{offset}` a late-attach replay
+ // reconstructs the timeline from (05.1). The same id keys the journal + status.
+ let journal_run_id = journal::mint_run_id();
+ let events = Some(EventSink::with_stream_id(journal_run_id.as_str()));
+
+ // Attach the event bridge for EVERY turn — including an unobserved
+ // (`on_progress = None`) background/cron turn (#4467, item 3). The bridge's
+ // `record_usage` feeds the global cost tracker on each `UsageRecorded` event
+ // *during* the run, so a run that burns N model calls and then fails still
+ // contributes that spend to the wallet/cost surfaces — the post-run
+ // `record_unobserved_turn_usage` fallback below only runs on the success path
+ // and never sees a failed run's usage. With `on_progress = None` the bridge
+ // still records cost but its progress `send`s are inert no-ops, so there is
+ // no spurious streaming. `events` is created unconditionally above, so the
+ // bridge is always present.
+ let bridge = events.as_ref().map(|events| {
+ let bridge = OpenhumanEventBridge::with_scope(
+ on_progress,
+ model,
+ provider_id.clone(),
+ max_iterations,
+ subagent_scope.clone(),
+ cursor.clone(),
+ tool_names.clone(),
+ failure_map.clone(),
+ provider_usage_carry.clone(),
+ );
+ events.subscribe(bridge.clone());
+ bridge
+ });
+
+ // Cap pauser: stop gracefully at the model-call budget (returning the partial
+ // transcript) so the caller can summarize a checkpoint instead of erroring.
+ //
+ // It is also handed the turn's dispatch guard, so the pause is *recorded* and
+ // not merely requested. `SteeringCommand::Pause` is advisory — honoured at the
+ // loop boundary — and nothing consulted it before dispatching a new sub-agent,
+ // so a dispatch issued in the same instant raced it and took the whole turn
+ // down with the run's remaining wall-clock budget (#5804). The guard is
+ // resolved here rather than inside the listener because this future runs on
+ // the turn's task, where the task-local is in scope; the listener need not.
+ if pause_at_cap {
+ if let (Some(events), Some(handle)) = (&events, &handle) {
+ // Only the TOP-LEVEL turn's cap pause is binding on dispatch. A
+ // sub-agent reaching its own model-call cap is a routine outcome —
+ // it summarises and hands its result back (`hit_cap`) — and the
+ // parent may legitimately keep delegating afterwards. Recording a
+ // child's cap here would stop the whole turn's fan-out on a signal
+ // that says nothing about the parent's budget, so `subagent_scope`
+ // gates it: `None` is the chat turn, `Some` is a delegated child.
+ // The child still gets its advisory `Pause` either way.
+ let dispatch_guard = subagent_scope
+ .is_none()
+ .then(|| run_context.dispatch.clone())
+ .flatten();
+ events.subscribe(CapPauser::new(
+ handle.clone(),
+ max_iterations,
+ ctx.run_id().as_str(),
+ dispatch_guard,
+ ));
+ }
+ }
+
+ // Durable event journal + status store (issue #4249, 05.1). Attached *in
+ // addition to* the bridge above: the EventSink fans out to both, so the
+ // existing progress/global-bus path is untouched. Best-effort and non-fatal
+ // — a failure to open/attach the journal returns `None` and the turn runs
+ // unaffected. The handle stamps the terminal status once the run returns.
+ // A sub-agent turn records under its task scope as the status thread id, so
+ // `list_by_thread` can enumerate a task's runs (full parent/root lineage is
+ // a 05.2/05.3 follow-up).
+ let journal_thread_id = subagent_scope
+ .as_ref()
+ .map(|scope| tinyagents_harness::ids::ThreadId::new(scope.task_id.clone()));
+ let turn_journal = match &events {
+ Some(events) => {
+ journal::attach_turn_journal(events, model, journal_run_id.clone(), journal_thread_id)
+ .await
+ }
+ None => None,
+ };
+ if subagent_scope.is_none() {
+ if let Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat {
+ request_id: Some(request_id),
+ ..
+ }) = run_context.origin.as_ref()
+ {
+ journal::register_request_journal_run(request_id, journal_run_id.as_str());
+ }
+ }
+
+ if let Some(events) = &events {
+ ctx = ctx.with_events(events.clone());
+ }
+
+ // Steering: attach the shared handle (when present), drain any already-queued
+ // steer messages into it (so a pre-run steer lands before the first model
+ // call), and forward mid-flight steers via a poll loop. The same handle
+ // carries the early-exit `Pause`.
+ //
+ // Best-effort thread label for the delivery/requeue observability events and
+ // the metadata on any requeued steer: a sub-agent uses its task id; the
+ // interactive/channel parent turn reads the task-local turn origin.
+ let steer_thread_label = subagent_scope
+ .as_ref()
+ .map(|s| s.task_id.clone())
+ .or_else(|| match run_context.origin.as_ref() {
+ Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat { thread_id, .. }) => {
+ Some(thread_id.clone())
+ }
+ Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
+ reply_target,
+ ..
+ }) => Some(reply_target.clone()),
+ _ => None,
+ })
+ .unwrap_or_default();
+
+ // The forwarder is wrapped in an abort-on-drop RAII guard (issue #4456): its
+ // `Drop` aborts the poll task, deregisters the sub-agent steering handle, and
+ // drains residual (delivered-but-unapplied) steers back into the session run
+ // queue. Because the guard is held across the drive future, that cleanup runs
+ // identically on normal return, error, AND drop-cancellation — the previous
+ // manual `forwarder.abort()` after the drive future only ran on normal
+ // return, so a cancelled turn (web interrupt / sub-agent abort, both
+ // drop-based) leaked a forwarder task that looped forever and raced the next
+ // turn for the shared run queue.
+ let steering_forwarder_guard = if let Some(handle) = handle {
+ let registry_task_id = if let Some(scope) = &subagent_scope {
+ let task_id = TaskId::new(scope.task_id.clone());
+ shared_steering_registry().register(task_id.clone(), handle.clone());
+ tracing::debug!(
+ task_id = scope.task_id.as_str(),
+ "[tinyagents] registered subagent steering handle"
+ );
+ Some(task_id)
+ } else {
+ None
+ };
+ // Pre-run drain so a steer/collect queued before the turn started lands
+ // ahead of the first model call.
+ if let Some(queue) = run_queue.clone() {
+ steering_forwarder::forward_steers(&queue, &handle, &steer_thread_label).await;
+ steering_forwarder::forward_collects(&queue, &handle, &steer_thread_label).await;
+ }
+ ctx = ctx.with_steering(handle.clone());
+ Some(steering_forwarder::SteeringForwarderGuard::new(
+ handle,
+ run_queue,
+ registry_task_id,
+ steer_thread_label.clone(),
+ ))
+ } else {
+ None
+ };
+
+ // Heap-allocate the harness drive future. It is large (it owns the whole run
+ // context, middleware stack, and loop state), and a sub-agent turn runs
+ // nested inside its parent's drive future — leaving it inline on the stack
+ // overflows when the parent + child drives compose. Boxing keeps only a
+ // pointer on the stack at each level.
+ let resolved_route_slot = run_context.resolved_route.clone();
+ let run_result = if let Some((base, agent_id)) = hosted_root {
+ let tool_sets = hosted_tool_sets.expect("hosted root retained its tool sets");
+ let mut host_bundle =
+ crate::agent::tinyagents::host::OpenHumanHostBundleFactory::build_for_invocation(
+ crate::agent::tinyagents::host::OpenHumanHostInvocationInputs {
+ base,
+ tool_sets,
+ tool_policy: tool_policy
+ .as_ref()
+ .map(|policy| Arc::new(policy.session.clone())),
+ model_resolver: hosted_model_resolver,
+ },
+ &run_context,
+ );
+ // The root session has already assembled its exact system prompt,
+ // learned context and history before this graph runs. Keep those bytes
+ // as the hosted request rather than composing/recalling a second copy;
+ // the host still owns definition resolution, security, model routing,
+ // budgets, progress and outcome classification for this invocation.
+ host_bundle.capabilities.context = Arc::new(PrecomposedRootContext);
+ host_bundle.capabilities.memory = None;
+ host_bundle.capabilities.experience = None;
+ // Session finalization owns the full-fidelity hook payload (including
+ // sanitized per-tool outcomes). The generic names-only summary would
+ // otherwise fire the same hooks a second time.
+ host_bundle.capabilities.learning = None;
+
+ let invocation = AgentInvocation::new(
+ host_bundle.capabilities,
+ AgentTurnRequest::new(agent_id, input),
+ ctx,
+ )
+ .with_runtime(InvocationRuntime::new(harness));
+ let state = ();
+ if streaming {
+ let stream = root_hosted_harness()
+ .invoke_agent_stream(invocation, &state)
+ .await;
+ match stream {
+ Ok(mut stream) => {
+ let mut terminal = None;
+ while let Some(item) = stream.next().await {
+ match item {
+ AgentStreamItem::Event(_) => {}
+ AgentStreamItem::Completed(run) => {
+ terminal = Some(Ok(*run));
+ break;
+ }
+ AgentStreamItem::Failed { error, .. } => {
+ terminal =
+ Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));
+ break;
+ }
+ }
+ }
+ terminal.unwrap_or_else(|| {
+ Err(tinyagents_harness::TinyAgentsError::Model(
+ "hosted agent stream ended without terminal run".to_string(),
+ ))
+ })
+ }
+ Err(error) => Err(error),
+ }
+ } else {
+ root_hosted_harness().invoke_agent(invocation, &state).await
+ }
+ } else if streaming {
+ let mut stream = Box::pin(harness.invoke_stream_in_context(&(), ctx, input));
+ let mut terminal = None;
+ while let Some(item) = stream.next().await {
+ match item {
+ AgentStreamItem::Event(_) => {}
+ AgentStreamItem::Completed(run) => {
+ terminal = Some(Ok(*run));
+ break;
+ }
+ AgentStreamItem::Failed { error, .. } => {
+ terminal = Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));
+ break;
+ }
+ }
+ }
+ terminal.unwrap_or_else(|| {
+ Err(tinyagents_harness::TinyAgentsError::Model(
+ "tinyagents stream ended without terminal run".to_string(),
+ ))
+ })
+ } else {
+ Box::pin(harness.invoke_in_context(&(), ctx, input)).await
+ };
+ // Drive future returned: run cleanup now (abort poll task + deregister +
+ // requeue residual steers) rather than deferring to end-of-scope so the poll
+ // loop cannot deliver into the no-longer-drained handle during post-run
+ // journal/mapping work. On a *cancelled* turn this line is never reached; the
+ // guard's `Drop` fires as the turn future unwinds, giving identical cleanup.
+ drop(steering_forwarder_guard);
+ let run = match run_result {
+ Ok(run) => run,
+ Err(e) => {
+ return Err(map_turn_run_error(
+ e,
+ model,
+ max_iterations,
+ &error_slot,
+ turn_journal.as_ref(),
+ )
+ .await);
+ }
+ };
+
+ let resolved_route = resolved_route_slot
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .clone();
+ Ok(finalize_turn_outcome(
+ run,
+ model,
+ max_iterations,
+ &subagent_scope,
+ pause_at_cap,
+ turn_journal.as_ref(),
+ compression_mw.as_ref(),
+ prompt_cache_guard.as_ref(),
+ turn_completed_sink,
+ bridge,
+ early_exit_hook,
+ &halt_summary,
+ &wrap_up_fired,
+ &tool_outcome_sink,
+ resolved_route,
+ request_base_len,
+ )
+ .await)
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner_tests.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner_tests.rs
index 2fbaf3b22d..d5e103ec2a 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner_tests.rs
@@ -137,8 +137,18 @@ async fn concurrent_hosted_roots_keep_models_progress_workspace_and_origin_isola
assert_eq!(left.text, "left");
assert_eq!(right.text, "right");
+ let left_history: Vec<_> = left
+ .history
+ .iter()
+ .map(|message| (&message.role, &message.content))
+ .collect();
+ let right_history: Vec<_> = right
+ .history
+ .iter()
+ .map(|message| (&message.role, &message.content))
+ .collect();
assert_ne!(
- left.history, right.history,
+ left_history, right_history,
"each overlay kept its transcript"
);
assert!(
diff --git a/crates/openhuman-core/src/bin/rss_bench.rs b/crates/openhuman-core/src/bin/rss_bench.rs
index c2f8c82aea..1fd7ae5b7f 100644
--- a/crates/openhuman-core/src/bin/rss_bench.rs
+++ b/crates/openhuman-core/src/bin/rss_bench.rs
@@ -32,8 +32,8 @@ use openhuman_core::platform::proc_metrics::{
self, BenchReport, ProcSample, RosterResult, REPORT_SCHEMA_VERSION, RSS_BUDGET_KIB,
RSS_HARD_CAP_KIB,
};
-use openhuman_core::tinytools_agent::dialect::NativeDialect;
use tinytools::{Tool, ToolResult};
+use tinytools_agent::dialect::NativeDialect;
use std::path::PathBuf;
use std::process::Stdio;
diff --git a/crates/openhuman-core/src/cron/seed_tests.rs b/crates/openhuman-core/src/cron/seed_tests.rs
index 6856772126..39a068cd2b 100644
--- a/crates/openhuman-core/src/cron/seed_tests.rs
+++ b/crates/openhuman-core/src/cron/seed_tests.rs
@@ -101,7 +101,6 @@ fn seed_prunes_legacy_welcome_job() {
true,
Some(LEGACY_WELCOME_JOB_NAME.to_string()),
true, // enabled
- None,
)
.expect("seed legacy welcome");
assert_eq!(list_jobs(&config).unwrap().len(), 1);
@@ -144,7 +143,6 @@ fn startup_prune_removes_retired_tinyplace_autopilot_jobs() {
false,
Some(RETIRED_TINYPLACE_AUTOPILOT_AGENT_ID.to_string()),
true,
- None,
)
.expect("seed retired autopilot");
@@ -173,7 +171,6 @@ fn retired_autopilot_prune_uses_immutable_agent_id() {
false,
Some(RETIRED_TINYPLACE_AUTOPILOT_AGENT_ID.to_string()),
true,
- None,
)
.expect("seed renamed retired autopilot");
add_agent_job_with_definition(
@@ -191,7 +188,6 @@ fn retired_autopilot_prune_uses_immutable_agent_id() {
false,
Some("unrelated_agent".to_string()),
true,
- None,
)
.expect("seed unrelated same-name job");
diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs
index 2f84fa42ac..2588734854 100644
--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs
+++ b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs
@@ -81,6 +81,8 @@ fn project_managed_usage_recovers_charged_and_cached() {
resolved_model: None,
continue_turn: None,
served_from_cache: false,
+ correlation: None,
+ resolved_route: None,
};
let projected = project_managed_usage(response);
@@ -122,6 +124,8 @@ fn project_managed_usage_is_noop_without_envelope() {
resolved_model: None,
continue_turn: None,
served_from_cache: false,
+ correlation: None,
+ resolved_route: None,
};
let projected = project_managed_usage(response);
diff --git a/crates/openhuman-core/src/integrations/mod.rs b/crates/openhuman-core/src/integrations/mod.rs
index 939ac1b3f9..450a6d0249 100644
--- a/crates/openhuman-core/src/integrations/mod.rs
+++ b/crates/openhuman-core/src/integrations/mod.rs
@@ -14,6 +14,7 @@ pub mod tools;
pub mod types;
pub use client::{build_client, pricing_for_config, IntegrationClient};
+pub use tinytools::ToolScope;
pub use types::{
BackendResponse, IntegrationPricing, IntegrationPricingEntry, PricingIntegrations,
};
diff --git a/crates/openhuman-core/src/threads/transcript_view/transcript_view_tests.rs b/crates/openhuman-core/src/threads/transcript_view/transcript_view_tests.rs
index 35628d9ebc..a93d360ad0 100644
--- a/crates/openhuman-core/src/threads/transcript_view/transcript_view_tests.rs
+++ b/crates/openhuman-core/src/threads/transcript_view/transcript_view_tests.rs
@@ -503,7 +503,7 @@ fn append_transcript_turn_projects_full_display_shape() {
usage: usage(0.001),
ts: "2026-07-21T09:00:01Z".into(),
reasoning_content: Some("I should call the weather tool.".into()),
- tool_calls: vec![crate::inference::provider::ToolCall {
+ tool_calls: vec![transcript::TranscriptToolCall {
id: "call-1".into(),
name: "get_weather".into(),
arguments: r#"{"city":"NYC"}"#.into(),
@@ -522,12 +522,17 @@ fn append_transcript_turn_projects_full_display_shape() {
iteration: 2,
};
- let msg = |id: Option<&str>, role: &str, content: &str| ChatMessage {
+ let msg = |id: Option<&str>, role: &str, content: &str| transcript::TranscriptMessage {
id: id.map(str::to_string),
role: role.into(),
content: content.into(),
extra_metadata: None,
cache_breakpoints: Vec::new(),
+ turn_usage: None,
+ request_id: None,
+ preserve_request_id: false,
+ interrupted: false,
+ tool_failure: None,
};
let first = vec![
diff --git a/crates/openhuman-core/src/threads/turn_state/mirror_tests.rs b/crates/openhuman-core/src/threads/turn_state/mirror_tests.rs
index d1348800fb..3dc43692a8 100644
--- a/crates/openhuman-core/src/threads/turn_state/mirror_tests.rs
+++ b/crates/openhuman-core/src/threads/turn_state/mirror_tests.rs
@@ -13,9 +13,9 @@ fn fresh(thread_id: &str) -> (tempfile::TempDir, TurnStateMirror) {
// ── Interrupted-partial → session transcript wiring (Task 1) ──────────
-use crate::agent::messages::ChatMessage;
use tinyagents_session::transcript::{
- self, read_transcript, read_transcript_display, DisplayRecord, TranscriptMeta,
+ self, read_transcript, read_transcript_display, DisplayRecord, TranscriptMessage,
+ TranscriptMeta,
};
fn seed_root_transcript(workspace: &std::path::Path, thread_id: &str) -> std::path::PathBuf {
@@ -38,8 +38,13 @@ fn seed_root_transcript(workspace: &std::path::Path, thread_id: &str) -> std::pa
thread_id: Some(thread_id.to_string()),
task_id: None,
};
- transcript::write_transcript(&path, &[ChatMessage::user("hello there")], &meta, None)
- .expect("seed transcript");
+ transcript::write_transcript(
+ &path,
+ &[TranscriptMessage::new("user", "hello there")],
+ &meta,
+ None,
+ )
+ .expect("seed transcript");
path
}
diff --git a/crates/openhuman-core/src/tools/host_extensions.rs b/crates/openhuman-core/src/tools/host_extensions.rs
index c4f593a79e..9fc5c473dc 100644
--- a/crates/openhuman-core/src/tools/host_extensions.rs
+++ b/crates/openhuman-core/src/tools/host_extensions.rs
@@ -8,6 +8,8 @@ use crate::agent::orchestration::tools::DelegationTarget;
use crate::agent::tool_policy::GeneratedToolRuntimeContext;
use crate::tools::toolpacks::PackRegistryHandle;
use tinytools::Tool;
+#[cfg(test)]
+use tinytools::{PermissionLevel, ToolCategory, ToolResult, ToolScope};
/// Reads a tool's pack-registry handle from its erased host extension.
pub fn pack_registry_handle(tool: &dyn Tool) -> Option<&PackRegistryHandle> {
diff --git a/crates/openhuman-core/src/tools/impl/system/node_exec_tests.rs b/crates/openhuman-core/src/tools/impl/system/node_exec_tests.rs
index 70a7a6dc69..62d4187f49 100644
--- a/crates/openhuman-core/src/tools/impl/system/node_exec_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/system/node_exec_tests.rs
@@ -27,12 +27,12 @@ fn node_timeout_policy_unbounded_by_default() {
fn node_timeout_policy_enforces_and_caps_explicit() {
assert_eq!(
node_timeout_policy(&json!({"timeout_secs": 120})),
- ToolTimeout::Secs(120)
+ ToolTimeout::Millis(120_000)
);
// Clamped to the 1800s ceiling.
assert_eq!(
node_timeout_policy(&json!({"timeout_secs": 99999})),
- ToolTimeout::Secs(NODE_TIMEOUT_MAX_SECS)
+ ToolTimeout::Millis(NODE_TIMEOUT_MAX_SECS * 1000)
);
}
diff --git a/crates/openhuman-core/src/tools/impl/system/npm_exec_tests.rs b/crates/openhuman-core/src/tools/impl/system/npm_exec_tests.rs
index 70ab83a698..30c51a322e 100644
--- a/crates/openhuman-core/src/tools/impl/system/npm_exec_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/system/npm_exec_tests.rs
@@ -20,11 +20,11 @@ fn npm_timeout_policy_unbounded_by_default() {
fn npm_timeout_policy_enforces_and_caps_explicit() {
assert_eq!(
npm_timeout_policy(&json!({"timeout_secs": 300})),
- ToolTimeout::Secs(300)
+ ToolTimeout::Millis(300_000)
);
assert_eq!(
npm_timeout_policy(&json!({"timeout_secs": 99999})),
- ToolTimeout::Secs(NPM_TIMEOUT_MAX_SECS)
+ ToolTimeout::Millis(NPM_TIMEOUT_MAX_SECS * 1000)
);
}
diff --git a/crates/openhuman-core/src/tools/impl/system/python_exec_tests.rs b/crates/openhuman-core/src/tools/impl/system/python_exec_tests.rs
index 23a58cdaf5..b8b87da3f8 100644
--- a/crates/openhuman-core/src/tools/impl/system/python_exec_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/system/python_exec_tests.rs
@@ -13,11 +13,11 @@ fn python_timeout_policy_unbounded_by_default() {
fn python_timeout_policy_enforces_and_caps_explicit() {
assert_eq!(
python_timeout_policy(&json!({"timeout_secs": 120})),
- ToolTimeout::Secs(120)
+ ToolTimeout::Millis(120_000)
);
assert_eq!(
python_timeout_policy(&json!({"timeout_secs": 99999})),
- ToolTimeout::Secs(PYTHON_TIMEOUT_MAX_SECS)
+ ToolTimeout::Millis(PYTHON_TIMEOUT_MAX_SECS * 1000)
);
}
diff --git a/crates/openhuman-core/src/tools/impl/system/shell_tests_schema_and_env_tests.rs b/crates/openhuman-core/src/tools/impl/system/shell_tests_schema_and_env_tests.rs
index 3b3a0d3144..f72e8e4ca2 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell_tests_schema_and_env_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell_tests_schema_and_env_tests.rs
@@ -527,7 +527,7 @@ fn shell_timeout_honors_explicit_per_call_value() {
// An explicit in-range request is enforced verbatim.
assert_eq!(
tool.timeout_policy(&json!({"command": "make", "timeout_secs": 1800})),
- ToolTimeout::Secs(1800)
+ ToolTimeout::Millis(1_800_000)
);
assert_eq!(
tool.explicit_timeout(Some(1800)),
diff --git a/crates/openhuman-core/src/tools/mod.rs b/crates/openhuman-core/src/tools/mod.rs
index 5ed1ecf8ee..60adfce790 100644
--- a/crates/openhuman-core/src/tools/mod.rs
+++ b/crates/openhuman-core/src/tools/mod.rs
@@ -68,4 +68,5 @@ pub use schemas::{
all_controller_schemas as all_tools_controller_schemas,
all_registered_controllers as all_tools_registered_controllers,
};
+pub use tinytools::{PermissionLevel, ToolCategory, ToolResult, ToolScope, ToolSpec};
pub(crate) use user_filter::filter_tools_by_user_preference;
diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rs
index 8b597e58c6..7fc71e75d0 100644
--- a/crates/openhuman-core/src/tools/ops.rs
+++ b/crates/openhuman-core/src/tools/ops.rs
@@ -8,6 +8,8 @@ use crate::security::{AuditLogger, SecurityPolicy};
use std::collections::HashMap;
use std::sync::Arc;
use tinytools::Tool;
+#[cfg(test)]
+use tinytools::{ToolResult, ToolSpec};
pub(crate) use super::capability::tool_capability;
diff --git a/crates/openhuman-core/src/web_chat/web_tests.rs b/crates/openhuman-core/src/web_chat/web_tests.rs
index cc8fabc1e9..bd453073c0 100644
--- a/crates/openhuman-core/src/web_chat/web_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests.rs
@@ -1,14 +1,13 @@
use super::{
all_web_channel_controller_schemas, all_web_channel_registered_controllers, cancel_chat,
- classify_inference_error, compose_system_prompt_suffix, event_session_id_for,
- extract_provider_error_detail, generic_inference_error_user_message,
- in_flight_entries_for_test, inference_budget_exceeded_user_message,
- is_inference_budget_exceeded_error, json_output, key_for, locale_reply_directive,
- normalize_model_override, optional_f64, optional_string, parallel_in_flight_entries_for_test,
- provider_role_for_model_override, required_string, schemas, sentry_suppression_reason,
- set_test_forced_run_chat_task_error, set_test_run_chat_task_block, start_chat,
- subscribe_web_channel_events, ChatRequestMetadata, ClassifiedError, TestRunChatTaskBlock,
- WebChatParams,
+ classify_inference_error, event_session_id_for, extract_provider_error_detail,
+ generic_inference_error_user_message, in_flight_entries_for_test,
+ inference_budget_exceeded_user_message, is_inference_budget_exceeded_error, json_output,
+ key_for, locale_reply_directive, normalize_model_override, optional_f64, optional_string,
+ parallel_in_flight_entries_for_test, provider_role_for_model_override, required_string,
+ schemas, sentry_suppression_reason, set_test_forced_run_chat_task_error,
+ set_test_run_chat_task_block, start_chat, subscribe_web_channel_events, ChatRequestMetadata,
+ ClassifiedError, TestRunChatTaskBlock, WebChatParams,
};
use crate::core::TypeSchema;
use std::sync::atomic::{AtomicBool, Ordering};
diff --git a/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs
index 4d8b0fed0a..3d0a95612d 100644
--- a/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs
@@ -193,7 +193,6 @@ async fn start_chat_chat_error_event_serializes_structured_fields_to_json_wire()
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await
@@ -288,7 +287,6 @@ async fn start_chat_emits_structured_rate_limit_metadata_on_chat_error_event() {
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await
diff --git a/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rs
index 7b42d60f68..ac2b32fbaf 100644
--- a/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rs
@@ -99,27 +99,6 @@ fn locale_reply_directive_renders_known_locales() {
assert!(zh.contains("Simplified Chinese"));
}
-#[test]
-fn compose_system_prompt_suffix_combines_locale_and_profile() {
- // Both present → locale first, blank line, then profile suffix.
- let combined = compose_system_prompt_suffix(Some("LOCALE"), Some("PROFILE"))
- .expect("Some output expected when either input is set");
- assert_eq!(combined, "LOCALE\n\nPROFILE");
-
- // Only locale.
- assert_eq!(
- compose_system_prompt_suffix(Some("LOCALE"), None).as_deref(),
- Some("LOCALE")
- );
- // Only profile.
- assert_eq!(
- compose_system_prompt_suffix(None, Some("PROFILE")).as_deref(),
- Some("PROFILE")
- );
- // Both absent → None preserves the agent's vanilla prompt.
- assert!(compose_system_prompt_suffix(None, None).is_none());
-}
-
// ── PTT field additions (Task 1 of global-ptt plan) ─────────────────────────
#[test]
@@ -225,7 +204,6 @@ async fn start_chat_runs_distinct_threads_concurrently() {
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await
@@ -238,7 +216,6 @@ async fn start_chat_runs_distinct_threads_concurrently() {
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await
@@ -279,7 +256,6 @@ async fn cancel_chat_cooperatively_stops_in_flight_turn() {
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await
@@ -346,7 +322,6 @@ async fn wedged_turn_hits_wall_clock_backstop_and_emits_turn_timeout_chat_error(
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await
@@ -406,7 +381,6 @@ async fn parallel_turn_runs_concurrently_with_primary_on_same_thread() {
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await
@@ -422,7 +396,6 @@ async fn parallel_turn_runs_concurrently_with_primary_on_same_thread() {
None,
None,
None,
- None,
Some("parallel".to_string()),
ChatRequestMetadata::default(),
)
diff --git a/crates/openhuman-core/src/web_chat/web_tests_start_chat_ingress_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_start_chat_ingress_tests.rs
index e45492aaee..c565cb8072 100644
--- a/crates/openhuman-core/src/web_chat/web_tests_start_chat_ingress_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests_start_chat_ingress_tests.rs
@@ -10,7 +10,6 @@ async fn start_chat_validates_required_fields() {
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await
@@ -25,7 +24,6 @@ async fn start_chat_validates_required_fields() {
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await
@@ -40,7 +38,6 @@ async fn start_chat_validates_required_fields() {
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await
@@ -58,7 +55,6 @@ async fn start_chat_rejects_prompt_injection_payload() {
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await
@@ -102,7 +98,6 @@ async fn start_chat_emits_sanitized_chat_error_on_inference_failure() {
None,
None,
None,
- None,
ChatRequestMetadata::default(),
)
.await