The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Bound web research and stop repetitive model streams
Steven Enamakelaa255f352100
diff --git a/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.md b/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.mdindex 0b9b0030e5..13558a459f 100644--- a/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.md+++ b/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.md@@ -32,6 +32,7 @@ Three or more steps? Track them on `todo` cards. Don't stop with a plan: execute- Preserve numeric evidence exactly: copy numbers, dates, durations, currencies and ids as observed; don't round or recompute unless asked, and then show the working.- A sub-agent's summary is claims: check it against its `Evidence used`, `Actions taken` and `Failed tool calls`. Do not introduce facts its evidence does not support. Output marked truncated, oversized, partial or unavailable is not complete: fetch more or say so.- Never pass off fabricated output as a result. If a step failed, say so and what you did instead.+- For a short public-research answer, search for the named subject, read the most relevant primary source when available, then answer from the evidence already in the turn. Search again only to fill a specific missing fact needed for the user's request. A differently worded query or a second summary of the same page is not new evidence. If a source cannot be read, state that limit; do not restart the research or claim that you read it.- `retrieve_memory` walks already-ingested history, not a live API; for what is in an inbox right now, search for and call the live integration's action.## Scheduling and workflowsdiff --git a/crates/openhuman-core/src/agent/session_host/driver.rs b/crates/openhuman-core/src/agent/session_host/driver.rsindex a698e01196..5e3606a7c4 100644--- a/crates/openhuman-core/src/agent/session_host/driver.rs+++ b/crates/openhuman-core/src/agent/session_host/driver.rs@@ -512,9 +512,25 @@ fn driver_error_with_snapshot(let history = guard.messages[..accepted_end].to_vec();let unanswered =crate::agent::tinyagents::render_unanswered_steps(&guard.messages[accepted_end..]);- let display = match unanswered {- Some(steps) => format!("The turn stopped before completion: {error}.\n\n{steps}"),- None => format!("The turn stopped before completion: {error}."),+ let display = if error.contains(crate::agent::tinyagents::middleware::STREAM_STALL_ERROR) {+ // The model's streamed narration was stopped before it could repeat+ // indefinitely. Preserve the completed tools as a useful, bounded+ // partial rather than showing only the failed model's process text.+ let results = crate::agent::session_host::turn_checkpoint::results_from_tool_outcomes(+ &guard.tool_outcomes,+ );+ let evidence = crate::agent::session_host::turn_checkpoint::render_tool_results(+ &results,+ crate::agent::session_host::turn_checkpoint::CHECKPOINT_TOTAL_CHARS,+ );+ format!(+ "I stopped a repetitive model response before it could finish. Here are the completed tool results I can report:\n{evidence}"+ )+ } else {+ match unanswered {+ Some(steps) => format!("The turn stopped before completion: {error}.\n\n{steps}"),+ None => format!("The turn stopped before completion: {error}."),+ }};DriverFailure {error: RuntimeError::Driver(error),diff --git a/crates/openhuman-core/src/agent/session_host/driver_tests.rs b/crates/openhuman-core/src/agent/session_host/driver_tests.rsindex 1d360f867c..e31b44b6cb 100644--- a/crates/openhuman-core/src/agent/session_host/driver_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/driver_tests.rs@@ -40,6 +40,38 @@ fn graph_failure_persists_only_accepted_snapshot_history() {.contains("provider rejected follow-up"));}+#[test]+fn stalled_model_stream_reports_completed_evidence_instead_of_its_narration() {+ let snapshot = Arc::new(std::sync::Mutex::new(+ crate::agent::tinyagents::TranscriptSnapshot {+ messages: vec![Message::user("Find information about Jev")],+ accepted_len: 1,+ request_base_len: 1,+ tool_outcomes: vec![crate::agent::tinyagents::ToolCallOutcome {+ call_id: "search-1".into(),+ name: "web_search_tool".into(),+ arguments: serde_json::json!({"query": "Jev TypeSafe"}),+ success: true,+ content: "TypeSafe describes Jev as a System One model".into(),+ duration_ms: 12,+ }],+ ..Default::default()+ },+ ));+ let failure = driver_error_with_snapshot(+ crate::agent::tinyagents::middleware::STREAM_STALL_ERROR,+ &snapshot,+ &sidecar(),+ std::time::Duration::from_millis(1),+ "chat-v1",+ );+ let partial = failure.partial.expect("interrupted partial");+ let display = partial.partial.expect("display partial").content;+ assert!(display.contains("stopped a repetitive model response"));+ assert!(display.contains("TypeSafe describes Jev as a System One model"));+ assert!(!display.contains("Let me"));+}+#[test]fn graph_failure_copies_snapshot_usage_and_failed_tool_outcome_to_sidecar() {let snapshot = Arc::new(std::sync::Mutex::new(diff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.mdindex 60d7eacd19..1532f0df70 100644--- a/crates/openhuman-core/src/agent/tinyagents/README.md+++ b/crates/openhuman-core/src/agent/tinyagents/README.md@@ -30,6 +30,8 @@ The **adapter seam** between OpenHuman and the vendored [`tinyagents`](../../../| `journal.rs` | `TurnJournal` and `FileStatusStore`: a crate `StoreEventJournal` over a JSONL append store plus a `HarnessStatusStore` writer under `{workspace}/tinyagents_store`. Attached alongside the live `observability` bridge as an independent `EventSink` subscriber, wrapped in `RedactingSink`; best-effort and non-fatal. || `reaper.rs` | `reap_orphaned_runs`: startup sweep that marks non-terminal runs `Cancelled` in the durable status store. The only writer over the status seam that `replay/` reads. || `middleware.rs` + `middleware/` | The named OpenHuman middleware stack. `turn_context.rs`: `TurnContextMiddleware` (bundles config and installs the enabled hooks), `TranscriptSnapshotMiddleware`/`TranscriptSnapshotSink`, `HandoffConfig`/`HandoffMiddleware` (oversized sub-agent results stashed for `extract_from_result`). `prompt_cache.rs`: `PromptCacheSegmentMiddleware`. `tool_output.rs`: `ToolOutputMiddleware` (per-result byte cap and optional payload summarizer). `approval.rs`: `ApprovalSecurityMiddleware`. `cli_rpc_only.rs`: `CliRpcOnlyMiddleware`. `tool_policy.rs`: the `ToolPolicyMiddleware` struct and impl (records blocks into `crate::tools::registry::denials`). `tool_outcome_capture.rs`: `ToolOutcomeCaptureMiddleware`. `embedder_hooks.rs`: `EmbedderToolHooksMiddleware`. `arg_recovery.rs`: `ArgRecoveryMiddleware`. `memory_protocol.rs`: `MemoryProtocolMiddleware`. `cost_budget.rs`: `CostBudgetMiddleware`. `repeated_failure.rs`: `RepeatedToolFailureMiddleware`. `loop_guards.rs`: `TerminalInferenceFailure`. `repeat_progress.rs`: `RepeatProgressMiddleware` (adjacent-repeat streaks plus a run-wide `(call, result)` recurrence ledger) and `RepeatEvictionObserver` (registered last; resets the ledger when compaction evicts a recorded result, #6275). `message_trim.rs`: `ImageAwareMessageTrimMiddleware`. `final_call_wrap_up.rs`: `FinalCallWrapUpMiddleware` (on the last permitted model call it withdraws the belt and asks for the conclusion; on the one before it, narrows the belt to `DELIVERABLE_TOOLS` so a turn whose product is a file can still write it). `artifact_index_toc.rs`: `ArtifactIndexTocMiddleware` (issue #6014). `credential_scrub.rs`: `CredentialScrubMiddleware` (issue #4453). |+| `middleware/research_budget.rs` | Forces a top-level direct web research turn to answer after eight completed search or fetch calls. |+| `middleware/stream_stall.rs` | Stops repeated streamed narration before it can continue indefinitely. || `model.rs` | Helpers and wrappers over native crate `ChatModel` values: message/response translation, usage merging, stream-delta forwarding, `MaxTokensModel`, `ProfileOverrideModel`. || `tools.rs` | `CanonicalSharedToolAdapter`: resolves an OpenHuman shared tool registry and forwards the canonical `tinytools::Tool` contract; `EarlyExitHook` pauses successful `ask_user_clarification`-style calls. || `routes.rs` | `WORKLOAD_ROUTE_TIERS` (the tier inventory projected into the model registry), `RequiredCapabilitiesMiddleware`, `FallbackObserverMiddleware`, `UsageCarryMiddleware`, and the per-model fallback policy. |diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex c0971f2286..65b503128c 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -553,6 +553,15 @@ pub(super) fn assemble_turn_harness(&tool_outcome_sink,);+ // Direct web lookup is for a bounded answer. Once enough search/fetch+ // results have returned, spend the next model call on synthesis rather+ // than another variation of the same query. Specialist research runs keep+ // their own budgets and are not narrowed here.+ if subagent_scope.is_none() {+ harness.push_middleware(Arc::new(middleware::ResearchBudgetMiddleware::new()));+ }+ harness.push_middleware(Arc::new(middleware::StreamStallMiddleware::new()));+// SDK-owned tool-policy projection (issue #4249 / tinyagents-full-migration// 01.1). Keep this narrow for now: enforce sandbox requirements declared by// adapter policies without enabling classification/approval/result-bytediff --git a/crates/openhuman-core/src/agent/tinyagents/middleware.rs b/crates/openhuman-core/src/agent/tinyagents/middleware.rsindex f8b631109f..482885da47 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware.rs@@ -39,6 +39,8 @@ mod packed_tool_route;mod prompt_cache;mod repeat_progress;mod repeated_failure;+mod research_budget;+mod stream_stall;mod tool_exposure;mod tool_outcome_capture;mod tool_output;@@ -59,6 +61,8 @@ pub(crate) use packed_tool_route::PackedToolRouteMiddleware;pub(crate) use prompt_cache::PromptCacheSegmentMiddleware;pub(crate) use repeat_progress::RepeatProgressMiddleware;pub(crate) use repeated_failure::RepeatedToolFailureMiddleware;+pub(crate) use research_budget::ResearchBudgetMiddleware;+pub(crate) use stream_stall::{StreamStallMiddleware, STREAM_STALL_ERROR};pub(crate) use tool_exposure::OpenHumanToolExposureShadowMiddleware;pub(crate) use tool_outcome_capture::ToolOutcomeCaptureMiddleware;pub(crate) use tool_policy::ToolPolicyMiddleware;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/research_budget.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/research_budget.rsnew file mode 100644index 0000000000..8b013c9620--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/research_budget.rs@@ -0,0 +1,72 @@+//! Bound direct web research so a run that keeps finding more leads still answers.++use std::sync::atomic::{AtomicUsize, Ordering};++use async_trait::async_trait;+use tinyagents_harness::context::RunContext;+use tinyagents_harness::error::Result as TaResult;+use tinyagents_harness::middleware::{Middleware, ToolInvocationIdentity};+use tinyinference_llm::message::Message;+use tinyinference_llm::model::{ModelRequest, ToolChoice};+use tinytools::ToolResult;++use crate::agent::tinyagents::host::OpenHumanRunContext;++/// Direct web reads allowed before the next model call must conclude the turn.+/// Broad research can use the dedicated research agent; this bounds the master+/// agent's exploratory search while leaving room to read primary sources.+pub(super) const DIRECT_WEB_READ_LIMIT: usize = 8;++const RESEARCH_CLOSE_INSTRUCTION: &str = "The direct web research budget for this turn is exhausted. Answer the user's latest request now using the results already available. State any remaining uncertainty. Do not search again, repeat a page fetch, or merely describe what you plan to read.";++#[derive(Default)]+pub(crate) struct ResearchBudgetMiddleware {+ completed_reads: AtomicUsize,+}++impl ResearchBudgetMiddleware {+ pub(crate) fn new() -> Self {+ Self::default()+ }+}++#[async_trait]+impl Middleware<(), OpenHumanRunContext> for ResearchBudgetMiddleware {+ fn name(&self) -> &str {+ "research_budget"+ }++ async fn after_tool(+ &self,+ _ctx: &mut RunContext<OpenHumanRunContext>,+ _state: &(),+ invocation: &ToolInvocationIdentity,+ _result: &mut ToolResult,+ ) -> TaResult<()> {+ if matches!(invocation.tool_name(), "web_search_tool" | "web_fetch") {+ self.completed_reads.fetch_add(1, Ordering::Relaxed);+ }+ Ok(())+ }++ async fn before_model(+ &self,+ _ctx: &mut RunContext<OpenHumanRunContext>,+ _state: &(),+ request: &mut ModelRequest,+ ) -> TaResult<()> {+ if self.completed_reads.load(Ordering::Relaxed) < DIRECT_WEB_READ_LIMIT {+ return Ok(());+ }+ tracing::info!(+ web_reads = self.completed_reads.load(Ordering::Relaxed),+ "[tinyagents::mw] direct web research budget reached; concluding turn"+ );+ request.tools.clear();+ request.tool_choice = ToolChoice::None;+ request+ .messages+ .push(Message::user(RESEARCH_CLOSE_INSTRUCTION.to_string()));+ Ok(())+ }+}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/stream_stall.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/stream_stall.rsnew file mode 100644index 0000000000..ba9cdba1c1--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/stream_stall.rs@@ -0,0 +1,56 @@+//! Abort a provider stream whose visible text has become repetitive narration.++use std::sync::Mutex;++use async_trait::async_trait;+use tinyagents_harness::context::RunContext;+use tinyagents_harness::error::{Result as TaResult, TinyAgentsError};+use tinyagents_harness::middleware::Middleware;+use tinyagents_harness::no_progress::StreamTextStallDetector;+use tinyinference_llm::model::ModelDelta;++use crate::agent::tinyagents::host::OpenHumanRunContext;++pub(crate) const STREAM_STALL_ERROR: &str = "streamed response stalled on repeated narration";++#[derive(Default)]+pub(crate) struct StreamStallMiddleware {+ current: Mutex<(String, StreamTextStallDetector)>,+}++impl StreamStallMiddleware {+ pub(crate) fn new() -> Self {+ Self::default()+ }+}++#[async_trait]+impl Middleware<(), OpenHumanRunContext> for StreamStallMiddleware {+ fn name(&self) -> &str {+ "stream_stall"+ }++ async fn on_model_delta(+ &self,+ _ctx: &mut RunContext<OpenHumanRunContext>,+ _state: &(),+ delta: &mut ModelDelta,+ ) -> TaResult<()> {+ let Ok(mut current) = self.current.lock() else {+ return Ok(());+ };+ if current.0 != delta.call_id {+ current.0.clone_from(&delta.call_id);+ current.1.reset();+ }+ if delta.tool_call.is_some() {+ current.1.reset();+ return Ok(());+ }+ if current.1.observe(&delta.content) {+ tracing::warn!("[tinyagents::mw] stopped a repetitive model text stream");+ return Err(TinyAgentsError::Middleware(STREAM_STALL_ERROR.to_string()));+ }+ Ok(())+ }+}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_research_budget_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_research_budget_tests.rsnew file mode 100644index 0000000000..75fd328ebf--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_research_budget_tests.rs@@ -0,0 +1,70 @@+use super::*;++fn research_request() -> ModelRequest {+ ModelRequest {+ tools: vec![ToolSchema::new("web_search_tool", "search", json!({}))],+ ..ModelRequest::new(vec![TaMessage::user(+ "Find more information about Jev from TypeSafe".to_string(),+ )])+ }+}++#[tokio::test]+async fn web_research_concludes_after_eight_reads() {+ let mw = ResearchBudgetMiddleware::new();+ let mut run = ctx();+ for i in 0..7 {+ let name = if i % 2 == 0 {+ "web_search_tool"+ } else {+ "web_fetch"+ };+ mw.after_tool(+ &mut run,+ &(),+ &invocation(format!("web-{i}"), name),+ &mut tool_result(name, "Jev is TypeSafe's System One model"),+ )+ .await+ .unwrap();+ }+ let mut request = research_request();+ mw.before_model(&mut run, &(), &mut request).await.unwrap();+ assert_eq!(request.tools.len(), 1);++ mw.after_tool(+ &mut run,+ &(),+ &invocation("web-7", "web_fetch"),+ &mut tool_result("web_fetch", "TypeSafe's announcement"),+ )+ .await+ .unwrap();+ let mut request = research_request();+ mw.before_model(&mut run, &(), &mut request).await.unwrap();+ assert!(request.tools.is_empty());+ assert_eq!(+ request.tool_choice,+ tinyinference_llm::model::ToolChoice::None+ );+ assert!(request.messages.last().unwrap().text().contains("Answer"));+}++#[tokio::test]+async fn unrelated_tools_do_not_spend_the_web_research_budget() {+ let mw = ResearchBudgetMiddleware::new();+ let mut run = ctx();+ for i in 0..10 {+ mw.after_tool(+ &mut run,+ &(),+ &invocation(format!("file-{i}"), "file_read"),+ &mut tool_result("file_read", "content"),+ )+ .await+ .unwrap();+ }+ let mut request = research_request();+ mw.before_model(&mut run, &(), &mut request).await.unwrap();+ assert_eq!(request.tools.len(), 1);+}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_stream_stall_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_stream_stall_tests.rsnew file mode 100644index 0000000000..c660d4b560--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_stream_stall_tests.rs@@ -0,0 +1,63 @@+use super::*;++#[tokio::test]+async fn repetitive_stream_is_stopped_before_it_reaches_the_ui_indefinitely() {+ let mw = StreamStallMiddleware::new();+ let mut run = ctx();+ let mut stopped = false;+ for i in 0..12 {+ let mut delta = tinyinference_llm::model::ModelDelta {+ call_id: "jev-research".to_string(),+ content: format!("Let me check another page number {i} before answering the user. "),+ reasoning: String::new(),+ tool_call: None,+ };+ if mw.on_model_delta(&mut run, &(), &mut delta).await.is_err() {+ stopped = true;+ break;+ }+ }+ assert!(stopped);+}++#[tokio::test]+async fn tool_progress_and_a_new_model_call_start_fresh_windows() {+ let mw = StreamStallMiddleware::new();+ let mut run = ctx();+ for call_id in ["first-call", "second-call"] {+ for i in 0..7 {+ let mut delta = tinyinference_llm::model::ModelDelta {+ call_id: call_id.to_string(),+ content: format!(+ "Let me check source number {i} before answering the user's request. "+ ),+ reasoning: String::new(),+ tool_call: None,+ };+ mw.on_model_delta(&mut run, &(), &mut delta).await.unwrap();+ }+ }+ let mut tool_delta = tinyinference_llm::model::ModelDelta {+ call_id: "second-call".to_string(),+ content: String::new(),+ reasoning: String::new(),+ tool_call: Some(tinyinference_llm::tool::ToolDelta {+ call_id: "fetch-1".to_string(),+ content: String::new(),+ tool_name: Some("web_fetch".to_string()),+ content_index: None,+ }),+ };+ mw.on_model_delta(&mut run, &(), &mut tool_delta)+ .await+ .unwrap();+ for i in 0..7 {+ let mut delta = tinyinference_llm::model::ModelDelta {+ call_id: "second-call".to_string(),+ content: format!("Let me inspect result number {i} before answering the user. "),+ reasoning: String::new(),+ tool_call: None,+ };+ mw.on_model_delta(&mut run, &(), &mut delta).await.unwrap();+ }+}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rsindex 2126897d5d..d6c830960d 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs@@ -486,6 +486,12 @@ mod loop_guard_tests;mod prompt_cache_tests;#[path = "middleware_repeat_progress_tests.rs"]mod repeat_progress_tests;++#[path = "middleware_research_budget_tests.rs"]+mod research_budget_tests;++#[path = "middleware_stream_stall_tests.rs"]+mod stream_stall_tests;#[path = "middleware_tool_output_artifact_tests.rs"]mod tool_output_artifact_tests;#[path = "middleware_tool_output_tests.rs"]diff --git a/vendor/tinyagents b/vendor/tinyagentsindex 19cafdace8..cbc857b69a 160000--- a/vendor/tinyagents+++ b/vendor/tinyagents@@ -1 +1 @@-Subproject commit 19cafdace8fc87a1015f49198984fd1e4c66ddae+Subproject commit cbc857b69a23c7bbc2df01544e42b71f0c61e537