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
chore: remove unused handoff and extract tool modules
Steven Enamakeld22cf46ef095
diff --git a/crates/openhuman-core/src/agent/subagent_host/extract_tool.rs b/crates/openhuman-core/src/agent/subagent_host/extract_tool.rsdeleted file mode 100644index a0969ec131..0000000000--- a/crates/openhuman-core/src/agent/subagent_host/extract_tool.rs+++ /dev/null@@ -1,645 +0,0 @@-//! `extract_from_result` — a sub-agent-side tool that answers a targeted-//! query against a payload previously stashed by the handoff cache (see-//! [`super::handoff`]).-//!-//! This used to dispatch the `summarizer` archetype as a full sub-agent.-//! That dragged along system-prompt scaffolding, a tool-loop, and an-//! extra inference round for a workload that really only needs one-//! completion call. So the tool now drives `provider.chat_with_system`-//! directly. Both the provider AND the model id are resolved by the runner-//! through the `summarization` role (`create_chat_provider("summarization")`)-//! and handed in, so this extraction follows the user's `memory_provider`-//! routing — managed (`hint:summarization`), BYOK, or local — exactly like every-//! other summarization path, instead of borrowing the parent agent's provider-//! with a hardcoded tier string (which 400'd on BYOK/local providers that don't-//! know the literal `hint:summarization`).-//!-//! Transcript discipline: the LLM call still costs tokens, so every-//! extraction round-trip is persisted as its own `session_raw/` JSONL (+-//! companion `.md`) under the parent's session chain. Single-shot calls-//! produce one file; chunked calls produce one file per chunk sharing a-//! common `call_seq`. Transcript failures are warnings — they never-//! block the tool result.--use std::path::{Path, PathBuf};-use std::sync::{Arc, Mutex as StdMutex};--use async_trait::async_trait;-use serde_json::{json, Value};-use tinyagents_graph::parallel::{map_reduce, FailurePolicy, ParallelOptions};--use super::handoff::{chunk_content, ResultHandoffCache, HANDOFF_MAX_ENTRIES};-use crate::agent::messages::{transcript_message_from_chat, ChatMessage};-use crate::agent::tinyagents::TurnModelSource;-use tinyagents_session::transcript::{- resolve_keyed_transcript_path, write_transcript, MessageUsage, TranscriptMeta, TurnUsage,-};-use tinyinference_llm::message::Message;-use tinyinference_llm::model::ModelRequest;-use tinytools::{Tool, ToolCallOptions, ToolCategory, ToolResult, ToolRunContext};--// ── Tunables ──────────────────────────────────────────────────────────--/// Temperature for extraction calls. Low but non-zero so the model can-/// pick reasonable phrasings when rewriting identifiers into a compact-/// answer, without straying into creative territory.-const EXTRACT_TEMPERATURE: f64 = 0.2;--/// Convert a context window (tokens) into the per-chunk char budget. A payload-/// at or under this budget is extracted in a single shot over its **entire**-/// content — higher quality than the chunk+concat fallback, which has no reduce-/// stage and can miss facts that span a chunk boundary. Headroom is reserved for-/// the extraction contract, the query, and the response.-///-/// `window_tokens = None` means neither the provider nor the static registry-/// could size the model — only reached for **cloud** models the registry doesn't-/// know (an unknown *local* model resolves to its small provider-profile window-/// via [`ExtractFromResultTool::extract_chunk_char_budget`], not here), so a-/// large window is a safe assumption.-fn chunk_char_budget_for_window(window_tokens: Option<u64>) -> usize {- /// Last-resort window (tokens) when the model is unsizable — see above.- const FALLBACK_WINDOW_TOKENS: u64 = 128_000;- /// Approximate chars per token used for budgeting.- const CHARS_PER_TOKEN: u64 = 4;- /// Fraction of the window spent on the payload slice; the remainder covers- /// the prompt scaffolding, query, and model response.- const USABLE_PCT: u64 = 70;-- let window = window_tokens.unwrap_or(FALLBACK_WINDOW_TOKENS);- (window * USABLE_PCT / 100 * CHARS_PER_TOKEN) as usize-}--/// System prompt fed to the provider on every `extract_from_result`-/// call. Lifted in spirit from the old `summarizer` agent's prompt but-/// trimmed to the core extraction contract — no fluff about iteration-/// budgets or sub-agent roles because this is a pure tool call.-const EXTRACT_SYSTEM_PROMPT: &str = "\-You are an extraction assistant. A larger tool output is provided below. \-Return ONLY the specific facts the user's query asks for. \-Preserve identifiers verbatim (ids, urls, emails, timestamps, prices). \-Be compact: no preamble, no commentary, no apologies, no meta-statements. \-If the payload contains nothing relevant to the query, reply with an \-empty string — do not invent information.";--// ── Tool impl ─────────────────────────────────────────────────────────--/// The `extract_from_result` tool registered into the sub-agent's tool-/// surface when a handoff cache is active (currently: integrations_agent-/// with a toolkit scope).-pub(super) struct ExtractFromResultTool {- cache: Arc<ResultHandoffCache>,- /// The turn's model source (issue #4249, Phase 3 / Motion A): the tool builds- /// a summarizer crate `ChatModel` from it per call and queries the model's- /// context window through it, so it no longer names the `Provider` trait.- source: TurnModelSource,- /// Model id for the extraction summary calls. Resolved by the- /// runner through the `summarization` role (alongside `provider`), so it- /// tracks the user's `memory_provider` routing + `cloud_llm_model` override- /// instead of a hardcoded tier string.- model: String,- /// Workspace root for transcript writes.- workspace_dir: PathBuf,- /// Parent session chain joined with `__`, e.g.- /// `"1700000000_orchestrator__1700000005_1234_integrations_agent_abc"`.- /// Extract-call transcripts append a unique per-call suffix to this.- parent_chain: String,- /// Logical agent id that owns the calls (e.g. `"integrations_agent"`).- /// Only used to compose a descriptive `agent_name` in transcript meta.- owner_agent_id: String,- /// Monotonic counter so repeated calls within the same millisecond- /// still land on distinct transcript files.- call_seq: StdMutex<u64>,-}--impl ExtractFromResultTool {- pub(super) fn new(- cache: Arc<ResultHandoffCache>,- source: TurnModelSource,- model: String,- workspace_dir: PathBuf,- parent_chain: String,- owner_agent_id: String,- ) -> Self {- Self {- cache,- source,- model,- workspace_dir,- parent_chain,- owner_agent_id,- call_seq: StdMutex::new(0),- }- }-- /// Resolve the per-chunk char budget for `self.model` against the chosen- /// provider's context window.- ///- /// Asks the **provider** first: a local runtime (Ollama / LM Studio) reports- /// its real loaded / profile window here (~8k tokens for Ollama), so an- /// unknown *local* model is budgeted against its actual small context and the- /// payload is chunked — instead of assuming a 128k window and sending an- /// oversized single-shot prompt that overflows the local context (Codex P2).- /// Falls back to the static registry, then the cloud-safe default in- /// [`chunk_char_budget_for_window`].- async fn extract_chunk_char_budget(&self) -> usize {- let window = self- .source- .effective_context_window(&self.model)- .await- .or_else(|| crate::inference::context_window_for_model(&self.model));- chunk_char_budget_for_window(window)- }-- fn next_call_seq(&self) -> u64 {- let mut guard = self- .call_seq- .lock()- .expect("extract_from_result call_seq mutex poisoned");- *guard = guard.saturating_add(1);- *guard- }-}--#[async_trait]-impl Tool for ExtractFromResultTool {- fn name(&self) -> &str {- "extract_from_result"- }-- fn description(&self) -> &str {- "Answer a targeted question against an oversized tool output that was \- stashed under a `result_id` handle. Use this when a previous tool call \- returned a placeholder like `result_id=\"res_1\"` because its raw output \- was too large to show inline. Pass the handle plus a natural-language \- `query` naming the exact facts/identifiers you need; returns only the \- extracted answer, not the full payload. Multiple queries against the \- same `result_id` are allowed — each one is independent."- }-- fn parameters_schema(&self) -> Value {- json!({- "type": "object",- "properties": {- "result_id": {- "type": "string",- "description": "The handle emitted in the oversized tool output placeholder (e.g. `res_1`)."- },- "query": {- "type": "string",- "description": "Natural-language question naming the exact facts or identifiers to extract. Be specific."- }- },- "required": ["result_id", "query"]- })- }-- fn category(&self) -> ToolCategory {- ToolCategory::System- }-- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- self.execute_inner(args, None).await- }-- async fn execute_with_context(- &self,- args: Value,- _options: ToolCallOptions,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- self.execute_inner(args, context.and_then(ToolRunContext::thread_id))- .await- }-}--impl ExtractFromResultTool {- async fn execute_inner(- &self,- args: Value,- thread_id: Option<&str>,- ) -> anyhow::Result<ToolResult> {- let thread_id = thread_id.map(str::to_owned);- let result_id = args.get("result_id").and_then(|v| v.as_str()).unwrap_or("");- let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");-- if result_id.is_empty() || query.is_empty() {- return Ok(ToolResult::error(- "extract_from_result requires non-empty `result_id` and `query`.",- ));- }-- let cached = match self.cache.get(result_id) {- Some(c) => c,- None => {- return Ok(ToolResult::error(format!(- "No cached result found for id '{result_id}'. The handle may have been evicted (cache holds the {HANDOFF_MAX_ENTRIES} most recent entries). Re-run the original tool to get a fresh handle."- )));- }- };-- // Allow test harnesses to lower the chunk budget so multi-chunk- // extraction can be exercised on compacted payloads. Never consulted- // in production (env var absent).- let effective_chunk_budget = match std::env::var("OPENHUMAN_TEST_EXTRACT_CHUNK_BUDGET")- .ok()- .and_then(|v| v.parse::<usize>().ok())- {- Some(budget) => budget,- None => self.extract_chunk_char_budget().await,- };-- // Fast path: payload fits in a single provider turn.- if cached.content.len() <= effective_chunk_budget {- tracing::debug!(- tool = %cached.tool_name,- bytes = cached.content.len(),- "[extract_from_result] single-shot extraction"- );- return self- .extract_single_shot(- &cached.tool_name,- &cached.content,- query,- thread_id.as_deref(),- )- .await;- }-- // Slow path: chunk + parallel map. A single call on a payload- // large enough to need the handoff (hundreds of KB common for- // Gmail / Notion list operations) risks either (a) overflowing- // the extraction model's context window, or (b) a low-quality- // single-pass answer that misses facts near the tail. Splitting- // into budgeted chunks and running them in parallel keeps each- // call under its context budget and usually finishes faster- // than a sequential single-shot call on the whole blob.- //- // No reduce stage: per-chunk extracts are concatenated in- // original chunk order. A reduce LLM call adds latency (often- // the slowest single turn) and becomes a single point of- // failure when the upstream provider stalls. For- // listing/extraction queries concatenation is equivalent; for- // top-N / global-ordering queries the caller can post-process.- let chunks = chunk_content(&cached.content, effective_chunk_budget);- tracing::info!(- tool = %cached.tool_name,- total_bytes = cached.content.len(),- chunk_count = chunks.len(),- chunk_budget = effective_chunk_budget,- "[extract_from_result] chunked extraction"- );-- // Map stage: each chunk extracts items matching `query` from- // ITS OWN slice only. Dispatched through the shared bounded fan-out- // (`tinyagents_graph::parallel::map_reduce`), which keeps at most- // `MAP_CONCURRENCY` calls in flight and hands results back in input- // order. Fully parallel `join_all` was generating 504-gateway-timeout- // storms from the staging proxy when 7+ concurrent calls piled onto the- // upstream; batching at 3 trades some wall-clock time for reliability.- const MAP_CONCURRENCY: usize = 3;- let total_chunks = chunks.len();-- // Each chunk gets its own monotonic call_seq so sibling- // transcripts written in parallel still land on distinct files.- let call_seq_base = self.next_call_seq();- let workspace_dir = self.workspace_dir.clone();- let parent_chain = self.parent_chain.clone();- let owner_agent_id = self.owner_agent_id.clone();- // One summarizer model for the whole chunk fan-out; each concurrent- // future clones the Arc (issue #4249, Phase 3 / Motion A). Model +- // temperature are baked into the model, so the per-call request only- // carries the messages.- let chat =- self.source- .build_summarizer(&self.model, EXTRACT_TEMPERATURE, thread_id.as_deref())?;- // Model id for the per-chunk transcript metadata (the chat call itself- // bakes it into `chat`).- let model = self.model.clone();-- // Each chunk's future owns its `String`: the fan-out polls lazily and- // needs futures with no borrows into the enclosing scope.- let extract_chunk = move |i: usize, chunk: String| {- let chat = chat.clone();- let tool_name = cached.tool_name.clone();- let query = query.to_string();- let workspace_dir = workspace_dir.clone();- let parent_chain = parent_chain.clone();- let owner_agent_id = owner_agent_id.clone();- let model = model.clone();- let thread_id = thread_id.clone();- async move {- let user_prompt = format!(- "Tool name: {tool_name}\nChunk {idx} of {total}\n\n\- Query: {query}\n\n\- This is one slice of a larger tool output. Extract ONLY \- items in THIS slice that match the query. Preserve \- identifiers verbatim. Return an empty string if nothing \- in this slice is relevant.\n\n\- --- BEGIN SLICE ---\n{chunk}\n--- END SLICE ---",- idx = i + 1,- total = total_chunks,- );- let result = chat- .invoke(- &(),- ModelRequest::new(vec![- Message::system(EXTRACT_SYSTEM_PROMPT.to_string()),- Message::user(user_prompt.clone()),- ]),- )- .await- .map(|r| r.text())- .map_err(|e| anyhow::anyhow!(e.to_string()));-- // Persist this chunk's transcript before returning, so- // a partial failure higher up the stream still leaves- // an auditable record on disk.- let transcript_input: Result<&str, String> = match &result {- Ok(text) => Ok(text.as_str()),- Err(e) => Err(e.to_string()),- };- let chunk_label = format!("chunk{:03}of{:03}", i + 1, total_chunks);- write_extract_transcript(- &workspace_dir,- &parent_chain,- &owner_agent_id,- call_seq_base,- Some(&chunk_label),- EXTRACT_SYSTEM_PROMPT,- &user_prompt,- match &transcript_input {- Ok(s) => Ok(*s),- Err(s) => Err(s.as_str()),- },- &model,- thread_id.as_deref(),- );-- // The per-chunk result is the fan-out's *item*, not its error:- // a failed chunk is dropped below with a warning, and must not- // abort its siblings.- Ok(result)- }- };-- // `map_reduce` returns outcomes in input order, so the concatenated- // output keeps the natural ordering of the underlying tool result- // (e.g. Notion's reverse-chrono page list) with no re-sort here.- let outcome = map_reduce(- chunks,- ParallelOptions::default()- .with_max_concurrency(MAP_CONCURRENCY)- .with_failure_policy(FailurePolicy::BestEffort),- extract_chunk,- )- .await- .map_err(|e| anyhow::anyhow!(e.to_string()))?;-- let partials: Vec<String> = outcome- .outcomes- .into_iter()- .filter_map(|item| {- let i = item.index;- // `BestEffort` never fails an item at the fan-out level; the- // inner `Result` is the provider call's own outcome.- let r = item.result.unwrap_or_else(|e| Err(anyhow::anyhow!(e)));- match r {- Ok(text) => {- let trimmed = text.trim();- if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- }- }- Err(e) => {- tracing::warn!(- chunk_idx = i,- error = %e,- "[extract_from_result] map-stage provider call failed; dropping partial"- );- None- }- }- })- .collect();-- if partials.is_empty() {- tracing::debug!(- "[extract_from_result] no matching content found across any chunk; returning empty extraction"- );- return Ok(ToolResult::success(String::new()));- }-- // Concatenate per-chunk summaries in original chunk order.- // `join` with a single partial yields it unchanged (no trailing- // separator), so no special-case is needed.- Ok(ToolResult::success(partials.join("\n\n---\n\n")))- }-}--impl ExtractFromResultTool {- async fn extract_single_shot(- &self,- tool_name: &str,- content: &str,- query: &str,- thread_id: Option<&str>,- ) -> anyhow::Result<ToolResult> {- let user_prompt = format!(- "Tool name: {tool_name}\n\nQuery: {query}\n\n\- Raw tool output follows. Extract ONLY the information the query \- asks for.\n\n\- --- BEGIN ---\n{content}\n--- END ---",- );-- let call_seq = self.next_call_seq();- let provider_result = self- .source- .build_summarizer(&self.model, EXTRACT_TEMPERATURE, thread_id)?- .invoke(- &(),- ModelRequest::new(vec![- Message::system(EXTRACT_SYSTEM_PROMPT.to_string()),- Message::user(user_prompt.clone()),- ]),- )- .await- .map(|r| r.text())- .map_err(|e| anyhow::anyhow!(e.to_string()));-- // Persist the transcript before returning — the LLM call cost- // tokens regardless of whether we ultimately return success.- let transcript_input: Result<&str, String> = match &provider_result {- Ok(text) => Ok(text.as_str()),- Err(e) => Err(e.to_string()),- };- write_extract_transcript(- &self.workspace_dir,- &self.parent_chain,- &self.owner_agent_id,- call_seq,- None,- EXTRACT_SYSTEM_PROMPT,- &user_prompt,- match &transcript_input {- Ok(s) => Ok(*s),- Err(s) => Err(s.as_str()),- },- &self.model,- thread_id,- );-- match provider_result {- Ok(text) => {- let trimmed = text.trim();- if trimmed.is_empty() {- tracing::debug!(- "[extract_from_result] provider returned an empty response; returning empty extraction"- );- Ok(ToolResult::success(String::new()))- } else {- Ok(ToolResult::success(trimmed.to_string()))- }- }- Err(e) => Ok(ToolResult::error(format!(- "extract_from_result: provider call failed: {e}"- ))),- }- }-}--// ── Transcript writer ─────────────────────────────────────────────────--/// Persist a single extract-from-result LLM round-trip as its own-/// transcript file under `session_raw/DDMMYYYY/{stem}.jsonl` (+ `.md`).-///-/// Best-effort: transcript failures are logged and swallowed so a-/// readable-log hiccup never blocks the extraction itself. Appends a-/// short suffix to the parent chain so every call lands on a distinct-/// file (sibling extract calls within the same tool invocation still-/// get unique stems).-fn write_extract_transcript(- workspace_dir: &Path,- parent_chain: &str,- owner_agent_id: &str,- call_seq: u64,- chunk_label: Option<&str>,- system_prompt: &str,- user_prompt: &str,- assistant_output: Result<&str, &str>,- model: &str,- thread_id: Option<&str>,-) {- let now = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default();- let unix_ts = now.as_secs();- let nanos = now.subsec_nanos();- let chunk_tag = match chunk_label {- Some(label) => format!("_{label}"),- None => String::new(),- };- let stem = format!("{parent_chain}__extract_{unix_ts}_{nanos:09}_{call_seq:04}{chunk_tag}");-- let path = match resolve_keyed_transcript_path(workspace_dir, &stem) {- Ok(p) => p,- Err(e) => {- tracing::warn!(- error = %e,- stem = %stem,- "[extract_from_result] could not resolve transcript path; skipping transcript"- );- return;- }- };-- let (assistant_text, is_error) = match assistant_output {- Ok(text) => (text.to_string(), false),- Err(err) => (format!("[error] {err}"), true),- };-- let messages = [- ChatMessage {- id: None,- role: "system".into(),- content: system_prompt.to_string(),- extra_metadata: None,- cache_breakpoints: Vec::new(),- },- ChatMessage {- id: None,- role: "user".into(),- content: user_prompt.to_string(),- extra_metadata: None,- cache_breakpoints: Vec::new(),- },- ChatMessage {- id: None,- role: "assistant".into(),- content: assistant_text,- extra_metadata: None,- cache_breakpoints: Vec::new(),- },- ];-- // Token counts aren't surfaced by `chat_with_system`; leave cost /- // usage fields zeroed and let the backend's own telemetry fill in- // the blanks when we wire richer accounting later.- let ts_rfc3339 = chrono::Utc::now().to_rfc3339();- let turn_usage = TurnUsage {- provider: "extract_from_result".to_string(),- model: model.to_string(),- usage: MessageUsage {- input: 0,- output: 0,- cached_input: 0,- context_window: 0,- cost_usd: 0.0,- },- ts: ts_rfc3339.clone(),- reasoning_content: None,- tool_calls: Vec::new(),- iteration: 1,- };-- let meta = TranscriptMeta {- session_id: None,- parent_session_id: None,- agent_name: format!("{owner_agent_id}::extract_from_result"),- agent_id: Some(owner_agent_id.to_string()),- agent_type: Some("extractor".to_string()),- dispatcher: "native".into(),- provider: Some(turn_usage.provider.clone()),- model: Some(turn_usage.model.clone()),- created: ts_rfc3339.clone(),- updated: ts_rfc3339,- turn_count: 1,- prefix_message_count: None,- input_tokens: 0,- output_tokens: 0,- cached_input_tokens: 0,- charged_amount_usd: 0.0,- thread_id: thread_id.map(str::to_owned),- task_id: None,- };-- let durable_messages: Vec<_> = messages.iter().map(transcript_message_from_chat).collect();- if let Err(e) = write_transcript(&path, &durable_messages, &meta, Some(&turn_usage)) {- tracing::warn!(- error = %e,- path = %path.display(),- "[extract_from_result] transcript write failed"- );- } else {- tracing::debug!(- path = %path.display(),- is_error,- "[extract_from_result] transcript written"- );- }-}--#[cfg(test)]-#[path = "extract_tool_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/subagent_host/extract_tool_tests.rs b/crates/openhuman-core/src/agent/subagent_host/extract_tool_tests.rsdeleted file mode 100644index ef9e4a6b5f..0000000000--- a/crates/openhuman-core/src/agent/subagent_host/extract_tool_tests.rs+++ /dev/null@@ -1,38 +0,0 @@-use super::*;--// The chunk budget tracks the resolved context window, so a small local-// window yields a much smaller budget than a long-context cloud tier — this-// is what forces chunking instead of an oversized single-shot prompt.-#[test]-fn chunk_budget_tracks_context_window() {- let summarization_window = crate::inference::context_window_for_model("summarization-v1");- let big = chunk_char_budget_for_window(summarization_window);- let small = chunk_char_budget_for_window(Some(8_192)); // Ollama local default- assert!(- big > small,- "long-context tier budget {big} must exceed an 8k local window budget {small}"- );-}--// Codex P2: an unknown LOCAL model resolves (via the provider) to its small-// ~8k profile window, NOT the 128k cloud fallback. The resulting budget must-// be well under a production handoff payload (~200k chars) so it chunks-// instead of single-shotting into a local context overflow.-#[test]-fn chunk_budget_for_small_local_window_forces_chunking() {- let budget = chunk_char_budget_for_window(Some(8_192));- // 8192 * 70% * 4 = 22_937 chars.- assert_eq!(budget, (8_192u64 * 70 / 100 * 4) as usize);- assert!(- budget < 200_000,- "an 8k local window must budget below a typical handoff payload so it chunks"- );-}--// When neither provider nor registry can size the model (cloud-unknown), the-// cloud-safe 128k fallback applies.-#[test]-fn chunk_budget_uses_cloud_fallback_when_unsizable() {- let expected = (128_000u64 * 70 / 100 * 4) as usize;- assert_eq!(chunk_char_budget_for_window(None), expected);-}diff --git a/crates/openhuman-core/src/agent/subagent_host/handoff.rs b/crates/openhuman-core/src/agent/subagent_host/handoff.rsdeleted file mode 100644index 5ce96fca04..0000000000--- a/crates/openhuman-core/src/agent/subagent_host/handoff.rs+++ /dev/null@@ -1,71 +0,0 @@-//! Progressive-disclosure handoff cache for oversized tool results.-//!-//! ## Where the implementation lives-//!-//! The cache, placeholder renderer, and content-hygiene helpers are-//! **TinyAgents'** ([`tinyagents_harness::handoff`]): host-agnostic and-//! re-exported here under their historical OpenHuman names so call sites-//! and the RPC/tool surface are unchanged. See that module's docs for the-//! full picture — typed sub-agents (integrations_agent in particular)-//! regularly call tools that return megabyte-scale payloads-//! (`GMAIL_LIST_MESSAGES`, `NOTION_GET_PAGE`, `GOOGLEDRIVE_LIST_FILES`);-//! progressive disclosure stashes the full payload, replaces it in history-//! with a short placeholder (size + preview + `result_id` + how to query-//! it), and exposes an `extract_from_result` tool (see-//! [`super::extract_tool`]) that the sub-agent can call with a targeted-//! query.-//!-//! ## What stays here-//!-//! Resolving the effective oversize threshold is host policy: the crate-//! takes `threshold_tokens` as an explicit parameter (it deliberately-//! dropped an environment-variable backdoor), and this host still needs-//! that backdoor for its own test harnesses —-//! `OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS` lets a test lower the-//! threshold so the handoff path can be exercised on payloads that survive-//! tokenjuice's compaction cap (see e.g.-//! `tests/raw_coverage/agent_large_round25_raw_coverage_e2e.rs`). Never-//! consulted in production (the env var is absent) so there is zero-//! runtime cost.--// `CachedResult`, `HANDOFF_PREVIEW_CHARS`, `build_handoff_placeholder` and-// `clean_tool_output` have no current OpenHuman call site (the crate now-// owns the only callers, inside `apply_handoff`/`build_handoff_placeholder`-// itself) but are kept re-exported here for surface parity with the-// pre-migration module and in case a future caller needs them directly.-#[allow(unused_imports)]-pub(crate) use tinyagents_harness::handoff::{- build_handoff_placeholder, chunk_content, clean_tool_output, CachedResult, ResultHandoffCache,- HANDOFF_MAX_ENTRIES, HANDOFF_OVERSIZE_THRESHOLD_TOKENS, HANDOFF_PREVIEW_CHARS,-};--/// Apply the progressive-disclosure handoff to a tool result. Resolves the-/// effective oversize threshold from `OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS`-/// when set, falling back to [`HANDOFF_OVERSIZE_THRESHOLD_TOKENS`] otherwise,-/// then delegates the cache/placeholder logic to-/// [`tinyagents_harness::handoff::apply_handoff`].-pub(crate) fn apply_handoff(- cache: &ResultHandoffCache,- tool_name: &str,- task_id: &str,- agent_id: &str,- result_text: String,-) -> String {- let effective_threshold = std::env::var("OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS")- .ok()- .and_then(|v| v.parse::<usize>().ok())- .unwrap_or(HANDOFF_OVERSIZE_THRESHOLD_TOKENS);- tinyagents_harness::handoff::apply_handoff(- cache,- &tinyagents_harness::handoff::HandoffConfig::default(),- tool_name,- task_id,- agent_id,- result_text,- effective_threshold,- )-}--#[cfg(test)]-#[path = "handoff_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/subagent_host/handoff_tests.rs b/crates/openhuman-core/src/agent/subagent_host/handoff_tests.rsdeleted file mode 100644index ac2e17d16a..0000000000--- a/crates/openhuman-core/src/agent/subagent_host/handoff_tests.rs+++ /dev/null@@ -1,84 +0,0 @@-use super::*;-use std::sync::{Mutex, OnceLock};--/// `OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS` is process-global and this-/// suite runs ~11.6k tests in one process, so serialize the two tests in-/// this module that touch it and restore the prior value on drop.-fn env_lock() -> std::sync::MutexGuard<'static, ()> {- static LOCK: OnceLock<Mutex<()>> = OnceLock::new();- LOCK.get_or_init(|| Mutex::new(()))- .lock()- .unwrap_or_else(|e| e.into_inner())-}--struct EnvGuard {- key: &'static str,- prev: Option<String>,-}--impl EnvGuard {- fn set(key: &'static str, val: &str) -> Self {- let prev = std::env::var(key).ok();- // SAFETY: caller holds `env_lock()` for the duration of the test.- unsafe { std::env::set_var(key, val) };- Self { key, prev }- }-- fn remove(key: &'static str) -> Self {- let prev = std::env::var(key).ok();- // SAFETY: caller holds `env_lock()` for the duration of the test.- unsafe { std::env::remove_var(key) };- Self { key, prev }- }-}--impl Drop for EnvGuard {- fn drop(&mut self) {- match &self.prev {- // SAFETY: caller holds `env_lock()` for the duration of the test.- Some(val) => unsafe { std::env::set_var(self.key, val) },- None => unsafe { std::env::remove_var(self.key) },- }- }-}--#[test]-fn apply_handoff_uses_the_test_env_threshold_when_set() {- let _guard = env_lock();- let _env = EnvGuard::set("OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS", "5");- let cache = ResultHandoffCache::new();-- // 40 bytes / 4 => 10 estimated tokens, comfortably above the- // env-lowered threshold of 5 but nowhere near the real default of- // 50_000 — this only exercises the handoff path because the env var- // was actually read and honoured.- let oversized = "x".repeat(40);- let out = apply_handoff(&cache, "some_tool", "task-1", "agent-1", oversized.clone());-- assert_ne!(- out, oversized,- "result above the env-lowered threshold should be replaced with a placeholder"- );- assert!(- out.contains("result_id"),- "placeholder should mention how to retrieve the cached result: {out}"- );-}--#[test]-fn apply_handoff_falls_back_to_the_default_threshold_when_env_unset() {- let _guard = env_lock();- let _env = EnvGuard::remove("OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS");- let cache = ResultHandoffCache::new();-- // Comfortably below HANDOFF_OVERSIZE_THRESHOLD_TOKENS (50_000 tokens- // / 200_000 bytes), so with the env var unset (falling back to the- // real default) the text passes through unchanged.- let small = "hello world".to_string();- let out = apply_handoff(&cache, "some_tool", "task-1", "agent-1", small.clone());-- assert_eq!(- out, small,- "a small result under the default threshold must pass through unchanged"- );-}diff --git a/crates/openhuman-core/src/agent/subagent_host/mod.rs b/crates/openhuman-core/src/agent/subagent_host/mod.rsindex bdefb04b74..c35a482538 100644--- a/crates/openhuman-core/src/agent/subagent_host/mod.rs+++ b/crates/openhuman-core/src/agent/subagent_host/mod.rs@@ -33,13 +33,9 @@//! | ----------------- | ----------------------------------------------------------- |//! | `types.rs` | `SubagentRun{Options,Outcome,Error}`, `SubagentMode` |//! | `ops/` | `run_subagent`, typed/fork mode, TinyAgents graph route |-//! | `handoff.rs` | Oversized-tool-result cache + hygiene helpers |-//! | `extract_tool.rs` | `extract_from_result` tool (direct provider extraction) |-//! | `tool_prep.rs` | Tool filtering + prompt loading + text-mode protocol block |+//! | `tool_prep.rs` | Tool filtering + prompt loading + prompt protocol block |mod autonomous;-mod extract_tool;-mod handoff;mod lifecycle;mod ops;mod tool_prep;@@ -68,10 +64,6 @@ pub use types::{SubagentRunStatus, SubagentUsage,};-// Progressive-disclosure handoff: the tinyagents `HandoffMiddleware` intercepts-// oversized sub-agent tool results via `apply_handoff`, sharing the per-spawn-// `ResultHandoffCache` with the `extract_from_result` tool.-pub(crate) use handoff::{apply_handoff, ResultHandoffCache};pub(crate) use ops::run_agent_turn_request_via_default_graph;pub(crate) use ops::{append_subagent_role_contract, resolve_subagent_source};diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner/toolkit_scope_filter.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner/toolkit_scope_filter.rsdeleted file mode 100644index 8e281635ae..0000000000--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner/toolkit_scope_filter.rs+++ /dev/null@@ -1,39 +0,0 @@-//! Re-filtering a cached toolkit action catalogue against the user's-//! *current* per-toolkit scope preference (read/write/admin), used by the-//! typed-mode prompt builder when it reuses a cached connected-integration-//! catalogue instead of re-fetching it.--/// Re-filter `actions` (a cached toolkit action catalogue) against the-/// caller's live per-toolkit scope preference, so a scope change since the-/// catalogue was cached is honored without a re-fetch.-pub(super) async fn filter_cached_toolkit_actions_with_current_scope(- agent_id: &str,- toolkit: &str,- config: &crate::config::Config,- actions: &[crate::agent::prompts::ConnectedIntegrationTool],-) -> Vec<crate::agent::prompts::ConnectedIntegrationTool> {- let pref = crate::integrations::composio::ops::load_user_scope_pref(config, toolkit).await;- let before = actions.len();- let filtered: Vec<_> = actions- .iter()- .filter(|action| {- crate::integrations::composio::providers::is_action_visible_with_pref(- &action.name,- &pref,- )- })- .cloned()- .collect();- tracing::debug!(- agent_id = %agent_id,- toolkit = %toolkit,- cached_actions = before,- visible_actions = filtered.len(),- hidden_actions = before.saturating_sub(filtered.len()),- read = pref.read,- write = pref.write,- admin = pref.admin,- "[subagent_host:typed] re-filtered cached toolkit catalogue with current user scope"- );- filtered-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_artifact_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_artifact_tests.rsindex 6c8b583e35..c37b3d39a6 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_artifact_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_artifact_tests.rs@@ -130,49 +130,3 @@ async fn a_raw_result_file_read_cannot_open_is_stored_as_the_processed_copy() {"a raw body over file_read's limit would be unreadable, so the processed copy is stored");}--/// #6284 review: `HandoffMiddleware` runs before the artifact pager, so it must-/// leave an artifact read alone or the pager only ever sees a handoff pointer.-#[tokio::test]-async fn handoff_leaves_an_artifact_read_for_the_pager_but_still_hands_off_other_results() {- use crate::agent::tinyagents::middleware::turn_context::{HandoffConfig, HandoffMiddleware};- let mw = HandoffMiddleware::new(HandoffConfig {- cache: Arc::new(crate::agent::subagent_host::ResultHandoffCache::new()),- agent_id: "agent-1".to_string(),- task_id: "task-1".to_string(),- });- // ~100k estimated tokens, above the 50k handoff threshold.- let oversized = "y".repeat(400_000);-- let mut ordinary = tool_result("echo", &oversized);- mw.after_tool(- &mut ctx(),- &(),- &invocation("ordinary", "echo"),- &mut ordinary,- )- .await- .unwrap();- assert_ne!(- result_text(&ordinary).len(),- oversized.len(),- "control: an oversized ordinary result is still handed off"- );-- let mut call = TaToolCall::new(- "c1",- "file_read",- json!({"path": "artifacts/tool-results/s/shell/c.txt"}),- );- let mut ctx = ctx();- mw.before_tool(&mut ctx, &(), &mut call).await.unwrap();- let mut read = tool_result("file_read", &oversized);- mw.after_tool(&mut ctx, &(), &invocation("c1", "file_read"), &mut read)- .await- .unwrap();- assert_eq!(- result_text(&read).len(),- oversized.len(),- "an artifact read must reach the artifact pager with its bytes, not a handoff pointer"- );-}