Skip to content

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

refactor(agent): add host subagent runtime

Steven Enamakelf247c10a3820
diff --git a/crates/openhuman-core/src/agent/subagent_host/autonomous.rs b/crates/openhuman-core/src/agent/subagent_host/autonomous.rs
new file mode 100644
index 0000000000..587dc3d23d
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/autonomous.rs
@@ -0,0 +1,56 @@
+//! Autonomous skill-run overrides.
+//!
+//! `skills_run` runs the orchestrator (and any sub-agents it spawns) as an
+//! unattended background tree: it isn't approval-gated (background turns carry
+//! no `APPROVAL_CHAT_CONTEXT`), and the per-agent iteration cap is lifted so the
+//! run continues until it's done or the repeated-failure circuit breaker trips.
+//!
+//! The lifted cap rides a `tokio` task-local set around the orchestrator's
+//! `run_single`. Sub-agent inner loops are awaited *inline* within that scope
+//! (`run_subagent` does not detach), so the task-local reaches them too — one
+//! switch covers the whole tree.
+
+use std::future::Future;
+
+tokio::task_local! {
+ static AUTONOMOUS_ITER_CAP: usize;
+}
+
+/// The active autonomous iteration cap, if a skill run scoped one.
+pub fn autonomous_iter_cap() -> Option<usize> {
+ AUTONOMOUS_ITER_CAP.try_with(|c| *c).ok()
+}
+
+/// Run `fut` with an autonomous iteration cap in scope. The cap propagates to
+/// every agentic loop awaited within — the orchestrator turn and the inline
+/// sub-agent loops.
+pub async fn with_autonomous_iter_cap<F: Future>(cap: usize, fut: F) -> F::Output {
+ AUTONOMOUS_ITER_CAP.scope(cap, fut).await
+}
+
+/// Lift a sub-agent's per-agent iteration `base` to the active autonomous cap
+/// when one is in scope (issue #4463).
+///
+/// Autonomous skill runs scope an
+/// [`with_autonomous_iter_cap`] of `TASK_RUN_MAX_ITERATIONS` /
+/// `WORKFLOW_RUN_MAX_ITERATIONS` around the whole tree so an unattended run
+/// continues until it's done or a circuit breaker trips, rather than stopping at
+/// a specialist sub-agent's normal cap (e.g. 10). The migration to the tinyagents
+/// harness dropped every reader of [`autonomous_iter_cap`], so those setters
+/// became dead knobs and sub-agents silently reverted to the normal cap. This is
+/// the restored reader: sub-agent iteration computations run their
+/// `effective_max_iterations()` through it so the lift takes effect again. The
+/// cost budget + repeated-failure breakers remain the primary runaway guards.
+pub fn subagent_iter_cap_with_autonomous_lift(base: usize) -> usize {
+ match autonomous_iter_cap() {
+ Some(cap) if cap > base => {
+ tracing::debug!(
+ base,
+ autonomous_cap = cap,
+ "[subagent_host:autonomous] lifting sub-agent iteration cap for autonomous run"
+ );
+ cap
+ }
+ _ => base,
+ }
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/extract_tool.rs b/crates/openhuman-core/src/agent/subagent_host/extract_tool.rs
new file mode 100644
index 0000000000..37e36e4476
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/extract_tool.rs
@@ -0,0 +1,642 @@
+//! `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 (`summarization-v1`), 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 `summarization-v1`).
+//!
+//! 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 = vec![
+ 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 {
+ 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,
+ 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.rs
new file mode 100644
index 0000000000..ef9e4a6b5f
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/extract_tool_tests.rs
@@ -0,0 +1,38 @@
+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.rs
new file mode 100644
index 0000000000..5c29321e44
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/handoff.rs
@@ -0,0 +1,70 @@
+//! 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,
+ 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.rs
new file mode 100644
index 0000000000..ac2e17d16a
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/handoff_tests.rs
@@ -0,0 +1,84 @@
+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/lifecycle.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
new file mode 100644
index 0000000000..f88c2ee9aa
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
@@ -0,0 +1,1288 @@
+//! OpenHuman's three host seams for the neutral subagent lifecycle.
+//!
+//! The old runner deliberately remains the execution leaf while its policy-rich
+//! prompt/tool assembly is decomposed. This adapter makes the ownership
+//! boundary explicit now: TinyAgents owns the lifecycle and OpenHuman owns the
+//! plan, execution details, and translation back to its public DTOs.
+
+use std::{
+ collections::HashMap,
+ fs::OpenOptions,
+ path::PathBuf,
+ sync::{Arc, Mutex, OnceLock},
+};
+
+use async_trait::async_trait;
+use fs2::FileExt;
+use tinyagents_harness::context::{RunConfig, RunContext};
+use tinyagents_orchestration::subagent::{
+ ArtifactReference, PreparedSubagent, SubagentCapabilities, SubagentDriver, SubagentError,
+ SubagentExecution, SubagentExecutor, SubagentIncomplete, SubagentOutcome, SubagentPause,
+ SubagentPausePersistenceDisposition, SubagentPlanner, SubagentRequest, SubagentResume,
+ SubagentRunResult, SubagentStatus, SubagentTaskKey, SubagentTerminalPersistenceDisposition,
+};
+use tinyagents_runtime::ToolSnapshot;
+use tinyinference_llm::{
+ message::Message,
+ usage::{ChargedAmount, Usage, UsageTotals},
+};
+use tokio::sync::{Mutex as AsyncMutex, Notify};
+
+use super::{
+ SubagentRunError, SubagentRunOptions, SubagentRunOutcome, SubagentRunStatus, SubagentUsage,
+};
+
+/// Runs one host subagent through a neutral driver using a real direct child.
+///
+/// Callers that are already inside a TinyAgents turn must use this entrypoint:
+/// it derives the durable key from `parent` before constructing the child and
+/// therefore preserves root, parent, thread, and cancellation lineage.
+pub async fn run_subagent_with_parent(
+ parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ definition: crate::agent::harness::definition::AgentDefinition,
+ input: impl Into<String>,
+ options: SubagentRunOptions,
+) -> Result<SubagentRunOutcome, SubagentRunError> {
+ OpenHumanSubagentHost::new(definition, options)
+ .run(parent, input.into())
+ .await
+}
+
+/// Root host entrypoint for callers that begin outside a retained live parent
+/// context. It creates the one explicit root context, then drives the same
+/// neutral lifecycle as nested callers.
+pub async fn run_subagent(
+ definition: &crate::agent::harness::definition::AgentDefinition,
+ input: &str,
+ options: SubagentRunOptions,
+) -> Result<SubagentRunOutcome, SubagentRunError> {
+ let mut root_data = options.run_context.clone();
+ let root_config = root_data.root_run_config("subagent-host");
+ let root = root_data.into_tinyagents(root_config);
+ run_subagent_with_parent(&root, definition.clone(), input, options).await
+}
+
+/// Resume a durable lifecycle with its recovered original task key. The fresh
+/// child supplies live execution lineage only; all coalescing, pause lookup and
+/// terminal persistence remain scoped to `original_key`.
+pub async fn continue_subagent_with_parent(
+ parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ original_key: SubagentTaskKey,
+ definition: crate::agent::harness::definition::AgentDefinition,
+ input: impl Into<String>,
+ options: SubagentRunOptions,
+) -> Result<SubagentRunOutcome, SubagentRunError> {
+ OpenHumanSubagentHost::new(definition, options)
+ .continue_with_key(parent, original_key, input.into())
+ .await
+}
+
+/// Continuation counterpart for host surfaces that retain only the explicit
+/// OpenHuman carrier. The original durable key is mandatory.
+pub async fn continue_subagent(
+ original_key: SubagentTaskKey,
+ definition: &crate::agent::harness::definition::AgentDefinition,
+ input: &str,
+ options: SubagentRunOptions,
+) -> Result<SubagentRunOutcome, SubagentRunError> {
+ let mut root_data = options.run_context.clone();
+ let root_config = root_data.root_run_config("subagent-host");
+ let root = root_data.into_tinyagents(root_config);
+ continue_subagent_with_parent(&root, original_key, definition.clone(), input, options).await
+}
+
+/// Recover the original durable key and complete host pause payload from the
+/// safe task-id index written at the pause persistence boundary.
+pub(crate) fn load_subagent_checkpoint(
+ checkpoint_dir: &std::path::Path,
+ task_id: &str,
+) -> Result<super::SubagentCheckpointData, SubagentRunError> {
+ let persistence = OpenHumanPersistence::new(checkpoint_dir.to_path_buf());
+ // This reads under the full-key lifecycle lock and filters terminal state,
+ // so an index left behind by terminal cleanup can never reopen a closed
+ // subagent as an old pause.
+ persistence.checkpoint_for_task(task_id)
+}
+
+/// Per-invocation OpenHuman adapter state. A driver is intentionally created
+/// for one caller-owned lifecycle; process-wide persistence remains the source
+/// of truth for cross-process continuation and duplicate terminal effects.
+pub struct OpenHumanSubagentHost {
+ definition: crate::agent::harness::definition::AgentDefinition,
+ options: SubagentRunOptions,
+}
+
+/// Process-local coalescing extends TinyAgents' per-driver reservation across
+/// independently constructed host adapters. Durable persistence remains the
+/// cross-process authority; this prevents duplicate local child graphs.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+struct HostLifecycleKey {
+ checkpoint_dir: PathBuf,
+ task_key: SubagentTaskKey,
+}
+
+pub(super) struct HostInFlight {
+ /// `Some(Some(outcome))` is a committed leader result; `Some(None)` means
+ /// the leader failed before a durable result and followers must reserve a
+ /// new attempt rather than receiving a flattened host error.
+ result: AsyncMutex<Option<Option<SubagentRunOutcome>>>,
+ notify: Notify,
+}
+
+impl HostInFlight {
+ pub(super) fn new() -> Self {
+ Self {
+ result: AsyncMutex::new(None),
+ notify: Notify::new(),
+ }
+ }
+
+ pub(super) async fn wait(
+ &self,
+ cancellation: &tinyagents_harness::CancellationToken,
+ task_key: &SubagentTaskKey,
+ agent_id: &str,
+ ) -> Result<Option<SubagentRunOutcome>, SubagentRunError> {
+ loop {
+ let notified = self.notify.notified();
+ tokio::pin!(notified);
+ notified.as_mut().enable();
+ if let Some(result) = self.result.lock().await.clone() {
+ return Ok(result.map(host_observer_outcome));
+ }
+ tokio::select! {
+ biased;
+ _ = cancellation.cancelled() => {
+ return Ok(Some(observer_cancelled_outcome(task_key, agent_id)));
+ }
+ _ = &mut notified => {}
+ }
+ }
+ }
+
+ pub(super) async fn complete(&self, result: Option<SubagentRunOutcome>) {
+ *self.result.lock().await = Some(result);
+ self.notify.notify_waiters();
+ }
+}
+
+fn observer_cancelled_outcome(task_key: &SubagentTaskKey, agent_id: &str) -> SubagentRunOutcome {
+ SubagentRunOutcome {
+ task_id: task_key.task_id.clone(),
+ agent_id: agent_id.to_owned(),
+ output: String::new(),
+ iterations: 0,
+ elapsed: std::time::Duration::default(),
+ mode: super::SubagentMode::Typed,
+ status: SubagentRunStatus::Cancelled,
+ final_history: Vec::new(),
+ usage: SubagentUsage::default(),
+ artifact_paths: Vec::new(),
+ persistence_disposition:
+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::ObserverCancelled,
+ }
+}
+
+fn host_observer_outcome(mut outcome: SubagentRunOutcome) -> SubagentRunOutcome {
+ use tinyagents_orchestration::subagent::SubagentPersistenceDisposition as Disposition;
+
+ outcome.persistence_disposition = match outcome.persistence_disposition {
+ Disposition::PauseCommitted | Disposition::PauseReplaced | Disposition::PauseExisting => {
+ Disposition::PauseExisting
+ }
+ Disposition::TerminalInserted | Disposition::TerminalExisting => {
+ Disposition::TerminalExisting
+ }
+ Disposition::ObserverCancelled => Disposition::ObserverCancelled,
+ };
+ outcome
+}
+
+static HOST_IN_FLIGHT: OnceLock<AsyncMutex<HashMap<HostLifecycleKey, Arc<HostInFlight>>>> =
+ OnceLock::new();
+
+fn host_in_flight() -> &'static AsyncMutex<HashMap<HostLifecycleKey, Arc<HostInFlight>>> {
+ HOST_IN_FLIGHT.get_or_init(|| AsyncMutex::new(HashMap::new()))
+}
+
+fn absolute_checkpoint_dir(path: PathBuf) -> PathBuf {
+ std::fs::canonicalize(&path).unwrap_or_else(|_| {
+ if path.is_absolute() {
+ path
+ } else {
+ std::env::current_dir()
+ .map(|cwd| cwd.join(&path))
+ .unwrap_or(path)
+ }
+ })
+}
+
+impl OpenHumanSubagentHost {
+ pub fn new(
+ definition: crate::agent::harness::definition::AgentDefinition,
+ options: SubagentRunOptions,
+ ) -> Self {
+ Self {
+ definition,
+ options,
+ }
+ }
+
+ pub async fn run(
+ self,
+ parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ input: String,
+ ) -> Result<SubagentRunOutcome, SubagentRunError> {
+ let task_id = self
+ .options
+ .task_id
+ .clone()
+ .unwrap_or_else(|| format!("sub-{}", uuid::Uuid::new_v4()));
+ let child_config = RunConfig::new(format!("subagent-{}", uuid::Uuid::new_v4()));
+ let (task_key, child) = crate::agent::tinyagents::host::direct_subagent_child(
+ parent,
+ task_id.clone(),
+ child_config,
+ )
+ .map_err(|error| SubagentRunError::Provider(anyhow::anyhow!(error.to_string())))?;
+ self.run_with_request(parent, task_key, child, input, false)
+ .await
+ }
+
+ async fn continue_with_key(
+ self,
+ parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ task_key: SubagentTaskKey,
+ input: String,
+ ) -> Result<SubagentRunOutcome, SubagentRunError> {
+ let child_config = RunConfig::new(format!("subagent-{}", uuid::Uuid::new_v4()));
+ let (_, child) = crate::agent::tinyagents::host::direct_subagent_child(
+ parent,
+ task_key.task_id.clone(),
+ child_config,
+ )
+ .map_err(|error| SubagentRunError::Provider(anyhow::anyhow!(error.to_string())))?;
+ self.run_with_request(parent, task_key, child, input, true)
+ .await
+ }
+
+ async fn run_with_request(
+ self,
+ parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ task_key: SubagentTaskKey,
+ child: RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ input: String,
+ continuation: bool,
+ ) -> Result<SubagentRunOutcome, SubagentRunError> {
+ let checkpoint_dir =
+ absolute_checkpoint_dir(self.options.checkpoint_dir.clone().unwrap_or_else(|| {
+ parent
+ .data
+ .parent
+ .as_ref()
+ .map(|context| {
+ context
+ .workspace_dir
+ .join(".openhuman/subagent_checkpoints")
+ })
+ .unwrap_or_else(|| std::path::PathBuf::from(".openhuman/subagent_checkpoints"))
+ }));
+ let lifecycle_key = HostLifecycleKey {
+ checkpoint_dir: checkpoint_dir.clone(),
+ task_key: task_key.clone(),
+ };
+ let (entry, is_leader) = {
+ let mut entries = host_in_flight().lock().await;
+ match entries.get(&lifecycle_key) {
+ Some(entry) => (entry.clone(), false),
+ None => {
+ let entry = Arc::new(HostInFlight::new());
+ entries.insert(lifecycle_key.clone(), entry.clone());
+ (entry, true)
+ }
+ }
+ };
+ if !is_leader {
+ if let Some(outcome) = entry
+ .wait(&parent.cancellation, &task_key, &self.definition.id)
+ .await?
+ {
+ return Ok(outcome);
+ }
+ // Do not collapse the leader's typed error into an untyped string.
+ // A follower retries the reservation and, if it becomes leader,
+ // reports its own native planning/provider/policy classification.
+ // The retry is boxed because the host keeps the typed leader error
+ // out of the shared result. In practice it retries only after the
+ // prior entry has been removed; boxing keeps that recovery path
+ // from making the public host future infinitely sized.
+ return Box::pin(self.run_with_request(parent, task_key, child, input, continuation))
+ .await;
+ }
+
+ let result = self
+ .run_leader(
+ parent,
+ task_key.clone(),
+ child,
+ input,
+ continuation,
+ checkpoint_dir,
+ )
+ .await;
+ entry.complete(result.as_ref().ok().cloned()).await;
+ let mut entries = host_in_flight().lock().await;
+ if entries
+ .get(&lifecycle_key)
+ .is_some_and(|current| Arc::ptr_eq(current, &entry))
+ {
+ entries.remove(&lifecycle_key);
+ }
+ result
+ }
+
+ async fn run_leader(
+ self,
+ parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ task_key: SubagentTaskKey,
+ child: RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ input: String,
+ continuation: bool,
+ checkpoint_dir: PathBuf,
+ ) -> Result<SubagentRunOutcome, SubagentRunError> {
+ let failures = Arc::new(Mutex::new(None));
+ let host_outcome = Arc::new(Mutex::new(None));
+ let plan = Arc::new(Mutex::new(None));
+ let fallback_agent_id = self.definition.id.clone();
+ let request = HostRequest {
+ definition: self.definition,
+ options: self.options,
+ };
+ let planner = Arc::new(OpenHumanPlanner {
+ plan: Arc::clone(&plan),
+ });
+ let executor = Arc::new(OpenHumanExecutor {
+ plan,
+ failures: Arc::clone(&failures),
+ host_outcome: Arc::clone(&host_outcome),
+ });
+ let persistence = Arc::new(
+ OpenHumanPersistence::new(checkpoint_dir).with_host_outcome(Arc::clone(&host_outcome)),
+ );
+ let lifecycle_persistence: Arc<
+ dyn tinyagents_orchestration::subagent::SubagentPersistence,
+ > = persistence.clone();
+ let driver = SubagentDriver::new(SubagentCapabilities {
+ planner: Some(planner),
+ executor: Some(executor),
+ persistence: Some(lifecycle_persistence),
+ })
+ .map_err(map_lifecycle_error)?;
+ let request = if continuation {
+ SubagentRequest::continue_with_key(task_key.clone(), child, request, input, None)
+ } else {
+ // `direct_subagent_child` derives the same key for the host's
+ // durable lookup; this constructor independently proves that the
+ // execution context is the supplied parent's direct child.
+ SubagentRequest::fresh_from_parent(
+ parent,
+ child,
+ task_key.task_id.clone(),
+ request,
+ input,
+ None,
+ )
+ }
+ .map_err(map_lifecycle_error)?;
+ let cancellation = parent.cancellation.clone();
+ match driver.run(request, cancellation).await {
+ Ok(result) => Ok(outcome_to_host(
+ result,
+ host_outcome
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .take(),
+ &persistence,
+ &task_key,
+ &fallback_agent_id,
+ )),
+ Err(error) => {
+ if let Some(host_error) = failures.lock().unwrap_or_else(|p| p.into_inner()).take()
+ {
+ Err(host_error)
+ } else {
+ Err(map_lifecycle_error(error))
+ }
+ }
+ }
+ }
+}
+
+#[derive(Clone)]
+struct HostRequest {
+ definition: crate::agent::harness::definition::AgentDefinition,
+ options: SubagentRunOptions,
+}
+
+struct PreparedHostPlan {
+ definition: crate::agent::harness::definition::AgentDefinition,
+ options: SubagentRunOptions,
+}
+
+struct OpenHumanPlanner {
+ plan: Arc<Mutex<Option<PreparedHostPlan>>>,
+}
+
+/// Appends the new continuation input to the exact durable history supplied by
+/// TinyAgents. Kept separate so the no-drop/no-duplicate resume contract has a
+/// focused regression test independent of provider execution.
+pub(super) fn merged_resume_history(mut history: Vec<Message>, input: String) -> Vec<Message> {
+ if !input.is_empty() {
+ history.push(Message::user(input));
+ }
+ history
+}
+
+#[async_trait]
+impl SubagentPlanner<crate::agent::tinyagents::host::OpenHumanRunContext, HostRequest>
+ for OpenHumanPlanner
+{
+ async fn prepare(
+ &self,
+ request: SubagentRequest<crate::agent::tinyagents::host::OpenHumanRunContext, HostRequest>,
+ ) -> Result<PreparedSubagent<crate::agent::tinyagents::host::OpenHumanRunContext>, SubagentError>
+ {
+ let request = request.into_parts();
+ let mut options = request.host_request.options;
+ let input = request.input;
+ // The generic persistence seam supplies the pause *before* host
+ // options are prepared. A continuation's new user answer belongs
+ // after that durable history, exactly once; never overwrite a
+ // caller-provided answer with the loaded checkpoint.
+ let planned_input = if let Some(resume) = request.resume {
+ let history = merged_resume_history(resume.history, input);
+ options.initial_history = Some(
+ history
+ .iter()
+ .map(crate::agent::message_convert::message_to_native_chat_message)
+ .collect(),
+ );
+ history
+ } else {
+ vec![Message::user(input)]
+ };
+ options.task_id = Some(request.task_key.task_id.clone());
+ options.run_context = request.run_context.data.clone();
+ *self.plan.lock().unwrap_or_else(|p| p.into_inner()) = Some(PreparedHostPlan {
+ definition: request.host_request.definition.clone(),
+ options,
+ });
+ Ok(PreparedSubagent {
+ task_id: request.task_key.task_id,
+ agent_key: request.host_request.definition.id,
+ input: planned_input,
+ // The host execution leaf resolves the exact filtered tool snapshot
+ // together with its executable instances and policy. A neutral
+ // empty declaration prevents this transport plan from advertising
+ // an authority it has not resolved.
+ tools: ToolSnapshot::default(),
+ run_context: request.run_context,
+ })
+ }
+}
+
+struct OpenHumanExecutor {
+ plan: Arc<Mutex<Option<PreparedHostPlan>>>,
+ failures: Arc<Mutex<Option<SubagentRunError>>>,
+ host_outcome: Arc<Mutex<Option<SubagentRunOutcome>>>,
+}
+
+#[async_trait]
+impl SubagentExecutor<crate::agent::tinyagents::host::OpenHumanRunContext> for OpenHumanExecutor {
+ async fn execute(
+ &self,
+ execution: SubagentExecution<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ ) -> Result<SubagentOutcome, SubagentError> {
+ let PreparedHostPlan {
+ definition,
+ mut options,
+ } = self
+ .plan
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .take()
+ .ok_or_else(|| {
+ SubagentError::Execution("OpenHuman subagent plan was consumed".into())
+ })?;
+ // Both carriers observe one token. The generic driver installs this
+ // token on the prepared RunContext; the host graph polls the copy in
+ // its explicit OpenHuman carrier.
+ options.run_context = execution.prepared.run_context.data.clone();
+ options.run_context.cancellation = execution.cancellation.clone();
+ match super::ops::run_subagent_direct(
+ &definition,
+ &execution
+ .prepared
+ .input
+ .last()
+ .map(Message::text)
+ .unwrap_or_default(),
+ options.clone(),
+ )
+ .await
+ {
+ Ok(outcome) => {
+ *self.host_outcome.lock().unwrap_or_else(|p| p.into_inner()) =
+ Some(outcome.clone());
+ Ok(host_outcome_to_neutral(outcome, &definition, &options))
+ }
+ Err(error) => {
+ *self.failures.lock().unwrap_or_else(|p| p.into_inner()) = Some(error);
+ Err(SubagentError::Execution(
+ "OpenHuman execution failed".into(),
+ ))
+ }
+ }
+ }
+}
+
+/// Durable OpenHuman pause/terminal records scoped by the complete neutral
+/// task key. The key is encoded rather than using a task id as a filename, so
+/// equally named children of separate roots/parents can never resume or close
+/// one another's lifecycle.
+pub(super) struct OpenHumanPersistence {
+ checkpoint_dir: std::path::PathBuf,
+ host_outcome: Arc<Mutex<Option<SubagentRunOutcome>>>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+struct TerminalRecord {
+ outcome: SubagentOutcome,
+ #[serde(default)]
+ agent_id: String,
+ #[serde(default)]
+ elapsed_ms: u64,
+}
+
+#[derive(serde::Deserialize)]
+#[serde(untagged)]
+enum CompatibleTerminalRecord {
+ Current(TerminalRecord),
+ Legacy(SubagentOutcome),
+}
+
+impl OpenHumanPersistence {
+ pub(super) fn new(checkpoint_dir: std::path::PathBuf) -> Self {
+ Self {
+ checkpoint_dir,
+ host_outcome: Arc::new(Mutex::new(None)),
+ }
+ }
+
+ fn with_host_outcome(mut self, host_outcome: Arc<Mutex<Option<SubagentRunOutcome>>>) -> Self {
+ self.host_outcome = host_outcome;
+ self
+ }
+
+ fn key_component(key: &SubagentTaskKey) -> String {
+ fn hex(value: &str) -> String {
+ value
+ .as_bytes()
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect()
+ }
+ format!(
+ "{}-{}-{}-{}",
+ hex(&key.root_run_id),
+ hex(&key.parent_run_id),
+ hex(key.thread_id.as_deref().unwrap_or("")),
+ hex(&key.task_id),
+ )
+ }
+
+ fn pause_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
+ self.checkpoint_dir
+ .join("lifecycle")
+ .join(format!("{}.pause.json", Self::key_component(key)))
+ }
+
+ fn terminal_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
+ self.checkpoint_dir
+ .join("lifecycle")
+ .join(format!("{}.terminal.json", Self::key_component(key)))
+ }
+
+ fn index_path(&self, task_id: &str) -> std::path::PathBuf {
+ self.checkpoint_dir.join("lifecycle").join(format!(
+ "task-{}.index.json",
+ task_id
+ .as_bytes()
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect::<String>()
+ ))
+ }
+
+ fn lock_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
+ self.checkpoint_dir
+ .join("lifecycle")
+ .join(format!("{}.lock", Self::key_component(key)))
+ }
+
+ fn index_lock_path(&self, task_id: &str) -> std::path::PathBuf {
+ self.checkpoint_dir.join("lifecycle").join(format!(
+ "task-{}.index.lock",
+ task_id
+ .as_bytes()
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect::<String>()
+ ))
+ }
+
+ fn lock_file(path: &std::path::Path) -> Result<std::fs::File, SubagentError> {
+ let parent = path.parent().expect("lifecycle lock path has a parent");
+ std::fs::create_dir_all(parent)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ let file = OpenOptions::new()
+ .create(true)
+ .read(true)
+ .write(true)
+ .open(path)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ file.lock_exclusive()
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ Ok(file)
+ }
+
+ fn key_lock(&self, key: &SubagentTaskKey) -> Result<std::fs::File, SubagentError> {
+ Self::lock_file(&self.lock_path(key))
+ }
+
+ fn index_lock(&self, task_id: &str) -> Result<std::fs::File, SubagentError> {
+ Self::lock_file(&self.index_lock_path(task_id))
+ }
+
+ fn read_index_keys(&self, task_id: &str) -> Result<Vec<SubagentTaskKey>, SubagentError> {
+ let raw = match std::fs::read_to_string(self.index_path(task_id)) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),
+ };
+ let value: serde_json::Value = serde_json::from_str(&raw)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ // Accept the short-lived single-key format written by the first
+ // lifecycle extraction, but immediately write the collision-safe
+ // vector format on the next mutation.
+ let keys = value
+ .get("keys")
+ .cloned()
+ .map(serde_json::from_value)
+ .transpose()
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?
+ .or_else(|| {
+ value
+ .get("key")
+ .cloned()
+ .and_then(|key| serde_json::from_value(key).ok())
+ .map(|key| vec![key])
+ })
+ .unwrap_or_default();
+ Ok(keys)
+ }
+
+ fn write_index_keys(
+ &self,
+ task_id: &str,
+ keys: &[SubagentTaskKey],
+ ) -> Result<(), SubagentError> {
+ let path = self.index_path(task_id);
+ if keys.is_empty() {
+ match std::fs::remove_file(path) {
+ Ok(()) => return Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),
+ }
+ }
+ Self::replace_file(
+ &path,
+ serde_json::to_vec(&serde_json::json!({"keys": keys}))
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?,
+ )
+ }
+
+ fn add_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {
+ let _index_lock = self.index_lock(&key.task_id)?;
+ let mut keys = self.read_index_keys(&key.task_id)?;
+ if !keys.contains(key) {
+ keys.push(key.clone());
+ self.write_index_keys(&key.task_id, &keys)?;
+ }
+ Ok(())
+ }
+
+ fn remove_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {
+ let _index_lock = self.index_lock(&key.task_id)?;
+ let mut keys = self.read_index_keys(&key.task_id)?;
+ keys.retain(|candidate| candidate != key);
+ self.write_index_keys(&key.task_id, &keys)
+ }
+
+ fn replace_file(path: &std::path::Path, bytes: Vec<u8>) -> Result<(), SubagentError> {
+ let parent = path.parent().expect("lifecycle state path has a parent");
+ std::fs::create_dir_all(parent)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
+ std::fs::write(&temporary, bytes)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ match std::fs::rename(&temporary, path) {
+ Ok(()) => Ok(()),
+ Err(error) => {
+ let _ = std::fs::remove_file(&temporary);
+ Err(SubagentError::Persistence(error.to_string()))
+ }
+ }
+ }
+
+ fn insert_file(path: &std::path::Path, bytes: Vec<u8>) -> Result<bool, SubagentError> {
+ let parent = path.parent().expect("lifecycle state path has a parent");
+ std::fs::create_dir_all(parent)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
+ std::fs::write(&temporary, bytes)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ match std::fs::hard_link(&temporary, path) {
+ Ok(()) => {
+ let _ = std::fs::remove_file(&temporary);
+ Ok(true)
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
+ let _ = std::fs::remove_file(&temporary);
+ Ok(false)
+ }
+ Err(error) => {
+ let _ = std::fs::remove_file(&temporary);
+ Err(SubagentError::Persistence(error.to_string()))
+ }
+ }
+ }
+
+ fn read_pause_checkpoint(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<super::SubagentCheckpointData>, SubagentError> {
+ let raw = match std::fs::read_to_string(self.pause_path(key)) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),
+ };
+ let checkpoint = serde_json::from_str::<super::SubagentCheckpointData>(&raw)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ if checkpoint.task_key.as_ref() != Some(key) {
+ return Err(SubagentError::Persistence("checkpoint key mismatch".into()));
+ }
+ Ok(Some(checkpoint))
+ }
+
+ fn read_terminal_record(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<TerminalRecord>, SubagentError> {
+ let raw = match std::fs::read_to_string(self.terminal_path(key)) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),
+ };
+ match serde_json::from_str(&raw)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?
+ {
+ CompatibleTerminalRecord::Current(record) => Ok(Some(record)),
+ CompatibleTerminalRecord::Legacy(outcome) => Ok(Some(TerminalRecord {
+ outcome,
+ agent_id: String::new(),
+ elapsed_ms: 0,
+ })),
+ }
+ }
+
+ fn durable_host_metadata(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<(String, u64)>, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ if let Some(record) = self.read_terminal_record(key)? {
+ return Ok(
+ (!record.agent_id.is_empty()).then_some((record.agent_id, record.elapsed_ms))
+ );
+ }
+ Ok(self.read_pause_checkpoint(key)?.and_then(|checkpoint| {
+ (!checkpoint.agent_id.is_empty())
+ .then_some((checkpoint.agent_id, checkpoint.elapsed_ms))
+ }))
+ }
+
+ fn checkpoint_resume(checkpoint: &super::SubagentCheckpointData) -> SubagentResume {
+ SubagentResume {
+ history: checkpoint
+ .history
+ .iter()
+ .map(crate::agent::message_convert::chat_message_to_message)
+ .collect(),
+ checkpoint: checkpoint.resume_checkpoint.clone(),
+ metadata: checkpoint.resume_metadata.clone(),
+ }
+ }
+
+ fn checkpoint_outcome(checkpoint: super::SubagentCheckpointData) -> SubagentOutcome {
+ let resume = Self::checkpoint_resume(&checkpoint);
+ SubagentOutcome {
+ task_id: checkpoint.task_id,
+ output: checkpoint.output,
+ history: checkpoint
+ .history
+ .iter()
+ .map(crate::agent::message_convert::chat_message_to_message)
+ .collect(),
+ status: SubagentStatus::AwaitingInput(SubagentPause {
+ reason: checkpoint.question,
+ resume,
+ }),
+ usage: UsageTotals {
+ calls: checkpoint.iterations as u64,
+ usage: Usage {
+ input_tokens: checkpoint.usage.input_tokens,
+ output_tokens: checkpoint.usage.output_tokens,
+ total_tokens: checkpoint
+ .usage
+ .input_tokens
+ .saturating_add(checkpoint.usage.output_tokens),
+ cache_read_tokens: checkpoint.usage.cached_input_tokens,
+ charged_amount: Some(ChargedAmount::usd_micros(
+ (checkpoint.usage.charged_amount_usd * 1_000_000.0).round() as i64,
+ )),
+ ..Usage::default()
+ },
+ },
+ artifacts: checkpoint
+ .artifact_paths
+ .into_iter()
+ .map(|id| ArtifactReference {
+ id,
+ ..ArtifactReference::default()
+ })
+ .collect(),
+ }
+ }
+
+ fn live_checkpoint(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<super::SubagentCheckpointData>, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ if self.terminal_path(key).exists() {
+ return Ok(None);
+ }
+ self.read_pause_checkpoint(key)
+ }
+
+ fn checkpoint_for_task(
+ &self,
+ task_id: &str,
+ ) -> Result<super::SubagentCheckpointData, SubagentRunError> {
+ if !super::ops::is_safe_task_id(task_id) {
+ return Err(SubagentRunError::Provider(anyhow::anyhow!(
+ "unsafe task id"
+ )));
+ }
+ let keys = {
+ let _index_lock = self.index_lock(task_id).map_err(map_lifecycle_error)?;
+ self.read_index_keys(task_id).map_err(map_lifecycle_error)?
+ };
+ let mut live = Vec::new();
+ for key in keys {
+ if let Some(checkpoint) = self.live_checkpoint(&key).map_err(map_lifecycle_error)? {
+ live.push(checkpoint);
+ }
+ }
+ match live.len() {
+ 1 => Ok(live.remove(0)),
+ 0 => Err(SubagentRunError::Provider(anyhow::anyhow!(
+ "no live subagent pause checkpoint for task id"
+ ))),
+ _ => Err(SubagentRunError::Provider(anyhow::anyhow!(
+ "ambiguous subagent task id; select a scoped lifecycle key"
+ ))),
+ }
+ }
+
+ pub(crate) fn recover_key(
+ checkpoint_dir: &std::path::Path,
+ task_id: &str,
+ ) -> Result<SubagentTaskKey, SubagentRunError> {
+ let persistence = Self::new(checkpoint_dir.to_path_buf());
+ let checkpoint = persistence.checkpoint_for_task(task_id)?;
+ checkpoint.task_key.ok_or_else(|| {
+ SubagentRunError::Provider(anyhow::anyhow!("checkpoint omitted original task key"))
+ })
+ }
+}
+
+#[async_trait]
+impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersistence {
+ async fn load_terminal(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<SubagentOutcome>, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ Ok(self.read_terminal_record(key)?.map(|record| record.outcome))
+ }
+ async fn load(&self, key: &SubagentTaskKey) -> Result<Option<SubagentResume>, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ if self.terminal_path(key).exists() {
+ return Ok(None);
+ }
+ Ok(self
+ .read_pause_checkpoint(key)?
+ .as_ref()
+ .map(Self::checkpoint_resume))
+ }
+
+ async fn load_pause(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<SubagentOutcome>, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ if self.terminal_path(key).exists() {
+ return Ok(None);
+ }
+ Ok(self
+ .read_pause_checkpoint(key)?
+ .map(Self::checkpoint_outcome))
+ }
+
+ async fn save_pause(
+ &self,
+ pause: tinyagents_orchestration::subagent::PersistedSubagentPause,
+ ) -> Result<SubagentPausePersistenceDisposition, SubagentError> {
+ let _key_lock = self.key_lock(&pause.key)?;
+ if self.terminal_path(&pause.key).exists() {
+ return Ok(SubagentPausePersistenceDisposition::TerminalExisting);
+ }
+ let paused = match &pause.outcome.status {
+ SubagentStatus::AwaitingInput(paused) => paused,
+ _ => {
+ return Err(SubagentError::Persistence(
+ "attempted to persist a non-paused subagent outcome as a pause".into(),
+ ));
+ }
+ };
+ let metadata = &paused.resume.metadata;
+ let optional_metadata = |name: &str| {
+ metadata
+ .get(name)
+ .filter(|value| !value.is_empty())
+ .cloned()
+ };
+ let checkpoint = super::SubagentCheckpointData {
+ task_key: Some(pause.key.clone()),
+ task_id: pause.key.task_id.clone(),
+ agent_id: optional_metadata("agent_id").unwrap_or_default(),
+ worker_thread_id: optional_metadata("worker_thread_id"),
+ history: pause
+ .outcome
+ .history
+ .iter()
+ .map(crate::agent::message_convert::message_to_native_chat_message)
+ .collect(),
+ question: paused.reason.clone(),
+ options: None,
+ toolkit_override: optional_metadata("toolkit_override"),
+ skill_filter_override: optional_metadata("skill_filter_override"),
+ model_override: optional_metadata("model_override"),
+ created_at: chrono::Utc::now().to_rfc3339(),
+ resume_checkpoint: paused.resume.checkpoint.clone(),
+ resume_metadata: metadata.clone(),
+ output: pause.outcome.output.clone(),
+ iterations: pause.outcome.usage.calls as usize,
+ usage: SubagentUsage {
+ input_tokens: pause.outcome.usage.usage.input_tokens,
+ output_tokens: pause.outcome.usage.usage.output_tokens,
+ cached_input_tokens: pause.outcome.usage.usage.cache_read_tokens,
+ charged_amount_usd: pause
+ .outcome
+ .usage
+ .usage
+ .charged_amount
+ .map(|amount| amount.micros as f64 / 1_000_000.0)
+ .unwrap_or_default(),
+ },
+ artifact_paths: pause
+ .outcome
+ .artifacts
+ .iter()
+ .map(|artifact| artifact.id.clone())
+ .collect(),
+ elapsed_ms: self
+ .host_outcome
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .as_ref()
+ .map(|outcome| outcome.elapsed.as_millis() as u64)
+ .unwrap_or_default(),
+ };
+ let json = serde_json::to_vec_pretty(&checkpoint)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ let path = self.pause_path(&pause.key);
+ let existing = self.read_pause_checkpoint(&pause.key)?;
+ match (pause.replaces.as_ref(), existing) {
+ (None, None) => {
+ // Index first: a failed data write can leave a stale index,
+ // which readers filter by the live pause record. A successful
+ // pause can never be unresumable through a missing index.
+ self.add_index_key(&pause.key)?;
+ if Self::insert_file(&path, json)? {
+ Ok(SubagentPausePersistenceDisposition::Inserted)
+ } else {
+ Ok(SubagentPausePersistenceDisposition::Existing)
+ }
+ }
+ (Some(expected), Some(current)) if Self::checkpoint_resume(&current) == *expected => {
+ self.add_index_key(&pause.key)?;
+ Self::replace_file(&path, json)?;
+ Ok(SubagentPausePersistenceDisposition::Replaced)
+ }
+ _ => Ok(SubagentPausePersistenceDisposition::Existing),
+ }
+ }
+
+ async fn record_terminal(
+ &self,
+ key: &SubagentTaskKey,
+ outcome: &SubagentOutcome,
+ replaces: Option<&SubagentResume>,
+ ) -> Result<SubagentTerminalPersistenceDisposition, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ if self.terminal_path(key).exists() {
+ return Ok(SubagentTerminalPersistenceDisposition::Existing);
+ }
+ if let Some(current) = self.read_pause_checkpoint(key)? {
+ let can_consume_pause =
+ replaces.is_some_and(|expected| Self::checkpoint_resume(&current) == *expected);
+ if !can_consume_pause {
+ return Ok(SubagentTerminalPersistenceDisposition::PauseExisting);
+ }
+ } else if replaces.is_some() {
+ return Err(SubagentError::Persistence(
+ "terminal continuation lost its expected durable pause".into(),
+ ));
+ }
+ let path = self.terminal_path(key);
+ let host = self
+ .host_outcome
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .clone();
+ let record = serde_json::to_vec(&TerminalRecord {
+ outcome: outcome.clone(),
+ agent_id: host
+ .as_ref()
+ .map(|outcome| outcome.agent_id.clone())
+ .unwrap_or_default(),
+ elapsed_ms: host
+ .as_ref()
+ .map(|outcome| outcome.elapsed.as_millis() as u64)
+ .unwrap_or_default(),
+ })
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ match Self::insert_file(&path, record)? {
+ true => {
+ // Terminal is the durable winner. Retiring a matching pause
+ // afterwards cannot reopen the lifecycle because `load` first
+ // observes this terminal marker.
+ let _ = std::fs::remove_file(self.pause_path(key));
+ // A stale task-id index is harmless because recovery filters
+ // terminal keys. Never turn a durable terminal success into an
+ // error merely because cleanup of a derived index failed.
+ if let Err(error) = self.remove_index_key(key) {
+ tracing::warn!(task_id = %key.task_id, error = %error, "[subagent] terminal committed but task-id index cleanup failed");
+ }
+ Ok(SubagentTerminalPersistenceDisposition::Inserted)
+ }
+ false => Ok(SubagentTerminalPersistenceDisposition::Existing),
+ }
+ }
+}
+
+fn host_outcome_to_neutral(
+ outcome: SubagentRunOutcome,
+ definition: &crate::agent::harness::definition::AgentDefinition,
+ options: &SubagentRunOptions,
+) -> SubagentOutcome {
+ let status = match outcome.status {
+ SubagentRunStatus::Completed => SubagentStatus::Completed,
+ SubagentRunStatus::AwaitingUser { question, .. } => {
+ SubagentStatus::AwaitingInput(SubagentPause {
+ reason: question,
+ resume: SubagentResume {
+ history: outcome
+ .final_history
+ .iter()
+ .map(crate::agent::message_convert::chat_message_to_message)
+ .collect(),
+ metadata: std::collections::BTreeMap::from_iter([
+ ("agent_id".into(), definition.id.clone()),
+ (
+ "worker_thread_id".into(),
+ options.worker_thread_id.clone().unwrap_or_default(),
+ ),
+ (
+ "toolkit_override".into(),
+ options.toolkit_override.clone().unwrap_or_default(),
+ ),
+ (
+ "skill_filter_override".into(),
+ options.skill_filter_override.clone().unwrap_or_default(),
+ ),
+ (
+ "model_override".into(),
+ options.model_override.clone().unwrap_or_default(),
+ ),
+ ]),
+ ..SubagentResume::default()
+ },
+ })
+ }
+ SubagentRunStatus::Incomplete { reason } => {
+ SubagentStatus::Incomplete(SubagentIncomplete { reason })
+ }
+ SubagentRunStatus::Cancelled => SubagentStatus::Cancelled,
+ };
+ SubagentOutcome {
+ task_id: outcome.task_id,
+ output: outcome.output,
+ history: outcome
+ .final_history
+ .iter()
+ .map(crate::agent::message_convert::chat_message_to_message)
+ .collect(),
+ status,
+ usage: UsageTotals {
+ calls: outcome.iterations as u64,
+ usage: Usage {
+ input_tokens: outcome.usage.input_tokens,
+ output_tokens: outcome.usage.output_tokens,
+ total_tokens: outcome
+ .usage
+ .input_tokens
+ .saturating_add(outcome.usage.output_tokens),
+ cache_read_tokens: outcome.usage.cached_input_tokens,
+ charged_amount: Some(ChargedAmount::usd_micros(
+ (outcome.usage.charged_amount_usd * 1_000_000.0).round() as i64,
+ )),
+ ..Usage::default()
+ },
+ },
+ artifacts: outcome
+ .artifact_paths
+ .into_iter()
+ .map(|id| ArtifactReference {
+ id,
+ ..ArtifactReference::default()
+ })
+ .collect(),
+ }
+}
+
+fn outcome_to_host(
+ result: SubagentRunResult,
+ host: Option<SubagentRunOutcome>,
+ persistence: &OpenHumanPersistence,
+ task_key: &SubagentTaskKey,
+ fallback_agent_id: &str,
+) -> SubagentRunOutcome {
+ let persistence_disposition = result.disposition;
+ let outcome = result.outcome;
+ // A driver that lost a pause/terminal CAS may have a perfectly valid local
+ // execution result, but it is not the authoritative lifecycle outcome.
+ // Reconstruct the durable winner instead of leaking the loser’s output,
+ // usage, or artifacts to an observer.
+ let host = if persistence_disposition.should_emit_host_effects() {
+ host
+ } else {
+ None
+ };
+ let durable_metadata = if host.is_none() {
+ persistence.durable_host_metadata(task_key).ok().flatten()
+ } else {
+ None
+ };
+ let mut host = host.unwrap_or_else(|| SubagentRunOutcome {
+ task_id: outcome.task_id.clone(),
+ agent_id: durable_metadata
+ .as_ref()
+ .map(|(agent_id, _)| agent_id.clone())
+ .unwrap_or_else(|| fallback_agent_id.to_owned()),
+ output: outcome.output.clone(),
+ iterations: outcome.usage.calls as usize,
+ elapsed: std::time::Duration::from_millis(
+ durable_metadata
+ .map(|(_, elapsed_ms)| elapsed_ms)
+ .unwrap_or_default(),
+ ),
+ mode: super::SubagentMode::Typed,
+ status: SubagentRunStatus::Completed,
+ final_history: outcome
+ .history
+ .iter()
+ .map(crate::agent::message_convert::message_to_native_chat_message)
+ .collect(),
+ usage: SubagentUsage {
+ input_tokens: outcome.usage.usage.input_tokens,
+ output_tokens: outcome.usage.usage.output_tokens,
+ cached_input_tokens: outcome.usage.usage.cache_read_tokens,
+ charged_amount_usd: outcome
+ .usage
+ .usage
+ .charged_amount
+ .map(|amount| amount.micros as f64 / 1_000_000.0)
+ .unwrap_or_default(),
+ },
+ artifact_paths: outcome
+ .artifacts
+ .iter()
+ .map(|artifact| artifact.id.clone())
+ .collect(),
+ persistence_disposition,
+ });
+ let is_awaiting_input = matches!(outcome.status, SubagentStatus::AwaitingInput(_));
+ let status = match outcome.status {
+ SubagentStatus::Completed => SubagentRunStatus::Completed,
+ SubagentStatus::AwaitingInput(pause) => SubagentRunStatus::AwaitingUser {
+ question: pause.reason,
+ options: None,
+ checkpoint: None,
+ },
+ SubagentStatus::Incomplete(incomplete) => SubagentRunStatus::Incomplete {
+ reason: incomplete.reason,
+ },
+ SubagentStatus::Cancelled => SubagentRunStatus::Cancelled,
+ };
+ host.status = status;
+ host.persistence_disposition = persistence_disposition;
+ if is_awaiting_input {
+ host.status = SubagentRunStatus::AwaitingUser {
+ question: match host.status {
+ SubagentRunStatus::AwaitingUser { ref question, .. } => question.clone(),
+ _ => String::new(),
+ },
+ options: None,
+ checkpoint: Some(persistence.pause_path(task_key)),
+ };
+ }
+ host
+}
+
+fn map_lifecycle_error(error: SubagentError) -> SubagentRunError {
+ SubagentRunError::Provider(anyhow::anyhow!(error.to_string()))
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle_tests.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle_tests.rs
new file mode 100644
index 0000000000..964110a60e
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_tests.rs
@@ -0,0 +1,300 @@
+use tinyagents_orchestration::subagent::{
+ PersistedSubagentPause, SubagentOutcome, SubagentPause, SubagentPausePersistenceDisposition,
+ SubagentPersistence, SubagentResume, SubagentStatus, SubagentTaskKey,
+};
+
+use super::lifecycle::{
+ load_subagent_checkpoint, merged_resume_history, HostInFlight, OpenHumanPersistence,
+};
+use super::{SubagentMode, SubagentRunOutcome, SubagentRunStatus, SubagentUsage};
+
+fn key() -> SubagentTaskKey {
+ SubagentTaskKey {
+ root_run_id: "root".into(),
+ parent_run_id: "parent".into(),
+ thread_id: Some("thread".into()),
+ task_id: "task".into(),
+ }
+}
+
+fn paused_outcome(question: &str, resume: SubagentResume) -> SubagentOutcome {
+ SubagentOutcome {
+ task_id: "task".into(),
+ output: "partial result".into(),
+ history: resume.history.clone(),
+ status: SubagentStatus::AwaitingInput(SubagentPause {
+ reason: question.into(),
+ resume,
+ }),
+ usage: Default::default(),
+ artifacts: Vec::new(),
+ }
+}
+
+fn scoped_key(root: &str, parent: &str, thread: Option<&str>) -> SubagentTaskKey {
+ SubagentTaskKey {
+ root_run_id: root.into(),
+ parent_run_id: parent.into(),
+ thread_id: thread.map(str::to_owned),
+ task_id: "task".into(),
+ }
+}
+
+fn persisted_pause(
+ key: SubagentTaskKey,
+ question: &str,
+ replaces: Option<SubagentResume>,
+) -> PersistedSubagentPause {
+ let resume = if replaces.is_some() {
+ SubagentResume {
+ checkpoint: Some(format!("checkpoint-for-{question}")),
+ ..SubagentResume::default()
+ }
+ } else {
+ SubagentResume::default()
+ };
+ PersistedSubagentPause {
+ key,
+ outcome: paused_outcome(question, resume),
+ replaces,
+ }
+}
+
+#[test]
+fn resume_history_keeps_the_durable_transcript_and_appends_user_answer_once() {
+ let merged = merged_resume_history(
+ vec![tinyinference_llm::message::Message::assistant("prior work")],
+ "the user's answer".into(),
+ );
+ assert_eq!(
+ merged
+ .iter()
+ .map(tinyinference_llm::message::Message::text)
+ .collect::<Vec<_>>(),
+ vec!["prior work", "the user's answer"],
+ );
+}
+
+#[tokio::test]
+async fn persistence_commits_one_scoped_pause_and_recovers_its_original_key() {
+ let directory = tempfile::tempdir().unwrap();
+ let persistence = OpenHumanPersistence::new(directory.path().to_path_buf());
+ let key = key();
+ let pause = PersistedSubagentPause {
+ key: key.clone(),
+ outcome: paused_outcome("need input", SubagentResume::default()),
+ replaces: None,
+ };
+
+ assert_eq!(
+ persistence.save_pause(pause.clone()).await.unwrap(),
+ SubagentPausePersistenceDisposition::Inserted
+ );
+ assert_eq!(
+ persistence.save_pause(pause).await.unwrap(),
+ SubagentPausePersistenceDisposition::Existing
+ );
+ assert_eq!(
+ OpenHumanPersistence::recover_key(directory.path(), "task").unwrap(),
+ key
+ );
+ assert_eq!(
+ load_subagent_checkpoint(directory.path(), "task")
+ .unwrap()
+ .task_key,
+ Some(key)
+ );
+}
+
+#[tokio::test]
+async fn persistence_inserts_one_terminal_and_returns_the_durable_winner() {
+ let directory = tempfile::tempdir().unwrap();
+ let persistence = OpenHumanPersistence::new(directory.path().to_path_buf());
+ let key = key();
+ let mut winner = SubagentOutcome::cancelled("task");
+ winner.status = SubagentStatus::Completed;
+ winner.output = "winner".into();
+ let mut loser = SubagentOutcome::cancelled("task");
+ loser.status = SubagentStatus::Completed;
+ loser.output = "loser".into();
+
+ assert_eq!(
+ persistence
+ .record_terminal(&key, &winner, None)
+ .await
+ .unwrap(),
+ tinyagents_orchestration::subagent::SubagentTerminalPersistenceDisposition::Inserted
+ );
+ assert_eq!(
+ persistence
+ .record_terminal(&key, &loser, None)
+ .await
+ .unwrap(),
+ tinyagents_orchestration::subagent::SubagentTerminalPersistenceDisposition::Existing
+ );
+ assert_eq!(persistence.load_terminal(&key).await.unwrap(), Some(winner));
+}
+
+#[tokio::test]
+async fn continuation_replaces_only_the_pause_it_loaded_and_stale_duplicate_gets_winner() {
+ let directory = tempfile::tempdir().unwrap();
+ let persistence = OpenHumanPersistence::new(directory.path().to_path_buf());
+ let key = key();
+ let original = SubagentResume::default();
+ assert_eq!(
+ persistence
+ .save_pause(persisted_pause(key.clone(), "first question", None))
+ .await
+ .unwrap(),
+ SubagentPausePersistenceDisposition::Inserted
+ );
+
+ assert_eq!(
+ persistence
+ .save_pause(persisted_pause(
+ key.clone(),
+ "replacement question",
+ Some(original.clone()),
+ ))
+ .await
+ .unwrap(),
+ SubagentPausePersistenceDisposition::Replaced
+ );
+ assert_eq!(
+ persistence
+ .save_pause(persisted_pause(
+ key.clone(),
+ "stale duplicate question",
+ Some(original),
+ ))
+ .await
+ .unwrap(),
+ SubagentPausePersistenceDisposition::Existing
+ );
+
+ let winner = persistence.load_pause(&key).await.unwrap().unwrap();
+ assert!(matches!(
+ winner.status,
+ SubagentStatus::AwaitingInput(SubagentPause { ref reason, .. })
+ if reason == "replacement question"
+ ));
+}
+
+#[tokio::test]
+async fn task_id_index_retains_scoped_collisions_and_terminal_does_not_reopen_pause() {
+ let directory = tempfile::tempdir().unwrap();
+ let persistence = OpenHumanPersistence::new(directory.path().to_path_buf());
+ let first = scoped_key("root-a", "parent-a", Some("thread-a"));
+ let second = scoped_key("root-b", "parent-b", Some("thread-b"));
+ assert_eq!(
+ persistence
+ .save_pause(persisted_pause(first.clone(), "first", None))
+ .await
+ .unwrap(),
+ SubagentPausePersistenceDisposition::Inserted
+ );
+ assert_eq!(
+ persistence
+ .save_pause(persisted_pause(second.clone(), "second", None))
+ .await
+ .unwrap(),
+ SubagentPausePersistenceDisposition::Inserted
+ );
+ assert!(load_subagent_checkpoint(directory.path(), "task").is_err());
+
+ let mut terminal = SubagentOutcome::cancelled("task");
+ terminal.status = SubagentStatus::Completed;
+ assert_eq!(
+ persistence
+ .record_terminal(&first, &terminal, None)
+ .await
+ .unwrap(),
+ tinyagents_orchestration::subagent::SubagentTerminalPersistenceDisposition::PauseExisting
+ );
+ assert_eq!(
+ persistence
+ .record_terminal(&first, &terminal, Some(&SubagentResume::default()))
+ .await
+ .unwrap(),
+ tinyagents_orchestration::subagent::SubagentTerminalPersistenceDisposition::Inserted
+ );
+ assert_eq!(
+ load_subagent_checkpoint(directory.path(), "task")
+ .unwrap()
+ .task_key,
+ Some(second.clone())
+ );
+ assert!(persistence.load_pause(&first).await.unwrap().is_none());
+ assert!(persistence.load_terminal(&first).await.unwrap().is_some());
+}
+
+#[tokio::test]
+async fn terminal_and_pause_race_leave_only_one_authoritative_state() {
+ let directory = tempfile::tempdir().unwrap();
+ let persistence =
+ std::sync::Arc::new(OpenHumanPersistence::new(directory.path().to_path_buf()));
+ let key = key();
+ let mut terminal = SubagentOutcome::cancelled("task");
+ terminal.status = SubagentStatus::Completed;
+ let (pause, terminal_write) = tokio::join!(
+ persistence.save_pause(persisted_pause(key.clone(), "question", None)),
+ persistence.record_terminal(&key, &terminal, None),
+ );
+ assert!(pause.is_ok());
+ assert_eq!(
+ terminal_write.unwrap(),
+ tinyagents_orchestration::subagent::SubagentTerminalPersistenceDisposition::PauseExisting
+ );
+ assert!(persistence.load_terminal(&key).await.unwrap().is_none());
+ assert!(persistence.load_pause(&key).await.unwrap().is_some());
+ assert!(load_subagent_checkpoint(directory.path(), "task").is_ok());
+}
+
+#[tokio::test]
+async fn host_coalescer_keeps_the_leader_winner_and_cancels_only_the_observer() {
+ let entry = HostInFlight::new();
+ let key = key();
+ let cancelled = tinyagents_harness::CancellationToken::new();
+ cancelled.cancel();
+
+ let observer = entry
+ .wait(&cancelled, &key, "observer-agent")
+ .await
+ .unwrap()
+ .expect("cancelled follower reports an outcome");
+ assert!(matches!(observer.status, SubagentRunStatus::Cancelled));
+ assert_eq!(
+ observer.persistence_disposition,
+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::ObserverCancelled
+ );
+
+ let winner = SubagentRunOutcome {
+ task_id: key.task_id.clone(),
+ agent_id: "leader-agent".into(),
+ output: "durable winner".into(),
+ iterations: 3,
+ elapsed: std::time::Duration::from_millis(42),
+ mode: SubagentMode::Typed,
+ status: SubagentRunStatus::Completed,
+ final_history: Vec::new(),
+ usage: SubagentUsage::default(),
+ artifact_paths: Vec::new(),
+ persistence_disposition:
+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalInserted,
+ };
+ entry.complete(Some(winner)).await;
+
+ let active = tinyagents_harness::CancellationToken::new();
+ let follower = entry
+ .wait(&active, &key, "other-agent")
+ .await
+ .unwrap()
+ .expect("leader result remains available");
+ assert_eq!(follower.output, "durable winner");
+ assert_eq!(follower.agent_id, "leader-agent");
+ assert_eq!(follower.elapsed, std::time::Duration::from_millis(42));
+ assert_eq!(
+ follower.persistence_disposition,
+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalExisting
+ );
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/mod.rs b/crates/openhuman-core/src/agent/subagent_host/mod.rs
new file mode 100644
index 0000000000..4ed5f0090c
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/mod.rs
@@ -0,0 +1,88 @@
+//! OpenHuman adapters for the neutral TinyAgents subagent lifecycle.
+//!
+//! Given an [`super::definition::AgentDefinition`] and a task prompt, the
+//! runner:
+//!
+//! 1. Reads the [`super::fork_context::ParentExecutionContext`] task-local
+//! set by the parent [`crate::agent::OpenHumanSessionHost::turn`].
+//! 2. Resolves the sub-agent's model name (inherit / hint / exact).
+//! 3. Filters the parent's tool registry per `definition.tools`,
+//! `disallowed_tools`, and `skill_filter` (or, in `fork` mode,
+//! inherits the parent's tools verbatim).
+//! 4. Builds a narrow system prompt that strips the sections the
+//! definition asks to omit (`omit_identity`, `omit_memory_context`,
+//! `omit_safety_preamble`).
+//! 5. Runs the child turn on the TinyAgents harness (`ops::graph` →
+//! [`crate::agent::tinyagents::run_turn_via_tinyagents_shared`]) using
+//! the parent's [`crate::inference::provider::Provider`], then
+//! mirrors the child transcript/progress and returns one compact tool result
+//! to the parent.
+//!
+//! This module owns product policy and effects: definition resolution, prompt
+//! assembly, tool narrowing, model selection, workspace/sandbox setup,
+//! artifacts, checkpoints, and progress. `tinyagents_orchestration::subagent`
+//! owns lifecycle ordering, task-key coalescing and mutually-exclusive pause or
+//! terminal persistence.
+//!
+//! ## Layout
+//!
+//! This is a light `mod.rs`: every item below is declared in a sibling
+//! file and re-exported here.
+//!
+//! | File | Contents |
+//! | ----------------- | ----------------------------------------------------------- |
+//! | `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 |
+
+mod autonomous;
+mod extract_tool;
+mod handoff;
+mod lifecycle;
+mod ops;
+mod tool_prep;
+mod types;
+
+#[cfg(test)]
+#[path = "tool_ranking_tests.rs"]
+mod tool_ranking_tests;
+
+#[cfg(test)]
+#[path = "lifecycle_tests.rs"]
+mod lifecycle_tests;
+
+// Public API — the entry point and the shapes it returns.
+pub use autonomous::{
+ autonomous_iter_cap, subagent_iter_cap_with_autonomous_lift, with_autonomous_iter_cap,
+};
+pub(crate) use lifecycle::load_subagent_checkpoint;
+pub use lifecycle::{
+ continue_subagent, continue_subagent_with_parent, run_subagent, run_subagent_with_parent,
+ OpenHumanSubagentHost,
+};
+pub(crate) use ops::is_safe_task_id;
+pub use types::{
+ SubagentCheckpointData, SubagentMode, SubagentRunError, SubagentRunOptions, SubagentRunOutcome,
+ SubagentRunStatus, SubagentUsage,
+};
+
+// Crate-internal re-exports: `agent::debug` calls the text-mode protocol
+// renderer. The other `tool_prep` helpers are used only inside this module.
+pub(crate) use tool_prep::build_text_mode_tool_instructions;
+
+// 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};
+
+// `user_is_signed_in_to_composio` is the mode-aware "can the user call
+// composio at all?" probe added in Wave 2 (#1710). Re-exported here so
+// non-composio probe sites (registration gates, heartbeat telemetry)
+// can call it as
+// `crate::agent::subagent_host::user_is_signed_in_to_composio`
+// without reaching into a private sibling module.
+pub(crate) use ops::user_is_signed_in_to_composio;
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/checkpoint.rs b/crates/openhuman-core/src/agent/subagent_host/ops/checkpoint.rs
new file mode 100644
index 0000000000..9ee6166ed5
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/checkpoint.rs
@@ -0,0 +1,80 @@
+//! Sub-agent cap-hit checkpoint summary.
+//!
+//! When the iteration cap is hit, summarize the run-so-far into a resumable
+//! checkpoint (so the delegating agent can continue from partial progress)
+//! instead of erroring. Falls back to a deterministic digest summary if the
+//! summarization call fails or returns no prose.
+
+use crate::inference::provider::UsageInfo;
+use std::sync::Arc;
+use tinyinference_llm::message::Message;
+use tinyinference_llm::model::{ChatModel, ModelRequest};
+
+/// A checkpoint result. `usage`, when present, is the provider usage from the
+/// summary call so the caller can fold it into sub-agent token/cost accounting.
+pub(super) struct SubagentCheckpointOutcome {
+ pub(super) text: String,
+ pub(super) usage: Option<UsageInfo>,
+}
+
+/// Sub-agent cap-hit summary: when the iteration cap is hit, summarize the
+/// run-so-far into a resumable checkpoint (so the delegating agent can continue
+/// from partial progress) instead of erroring. Falls back to a deterministic
+/// digest summary if the summarization call fails or returns no prose.
+///
+/// The summary runs on a crate [`ChatModel`] (built from the turn's
+/// [`TurnModelSource`](crate::agent::tinyagents::TurnModelSource) — model +
+/// temperature baked in), so the checkpoint no longer names the `Provider` trait
+/// (issue #4249, Phase 3 / Motion A).
+pub(super) struct SubagentCheckpoint {
+ pub(super) chat_model: Arc<dyn ChatModel<()>>,
+ pub(super) agent_id: String,
+ pub(super) max_output_tokens: u32,
+}
+
+impl SubagentCheckpoint {
+ pub(super) async fn summarize_cap_hit(
+ &self,
+ digest: &str,
+ max_iterations: usize,
+ ) -> anyhow::Result<SubagentCheckpointOutcome> {
+ let agent_id = &self.agent_id;
+ let deterministic = format!(
+ "I reached my tool-call limit ({max_iterations} steps) before finishing this task. \
+ Progress so far (tool calls + results):\n{digest}\n\nThe task is incomplete — the above is \
+ what I accomplished; continue from here."
+ );
+ let summary_input = vec![Message::user(format!(
+ "You are sub-agent `{agent_id}` and reached your tool-call limit before finishing. Here are \
+ the tool calls you made and their results — compile a brief progress checkpoint (what you \
+ accomplished, what still remains) for the agent that delegated to you. Do not call tools.\n\n{digest}"
+ ))];
+ // Bounded progress-summary turn; the cap also keeps the reservation-pricing
+ // pre-flight realistic (TAURI-RUST-C62). Temperature is baked into the model.
+ let request = ModelRequest::new(summary_input).with_max_tokens(self.max_output_tokens);
+ match self.chat_model.invoke(&(), request).await {
+ Ok(resp) => {
+ let usage = crate::agent::tinyagents::model::usage_info_from_response(&resp);
+ let raw = resp.text();
+ let (prose, _) = tinytools_agent::parse_tool_calls(&raw);
+ let text = if prose.trim().is_empty() {
+ deterministic
+ } else {
+ prose
+ };
+ Ok(SubagentCheckpointOutcome { text, usage })
+ }
+ Err(e) => {
+ tracing::warn!(
+ agent_id = %self.agent_id,
+ error = %e,
+ "[subagent_host] checkpoint summary call failed — using deterministic fallback"
+ );
+ Ok(SubagentCheckpointOutcome {
+ text: deterministic,
+ usage: None,
+ })
+ }
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph.rs
new file mode 100644
index 0000000000..7fe34dd1f5
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph.rs
@@ -0,0 +1,71 @@
+//! The **sub-agent turn graph** (issue #4249).
+//!
+//! Per the per-folder `graph.rs` convention, this module owns the sub-agent
+//! folder's graph definition, its available tools, and its summarization step —
+//! all thin over the shared tinyagents seam
+//! ([`run_turn_via_tinyagents_shared`]).
+//!
+//! **Graph.** A single agent-loop turn driven by the tinyagents harness: the
+//! model is called, requested tools run, and the loop repeats until the model
+//! returns without further tool calls or the iteration budget is exhausted. The
+//! canonical sub-agent turn path (the legacy `run_inner_loop` / `run_turn_engine`
+//! are removed); `run_typed_mode` calls it unconditionally.
+//!
+//! **Available tools.** The sub-agent reuses the parent's harness tools plus the
+//! per-spawn dynamic tools, advertised via the canonical shared-tool adapter over the shared
+//! `Arc<Vec<Box<dyn Tool>>>` tool sets (`[dynamic_tools, parent_tools]` — dynamic
+//! first so a shadowing dynamic tool executes, matching advertisement), filtered
+//! by `allowed_names`. `ask_user_clarification` is the early-exit tool.
+//!
+//! **Summarization.** When the sub-agent model's effective context window is
+//! known, the shared seam installs the context-window summarization step
+//! (`tinyagents::summarize`) ahead of the deterministic front-trim — see
+//! [`run_subagent_via_graph`], which resolves the window before dispatch.
+//!
+//! It mirrors the original seams: child progress deltas (`Subagent*` events incl.
+//! thinking), mid-flight steering, the `ask_user_clarification` early-exit pause,
+//! and a graceful model-call-cap checkpoint summary
+//! (`SubagentCheckpoint::summarize_cap_hit`).
+
+// Split by responsibility rather than by line count:
+//
+// - [`dispatch`] — drives one sub-agent turn through the shared tinyagents
+// seam, builds its context middleware, and folds a cap-hit checkpoint
+// summary back into the result.
+// - [`transcript`] — persists a sub-agent turn's (or a failed run's) raw
+// transcript to `session_raw`.
+// - [`worker_mirror`] — mirrors a sub-agent turn's conversation onto its
+// spawn's worker thread.
+mod dispatch;
+mod transcript;
+mod worker_mirror;
+
+// Re-exported under the original flat `graph::` path so external callers
+// (`ops/mod.rs`, `ops/runner.rs`, `graph_tests.rs`'s `use super::*`) are
+// unaffected by the responsibility split.
+#[cfg(test)]
+pub(super) use dispatch::inherited_thread_id;
+pub(crate) use dispatch::run_agent_turn_request_via_default_graph;
+pub(super) use dispatch::{run_subagent_via_graph, AggregatedUsage};
+
+// Only what `graph_tests.rs`'s `use super::*` still needs directly (the rest
+// of the original flat imports now live with the code that uses them, in
+// `dispatch.rs` / `transcript.rs` / `worker_mirror.rs`).
+#[cfg(test)]
+use crate::agent::messages::{ChatMessage, ConversationMessage};
+#[cfg(test)]
+use crate::agent::progress::AgentProgress;
+#[cfg(test)]
+use crate::inference::tokenjuice::AgentTokenjuiceCompression;
+#[cfg(test)]
+use std::collections::HashSet;
+#[cfg(test)]
+use std::sync::Arc;
+#[cfg(test)]
+use tinytools::Tool;
+#[cfg(test)]
+use worker_mirror::{mirror_worker_thread, mirror_worker_thread_from_history};
+
+#[cfg(test)]
+#[path = "graph_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
new file mode 100644
index 0000000000..1e093d1e2d
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
@@ -0,0 +1,703 @@
+//! The sub-agent turn dispatch: driving one graph turn through the shared
+//! tinyagents seam, building its context middleware, and folding a cap-hit
+//! checkpoint summary back into the result.
+
+use crate::agent::subagent_host::ops::checkpoint;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use crate::agent::harness::agent_graph::{AgentTurnRequest, AgentTurnResult, AgentTurnUsage};
+use crate::agent::messages::{ChatMessage, ConversationMessage};
+use crate::agent::progress::AgentProgress;
+use crate::agent::subagent_host::types::SubagentRunError;
+use crate::agent::tinyagents::{run_turn_via_tinyagents_shared, SubagentScope};
+use crate::inference::tokenjuice::AgentTokenjuiceCompression;
+use tinyagents_harness::run_queue::RunQueue;
+use tinytools::WorkspaceDescriptor;
+use tinytools::{Tool, ToolSpec};
+
+use super::transcript::persist_subagent_transcript;
+use super::worker_mirror::mirror_worker_thread;
+
+/// Cumulative usage stats gathered across a sub-agent graph run.
+#[derive(Debug, Clone, Default)]
+pub(in super::super) struct AggregatedUsage {
+ pub(in super::super) input_tokens: u64,
+ pub(in super::super) output_tokens: u64,
+ pub(in super::super) cached_input_tokens: u64,
+ pub(in super::super) charged_amount_usd: f64,
+}
+
+/// Run an assembled custom per-agent turn through the shared default sub-agent
+/// leaf. Bespoke `AgentGraph::Custom` graphs use this after their own routing
+/// nodes so transcript persistence, worker-thread mirroring, progress events,
+/// handoff middleware, cap summaries, and usage aggregation stay byte-for-byte
+/// on the default path.
+pub(crate) async fn run_agent_turn_request_via_default_graph(
+ req: AgentTurnRequest,
+) -> Result<AgentTurnResult, SubagentRunError> {
+ let AgentTurnRequest {
+ turn_model_source,
+ model,
+ temperature,
+ mut history,
+ parent_tools,
+ dynamic_tools,
+ specs,
+ allowed_names,
+ max_iterations,
+ run_queue,
+ on_progress,
+ agent_id,
+ task_id,
+ extended_policy,
+ thread_id,
+ run_context,
+ worker_thread_id,
+ workspace_dir,
+ workspace_descriptor,
+ max_output_tokens,
+ model_vision,
+ transcript_stem,
+ provider_label,
+ handoff_cache,
+ tokenjuice_compression,
+ config,
+ } = req;
+
+ let (output, iterations, usage, early_exit_tool, hit_cap, breaker_halt) =
+ run_subagent_via_graph(
+ turn_model_source,
+ &model,
+ temperature,
+ &mut history,
+ parent_tools,
+ dynamic_tools,
+ specs,
+ allowed_names,
+ max_iterations,
+ run_queue,
+ on_progress,
+ &agent_id,
+ &task_id,
+ extended_policy,
+ thread_id,
+ run_context,
+ worker_thread_id,
+ workspace_dir,
+ workspace_descriptor,
+ max_output_tokens,
+ model_vision,
+ &transcript_stem,
+ &provider_label,
+ handoff_cache,
+ tokenjuice_compression,
+ config.as_deref(),
+ )
+ .await?;
+
+ Ok(AgentTurnResult {
+ history,
+ output,
+ iterations,
+ usage: AgentTurnUsage {
+ input_tokens: usage.input_tokens,
+ output_tokens: usage.output_tokens,
+ cached_input_tokens: usage.cached_input_tokens,
+ charged_amount_usd: usage.charged_amount_usd,
+ },
+ early_exit_tool,
+ hit_cap,
+ breaker_halt,
+ })
+}
+
+/// Drive a sub-agent turn on the tinyagents harness. Returns
+/// `(text, model_calls, AggregatedUsage, early_exit_tool, hit_cap)` — `hit_cap`
+/// is `true` when the run stopped at the model-call cap with work still pending
+/// (the caller surfaces this as `SubagentRunStatus::Incomplete`, #4096).
+#[allow(clippy::too_many_arguments)]
+pub(in super::super) async fn run_subagent_via_graph(
+ source: crate::agent::tinyagents::TurnModelSource,
+ model: &str,
+ temperature: f64,
+ history: &mut Vec<ChatMessage>,
+ parent_tools: Arc<Vec<Box<dyn Tool>>>,
+ dynamic_tools: Vec<Box<dyn Tool>>,
+ specs: Vec<ToolSpec>,
+ allowed_names: HashSet<String>,
+ max_iterations: usize,
+ run_queue: Option<Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
+ on_progress: Option<tokio::sync::mpsc::Sender<AgentProgress>>,
+ agent_id: &str,
+ task_id: &str,
+ extended_policy: bool,
+ thread_id: Option<String>,
+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
+ worker_thread_id: Option<String>,
+ workspace_dir: std::path::PathBuf,
+ workspace_descriptor: Option<WorkspaceDescriptor>,
+ max_output_tokens: u32,
+ model_vision: bool,
+ // Transcript-persistence provenance: the resolved child transcript stem
+ // (`{parent_chain}__{child_session_key}`) and the provider label (the parent
+ // turn's event channel) so the child's raw transcript lands in `session_raw`
+ // with the right stem + provider/model meta — parity with the removed
+ // `SubagentObserver::persist_transcript`.
+ transcript_stem: &str,
+ provider_label: &str,
+ // Progressive-disclosure handoff cache (integrations_agent with a resolved
+ // toolkit); `Some` installs the `HandoffMiddleware` that stashes oversized
+ // tool results and shares the cache with the `extract_from_result` tool.
+ handoff_cache: Option<std::sync::Arc<crate::agent::subagent_host::ResultHandoffCache>>,
+ // Agent-level TokenJuice profile (`definition.effective_tokenjuice_compression()`,
+ // #4466). Threaded into the sub-agent `TurnContextMiddleware` so sub-agent
+ // tool outputs get the same content-aware compaction the chat path applies
+ // instead of a blunt byte-cap truncation.
+ tokenjuice_compression: AgentTokenjuiceCompression,
+ // Host config for the `[context]` middleware knobs. Passed in rather than
+ // loaded here (plan-agents Phase 3): this function is slated to move into
+ // TinyAgents, where there is no config file. `None` yields the safe
+ // byte-cap-only defaults.
+ config: Option<&crate::config::Config>,
+) -> Result<
+ (
+ String,
+ usize,
+ AggregatedUsage,
+ Option<String>,
+ bool,
+ // Breaker-halt reason (#4466): `Some` when the repeated-failure /
+ // repeat-progress circuit breaker stopped the run; the caller reports
+ // `Incomplete` instead of `Completed`.
+ Option<String>,
+ ),
+ SubagentRunError,
+> {
+ // One resolved thread identity drives every child-facing boundary. An
+ // explicit worker/task thread deliberately replaces the inherited parent;
+ // otherwise a child remains in its parent's conversation. Do this before
+ // constructing *any* model so managed requests, transcript metadata, and
+ // the child carrier cannot disagree.
+ let thread_id = inherited_thread_id(run_context.thread_id.clone(), thread_id);
+ tracing::info!(
+ model,
+ max_iterations,
+ agent_id,
+ task_id,
+ model_vision,
+ observed = on_progress.is_some(),
+ "[subagent_host:graph] routing sub-agent turn through tinyagents harness"
+ );
+ // `specs` is derived from the registry inside the runner; the tinyagents
+ // adapters advertise each tool via its own `spec()`, so it's unused here.
+ let _ = &specs;
+
+ // Child-progress attribution: mirror this sub-agent's iterations / tool calls
+ // / text + thinking deltas as `Subagent*` events scoped to (`agent_id`,
+ // `task_id`) so the parent thread can nest them under the live subagent row.
+ // Always set (not gated on `on_progress`): the scope also tells the shared
+ // seam this is a sub-agent turn, so the unknown-tool recovery uses the
+ // sub-agent wording. With no progress sink the scoped events simply have
+ // nowhere to go, which is harmless.
+ let subagent_scope = Some(SubagentScope {
+ agent_id: agent_id.to_string(),
+ task_id: task_id.to_string(),
+ extended_policy,
+ });
+
+ // A standalone summarizer model for the cap-hit checkpoint call below (the
+ // turn's own model set is consumed by the run). Built off the same source, so
+ // the checkpoint invokes a crate `ChatModel` without naming `Provider`
+ // (issue #4249, Phase 3 / Motion A).
+ let summary_model = source.build_summarizer(model, temperature, thread_id.as_deref())?;
+
+ // Resolve the sub-agent model's effective context window so the harness runs
+ // the context-window summarization step (issue #4249) on sub-agent turns too.
+ // A long-running / resumed sub-agent (worker threads, durable sessions) can
+ // accumulate a transcript past its own window; summarize before each model
+ // call rather than relying solely on the parent's one-time trim.
+ let context_window = source.effective_context_window(model).await;
+
+ // Build the child turn's crate `ChatModel` set from the source; capability
+ // reads (vision/native-tools) + telemetry id now come off the built bundle,
+ // so the sub-agent path names crate model types only.
+ let turn_models = source.build(model, temperature, context_window, thread_id.as_deref())?;
+
+ // Vision forwarding (parity with the legacy `run_inner_loop`): rehydrate
+ // `[IMAGE:…]` placeholders in the sub-agent's history when either the model
+ // advertises vision or the sub-agent model is user-flagged as vision-capable
+ // (BYOK/custom). The expanded copy is provider-only — the persisted `history`
+ // written back below keeps the original markers.
+ let dispatch_history = if (turn_models.supports_vision() || model_vision)
+ && crate::agent::multimodal::has_image_placeholders(history)
+ {
+ crate::agent::multimodal::rehydrate_image_placeholders(history)
+ } else {
+ history.clone()
+ };
+
+ // Build the sub-agent's context middleware from the live `[context]` config +
+ // the agent's TokenJuice profile (#4466), matching how the chat path wires
+ // `TurnContextMiddleware` (session/turn/core.rs). The migrated sub-agent path
+ // had regressed to `TurnContextMiddleware::defaults()` — compression Off — so
+ // sub-agent tool outputs took a blunt 16 KiB truncation instead of the
+ // content-aware TokenJuice compaction the definition asked for. Honor the
+ // `[context]` enabled / autocompact opt-outs, microcompact keep-recent, and
+ // per-result byte budget too, so a sub-agent turn compacts like a chat turn.
+ let context_mw = build_subagent_context_mw(tokenjuice_compression, config);
+
+ // Live transcript snapshot sink (#4466): the harness owns the working message
+ // vector and drops it on a mid-run `Err`, so a failed sub-agent run used to
+ // persist NOTHING (breaking `learning/transcript_ingest`) and leave an empty
+ // worker thread. Attach a snapshot middleware that mirrors each `before_model`
+ // request's transcript here, so the error path below can still persist the
+ // rounds that completed before the failure.
+ let transcript_snapshot = crate::agent::tinyagents::TranscriptSnapshotSink::default();
+ // The seeded history is always kept; only rounds past it are split into
+ // accepted and unanswered on failure (#6281).
+ transcript_snapshot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .request_base_len = dispatch_history.len();
+
+ // A sub-agent turn runs *nested inside* the parent agent's turn (parent
+ // harness → spawn_subagent tool → here), so the child's full
+ // `run_turn_via_tinyagents_shared` future would otherwise sit on the parent's
+ // poll stack. Heap-allocate it (as the legacy `run_inner_loop` did) so the
+ // parent+child harness drives don't overflow the stack.
+ // Native-tool support drives the durable-history suffix dispatcher; capture it
+ // (and the telemetry id) before `turn_models` is moved into the runner.
+ let native_tools = turn_models.native_tools();
+ let provider_id = turn_models.provider_id().to_string();
+ // `SubagentRunOptions` already carries the child context built at the tool
+ // dispatch boundary. Reusing that owned value preserves its immediate
+ // parent-ledger link; forking again here would hide nested child usage in a
+ // second, unreachable ledger.
+ let mut child_context = run_context;
+ // A parallel task may omit `thread_id`; that means inherit the parent
+ // conversation, not erase it. Only an explicit task thread may replace
+ // the typed carrier's inherited affinity.
+ child_context.thread_id = thread_id.clone();
+ child_context.progress = on_progress.clone().or(child_context.progress);
+ child_context.workspace = workspace_descriptor.clone().or(child_context.workspace);
+ let run_result = Box::pin(run_turn_via_tinyagents_shared(
+ child_context,
+ turn_models,
+ provider_id,
+ model,
+ dispatch_history,
+ // Dynamic (per-spawn) tools first so a dynamic tool that intentionally
+ // shadows a parent-registry tool of the same name is the one that
+ // *executes* — matching the advertisement order (`dedup_tool_specs_by_name`
+ // lists dynamic specs before parent specs in `runner.rs`). The shared
+ // adapter resolves a name by scanning the sets in order, so a
+ // parent-first order would run the parent impl for a shadowed name.
+ vec![Arc::new(dynamic_tools), parent_tools],
+ // Fail-closed (issue #4452): a sub-agent ALWAYS carries a concrete,
+ // resolved allowlist (`allowed_names`), so pass it as `Some(..)`. An empty
+ // set is therefore a genuine deny-all — a tool-less agent
+ // (`ToolScope::Named([])`), a zero-match `skill_filter`, or a `named` list
+ // that resolved to nothing registers ZERO tools instead of implicitly
+ // inheriting the parent's full surface (shell/file-write/spawn).
+ Some(allowed_names),
+ max_iterations,
+ subagent_scope,
+ // Resolved above — drives the sub-agent context-window summarization step.
+ context_window,
+ // Mid-flight steering: forward queued steer messages into the run.
+ run_queue,
+ // Pause + checkpoint when the child asks the user a clarifying question.
+ &["ask_user_clarification"],
+ // Pause gracefully at the model-call cap so we can summarize a resumable
+ // checkpoint (below) instead of erroring — legacy cap-summary parity.
+ true,
+ // Bound the sub-agent's per-call output at its configured budget.
+ Some(max_output_tokens),
+ // Context middlewares (#4466): config-sourced TokenJuice compaction +
+ // tool-result byte cap + microcompact + summarization opt-outs (built
+ // above), plus the progressive-disclosure handoff when a cache is
+ // attached, plus the live transcript-snapshot sink for error recovery.
+ {
+ let mut mw = context_mw;
+ if let Some(cache) = handoff_cache {
+ mw.handoff = Some(crate::agent::tinyagents::HandoffConfig {
+ cache,
+ agent_id: agent_id.to_string(),
+ task_id: task_id.to_string(),
+ });
+ }
+ mw.transcript_snapshot = Some(transcript_snapshot.clone());
+ mw
+ },
+ // Sub-agents gate via their own SubagentToolSource policy path, not the
+ // session `.tool_policy()`; no enforcement threaded here.
+ None,
+ // Sub-agent turns run tools with external effects; not a deterministic
+ // internal run, so response caching stays off (safe default).
+ false,
+ // #4457 (defect C): irrelevant for sub-agents — they carry a
+ // `subagent_scope`, so the seam never emits a top-level `TurnCompleted`
+ // (they report via `Subagent*` events). Pass `false` for clarity.
+ false,
+ ))
+ .await;
+
+ let mut outcome = match run_result {
+ Ok(outcome) => outcome,
+ Err(err) => {
+ // #4466: the harness dropped its partial transcript, but the snapshot
+ // middleware mirrored every completed round. Persist those rounds to
+ // `session_raw` (so `learning/transcript_ingest` can still read a
+ // failed run) and mirror them onto the worker thread, THEN surface the
+ // error. Previously the `?`-return skipped both persistence steps, so
+ // a failed run left no transcript and an empty worker thread.
+ let mapped = map_tinyagents_subagent_error(err);
+ // Persist the caller's original history plus only what a provider
+ // accepted as structured messages: a request rejected for malformed
+ // tool history must not be replayed by a resumed sub-agent, and the
+ // snapshot's own seed is the provider-bound copy with rehydrated
+ // images. The unanswered suffix rides the failure marker as text
+ // (#6281).
+ let (recovered, unanswered_steps, recovered_usage, completed_rounds) = {
+ let snapshot = transcript_snapshot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let (recovered, unanswered) =
+ super::transcript::failed_run_history(history.as_slice(), &snapshot);
+ let usage = AggregatedUsage {
+ input_tokens: snapshot.input_tokens,
+ output_tokens: snapshot.output_tokens,
+ cached_input_tokens: snapshot.cached_input_tokens,
+ charged_amount_usd: crate::platform::cost::catalog::estimate_cost_usd(
+ model,
+ snapshot.input_tokens,
+ snapshot.output_tokens,
+ snapshot.cached_input_tokens,
+ ),
+ };
+ (recovered, unanswered, usage, snapshot.model_calls)
+ };
+ tracing::warn!(
+ agent_id,
+ task_id,
+ error = %mapped,
+ recovered_rounds = recovered.len(),
+ unanswered_steps = unanswered_steps.is_some(),
+ "[subagent_host:graph] sub-agent run errored; persisting recovered transcript before returning (#4466)"
+ );
+ super::transcript::persist_failed_run(
+ &workspace_dir,
+ transcript_stem,
+ agent_id,
+ task_id,
+ provider_label,
+ model,
+ &recovered,
+ &recovered_usage,
+ thread_id.as_deref(),
+ unanswered_steps.as_deref(),
+ completed_rounds,
+ context_window.unwrap_or(0),
+ if native_tools { "native" } else { "xml" },
+ worker_thread_id.as_deref(),
+ &mapped,
+ );
+ return Err(mapped);
+ }
+ };
+
+ // Write the final conversation back so the caller can checkpoint / persist.
+ // Keep the original (un-expanded) prior turns and append only this turn's typed
+ // suffix, serialized with the matching dispatcher so a native tool round
+ // persists as the `{content, tool_calls}` / `{tool_call_id, content}` envelope
+ // (re-parsed by `convert::chat_message_to_message` next turn) instead of an
+ // assistant with no `tool_calls` followed by an orphan `tool` row. Appending
+ // the typed `outcome.conversation` (messages-since-last-user) also avoids
+ // indexing a post-trim `outcome.history` with the pre-trim length, and the
+ // durable `[IMAGE:…]` markers stay put since the prior user turns are untouched.
+ let suffix = if native_tools {
+ crate::agent::message_convert::provider_messages_from_conversation(
+ &tinytools_agent::dialect::NativeDialect,
+ &outcome.conversation,
+ )
+ } else {
+ crate::agent::message_convert::provider_messages_from_conversation(
+ &tinytools_agent::dialect::XmlDialect,
+ &outcome.conversation,
+ )
+ };
+ history.extend(suffix);
+
+ let mut usage = AggregatedUsage {
+ input_tokens: outcome.input_tokens,
+ output_tokens: outcome.output_tokens,
+ // Carry the child's cached-prefix tokens + estimated cost (the turn
+ // outcome now reports both) so sub-agent spend rolls into the parent
+ // instead of being recorded as uncached and $0.
+ cached_input_tokens: outcome.cached_input_tokens,
+ charged_amount_usd: outcome.charged_amount_usd,
+ };
+
+ // Cap hit with work still pending: summarize the run-so-far into a resumable
+ // checkpoint (the delegating agent continues from partial progress) rather
+ // than surfacing an empty/partial answer — the legacy `SubagentCheckpoint`.
+ if outcome.hit_cap {
+ let digest = build_cap_digest(&outcome.conversation, &outcome.tool_outcomes);
+ let strategy = checkpoint::SubagentCheckpoint {
+ chat_model: summary_model.clone(),
+ agent_id: agent_id.to_string(),
+ // The checkpoint summary call's output cap. #4469 item 5: honour this
+ // sub-agent definition's own per-call output budget (the same
+ // `max_output_tokens` bounding every task model call above) instead of
+ // the process-global `AGENT_TURN_MAX_OUTPUT_TOKENS` floor, so a
+ // definition that raised or lowered its output cap is respected by the
+ // cap-summary call too.
+ max_output_tokens,
+ };
+ match strategy.summarize_cap_hit(&digest, max_iterations).await {
+ Ok(co) => {
+ if let Some(u) = co.usage {
+ // Fold ALL four token fields (the legacy cap-summary folded
+ // cached tokens too, not just input/output), then price the
+ // call and feed the global cost tracker directly (#4467,
+ // item 2). The checkpoint summary call bypasses the harness so
+ // the observability bridge never sees it — without this record
+ // its cached tokens are lost and it costs $0 in the footer /
+ // transcript meta / cost dashboard.
+ usage.input_tokens += u.input_tokens;
+ usage.output_tokens += u.output_tokens;
+ usage.cached_input_tokens += u.cached_input_tokens;
+ let call_cost =
+ if u.charged_amount_usd.is_finite() && u.charged_amount_usd > 0.0 {
+ u.charged_amount_usd
+ } else {
+ crate::platform::cost::catalog::estimate_cost_usd(
+ model,
+ u.input_tokens,
+ u.output_tokens,
+ u.cached_input_tokens,
+ )
+ };
+ usage.charged_amount_usd += call_cost;
+ crate::platform::cost::record_provider_usage(
+ model,
+ &crate::inference::provider::UsageInfo {
+ input_tokens: u.input_tokens,
+ output_tokens: u.output_tokens,
+ context_window: u.context_window,
+ cached_input_tokens: u.cached_input_tokens,
+ cache_creation_tokens: u.cache_creation_tokens,
+ reasoning_tokens: u.reasoning_tokens,
+ charged_amount_usd: call_cost,
+ },
+ );
+ tracing::debug!(
+ agent_id,
+ input_tokens = u.input_tokens,
+ output_tokens = u.output_tokens,
+ cached_input_tokens = u.cached_input_tokens,
+ call_cost,
+ "[subagent] cap-hit summary call folded + priced + recorded into cost tracker (#4467, item 2)"
+ );
+ }
+ outcome.text = co.text;
+ }
+ Err(e) => return Err(SubagentRunError::Provider(e)),
+ }
+ }
+
+ // Persist the sub-agent's raw transcript to `session_raw` (parity with the
+ // removed `SubagentObserver::persist_transcript`). The graph runner replaced
+ // the observer but only mirrored to the worker thread, so per-child
+ // transcripts stopped being written — breaking downstream learning ingestion
+ // (`learning/transcript_ingest`, which reads `session_raw/*.jsonl`).
+ // On a cap-hit / early-exit, `outcome.text` is the checkpoint (or clarifying
+ // question) that stands in for a final assistant turn — append it so the
+ // persisted transcript reflects the actual final state, not the pre-checkpoint
+ // history. `history` already carries this turn's typed suffix.
+ let transcript_history;
+ let history_for_transcript: &[ChatMessage] = if (outcome.hit_cap
+ || outcome.early_exit_tool.is_some())
+ && !outcome.text.trim().is_empty()
+ {
+ transcript_history = {
+ let mut messages = history.clone();
+ messages.push(ChatMessage::assistant(outcome.text.clone()));
+ messages
+ };
+ &transcript_history
+ } else {
+ history.as_slice()
+ };
+ persist_subagent_transcript(
+ &workspace_dir,
+ transcript_stem,
+ agent_id,
+ task_id,
+ provider_label,
+ model,
+ history_for_transcript,
+ &usage,
+ thread_id.as_deref(),
+ context_window.unwrap_or(0),
+ // Match the dispatcher the history was actually serialized with (text-mode
+ // integrations turns write XML), and the real iteration count.
+ if native_tools { "native" } else { "xml" },
+ outcome.model_calls as u32,
+ );
+
+ // Mirror this turn's conversation to the spawn's worker thread (when one is
+ // attached), matching the legacy `SubagentObserver`: assistant intents +
+ // final answer as `agent` messages, tool results as `user` messages. The
+ // initial user prompt was already written when the worker thread was created.
+ if let Some(thread_id) = worker_thread_id {
+ mirror_worker_thread(
+ &workspace_dir,
+ &thread_id,
+ agent_id,
+ task_id,
+ &outcome.conversation,
+ // On a cap/early-exit, `outcome.text` is the checkpoint/question that
+ // replaced (or stands in for) a final assistant turn.
+ if outcome.hit_cap || outcome.early_exit_tool.is_some() {
+ Some(outcome.text.as_str())
+ } else {
+ None
+ },
+ );
+ }
+
+ // On an early-exit (`ask_user_clarification`), `outcome.text` is the question
+ // and the runner checkpoints + returns AwaitingUser. `None` = ran to a final
+ // answer (or a cap-hit checkpoint summary).
+ Ok((
+ outcome.text,
+ outcome.model_calls,
+ usage,
+ outcome.early_exit_tool,
+ outcome.hit_cap,
+ // #4466: propagate a circuit-breaker halt so the runner reports Incomplete.
+ outcome.breaker_halt,
+ ))
+}
+
+/// A task-specific thread explicitly routes a worker; an absent task thread
+/// leaves the parent run's transcript affinity intact.
+pub(crate) fn inherited_thread_id(
+ parent_thread_id: Option<String>,
+ task_thread_id: Option<String>,
+) -> Option<String> {
+ task_thread_id.or(parent_thread_id)
+}
+
+/// Build the sub-agent turn's [`TurnContextMiddleware`] from the live
+/// `[context]` config and the agent's TokenJuice profile (#4466), mirroring the
+/// chat path (`session/turn/core.rs`). Falls back to
+/// [`TurnContextMiddleware::defaults`] when the config can't be loaded so a
+/// config glitch degrades to the safe (byte-cap-only) behavior rather than
+/// erroring the run.
+fn build_subagent_context_mw(
+ tokenjuice_compression: AgentTokenjuiceCompression,
+ config: Option<&crate::config::Config>,
+) -> crate::agent::tinyagents::TurnContextMiddleware {
+ let mut mw = crate::agent::tinyagents::TurnContextMiddleware::defaults();
+ // Always thread the agent's compression profile — even on the config-default
+ // path — so the definition's TokenJuice choice is honored.
+ mw.tokenjuice_compression = tokenjuice_compression;
+ match config {
+ Some(config) => {
+ mw.runtime_config = Some(Arc::new(config.clone()));
+ let ctx = &config.context;
+ // TokenJuice content-aware compaction gates on the same master
+ // `[context].compaction_enabled` the chat path reads
+ // (`ContextManager::compaction_enabled`).
+ mw.tokenjuice_compaction_enabled = ctx.compaction_enabled;
+ mw.tool_result_budget_bytes = ctx.tool_result_budget_bytes;
+ // Microcompact keep-recent is `0` (disabled) unless microcompact is on.
+ mw.microcompact_keep_recent = if ctx.microcompact_enabled {
+ ctx.microcompact_keep_recent
+ } else {
+ 0
+ };
+ // Summarization step honors the `[context].enabled` + autocompact
+ // opt-outs, same as `ContextManager::autocompact_enabled`.
+ mw.autocompact_enabled = ctx.enabled && ctx.autocompact_enabled;
+ tracing::debug!(
+ tokenjuice_compaction_enabled = mw.tokenjuice_compaction_enabled,
+ compression = ?mw.tokenjuice_compression,
+ tool_result_budget_bytes = mw.tool_result_budget_bytes,
+ microcompact_keep_recent = mw.microcompact_keep_recent,
+ autocompact_enabled = mw.autocompact_enabled,
+ "[subagent_host:graph] built sub-agent context middleware from config (#4466)"
+ );
+ }
+ None => {
+ tracing::debug!(
+ "[subagent_host:graph] no config available building sub-agent context mw; using defaults + compression profile"
+ );
+ }
+ }
+ mw
+}
+
+fn map_tinyagents_subagent_error(err: anyhow::Error) -> SubagentRunError {
+ match err.downcast::<SubagentRunError>() {
+ Ok(run_err) => run_err,
+ Err(err) => SubagentRunError::Provider(err),
+ }
+}
+
+/// Build the `tool → outcome` digest the cap-hit summary call summarizes, in the
+/// legacy `- {name} [{ok|failed}]: {output}` format (engine `run_tool_digest`),
+/// pairing each tool result back to its call by id. Per-tool success is derived
+/// from the turn's captured [`ToolCallOutcome`]s (#4467, item 7) rather than
+/// reported optimistically as `ok`: a result whose call has no captured outcome
+/// — e.g. a hallucinated/unknown tool the crate recovered without running
+/// `after_tool` — is marked `failed`, so the summary no longer tells the model
+/// every call succeeded.
+fn build_cap_digest(
+ conversation: &[ConversationMessage],
+ tool_outcomes: &[crate::agent::tinyagents::ToolCallOutcome],
+) -> String {
+ use std::collections::HashMap;
+ use std::fmt::Write as _;
+
+ // call_id -> tool name, from this turn's assistant tool-call rounds.
+ let mut names: HashMap<&str, &str> = HashMap::new();
+ for msg in conversation {
+ if let ConversationMessage::AssistantToolCalls { tool_calls, .. } = msg {
+ for call in tool_calls {
+ names.insert(call.id.as_str(), call.name.as_str());
+ }
+ }
+ }
+
+ // call_id -> success, from the captured per-call outcomes.
+ let success_by_id: HashMap<&str, bool> = tool_outcomes
+ .iter()
+ .map(|o| (o.call_id.as_str(), o.success))
+ .collect();
+
+ let mut out = String::new();
+ for msg in conversation {
+ if let ConversationMessage::ToolResults(results) = msg {
+ for r in results {
+ let name = names
+ .get(r.tool_call_id.as_str())
+ .copied()
+ .unwrap_or("tool");
+ // Missing outcome → `false` (unknown/hallucinated tool): honest
+ // failed status rather than an optimistic `[ok]`.
+ let ok = success_by_id
+ .get(r.tool_call_id.as_str())
+ .copied()
+ .unwrap_or(false);
+ let tag = if ok { "ok" } else { "failed" };
+ let body = crate::util::truncate_with_ellipsis(&r.content, 800);
+ let _ = writeln!(out, "- {name} [{tag}]: {body}");
+ }
+ }
+ }
+ out.trim_end().to_string()
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/transcript.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/transcript.rs
new file mode 100644
index 0000000000..de8fa815ea
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/transcript.rs
@@ -0,0 +1,177 @@
+//! Persisting a sub-agent turn's (or a failed run's) raw transcript to
+//! `session_raw`, mirroring the removed `SubagentObserver::persist_transcript`.
+
+use crate::agent::messages::ChatMessage;
+use crate::agent::subagent_host::types::SubagentRunError;
+
+use super::dispatch::AggregatedUsage;
+use super::worker_mirror::mirror_worker_thread_from_history;
+
+/// The history a failed sub-agent run persists, plus the unanswered steps as
+/// text (#6281).
+///
+/// Starts from the caller's original `history`, not the snapshot's seeded
+/// prefix: that prefix is the provider-bound `dispatch_history`, which carries
+/// rehydrated image data where the durable history keeps its placeholders. Only
+/// the rounds a provider accepted follow it as structured messages. An empty
+/// snapshot (the run failed before its first model call) recovers nothing, as
+/// before.
+pub(super) fn failed_run_history(
+ original: &[ChatMessage],
+ snapshot: &crate::agent::tinyagents::TranscriptSnapshot,
+) -> (Vec<ChatMessage>, Option<String>) {
+ if snapshot.messages.is_empty() {
+ return (Vec::new(), None);
+ }
+ let base = snapshot.request_base_len.min(snapshot.messages.len());
+ let end = snapshot.accepted_end();
+ let mut recovered = original.to_vec();
+ recovered.extend(crate::agent::message_convert::messages_to_history(
+ &snapshot.messages[base..end],
+ ));
+ (
+ recovered,
+ crate::agent::tinyagents::render_unanswered_steps(&snapshot.messages[end..]),
+ )
+}
+
+/// Persist a sub-agent turn's raw transcript to `session_raw`, mirroring the
+/// removed `SubagentObserver::persist_transcript`: `agent_type:"subagent"`, the
+/// `task_id`, and the provider/model + usage carried on the last assistant
+/// message so per-thread usage reads price the sub-agent at its own model.
+#[allow(clippy::too_many_arguments)]
+pub(super) fn persist_subagent_transcript(
+ workspace_dir: &std::path::Path,
+ transcript_stem: &str,
+ agent_id: &str,
+ task_id: &str,
+ provider_label: &str,
+ model: &str,
+ history: &[ChatMessage],
+ usage: &AggregatedUsage,
+ thread_id: Option<&str>,
+ context_window: u64,
+ dispatcher: &str,
+ iteration: u32,
+) {
+ use tinyagents_session::transcript;
+
+ let path = match transcript::resolve_keyed_transcript_path(workspace_dir, transcript_stem) {
+ Ok(p) => p,
+ Err(err) => {
+ tracing::debug!(
+ agent_id,
+ error = %err,
+ "[subagent_host:graph] failed to resolve child transcript path"
+ );
+ return;
+ }
+ };
+ let now = chrono::Utc::now().to_rfc3339();
+ let turn_usage = transcript::TurnUsage {
+ provider: provider_label.to_string(),
+ model: model.to_string(),
+ usage: transcript::MessageUsage {
+ input: usage.input_tokens,
+ output: usage.output_tokens,
+ cached_input: usage.cached_input_tokens,
+ context_window,
+ cost_usd: usage.charged_amount_usd,
+ },
+ ts: now.clone(),
+ reasoning_content: None,
+ tool_calls: Vec::new(),
+ iteration,
+ };
+ let meta = transcript::TranscriptMeta {
+ agent_name: agent_id.to_string(),
+ agent_id: Some(agent_id.to_string()),
+ agent_type: Some("subagent".to_string()),
+ dispatcher: dispatcher.into(),
+ provider: Some(turn_usage.provider.clone()),
+ model: Some(turn_usage.model.clone()),
+ created: now.clone(),
+ updated: now,
+ turn_count: 1,
+ input_tokens: usage.input_tokens,
+ output_tokens: usage.output_tokens,
+ cached_input_tokens: usage.cached_input_tokens,
+ charged_amount_usd: usage.charged_amount_usd,
+ thread_id: thread_id.map(str::to_owned),
+ task_id: Some(task_id.to_string()),
+ };
+ let durable_history: Vec<_> = history
+ .iter()
+ .map(crate::agent::messages::transcript_message_from_chat)
+ .collect();
+ if let Err(err) =
+ transcript::write_transcript(&path, &durable_history, &meta, Some(&turn_usage))
+ {
+ tracing::debug!(
+ agent_id,
+ error = %err,
+ "[subagent_host:graph] failed to write child transcript"
+ );
+ }
+}
+
+/// Persist a **failed** sub-agent run (#4466): write whatever rounds the live
+/// transcript-snapshot middleware captured before the harness error to
+/// `session_raw` (so `learning/transcript_ingest` can still ingest a failed run,
+/// not skip an absent file), mirror those rounds onto the worker thread, and
+/// append a trailing failure marker so the record is self-describing. `recovered`
+/// holds only what a provider accepted; steps only the failing request carried
+/// arrive as `unanswered_steps` text and are appended to the marker (#6281).
+/// `usage` is what the answered calls reported, and `completed_rounds` is the
+/// number of model calls a provider answered.
+#[allow(clippy::too_many_arguments)]
+pub(super) fn persist_failed_run(
+ workspace_dir: &std::path::Path,
+ transcript_stem: &str,
+ agent_id: &str,
+ task_id: &str,
+ provider_label: &str,
+ model: &str,
+ recovered: &[ChatMessage],
+ usage: &AggregatedUsage,
+ thread_id: Option<&str>,
+ unanswered_steps: Option<&str>,
+ completed_rounds: u32,
+ context_window: u64,
+ dispatcher: &str,
+ worker_thread_id: Option<&str>,
+ error: &SubagentRunError,
+) {
+ let marker = match unanswered_steps {
+ Some(steps) => format!("[subagent run failed before completion: {error}]\n\n{steps}"),
+ None => format!("[subagent run failed before completion: {error}]"),
+ };
+ let mut history = recovered.to_vec();
+ history.push(ChatMessage::assistant(marker.clone()));
+
+ persist_subagent_transcript(
+ workspace_dir,
+ transcript_stem,
+ agent_id,
+ task_id,
+ provider_label,
+ model,
+ &history,
+ usage,
+ thread_id,
+ context_window,
+ dispatcher,
+ completed_rounds,
+ );
+
+ if let Some(thread_id) = worker_thread_id {
+ mirror_worker_thread_from_history(
+ workspace_dir,
+ thread_id,
+ agent_id,
+ task_id,
+ recovered,
+ Some(marker.as_str()),
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/worker_mirror.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/worker_mirror.rs
new file mode 100644
index 0000000000..0f4f84142a
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/worker_mirror.rs
@@ -0,0 +1,225 @@
+//! Mirroring a sub-agent turn's conversation onto its spawn's worker thread,
+//! matching the legacy `SubagentObserver`.
+
+use crate::agent::messages::{ChatMessage, ConversationMessage};
+
+/// Append a worker-thread [`StoredMessage`](crate::memory::conversations::ConversationMessage)
+/// with the restored legacy [`SubagentObserver`] metadata (#4466): `scope`,
+/// `agent_id`, `task_id`, plus the per-message `iteration`, `final`, `mode`, and
+/// (for assistant tool rounds / tool results) `tool_calls` / `tool_call_id` /
+/// `tool_name`. The migrated path had reduced this to `{scope, agent_id,
+/// task_id}` only, dropping the fields worker-thread consumers key on.
+#[allow(clippy::too_many_arguments)]
+fn append_worker_message(
+ workspace_dir: &std::path::Path,
+ thread_id: &str,
+ agent_id: &str,
+ task_id: &str,
+ content: String,
+ sender: &str,
+ metadata: serde_json::Value,
+) {
+ use crate::memory::conversations::{append_message, ConversationMessage as StoredMessage};
+ let mut extra = serde_json::json!({
+ "scope": "worker_thread",
+ "agent_id": agent_id,
+ "task_id": task_id,
+ "mode": "typed",
+ // #5934: a mirror row that is not the sub-agent speaking is a tool
+ // result, and the renderer maps every non-`"agent"` sender to
+ // `role: 'user'` (`assistantUiMessages.ts`) — so without this flag a
+ // tool's raw output is painted, in an openable worker thread, as
+ // something the human typed. `hidden` keeps the row in the log for the
+ // process rail and the process-source view; it only stops being chat.
+ // Genuine worker-thread user turns are written by
+ // `worker_thread::{create_worker_thread, append_worker_user_message}`,
+ // not here, so they are unaffected. Overridable by `metadata` below.
+ "hidden": sender != "agent",
+ });
+ if let (Some(base), Some(extra_fields)) = (extra.as_object_mut(), metadata.as_object()) {
+ for (k, v) in extra_fields {
+ base.insert(k.clone(), v.clone());
+ }
+ }
+ let message = StoredMessage {
+ id: format!("{sender}:{}", uuid::Uuid::new_v4()),
+ content,
+ message_type: "text".to_string(),
+ extra_metadata: extra,
+ sender: sender.to_string(),
+ created_at: chrono::Utc::now().to_rfc3339(),
+ };
+ if let Err(err) = append_message(workspace_dir.to_path_buf(), thread_id, message) {
+ tracing::debug!(
+ agent_id,
+ thread_id,
+ error = %err,
+ "[subagent_host:graph] failed to append worker-thread message"
+ );
+ }
+}
+
+/// Mirror a sub-agent turn's structured conversation to its worker thread,
+/// matching the legacy [`SubagentObserver`]: assistant turns (intents + final)
+/// become `agent` messages, tool results become `user` messages. `extra_final`,
+/// when set, is appended as a trailing `agent` message (the cap checkpoint or
+/// clarifying question, which isn't a plain assistant turn in the transcript).
+///
+/// Each message carries the restored legacy metadata (#4466): a per-round
+/// `iteration` counter, `final` on the trailing message, `tool_calls` on an
+/// assistant round, and `tool_call_id` / `tool_name` on each tool result.
+pub(super) fn mirror_worker_thread(
+ workspace_dir: &std::path::Path,
+ thread_id: &str,
+ agent_id: &str,
+ task_id: &str,
+ conversation: &[ConversationMessage],
+ extra_final: Option<&str>,
+) {
+ use std::collections::HashMap;
+
+ // call_id -> tool name, so each tool result records the tool it came from.
+ let mut names: HashMap<&str, &str> = HashMap::new();
+ for msg in conversation {
+ if let ConversationMessage::AssistantToolCalls { tool_calls, .. } = msg {
+ for call in tool_calls {
+ names.insert(call.id.as_str(), call.name.as_str());
+ }
+ }
+ }
+
+ let mut iteration: u64 = 0;
+ for msg in conversation {
+ match msg {
+ ConversationMessage::AssistantToolCalls {
+ text, tool_calls, ..
+ } => {
+ iteration += 1;
+ if let Some(t) = text.as_deref().filter(|t| !t.trim().is_empty()) {
+ let call_names: Vec<&str> =
+ tool_calls.iter().map(|c| c.name.as_str()).collect();
+ append_worker_message(
+ workspace_dir,
+ thread_id,
+ agent_id,
+ task_id,
+ t.to_string(),
+ "agent",
+ serde_json::json!({
+ "iteration": iteration,
+ "final": false,
+ "tool_calls": call_names,
+ }),
+ );
+ }
+ }
+ ConversationMessage::ToolResults(results) => {
+ for r in results {
+ let tool_name = names
+ .get(r.tool_call_id.as_str())
+ .copied()
+ .unwrap_or("tool");
+ append_worker_message(
+ workspace_dir,
+ thread_id,
+ agent_id,
+ task_id,
+ r.content.clone(),
+ "user",
+ serde_json::json!({
+ "iteration": iteration,
+ "final": false,
+ "tool_call_id": r.tool_call_id,
+ "tool_name": tool_name,
+ }),
+ );
+ }
+ }
+ ConversationMessage::Chat(c)
+ if c.role == "assistant" && !c.content.trim().is_empty() =>
+ {
+ iteration += 1;
+ append_worker_message(
+ workspace_dir,
+ thread_id,
+ agent_id,
+ task_id,
+ c.content.clone(),
+ "agent",
+ serde_json::json!({
+ "iteration": iteration,
+ "final": extra_final.is_none(),
+ }),
+ );
+ }
+ _ => {}
+ }
+ }
+
+ if let Some(text) = extra_final.filter(|t| !t.trim().is_empty()) {
+ append_worker_message(
+ workspace_dir,
+ thread_id,
+ agent_id,
+ task_id,
+ text.to_string(),
+ "agent",
+ serde_json::json!({ "iteration": iteration + 1, "final": true }),
+ );
+ }
+}
+
+/// Worker-thread mirror from a flat [`ChatMessage`] history (the error-recovery
+/// path, #4466): assistant messages become `agent` rows, tool messages become
+/// `user` rows. Used when only the recovered snapshot (not the typed
+/// `conversation`) is available. `failure_final`, when set, is appended as a
+/// trailing `agent` failure marker.
+pub(super) fn mirror_worker_thread_from_history(
+ workspace_dir: &std::path::Path,
+ thread_id: &str,
+ agent_id: &str,
+ task_id: &str,
+ history: &[ChatMessage],
+ failure_final: Option<&str>,
+) {
+ let mut iteration: u64 = 0;
+ for m in history {
+ match m.role.as_str() {
+ "assistant" if !m.content.trim().is_empty() => {
+ iteration += 1;
+ append_worker_message(
+ workspace_dir,
+ thread_id,
+ agent_id,
+ task_id,
+ m.content.clone(),
+ "agent",
+ serde_json::json!({ "iteration": iteration, "final": false }),
+ );
+ }
+ "tool" if !m.content.trim().is_empty() => {
+ append_worker_message(
+ workspace_dir,
+ thread_id,
+ agent_id,
+ task_id,
+ m.content.clone(),
+ "user",
+ serde_json::json!({ "iteration": iteration, "final": false }),
+ );
+ }
+ _ => {}
+ }
+ }
+ if let Some(text) = failure_final.filter(|t| !t.trim().is_empty()) {
+ append_worker_message(
+ workspace_dir,
+ thread_id,
+ agent_id,
+ task_id,
+ text.to_string(),
+ "agent",
+ serde_json::json!({ "iteration": iteration + 1, "final": true }),
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph_failed_run_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph_failed_run_tests.rs
new file mode 100644
index 0000000000..f1077398c0
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph_failed_run_tests.rs
@@ -0,0 +1,179 @@
+use super::*;
+use tinytools::{Tool, ToolSpec};
+
+/// Answers two tool rounds, then rejects the third request with a 400 (which the
+/// harness does not retry).
+struct FailsOnThirdCallProvider {
+ calls: AtomicUsize,
+}
+#[async_trait]
+impl ChatModel<()> for FailsOnThirdCallProvider {
+ fn profile(&self) -> Option<&ModelProfile> {
+ Some(native_tool_profile())
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ let n = self.calls.fetch_add(1, Ordering::SeqCst);
+ if n < 2 {
+ Ok(tool_response(
+ &format!("call-{n}"),
+ "echo",
+ serde_json::json!({ "msg": format!("round-{n}") }),
+ ))
+ } else {
+ Err(tinyinference_llm::Error::Model(
+ "400 Bad Request: provider boom".to_string(),
+ ))
+ }
+ }
+}
+
+/// #6281: a failed sub-agent run persists only the round a provider accepted as
+/// structured history; the round only the rejected request carried goes into the
+/// failure marker as text, so a resumed sub-agent cannot replay it.
+#[tokio::test]
+async fn failed_subagent_run_keeps_its_unanswered_round_out_of_history() {
+ let provider = Arc::new(FailsOnThirdCallProvider {
+ calls: AtomicUsize::new(0),
+ });
+ let parent_tools: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![Box::new(EchoTool)]);
+ let mut allowed = HashSet::new();
+ allowed.insert("echo".to_string());
+ let mut history = vec![ChatMessage::user("please echo twice")];
+ let workspace = tempfile::TempDir::new().expect("temp workspace");
+ let stem = "root-session__failed_run";
+
+ let result = 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-failed",
+ false,
+ None,
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ None,
+ workspace.path().to_path_buf(),
+ None,
+ 1024,
+ false,
+ stem,
+ "mock-channel",
+ None,
+ AgentTokenjuiceCompression::Off,
+ None,
+ )
+ .await;
+ assert!(result.is_err(), "the rejected third call fails the run");
+
+ use tinyagents_session::transcript;
+ let path =
+ transcript::resolve_keyed_transcript_path(workspace.path(), stem).expect("transcript path");
+ let persisted = transcript::read_transcript(&path).expect("failed run transcript");
+ let tool_rows: Vec<&str> = persisted
+ .messages
+ .iter()
+ .filter(|message| message.role == "tool")
+ .map(|message| message.content.as_str())
+ .collect();
+ assert_eq!(
+ tool_rows.len(),
+ 1,
+ "only the accepted round is persisted as a tool row: {tool_rows:?}"
+ );
+ assert!(
+ tool_rows[0].contains("echoed:round-0"),
+ "got: {tool_rows:?}"
+ );
+ let marker = &persisted.messages.last().expect("failure marker").content;
+ assert!(
+ marker.starts_with("[subagent run failed before completion:")
+ && marker.contains("provider boom")
+ && marker.contains("round-1"),
+ "the marker carries the cause and the unanswered round as text, got: {marker}"
+ );
+
+ // Two model calls were answered before the rejection; the recorded
+ // iteration must say so rather than count persisted messages.
+ let raw = std::fs::read_to_string(&path).expect("raw transcript");
+ let marker_line = raw
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .filter(|line| line.get("role").and_then(|role| role.as_str()) == Some("assistant"))
+ .last()
+ .expect("failure marker line");
+ assert_eq!(
+ marker_line.get("iteration").and_then(|n| n.as_u64()),
+ Some(2),
+ "the failed run reports the model calls a provider answered: {marker_line}"
+ );
+}
+
+/// #6281 review: a failed run recovers the caller's original history, not the
+/// provider-bound seed the snapshot started from (which carries rehydrated image
+/// data for a vision run).
+#[test]
+fn failed_run_history_keeps_the_original_seed_not_the_provider_bound_one() {
+ use crate::agent::tinyagents::TranscriptSnapshot;
+ use tinyinference_llm::message::Message;
+
+ let original = vec![ChatMessage::user("describe [IMAGE:attachment-1]")];
+ let snapshot = TranscriptSnapshot {
+ messages: vec![
+ // The provider-bound seed: the placeholder expanded to image data.
+ Message::user("describe data:image/png;base64,AAAA"),
+ // Round 0, answered by the next request.
+ Message::Assistant(
+ tool_response("call-0", "echo", serde_json::json!({ "msg": "round-0" })).message,
+ ),
+ Message::tool("call-0", "echoed:round-0"),
+ // Round 1, carried only by the failing request.
+ Message::Assistant(
+ tool_response("call-1", "echo", serde_json::json!({ "msg": "round-1" })).message,
+ ),
+ Message::tool("call-1", "echoed:round-1"),
+ ],
+ accepted_len: 3,
+ request_base_len: 1,
+ ..TranscriptSnapshot::default()
+ };
+
+ let (recovered, unanswered) =
+ super::super::transcript::failed_run_history(&original, &snapshot);
+
+ assert_eq!(
+ recovered.first().map(|message| message.content.as_str()),
+ Some("describe [IMAGE:attachment-1]"),
+ "the durable placeholder must be kept: {recovered:?}"
+ );
+ assert!(
+ !recovered
+ .iter()
+ .any(|message| message.content.contains("base64")),
+ "provider-bound image data must not be persisted: {recovered:?}"
+ );
+ assert_eq!(
+ recovered
+ .iter()
+ .filter(|message| message.role == "tool")
+ .count(),
+ 1,
+ "only the accepted round follows the seed: {recovered:?}"
+ );
+ assert!(
+ unanswered.is_some_and(|steps| steps.contains("round-1")),
+ "the unanswered round is kept as text"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs
new file mode 100644
index 0000000000..352ce51ad0
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs
@@ -0,0 +1,818 @@
+use super::*;
+use async_trait::async_trait;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use tinyinference_llm::message::{AssistantMessage, MessageDelta};
+use tinyinference_llm::model::{
+ ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
+};
+use tinyinference_llm::tool::ToolCall;
+use tinytools::ToolResult;
+use tinytools::{Tool, ToolSpec};
+
+fn native_tool_profile() -> &'static ModelProfile {
+ static PROFILE: std::sync::LazyLock<ModelProfile> = std::sync::LazyLock::new(|| ModelProfile {
+ provider: Some("subagent-graph-test".to_string()),
+ tool_calling: true,
+ parallel_tool_calls: true,
+ streaming: true,
+ ..ModelProfile::default()
+ });
+ &PROFILE
+}
+
+fn tool_response(id: &str, name: &str, arguments: serde_json::Value) -> ModelResponse {
+ ModelResponse {
+ message: AssistantMessage {
+ id: None,
+ content: Vec::new(),
+ tool_calls: vec![ToolCall::new(id, name, arguments)],
+ usage: None,
+ },
+ usage: None,
+ finish_reason: Some("tool_calls".to_string()),
+ raw: None,
+ resolved_model: None,
+ continue_turn: None,
+ served_from_cache: false,
+ }
+}
+
+struct EchoTool;
+#[async_trait]
+impl Tool for EchoTool {
+ fn name(&self) -> &str {
+ "echo"
+ }
+ fn description(&self) -> &str {
+ "echo"
+ }
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type": "object"})
+ }
+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ let m = args.get("msg").and_then(|v| v.as_str()).unwrap_or("");
+ Ok(ToolResult::success(format!("echoed:{m}")))
+ }
+}
+
+struct TwoStepProvider {
+ calls: AtomicUsize,
+}
+#[async_trait]
+impl ChatModel<()> for TwoStepProvider {
+ fn profile(&self) -> Option<&ModelProfile> {
+ Some(native_tool_profile())
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ let n = self.calls.fetch_add(1, Ordering::SeqCst);
+ if n == 0 {
+ Ok(tool_response("1", "echo", serde_json::json!({"msg": "hi"})))
+ } else {
+ Ok(ModelResponse::assistant("all done"))
+ }
+ }
+}
+
+#[path = "graph_failed_run_tests.rs"]
+mod graph_failed_run_tests;
+
+#[test]
+fn parallel_worker_without_thread_keeps_parent_transcript_affinity() {
+ assert_eq!(
+ inherited_thread_id(Some("parent-thread".to_string()), None),
+ Some("parent-thread".to_string())
+ );
+ assert_eq!(
+ inherited_thread_id(
+ Some("parent-thread".to_string()),
+ Some("task-thread".to_string())
+ ),
+ Some("task-thread".to_string())
+ );
+}
+
+#[tokio::test]
+async fn explicit_worker_thread_replaces_parent_for_model_run_and_transcript() {
+ let workspace = tempfile::tempdir().expect("workspace");
+ let mut parent = crate::agent::tinyagents::host::OpenHumanRunContext::new();
+ parent.thread_id = Some("parent-thread".to_owned());
+ let mut history = vec![ChatMessage::user("finish this")];
+
+ run_subagent_via_graph(
+ crate::agent::tinyagents::TurnModelSource::from_model(Arc::new(TwoStepProvider {
+ calls: AtomicUsize::new(1),
+ })),
+ "mock-model",
+ 0.0,
+ &mut history,
+ Arc::new(vec![]),
+ vec![],
+ vec![],
+ HashSet::new(),
+ 2,
+ None,
+ None,
+ "researcher",
+ "worker-task",
+ false,
+ Some("worker-thread".to_owned()),
+ parent,
+ None,
+ workspace.path().to_path_buf(),
+ None,
+ 1024,
+ false,
+ "root__worker-thread",
+ "test",
+ None,
+ AgentTokenjuiceCompression::Off,
+ None,
+ )
+ .await
+ .expect("worker run");
+
+ let path = tinyagents_session::transcript::resolve_keyed_transcript_path(
+ workspace.path(),
+ "root__worker-thread",
+ )
+ .expect("transcript path");
+ let persisted =
+ tinyagents_session::transcript::read_transcript(&path).expect("worker transcript");
+ assert_eq!(persisted.meta.thread_id.as_deref(), Some("worker-thread"));
+ assert_ne!(persisted.meta.thread_id.as_deref(), Some("parent-thread"));
+}
+
+#[tokio::test]
+async fn subagent_runs_through_the_graph_engine_with_real_tools() {
+ let provider = Arc::new(TwoStepProvider {
+ calls: AtomicUsize::new(0),
+ });
+ let parent_tools: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![Box::new(EchoTool)]);
+ let mut allowed = HashSet::new();
+ allowed.insert("echo".to_string());
+ let mut history = vec![ChatMessage::user("please echo hi")];
+
+ let (output, iterations, usage, early_exit, hit_cap, _breaker) = 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-1",
+ false,
+ None,
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ None,
+ std::env::temp_dir(),
+ None,
+ 1024,
+ false,
+ "root-session__real_tools",
+ "mock-channel",
+ None,
+ AgentTokenjuiceCompression::Off,
+ // No host config in tests: the graph takes byte-cap-only
+ // context defaults instead of reading the developer machine's
+ // real config.toml, which is what the old in-graph load did.
+ None,
+ )
+ .await
+ .expect("graph subagent runs");
+
+ assert_eq!(output, "all done");
+ assert_eq!(iterations, 2);
+ assert!(early_exit.is_none());
+ assert!(!hit_cap, "a clean finish should not report a cap hit");
+ let _ = usage;
+ // History was written back: user + assistant(tool) + tool result + assistant(final).
+ assert!(history.len() >= 4);
+ assert!(history.iter().any(|m| m.content.contains("echoed:hi")));
+}
+
+/// A provider that streams visible text + reasoning through the request's
+/// delta sender, exercising the child-progress bridge end to end.
+struct ThinkingStreamProvider;
+#[async_trait]
+impl ChatModel<()> for ThinkingStreamProvider {
+ fn profile(&self) -> Option<&ModelProfile> {
+ Some(native_tool_profile())
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ Ok(ModelResponse::assistant("Hello"))
+ }
+
+ async fn stream(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelStream> {
+ let response = ModelResponse::assistant("Hello");
+ Ok(Box::pin(futures::stream::iter(vec![
+ ModelStreamItem::Started,
+ ModelStreamItem::MessageDelta(MessageDelta {
+ text: String::new(),
+ reasoning: "let me think".to_string(),
+ tool_call: None,
+ }),
+ ModelStreamItem::MessageDelta(MessageDelta::text("Hel")),
+ ModelStreamItem::MessageDelta(MessageDelta::text("lo")),
+ ModelStreamItem::Completed(response),
+ ])))
+ }
+}
+
+#[tokio::test]
+async fn child_text_and_thinking_deltas_are_scoped_to_the_subagent() {
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<AgentProgress>(64);
+ let parent_tools: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![]);
+ let mut history = vec![ChatMessage::user("hi")];
+
+ let (output, _iters, _usage, _early, _hit_cap, _breaker) = run_subagent_via_graph(
+ crate::agent::tinyagents::TurnModelSource::from_model(Arc::new(ThinkingStreamProvider)),
+ "mock-model",
+ 0.0,
+ &mut history,
+ parent_tools,
+ vec![],
+ vec![],
+ HashSet::new(),
+ 4,
+ None,
+ Some(tx),
+ "researcher",
+ "task-7",
+ false,
+ None,
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ None,
+ std::env::temp_dir(),
+ None,
+ 1024,
+ false,
+ "root-session__scoped_deltas",
+ "mock-channel",
+ None,
+ AgentTokenjuiceCompression::Off,
+ // No host config in tests: the graph takes byte-cap-only
+ // context defaults instead of reading the developer machine's
+ // real config.toml, which is what the old in-graph load did.
+ None,
+ )
+ .await
+ .expect("child-delta subagent runs");
+
+ assert_eq!(output, "Hello");
+
+ let mut text = String::new();
+ let mut thinking = String::new();
+ let mut saw_iter = false;
+ while let Ok(p) = rx.try_recv() {
+ match p {
+ AgentProgress::SubagentTextDelta { delta, task_id, .. } => {
+ assert_eq!(task_id, "task-7");
+ text.push_str(&delta);
+ }
+ AgentProgress::SubagentThinkingDelta {
+ delta, agent_id, ..
+ } => {
+ assert_eq!(agent_id, "researcher");
+ thinking.push_str(&delta);
+ }
+ AgentProgress::SubagentIterationStarted { task_id, .. } => {
+ assert_eq!(task_id, "task-7");
+ saw_iter = true;
+ }
+ // The parent-scoped variants must never appear on a child run.
+ AgentProgress::TextDelta { .. }
+ | AgentProgress::ThinkingDelta { .. }
+ | AgentProgress::IterationStarted { .. } => {
+ panic!("child run emitted a parent-scoped progress event");
+ }
+ _ => {}
+ }
+ }
+ assert!(saw_iter, "a SubagentIterationStarted should be emitted");
+ assert!(
+ text.contains("Hello"),
+ "child text deltas should reassemble, got {text:?}"
+ );
+ assert!(
+ thinking.contains("let me think"),
+ "child thinking deltas should be forwarded, got {thinking:?}"
+ );
+}
+
+/// A tool named like the early-exit tool that echoes its `question` arg.
+struct AskTool;
+#[async_trait]
+impl Tool for AskTool {
+ fn name(&self) -> &str {
+ "ask_user_clarification"
+ }
+ fn description(&self) -> &str {
+ "ask the user a clarifying question"
+ }
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type": "object", "properties": {"question": {"type": "string"}}})
+ }
+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ let q = args
+ .get("question")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ Ok(ToolResult::success(q))
+ }
+}
+
+/// A provider whose first turn calls `ask_user_clarification`; a second turn
+/// would answer, but the early-exit pause should stop the loop before it.
+struct AskThenAnswer {
+ calls: AtomicUsize,
+}
+#[async_trait]
+impl ChatModel<()> for AskThenAnswer {
+ fn profile(&self) -> Option<&ModelProfile> {
+ Some(native_tool_profile())
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ let n = self.calls.fetch_add(1, Ordering::SeqCst);
+ if n == 0 {
+ Ok(tool_response(
+ "ask-1",
+ "ask_user_clarification",
+ serde_json::json!({"question": "which file?"}),
+ ))
+ } else {
+ Ok(ModelResponse::assistant("should not be reached"))
+ }
+ }
+}
+
+#[tokio::test]
+async fn ask_user_clarification_pauses_and_surfaces_the_question() {
+ let provider = Arc::new(AskThenAnswer {
+ calls: AtomicUsize::new(0),
+ });
+ let parent_tools: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![Box::new(AskTool)]);
+ let mut allowed = HashSet::new();
+ allowed.insert("ask_user_clarification".to_string());
+ let mut history = vec![ChatMessage::user("help me")];
+
+ let (output, iterations, _usage, early_exit, _hit_cap, _breaker) = run_subagent_via_graph(
+ crate::agent::tinyagents::TurnModelSource::from_model(provider.clone()),
+ "mock-model",
+ 0.0,
+ &mut history,
+ parent_tools,
+ vec![],
+ vec![],
+ allowed,
+ 10,
+ None,
+ None,
+ "researcher",
+ "task-9",
+ false,
+ None,
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ None,
+ std::env::temp_dir(),
+ None,
+ 1024,
+ false,
+ "root-session__clarification",
+ "mock-channel",
+ None,
+ AgentTokenjuiceCompression::Off,
+ // No host config in tests: the graph takes byte-cap-only
+ // context defaults instead of reading the developer machine's
+ // real config.toml, which is what the old in-graph load did.
+ None,
+ )
+ .await
+ .expect("ask-clarification subagent runs");
+
+ // The loop paused after the tool round: the early-exit tool is surfaced
+ // and the question is the returned text — the second model turn never ran.
+ assert_eq!(early_exit.as_deref(), Some("ask_user_clarification"));
+ assert_eq!(output, "which file?");
+ assert_eq!(
+ iterations, 1,
+ "the loop should pause before a second model call"
+ );
+ assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
+}
+
+/// A tool that always succeeds, so the loop keeps going until the cap.
+struct NoopTool;
+#[async_trait]
+impl Tool for NoopTool {
+ fn name(&self) -> &str {
+ "noop"
+ }
+ fn description(&self) -> &str {
+ "no-op"
+ }
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type": "object"})
+ }
+ async fn execute(&self, _a: serde_json::Value) -> anyhow::Result<ToolResult> {
+ Ok(ToolResult::success("ok"))
+ }
+}
+
+/// A provider that never finishes: every tool-enabled turn asks for `noop`.
+/// A request with no tools is the cap-hit summary call — it returns prose.
+struct LoopForeverProvider;
+#[async_trait]
+impl ChatModel<()> for LoopForeverProvider {
+ fn profile(&self) -> Option<&ModelProfile> {
+ Some(native_tool_profile())
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ if !request.tools.is_empty() {
+ Ok(tool_response("n", "noop", serde_json::json!({})))
+ } else {
+ // The summary call (tools=None): return a progress checkpoint.
+ Ok(ModelResponse::assistant("progress: explored two leads"))
+ }
+ }
+}
+
+#[tokio::test]
+async fn cap_hit_summarizes_a_resumable_checkpoint() {
+ let parent_tools: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![Box::new(NoopTool)]);
+ let mut allowed = HashSet::new();
+ allowed.insert("noop".to_string());
+ let mut history = vec![ChatMessage::user("do a big task")];
+
+ let (output, iterations, _usage, early_exit, hit_cap, _breaker) = run_subagent_via_graph(
+ crate::agent::tinyagents::TurnModelSource::from_model(Arc::new(LoopForeverProvider)),
+ "mock-model",
+ 0.0,
+ &mut history,
+ parent_tools,
+ vec![],
+ vec![],
+ allowed,
+ 2,
+ None,
+ None,
+ "researcher",
+ "task-cap",
+ false,
+ None,
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ None,
+ std::env::temp_dir(),
+ None,
+ 1024,
+ false,
+ "root-session__cap_hit",
+ "mock-channel",
+ None,
+ AgentTokenjuiceCompression::Off,
+ // No host config in tests: the graph takes byte-cap-only
+ // context defaults instead of reading the developer machine's
+ // real config.toml, which is what the old in-graph load did.
+ None,
+ )
+ .await
+ .expect("cap-hit subagent runs");
+
+ // The loop paused at the 2-call budget and summarized instead of erroring.
+ assert!(early_exit.is_none());
+ assert!(hit_cap, "reaching the model-call cap should report hit_cap");
+ assert_eq!(iterations, 2, "the loop should stop at the model-call cap");
+ assert!(
+ output.contains("progress: explored two leads"),
+ "cap hit should return the summary checkpoint, got {output:?}"
+ );
+}
+
+// ── Spawn-tool refusal on a sub-agent run (#6157, #4452) ────────────────
+
+/// 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);
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/mod.rs b/crates/openhuman-core/src/agent/subagent_host/ops/mod.rs
new file mode 100644
index 0000000000..de4923d8e0
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/mod.rs
@@ -0,0 +1,87 @@
+//! Sub-agent execution entry points.
+//!
+//! The public runner lives in [`run_subagent`]. It dispatches to
+//! [`runner::run_typed_mode`] (narrow prompt + filtered tools) which builds a
+//! brand-new system prompt and a filtered tool list for the requested
+//! archetype, then drives the turn through the tinyagents harness
+//! ([`graph::run_subagent_via_graph`]) until the model returns without
+//! further tool calls (or the iteration budget is exhausted).
+//!
+//! ## Layout
+//!
+//! | File | Contents |
+//! | ------------------- | -------------------------------------------------------------- |
+//! | `provider.rs` | `resolve_subagent_source`, `user_is_signed_in_to_composio`, `LazyToolkitResolver` |
+//! | `prompt.rs` | Role-contract suffix, `append_subagent_role_contract`, `dedup_tool_specs_by_name` |
+//! | `runner.rs` | `run_subagent`, `run_typed_mode` |
+//! | `graph.rs` | `run_subagent_via_graph` — the sub-agent turn graph + tools |
+//! | `checkpoint.rs` | `SubagentCheckpoint` — cap-hit summary |
+//! | `pause_checkpoint.rs` | `write` — the on-disk pause snapshot for `continue_subagent` |
+
+mod checkpoint;
+mod graph;
+mod pause_checkpoint;
+// The checkpoint filename validator, shared with `continue_subagent`: the
+// model-authored `task_id` must be rejected at the tool boundary as well as at
+// the write, so the read path cannot traverse either.
+pub(crate) use graph::run_agent_turn_request_via_default_graph;
+pub(crate) use pause_checkpoint::is_safe_task_id;
+mod prompt;
+mod provider;
+mod runner;
+
+// The lifecycle adapter owns the public entry point. This is its host-only
+// execution leaf after a neutral driver has prepared and admitted a request.
+pub(crate) use runner::run_subagent_direct;
+
+// `user_is_signed_in_to_composio` is the mode-aware "can the user call
+// composio at all?" probe added in Wave 2 (#1710). Re-exported here so
+// non-composio probe sites (registration gates, heartbeat telemetry)
+// can call it as
+// `crate::agent::subagent_host::user_is_signed_in_to_composio`
+// without reaching into a private sibling module.
+pub(crate) use provider::user_is_signed_in_to_composio;
+
+pub(crate) use prompt::append_subagent_role_contract;
+pub(crate) use provider::resolve_subagent_source;
+
+// Re-exports for test companion modules that use `use super::*`.
+// These provide the same flat namespace the original ops.rs had.
+// `append_subagent_role_contract` is already re-exported (pub(crate)) above.
+// `dedup_tool_specs_by_name` and `normalize_slug` are private in their source
+// modules and cannot be `pub`-re-exported; a plain `use` still makes them
+// reachable from the `#[cfg(test)]` companion modules via their `use super::*`
+// (descendants can name ancestor-private imports).
+#[cfg(test)]
+use prompt::dedup_tool_specs_by_name;
+#[cfg(test)]
+use provider::normalize_slug;
+#[cfg(test)]
+pub(super) use provider::LazyToolkitResolver;
+// filter_tool_indices lives in tool_prep (sibling of ops).
+#[cfg(test)]
+pub(super) use super::tool_prep::filter_tool_indices;
+// Types used by tests that were previously in scope via the flat ops.rs imports.
+#[cfg(test)]
+pub(super) use super::types::{SubagentMode, SubagentRunError, SubagentRunOptions};
+#[cfg(test)]
+pub(super) use crate::agent::harness::definition::{AgentDefinition, PromptSource};
+#[cfg(test)]
+pub(super) use crate::agent::harness::fork_context::ParentExecutionContext;
+#[cfg(test)]
+pub(super) use crate::agent::harness::{with_spawn_depth, MAX_SPAWN_DEPTH};
+#[cfg(test)]
+use tinytools::ToolSpec;
+
+// Test companion modules — path references relative to their original location.
+#[cfg(test)]
+#[path = "../ops_tests.rs"]
+mod tests;
+
+#[cfg(test)]
+#[path = "../ops_dedup_tests.rs"]
+mod dedup_tests;
+
+#[cfg(test)]
+#[path = "../ops_truncation_tests.rs"]
+mod truncation_tests;
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/pause_checkpoint.rs b/crates/openhuman-core/src/agent/subagent_host/ops/pause_checkpoint.rs
new file mode 100644
index 0000000000..3ee344741a
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/pause_checkpoint.rs
@@ -0,0 +1,104 @@
+//! Persisting a paused sub-agent so `continue_subagent` can resume it.
+//!
+//! Distinct from [`super::checkpoint`], which summarises a *cap-hit* run into
+//! resumable prose. This one is the on-disk conversation snapshot written when
+//! a child exits early on `ask_user_clarification`.
+
+/// Persist a paused sub-agent's conversation so `continue_subagent` can resume
+/// it, returning the path actually written or `None` when it could not be.
+///
+/// Every failure here is logged at `error`, not `warn`. A checkpoint that was
+/// not written is not a degraded nicety: the run is about to be reported as
+/// `AwaitingUser`, the orchestrator will relay a `task_id` and ask the user to
+/// answer, and the loss only becomes visible after they have — at which point
+/// the answer has nowhere to go. That late, invisible failure is what #5928's
+/// first acceptance criterion is about, and the `Option` this returns is what
+/// lets the caller stop promising a resumable pause it did not achieve.
+///
+/// Its own module so each failure branch is reachable from a test, and so
+/// `runner.rs` stays under the layout gate's line pin: point `checkpoint_dir` at a path that cannot be created, or at one
+/// whose target file cannot be written.
+/// Whether `task_id` is usable as a single filename component.
+///
+/// This is untrusted input on its way into a path join. `continue_subagent`
+/// takes `task_id` straight from its tool arguments — which the model authors —
+/// and passes it back through `SubagentRunOptions::task_id`, so a re-paused
+/// child writes its checkpoint under a name the model chose. Without this,
+/// `../../../../tmp/pwn` walks the write clean out of the checkpoint directory.
+///
+/// Deliberately an allow-list rather than a `..`-blocklist: every id this
+/// system mints is `sub-{uuid}`, `subsess-{uuid}` or a short test label, so
+/// nothing legitimate needs a separator, a dot, or a non-ASCII character, and
+/// an allow-list cannot be walked around by an encoding this check did not
+/// anticipate.
+pub(crate) fn is_safe_task_id(task_id: &str) -> bool {
+ !task_id.is_empty()
+ && task_id.len() <= 128
+ && task_id
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
+}
+
+pub(super) fn write(
+ checkpoint_dir: &std::path::Path,
+ task_id: &str,
+ data: &crate::agent::subagent_host::types::SubagentCheckpointData,
+) -> Option<std::path::PathBuf> {
+ if !is_safe_task_id(task_id) {
+ tracing::error!(
+ task_id = %task_id,
+ dir = %checkpoint_dir.display(),
+ "[subagent_host] refusing to write a checkpoint under an unsafe task id; \
+ this pause will not be resumable from disk"
+ );
+ return None;
+ }
+
+ if let Err(e) = std::fs::create_dir_all(checkpoint_dir) {
+ tracing::error!(
+ task_id = %task_id,
+ dir = %checkpoint_dir.display(),
+ error = %e,
+ "[subagent_host] could not create the checkpoint directory; this pause will not be \
+ resumable from disk"
+ );
+ return None;
+ }
+
+ let json = match serde_json::to_string_pretty(data) {
+ Ok(json) => json,
+ Err(e) => {
+ tracing::error!(
+ task_id = %task_id,
+ error = %e,
+ "[subagent_host] could not serialize the checkpoint; this pause will not be \
+ resumable from disk"
+ );
+ return None;
+ }
+ };
+
+ let checkpoint_path = checkpoint_dir.join(format!("{task_id}.json"));
+ if let Err(e) = std::fs::write(&checkpoint_path, json) {
+ tracing::error!(
+ task_id = %task_id,
+ path = %checkpoint_path.display(),
+ error = %e,
+ "[subagent_host] could not write the checkpoint; this pause will not be resumable \
+ from disk"
+ );
+ return None;
+ }
+
+ tracing::info!(
+ task_id = %task_id,
+ path = %checkpoint_path.display(),
+ history_len = data.history.len(),
+ "[subagent_host] checkpoint written for awaiting_user"
+ );
+ Some(checkpoint_path)
+}
+
+#[cfg(test)]
+#[path = "runner_checkpoint_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/prompt.rs b/crates/openhuman-core/src/agent/subagent_host/ops/prompt.rs
new file mode 100644
index 0000000000..849fd7f84c
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/prompt.rs
@@ -0,0 +1,177 @@
+//! System-prompt helpers for sub-agent typed mode.
+//!
+//! Includes the role-contract suffix, its injector, and the tool-spec
+//! deduplication helper used before sending specs to the provider.
+
+use crate::agent::harness::artifact_offload::{
+ render_artifact_offload_contract, should_render_offload_contract, ARTIFACT_OFFLOAD_HEADING,
+};
+use std::collections::HashSet;
+use tinytools::ToolSpec;
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Sub-agent role contract
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Prompt suffix injected into every typed sub-agent run.
+///
+/// Purpose:
+/// - make the child explicitly aware it is acting as a sub-agent
+/// - keep delegated outputs concise so parent-context growth stays bounded
+/// - discourage verbose restatement of the delegated task/context
+pub(super) const SUBAGENT_ROLE_CONTRACT_SUFFIX: &str = "## Sub-agent Role Contract\n\n\
+You are a sub-agent working for a parent OpenHuman agent, not a direct end-user assistant.\n\
+- Stay tightly scoped to the delegated task.\n\
+- Keep tool arguments and follow-up prompts compact, include only required fields/context.\n\
+- Keep your final response concise and synthesis-ready for the parent, prefer short bullets or short paragraphs.\n\
+- Do not restate the full task/context unless strictly required for correctness.\n\
+\n\
+## Sub-agent Result Contract\n\n\
+Return a compact result with these headings:\n\
+- Answer\n\
+- Evidence used\n\
+- Actions taken\n\
+- Open uncertainties\n\
+- Failed tool calls\n\
+- Recommended next step\n\
+\n\
+Do not include facts in Answer that are not supported by Evidence used or Actions taken.\n\
+If a tool result was truncated, partial, or too large to inspect fully, say so under Open uncertainties and do not treat it as complete.\n";
+
+pub(crate) fn append_subagent_role_contract(base_prompt: String, agent_id: &str) -> String {
+ // `context_scout` defines its own strict output contract (emit a single
+ // `[context_bundle]` and nothing else). The generic Result Contract here
+ // (Answer / Evidence used / Actions taken / …) directly conflicts with
+ // that and can make the scout emit the generic headings instead of the
+ // bundle — leaving the orchestrator without `has_enough_context` /
+ // `recommended_tool_calls`. Skip the suffix for the scout; its prompt.md
+ // already carries the sub-agent framing it needs.
+ if agent_id == "context_scout" {
+ tracing::debug!(
+ agent_id = %agent_id,
+ "[subagent_host] skipping role-contract suffix — agent defines its own output contract"
+ );
+ return base_prompt;
+ }
+
+ if base_prompt.contains(SUBAGENT_ROLE_CONTRACT_SUFFIX.trim()) {
+ tracing::debug!(
+ agent_id = %agent_id,
+ base_chars = base_prompt.chars().count(),
+ "[subagent_host] sub-agent role contract already present in system prompt"
+ );
+ return base_prompt;
+ }
+
+ let mut prompt = base_prompt;
+ if !prompt.ends_with('\n') {
+ prompt.push('\n');
+ }
+ prompt.push('\n');
+ prompt.push_str(SUBAGENT_ROLE_CONTRACT_SUFFIX);
+
+ tracing::debug!(
+ agent_id = %agent_id,
+ suffix_chars = SUBAGENT_ROLE_CONTRACT_SUFFIX.chars().count(),
+ final_chars = prompt.chars().count(),
+ "[subagent_host] appended sub-agent role contract to system prompt"
+ );
+
+ prompt
+}
+
+/// Append the filesystem-offload contract (#3883), but only for a sub-agent
+/// that actually holds a file-write tool.
+///
+/// Kept separate from [`append_subagent_role_contract`] because it is **not**
+/// universal. A sub-agent's system prompt may only name tools it can really
+/// call — `researcher` is search + fetch only, and a skill-filtered specialist
+/// sees just its own toolkit. Telling either to write a file yields
+/// hallucinated calls that fail, and two guards enforce it
+/// (`researcher::prompt::tests::build_returns_nonempty_body`,
+/// `ops_tests::typed_mode_filters_tools_by_skill_filter`).
+///
+/// Agents skipped here are still covered: `offload_oversized_result` runs on
+/// every sub-agent outcome and needs no cooperation from the model.
+///
+/// The contract text is rendered from the artifact module so the directory
+/// names the model is told about can never drift from the ones
+/// `resolve_artifact_path` will actually accept. The heading check makes it
+/// idempotent, and lets an archetype prompt spell the convention out itself.
+pub(crate) fn append_artifact_offload_contract(
+ base_prompt: String,
+ agent_id: &str,
+ visible_tool_names: &HashSet<String>,
+) -> String {
+ if !should_render_offload_contract(visible_tool_names) {
+ tracing::debug!(
+ agent_id = %agent_id,
+ "[artifact] sub-agent holds no file-write tool — skipping offload contract (harness-side offload still applies)"
+ );
+ return base_prompt;
+ }
+ if base_prompt.contains(ARTIFACT_OFFLOAD_HEADING) {
+ return base_prompt;
+ }
+
+ let mut prompt = base_prompt;
+ if !prompt.ends_with('\n') {
+ prompt.push('\n');
+ }
+ prompt.push('\n');
+ prompt.push_str(&render_artifact_offload_contract());
+
+ tracing::debug!(
+ agent_id = %agent_id,
+ final_chars = prompt.chars().count(),
+ "[artifact] appended offload contract to sub-agent system prompt"
+ );
+
+ prompt
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Tool-spec deduplication
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Deduplicate assembled tool specs by name, keeping the first occurrence.
+///
+/// The sub-agent's `filtered_specs` is a `Vec` assembled from
+/// `parent.all_tool_specs` indices plus dynamic tools, so a delegation tool can
+/// shadow a same-named skill/integration tool (common for the wide-set
+/// `tools_agent`), leaving two specs with the same name. Strict providers reject
+/// such a request with `400 "Tool names must be unique."` The main-agent path
+/// dedups via [`session::builder::dedup_visible_tool_specs`]; this separate
+/// sub-agent assembly must do the same.
+///
+/// First occurrence wins so registration-order semantics are preserved (tool
+/// dispatch still resolves by name). Dropped duplicates are logged at `debug`
+/// (diagnostic instrumentation, per the repo Rust logging guideline).
+///
+/// Extracted as a free function so the regression suite can exercise the dedup
+/// without standing up the full `run_typed_mode` plumbing.
+pub(super) fn dedup_tool_specs_by_name(agent_id: &str, specs: Vec<ToolSpec>) -> Vec<ToolSpec> {
+ let mut seen: HashSet<String> = HashSet::with_capacity(specs.len());
+ let mut deduped: Vec<ToolSpec> = Vec::with_capacity(specs.len());
+ let mut dropped: Vec<String> = Vec::new();
+ for spec in specs {
+ if seen.insert(spec.name.clone()) {
+ deduped.push(spec);
+ } else {
+ dropped.push(spec.name);
+ }
+ }
+ if !dropped.is_empty() {
+ tracing::debug!(
+ agent_id = %agent_id,
+ "[subagent_host] dropped {} duplicate tool spec(s) before sending to provider: {:?}",
+ dropped.len(),
+ dropped
+ );
+ }
+ deduped
+}
+
+#[cfg(test)]
+#[path = "prompt_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/prompt_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops/prompt_tests.rs
new file mode 100644
index 0000000000..9ceab5f562
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/prompt_tests.rs
@@ -0,0 +1,18 @@
+use super::*;
+
+#[test]
+fn context_scout_skips_role_contract_suffix() {
+ // The scout owns its own [context_bundle] output contract; the generic
+ // result contract must not be appended (it conflicts).
+ let base = "scout prompt body".to_string();
+ let out = append_subagent_role_contract(base.clone(), "context_scout");
+ assert_eq!(out, base);
+ assert!(!out.contains("Sub-agent Result Contract"));
+}
+
+#[test]
+fn other_agents_get_role_contract_suffix() {
+ let out = append_subagent_role_contract("body".to_string(), "researcher");
+ assert!(out.contains("Sub-agent Result Contract"));
+ assert!(out.contains("Recommended next step"));
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/provider.rs b/crates/openhuman-core/src/agent/subagent_host/ops/provider.rs
new file mode 100644
index 0000000000..b9aa8d8117
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/provider.rs
@@ -0,0 +1,310 @@
+//! Sub-agent provider and model resolution.
+//!
+//! Resolves `(provider, model)` from a declarative [`ModelSpec`], plus
+//! Composio sign-in probe and the lazy toolkit action resolver.
+
+use std::sync::Arc;
+
+pub(crate) fn resolve_subagent_source(
+ spec: &crate::agent::harness::definition::ModelSpec,
+ agent_id: &str,
+ config: Option<&crate::config::Config>,
+ parent_source: crate::agent::tinyagents::TurnModelSource,
+ parent_model: String,
+ is_team_lead: bool,
+ model_override: Option<&str>,
+ temperature: f64,
+) -> (crate::agent::tinyagents::TurnModelSource, String) {
+ use crate::agent::harness::definition::ModelSpec;
+ if let Some(model) = model_override
+ .map(str::trim)
+ .filter(|model| !model.is_empty())
+ {
+ tracing::debug!(
+ agent_id,
+ model,
+ "[subagent_host] using inline model override"
+ );
+ return (parent_source, model.to_string());
+ }
+ if let Some(model) = config.and_then(|cfg| cfg.configured_agent_model(agent_id, is_team_lead)) {
+ tracing::debug!(
+ agent_id,
+ model,
+ "[subagent_host] using config-level model pin"
+ );
+ return (parent_source, model.to_string());
+ }
+ match spec {
+ ModelSpec::Hint(workload) => match config {
+ Some(config) => {
+ match crate::inference::provider::create_chat_model_with_model_id(
+ workload,
+ config,
+ temperature,
+ ) {
+ Ok((_model, model_id)) => {
+ tracing::info!(
+ agent_id,
+ role = workload,
+ model = %model_id,
+ "[subagent_host] resolved crate-native workload source"
+ );
+ (
+ crate::agent::tinyagents::TurnModelSource::new_crate_native(
+ workload.clone(),
+ Arc::new(config.clone()),
+ ),
+ model_id,
+ )
+ }
+ Err(error) => {
+ tracing::warn!(
+ agent_id,
+ role = workload,
+ %error,
+ parent_model,
+ "[subagent_host] workload model build failed; inheriting parent source"
+ );
+ (parent_source, parent_model)
+ }
+ }
+ }
+ None => {
+ tracing::warn!(
+ agent_id,
+ role = workload,
+ parent_model,
+ "[subagent_host] config unavailable; inheriting parent source"
+ );
+ (parent_source, parent_model)
+ }
+ },
+ ModelSpec::Inherit => (parent_source, parent_model),
+ ModelSpec::Exact(model) => (parent_source, model.clone()),
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Composio sign-in probe
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Probe whether the user can call Composio at all under the current
+/// config. Returns `true` when the mode-aware factory can build EITHER
+/// a backend-mode client (legacy JWT-driven path) OR a direct-mode
+/// client (BYO Composio API key). The resolved client is dropped
+/// immediately — this is purely a "signed-in vs not" check used by the
+/// spawn-time refresh path. Per-action dispatch resolves a fresh client
+/// elsewhere via [`create_composio_client`] so the live `composio.mode`
+/// toggle keeps winning.
+///
+/// Extracted as a free function so the regression suite can exercise
+/// the same probe the runner uses without spinning up the full
+/// `run_typed_mode` plumbing.
+pub(crate) fn user_is_signed_in_to_composio(config: &crate::config::Config) -> bool {
+ crate::integrations::composio::client::create_composio_client(config).is_ok()
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Lazy toolkit resolver
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Lazy resolver that lets `integrations_agent` recover when the model
+/// calls a Composio action slug that exists in the bound toolkit's full
+/// catalogue but was filtered out of the up-front fuzzy top-K. On a
+/// match we build the [`ComposioActionTool`] on demand so the call
+/// dispatches normally instead of dead-ending in
+/// `Error: tool '...' is not available`.
+///
+/// Holds an [`Arc<Config>`] rather than a pre-baked
+/// [`crate::integrations::composio::ComposioClient`] so the live
+/// `composio.mode` toggle is honoured per execute — see
+/// [`crate::integrations::composio::ComposioActionTool`] and issue #1710.
+///
+/// ## Tool caching (#5119)
+///
+/// `resolve()` caches the built [`ComposioActionTool`] (and therefore its
+/// [`ContractGate`]) per slug so that a given action reuses the same gate
+/// instance across multiple `resolve()` calls. This is forward-looking: the
+/// `lazy_resolver` is not yet wired for production dispatch (#4249 1b), but
+/// when it is, caching prevents the fresh-gate-per-call problem that would
+/// cause every resolution to surface the contract instead of executing.
+/// Additionally, the [`ContractGate`] itself has a process-wide auto-proceed
+/// safety net that handles the re-delegation pattern even without caching.
+pub(crate) struct LazyToolkitResolver {
+ pub(super) config: std::sync::Arc<crate::config::Config>,
+ pub(super) actions: Vec<crate::agent::prompts::ConnectedIntegrationTool>,
+ /// Cache of resolved tools keyed by action slug. Once a tool is built
+ /// for a slug, subsequent `resolve()` calls for the same slug reuse the
+ /// cached instance — sharing its [`ContractGate`] state (#5119).
+ #[allow(dead_code)] // used via pub(super) from tests
+ pub(super) resolved:
+ std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<dyn tinytools::Tool>>>,
+}
+
+/// Minimum normalized-slug length before the prefix/superstring tier in
+/// [`LazyToolkitResolver::find_action`] engages (#3152). Below this, a stray
+/// short slug (`notion`, `gmail`) would prefix-match too many actions; the
+/// uniqueness check would reject it anyway, but the length gate makes the
+/// intent explicit and skips needless scans.
+const TIER4_MIN_SLUG_LEN: usize = 8;
+
+impl LazyToolkitResolver {
+ /// Resolve a `ComposioActionTool` for `name`, caching the built tool per
+ /// slug so subsequent calls for the same slug return the same
+ /// [`ContractGate`] instance (#5119).
+ ///
+ /// ## Caching
+ ///
+ /// Tools are cached by slug in the `resolved` map. The first call for a
+ /// slug builds the tool and stores it; subsequent calls return the cached
+ /// `Arc<dyn Tool>`, sharing the [`ContractGate`] state across calls. This
+ /// prevents the fresh-gate-per-call problem: the contract is surfaced at
+ /// most once per resolver instance, and the retry proceeds normally.
+ ///
+ /// Additionally, the [`ContractGate`] has a process-wide auto-proceed
+ /// safety net that fires when too many fresh gate instances have all
+ /// surfaced the same contract without executing (#5119). This handles
+ /// the cross-spawn re-delegation pattern even when caching is bypassed.
+ pub(super) fn resolve(&self, name: &str) -> Option<std::sync::Arc<dyn tinytools::Tool>> {
+ // Check cache first — returns the same Arc (and therefore the same
+ // ContractGate) for repeated resolve calls on the same slug.
+ {
+ let cache = self
+ .resolved
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ if let Some(cached) = cache.get(name) {
+ tracing::trace!(
+ target: "subagent_runner",
+ slug = %name,
+ "[subagent_host] returning cached composio tool"
+ );
+ return Some(cached.clone());
+ }
+ }
+
+ let action = self.find_action(name)?;
+ let tool: std::sync::Arc<dyn tinytools::Tool> =
+ std::sync::Arc::new(crate::integrations::composio::ComposioActionTool::new(
+ self.config.clone(),
+ action.name.clone(),
+ action.description.clone(),
+ action.parameters.clone(),
+ ));
+
+ // Store in cache for future lookups.
+ {
+ let mut cache = self
+ .resolved
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ cache.insert(action.name.clone(), tool.clone());
+ }
+
+ Some(tool)
+ }
+
+ /// Match a model-supplied tool name to a real toolkit action, tolerant
+ /// of the near-miss slugs models routinely emit — case differences and
+ /// separator/prefix drift (bug-report-2026-05-26 A2). Tries, in order:
+ /// exact, case-insensitive, then a normalized alphanumeric match
+ /// (accepted only when **unique**, so a fabricated slug can't silently
+ /// resolve to the wrong action — those still fall through to the
+ /// "tool not available" error, which lists `known_slugs` for the model
+ /// to self-correct).
+ fn find_action(&self, name: &str) -> Option<&crate::agent::prompts::ConnectedIntegrationTool> {
+ if let Some(action) = self.actions.iter().find(|a| a.name == name) {
+ return Some(action);
+ }
+ if let Some(action) = self
+ .actions
+ .iter()
+ .find(|a| a.name.eq_ignore_ascii_case(name))
+ {
+ tracing::debug!(
+ requested = %name,
+ matched = %action.name,
+ "[subagent_host] resolved tool by case-insensitive match"
+ );
+ return Some(action);
+ }
+ let norm = normalize_slug(name);
+ if !norm.is_empty() {
+ let mut matches = self
+ .actions
+ .iter()
+ .filter(|a| normalize_slug(&a.name) == norm);
+ if let Some(action) = matches.next() {
+ if matches.next().is_none() {
+ tracing::info!(
+ requested = %name,
+ matched = %action.name,
+ "[subagent_host] resolved tool by normalized-slug match"
+ );
+ return Some(action);
+ }
+ // Ambiguous: 2+ actions normalize to the same slug (e.g.
+ // `read_file` and `ReadFile` → `readfile`). We deliberately
+ // refuse to guess. Warn (not debug): a slug collision is a
+ // toolkit configuration anomaly that should surface in normal
+ // operator logs, not stay hidden behind debug filtering.
+ tracing::warn!(
+ requested = %name,
+ norm = %norm,
+ "[subagent_host] ambiguous normalized-slug match — multiple actions resolve to the same slug; not resolving"
+ );
+ return None;
+ }
+
+ // Tier 4: unique prefix/superstring match (#3152). Models
+ // routinely emit a TRUNCATED action slug — `NOTION_SEARCH_NOTION`
+ // for the catalogued `NOTION_SEARCH_NOTION_PAGE` — or, less often,
+ // a suffixed one. Accept only when exactly one action's normalized
+ // slug extends the request (or vice-versa). Gated on a non-trivial
+ // request length so a short or hallucinated slug can't fan out
+ // across many actions, and strictly unique so a near-miss WRITE
+ // can never silently dispatch to the wrong action (data-integrity:
+ // a mis-resolved create/update would touch the wrong resource).
+ if norm.len() >= TIER4_MIN_SLUG_LEN {
+ let mut prefix_matches = self.actions.iter().filter(|a| {
+ let cand = normalize_slug(&a.name);
+ !cand.is_empty() && (cand.starts_with(&norm) || norm.starts_with(&cand))
+ });
+ if let Some(action) = prefix_matches.next() {
+ if prefix_matches.next().is_none() {
+ tracing::info!(
+ requested = %name,
+ matched = %action.name,
+ "[subagent_host] resolved tool by unique prefix/superstring match"
+ );
+ return Some(action);
+ }
+ tracing::warn!(
+ requested = %name,
+ norm = %norm,
+ "[subagent_host] ambiguous prefix/superstring match — multiple actions share the slug prefix; not resolving"
+ );
+ }
+ }
+ }
+ None
+ }
+
+ /// Slugs from the bound toolkit, for inclusion in unknown-tool
+ /// errors so the model can self-correct without burning a turn.
+ pub(super) fn known_slugs(&self) -> Vec<&str> {
+ self.actions.iter().map(|a| a.name.as_str()).collect()
+ }
+}
+
+/// Lowercased, non-alphanumerics stripped — collapses separator/prefix
+/// drift (`GOOGLESLIDES_BATCH_UPDATE` vs `googleslides_batch_update`) so
+/// near-miss tool slugs still resolve, while genuinely different slugs
+/// (e.g. a hallucinated `GMAIL_GET_LAST_3_MESSAGES`) stay distinct.
+pub(super) fn normalize_slug(s: &str) -> String {
+ s.chars()
+ .filter(|c| c.is_ascii_alphanumeric())
+ .map(|c| c.to_ascii_lowercase())
+ .collect()
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
new file mode 100644
index 0000000000..41c0b9fb42
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
@@ -0,0 +1,1793 @@
+//! Top-level sub-agent run entry points.
+//!
+//! [`run_subagent`] is the primary entry point for agent delegation and
+//! dispatches to [`run_typed_mode`] which builds a brand-new system prompt
+//! and a filtered tool list for the requested archetype, then drives provider
+//! calls and tool execution until the model returns without further tool calls
+//! (or the iteration budget is exhausted).
+
+use std::collections::HashSet;
+use std::sync::Arc;
+use std::time::Instant;
+
+use crate::agent::file_state::with_file_state_agent_id;
+use crate::agent::harness::agent_graph::{AgentTurnRequest, AgentTurnUsage};
+use crate::agent::harness::artifact_offload::{
+ effective_offload_threshold, extract_artifact_paths, new_artifact_offload,
+ note_artifact_handoff, offload_oversized_result, DEFAULT_OFFLOAD_THRESHOLD_BYTES,
+ HANDOFF_STAGE_RECORDED,
+};
+use crate::agent::harness::definition::{
+ validate_tier_transition, AgentDefinition, AgentDefinitionRegistry, AgentTier, IterationPolicy,
+ PromptSource, SandboxMode as AgentSandboxMode,
+};
+use crate::agent::harness::fork_context::ParentExecutionContext;
+use crate::agent::harness::{with_current_sandbox_mode, with_spawn_depth, MAX_SPAWN_DEPTH};
+use crate::agent::prompts::{
+ render_subagent_system_prompt_with_format, PromptContext, PromptTool, SubagentRenderOptions,
+};
+use crate::agent::subagent_host::extract_tool::ExtractFromResultTool;
+use crate::agent::subagent_host::handoff::ResultHandoffCache;
+use crate::agent::subagent_host::subagent_iter_cap_with_autonomous_lift;
+use crate::agent::subagent_host::tool_prep::{
+ build_text_mode_tool_instructions, filter_tool_indices, is_subagent_spawn_tool,
+ load_prompt_source, select_actions_with_essentials, strip_spawn_tools_from_dynamic,
+ subagent_prompt_protocol, top_k_for_toolkit,
+};
+use crate::agent::subagent_host::types::{
+ SubagentMode, SubagentRunError, SubagentRunOptions, SubagentRunOutcome, SubagentRunStatus,
+ SubagentUsage,
+};
+use crate::inference::provider::AGENT_TURN_MAX_OUTPUT_TOKENS;
+use crate::memory::api::provider::retrieval::{FastRetrieveQuery, RetrievalResponse};
+use crate::memory::source_scope::as_bus_scope;
+use tinyagents_harness::tool::{rank_tools_by_prompt, SelectableTool, MIN_CONFIDENT_HITS};
+use tinytools::{
+ SandboxMode as TinyagentsSandboxMode, Tool, ToolCategory, ToolSpec, WorkspaceDescriptor,
+};
+
+use super::prompt::{
+ append_artifact_offload_contract, append_subagent_role_contract, dedup_tool_specs_by_name,
+};
+use super::provider::{
+ resolve_subagent_source, user_is_signed_in_to_composio, LazyToolkitResolver,
+};
+
+/// Runtime spawn-hierarchy gate decision for one delegation hop.
+///
+/// `parent_def` is the resolved parent agent definition (looked up from the
+/// global registry by its definition id) or `None` when the parent can't be
+/// resolved — e.g. a dynamically-named agent (model-council juror) or a custom
+/// agent absent from the registry, or any context where the registry isn't
+/// initialised. A `None` parent yields `Ok(())`: we skip rather than mask, the
+/// same defensive posture the loader takes for unknown child ids.
+///
+/// A **worker** parent is also exempted. At runtime a worker only reaches the
+/// spawn chokepoint via the documented collapsed `delegate_to_integrations_agent`
+/// path (→ `integrations_agent`, itself a worker) — a shape the loader
+/// intentionally leaves untouched. Re-denying it here would turn valid custom
+/// worker agents that use `{ skills = "*" }` into runtime failures. The
+/// worker-leaf authoring rule stays enforced statically at boot, and the
+/// per-parent allowlist gate blocks any other worker spawn.
+///
+/// For chat / reasoning parents the hop is checked against
+/// [`validate_tier_transition`] (the single source of truth shared with the
+/// boot loader walk); a forbidden hop is logged and becomes a
+/// [`SubagentRunError::TierViolation`]. Logging lives here (rather than at the
+/// call site) so the deny path is exercised by this fn's unit tests.
+pub(super) fn tier_gate_decision(
+ parent_def: Option<&AgentDefinition>,
+ child: &AgentDefinition,
+ parent_agent_id: &str,
+ task_id: &str,
+) -> Result<(), SubagentRunError> {
+ let Some(parent_def) = parent_def else {
+ return Ok(());
+ };
+ if parent_def.agent_tier == AgentTier::Worker {
+ return Ok(());
+ }
+ if let Err(reason) = validate_tier_transition(parent_def.agent_tier, child.agent_tier) {
+ tracing::warn!(
+ parent_agent = %parent_agent_id,
+ parent_tier = %parent_def.agent_tier,
+ child_agent = %child.id,
+ child_tier = %child.agent_tier,
+ task_id = %task_id,
+ "[subagent_host] blocked tier-violating delegation: {reason}"
+ );
+ return Err(SubagentRunError::TierViolation {
+ parent_tier: parent_def.agent_tier,
+ child_tier: child.agent_tier,
+ reason,
+ });
+ }
+ 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_host] 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_host] 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_host] scoring extract_entities failed (non-fatal) — deferring to model walk (#4677)"
+ );
+ true
+ }
+ },
+ None => {
+ tracing::debug!(
+ task_id = %task_id,
+ "[subagent_host] 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_host] memory binding unavailable (non-fatal) — deferring to model walk (#4677)"
+ );
+ true
+ }
+ };
+ if entities_empty {
+ tracing::debug!(
+ task_id = %task_id,
+ "[subagent_host] 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_host] 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_host] 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_host] 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(),
+ persistence_disposition:
+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalExisting,
+ })
+}
+
+/// 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.
+/// 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.
+pub(crate) async fn run_subagent_direct(
+ definition: &AgentDefinition,
+ task_prompt: &str,
+ options: SubagentRunOptions,
+) -> Result<SubagentRunOutcome, SubagentRunError> {
+ // Unconditionally heap-allocate the entire run_subagent body so
+ // every caller doesn't have to carry this future's state inline.
+ // Tools that delegate run inside the parent agent's already-deep
+ // turn poll (the boxed tinyagents harness drive future in
+ // `run_turn_via_tinyagents_shared`), so the parent's stack would
+ // otherwise pile (parent turn state + dispatch_subagent state +
+ // run_subagent's wrapper state + run_typed_mode state + child turn
+ // state) onto tokio's 2 MiB worker stack and abort with "thread
+ // 'tokio-rt-worker' has overflowed its stack, fatal runtime error:
+ // stack overflow" — observed at `[subagent_host] dispatching
+ // agent_id=researcher ...` in the `chat-harness-subagent` Playwright
+ // lane crash. The inner `Box::pin`s around `run_typed_mode` and the
+ // child's tinyagents drive future further chunk the child's state so
+ // a single sub-agent run can't blow the stack either.
+ Box::pin(async move {
+ // A nested delegate writes its terminal total to this run's isolated
+ // ledger. If the outer future errors or is cancelled after that child
+ // has completed, Drop promotes those finished totals before the error
+ // can escape. Success marks the finalizer complete after folding the
+ // same entries into this run's single terminal total.
+ struct UsageFinalizer {
+ context: crate::agent::tinyagents::host::OpenHumanRunContext,
+ complete: bool,
+ }
+ impl UsageFinalizer {
+ fn finish(&mut self, entry: crate::agent::tinyagents::host::SubagentUsageEntry) {
+ self.context.record_completed_subagent_usage(entry);
+ self.complete = true;
+ }
+ }
+ impl Drop for UsageFinalizer {
+ fn drop(&mut self) {
+ if !self.complete {
+ self.context.promote_completed_descendant_usage();
+ }
+ }
+ }
+ let mut usage_finalizer = UsageFinalizer {
+ context: options.run_context.clone(),
+ complete: false,
+ };
+ let task_id = options
+ .task_id
+ .clone()
+ .unwrap_or_else(|| format!("sub-{}", uuid::Uuid::new_v4()));
+
+ // Turn-scoped dispatch gate (#5804) — deliberately the FIRST gate, for
+ // the same reason the depth gate is synchronous and pre-dispatch: a
+ // delegation we already know cannot land should cost nothing, not a
+ // config load, a hook, or a provider round-trip.
+ //
+ // Two refusals, both evidence-based and both derived from what this
+ // turn has actually observed rather than from any configured constant
+ // or task shape: a graceful pause has been requested at the model-call
+ // cap, or less wall-clock remains than this turn's slowest completed
+ // sub-agent took. Outside a turn scope the guard is absent and this is
+ // a no-op, so CLI and direct invocations are unaffected.
+ match options.run_context.dispatch.as_deref().map_or(
+ crate::agent::tinyagents::host::DispatchDecision::Allow,
+ crate::agent::tinyagents::host::TurnDispatchState::check,
+ ) {
+ crate::agent::tinyagents::host::DispatchDecision::Allow => {}
+ crate::agent::tinyagents::host::DispatchDecision::RefusePaused {
+ completed_model_calls,
+ cap,
+ } => {
+ tracing::info!(
+ agent_id = %definition.id,
+ task_id = %task_id,
+ completed_model_calls,
+ cap,
+ "[subagent_host] dispatch refused — turn already requested a graceful pause"
+ );
+ return Err(SubagentRunError::PauseRequested {
+ completed_model_calls,
+ cap,
+ });
+ }
+ crate::agent::tinyagents::host::DispatchDecision::RefuseBudget {
+ remaining_ms,
+ observed_max_ms,
+ observed_samples,
+ } => {
+ tracing::info!(
+ agent_id = %definition.id,
+ task_id = %task_id,
+ remaining_ms,
+ observed_max_ms,
+ observed_samples,
+ "[subagent_host] dispatch refused — remaining budget is shorter than this \
+ turn's slowest sub-agent"
+ );
+ return Err(SubagentRunError::DispatchBudgetExhausted {
+ remaining_ms,
+ observed_max_ms,
+ observed_samples,
+ });
+ }
+ }
+
+ let parent = options
+ .run_context
+ .parent
+ .clone()
+ .ok_or(SubagentRunError::NoParentContext)?;
+ let started = Instant::now();
+ let attempted_depth = options.run_context.spawn_depth;
+
+ // Synchronous pre-dispatch projection of the single depth authority
+ // (`MAX_SPAWN_DEPTH`, also fed to the crate's `RunPolicy.limits.max_depth`).
+ // This surfaces `SpawnDepthExceeded` before a provider round-trip and
+ // across the MCP process hop; the crate's `TinyAgentsError::SubAgentDepth`
+ // maps onto this same error shape for over-deep in-process runs.
+ if attempted_depth > MAX_SPAWN_DEPTH {
+ tracing::warn!(
+ agent_id = %definition.id,
+ task_id = %task_id,
+ attempted_depth,
+ max_depth = MAX_SPAWN_DEPTH,
+ "[subagent_host] spawn depth exceeded"
+ );
+ return Err(SubagentRunError::SpawnDepthExceeded {
+ attempted_depth,
+ max_depth: MAX_SPAWN_DEPTH,
+ });
+ }
+
+ // Runtime spawn-hierarchy (tier) gate — defense-in-depth alongside the
+ // depth gate above. The loader validates *declared* `subagents` pairs
+ // statically at boot (`validate_tier_hierarchy`), but dynamic, custom,
+ // or model-chosen spawns reach this chokepoint without ever passing
+ // through that walk. Resolve the parent's tier from the registry by its
+ // definition id; `tier_gate_decision` rejects (and logs) any forbidden
+ // chat/reasoning hop while exempting unresolved + worker parents.
+ let parent_def =
+ AgentDefinitionRegistry::global().and_then(|reg| reg.get(&parent.agent_definition_id));
+ tier_gate_decision(parent_def, definition, &parent.agent_definition_id, &task_id)?;
+
+ // Configured `subagentStart` hooks — the last gate before a spawn costs
+ // anything. Placed after the tier gate so a spawn the graph already
+ // forbids never reaches a user script, and before config load so a
+ // denied spawn has no side effects at all.
+ if let Err(reason) = crate::hooks::ops::subagent_starting(
+ crate::hooks::context::TurnIdentity {
+ conversation_id: Some(parent.session_id.clone()),
+ session_id: Some(parent.session_id.clone()),
+ agent_id: Some(parent.agent_definition_id.clone()),
+ ..Default::default()
+ },
+ &definition.id,
+ task_prompt,
+ )
+ .await
+ {
+ // A denial reason is hook-supplied (`agent_message`/`user_message`),
+ // so it can carry arbitrary content. Log a fixed sentence with the
+ // task identity; the caller still surfaces the detailed reason back
+ // to the model through `SubagentRunError::HookDenied`.
+ tracing::info!(
+ agent_id = %definition.id,
+ task_id = %task_id,
+ "[subagent_host] spawn denied by a configured hook"
+ );
+ return Err(SubagentRunError::HookDenied(reason));
+ }
+
+ // Load the host config exactly once for this spawn and hand it to
+ // everything below. See `LoadedConfig` — `load_or_init` re-reads
+ // config.toml on every call, and the runtime below is slated to move
+ // into TinyAgents, where there is no config file to load.
+ //
+ // Deliberately placed *after* `tier_gate_decision`: `load_or_init` can
+ // initialize config on first run, and a spawn the tier gate rejects
+ // should not have that side effect.
+ let loaded_config: LoadedConfig = crate::config::Config::load_or_init()
+ .await
+ .map(std::sync::Arc::new)
+ .map_err(|e| e.to_string());
+
+ // Deterministic fast path for the pure-retrieval memory agent (#4677).
+ // Both `retrieve_memory` (chat delegate) and `call_memory_agent` land
+ // here via `run_subagent`; short-circuit with the E2GraphRAG hits when
+ // data is present so the happy path costs ~1 deterministic pass instead
+ // of a ≤6-iteration model walk (~30–40s of round-trips). Falls through
+ // to the full sub-agent when the fast path is disabled/errs/finds
+ // nothing (the empty/degraded case is handled by #4655).
+ if definition.id == AGENT_MEMORY_ID {
+ if let Some(outcome) = try_deterministic_memory_retrieval(
+ task_prompt,
+ definition,
+ &task_id,
+ started,
+ &loaded_config,
+ )
+ .await
+ {
+ // The fast path completes a real delegation and returns here,
+ // short-circuiting the recorder below — so record it too, or a
+ // turn whose only delegations are deterministic memory
+ // retrievals never accumulates a sample and the budget gate
+ // stays disarmed for the whole turn (#5804 review).
+ //
+ // Including it cannot weaken the gate. `observed_max` is a
+ // running **maximum**, so a short sample can only leave it
+ // where it was — an earlier revision of this comment claimed
+ // the opposite and was wrong about its own statistic. What it
+ // does buy is a correct `observed_samples` count and a gate
+ // that arms on a turn shaped entirely from fast-path work.
+ if let Some(dispatch) = options.run_context.dispatch.as_deref() {
+ dispatch.record_subagent_elapsed(started.elapsed());
+ }
+ usage_finalizer.finish(crate::agent::tinyagents::host::SubagentUsageEntry {
+ task_id: task_id.clone(),
+ agent_id: definition.id.clone(),
+ usage: outcome.usage,
+ });
+ return Ok(outcome);
+ }
+ }
+
+ tracing::info!(
+ agent_id = %definition.id,
+ task_id = %task_id,
+ spawn_depth = attempted_depth,
+ max_spawn_depth = MAX_SPAWN_DEPTH,
+ prompt_chars = task_prompt.chars().count(),
+ skill_filter = ?options.skill_filter_override.as_deref().or(definition.skill_filter.as_deref()),
+ "[subagent_host] dispatching"
+ );
+
+ // Install the sub-agent's declared `sandbox_mode` as the active
+ // task-local for every tool invocation inside this run.
+ //
+ // When the worker opted into git-worktree isolation, its isolated
+ // checkout is carried on the `WorkspaceDescriptor` prepared below and
+ // threaded onto the run's tinyagents `RunContext`
+ // (`run_turn_via_tinyagents_shared` → `RunContext::with_workspace`).
+ // Every tool call then receives it via
+ // `ToolExecutionContext::from_run_context`, so acting tools (shell, git)
+ // resolve their CWD to that worktree (`effective_action_dir_for_context`)
+ // instead of the shared `Config.action_dir` — no task-local override
+ // needed. When no descriptor is prepared (the default / non-isolated
+ // path), tools fall through to `security.action_dir` and behaviour is
+ // unchanged.
+ let mut parent_for_subagent = parent.clone();
+ parent_for_subagent.workspace_descriptor =
+ workspace_descriptor_for_subagent(definition, &options, &parent, &task_id);
+ if let Some(descriptor) = parent_for_subagent.workspace_descriptor.as_ref() {
+ tracing::debug!(
+ agent_id = %definition.id,
+ task_id = %task_id,
+ worktree = %descriptor.root.display(),
+ policy_id = %descriptor.policy_id,
+ "[subagent_host] worktree-isolated worker: descriptor will route acting-tool CWD"
+ );
+ }
+ let run_result = with_spawn_depth(attempted_depth, async {
+ with_file_state_agent_id(task_id.clone(), async {
+ with_current_sandbox_mode(definition.sandbox_mode, async {
+ Box::pin(run_typed_mode(
+ definition,
+ task_prompt,
+ &options,
+ &parent_for_subagent,
+ &task_id,
+ &loaded_config,
+ ))
+ .await
+ })
+ .await
+ })
+ .await
+ })
+ .await;
+
+ // Feed this delegation's wall-clock into the turn's running maximum,
+ // which is the only thing the budget gate above judges a later
+ // dispatch against (#5804). The deterministic fast path above records
+ // separately and returns, so it cannot reach here twice.
+ //
+ // Recorded on BOTH the success and the failure path, and before the
+ // `?`: a delegation that ran for three minutes and then errored spent
+ // exactly as much of the turn's budget as one that succeeded, and is
+ // exactly as much evidence about what a dispatch costs. Dropping
+ // failures would bias the estimate downwards, and the gate fails open,
+ // so the bias would show up as the guard not firing when it should.
+ //
+ // Measured from the outer `started` rather than `outcome.elapsed`, so
+ // the config load and the tier/hook gates are inside the figure — the
+ // question the gate asks is how long a *dispatch* takes end to end,
+ // not how long the child's own loop ran.
+ if let Some(dispatch) = options.run_context.dispatch.as_deref() {
+ dispatch.record_subagent_elapsed(started.elapsed());
+ }
+
+ let mut outcome = run_result?;
+
+ // Commit the completed subtree before the soft, awaited artifact
+ // offload. A cancellation while that filesystem work is pending must
+ // not erase direct model usage or descendants that already finished.
+ usage_finalizer.finish(crate::agent::tinyagents::host::SubagentUsageEntry {
+ task_id: task_id.clone(),
+ agent_id: definition.id.clone(),
+ usage: outcome.usage,
+ });
+
+ // #3883: offload an oversized worker result to `action_dir/outputs/`
+ // BEFORE the cap below truncates it, so the parent receives a path plus
+ // an abstract and the full-fidelity body survives on disk instead of
+ // being cut. A refused or failed offload is soft: the inline payload
+ // continues on to the cap and the summarizer detour exactly as before.
+ offload_outcome_artifacts(&mut outcome, definition, &options, &task_id).await;
+
+ // Truncate result to the definition's cap if set (shared with the
+ // deterministic memory fast path via `apply_max_result_chars`).
+ apply_max_result_chars(&mut outcome.output, definition.max_result_chars, &definition.id);
+
+ tracing::info!(
+ agent_id = %definition.id,
+ task_id = %task_id,
+ spawn_depth = attempted_depth,
+ elapsed_ms = outcome.elapsed.as_millis() as u64,
+ iterations = outcome.iterations,
+ output_chars = outcome.output.chars().count(),
+ "[subagent_host] completed"
+ );
+
+ let _ = started; // silence unused-warning if logging is compiled out
+ Ok(outcome)
+ })
+ .await
+}
+
+/// Apply the filesystem-offload convention to a finished sub-agent run (#3883).
+///
+/// Writes an oversized result to `action_dir/outputs/` and swaps `output` for a
+/// path + abstract, then records every `[artifact]` pointer the outgoing payload
+/// carries — the harness-written one and any the worker authored itself by
+/// following the prompt contract — onto `SubagentRunOutcome::artifact_paths`, so
+/// the parent receives the paths structurally, not only as prose.
+///
+/// Every failure is soft. With no resolvable action root (or a refused target)
+/// the outcome is left untouched and the summarizer detour plus
+/// `tool_result_budget_bytes` truncation stay in charge as the fallback.
+async fn offload_outcome_artifacts(
+ outcome: &mut SubagentRunOutcome,
+ definition: &AgentDefinition,
+ options: &SubagentRunOptions,
+ task_id: &str,
+) {
+ // Pointers the WORKER authored itself (prompt contract) are read first: the
+ // harness may be about to replace `output` wholesale with its own pointer,
+ // which would otherwise drop them. They also have to survive the early
+ // returns below, so a run with no resolvable action root still reports the
+ // paths its child wrote by hand.
+ let mut paths = extract_artifact_paths(&outcome.output);
+
+ // A worktree-isolated worker offloads into its own checkout; everyone else
+ // uses the live policy's action root, which is the same root a parent's
+ // relative read resolves the returned path against.
+ let policy = crate::security::live_policy::current();
+ let Some(action_dir) = options
+ .worktree_action_dir
+ .clone()
+ .or_else(|| policy.as_ref().map(|p| p.action_dir.clone()))
+ else {
+ tracing::debug!(
+ task_id = %task_id,
+ agent_id = %outcome.agent_id,
+ worker_authored_paths = paths.len(),
+ "[artifact] no resolvable action_dir — skipping offload (summarizer/truncation backstop applies)"
+ );
+ outcome.artifact_paths = paths;
+ note_artifact_handoff(
+ HANDOFF_STAGE_RECORDED,
+ &outcome.agent_id,
+ task_id,
+ &outcome.artifact_paths,
+ );
+ return;
+ };
+
+ // A read-only tier means this run may not mutate the disk at all, so the
+ // harness does not persist on its behalf either. The result stays inline and
+ // the summarizer / truncation backstops handle it, exactly as before #3883.
+ if policy
+ .as_ref()
+ .is_some_and(|p| p.autonomy == crate::security::AutonomyLevel::ReadOnly)
+ {
+ tracing::debug!(
+ task_id = %task_id,
+ agent_id = %outcome.agent_id,
+ "[artifact] readonly autonomy tier — skipping offload (summarizer/truncation backstop applies)"
+ );
+ outcome.artifact_paths = paths;
+ note_artifact_handoff(
+ HANDOFF_STAGE_RECORDED,
+ &outcome.agent_id,
+ task_id,
+ &outcome.artifact_paths,
+ );
+ return;
+ }
+
+ // Offload at the tighter of the global default and this agent's own result
+ // cap, so a definition capped below the default (flow_memory_agent at 4 000
+ // chars, context_scout at 5 000) gets its full body on disk instead of
+ // truncated by `apply_max_result_chars` immediately after.
+ let threshold =
+ effective_offload_threshold(DEFAULT_OFFLOAD_THRESHOLD_BYTES, definition.max_result_chars);
+
+ // Worktree-isolated workers write inside their own checkout, but the parent
+ // that receives the pointer resolves relative paths against ITS action root.
+ // Render against that root so the handed-back path is one the parent can
+ // actually open (relative when the worktree nests inside it, absolute when
+ // it does not) rather than a bare `outputs/…` that silently misses.
+ let render_root = policy
+ .as_ref()
+ .map(|p| p.action_dir.clone())
+ .unwrap_or_else(|| action_dir.clone());
+ let offload = new_artifact_offload(action_dir, policy, outcome.agent_id.clone(), task_id)
+ .with_render_root(render_root);
+ let (output, _artifact) =
+ offload_oversized_result(std::mem::take(&mut outcome.output), &offload, threshold).await;
+ outcome.output = output;
+
+ // Merge: the harness pointer (if it fired) plus any worker-authored pointer
+ // read before the swap. `extract_artifact_paths` already de-duplicates
+ // within a payload; dedupe across the two sources here.
+ for path in extract_artifact_paths(&outcome.output) {
+ if !paths.contains(&path) {
+ paths.push(path);
+ }
+ }
+ outcome.artifact_paths = paths;
+ note_artifact_handoff(
+ HANDOFF_STAGE_RECORDED,
+ &outcome.agent_id,
+ task_id,
+ &outcome.artifact_paths,
+ );
+}
+
+fn workspace_descriptor_for_subagent(
+ definition: &AgentDefinition,
+ options: &SubagentRunOptions,
+ parent: &ParentExecutionContext,
+ task_id: &str,
+) -> Option<WorkspaceDescriptor> {
+ if let Some(descriptor) = options.workspace_descriptor.clone() {
+ return Some(descriptor);
+ }
+ if let Some(descriptor) = parent.workspace_descriptor.clone() {
+ return Some(descriptor);
+ }
+ let root = options.worktree_action_dir.clone()?;
+ let sandbox = match definition.sandbox_mode {
+ AgentSandboxMode::Sandboxed => TinyagentsSandboxMode::Required,
+ AgentSandboxMode::None | AgentSandboxMode::ReadOnly => TinyagentsSandboxMode::Inherit,
+ };
+ Some(
+ WorkspaceDescriptor::new(root)
+ .with_policy_id(format!("openhuman.worktree:{task_id}"))
+ .with_sandbox(sandbox),
+ )
+}
+
+/// One spawn's snapshot of the host config, loaded once by [`run_subagent`].
+///
+/// `Config::load_or_init()` is **not cached** — it re-resolves the config dirs
+/// and re-reads `config.toml` on every call. `run_typed_mode` needed it in six
+/// places, so a single sub-agent spawn used to hit the disk six times and could
+/// observe six *different* configs if the file changed mid-spawn. One snapshot
+/// is both cheaper and more coherent.
+///
+/// The error is captured as a `String` rather than dropped to `Option` because
+/// the `integrations_agent` path reports it to the caller; the other five sites
+/// degrade without it. Keeping both shapes available is what lets each site
+/// preserve its original failure behaviour.
+///
+/// Threading this in as a parameter (rather than loading it inside the runtime)
+/// is `docs/specs/plan-agents.md` Phase 3: the sub-agent runner is slated to
+/// move into TinyAgents, and a generic runtime has no config file to load.
+type LoadedConfig = Result<std::sync::Arc<crate::config::Config>, String>;
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Typed mode — narrow prompt, filtered tools, cheaper model
+// ─────────────────────────────────────────────────────────────────────────────
+
+mod toolkit_scope_filter;
+use toolkit_scope_filter::filter_cached_toolkit_actions_with_current_scope;
+
+/// Execute a sub-agent in "Typed" mode.
+///
+/// This mode builds a brand-new, minimized system prompt specifically for the
+/// agent's archetype. It filters the parent's tools down to only those allowed
+/// by the definition and per-spawn overrides.
+async fn run_typed_mode(
+ definition: &AgentDefinition,
+ task_prompt: &str,
+ options: &SubagentRunOptions,
+ parent: &ParentExecutionContext,
+ task_id: &str,
+ config: &LoadedConfig,
+) -> Result<SubagentRunOutcome, SubagentRunError> {
+ let started = Instant::now();
+
+ // Resolve model source + model. See `resolve_subagent_source` for the
+ // semantics of each ModelSpec variant; the helper itself is sync and
+ // unit-tested, and takes the config the caller already loaded.
+ let (mut subagent_source, model) = resolve_subagent_source(
+ &definition.model,
+ &definition.id,
+ config.as_ref().ok().map(|c| c.as_ref()),
+ parent.turn_model_source.clone(),
+ parent.model_name.clone(),
+ !definition.subagents.is_empty(),
+ options.model_override.as_deref(),
+ definition.temperature,
+ );
+ let temperature = definition.temperature;
+ let max_output_tokens = definition
+ .max_turn_output_tokens
+ .unwrap_or(AGENT_TURN_MAX_OUTPUT_TOKENS);
+
+ // ── Refresh connected-integrations at spawn time ───────────────────
+ //
+ // The parent session's `connected_integrations` Vec is frozen at
+ // session-start. Re-fetch from the global integrations cache here.
+ // The cache is invalidated by `ComposioConnectionCreatedSubscriber`
+ // once the OAuth handshake reaches ACTIVE/CONNECTED, so this call
+ // returns the fresh list almost for free on the warm path. Fall back
+ // to the parent's frozen list when the live fetch returns empty.
+ let live_integrations: Vec<crate::agent::prompts::ConnectedIntegration> = {
+ let signed_in = config
+ .as_ref()
+ .ok()
+ .map(|cfg| user_is_signed_in_to_composio(cfg))
+ .unwrap_or(false);
+ if !signed_in {
+ parent.connected_integrations.clone()
+ } else {
+ match config.as_ref() {
+ Ok(cfg) => {
+ use crate::integrations::composio::FetchConnectedIntegrationsStatus;
+ match crate::integrations::composio::fetch_connected_integrations_status(cfg)
+ .await
+ {
+ FetchConnectedIntegrationsStatus::Authoritative(fresh) => {
+ tracing::debug!(
+ count = fresh.len(),
+ parent_count = parent.connected_integrations.len(),
+ "[subagent_host] refreshed connected_integrations at spawn time"
+ );
+ fresh
+ }
+ FetchConnectedIntegrationsStatus::Unavailable => {
+ tracing::debug!(
+ "[subagent_host] integrations backend unavailable; falling back to parent's frozen list"
+ );
+ parent.connected_integrations.clone()
+ }
+ }
+ }
+ Err(e) => {
+ tracing::debug!(
+ error = %e,
+ "[subagent_host] config load failed; falling back to parent's frozen integrations list"
+ );
+ parent.connected_integrations.clone()
+ }
+ }
+ }
+ };
+
+ // ── Filter tools per definition + per-spawn override ───────────────
+ let toolkit_filter = options.toolkit_override.as_deref();
+ let mut allowed_indices = filter_tool_indices(
+ &parent.all_tools,
+ &definition.tools,
+ &definition.disallowed_tools,
+ options
+ .skill_filter_override
+ .as_deref()
+ .or(definition.skill_filter.as_deref()),
+ );
+
+ // Sub-agents must never spawn their own sub-agents. Strip `spawn_subagent`
+ // and every synthesised `delegate_*` tool regardless of the archetype's
+ // declared scope.
+ let before = allowed_indices.len();
+ allowed_indices.retain(|&i| {
+ let name = parent.all_tools[i].name();
+ !is_subagent_spawn_tool(name) && name != "spawn_worker_thread"
+ });
+ let stripped = before - allowed_indices.len();
+ if stripped > 0 {
+ tracing::debug!(
+ agent_id = %definition.id,
+ stripped,
+ "[subagent_host] removed sub-agent spawn tools from sub-agent's tool surface"
+ );
+ }
+
+ // ── Force-include extra_tools ──────────────────────────────────────
+ if !definition.extra_tools.is_empty() {
+ for (i, tool) in parent.all_tools.iter().enumerate() {
+ let name = tool.name();
+ if definition.extra_tools.iter().any(|n| n == name)
+ && !allowed_indices.contains(&i)
+ && !super::super::tool_prep::disallowed_tool_matches(
+ &definition.disallowed_tools,
+ name,
+ )
+ && !is_subagent_spawn_tool(name)
+ {
+ allowed_indices.push(i);
+ }
+ }
+ }
+
+ // ── Dynamic per-action toolkit tools (integrations_agent + toolkit) ──────
+ let mut dynamic_tools: Vec<Box<dyn Tool>> = Vec::new();
+ let mut lazy_resolver: Option<LazyToolkitResolver> = None;
+ let is_integrations_agent_with_toolkit =
+ definition.id == "integrations_agent" && toolkit_filter.is_some();
+
+ // `tools_agent` must never see Workflow-category tools.
+ if definition.id == "tools_agent" {
+ allowed_indices.retain(|&i| parent.all_tools[i].category() != ToolCategory::Workflow);
+ }
+ // A child may only narrow an explicit profile/channel ceiling, never widen
+ // it back to `all_tools`. The parent's own role-specific prompt surface is
+ // intentionally not a ceiling: coordinators delegate effectful work to
+ // specialists whose tools they do not advertise directly.
+ super::super::tool_prep::retain_parent_visible_tool_indices(
+ &mut allowed_indices,
+ &parent.all_tools,
+ &parent.subagent_tool_ceiling_names,
+ );
+
+ if is_integrations_agent_with_toolkit {
+ if let Some(tk) = toolkit_filter {
+ let arc_config = match config.as_ref() {
+ Ok(c) => std::sync::Arc::clone(c),
+ Err(e) => {
+ tracing::warn!(
+ agent_id = %definition.id,
+ toolkit = %tk,
+ error = %e,
+ "[subagent_host:typed] config load failed; dynamic composio tools won't be registered"
+ );
+ return Err(SubagentRunError::Provider(anyhow::anyhow!(
+ "subagent_runner: config load failed building integrations_agent for toolkit `{tk}`: {e}"
+ )));
+ }
+ };
+
+ use crate::integrations::composio::client::{
+ create_composio_client, ComposioClientKind,
+ };
+ let client_kind = match create_composio_client(arc_config.as_ref()) {
+ Ok(k) => Some(k),
+ Err(e) => {
+ tracing::warn!(
+ agent_id = %definition.id,
+ toolkit = %tk,
+ error = %e,
+ "[subagent_host:typed] composio factory failed; dynamic per-action tools fall back to cached catalogue"
+ );
+ None
+ }
+ };
+
+ if let Some(cached_integration) = live_integrations
+ .iter()
+ .find(|ci| ci.connected && ci.toolkit.eq_ignore_ascii_case(tk))
+ {
+ let fresh_actions = if !cached_integration.tools.is_empty() {
+ tracing::debug!(
+ agent_id = %definition.id,
+ toolkit = %tk,
+ cached_actions = cached_integration.tools.len(),
+ "[subagent_host:typed] using cached toolkit catalogue"
+ );
+ filter_cached_toolkit_actions_with_current_scope(
+ &definition.id,
+ tk,
+ arc_config.as_ref(),
+ &cached_integration.tools,
+ )
+ .await
+ } else {
+ match &client_kind {
+ Some(ComposioClientKind::Backend(client)) => {
+ match crate::integrations::composio::fetch_toolkit_actions(
+ arc_config.as_ref(),
+ client,
+ tk,
+ None,
+ )
+ .await
+ {
+ Ok(actions) if !actions.is_empty() => actions,
+ Ok(_) => {
+ tracing::debug!(
+ agent_id = %definition.id,
+ toolkit = %tk,
+ "[subagent_host:typed] fresh list_tools returned empty; falling back to cached catalogue"
+ );
+ cached_integration.tools.clone()
+ }
+ Err(e) => {
+ tracing::warn!(
+ agent_id = %definition.id,
+ toolkit = %tk,
+ error = %e,
+ "[subagent_host:typed] fresh list_tools failed; falling back to cached catalogue"
+ );
+ cached_integration.tools.clone()
+ }
+ }
+ }
+ Some(ComposioClientKind::Direct(_)) => {
+ tracing::info!(
+ agent_id = %definition.id,
+ toolkit = %tk,
+ cached_actions = cached_integration.tools.len(),
+ "[composio-direct] subagent_runner:typed: direct mode active — using cached catalogue, skipping backend list_tools refresh"
+ );
+ cached_integration.tools.clone()
+ }
+ None => {
+ tracing::debug!(
+ agent_id = %definition.id,
+ toolkit = %tk,
+ cached_actions = cached_integration.tools.len(),
+ "[subagent_host:typed] composio client unavailable; using cached catalogue"
+ );
+ cached_integration.tools.clone()
+ }
+ }
+ };
+ let integration = crate::agent::prompts::ConnectedIntegration {
+ toolkit: cached_integration.toolkit.clone(),
+ description: cached_integration.description.clone(),
+ tools: fresh_actions,
+ gated_tools: cached_integration.gated_tools.clone(),
+ connected: cached_integration.connected,
+ connections: cached_integration.connections.clone(),
+ non_active_status: cached_integration.non_active_status.clone(),
+ };
+ let integration = &integration;
+ let top_k = top_k_for_toolkit(tk);
+ let candidates: Vec<_> = integration
+ .tools
+ .iter()
+ .map(|tool| SelectableTool::new(&tool.name, &tool.description))
+ .collect();
+ let filter_hits = rank_tools_by_prompt(task_prompt, &candidates, top_k);
+ let selected: Vec<&crate::agent::prompts::ConnectedIntegrationTool> = if filter_hits
+ .len()
+ >= MIN_CONFIDENT_HITS
+ {
+ // The ranker's verb gate can drop every content-returning
+ // action for a find/search prompt, so the toolkit's
+ // essentials are reserved inside the same budget (#6033).
+ let kept_idx =
+ select_actions_with_essentials(tk, &integration.tools, &filter_hits, top_k);
+ let kept: Vec<_> = kept_idx.iter().map(|&i| &integration.tools[i]).collect();
+ tracing::info!(
+ agent_id = %definition.id,
+ toolkit = %tk,
+ total = integration.tools.len(),
+ kept = kept.len(),
+ top_k = top_k,
+ kept_actions = %kept
+ .iter()
+ .map(|a| a.name.as_str())
+ .collect::<Vec<_>>()
+ .join(","),
+ "[subagent_host:typed] fuzzy tool filter narrowed toolkit"
+ );
+ kept
+ } else {
+ tracing::info!(
+ agent_id = %definition.id,
+ toolkit = %tk,
+ total = integration.tools.len(),
+ filter_hits = filter_hits.len(),
+ "[subagent_host:typed] fuzzy filter thin; falling back to full toolkit"
+ );
+ integration.tools.iter().collect()
+ };
+
+ for action in selected {
+ dynamic_tools.push(Box::new(
+ crate::integrations::composio::ComposioActionTool::new(
+ arc_config.clone(),
+ action.name.clone(),
+ action.description.clone(),
+ action.parameters.clone(),
+ ),
+ ));
+ }
+ tracing::debug!(
+ agent_id = %definition.id,
+ toolkit = %tk,
+ action_count = dynamic_tools.len(),
+ "[subagent_host:typed] dynamically registered per-action composio tools"
+ );
+ lazy_resolver = Some(LazyToolkitResolver {
+ config: arc_config.clone(),
+ actions: integration.tools.clone(),
+ resolved: std::sync::Mutex::default(),
+ });
+ } else {
+ tracing::warn!(
+ agent_id = %definition.id,
+ toolkit = %tk,
+ "[subagent_host:typed] toolkit not found among parent's connected integrations; sub-agent will have no callable actions (spawn_subagent pre-flight should have caught this)"
+ );
+ }
+ }
+ }
+
+ // Dynamic Composio action tools are effectful too. Do not let delegation
+ // synthesize one that the parent profile/policy did not expose. Internal
+ // runner-only tools (such as extract_from_result below) are added after
+ // this intersection and cannot access the filesystem/process surface.
+ if !parent.subagent_tool_ceiling_names.is_empty() {
+ dynamic_tools.retain(|tool| parent.subagent_tool_ceiling_names.contains(tool.name()));
+ }
+
+ // ── Progressive-disclosure handoff cache ───────────────────────────
+ let handoff_cache: Option<Arc<ResultHandoffCache>> = if is_integrations_agent_with_toolkit {
+ let cache = Arc::new(ResultHandoffCache::new());
+ let parent_chain = match parent.session_parent_prefix.as_deref() {
+ Some(prefix) => format!("{}__{}", prefix, parent.session_key),
+ None => parent.session_key.clone(),
+ };
+ // Resolve the extraction provider + model through the `summarization`
+ // role so extraction follows the user's `memory_provider` routing.
+ //
+ // When summarization routes to the **managed** backend, the parent
+ // provider already speaks the managed tier names, so we reuse it with the
+ // fixed `summarization-v1` model — no redundant provider build, and (with
+ // no live backend) no network dependency. Only when summarization routes
+ // to a **concrete BYOK/local** provider — exactly where passing the
+ // parent agent's (agentic) provider the literal `summarization-v1` would
+ // 400/404 — do we build the dedicated summarization provider so the call
+ // lands on the right endpoint + model.
+ //
+ // A local parent never reuses (its runtime would 404 on the managed tier
+ // string): it falls through to building the managed summarization
+ // provider. Any config/factory glitch degrades to parent + the fixed tier
+ // id rather than dead-ending extraction.
+ let summarization_tier =
+ crate::inference::provider::factory::summarization_tier_model().to_string();
+ // The extract summarizer stays on the resolved `Provider` (the extract's own
+ // summarization resolution, incl. test-injected mocks + the managed-vs-local
+ // decision). It is NOT flipped to a role-resolved crate-native source: that
+ // would re-resolve "summarization" from config and bypass the resolved
+ // provider — production stays managed either way, but a test mock injected on
+ // the parent/extract provider would no longer be observed (issue #4249 P3-B:
+ // the extract flip is deferred; the turn-path flip goes through the primary
+ // producers instead).
+ let (extract_source, extract_model) = match config.as_ref() {
+ Ok(cfg) => {
+ let route = crate::inference::provider::provider_for_role("summarization", cfg);
+ let r = route.trim();
+ let route_is_managed = r.is_empty() || r == "cloud" || r == "openhuman";
+ if route_is_managed && !parent.turn_model_source.is_local_provider() {
+ (parent.turn_model_source.clone(), summarization_tier.clone())
+ } else {
+ match crate::inference::provider::create_chat_model_with_model_id(
+ "summarization",
+ cfg,
+ parent.temperature,
+ ) {
+ Ok((_model, resolved_model)) => (
+ crate::agent::tinyagents::TurnModelSource::new_crate_native(
+ "summarization",
+ // Already an `Arc` from the spawn-wide snapshot —
+ // share it rather than deep-copying the Config.
+ Arc::clone(cfg),
+ ),
+ resolved_model,
+ ),
+ Err(e) => {
+ tracing::warn!(
+ agent_id = %definition.id,
+ error = %e,
+ "[subagent_host:typed] extract summarization provider build failed; falling back to parent provider"
+ );
+ (parent.turn_model_source.clone(), summarization_tier.clone())
+ }
+ }
+ }
+ }
+ Err(e) => {
+ tracing::warn!(
+ agent_id = %definition.id,
+ error = %e,
+ "[subagent_host:typed] config load failed for extract provider; falling back to parent provider + summarization-v1"
+ );
+ (parent.turn_model_source.clone(), summarization_tier.clone())
+ }
+ };
+ dynamic_tools.push(Box::new(ExtractFromResultTool::new(
+ cache.clone(),
+ extract_source,
+ extract_model,
+ parent.workspace_dir.clone(),
+ parent_chain,
+ definition.id.clone(),
+ )));
+ tracing::debug!(
+ agent_id = %definition.id,
+ "[subagent_host:typed] registered extract_from_result tool + handoff cache"
+ );
+ Some(cache)
+ } else {
+ None
+ };
+
+ // Dynamic tools never pass through `allowed_indices`, so the strip above has
+ // not seen them — the one route by which a spawn/delegate name can reach a
+ // child admitted (issue #6157). Strip before their five consumers below.
+ strip_spawn_tools_from_dynamic(&mut dynamic_tools, &definition.id);
+
+ // Build provider-visible tool schemas in EXECUTION-PRECEDENCE order:
+ // `dynamic_tools` (extra_tools at runtime) before parent specs.
+ let mut filtered_specs: Vec<ToolSpec> = dynamic_tools.iter().map(|t| t.spec()).collect();
+ filtered_specs.extend(
+ allowed_indices
+ .iter()
+ .map(|&i| parent.all_tool_specs[i].as_ref().clone()),
+ );
+ let mut allowed_names: HashSet<String> = allowed_indices
+ .iter()
+ .map(|&i| parent.all_tools[i].name().to_string())
+ .collect();
+ // Dynamic tool names must also be in the allowlist so the inner loop
+ // accepts model tool_calls that reference them.
+ for tool in &dynamic_tools {
+ allowed_names.insert(tool.name().to_string());
+ }
+ let filtered_specs = crate::agent::session_host::dedup_visible_tool_specs(filtered_specs);
+ let filtered_specs = dedup_tool_specs_by_name(&definition.id, filtered_specs);
+
+ tracing::debug!(
+ agent_id = %definition.id,
+ model = %model,
+ tool_count = allowed_names.len(),
+ max_iterations = subagent_iter_cap_with_autonomous_lift(definition.effective_max_iterations()),
+ iteration_policy = ?definition.iteration_policy,
+ "[subagent_host:typed] resolved configuration"
+ );
+
+ // ── Build the narrow system prompt ─────────────────────────────────
+ let render_options = SubagentRenderOptions::from_definition_flags(
+ definition.omit_identity,
+ definition.omit_safety_preamble,
+ definition.omit_profile,
+ definition.omit_memory_md,
+ );
+
+ let narrowed_integrations: Vec<crate::agent::prompts::ConnectedIntegration> =
+ match toolkit_filter {
+ Some(tk) => live_integrations
+ .iter()
+ .filter(|ci| ci.connected && ci.toolkit.eq_ignore_ascii_case(tk))
+ .cloned()
+ .collect(),
+ None => live_integrations
+ .iter()
+ .filter(|ci| ci.connected)
+ .cloned()
+ .collect(),
+ };
+
+ let prompt_tools: Vec<PromptTool<'_>> = allowed_indices
+ .iter()
+ .map(|&i| {
+ let t = parent.all_tools[i].as_ref();
+ PromptTool {
+ name: t.name(),
+ description: t.description(),
+ parameters_schema: Some(t.parameters_schema().to_string()),
+ }
+ })
+ .chain(dynamic_tools.iter().map(|t| PromptTool {
+ name: t.name(),
+ description: t.description(),
+ parameters_schema: Some(t.parameters_schema().to_string()),
+ }))
+ .collect();
+ let visible_tool_names: std::collections::HashSet<String> =
+ prompt_tools.iter().map(|t| t.name.to_string()).collect();
+ let (prompt_tool_call_format, dispatcher_instructions) =
+ subagent_prompt_protocol(parent.tool_call_format, is_integrations_agent_with_toolkit);
+ // Load AGENTS.md instruction layers once, at prompt-build time, when the
+ // config gate is on. The global layer comes from the workspace dir; the
+ // project layer comes from the sub-agent's `worktree_action_dir` override
+ // when present (git-worktree isolation), otherwise the global config
+ // `action_dir`. Loading here (not per turn) keeps the sub-agent system
+ // prompt byte-stable for prefix caching.
+ let agents_md = if parent.agent_config.agents_md_enabled {
+ let local_dir = options
+ .worktree_action_dir
+ .clone()
+ .or_else(|| config.as_ref().ok().map(|c| c.action_dir.clone()));
+ match local_dir {
+ Some(dir) => crate::agent::prompts::load_agents_md_layers(&parent.workspace_dir, &dir),
+ None => {
+ // No resolvable project dir — still surface the workspace layer.
+ crate::agent::prompts::AgentsMdContent {
+ global: crate::agent::prompts::load_agents_md(&parent.workspace_dir),
+ local: None,
+ }
+ }
+ }
+ } else {
+ tracing::debug!(
+ agent_id = %definition.id,
+ "[agents_md] disabled by config; skipping AGENTS.md injection for subagent"
+ );
+ crate::agent::prompts::AgentsMdContent::default()
+ };
+
+ let prompt_ctx = PromptContext {
+ workspace_dir: &parent.workspace_dir,
+ model_name: &model,
+ agent_id: &definition.id,
+ tools: &prompt_tools,
+ workflows: &parent.workflows,
+ dispatcher_instructions: &dispatcher_instructions,
+ learned: crate::agent::prompts::LearnedContextData::default(),
+ visible_tool_names: &visible_tool_names,
+ tool_call_format: prompt_tool_call_format,
+ connected_integrations: &narrowed_integrations,
+ connected_identities_md: crate::agent::prompts::render_connected_identities(),
+ include_profile: !definition.omit_profile,
+ include_memory_md: !definition.omit_memory_md,
+ curated_snapshot: None,
+ user_identity: crate::security::credentials::identity::peek_credential_user_identity(),
+ personality_roster: vec![],
+ agents_md_global: agents_md.global.clone(),
+ agents_md_local: agents_md.local.clone(),
+ };
+
+ let system_prompt = match &definition.system_prompt {
+ PromptSource::Dynamic(build) => {
+ build(&prompt_ctx).map_err(|e| SubagentRunError::PromptLoad {
+ path: format!("<dynamic:{}>", definition.id),
+ source: std::io::Error::other(e.to_string()),
+ })?
+ }
+ PromptSource::Inline(_) | PromptSource::File { .. } => {
+ let archetype_prompt_body = load_prompt_source(&definition.system_prompt, &prompt_ctx)?;
+ render_subagent_system_prompt_with_format(
+ &parent.workspace_dir,
+ &model,
+ &allowed_indices,
+ &parent.all_tools,
+ &dynamic_tools,
+ &archetype_prompt_body,
+ render_options,
+ prompt_tool_call_format,
+ &narrowed_integrations,
+ agents_md.global.as_deref(),
+ agents_md.local.as_deref(),
+ )
+ }
+ };
+
+ let system_prompt = append_subagent_role_contract(system_prompt, &definition.id);
+ // #3883: only agents that actually hold a file-write tool are told to
+ // offload. `visible_tool_names` is this sub-agent's real, post-filter tool
+ // surface, so the contract can never advertise a tool the child cannot call.
+ let system_prompt =
+ append_artifact_offload_contract(system_prompt, &definition.id, &visible_tool_names);
+
+ // ── Build the user message (with optional context prefix) ──────────
+ // Shared one-line stamp (#3602) so sub-agents report time in the same
+ // format as the main agent. Lives on the user message because sub-agent
+ // system prompts are byte-stable for prefix caching.
+ let now_str = crate::agent::prompts::current_datetime_line();
+
+ let mut context_parts: Vec<&str> = Vec::new();
+ if !definition.omit_memory_context {
+ if let Some(ref mem_ctx) = *parent.memory_context {
+ context_parts.push(mem_ctx);
+ }
+ }
+ context_parts.push(&now_str);
+
+ if let Some(ref ctx) = options.context {
+ context_parts.push(ctx);
+ }
+ let mut history: Vec<crate::agent::messages::ChatMessage> =
+ if let Some(ref initial) = options.initial_history {
+ tracing::info!(
+ agent_id = %definition.id,
+ task_id = %task_id,
+ history_len = initial.len(),
+ "[subagent_host] resuming with initial_history (checkpoint replay)"
+ );
+ initial.clone()
+ } else {
+ let user_message = if context_parts.is_empty() {
+ task_prompt.to_string()
+ } else {
+ format!("[Context]\n{}\n\n{task_prompt}", context_parts.join("\n\n"))
+ };
+ vec![
+ crate::agent::messages::ChatMessage::system(system_prompt),
+ crate::agent::messages::ChatMessage::user(user_message),
+ ]
+ };
+
+ // `integrations_agent` with a resolved toolkit runs in **text mode**: its
+ // large per-action Composio toolkit compiles into a provider grammar that
+ // blows the native tool-schema ceiling, so omit native tool advertisement and
+ // describe the tools in the system prompt as prose, parsing `<tool_call>` tags
+ // from the response (legacy `force_text_mode` parity — the tinyagents rewrite
+ // dropped it, so integrations turns advertised native schemas the backend then
+ // rejected). Wrapping the provider clears `native_tool_calling`, which makes
+ // the model adapter skip native advertisement and fall back to XML parsing.
+ if is_integrations_agent_with_toolkit {
+ if let Some(sys) = history.iter_mut().find(|m| m.role == "system") {
+ sys.content.push_str("\n\n");
+ sys.content.push_str(&build_text_mode_tool_instructions());
+ }
+ tracing::info!(
+ agent_id = %definition.id,
+ task_id = %task_id,
+ tool_count = filtered_specs.len(),
+ "[subagent_host:text-mode] omitting native tool schemas; injected XML tool protocol into system prompt"
+ );
+ subagent_source = subagent_source.with_text_mode();
+ }
+
+ // ── Run the inner tool-call loop ───────────────────────────────────
+ // Resolve the sub-agent model's user-configured vision flag; defaults to
+ // `false` when config can't be loaded. Combined with the provider capability
+ // at the gate, this lets a flagged custom/BYOK sub-agent model forward images.
+ let model_vision = config
+ .as_ref()
+ .ok()
+ .map(|cfg| crate::inference::model_context::model_supports_vision(&model, cfg))
+ .unwrap_or(false);
+ tracing::debug!(
+ target: "subagent_runner",
+ model = %model,
+ model_vision,
+ "[subagent_host] resolved sub-agent model vision capability"
+ );
+ // Sub-agent turns run through the tinyagents harness (issue #4249): the graph
+ // route reuses the same provider + tools and mirrors every legacy seam (child
+ // progress, steering, cap checkpoint, ask_user_clarification pause,
+ // worker-thread mirror). The legacy `run_inner_loop` has been removed.
+ //
+ // `model_vision` and `max_output_tokens` are now forwarded into the graph
+ // route (image rehydration + per-call output cap). `lazy_resolver` /
+ // `handoff_cache` — the integrations-agent progressive-disclosure seams — are
+ // not yet re-expressed on the tinyagents path; they need a tool-result
+ // interception middleware and are tracked as a follow-up (issue #4249, 1b).
+ // `handoff_cache` is now threaded into the graph route below (progressive
+ // disclosure). `lazy_resolver` remains a follow-up (#4249 1b).
+ let _ = &lazy_resolver;
+ // Per-agent turn graph (issue #4249): `Default` runs the shared sub-agent
+ // graph; `Custom` hands the assembled turn to this agent's own graph runner
+ // (declared in its `graph.rs::graph()`). Every built-in agent selects
+ // `Default` today — the branch is the extension point.
+ use super::graph::AggregatedUsage;
+ use crate::agent::harness::agent_graph::AgentGraph;
+ // Resolve the child transcript stem once — `{parent_chain}__{child_session_key}`
+ // — so the sub-agent's raw transcript lands in `session_raw` under a filename
+ // that chains the parent session (parity with the removed observer stem).
+ let child_session_key = {
+ 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 sanitized: String = definition
+ .id
+ .chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
+ c
+ } else {
+ '_'
+ }
+ })
+ .collect();
+ let task_suffix: String = task_id
+ .chars()
+ .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
+ .take(12)
+ .collect();
+ if task_suffix.is_empty() {
+ format!("{unix_ts}_{nanos:09}_{sanitized}")
+ } else {
+ format!("{unix_ts}_{nanos:09}_{sanitized}_{task_suffix}")
+ }
+ };
+ let transcript_stem = {
+ let parent_chain = match parent.session_parent_prefix.as_deref() {
+ Some(prefix) => format!("{}__{}", prefix, parent.session_key),
+ None => parent.session_key.clone(),
+ };
+ format!("{parent_chain}__{child_session_key}")
+ };
+ let workspace_descriptor =
+ workspace_descriptor_for_subagent(definition, options, parent, task_id);
+ if let Some(descriptor) = &workspace_descriptor {
+ tracing::debug!(
+ agent_id = %definition.id,
+ task_id,
+ root = %descriptor.root.display(),
+ policy_id = %descriptor.policy_id,
+ "[subagent_host] prepared workspace descriptor for tinyagents run"
+ );
+ }
+
+ let (output, iterations, agg_usage, early_exit_tool, hit_cap, breaker_halt) =
+ match &definition.graph {
+ AgentGraph::Default => {
+ super::graph::run_subagent_via_graph(
+ subagent_source.clone(),
+ &model,
+ temperature,
+ &mut history,
+ parent.all_tools.clone(),
+ dynamic_tools,
+ filtered_specs.clone(),
+ allowed_names,
+ subagent_iter_cap_with_autonomous_lift(definition.effective_max_iterations()),
+ options.run_queue.clone(),
+ parent.on_progress.clone(),
+ &definition.id,
+ task_id,
+ definition.iteration_policy == IterationPolicy::Extended,
+ options.thread_id.clone(),
+ options.run_context.clone(),
+ options.worker_thread_id.clone(),
+ parent.workspace_dir.clone(),
+ workspace_descriptor.clone(),
+ max_output_tokens,
+ model_vision,
+ &transcript_stem,
+ // Sub-agent turns record their provider label as the literal
+ // "subagent" (parity with the legacy observer's TurnObserver
+ // provenance), distinguishing delegated spend from the parent's
+ // own channel in per-thread usage reads.
+ "subagent",
+ // Progressive-disclosure handoff cache (shared with the
+ // extract_from_result tool registered above).
+ handoff_cache.clone(),
+ // Agent-level TokenJuice profile → sub-agent context middleware
+ // (#4466), so sub-agent tool outputs compact like the chat path.
+ definition.effective_tokenjuice_compression(),
+ // The spawn-wide config snapshot supplies the `[context]`
+ // knobs the graph used to load for itself.
+ config.as_ref().ok().map(|c| c.as_ref()),
+ )
+ .await?
+ }
+ AgentGraph::Custom(run) => {
+ let req = AgentTurnRequest {
+ turn_model_source: subagent_source.clone(),
+ model: model.clone(),
+ temperature,
+ history: std::mem::take(&mut history),
+ parent_tools: parent.all_tools.clone(),
+ dynamic_tools,
+ specs: filtered_specs.clone(),
+ allowed_names,
+ max_iterations: subagent_iter_cap_with_autonomous_lift(
+ definition.effective_max_iterations(),
+ ),
+ run_queue: options.run_queue.clone(),
+ on_progress: parent.on_progress.clone(),
+ agent_id: definition.id.clone(),
+ task_id: task_id.to_string(),
+ extended_policy: definition.iteration_policy == IterationPolicy::Extended,
+ thread_id: options.thread_id.clone(),
+ run_context: options.run_context.clone(),
+ worker_thread_id: options.worker_thread_id.clone(),
+ workspace_dir: parent.workspace_dir.clone(),
+ workspace_descriptor: workspace_descriptor.clone(),
+ max_output_tokens,
+ model_vision,
+ transcript_stem: transcript_stem.clone(),
+ provider_label: "subagent".to_string(),
+ handoff_cache: handoff_cache.clone(),
+ tokenjuice_compression: definition.effective_tokenjuice_compression(),
+ config: config.as_ref().ok().map(Arc::clone),
+ };
+ let res = run(req).await?;
+ history = res.history;
+ let AgentTurnUsage {
+ input_tokens,
+ output_tokens,
+ cached_input_tokens,
+ charged_amount_usd,
+ } = res.usage;
+ (
+ res.output,
+ res.iterations,
+ AggregatedUsage {
+ input_tokens,
+ output_tokens,
+ cached_input_tokens,
+ charged_amount_usd,
+ },
+ res.early_exit_tool,
+ res.hit_cap,
+ res.breaker_halt,
+ )
+ }
+ };
+
+ // Determine status: if the turn engine exited early because of
+ // ask_user_clarification, checkpoint the history and return
+ // AwaitingUser so the orchestrator can relay the user's answer.
+ let status = if early_exit_tool.as_deref() == Some("ask_user_clarification") {
+ let question = output.clone();
+ let options_vec: Option<Vec<String>> = None;
+
+ crate::agent::subagent_host::types::SubagentRunStatus::AwaitingUser {
+ question,
+ options: options_vec,
+ // The neutral driver's persistence seam writes the one scoped
+ // checkpoint after the executor returns. Writing here would make
+ // pause effects visible before lifecycle admission and duplicate
+ // the durable record.
+ checkpoint: None,
+ }
+ } else if let Some(reason) = breaker_halt {
+ // The repeated-failure / repeat-progress circuit breaker halted the run
+ // (#4466). It is NOT a clean finish: `output` carries the breaker's
+ // root-cause summary, not a completed answer. Surface `Incomplete` with
+ // the halt reason so a delegating parent relays the blocker instead of
+ // treating the halted child as finished (the migrated path reported
+ // `hit_cap=false` → `Completed`, hiding the halt).
+ tracing::warn!(
+ task_id = %task_id,
+ agent_id = %definition.id,
+ reason = %reason,
+ "[subagent_host] child halted by circuit breaker; reporting Incomplete (#4466)"
+ );
+ crate::agent::subagent_host::types::SubagentRunStatus::Incomplete { reason }
+ } else if hit_cap {
+ // The tinyagents run stopped at the model-call cap with work still
+ // pending (graph summarized a resumable checkpoint into `output`).
+ // Surface it as Incomplete so the delegating agent relays the partial
+ // result + blocker instead of treating the summary as a finished answer
+ // or re-spinning the identical delegation (#4096).
+ crate::agent::subagent_host::types::SubagentRunStatus::Incomplete {
+ reason: "reached its tool-call limit before finishing".into(),
+ }
+ } else {
+ // A clean final response. (An `ask_user_clarification` early-exit is
+ // handled by the branch above.) The legacy circuit-breaker `Halted`
+ // distinction folds into the tinyagents stop-hook / cap handling.
+ crate::agent::subagent_host::types::SubagentRunStatus::Completed
+ };
+
+ // Surface this run's token/cost totals so the parent turn can roll them
+ // into the session-level meters and the global cost tracker. The caller's
+ // explicit host carrier owns the ledger; no Tokio task scope is involved.
+ let mut usage = crate::agent::subagent_host::types::SubagentUsage {
+ input_tokens: agg_usage.input_tokens,
+ output_tokens: agg_usage.output_tokens,
+ cached_input_tokens: agg_usage.cached_input_tokens,
+ charged_amount_usd: agg_usage.charged_amount_usd,
+ };
+ // A nested child records on this run's isolated ledger. Fold those totals
+ // into the completed child before writing the immediate parent's ledger so
+ // the root always receives complete subtree spend without siblings sharing
+ // mutable in-flight state.
+ for entry in options.run_context.subagent_usage_entries() {
+ usage.input_tokens = usage.input_tokens.saturating_add(entry.usage.input_tokens);
+ usage.output_tokens = usage
+ .output_tokens
+ .saturating_add(entry.usage.output_tokens);
+ usage.cached_input_tokens = usage
+ .cached_input_tokens
+ .saturating_add(entry.usage.cached_input_tokens);
+ usage.charged_amount_usd += entry.usage.charged_amount_usd;
+ }
+ Ok(SubagentRunOutcome {
+ task_id: task_id.to_string(),
+ agent_id: definition.id.clone(),
+ output,
+ iterations,
+ elapsed: started.elapsed(),
+ mode: SubagentMode::Typed,
+ status,
+ final_history: history,
+ usage,
+ // Filled in by `run_subagent` once the offload step has had its say, so
+ // both the harness-offloaded and worker-authored pointers are counted.
+ artifact_paths: Vec::new(),
+ persistence_disposition:
+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalExisting,
+ })
+}
+
+#[cfg(test)]
+#[path = "runner_fast_path_tests_tests.rs"]
+mod fast_path_tests;
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.rs
new file mode 100644
index 0000000000..8e281635ae
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner/toolkit_scope_filter.rs
@@ -0,0 +1,39 @@
+//! 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/subagent_host/ops/runner_checkpoint_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner_checkpoint_tests.rs
new file mode 100644
index 0000000000..8c4340849d
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner_checkpoint_tests.rs
@@ -0,0 +1,161 @@
+//! `write_pause_checkpoint` — the pause-persistence contract (#5928).
+//!
+//! Every failure branch returns `None`, and that `None` is what stops the
+//! runner reporting a resumable `AwaitingUser` for a pause it never saved.
+//! Before this, all three failures were logged at `warn` and then dropped, so
+//! the orchestrator relayed a `task_id` and asked the user to answer a question
+//! whose answer had nowhere to go.
+
+use crate::agent::subagent_host::types::SubagentCheckpointData;
+
+fn checkpoint_data(task_id: &str) -> SubagentCheckpointData {
+ SubagentCheckpointData {
+ task_key: None,
+ task_id: task_id.to_string(),
+ agent_id: "researcher".to_string(),
+ worker_thread_id: None,
+ history: Vec::new(),
+ question: "Which region?".to_string(),
+ options: None,
+ toolkit_override: None,
+ skill_filter_override: None,
+ model_override: None,
+ created_at: "2026-09-02T00:00:00Z".to_string(),
+ resume_checkpoint: None,
+ resume_metadata: Default::default(),
+ output: String::new(),
+ iterations: 0,
+ usage: Default::default(),
+ artifact_paths: Vec::new(),
+ elapsed_ms: 0,
+ }
+}
+
+#[test]
+fn a_written_checkpoint_returns_the_path_it_wrote() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let checkpoint_dir = dir.path().join("subagent_checkpoints");
+
+ let written = super::write(&checkpoint_dir, "task-1", &checkpoint_data("task-1"))
+ .expect("a writable directory must produce a checkpoint");
+
+ assert_eq!(
+ written,
+ checkpoint_dir.join("task-1.json"),
+ "the returned path must be the one the resume flow will read"
+ );
+ assert!(written.is_file(), "the checkpoint must exist on disk");
+
+ // Round-trips: a resume reads this back with `serde_json::from_str`, so a
+ // path that exists but cannot be parsed is no better than a missing one.
+ let raw = std::fs::read_to_string(&written).expect("read back");
+ let parsed: SubagentCheckpointData = serde_json::from_str(&raw).expect("checkpoint parses");
+ assert_eq!(parsed.task_id, "task-1");
+ assert_eq!(parsed.question, "Which region?");
+}
+
+#[test]
+fn the_directory_is_created_on_demand() {
+ // #5928 asks whether the checkpoint directory is created correctly on fresh
+ // installs. It is: nothing pre-creates it, `write_pause_checkpoint` does,
+ // including intermediate components.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let nested = dir.path().join("a/b/c/subagent_checkpoints");
+ assert!(!nested.exists(), "precondition: nothing has created it");
+
+ let written = super::write(&nested, "task-2", &checkpoint_data("task-2"))
+ .expect("a missing directory must be created, not treated as a failure");
+
+ assert!(written.is_file());
+}
+
+#[test]
+fn an_uncreatable_directory_reports_no_checkpoint() {
+ // A regular file where the directory should be: `create_dir_all` cannot
+ // succeed, and the pause is not resumable from disk.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let blocked = dir.path().join("not_a_dir");
+ std::fs::write(&blocked, b"i am a file").expect("seed the blocker");
+
+ assert!(
+ super::write(&blocked, "task-3", &checkpoint_data("task-3")).is_none(),
+ "a checkpoint directory that cannot exist must report no checkpoint, \
+ not a silently dropped warning"
+ );
+}
+
+#[test]
+fn an_unwritable_target_reports_no_checkpoint() {
+ // The directory exists, but the checkpoint's own path is occupied by a
+ // directory, so the write cannot land.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let checkpoint_dir = dir.path().join("subagent_checkpoints");
+ std::fs::create_dir_all(checkpoint_dir.join("task-4.json")).expect("occupy the target path");
+
+ assert!(
+ super::write(&checkpoint_dir, "task-4", &checkpoint_data("task-4")).is_none(),
+ "a checkpoint whose write fails must report no checkpoint"
+ );
+}
+
+// ── task_id is untrusted on its way into a path (tinysweeper, #5951) ────────
+//
+// `continue_subagent` takes `task_id` from its tool arguments — model-authored
+// — and feeds it back through `SubagentRunOptions::task_id`, so a re-paused
+// child writes a checkpoint under a name the model chose. Joined unchecked,
+// `../` walks the write out of the checkpoint directory entirely.
+
+#[test]
+fn a_traversing_task_id_is_refused_rather_than_written() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let checkpoint_dir = dir.path().join("subagent_checkpoints");
+ let outside = dir.path().join("outside.json");
+
+ assert!(
+ super::write(
+ &checkpoint_dir,
+ "../outside",
+ &checkpoint_data("../outside")
+ )
+ .is_none(),
+ "a traversing task id must not produce a checkpoint"
+ );
+ assert!(
+ !outside.exists(),
+ "the write must not land outside the checkpoint directory"
+ );
+
+ for bad in [
+ "../../etc/cron.d/pwn",
+ "a/b",
+ "a\\b",
+ "..",
+ ".",
+ "",
+ "with space",
+ "sub-\u{00e9}",
+ ] {
+ assert!(
+ !super::is_safe_task_id(bad),
+ "{bad:?} must be rejected as a checkpoint filename"
+ );
+ }
+}
+
+#[test]
+fn the_ids_this_system_actually_mints_are_accepted() {
+ // The guard is an allow-list, so it has to admit every shape in real use —
+ // otherwise it would break resumption instead of hardening it.
+ for good in [
+ "sub-2b9d1f4e-0c3a-4f10-9c2e-6a7b8c9d0e1f",
+ "subsess-2b9d1f4e-0c3a-4f10-9c2e-6a7b8c9d0e1f",
+ "task-fleet-b",
+ "t1",
+ "t_steer",
+ ] {
+ assert!(
+ super::is_safe_task_id(good),
+ "{good:?} is a real id shape and must be accepted"
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner_fast_path_tests_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner_fast_path_tests_tests.rs
new file mode 100644
index 0000000000..4169fa8753
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner_fast_path_tests_tests.rs
@@ -0,0 +1,145 @@
+use super::{
+ apply_max_result_chars, format_deterministic_memory_hits, parse_memory_fast_path_enabled,
+ MEMORY_FAST_PATH_LIMIT,
+};
+use crate::memory::api::provider::retrieval::{RetrievalHit, RetrievalNodeKind, RetrievalResponse};
+use chrono::Utc;
+
+// The contract's hit, not the engine's. `tree_kind` is an open `String`
+// here where the engine's is a `TreeKind` enum; the module serialises that
+// enum with `rename_all = "snake_case"`, so `"source"` is the same value
+// the engine's `TreeKind::Source` encodes to — no fixture drift, and one
+// fewer `tinycortex::` import in the tree (#5560).
+fn hit(content: &str, scope: &str, score: f32) -> RetrievalHit {
+ RetrievalHit {
+ node_id: "n1".into(),
+ node_kind: RetrievalNodeKind::Summary,
+ tree_id: "t1".into(),
+ tree_kind: Some("source".into()),
+ tree_scope: scope.into(),
+ level: 1,
+ content: content.into(),
+ entities: vec![],
+ topics: vec![],
+ time_range_start: Utc::now(),
+ time_range_end: Utc::now(),
+ score,
+ child_ids: vec![],
+ source_ref: None,
+ }
+}
+
+#[test]
+fn fast_path_enabled_by_default_and_opt_out_parsing() {
+ // Unset / unrecognised → enabled (fast path on by default).
+ assert!(parse_memory_fast_path_enabled(None));
+ assert!(parse_memory_fast_path_enabled(Some("1")));
+ assert!(parse_memory_fast_path_enabled(Some("yes")));
+ // Explicit falsy values → disabled (fall back to the model walk).
+ for off in ["0", "false", "no", "off", " OFF ", "False"] {
+ assert!(
+ !parse_memory_fast_path_enabled(Some(off)),
+ "{off:?} must disable the fast path"
+ );
+ }
+}
+
+#[test]
+fn format_returns_none_for_no_hits() {
+ // Empty response → None so the caller falls back to the full sub-agent
+ // (the empty/degraded case is #4655's territory, not this fast path).
+ let resp = RetrievalResponse::default();
+ assert!(format_deterministic_memory_hits(&resp).is_none());
+}
+
+#[test]
+fn format_renders_hits_with_scope_content_and_score() {
+ let resp = RetrievalResponse {
+ hits: vec![
+ hit("Q3 OKR is to ship memory v2", "notes", 0.91),
+ hit("prefers concise replies", "profile", 0.80),
+ ],
+ total: 2,
+ truncated: false,
+ };
+ let out = format_deterministic_memory_hits(&resp).expect("hits present → Some");
+ assert!(out.contains("Retrieved 2 relevant memories"), "{out}");
+ assert!(out.contains("[notes] Q3 OKR is to ship memory v2"), "{out}");
+ assert!(out.contains("[profile] prefers concise replies"), "{out}");
+ assert!(out.contains("(relevance 0.91)"), "{out}");
+ // Numbered list, no LLM synthesis needed.
+ assert!(out.contains("1. ") && out.contains("2. "), "{out}");
+}
+
+#[test]
+fn format_singular_wording_for_one_hit() {
+ let resp = RetrievalResponse {
+ hits: vec![hit("only one", "memory", 0.5)],
+ total: 1,
+ truncated: false,
+ };
+ let out = format_deterministic_memory_hits(&resp).unwrap();
+ assert!(out.contains("Retrieved 1 relevant memory"), "{out}");
+}
+
+#[test]
+fn format_truncates_oversized_hit_body() {
+ let big = "x".repeat(5_000);
+ let resp = RetrievalResponse {
+ hits: vec![hit(&big, "memory", 0.42)],
+ total: 1,
+ truncated: false,
+ };
+ let out = format_deterministic_memory_hits(&resp).unwrap();
+ assert!(
+ out.contains(" …"),
+ "oversized body must be ellipsised: {out}"
+ );
+ assert!(
+ out.chars().count() < big.chars().count(),
+ "output must be shorter than the raw 5k-char body"
+ );
+}
+
+#[test]
+fn fast_path_limit_is_small_single_digit() {
+ // Guards against an accidental blow-up of the deterministic fan-out.
+ assert!(
+ (1..=16).contains(&MEMORY_FAST_PATH_LIMIT),
+ "fast-path limit should stay small: {MEMORY_FAST_PATH_LIMIT}"
+ );
+}
+
+#[test]
+fn max_result_chars_none_is_noop() {
+ // No cap → output untouched (the `agent_memory` default).
+ let mut out = "hello world".to_string();
+ apply_max_result_chars(&mut out, None, "agent_memory");
+ assert_eq!(out, "hello world");
+}
+
+#[test]
+fn max_result_chars_under_cap_is_noop() {
+ let mut out = "short".to_string();
+ apply_max_result_chars(&mut out, Some(100), "agent_memory");
+ assert_eq!(out, "short");
+}
+
+#[test]
+fn max_result_chars_over_cap_truncates_with_marker() {
+ let mut out = "x".repeat(50);
+ apply_max_result_chars(&mut out, Some(10), "agent_memory");
+ assert!(out.starts_with(&"x".repeat(10)), "{out}");
+ assert!(out.ends_with("[...truncated]"), "{out}");
+ // 10 kept chars + the marker, and shorter than the 50-char original.
+ assert!(out.chars().count() < 50, "{out}");
+}
+
+#[test]
+fn max_result_chars_truncates_on_char_boundary_for_multibyte() {
+ // Cap lands mid-run of multi-byte chars; must not panic or split a char.
+ let mut out = "é".repeat(20); // each 'é' is 2 bytes
+ apply_max_result_chars(&mut out, Some(5), "agent_memory");
+ assert!(out.starts_with(&"é".repeat(5)), "{out}");
+ assert!(out.ends_with("[...truncated]"), "{out}");
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_dedup_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_dedup_tests.rs
new file mode 100644
index 0000000000..4df9bc1471
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops_dedup_tests.rs
@@ -0,0 +1,71 @@
+//! Focused unit tests for [`super::dedup_tool_specs_by_name`].
+//!
+//! Mirrors `session::builder::dedup_visible_tool_specs` coverage: the
+//! sub-agent assembly path must drop same-named duplicate tool specs
+//! (first occurrence wins) before they reach a strict provider that
+//! 400s on `"Tool names must be unique."`
+
+use super::*;
+use serde_json::json;
+
+fn spec(name: &str) -> ToolSpec {
+ ToolSpec {
+ name: name.to_string(),
+ description: format!("description for {name}"),
+ parameters: json!({}),
+ }
+}
+
+#[test]
+fn drops_duplicates_first_wins() {
+ // Real-world collision: a delegation tool (e.g. `tools_agent`) shadows a
+ // same-named skill/integration tool. Keep the *first* occurrence so
+ // registration-order semantics hold (dispatch still resolves by name).
+ let specs = vec![
+ spec("research"), // skill
+ spec("plan"),
+ spec("research"), // delegate, dropped
+ spec("run_code"),
+ spec("plan"), // dropped
+ ];
+
+ let deduped = dedup_tool_specs_by_name("test-agent", specs);
+
+ let names: Vec<&str> = deduped.iter().map(|s| s.name.as_str()).collect();
+ assert_eq!(names, vec!["research", "plan", "run_code"]);
+}
+
+#[test]
+fn passes_through_when_no_duplicates() {
+ let specs = vec![spec("a"), spec("b"), spec("c")];
+ let deduped = dedup_tool_specs_by_name("test-agent", specs);
+ let names: Vec<&str> = deduped.iter().map(|s| s.name.as_str()).collect();
+ assert_eq!(names, vec!["a", "b", "c"]);
+}
+
+#[test]
+fn handles_empty_input() {
+ let deduped = dedup_tool_specs_by_name("test-agent", Vec::<ToolSpec>::new());
+ assert!(deduped.is_empty());
+}
+
+#[test]
+fn preserves_full_spec_content_for_kept_entries() {
+ // Description + parameters must survive intact — the LLM uses both for
+ // tool-call decisions, and the kept entry must be the *first* one.
+ let mut first = spec("alpha");
+ first.description = "first alpha — should win".to_string();
+ first.parameters = json!({"type": "object", "required": ["x"]});
+
+ let mut dup = spec("alpha");
+ dup.description = "second alpha — should be dropped".to_string();
+
+ let deduped = dedup_tool_specs_by_name("test-agent", vec![first, dup]);
+
+ assert_eq!(deduped.len(), 1);
+ assert_eq!(deduped[0].description, "first alpha — should win");
+ assert_eq!(
+ deduped[0].parameters,
+ json!({"type": "object", "required": ["x"]})
+ );
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs
new file mode 100644
index 0000000000..4d72d291f5
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs
@@ -0,0 +1,348 @@
+use super::*;
+use crate::agent::harness::definition::{ModelSpec, ToolScope};
+use tinytools::{Tool, ToolSpec};
+
+fn make_def_named_tools(names: &[&str]) -> AgentDefinition {
+ AgentDefinition {
+ id: "test".into(),
+ when_to_use: "t".into(),
+ display_name: None,
+ system_prompt: PromptSource::Inline("system".into()),
+ omit_identity: true,
+ omit_memory_context: true,
+ omit_safety_preamble: true,
+ omit_profile: true,
+ omit_memory_md: true,
+ model: ModelSpec::Inherit,
+ temperature: 0.4,
+ tools: ToolScope::Named(names.iter().map(|s| s.to_string()).collect()),
+ disallowed_tools: vec![],
+ skill_filter: None,
+ extra_tools: vec![],
+ max_iterations: 5,
+ iteration_policy: Default::default(),
+ max_result_chars: None,
+ max_turn_output_tokens: None,
+ timeout_secs: None,
+ sandbox_mode: crate::agent::harness::definition::SandboxMode::None,
+ background: false,
+ trigger_memory_agent: Default::default(),
+ tokenjuice_compression: crate::inference::tokenjuice::AgentTokenjuiceCompression::Auto,
+ subagents: vec![],
+ delegate_name: None,
+ agent_tier: crate::agent::harness::definition::AgentTier::Worker,
+ source: crate::agent::harness::definition::DefinitionSource::Builtin,
+ graph: Default::default(),
+ }
+}
+
+/// Local tool used to populate `parent_tools` in tests.
+struct StubTool {
+ name: &'static str,
+}
+
+use async_trait::async_trait;
+use tinytools::{PermissionLevel, ToolResult};
+
+#[async_trait]
+impl Tool for StubTool {
+ fn name(&self) -> &str {
+ self.name
+ }
+ fn description(&self) -> &str {
+ "stub"
+ }
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type": "object"})
+ }
+ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ Ok(ToolResult::success("ok"))
+ }
+ fn permission_level(&self) -> PermissionLevel {
+ PermissionLevel::None
+ }
+}
+
+fn stub(name: &'static str) -> Box<dyn Tool> {
+ Box::new(StubTool { name })
+}
+
+// ── End-to-end runner tests with mock provider ────────────────────────
+
+use crate::agent::harness::fork_context::with_parent_context;
+use parking_lot::Mutex;
+use std::sync::Arc;
+use tinyagents_harness::run_queue::{QueueLane, RunQueue};
+use tinyinference_llm::message::{AssistantMessage, ContentBlock, Message, MessageDelta};
+use tinyinference_llm::model::{
+ ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
+};
+use tinyinference_llm::tool::ToolCall;
+
+/// Mock provider whose response queue can be inspected by the test
+/// to verify the bytes that arrive at the model.
+#[derive(Clone)]
+struct CapturedRequest {
+ messages: Vec<CapturedMessage>,
+ tool_count: usize,
+ model: String,
+}
+
+#[derive(Clone)]
+struct CapturedMessage {
+ role: &'static str,
+ content: String,
+}
+
+struct ScriptedProvider {
+ responses: Mutex<Vec<ModelResponse>>,
+ captured: Mutex<Vec<CapturedRequest>>,
+}
+
+impl ScriptedProvider {
+ fn new(responses: Vec<ModelResponse>) -> Arc<Self> {
+ Arc::new(Self {
+ responses: Mutex::new(responses),
+ captured: Mutex::new(Vec::new()),
+ })
+ }
+
+ fn take_response(&self, request: ModelRequest) -> ModelResponse {
+ self.captured.lock().push(CapturedRequest {
+ messages: request
+ .messages
+ .iter()
+ .map(|message| CapturedMessage {
+ role: match message {
+ Message::System(_) => "system",
+ Message::User(_) => "user",
+ Message::Assistant(_) => "assistant",
+ Message::Tool(_) => "tool",
+ },
+ content: message.text(),
+ })
+ .collect(),
+ tool_count: request.tools.len(),
+ model: request.model.unwrap_or_default(),
+ });
+ let mut responses = self.responses.lock();
+ if responses.is_empty() {
+ ModelResponse::assistant("")
+ } else {
+ responses.remove(0)
+ }
+ }
+}
+
+#[async_trait]
+impl ChatModel<()> for ScriptedProvider {
+ fn profile(&self) -> Option<&ModelProfile> {
+ static PROFILE: std::sync::LazyLock<ModelProfile> =
+ std::sync::LazyLock::new(|| ModelProfile {
+ provider: Some("subagent-runner-test".to_string()),
+ tool_calling: true,
+ parallel_tool_calls: true,
+ streaming: true,
+ ..ModelProfile::default()
+ });
+ Some(&PROFILE)
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ Ok(self.take_response(request))
+ }
+
+ async fn stream(
+ &self,
+ _state: &(),
+ request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelStream> {
+ let response = self.take_response(request);
+ let reasoning = response
+ .message
+ .content
+ .iter()
+ .filter_map(|block| match block {
+ ContentBlock::Thinking { text, .. } => Some(text.as_str()),
+ _ => None,
+ })
+ .collect::<String>();
+ let text = response.text();
+ let mut items = vec![ModelStreamItem::Started];
+ if !reasoning.is_empty() {
+ items.push(ModelStreamItem::MessageDelta(MessageDelta::reasoning(
+ reasoning,
+ )));
+ }
+ if !text.is_empty() {
+ items.push(ModelStreamItem::MessageDelta(MessageDelta::text(text)));
+ }
+ items.push(ModelStreamItem::Completed(response));
+ Ok(Box::pin(futures::stream::iter(items)))
+ }
+}
+
+fn text_response(text: &str) -> ModelResponse {
+ ModelResponse::assistant(text)
+}
+
+fn text_response_with_reasoning(text: &str, reasoning: &str) -> ModelResponse {
+ ModelResponse {
+ message: AssistantMessage {
+ id: None,
+ content: vec![
+ ContentBlock::Thinking {
+ text: reasoning.to_string(),
+ signature: None,
+ },
+ ContentBlock::Text(text.to_string()),
+ ],
+ tool_calls: Vec::new(),
+ usage: None,
+ },
+ usage: None,
+ finish_reason: None,
+ raw: None,
+ resolved_model: None,
+ continue_turn: None,
+ served_from_cache: false,
+ }
+}
+
+fn tool_response(name: &str, args: &str) -> ModelResponse {
+ ModelResponse {
+ message: AssistantMessage {
+ id: None,
+ content: Vec::new(),
+ tool_calls: vec![ToolCall::new(
+ "call-1",
+ name,
+ serde_json::from_str(args).expect("valid scripted tool arguments"),
+ )],
+ usage: None,
+ },
+ usage: None,
+ finish_reason: Some("tool_calls".to_string()),
+ raw: None,
+ resolved_model: None,
+ continue_turn: None,
+ served_from_cache: false,
+ }
+}
+
+/// Build a minimal `ParentExecutionContext` suitable for runner tests.
+/// Uses a no-op memory backend so we don't have to spin up a real one.
+fn make_parent(
+ provider: Arc<dyn ChatModel<()>>,
+ tools: Vec<Box<dyn Tool>>,
+) -> ParentExecutionContext {
+ let tool_specs: Vec<Arc<tinytools::ToolSpec>> =
+ tools.iter().map(|t| Arc::new(t.spec())).collect();
+ ParentExecutionContext {
+ workspace_descriptor: None,
+ agent_definition_id: "orchestrator".into(),
+ allowed_subagent_ids: ["test".to_string(), "child".to_string(), "inner".to_string()]
+ .into_iter()
+ .collect(),
+ turn_model_source: crate::agent::tinyagents::TurnModelSource::from_model(provider),
+ all_tools: Arc::new(tools),
+ all_tool_specs: Arc::new(tool_specs),
+ visible_tool_specs: Arc::new(Vec::new()),
+ visible_tool_names: std::collections::HashSet::new(),
+ subagent_tool_ceiling_names: std::collections::HashSet::new(),
+ model_name: "test-model".into(),
+ temperature: 0.5,
+ workspace_dir: std::env::temp_dir(),
+ memory: noop_memory(),
+ agent_config: crate::config::AgentConfig::default(),
+ workflows: Arc::new(vec![]),
+ memory_context: Arc::new(None),
+ session_id: "test-session".into(),
+ channel: "test".into(),
+ connected_integrations: vec![],
+ tool_call_format: crate::agent::prompts::ToolCallFormat::PFormat,
+ session_key: "0_test".into(),
+ session_parent_prefix: None,
+ on_progress: None,
+ run_queue: None,
+ }
+}
+
+fn noop_memory() -> Arc<dyn crate::memory::Memory> {
+ struct NoopMemory;
+ #[async_trait]
+ impl crate::memory::Memory for NoopMemory {
+ async fn store(
+ &self,
+ _namespace: &str,
+ _key: &str,
+ _content: &str,
+ _category: crate::memory::MemoryCategory,
+ _session_id: Option<&str>,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
+ async fn recall(
+ &self,
+ _query: &str,
+ _limit: usize,
+ _opts: crate::memory::RecallOpts<'_>,
+ ) -> anyhow::Result<Vec<crate::memory::MemoryEntry>> {
+ Ok(vec![])
+ }
+ async fn get(
+ &self,
+ _namespace: &str,
+ _key: &str,
+ ) -> anyhow::Result<Option<crate::memory::MemoryEntry>> {
+ Ok(None)
+ }
+ async fn list(
+ &self,
+ _namespace: Option<&str>,
+ _category: Option<&crate::memory::MemoryCategory>,
+ _session_id: Option<&str>,
+ ) -> anyhow::Result<Vec<crate::memory::MemoryEntry>> {
+ Ok(vec![])
+ }
+ async fn forget(&self, _namespace: &str, _key: &str) -> anyhow::Result<bool> {
+ Ok(true)
+ }
+ async fn namespace_summaries(
+ &self,
+ ) -> anyhow::Result<Vec<crate::memory::NamespaceSummary>> {
+ Ok(vec![])
+ }
+ async fn count(&self) -> anyhow::Result<usize> {
+ Ok(0)
+ }
+ async fn health_check(&self) -> bool {
+ true
+ }
+ fn name(&self) -> &str {
+ "noop"
+ }
+ }
+ Arc::new(NoopMemory)
+}
+
+// ── Runtime spawn-hierarchy (tier) gate (issue #4098) ───────────────────────
+// `tier_gate_decision` is the pure decision the runtime gate in `run_subagent`
+// applies to each delegation hop. Tested directly so the deny/allow/skip
+// table is covered without standing up a global registry or a live spawn.
+
+// Thin wrapper to call the gate with throwaway log-context ids.
+fn gate(parent: Option<&AgentDefinition>, child: &AgentDefinition) -> Result<(), SubagentRunError> {
+ super::runner::tier_gate_decision(parent, child, "parent-agent", "task-1")
+}
+
+#[path = "ops_tests_model_resolution_tests.rs"]
+mod model_resolution_tests;
+#[path = "ops_tests_slug_filter_typed_mode_tests.rs"]
+mod slug_filter_typed_mode_tests;
+#[path = "ops_tests_tier_gate_tests.rs"]
+mod tier_gate_tests;
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs
new file mode 100644
index 0000000000..47ae18b627
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs
@@ -0,0 +1,635 @@
+use super::*;
+use crate::agent::harness::spawn_depth_context::current_spawn_depth;
+use crate::agent::subagent_host::run_subagent;
+
+#[tokio::test]
+async fn runner_rejects_spawn_beyond_max_depth() {
+ let provider = ScriptedProvider::new(vec![text_response("should not be called")]);
+ let parent = make_parent(provider.clone(), vec![]);
+ let def = make_def_named_tools(&[]);
+
+ let result = with_parent_context(parent, async {
+ with_spawn_depth(MAX_SPAWN_DEPTH, async {
+ run_subagent(&def, "x", SubagentRunOptions::default()).await
+ })
+ .await
+ })
+ .await;
+
+ assert!(matches!(
+ result,
+ Err(SubagentRunError::SpawnDepthExceeded {
+ attempted_depth,
+ max_depth
+ }) if attempted_depth == MAX_SPAWN_DEPTH + 1 && max_depth == MAX_SPAWN_DEPTH
+ ));
+ assert!(
+ provider.captured.lock().is_empty(),
+ "depth rejection must happen before provider dispatch"
+ );
+ assert_eq!(
+ current_spawn_depth(),
+ 0,
+ "depth task-local must not leak after rejection"
+ );
+}
+
+#[tokio::test]
+async fn typed_mode_model_override_pins_exact_model_for_spawn() {
+ let provider = ScriptedProvider::new(vec![text_response("ok")]);
+ let parent = make_parent(provider.clone(), vec![]);
+ let mut def = make_def_named_tools(&[]);
+ def.model = ModelSpec::Inherit;
+
+ let _ = with_parent_context(parent, async {
+ run_subagent(
+ &def,
+ "use the pinned model",
+ SubagentRunOptions {
+ model_override: Some("deepseek/deepseek-r2".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ })
+ .await
+ .expect("runner should succeed");
+
+ let captured = provider.captured.lock();
+ assert_eq!(captured[0].model, "deepseek/deepseek-r2");
+}
+
+/// #1122 — when the parent attaches a progress sink, the inner loop
+/// emits `SubagentIterationStarted` for each round and a paired
+/// `SubagentToolCallStarted` / `SubagentToolCallCompleted` for each
+/// child tool call. The web-channel bridge translates these into the
+/// `subagent_iteration_start` / `subagent_tool_call` /
+/// `subagent_tool_result` socket events the parent thread renders.
+#[tokio::test]
+async fn typed_mode_emits_child_progress_events_when_sink_attached() {
+ use crate::agent::progress::AgentProgress;
+
+ let provider = ScriptedProvider::new(vec![
+ tool_response("file_read", "{\"path\":\"x\"}"),
+ text_response("done"),
+ ]);
+ let mut parent = make_parent(provider, vec![stub("file_read")]);
+
+ // Wire the parent's progress sink so the runner re-emits child
+ // lifecycle events through the same channel a real session would
+ // expose to the web bridge.
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<AgentProgress>(64);
+ parent.on_progress = Some(tx);
+
+ let def = make_def_named_tools(&["file_read"]);
+ let outcome = with_parent_context(parent, async {
+ run_subagent(&def, "read x", SubagentRunOptions::default()).await
+ })
+ .await
+ .expect("runner should succeed");
+ assert_eq!(outcome.iterations, 2);
+
+ // Drain everything the runner sent. The receiver's sender half is
+ // dropped when `parent` falls out of scope above, so `recv` returns
+ // None once the queue empties.
+ let mut events = Vec::new();
+ while let Some(ev) = rx.recv().await {
+ events.push(ev);
+ }
+
+ let iter_starts = events
+ .iter()
+ .filter(|e| matches!(e, AgentProgress::SubagentIterationStarted { .. }))
+ .count();
+ assert_eq!(iter_starts, 2, "one iteration_start per round");
+
+ let tool_starts: Vec<_> = events
+ .iter()
+ .filter_map(|e| match e {
+ AgentProgress::SubagentToolCallStarted {
+ call_id,
+ tool_name,
+ iteration,
+ ..
+ } => Some((call_id.clone(), tool_name.clone(), *iteration)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(tool_starts.len(), 1);
+ assert_eq!(tool_starts[0].1, "file_read");
+ assert_eq!(tool_starts[0].2, 1);
+
+ let tool_done: Vec<_> = events
+ .iter()
+ .filter_map(|e| match e {
+ AgentProgress::SubagentToolCallCompleted {
+ call_id,
+ success,
+ iteration,
+ ..
+ } => Some((call_id.clone(), *success, *iteration)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(tool_done.len(), 1);
+ assert_eq!(tool_done[0].0, tool_starts[0].0, "matching call_id pair");
+ assert!(tool_done[0].1, "stub tool returns ok");
+ assert_eq!(tool_done[0].2, 1);
+}
+
+/// A sub-agent's streamed visible text and reasoning are forwarded to the
+/// parent's progress sink as `SubagentTextDelta` / `SubagentThinkingDelta`
+/// events tagged with the child's `agent_id` / `task_id`, in order, and
+/// the concatenated text deltas reconstruct the final assistant text. The
+/// web-channel bridge turns these into `subagent_text_delta` /
+/// `subagent_thinking_delta` socket events the parent thread renders live.
+#[tokio::test]
+async fn typed_mode_forwards_child_text_and_thinking_deltas() {
+ use crate::agent::progress::AgentProgress;
+
+ let provider = ScriptedProvider::new(vec![text_response_with_reasoning(
+ "the final answer",
+ "let me reason about this",
+ )]);
+ let mut parent = make_parent(provider, vec![]);
+
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<AgentProgress>(64);
+ parent.on_progress = Some(tx);
+
+ let def = make_def_named_tools(&[]);
+ let outcome = with_parent_context(parent, async {
+ run_subagent(&def, "answer me", SubagentRunOptions::default()).await
+ })
+ .await
+ .expect("runner should succeed");
+ assert_eq!(outcome.output, "the final answer");
+
+ let mut events = Vec::new();
+ while let Some(ev) = rx.recv().await {
+ events.push(ev);
+ }
+
+ let thinking: Vec<_> = events
+ .iter()
+ .filter_map(|e| match e {
+ AgentProgress::SubagentThinkingDelta {
+ agent_id,
+ task_id,
+ delta,
+ iteration,
+ } => Some((agent_id.clone(), task_id.clone(), delta.clone(), *iteration)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(thinking.len(), 1, "one thinking delta forwarded");
+ assert_eq!(thinking[0].2, "let me reason about this");
+ assert_eq!(thinking[0].3, 1, "tagged with the child iteration");
+ assert!(!thinking[0].1.is_empty(), "carries the child task id");
+
+ let text: Vec<_> = events
+ .iter()
+ .filter_map(|e| match e {
+ AgentProgress::SubagentTextDelta {
+ agent_id,
+ task_id,
+ delta,
+ iteration,
+ } => Some((agent_id.clone(), task_id.clone(), delta.clone(), *iteration)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(text.len(), 1, "one text delta forwarded");
+ assert_eq!(text[0].2, "the final answer");
+ assert_eq!(text[0].3, 1);
+ // Same child identity on both delta kinds so the UI attributes them to
+ // one subagent row.
+ assert_eq!(text[0].0, thinking[0].0, "same agent_id");
+ assert_eq!(text[0].1, thinking[0].1, "same task_id");
+
+ // Ordering: the thinking delta precedes the text delta within the
+ // iteration, matching the provider's emission order.
+ let thinking_pos = events
+ .iter()
+ .position(|e| matches!(e, AgentProgress::SubagentThinkingDelta { .. }))
+ .unwrap();
+ let text_pos = events
+ .iter()
+ .position(|e| matches!(e, AgentProgress::SubagentTextDelta { .. }))
+ .unwrap();
+ assert!(
+ thinking_pos < text_pos,
+ "thinking streams before visible text"
+ );
+}
+
+/// Runs without an attached sink must remain backwards compatible — the
+/// runner is a no-op for child progress and the outcome is unchanged.
+#[tokio::test]
+async fn typed_mode_progress_emission_is_a_noop_without_sink() {
+ let provider = ScriptedProvider::new(vec![text_response("done")]);
+ let parent = make_parent(provider, vec![]);
+ assert!(parent.on_progress.is_none());
+ let def = make_def_named_tools(&[]);
+ let outcome = with_parent_context(parent, async {
+ run_subagent(&def, "x", SubagentRunOptions::default()).await
+ })
+ .await
+ .expect("runner should succeed");
+ assert_eq!(outcome.iterations, 1);
+}
+
+// Truncation tests live in ops_truncation_tests.rs to keep this file
+// under the ~500-line guideline.
+
+// ── resolve_subagent_source ───────────────────────────────────────────
+
+#[test]
+fn resolve_subagent_source_inherit_uses_parent_source_and_model() {
+ let parent: Arc<dyn ChatModel<()>> = ScriptedProvider::new(vec![]);
+ let parent_source = crate::agent::tinyagents::TurnModelSource::from_model(parent.clone());
+ let (_resolved_source, resolved_model) = super::super::resolve_subagent_source(
+ &ModelSpec::Inherit,
+ "test_agent",
+ None,
+ parent_source,
+ "parent-model-x".to_string(),
+ false,
+ None,
+ 0.0,
+ );
+ assert_eq!(resolved_model, "parent-model-x");
+}
+
+#[test]
+fn resolve_subagent_source_exact_overrides_only_model() {
+ // Exact keeps the parent's provider but replaces the model name.
+ // This is the explicit "I want a cheaper tier on the same backend"
+ // escape hatch.
+ let parent: Arc<dyn ChatModel<()>> = ScriptedProvider::new(vec![]);
+ let (_resolved_source, resolved_model) = super::super::resolve_subagent_source(
+ &ModelSpec::Exact("haiku-mini".to_string()),
+ "test_agent",
+ None,
+ crate::agent::tinyagents::TurnModelSource::from_model(parent.clone()),
+ "parent-model-x".to_string(),
+ false,
+ None,
+ 0.0,
+ );
+ assert_eq!(resolved_model, "haiku-mini");
+}
+
+#[test]
+fn resolve_subagent_source_spawn_override_wins_over_definition_model() {
+ let parent: Arc<dyn ChatModel<()>> = ScriptedProvider::new(vec![]);
+ let (_resolved_source, resolved_model) = super::super::resolve_subagent_source(
+ &ModelSpec::Exact("definition-model".to_string()),
+ "test_agent",
+ None,
+ crate::agent::tinyagents::TurnModelSource::from_model(parent.clone()),
+ "parent-model-x".to_string(),
+ false,
+ Some("spawn-model-y"),
+ 0.0,
+ );
+ assert_eq!(resolved_model, "spawn-model-y");
+}
+
+#[test]
+fn resolve_subagent_source_config_model_wins_over_definition_model() {
+ use crate::config::{Config, TeamModelConfig};
+
+ let mut config = Config::default();
+ config.teams.insert(
+ "test_agent".to_string(),
+ TeamModelConfig {
+ lead_model: None,
+ agent_model: Some("configured-agent-model".to_string()),
+ },
+ );
+
+ let parent: Arc<dyn ChatModel<()>> = ScriptedProvider::new(vec![]);
+ let (_resolved_source, resolved_model) = super::super::resolve_subagent_source(
+ &ModelSpec::Exact("definition-model".to_string()),
+ "test_agent",
+ Some(&config),
+ crate::agent::tinyagents::TurnModelSource::from_model(parent.clone()),
+ "parent-model-x".to_string(),
+ false,
+ None,
+ 0.0,
+ );
+ assert_eq!(resolved_model, "configured-agent-model");
+}
+
+#[test]
+fn resolve_subagent_source_inline_override_wins_over_config_model() {
+ use crate::config::{Config, TeamModelConfig};
+
+ let mut config = Config::default();
+ config.teams.insert(
+ "test_agent".to_string(),
+ TeamModelConfig {
+ lead_model: None,
+ agent_model: Some("configured-agent-model".to_string()),
+ },
+ );
+
+ let parent: Arc<dyn ChatModel<()>> = ScriptedProvider::new(vec![]);
+ let (_resolved_source, resolved_model) = super::super::resolve_subagent_source(
+ &ModelSpec::Exact("definition-model".to_string()),
+ "test_agent",
+ Some(&config),
+ crate::agent::tinyagents::TurnModelSource::from_model(parent),
+ "parent-model-x".to_string(),
+ false,
+ Some("inline-model"),
+ 0.0,
+ );
+ assert_eq!(resolved_model, "inline-model");
+}
+
+#[test]
+fn resolve_subagent_source_config_alias_matches_issue_team_examples() {
+ use crate::config::{Config, TeamModelConfig};
+
+ let mut config = Config::default();
+ config.teams.insert(
+ "research".to_string(),
+ TeamModelConfig {
+ lead_model: Some("research-lead-model".to_string()),
+ agent_model: Some("research-agent-model".to_string()),
+ },
+ );
+
+ let parent: Arc<dyn ChatModel<()>> = ScriptedProvider::new(vec![]);
+ let (_source, resolved_model) = super::super::resolve_subagent_source(
+ &ModelSpec::Hint("agentic".to_string()),
+ "researcher",
+ Some(&config),
+ crate::agent::tinyagents::TurnModelSource::from_model(parent),
+ "parent-model-x".to_string(),
+ false,
+ None,
+ 0.0,
+ );
+ assert_eq!(resolved_model, "research-agent-model");
+}
+
+#[test]
+fn resolve_subagent_source_hint_with_no_config_falls_back() {
+ // The async config load failed (transient I/O, missing file, etc.).
+ // The Hint arm must NOT silently swallow the failure and synthesise
+ // `{workload}-v1` — that's the OpenHuman-only naming that breaks
+ // Anthropic/OpenAI. Fall back to the parent's known-good
+ // (provider, model) instead.
+ let parent: Arc<dyn ChatModel<()>> = ScriptedProvider::new(vec![]);
+ let (_resolved_source, resolved_model) = super::super::resolve_subagent_source(
+ &ModelSpec::Hint("agentic".to_string()),
+ "test_agent",
+ None, // no config loaded
+ crate::agent::tinyagents::TurnModelSource::from_model(parent.clone()),
+ "real-claude-id".to_string(),
+ false,
+ None,
+ 0.0,
+ );
+ assert_eq!(
+ resolved_model, "real-claude-id",
+ "model must be parent's current model — NOT '{{workload}}-v1'"
+ );
+}
+
+#[test]
+fn resolve_subagent_source_hint_with_config_routes_via_factory() {
+ // The Hint arm with a real config takes the workload-factory path.
+ // We don't assert the *resulting* provider identity here (the
+ // factory may return a fresh OpenHuman backend or whatever
+ // primary_cloud resolves to), but we DO assert the resolved model
+ // is the workload's canonical managed tier — NOT `default_model`,
+ // and NOT the parent's model.
+ //
+ // Regression (#hint-routing): the managed backend used to ignore the
+ // workload role and return `default_model`, so `hint = "agentic"`
+ // silently ran on whatever `default_model` was (here `chat-v1`).
+ // `make_openhuman_backend` now pins specialised roles to their tier,
+ // so `agentic` resolves to `agentic-v1` regardless of `default_model`.
+ use crate::config::Config;
+ let mut config = Config::default();
+ // Route `agentic` to the OpenHuman backend explicitly, and set a
+ // distinct `default_model` so the assertion proves the role — not the
+ // global default — drives the resolved tier.
+ config.agentic_provider = Some("openhuman".to_string());
+ config.default_model = Some("chat-v1".to_string());
+
+ let parent: Arc<dyn ChatModel<()>> = ScriptedProvider::new(vec![]);
+ let (_resolved_source, resolved_model) = super::super::resolve_subagent_source(
+ &ModelSpec::Hint("agentic".to_string()),
+ "test_agent",
+ Some(&config),
+ crate::agent::tinyagents::TurnModelSource::from_model(parent),
+ "parent-model-ignored-on-hint".to_string(),
+ false,
+ None,
+ 0.0,
+ );
+ assert_eq!(
+ resolved_model, "agentic-v1",
+ "Hint must resolve to the workload's managed tier (agentic-v1), not \
+ fall back to default_model (chat-v1) or the parent's model"
+ );
+}
+
+#[test]
+fn resolve_subagent_source_hint_falls_back_on_factory_error() {
+ // An invalid provider string in the workload config (e.g. a typo
+ // like "groq:something") makes the factory return Err. The Hint
+ // arm must fall back to the parent provider rather than
+ // propagating — sub-agent execution should degrade to "use what
+ // the parent uses" not crash entirely.
+ use crate::config::Config;
+ let mut config = Config::default();
+ config.agentic_provider = Some("groq:not-a-real-prefix".to_string());
+
+ let parent: Arc<dyn ChatModel<()>> = ScriptedProvider::new(vec![]);
+ let (_resolved_source, resolved_model) = super::super::resolve_subagent_source(
+ &ModelSpec::Hint("agentic".to_string()),
+ "test_agent",
+ Some(&config),
+ crate::agent::tinyagents::TurnModelSource::from_model(parent.clone()),
+ "fallback-model".to_string(),
+ false,
+ None,
+ 0.0,
+ );
+ assert_eq!(resolved_model, "fallback-model");
+}
+
+// ── Probe regression tests (#1710 Wave 2) ──────────────────────────
+//
+// `user_is_signed_in_to_composio` replaces the legacy
+// `parent.composio_client.is_none()` gate. The legacy probe was
+// backend-only by construction: a direct-mode user with a stored API
+// key but no backend session token was falsely reported as "not signed
+// in" and the spawn-time integration refresh path was silently
+// skipped. These tests pin the new behaviour so that regression
+// can't sneak back in.
+
+#[test]
+fn direct_mode_user_with_stored_key_passes_signed_in_check() {
+ use super::super::user_is_signed_in_to_composio;
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let mut config = crate::config::Config::default();
+ config.config_path = tmp.path().join("config.toml");
+ // Direct mode + inline API key (the `config.composio.api_key`
+ // fallback path inside `create_composio_client` — equivalent to a
+ // stored direct key as far as the probe is concerned).
+ config.composio.mode = crate::config::schema::COMPOSIO_MODE_DIRECT.to_string();
+ config.composio.api_key = Some("test-direct-key".into());
+ assert!(
+ user_is_signed_in_to_composio(&config),
+ "direct-mode user with stored api key must be reported as signed in"
+ );
+}
+
+#[test]
+fn unsigned_in_user_fails_probe() {
+ use super::super::user_is_signed_in_to_composio;
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let mut config = crate::config::Config::default();
+ config.config_path = tmp.path().join("config.toml");
+ // Default mode = backend, no session token → factory errors with
+ // "no backend session". Direct fallback is unreachable because
+ // mode is not "direct".
+ assert!(
+ !user_is_signed_in_to_composio(&config),
+ "user with neither backend session nor direct key must NOT be reported as signed in"
+ );
+}
+
+/// Sanity-check: a parent agent delegating to a sub-agent must complete
+/// without panicking, even on a worker thread with a tight stack — this
+/// is the same recursion shape that crashed the
+/// `chat-harness-subagent` Playwright lane in production with
+/// `thread 'tokio-rt-worker' has overflowed its stack, fatal runtime
+/// error: stack overflow`.
+///
+/// The deep ground-truth regression catcher for this is the
+/// `chat-harness-subagent.spec.ts` Playwright spec, which exercises the
+/// real orchestrator → researcher dispatch end-to-end (real provider
+/// stream, real config load, real tool registry). The scripted unit
+/// path here has much smaller per-frame state than production, so a
+/// single stack size doesn't cleanly bracket boxed-vs-unboxed — we use
+/// the loose 1 MiB worker stack as a smoke check that the dispatch
+/// path remains poll-bounded after refactors. See `subagent_host/
+/// ops.rs` `Box::pin` callsites for the structural fix.
+#[test]
+fn nested_subagent_dispatch_runs_on_a_constrained_worker_stack() {
+ use async_trait::async_trait;
+ use std::sync::Arc;
+
+ struct RecursiveDelegateTool {
+ inner_def: AgentDefinition,
+ }
+
+ #[async_trait]
+ impl Tool for RecursiveDelegateTool {
+ fn name(&self) -> &str {
+ "delegate_inner"
+ }
+ fn description(&self) -> &str {
+ "Dispatches a nested sub-agent — reproduces the recursive engine poll."
+ }
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type":"object","properties":{}})
+ }
+ fn permission_level(&self) -> PermissionLevel {
+ PermissionLevel::Execute
+ }
+ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ let outcome = run_subagent(&self.inner_def, "inner go", SubagentRunOptions::default())
+ .await
+ .map_err(|e| anyhow::anyhow!("nested run_subagent failed: {e}"))?;
+ Ok(ToolResult::success(outcome.output))
+ }
+ }
+
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(1)
+ .thread_stack_size(1024 * 1024)
+ .enable_all()
+ .build()
+ .expect("build constrained-stack tokio runtime");
+
+ let outcome = runtime.block_on(async {
+ // Three scripted responses, shared by outer + inner runs
+ // (providers are Arc-cloned, so both pull from the same queue):
+ // [0] outer round 1: call `delegate_inner`
+ // [1] inner round 1: return final text
+ // [2] outer round 2: return final text using the tool result
+ let provider = ScriptedProvider::new(vec![
+ tool_response("delegate_inner", "{}"),
+ text_response("inner-final"),
+ text_response("outer-final: inner-final"),
+ ]);
+
+ let inner_def = make_def_named_tools(&[]);
+ let delegate_tool: Box<dyn Tool> = Box::new(RecursiveDelegateTool { inner_def });
+ let parent = make_parent(
+ Arc::clone(&(provider.clone() as Arc<dyn ChatModel<()>>)),
+ vec![delegate_tool],
+ );
+ let outer_def = make_def_named_tools(&["delegate_inner"]);
+
+ with_parent_context(parent, async {
+ run_subagent(&outer_def, "outer go", SubagentRunOptions::default()).await
+ })
+ .await
+ });
+
+ let outcome = outcome.expect(
+ "nested run_subagent must complete on a 1 MiB worker stack — \
+ a stack overflow here means the recursion boundary in \
+ `run_typed_mode` regressed (see the `Box::pin` callsites around \
+ `run_typed_mode` and the child's tinyagents drive future).",
+ );
+ assert!(
+ outcome.output.contains("inner-final"),
+ "outer should fold the inner sub-agent's result into its final \
+ answer, got: {}",
+ outcome.output
+ );
+}
+
+// ── Repro: issue #3152 — near-miss write slug fails to resolve ──────
+//
+// The model emits `NOTION_SEARCH_NOTION` (drops the `_PAGE` suffix). The
+// real action `NOTION_SEARCH_NOTION_PAGE` is the unique superstring, yet
+// find_action's three tiers (exact / case-insensitive / normalized) all
+// miss → None → lazy registration never fires → allowlist gate blocks the
+// write. Asserts DESIRED post-fix behaviour → RED until the unique
+// prefix/superstring resolution tier lands. Must stay conservative: a
+// fabricated slug with no unique match must still resolve to None (covered
+// by `lazy_resolver_tolerates_near_miss_slugs`).
+#[test]
+fn repro_3152_near_miss_write_slug_resolves_uniquely() {
+ use crate::agent::prompts::ConnectedIntegrationTool;
+ let mk = |name: &str| ConnectedIntegrationTool {
+ name: name.into(),
+ description: "d".into(),
+ parameters: None,
+ };
+ let resolver = LazyToolkitResolver {
+ config: std::sync::Arc::new(crate::config::Config::default()),
+ actions: vec![
+ mk("NOTION_SEARCH_NOTION_PAGE"),
+ mk("NOTION_CREATE_NOTION_PAGE"),
+ mk("NOTION_FETCH_DATA"),
+ ],
+ resolved: std::sync::Mutex::default(),
+ };
+ let resolved = resolver
+ .resolve("NOTION_SEARCH_NOTION")
+ .expect("#3152: near-miss write slug must resolve to its unique superstring");
+ assert_eq!(resolved.name(), "NOTION_SEARCH_NOTION_PAGE");
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests_slug_filter_typed_mode_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests_slug_filter_typed_mode_tests.rs
new file mode 100644
index 0000000000..279cf68b58
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests_slug_filter_typed_mode_tests.rs
@@ -0,0 +1,634 @@
+use super::*;
+use crate::agent::harness::spawn_depth_context::current_spawn_depth;
+use crate::agent::subagent_host::run_subagent;
+
+#[test]
+fn lazy_resolver_tolerates_near_miss_slugs() {
+ use crate::agent::prompts::ConnectedIntegrationTool;
+ let mk = |name: &str| ConnectedIntegrationTool {
+ name: name.into(),
+ description: "d".into(),
+ parameters: None,
+ };
+ let resolver = LazyToolkitResolver {
+ config: std::sync::Arc::new(crate::config::Config::default()),
+ actions: vec![mk("GOOGLESLIDES_BATCH_UPDATE"), mk("GMAIL_LIST_MESSAGES")],
+ resolved: std::sync::Mutex::default(),
+ };
+ // Exact, case-insensitive, and separator/prefix drift all resolve
+ // (bug-report-2026-05-26 A2).
+ assert!(resolver.resolve("GMAIL_LIST_MESSAGES").is_some());
+ assert!(resolver.resolve("gmail_list_messages").is_some());
+ assert!(resolver.resolve("googleslides_batch_update").is_some());
+ // A fabricated slug stays unresolved → routed to the "available tools"
+ // error so the model self-corrects, not silently mis-dispatched.
+ assert!(resolver.resolve("GMAIL_GET_LAST_3_MESSAGES").is_none());
+}
+
+#[test]
+fn normalize_slug_collapses_separators_and_case() {
+ assert_eq!(
+ normalize_slug("GOOGLESLIDES_BATCH_UPDATE"),
+ "googleslidesbatchupdate"
+ );
+ assert_eq!(
+ normalize_slug("googleslides_batch_update"),
+ "googleslidesbatchupdate"
+ );
+ assert_ne!(
+ normalize_slug("GMAIL_GET_LAST_3_MESSAGES"),
+ normalize_slug("GMAIL_LIST_MESSAGES")
+ );
+}
+
+#[test]
+fn filter_named_scope_keeps_only_named() {
+ let parent: Vec<Box<dyn Tool>> = vec![stub("alpha"), stub("beta"), stub("gamma")];
+ let def = make_def_named_tools(&["alpha", "gamma"]);
+ let idx = filter_tool_indices(&parent, &def.tools, &def.disallowed_tools, None);
+ let names: Vec<&str> = idx.iter().map(|&i| parent[i].name()).collect();
+ assert_eq!(names, vec!["alpha", "gamma"]);
+}
+
+#[test]
+fn filter_wildcard_includes_all_minus_disallowed() {
+ let parent: Vec<Box<dyn Tool>> = vec![stub("alpha"), stub("beta"), stub("gamma")];
+ let mut def = make_def_named_tools(&[]);
+ def.tools = ToolScope::Wildcard;
+ def.disallowed_tools = vec!["beta".into()];
+ let idx = filter_tool_indices(&parent, &def.tools, &def.disallowed_tools, None);
+ let names: Vec<&str> = idx.iter().map(|&i| parent[i].name()).collect();
+ assert_eq!(names, vec!["alpha", "gamma"]);
+}
+
+#[test]
+fn filter_wildcard_honours_disallowed_prefix_entries() {
+ let parent: Vec<Box<dyn Tool>> = vec![
+ stub("alpha"),
+ stub("vendor_registry_register"),
+ stub("vendor_marketplace_buy_identity"),
+ stub("gamma"),
+ ];
+ let mut def = make_def_named_tools(&[]);
+ def.tools = ToolScope::Wildcard;
+ def.disallowed_tools = vec!["vendor_*".into()];
+ let idx = filter_tool_indices(&parent, &def.tools, &def.disallowed_tools, None);
+ let names: Vec<&str> = idx.iter().map(|&i| parent[i].name()).collect();
+ assert_eq!(names, vec!["alpha", "gamma"]);
+}
+
+#[test]
+fn filter_skill_filter_restricts_to_prefix() {
+ let parent: Vec<Box<dyn Tool>> = vec![
+ stub("notion__search"),
+ stub("notion__read"),
+ stub("gmail__send"),
+ stub("file_read"),
+ ];
+ let mut def = make_def_named_tools(&[]);
+ def.tools = ToolScope::Wildcard;
+ let idx = filter_tool_indices(&parent, &def.tools, &def.disallowed_tools, Some("notion"));
+ let names: Vec<&str> = idx.iter().map(|&i| parent[i].name()).collect();
+ assert_eq!(names, vec!["notion__search", "notion__read"]);
+}
+
+#[test]
+fn filter_skill_filter_combined_with_named_scope() {
+ // Named scope intersects with skill_filter — only tools that
+ // appear in the named list AND match the prefix survive.
+ let parent: Vec<Box<dyn Tool>> = vec![
+ stub("notion__search"),
+ stub("notion__read"),
+ stub("gmail__send"),
+ ];
+ let def = make_def_named_tools(&["notion__search", "gmail__send"]);
+ let idx = filter_tool_indices(&parent, &def.tools, &def.disallowed_tools, Some("notion"));
+ let names: Vec<&str> = idx.iter().map(|&i| parent[i].name()).collect();
+ assert_eq!(names, vec!["notion__search"]);
+}
+
+#[test]
+fn subagent_mode_as_str_roundtrip() {
+ assert_eq!(SubagentMode::Typed.as_str(), "typed");
+}
+
+#[test]
+fn append_subagent_role_contract_adds_role_and_brevity_rules() {
+ let rendered = append_subagent_role_contract("base prompt".to_string(), "researcher");
+ assert!(rendered.contains("## Sub-agent Role Contract"));
+ assert!(rendered.contains("You are a sub-agent working for a parent OpenHuman agent"));
+ assert!(rendered.contains("Keep your final response concise and synthesis-ready"));
+ assert!(rendered.contains("## Sub-agent Result Contract"));
+ assert!(rendered.contains("Evidence used"));
+ assert!(rendered.contains("Do not include facts in Answer that are not supported"));
+ assert!(rendered.contains("truncated, partial, or too large"));
+}
+
+#[test]
+fn append_subagent_role_contract_is_idempotent() {
+ let once = append_subagent_role_contract("base prompt".to_string(), "researcher");
+ let twice = append_subagent_role_contract(once.clone(), "researcher");
+ assert_eq!(once, twice, "contract suffix should only appear once");
+}
+
+#[tokio::test]
+async fn typed_mode_injects_current_date_and_time_into_user_message() {
+ let provider = ScriptedProvider::new(vec![text_response("ok")]);
+ let parent = make_parent(provider.clone(), vec![stub("file_read")]);
+ let def = make_def_named_tools(&[]);
+
+ let _ = with_parent_context(parent, async {
+ run_subagent(
+ &def,
+ "the actual task prompt",
+ SubagentRunOptions::default(),
+ )
+ .await
+ })
+ .await
+ .unwrap();
+
+ let captured = provider.captured.lock();
+ let user_msg = captured[0]
+ .messages
+ .iter()
+ .find(|m| m.role == "user")
+ .expect("user message should be present");
+ assert!(
+ user_msg.content.contains("Current Date & Time:"),
+ "subagent user message must include current date/time context, got: {}",
+ user_msg.content
+ );
+}
+
+#[tokio::test]
+async fn typed_mode_system_prompt_includes_subagent_role_contract() {
+ let provider = ScriptedProvider::new(vec![text_response("ok")]);
+ let parent = make_parent(provider.clone(), vec![stub("file_read")]);
+ let def = make_def_named_tools(&[]);
+
+ let _ = with_parent_context(parent, async {
+ run_subagent(
+ &def,
+ "the actual task prompt",
+ SubagentRunOptions::default(),
+ )
+ .await
+ })
+ .await
+ .unwrap();
+
+ let captured = provider.captured.lock();
+ let system_msg = captured[0]
+ .messages
+ .iter()
+ .find(|m| m.role == "system")
+ .expect("system message should be present");
+ assert!(system_msg.content.contains("## Sub-agent Role Contract"));
+ assert!(system_msg
+ .content
+ .contains("You are a sub-agent working for a parent OpenHuman agent"));
+ assert!(system_msg
+ .content
+ .contains("Keep your final response concise and synthesis-ready"));
+}
+
+#[tokio::test]
+async fn typed_mode_returns_text_through_runner() {
+ let provider = ScriptedProvider::new(vec![text_response("X is Y")]);
+ let parent = make_parent(provider.clone(), vec![stub("file_read")]);
+ let def = make_def_named_tools(&[]);
+
+ let outcome = with_parent_context(parent, async {
+ run_subagent(
+ &def,
+ "summarise X",
+ SubagentRunOptions {
+ workspace_descriptor: None,
+ skill_filter_override: None,
+ toolkit_override: None,
+ context: None,
+ model_override: None,
+ task_id: Some("t1".into()),
+ thread_id: None,
+ run_context: Default::default(),
+ worker_thread_id: None,
+ initial_history: None,
+ checkpoint_dir: None,
+ worktree_action_dir: None,
+ run_queue: None,
+ },
+ )
+ .await
+ })
+ .await
+ .expect("runner should succeed");
+
+ assert_eq!(outcome.output, "X is Y");
+ assert_eq!(outcome.iterations, 1);
+ assert_eq!(outcome.mode, SubagentMode::Typed);
+ assert_eq!(outcome.task_id, "t1");
+}
+
+#[tokio::test]
+async fn capped_no_progress_subagent_returns_incomplete_status() {
+ use crate::agent::subagent_host::SubagentRunStatus;
+ // A sub-agent that keeps issuing tool calls without ever producing a final
+ // answer makes no progress and is halted at its model-call cap. The runner
+ // summarizes the run-so-far into a resumable checkpoint and reports
+ // `Incomplete` (NOT `Completed`) so the orchestrator relays the partial
+ // handback instead of mistaking the no-progress summary for a result (#4096).
+ //
+ // The legacy repeat-identical-call circuit-breaker `Halted` distinction
+ // folded into this cap handling during the tinyagents migration (#4249) —
+ // see `run_subagent`'s status mapping. With `max_iterations = 2` the two
+ // scripted tool calls exhaust the budget; the checkpoint summary call then
+ // draws the deterministic "reached my tool-call limit" digest.
+ let provider = ScriptedProvider::new(vec![
+ tool_response("file_read", "{\"path\":\"a\"}"),
+ tool_response("file_read", "{\"path\":\"a\"}"),
+ ]);
+ let parent = make_parent(provider.clone(), vec![stub("file_read")]);
+ let mut def = make_def_named_tools(&["file_read"]);
+ def.max_iterations = 2;
+
+ let outcome = with_parent_context(parent, async {
+ run_subagent(&def, "read the file", SubagentRunOptions::default()).await
+ })
+ .await
+ .expect("a cap halt is still Ok (not Err)");
+
+ match outcome.status {
+ SubagentRunStatus::Incomplete { reason } => assert!(
+ reason.contains("limit") || reason.contains("tool-call"),
+ "incomplete reason should describe the cap stop: {reason}"
+ ),
+ other => panic!("expected Incomplete, got {other:?}"),
+ }
+ assert!(
+ outcome.output.contains("tool-call limit"),
+ "the partial output should carry the cap-hit checkpoint summary: {}",
+ outcome.output
+ );
+}
+
+#[tokio::test]
+async fn run_queue_steer_lands_in_subagent_history() {
+ // End-to-end proof that flipping the subagent loop's run-queue arg from
+ // `None` to `Some(queue)` wires steering all the way through: a message
+ // pushed to the queue before the run is drained by the steering forwarder
+ // in the child's turn (`run_turn_via_tinyagents_shared`) and appears as a
+ // `[User steering message]:` user turn in the exact request sent to the
+ // provider. This is the mechanism behind the `steer_subagent` tool.
+ let provider = ScriptedProvider::new(vec![text_response("acknowledged")]);
+ let parent = make_parent(provider.clone(), vec![stub("file_read")]);
+ let def = make_def_named_tools(&[]);
+
+ let run_queue = Arc::new(RunQueue::new());
+ run_queue
+ .push(
+ QueueLane::Steer,
+ crate::agent::queued_turn::QueuedTurn {
+ text: "switch focus to memory safety".into(),
+ client_id: "steer_subagent".into(),
+ thread_id: "t-steer".into(),
+ queued_at_ms: 0,
+ model_override: None,
+ temperature: None,
+ locale: None,
+ },
+ )
+ .await;
+
+ let outcome = with_parent_context(parent, async {
+ run_subagent(
+ &def,
+ "investigate the bug",
+ SubagentRunOptions {
+ task_id: Some("t-steer".into()),
+ run_queue: Some(run_queue),
+ ..Default::default()
+ },
+ )
+ .await
+ })
+ .await
+ .expect("runner should succeed");
+
+ assert_eq!(outcome.output, "acknowledged");
+
+ let captured = provider.captured.lock();
+ let steered = captured[0]
+ .messages
+ .iter()
+ .any(|m| m.role == "user" && m.content.contains("switch focus to memory safety"));
+ assert!(
+ steered,
+ "steer message should be injected into the sub-agent's first request, got: {:?}",
+ captured[0]
+ .messages
+ .iter()
+ .map(|m| (&m.role, &m.content))
+ .collect::<Vec<_>>()
+ );
+}
+
+#[tokio::test]
+async fn typed_mode_no_memory_context_in_user_message() {
+ // Verifies that sub-agents skip memory loading entirely: the
+ // user message sent to the provider does NOT contain
+ // `[Memory context]`.
+ let provider = ScriptedProvider::new(vec![text_response("ok")]);
+ let parent = make_parent(provider.clone(), vec![stub("file_read")]);
+ let def = make_def_named_tools(&[]);
+
+ let _ = with_parent_context(parent, async {
+ run_subagent(
+ &def,
+ "the actual task prompt",
+ SubagentRunOptions::default(),
+ )
+ .await
+ })
+ .await
+ .unwrap();
+
+ let captured = provider.captured.lock();
+ assert_eq!(captured.len(), 1);
+ let user_msg = captured[0]
+ .messages
+ .iter()
+ .find(|m| m.role == "user")
+ .expect("user message should be present");
+ assert!(
+ !user_msg.content.contains("[Memory context]"),
+ "subagent user message must not include memory recall section, got: {}",
+ user_msg.content
+ );
+ assert!(user_msg.content.contains("the actual task prompt"));
+}
+
+#[tokio::test]
+async fn typed_mode_includes_memory_context_when_definition_allows_it() {
+ let provider = ScriptedProvider::new(vec![text_response("ok")]);
+ let mut parent = make_parent(provider.clone(), vec![stub("file_read")]);
+ parent.memory_context = Arc::new(Some(
+ "[Memory context]\n- prior fact: branch X failed\n".into(),
+ ));
+ let mut def = make_def_named_tools(&[]);
+ def.omit_memory_context = false;
+
+ let _ = with_parent_context(parent, async {
+ run_subagent(
+ &def,
+ "the actual task prompt",
+ SubagentRunOptions::default(),
+ )
+ .await
+ })
+ .await
+ .unwrap();
+
+ let captured = provider.captured.lock();
+ let user_msg = captured[0]
+ .messages
+ .iter()
+ .find(|m| m.role == "user")
+ .expect("user message should be present");
+ assert!(user_msg.content.contains("[Memory context]"));
+ assert!(user_msg.content.contains("branch X failed"));
+}
+
+#[tokio::test]
+async fn typed_mode_filters_tools_by_skill_filter() {
+ // Parent has tools spanning notion__*, gmail__*, and a generic
+ // file_read; spawn the runner with skill_filter override "notion"
+ // and assert that only the notion tools end up in the request.
+ let provider = ScriptedProvider::new(vec![text_response("done")]);
+ let parent = make_parent(
+ provider.clone(),
+ vec![
+ stub("notion__search"),
+ stub("notion__read"),
+ stub("gmail__send"),
+ stub("file_read"),
+ ],
+ );
+ // Wildcard scope so skill_filter is the only restrictor.
+ let mut def = make_def_named_tools(&[]);
+ def.tools = ToolScope::Wildcard;
+
+ let _ = with_parent_context(parent, async {
+ run_subagent(
+ &def,
+ "lookup",
+ SubagentRunOptions {
+ workspace_descriptor: None,
+ skill_filter_override: Some("notion".into()),
+ toolkit_override: None,
+ context: None,
+ model_override: None,
+ task_id: None,
+ thread_id: None,
+ run_context: Default::default(),
+ worker_thread_id: None,
+ initial_history: None,
+ checkpoint_dir: None,
+ worktree_action_dir: None,
+ run_queue: None,
+ },
+ )
+ .await
+ })
+ .await
+ .unwrap();
+
+ // The narrow system prompt should mention the notion tools by
+ // name and NOT mention gmail/file_read.
+ let captured = provider.captured.lock();
+ let system_msg = captured[0]
+ .messages
+ .iter()
+ .find(|m| m.role == "system")
+ .expect("system message present");
+ assert!(system_msg.content.contains("notion__search"));
+ assert!(system_msg.content.contains("notion__read"));
+ assert!(
+ !system_msg.content.contains("gmail__send"),
+ "skill_filter should have excluded gmail__send"
+ );
+ assert!(
+ !system_msg.content.contains("file_read"),
+ "skill_filter should have excluded file_read"
+ );
+}
+
+#[tokio::test]
+async fn typed_mode_executes_one_tool_then_returns() {
+ // Two-round script: round 1 returns a tool call, round 2 returns
+ // the final text. Verifies the inner tool-call loop wires up the
+ // tool result into history correctly.
+ let provider = ScriptedProvider::new(vec![
+ tool_response("file_read", "{\"path\":\"x\"}"),
+ text_response("the file contents say hello"),
+ ]);
+ let parent = make_parent(provider.clone(), vec![stub("file_read")]);
+ // Allow the runner to call file_read.
+ let def = make_def_named_tools(&["file_read"]);
+
+ let outcome = with_parent_context(parent, async {
+ run_subagent(&def, "read x", SubagentRunOptions::default()).await
+ })
+ .await
+ .expect("runner should succeed");
+
+ assert!(outcome.output.contains("hello"));
+ assert_eq!(outcome.iterations, 2);
+ // Second request should include the role=tool message produced
+ // by the runner from StubTool's "ok" output.
+ let captured = provider.captured.lock();
+ assert_eq!(captured.len(), 2);
+ let second_call_messages = &captured[1].messages;
+ let has_tool_msg = second_call_messages.iter().any(|m| m.role == "tool");
+ assert!(
+ has_tool_msg,
+ "second provider call should include role=tool message"
+ );
+}
+
+#[tokio::test]
+async fn typed_mode_blocks_unallowed_tool_calls() {
+ // Provider tries to call a tool that's not in the allowlist.
+ // Runner should surface an error tool result and the next
+ // iteration should be able to recover.
+ let provider = ScriptedProvider::new(vec![
+ tool_response("forbidden_tool", "{}"),
+ text_response("oops, I'll try something else"),
+ ]);
+ let parent = make_parent(
+ provider.clone(),
+ vec![stub("file_read"), stub("forbidden_tool")],
+ );
+ // Definition only allows file_read.
+ let def = make_def_named_tools(&["file_read"]);
+
+ let outcome = with_parent_context(parent, async {
+ run_subagent(&def, "do thing", SubagentRunOptions::default()).await
+ })
+ .await
+ .expect("runner should succeed");
+
+ assert!(outcome.output.contains("oops"));
+ let captured = provider.captured.lock();
+ let second_call_messages = &captured[1].messages;
+ let tool_msg = second_call_messages
+ .iter()
+ .find(|m| m.role == "tool")
+ .expect("tool result message should be present");
+ // A tool outside the allowlist is never registered on the sub-agent
+ // harness, so a call to it flows through the tinyagents
+ // `UnknownToolPolicy::ReturnToolError` path (issue #4249): the runner
+ // injects a recoverable `unknown tool `forbidden_tool` …` result (naming the
+ // blocked tool and listing the valid ones) instead of executing it, and the
+ // next iteration recovers. The security guarantee — the disallowed tool does
+ // NOT run — is preserved; only the message wording changed from the legacy
+ // "not available".
+ assert!(
+ tool_msg.content.contains("unknown tool") && tool_msg.content.contains("forbidden_tool"),
+ "blocked tool should produce a recoverable unknown-tool error naming it: {:?}",
+ tool_msg.content
+ );
+}
+
+#[tokio::test]
+async fn runner_errors_outside_parent_context() {
+ let def = make_def_named_tools(&[]);
+ let result = run_subagent(&def, "x", SubagentRunOptions::default()).await;
+ assert!(matches!(result, Err(SubagentRunError::NoParentContext)));
+}
+
+#[tokio::test]
+async fn subagent_emits_checkpoint_at_iteration_cap_instead_of_erroring() {
+ // A sub-agent that keeps calling tools and never finishes must hit its
+ // cap and return a graceful partial-progress checkpoint (Ok), not a bare
+ // MaxIterationsExceeded that discards its work — so the delegating agent
+ // can continue from what it got (bug-report-2026-05-26 A1, mirrors the
+ // main agent). Two tool rounds (max_iterations=2), then the summarize
+ // call returns prose which becomes the checkpoint.
+ let provider = ScriptedProvider::new(vec![
+ tool_response("file_read", "{}"),
+ tool_response("file_read", "{}"),
+ text_response("Progress so far: read the file. Remaining: keep going."),
+ ]);
+ let parent = make_parent(provider.clone(), vec![stub("file_read")]);
+ let mut def = make_def_named_tools(&["file_read"]);
+ def.max_iterations = 2;
+
+ let outcome = with_parent_context(parent, async {
+ run_subagent(&def, "keep reading forever", SubagentRunOptions::default()).await
+ })
+ .await
+ .expect("hitting the iteration cap should return a checkpoint, not error");
+
+ assert!(
+ outcome.output.contains("Progress so far"),
+ "expected the model-written checkpoint, got: {}",
+ outcome.output
+ );
+}
+
+#[tokio::test]
+async fn subagent_checkpoint_falls_back_to_deterministic_when_summary_empty() {
+ // Same cap, but the summarize call yields nothing (response queue
+ // exhausted → empty). The runner must fall back to a deterministic
+ // partial-progress digest so the parent still gets a usable result
+ // (bug-report-2026-05-26 A1).
+ let provider = ScriptedProvider::new(vec![
+ tool_response("file_read", "{}"),
+ tool_response("file_read", "{}"),
+ ]);
+ let parent = make_parent(provider.clone(), vec![stub("file_read")]);
+ let mut def = make_def_named_tools(&["file_read"]);
+ def.max_iterations = 2;
+
+ let outcome = with_parent_context(parent, async {
+ run_subagent(&def, "keep reading forever", SubagentRunOptions::default()).await
+ })
+ .await
+ .expect("empty summary should fall back, not error");
+
+ assert!(
+ outcome.output.contains("tool-call limit"),
+ "expected the deterministic fallback checkpoint, got: {}",
+ outcome.output
+ );
+ assert!(
+ outcome.output.contains("file_read"),
+ "deterministic checkpoint should list the tool work done, got: {}",
+ outcome.output
+ );
+}
+
+#[tokio::test]
+async fn runner_allows_spawn_at_max_depth() {
+ let provider = ScriptedProvider::new(vec![text_response("ok")]);
+ let parent = make_parent(provider.clone(), vec![]);
+ let def = make_def_named_tools(&[]);
+
+ let outcome = with_parent_context(parent, async {
+ with_spawn_depth(MAX_SPAWN_DEPTH - 1, async {
+ run_subagent(&def, "x", SubagentRunOptions::default()).await
+ })
+ .await
+ })
+ .await
+ .expect("runner should allow the configured maximum depth");
+
+ assert_eq!(outcome.output, "ok");
+ assert_eq!(provider.captured.lock().len(), 1);
+ assert_eq!(
+ current_spawn_depth(),
+ 0,
+ "depth task-local must not leak after the run"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests_tier_gate_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests_tier_gate_tests.rs
new file mode 100644
index 0000000000..0cf2602b67
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests_tier_gate_tests.rs
@@ -0,0 +1,194 @@
+use super::*;
+use crate::agent::subagent_host::run_subagent;
+
+// ── Guard: #3152 prefix tier must stay strictly unique ──────────────
+//
+// When a truncated slug prefix-matches MORE than one catalogued action,
+// the resolver must refuse rather than guess — a mis-dispatched write
+// could create/update the wrong resource (data-integrity). Also asserts
+// the length gate: a too-short request never fans out.
+#[test]
+fn prefix_tier_refuses_ambiguous_and_short_slugs() {
+ use crate::agent::prompts::ConnectedIntegrationTool;
+ let mk = |name: &str| ConnectedIntegrationTool {
+ name: name.into(),
+ description: "d".into(),
+ parameters: None,
+ };
+ let resolver = LazyToolkitResolver {
+ config: std::sync::Arc::new(crate::config::Config::default()),
+ actions: vec![
+ mk("NOTION_SEARCH_NOTION_PAGE"),
+ mk("NOTION_SEARCH_NOTION_DATABASE"),
+ mk("NOTION_CREATE_NOTION_PAGE"),
+ ],
+ resolved: std::sync::Mutex::default(),
+ };
+ // `NOTION_SEARCH_NOTION` is a prefix of TWO actions → ambiguous → None.
+ assert!(
+ resolver.resolve("NOTION_SEARCH_NOTION").is_none(),
+ "#3152: ambiguous prefix must not silently dispatch to a guess"
+ );
+ // Short slug below the length gate never engages the prefix tier.
+ assert!(resolver.resolve("NOTION").is_none());
+}
+
+#[test]
+fn tier_gate_skips_when_parent_unresolved() {
+ use crate::agent::harness::definition::AgentTier;
+ // No resolvable parent definition (e.g. registry uninitialised, or a
+ // dynamically-named model-council juror / custom agent absent from it) →
+ // skip rather than mask. Even a would-be-illegal child tier passes, because
+ // we have no parent tier to judge against.
+ let mut child = make_def_named_tools(&[]);
+ child.agent_tier = AgentTier::Chat;
+ assert!(gate(None, &child).is_ok());
+}
+
+#[test]
+fn tier_gate_allows_legal_descending_hops() {
+ use crate::agent::harness::definition::AgentTier;
+ let mut parent = make_def_named_tools(&[]);
+ let mut child = make_def_named_tools(&[]);
+
+ // chat → worker
+ parent.agent_tier = AgentTier::Chat;
+ child.agent_tier = AgentTier::Worker;
+ assert!(gate(Some(&parent), &child).is_ok());
+
+ // chat → reasoning
+ child.agent_tier = AgentTier::Reasoning;
+ assert!(gate(Some(&parent), &child).is_ok());
+
+ // reasoning → worker
+ parent.agent_tier = AgentTier::Reasoning;
+ child.agent_tier = AgentTier::Worker;
+ assert!(gate(Some(&parent), &child).is_ok());
+}
+
+#[test]
+fn tier_gate_allows_worker_parent_for_collapsed_integration() {
+ use crate::agent::harness::definition::AgentTier;
+ // A worker only reaches the runtime spawn chokepoint via the documented
+ // collapsed `delegate_to_integrations_agent` path (→ `integrations_agent`,
+ // itself a worker). The gate must NOT re-deny that — the worker-leaf rule
+ // is a static boot-time authoring constraint, not a runtime one. Regression
+ // for the wildcard-integration case (CodeRabbit P2 on PR #4102).
+ let mut parent = make_def_named_tools(&[]);
+ let child = make_def_named_tools(&[]); // worker by default
+ parent.agent_tier = AgentTier::Worker;
+ assert!(gate(Some(&parent), &child).is_ok());
+}
+
+#[test]
+fn tier_gate_denies_chat_to_chat() {
+ use crate::agent::harness::definition::AgentTier;
+ let mut parent = make_def_named_tools(&[]);
+ let mut child = make_def_named_tools(&[]);
+ parent.agent_tier = AgentTier::Chat;
+ child.agent_tier = AgentTier::Chat;
+
+ let err =
+ gate(Some(&parent), &child).expect_err("chat→chat must be denied at the runtime gate");
+ match err {
+ SubagentRunError::TierViolation {
+ parent_tier,
+ child_tier,
+ reason,
+ } => {
+ assert_eq!(parent_tier, AgentTier::Chat);
+ assert_eq!(child_tier, AgentTier::Chat);
+ assert!(
+ reason.contains("chat") && reason.contains("leaf"),
+ "got: {reason}"
+ );
+ }
+ other => panic!("expected TierViolation, got: {other:?}"),
+ }
+}
+
+#[test]
+fn tier_gate_allows_upward_reasoning_to_chat() {
+ use crate::agent::harness::definition::AgentTier;
+ // Upward delegation is intentionally legal (subconscious reasoner →
+ // orchestrator chat). The gate must not deny it.
+ let mut parent = make_def_named_tools(&[]);
+ let mut child = make_def_named_tools(&[]);
+ parent.agent_tier = AgentTier::Reasoning;
+ child.agent_tier = AgentTier::Chat;
+ assert!(gate(Some(&parent), &child).is_ok());
+}
+
+// ---------------------------------------------------------------------------
+// Turn-scoped dispatch gate (#5804)
+//
+// These exercise the gate at its real call site rather than only the policy it
+// consults. The lever is that no `ParentExecutionContext` is installed here, so
+// an ungated `run_subagent` returns `NoParentContext`: each refusal below is
+// therefore evidence the gate ran *and* that it ran before anything was spent,
+// and removing the gate turns every one of them into `NoParentContext`.
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn dispatch_is_refused_after_the_turn_requests_a_graceful_pause() {
+ let definition = make_def_named_tools(&[]);
+ let dispatch = std::sync::Arc::new(crate::agent::tinyagents::host::TurnDispatchState::new(
+ Some(std::time::Duration::from_secs(600)),
+ ));
+ dispatch.record_pause_requested(15, 15);
+ let mut options = SubagentRunOptions::default();
+ options.run_context.dispatch = Some(dispatch);
+ let outcome = run_subagent(&definition, "task", options).await;
+
+ assert!(
+ matches!(
+ outcome,
+ Err(SubagentRunError::PauseRequested {
+ completed_model_calls: 15,
+ cap: 15
+ })
+ ),
+ "a dispatch after the cap-pause request must be refused, not run: {outcome:?}"
+ );
+}
+
+#[tokio::test]
+async fn dispatch_is_refused_when_the_remaining_budget_cannot_fit_an_observed_subagent() {
+ let definition = make_def_named_tools(&[]);
+ let dispatch = std::sync::Arc::new(crate::agent::tinyagents::host::TurnDispatchState::new(
+ Some(std::time::Duration::ZERO),
+ ));
+ dispatch.record_subagent_elapsed(std::time::Duration::from_secs(60));
+ let mut options = SubagentRunOptions::default();
+ options.run_context.dispatch = Some(dispatch);
+ let outcome = run_subagent(&definition, "task", options).await;
+
+ assert!(
+ matches!(
+ outcome,
+ Err(SubagentRunError::DispatchBudgetExhausted { .. })
+ ),
+ "a dispatch that cannot fit the remaining budget must be refused: {outcome:?}"
+ );
+}
+
+#[tokio::test]
+async fn dispatch_is_not_refused_while_the_guard_has_no_evidence() {
+ // The other half of the contract, and the one that keeps this from being a
+ // throughput regression: with no pause requested and no completed
+ // sub-agent to learn from, the gate must let the dispatch through. Reaching
+ // `NoParentContext` is exactly that — the gate declined to interfere and
+ // the normal path ran.
+ let definition = make_def_named_tools(&[]);
+ let mut options = SubagentRunOptions::default();
+ options.run_context.dispatch = Some(std::sync::Arc::new(
+ crate::agent::tinyagents::host::TurnDispatchState::new(Some(std::time::Duration::ZERO)),
+ ));
+ let outcome = run_subagent(&definition, "task", options).await;
+
+ assert!(
+ matches!(outcome, Err(SubagentRunError::NoParentContext)),
+ "an exhausted budget with no observed sub-agent is not evidence — the \
+ dispatch must proceed: {outcome:?}"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_truncation_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_truncation_tests.rs
new file mode 100644
index 0000000000..e8141c07c7
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops_truncation_tests.rs
@@ -0,0 +1,67 @@
+/// Tests for the `max_result_chars` truncation logic in `ops.rs`.
+///
+/// Kept in a dedicated file so `ops_tests.rs` stays under ~500 lines.
+/// The logic under test lives in `run_subagent` — tests here cover the
+/// char-safe truncation path directly without spinning up a provider.
+
+#[test]
+fn max_result_chars_cap_is_enforced() {
+ // Verify that max_result_chars truncation uses char count (not bytes)
+ // and produces a truncated result ending with "[...truncated]".
+ let cap = 10usize;
+ let input = "hello world this is long".to_string();
+ let original_chars = input.chars().count();
+ let mut output = input.clone();
+ if original_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]");
+ }
+ assert_eq!(&output[..10], "hello worl");
+ assert!(output.ends_with("[...truncated]"));
+}
+
+#[test]
+fn max_result_chars_cap_is_char_safe_for_multibyte() {
+ // A cap landing in the middle of a multi-byte UTF-8 sequence must
+ // not panic. "café" has 4 chars but 'é' is 2 bytes — truncating at
+ // byte offset 4 with a raw String::truncate() would panic.
+ let cap = 3usize; // keep "caf", drop "é"
+ let input = "café latte".to_string();
+ let original_chars = input.chars().count();
+ let mut output = input.clone();
+ if original_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]");
+ }
+ assert_eq!(output, "caf\n[...truncated]");
+}
+
+#[test]
+fn max_result_chars_not_applied_when_none() {
+ let cap: Option<usize> = None;
+ let original = "short output".to_string();
+ let mut output = original.clone();
+ if let Some(c) = cap {
+ let char_len = output.chars().count();
+ if char_len > c {
+ let byte_offset = output
+ .char_indices()
+ .nth(c)
+ .map(|(i, _)| i)
+ .unwrap_or(output.len());
+ output.truncate(byte_offset);
+ output.push_str("\n[...truncated]");
+ }
+ }
+ assert_eq!(output, original);
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs b/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs
new file mode 100644
index 0000000000..a00671b0ee
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs
@@ -0,0 +1,489 @@
+//! Helpers that prepare the sub-agent's tool surface and system prompt
+//! body before [`super::run_typed_mode`] spins up its tool-loop.
+//!
+//! Kept together because they share a theme (what does the sub-agent
+//! actually see?). Only the text-mode protocol renderer is exposed outside
+//! this module so the debug-dump path in [`crate::agent::debug`] can
+//! mirror the live runner byte-for-byte instead of carrying its own drifting
+//! copy.
+
+use super::types::SubagentRunError;
+use crate::agent::harness::definition::{PromptSource, ToolScope};
+use crate::agent::prompts::PromptContext;
+use tinytools::Tool;
+
+// ── Heavy-schema toolkit accounting ─────────────────────────────────────
+
+/// Tight top-K ceiling for toolkits whose per-action JSON schemas are
+/// dense enough to blow through either Fireworks' 65 535-rule grammar
+/// cap (native mode) or the 196 607-token context cap (text mode) even
+/// before any tool results land in history. Determined empirically from
+/// the fixture dumps under `tests/fixtures/composio_*.json` and real
+/// staging failures — see the trace where Gmail at top-K=25 produced
+/// a 276k-token iter-1 prompt.
+const HEAVY_SCHEMA_TOOLKITS: &[&str] = &[
+ "gmail",
+ "notion",
+ "github",
+ "salesforce",
+ "hubspot",
+ "googledrive",
+ "googlesheets",
+ "googledocs",
+ "microsoftteams",
+];
+
+const TOOL_FILTER_TOP_K_DEFAULT: usize = 25;
+const TOOL_FILTER_TOP_K_HEAVY: usize = 12;
+
+/// Actions a toolkit must keep on the sub-agent's surface even when the
+/// fuzzy ranker does not pick them.
+///
+/// The ranker (`tinyagents_harness::tool::select`) derives an intent verb
+/// from the prompt and then **drops** every tool whose own name-verb
+/// conflicts with it. `FETCH`/`GET` are the `Read` verb and `find`/`search`
+/// are `List`, so a plain "find the emails about X" prompt removes
+/// `GMAIL_FETCH_EMAILS` and both `GMAIL_FETCH_MESSAGE_BY_*` before scoring
+/// even starts. A flat verb-alignment bonus then lets zero-overlap tools
+/// fill the budget, so the surviving surface can be twelve `GMAIL_LIST_*`
+/// actions — ids and settings, nothing that returns a message body. The
+/// sub-agent burns its iterations and answers without the email (#6033).
+///
+/// These names are **reserved inside** the top-K budget, never appended
+/// past it: [`TOOL_FILTER_TOP_K_HEAVY`] exists because Gmail at top-K=25
+/// produced a 276k-token first-iteration prompt, so an essential displaces
+/// the lowest-ranked hit rather than growing the surface.
+///
+/// **Every entry must be read-only.** These actions are forced onto a
+/// delegation whatever it asked for, so a write action here would hand a
+/// "read my email" task an unrequested side-effecting capability — and a
+/// `ComposioActionTool` does not override `external_effect`, so the
+/// approval middleware (which gates on `external_effect_with_args`) would
+/// not stop it. Prompt-injected instructions inside a fetched email could
+/// then act on the mailbox with no human in the loop. Send and the rest of
+/// the write surface stay where they were: reachable when the prompt
+/// actually asks for them, via the ranker.
+///
+/// Only Gmail is seeded, deliberately. A wrong entry spends a slot on
+/// every prompt for that toolkit, so add one only with a fixture-backed
+/// repro — the ranker's general behaviour is the upstream fix.
+const TOOLKIT_ESSENTIAL_ACTIONS: &[(&str, &[&str])] = &[(
+ "gmail",
+ &[
+ // The only action that returns message *content* for a search.
+ "GMAIL_FETCH_EMAILS",
+ // The follow-up once `GMAIL_LIST_MESSAGES` has handed back bare ids.
+ "GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID",
+ ],
+)];
+
+/// Pick a top-K budget for the fuzzy filter based on how dense the
+/// toolkit's action schemas tend to be. Match is case-insensitive so
+/// we don't care whether the caller passed `"Gmail"` or `"gmail"`.
+pub(super) fn top_k_for_toolkit(toolkit: &str) -> usize {
+ if HEAVY_SCHEMA_TOOLKITS
+ .iter()
+ .any(|t| t.eq_ignore_ascii_case(toolkit))
+ {
+ TOOL_FILTER_TOP_K_HEAVY
+ } else {
+ TOOL_FILTER_TOP_K_DEFAULT
+ }
+}
+
+/// Actions [`TOOLKIT_ESSENTIAL_ACTIONS`] reserves for `toolkit`, or an
+/// empty slice when the toolkit has no entry. Case-insensitive, matching
+/// [`top_k_for_toolkit`].
+pub(super) fn essential_actions_for_toolkit(toolkit: &str) -> &'static [&'static str] {
+ TOOLKIT_ESSENTIAL_ACTIONS
+ .iter()
+ .find(|(name, _)| name.eq_ignore_ascii_case(toolkit))
+ .map(|(_, actions)| *actions)
+ .unwrap_or(&[])
+}
+
+/// Pick the action indices the sub-agent will actually see: the toolkit's
+/// essentials first, then the ranker's hits in rank order, deduplicated and
+/// truncated to `top_k`.
+///
+/// An essential that the connected toolkit does not actually expose is
+/// skipped rather than guessed at, so a stale table entry costs nothing and
+/// can never produce an out-of-range index. A toolkit with no entry returns
+/// the ranker's hits unchanged (capped at `top_k`), which is what every
+/// call site did before the essentials existed.
+pub(super) fn select_actions_with_essentials(
+ toolkit: &str,
+ actions: &[crate::agent::prompts::ConnectedIntegrationTool],
+ filter_hits: &[usize],
+ top_k: usize,
+) -> Vec<usize> {
+ let essentials = essential_actions_for_toolkit(toolkit);
+ if essentials.is_empty() || top_k == 0 {
+ return filter_hits.iter().take(top_k).copied().collect();
+ }
+
+ let mut selected: Vec<usize> = Vec::with_capacity(top_k.min(actions.len()));
+ let mut reserved: Vec<&str> = Vec::new();
+ for essential in essentials {
+ if selected.len() >= top_k {
+ break;
+ }
+ let found = actions
+ .iter()
+ .position(|a| a.name.eq_ignore_ascii_case(essential));
+ if let Some(idx) = found {
+ if !selected.contains(&idx) {
+ selected.push(idx);
+ reserved.push(essential);
+ }
+ }
+ }
+
+ let ranked_before = filter_hits.len().min(top_k);
+ for &idx in filter_hits {
+ if selected.len() >= top_k {
+ break;
+ }
+ if !selected.contains(&idx) {
+ selected.push(idx);
+ }
+ }
+
+ // A reserved action the ranker had already chosen costs nothing; the
+ // rest displace the lowest-ranked hits that no longer fit.
+ let ranked_kept = filter_hits.iter().filter(|i| selected.contains(i)).count();
+ tracing::debug!(
+ toolkit = %toolkit,
+ reserved = %reserved.join(","),
+ kept = selected.len(),
+ top_k = top_k,
+ dropped_ranked = ranked_before.saturating_sub(ranked_kept),
+ "[subagent_host:tools] reserved essential actions inside the top-K budget"
+ );
+ selected
+}
+
+// ── Text-mode protocol block ────────────────────────────────────────────
+
+/// Format the tool-use protocol block appended to the system prompt in text
+/// mode. Teaches **P-Format** first (the same protocol
+/// [`tinytools_agent::dialect::PFormatDialect`] renders and
+/// the tinyagents adapter parses via `parse_tool_calls_with_pformat`), with
+/// the legacy JSON-in-tag form as the documented fallback for nested
+/// arguments. The `## Tools` catalogue already renders `Call as:` p-format
+/// signatures for every tool, so teaching JSON here contradicted the
+/// catalogue and threw away the p-format token savings.
+///
+/// Per-parameter rendering is intentionally **compact**: name, type, a
+/// "required" marker, and a short one-line description if present. We
+/// do **not** serialise the full JSON schema. Composio/Fireworks action
+/// schemas for toolkits like Gmail or Notion run multiple KB each —
+/// embedding them verbatim blows up the prompt past the model's
+/// context window (282k+ tokens for 26 Gmail tools vs a 196k cap).
+/// The compact listing keeps the model informed enough to call tools
+/// correctly while staying within budget. If the model needs deeper
+/// schema detail it can surface the error and the orchestrator will
+/// clarify on the next turn.
+pub(crate) fn build_text_mode_tool_instructions() -> String {
+ // The tool catalog is already rendered in the prompt's `## Tools`
+ // section (see `prompts::ToolsSection::build`) with full
+ // `Call as: NAME[arg|arg]` signatures. We previously also emitted
+ // an `### Available Tools` subsection here with a different
+ // formatting (`Parameters: name:type, ...`), which doubled the
+ // tool list bytes for text-mode agents — especially expensive for
+ // the integrations_agent toolkit-scoped spawns (~50 actions ×
+ // 2 listings). Keep only the protocol explanation; the tool
+ // catalog itself comes from the prompt template.
+ let mut out = String::new();
+ out.push_str("## Tool Use Protocol\n\n");
+ out.push_str(
+ "Tool calls use **P-Format** (Parameter-Format): compact, positional, \
+ pipe-delimited syntax wrapped in `<tool_call>` tags.\n\n",
+ );
+ out.push_str("```\n<tool_call>\nGMAIL_FETCH_EMAILS[ca_123||10]\n</tool_call>\n```\n\n");
+ out.push_str(
+ "**Rules:**\n\
+ - Form: `name[arg1|arg2|...|argN]`. Arguments are positional and must match the \
+ order shown in each tool's `Call as:` signature in the `## Tools` section \
+ (alphabetical by parameter name). Leave a slot empty to omit that argument.\n\
+ - Empty calls: `name[]` for zero-arg tools.\n\
+ - Escapes inside argument values: `\\|` for a literal `|`, `\\]` for `]`, `\\\\` for `\\`.\n\
+ - Do not nest tags. Emit one tag per call; you can emit multiple tags in the same \
+ response to run calls in parallel.\n\
+ - When an argument needs a nested object or array that p-format cannot express, \
+ fall back to the JSON form in the same tags: \
+ `<tool_call>{\"name\": \"tool_name\", \"arguments\": {\"param\": \"value\"}}</tool_call>`. \
+ Prefer p-format for everything else.\n",
+ );
+ out
+}
+
+/// The tool-call format a sub-agent's prompt is rendered for, and the
+/// dispatcher protocol block that goes with it.
+///
+/// Normally both follow the parent. A text-mode child (the toolkit-scoped
+/// `integrations_agent`) is sent no native `tools`, so it must render its own
+/// catalogue as text whatever the parent uses: under a native-tool parent,
+/// `ToolsSection` would otherwise emit no catalogue and the native JSON protocol,
+/// and the child would be told how to call tools but never which ones exist.
+/// Its protocol block is empty because the runner appends
+/// [`build_text_mode_tool_instructions`] itself.
+pub(crate) fn subagent_prompt_protocol(
+ parent_format: crate::agent::prompts::ToolCallFormat,
+ text_mode: bool,
+) -> (crate::agent::prompts::ToolCallFormat, String) {
+ use crate::agent::prompts::ToolCallFormat;
+ use tinytools_agent::dialect::{NativeDialect, PFormatDialect, ToolDialect, XmlDialect};
+ use tinytools_agent::PFormatRegistry;
+ if text_mode {
+ return (ToolCallFormat::PFormat, String::new());
+ }
+ let empty_tools = Vec::new();
+ let instructions = match parent_format {
+ ToolCallFormat::PFormat => {
+ PFormatDialect::new(PFormatRegistry::new()).prompt_instructions(&empty_tools)
+ }
+ ToolCallFormat::Native => NativeDialect.prompt_instructions(&empty_tools),
+ ToolCallFormat::Json => XmlDialect.prompt_instructions(&empty_tools),
+ };
+ (parent_format, instructions)
+}
+
+// ── Tool filtering ──────────────────────────────────────────────────────
+
+/// Tools that spawn a new sub-agent turn. A sub-agent must never be
+/// able to invoke any of these — only the top-level orchestrator
+/// delegates. Nested spawns would create a recursion tree the harness
+/// is not designed to budget, cost, or observe.
+///
+/// Matches:
+/// * the generic `spawn_subagent` meta-tool (arbitrary archetype by id);
+/// * every synthesised per-archetype `delegate_*` tool
+/// ([`crate::tools::orchestrator_tools::collect_orchestrator_tools`]
+/// emits `delegate_researcher`, `delegate_planner`, …).
+/// * `agent_prepare_context` — the context-scout entry point. It reads the
+/// *parent's* visible catalog/session via `current_parent()`, which inside a
+/// nested run is still the top-level orchestrator (the runner does not
+/// install a child-scoped parent context). A wildcard or named sub-agent
+/// calling it would therefore scout against the orchestrator's surface, not
+/// its own. Context preparation is a top-level concern only.
+///
+/// Kept as a tight prefix/exact match rather than a registry lookup so
+/// the strip is cheap to run inside [`super::ops::run_typed_mode`]'s
+/// filter pass. If the delegation-tool naming scheme changes, update
+/// this function and the corresponding generator in
+/// `orchestrator_tools.rs` together.
+pub(super) fn is_subagent_spawn_tool(name: &str) -> bool {
+ if name == "spawn_subagent" || name.starts_with("delegate_") || name == "agent_prepare_context"
+ {
+ return true;
+ }
+ // Synthesised delegation tools are named by the target agent's
+ // `delegate_name` override, which mostly does NOT carry the `delegate_`
+ // prefix (`plan`, `run_code`, `research`, `review_code`, `do_crypto`,
+ // `schedule_task`, …). The prefix check above misses every one of them,
+ // which let wildcard-scoped children inherit the orchestrator's spawn
+ // surface. Resolve the override names via the registry so the strip
+ // stays in lockstep with `collect_orchestrator_tools`'s naming.
+ if let Some(registry) = crate::agent::harness::definition::AgentDefinitionRegistry::global() {
+ return registry
+ .list()
+ .iter()
+ .any(|def| def.delegate_name.as_deref() == Some(name));
+ }
+ false
+}
+
+/// Returns indices into `parent_tools` for the tools the sub-agent may
+/// invoke. Index-based filtering avoids cloning `Box<dyn Tool>` (which
+/// isn't Clone) and lets us reuse the parent's existing instances.
+///
+/// Filters are applied in this order (shorter-circuit first):
+/// 1. `disallowed` — explicit deny list.
+/// 2. `skill_filter` — restrict to tools named `{skill}__*`.
+/// 3. `scope` — `Wildcard` (everything remaining) or `Named` allowlist.
+///
+pub(super) fn filter_tool_indices(
+ parent_tools: &[Box<dyn Tool>],
+ scope: &ToolScope,
+ disallowed: &[String],
+ skill_filter: Option<&str>,
+) -> Vec<usize> {
+ let skill_prefix = skill_filter.map(|s| format!("{s}__"));
+
+ parent_tools
+ .iter()
+ .enumerate()
+ .filter(|(_, tool)| {
+ let name = tool.name();
+ if disallowed_tool_matches(disallowed, name) {
+ return false;
+ }
+ // The CCR recovery tool is advertised to any agent that has a tool
+ // surface — compaction applies to its tool output, so the retrieve
+ // footer must be actionable regardless of scope/skill filters (an
+ // explicit `disallow` above still wins). A deliberately tool-less
+ // agent (`Named([])`, e.g. the payload summarizer) runs no tools,
+ // produces no compacted output, and so stays tool-less.
+ if crate::inference::tokenjuice::is_recovery_tool(name) {
+ return !matches!(scope, ToolScope::Named(allowed) if allowed.is_empty());
+ }
+ if let Some(prefix) = skill_prefix.as_deref() {
+ if !name.starts_with(prefix) {
+ return false;
+ }
+ }
+ match scope {
+ ToolScope::Wildcard => true,
+ ToolScope::Named(allowed) => allowed.iter().any(|n| n == name),
+ }
+ })
+ .map(|(i, _)| i)
+ .collect()
+}
+
+/// Intersect a child definition's tool indices with the tools the parent turn
+/// actually exposes. An empty parent set is the legacy "unknown/unrestricted"
+/// sentinel used by internal callers and older tests.
+pub(super) fn retain_parent_visible_tool_indices(
+ indices: &mut Vec<usize>,
+ parent_tools: &[Box<dyn Tool>],
+ parent_visible: &std::collections::HashSet<String>,
+) {
+ if parent_visible.is_empty() {
+ return;
+ }
+ indices.retain(|&index| parent_visible.contains(parent_tools[index].name()));
+}
+
+pub(super) fn disallowed_tool_matches(disallowed: &[String], name: &str) -> bool {
+ disallowed.iter().any(|entry| {
+ if let Some(prefix) = entry.strip_suffix('*') {
+ name.starts_with(prefix)
+ } else {
+ entry == name
+ }
+ })
+}
+
+#[cfg(test)]
+#[path = "tool_prep_tests.rs"]
+mod tests;
+
+#[cfg(test)]
+#[path = "tool_prep_recovery_visibility_tests_tests.rs"]
+mod recovery_visibility_tests;
+
+// ── Prompt loading ──────────────────────────────────────────────────────
+
+/// Resolve a [`PromptSource`] to its raw markdown body. Inline sources
+/// return immediately, `Dynamic` calls the builder with the supplied
+/// [`PromptContext`], `File` sources are read from disk relative to the
+/// workspace `prompts/` directory or the agent crate's bundled prompts.
+///
+pub(super) fn load_prompt_source(
+ source: &PromptSource,
+ ctx: &PromptContext<'_>,
+) -> Result<String, SubagentRunError> {
+ let workspace_dir = ctx.workspace_dir;
+ match source {
+ PromptSource::Inline(body) => Ok(body.clone()),
+ PromptSource::Dynamic(build) => build(ctx).map_err(|e| SubagentRunError::PromptLoad {
+ path: format!("<dynamic:{}>", ctx.agent_id),
+ source: std::io::Error::other(e.to_string()),
+ }),
+ PromptSource::File { path } => {
+ // Try the workspace's `agent/prompts/` first (so users can
+ // override built-in prompts), then fall back to the crate's
+ // own bundled prompts via `include_str!`-style lookup.
+ let prompt_root = workspace_dir.join("agent").join("prompts");
+ let workspace_path = prompt_root.join(path);
+ if workspace_path.is_file() {
+ if let Ok(resolved) =
+ crate::security::validate_path_within_root(&workspace_path, &prompt_root)
+ {
+ return std::fs::read_to_string(&resolved).map_err(|e| {
+ SubagentRunError::PromptLoad {
+ path: resolved.display().to_string(),
+ source: e,
+ }
+ });
+ }
+ tracing::warn!(
+ "[subagent_host] prompt path escapes workspace, skipping: {}",
+ workspace_path.display()
+ );
+ }
+ // Built-in prompt fallback. The agent prompts directory is
+ // already shipped at `crates/openhuman-core/src/agent/prompts/` and
+ // included in the binary via the `IdentitySection` workspace
+ // file write — so we re-use that scaffolding by reading from
+ // `<workspace>/<filename>` after the parent agent has
+ // bootstrapped its workspace files. For sub-agent
+ // archetype prompts (e.g. `archetypes/researcher.md`),
+ // we look up by basename in the workspace, then accept
+ // missing files as an empty body (the runner will fall
+ // back to a generic role hint).
+ let workspace_root_path = workspace_dir.join(path);
+ if workspace_root_path.is_file() {
+ if let Ok(resolved) =
+ crate::security::validate_path_within_root(&workspace_root_path, workspace_dir)
+ {
+ return std::fs::read_to_string(&resolved).map_err(|e| {
+ SubagentRunError::PromptLoad {
+ path: resolved.display().to_string(),
+ source: e,
+ }
+ });
+ }
+ tracing::warn!(
+ "[subagent_host] fallback prompt path escapes workspace, skipping: {}",
+ workspace_root_path.display()
+ );
+ }
+ tracing::warn!(
+ path = %path,
+ "[subagent_host] archetype prompt file not found, using empty body"
+ );
+ Ok(String::new())
+ }
+ }
+}
+
+/// Remove every sub-agent spawn/delegate tool from a child's **dynamic**
+/// (per-spawn) tool list, in place.
+///
+/// The archetype's static surface is stripped via `allowed_indices` in
+/// [`super::ops::run_typed_mode`], but dynamic tools — per-action Composio
+/// toolkit tools and `extract_from_result` — are appended afterwards and never
+/// pass through that filter. That makes this the only route by which a
+/// spawn/delegate name can reach a child's allowlist *admitted*, so the #4452
+/// invariant has to be re-asserted here (issue #6157).
+///
+/// Strip once, at the point the list is finished, rather than at each use: the
+/// same `Vec` feeds the provider-visible specs, the resolved allowlist, the
+/// prompt catalogue, harness registration and the custom-graph request. Filter
+/// one and the others disagree — a tool advertised but not admitted, or the
+/// reverse. The registration-time backstop in
+/// `tinyagents::is_subagent_spawn_or_delegate_tool` is not sufficient on its
+/// own here: it cannot resolve `delegate_name` overrides, so it matches
+/// strictly less than [`is_subagent_spawn_tool`] does.
+pub(super) fn strip_spawn_tools_from_dynamic(
+ dynamic_tools: &mut Vec<Box<dyn Tool>>,
+ agent_id: &str,
+) {
+ dynamic_tools.retain(|tool| {
+ let name = tool.name();
+ // `spawn_worker_thread` is matched separately for the same reason the
+ // caller-side strip does it: it spawns a run without being a delegate.
+ let is_spawn = is_subagent_spawn_tool(name) || name == "spawn_worker_thread";
+ if is_spawn {
+ tracing::warn!(
+ agent_id = %agent_id,
+ tool = name,
+ "[subagent_host] dropped a spawn/delegate tool from a sub-agent's dynamic tools"
+ );
+ }
+ !is_spawn
+ });
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/tool_prep_recovery_visibility_tests_tests.rs b/crates/openhuman-core/src/agent/subagent_host/tool_prep_recovery_visibility_tests_tests.rs
new file mode 100644
index 0000000000..5fdc45d249
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/tool_prep_recovery_visibility_tests_tests.rs
@@ -0,0 +1,73 @@
+use super::*;
+use crate::inference::tokenjuice::LEGACY_RETRIEVE_TOOL_NAME as RECOVERY_TOOL_NAME;
+use crate::tools::{CurrentTimeTool, RetrieveToolOutputTool};
+
+fn tools() -> Vec<Box<dyn tinytools::Tool>> {
+ vec![
+ Box::new(CurrentTimeTool::new()),
+ Box::new(RetrieveToolOutputTool::new()),
+ ]
+}
+
+fn names(idx: &[usize], tools: &[Box<dyn tinytools::Tool>]) -> Vec<String> {
+ idx.iter().map(|&i| tools[i].name().to_string()).collect()
+}
+
+#[test]
+fn named_scope_still_includes_recovery_tool() {
+ let t = tools();
+ // Named scope allow-lists only current_time — recovery tool not listed.
+ let idx = filter_tool_indices(
+ &t,
+ &ToolScope::Named(vec!["current_time".into()]),
+ &[],
+ None,
+ );
+ let got = names(&idx, &t);
+ assert!(got.contains(&"current_time".to_string()));
+ assert!(
+ got.contains(&RECOVERY_TOOL_NAME.to_string()),
+ "recovery tool must survive Named scope: {got:?}"
+ );
+}
+
+#[test]
+fn tool_less_agent_stays_tool_less() {
+ // A deliberately tool-less agent (e.g. the payload summarizer,
+ // ToolScope::Named([])) runs no tools and produces no compacted output,
+ // so it must NOT be handed the recovery tool — it stays empty.
+ let t = tools();
+ let idx = filter_tool_indices(&t, &ToolScope::Named(vec![]), &[], None);
+ assert!(idx.is_empty(), "empty scope must yield zero tools: {idx:?}");
+}
+
+#[test]
+fn skill_filter_still_includes_recovery_tool() {
+ let t = tools();
+ // A skill-restricted subagent (only `foo__*` tools) must still get it.
+ let idx = filter_tool_indices(&t, &ToolScope::Wildcard, &[], Some("foo"));
+ assert!(names(&idx, &t).contains(&RECOVERY_TOOL_NAME.to_string()));
+}
+
+#[test]
+fn explicit_disallow_still_wins() {
+ let t = tools();
+ let idx = filter_tool_indices(
+ &t,
+ &ToolScope::Wildcard,
+ &[RECOVERY_TOOL_NAME.to_string()],
+ None,
+ );
+ assert!(!names(&idx, &t).contains(&RECOVERY_TOOL_NAME.to_string()));
+}
+
+#[test]
+fn parent_visibility_caps_wildcard_child_scope() {
+ let t = tools();
+ let mut idx = filter_tool_indices(&t, &ToolScope::Wildcard, &[], None);
+ let parent_visible = ["current_time".to_string()].into_iter().collect();
+
+ retain_parent_visible_tool_indices(&mut idx, &t, &parent_visible);
+
+ assert_eq!(names(&idx, &t), vec!["current_time".to_string()]);
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/tool_prep_tests.rs b/crates/openhuman-core/src/agent/subagent_host/tool_prep_tests.rs
new file mode 100644
index 0000000000..39f919ad05
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/tool_prep_tests.rs
@@ -0,0 +1,491 @@
+use super::*;
+
+#[test]
+fn custom_delegate_is_treated_as_spawn_tool() {
+ assert!(is_subagent_spawn_tool("spawn_subagent"));
+ assert!(is_subagent_spawn_tool("delegate_researcher"));
+ // Context scouting is top-level only — never visible to sub-agents
+ // (incl. wildcard agents), which would otherwise scout the wrong
+ // parent context. See #3949 review.
+ assert!(is_subagent_spawn_tool("agent_prepare_context"));
+ assert!(!is_subagent_spawn_tool("directory_resolve"));
+}
+
+#[test]
+fn unprefixed_delegate_name_overrides_are_treated_as_spawn_tools() {
+ // Most synthesised delegation tools use an unprefixed
+ // `delegate_name` override (`plan`, `run_code`, `research`, …).
+ // They must be stripped from every sub-agent surface, exactly like
+ // the `delegate_*`-prefixed defaults.
+ let tmp = tempfile::TempDir::new().unwrap();
+ crate::agent::harness::definition::AgentDefinitionRegistry::init_global(tmp.path()).unwrap();
+ for delegate in [
+ "plan",
+ "run_code",
+ "research",
+ "review_code",
+ "do_crypto",
+ "schedule_task",
+ // `make_presentation` is `presentation_agent`'s `delegate_name`; the agent —
+ // and therefore this delegate tool — is compiled out with the
+ // `documents` feature.
+ #[cfg(feature = "documents")]
+ "make_presentation",
+ "archive_session",
+ // `use_mcp_server` is `mcp_agent`'s `delegate_name`; the agent —
+ // and therefore this delegate tool — is compiled out with the
+ // `mcp` feature (#4799). `setup_mcp_server` belongs to
+ // `mcp_setup`, which stays registered in both builds.
+ #[cfg(feature = "mcp")]
+ "use_mcp_server",
+ "setup_mcp_server",
+ ] {
+ assert!(
+ is_subagent_spawn_tool(delegate),
+ "`{delegate}` is a synthesised delegation tool and must be \
+ stripped from sub-agent tool surfaces"
+ );
+ }
+ // Ordinary worker tools stay visible.
+ for plain in ["shell", "file_read", "web_fetch", "todo"] {
+ assert!(
+ !is_subagent_spawn_tool(plain),
+ "`{plain}` must not be classified as a spawn tool"
+ );
+ }
+}
+
+// ── Essential-action reservation (#6033) ────────────────────────────────
+
+use crate::agent::prompts::ConnectedIntegrationTool;
+use tinyagents_harness::tool::{rank_tools_by_prompt, SelectableTool};
+
+fn action(name: &str) -> ConnectedIntegrationTool {
+ ConnectedIntegrationTool {
+ name: name.to_string(),
+ description: format!("{name} description"),
+ parameters: None,
+ }
+}
+
+/// The catalogue the ranker sees for Gmail in the failing case: every
+/// content-returning action gated out, twelve `LIST_*` slots kept.
+fn gmail_catalogue() -> Vec<ConnectedIntegrationTool> {
+ [
+ "GMAIL_LIST_CSE_IDENTITIES",
+ "GMAIL_LIST_DRAFTS",
+ "GMAIL_LIST_LABELS",
+ "GMAIL_LIST_MESSAGES",
+ "GMAIL_LIST_THREADS",
+ "GMAIL_FETCH_EMAILS",
+ "GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID",
+ "GMAIL_SEND_EMAIL",
+ ]
+ .iter()
+ .map(|n| action(n))
+ .collect()
+}
+
+#[test]
+fn essentials_are_reserved_ahead_of_ranked_hits() {
+ let actions = gmail_catalogue();
+ // The ranker picked only LIST_* actions — the #6033 repro.
+ let hits = vec![0, 1, 2, 3, 4];
+ let selected = select_actions_with_essentials("gmail", &actions, &hits, 12);
+ let names: Vec<&str> = selected.iter().map(|&i| actions[i].name.as_str()).collect();
+
+ assert_eq!(
+ &names[..2],
+ &["GMAIL_FETCH_EMAILS", "GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID"],
+ "essentials come first, in table order"
+ );
+ assert!(
+ !names.contains(&"GMAIL_SEND_EMAIL"),
+ "a read prompt must not be handed the send action: {names:?}"
+ );
+ assert!(
+ names.contains(&"GMAIL_LIST_MESSAGES"),
+ "ranked hits still follow the essentials"
+ );
+}
+
+#[test]
+fn an_essential_the_ranker_already_picked_costs_no_extra_slot() {
+ let actions = gmail_catalogue();
+ // Index 5 is GMAIL_FETCH_EMAILS — already ranked.
+ let hits = vec![5, 0, 1];
+ let selected = select_actions_with_essentials("gmail", &actions, &hits, 12);
+
+ let fetches = selected
+ .iter()
+ .filter(|&&i| actions[i].name == "GMAIL_FETCH_EMAILS")
+ .count();
+ assert_eq!(
+ fetches, 1,
+ "no duplicate index for an already-ranked essential"
+ );
+ assert_eq!(
+ selected.len(),
+ selected
+ .iter()
+ .collect::<std::collections::HashSet<_>>()
+ .len(),
+ "selection is duplicate-free"
+ );
+}
+
+#[test]
+fn selection_never_exceeds_the_top_k_budget() {
+ let actions = gmail_catalogue();
+ let hits: Vec<usize> = (0..actions.len()).collect();
+ for top_k in [0_usize, 1, 3, 4, 12] {
+ let selected = select_actions_with_essentials("gmail", &actions, &hits, top_k);
+ assert!(
+ selected.len() <= top_k,
+ "top_k={top_k} budget exceeded: {} kept",
+ selected.len()
+ );
+ assert_eq!(
+ selected.len(),
+ selected
+ .iter()
+ .collect::<std::collections::HashSet<_>>()
+ .len(),
+ "top_k={top_k} produced a duplicate index"
+ );
+ }
+}
+
+#[test]
+fn an_unlisted_toolkit_is_an_exact_passthrough() {
+ let actions: Vec<_> = ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]
+ .iter()
+ .map(|n| action(n))
+ .collect();
+ let hits = vec![1, 0];
+ assert_eq!(
+ select_actions_with_essentials("slack", &actions, &hits, 12),
+ hits,
+ "a toolkit with no essentials must rank exactly as before"
+ );
+}
+
+#[test]
+fn an_essential_absent_from_the_toolkit_is_skipped_not_guessed() {
+ // Connected Gmail exposing none of the essentials: the helper must not
+ // invent an index or panic.
+ let actions: Vec<_> = ["GMAIL_LIST_LABELS", "GMAIL_LIST_THREADS"]
+ .iter()
+ .map(|n| action(n))
+ .collect();
+ let hits = vec![0, 1];
+ let selected = select_actions_with_essentials("gmail", &actions, &hits, 12);
+ assert_eq!(selected, hits);
+ assert!(selected.iter().all(|&i| i < actions.len()));
+}
+
+#[test]
+fn toolkit_lookup_is_case_insensitive() {
+ assert_eq!(
+ essential_actions_for_toolkit("Gmail"),
+ essential_actions_for_toolkit("gmail")
+ );
+ assert!(!essential_actions_for_toolkit("GMAIL").is_empty());
+ assert!(essential_actions_for_toolkit("slack").is_empty());
+}
+
+#[test]
+fn every_essential_name_exists_in_the_real_toolkit_fixture() {
+ // A stale table entry would silently spend no slot and hide the bug it
+ // was added for, so pin the names against the real Composio dump.
+ for (toolkit, essentials) in TOOLKIT_ESSENTIAL_ACTIONS {
+ let path = format!(
+ "{}/tests/fixtures/composio_{}.json",
+ env!("OPENHUMAN_REPOSITORY_ROOT"),
+ toolkit
+ );
+ let raw = std::fs::read_to_string(&path)
+ .unwrap_or_else(|e| panic!("failed to read fixture {path}: {e}"));
+ let parsed: serde_json::Value =
+ serde_json::from_str(&raw).unwrap_or_else(|e| panic!("failed to parse {path}: {e}"));
+ let names: Vec<String> = parsed
+ .pointer("/result/result/tools")
+ .and_then(|t| t.as_array())
+ .unwrap_or_else(|| panic!("missing /result/result/tools in {path}"))
+ .iter()
+ .filter_map(|t| {
+ t.pointer("/function/name")
+ .and_then(|n| n.as_str())
+ .map(str::to_string)
+ })
+ .collect();
+ for essential in *essentials {
+ assert!(
+ names.iter().any(|n| n == essential),
+ "{toolkit} essential {essential} is not a real action in {path}"
+ );
+ }
+ }
+}
+
+#[test]
+fn gmail_read_prompt_keeps_a_content_returning_action() {
+ // The two prompts from #6033: the ranker returns twelve LIST_* actions
+ // and nothing that returns a message body. After reservation the
+ // sub-agent can actually read an email.
+ let path = format!(
+ "{}/tests/fixtures/composio_gmail.json",
+ env!("OPENHUMAN_REPOSITORY_ROOT")
+ );
+ let raw = std::fs::read_to_string(&path).expect("gmail fixture");
+ let parsed: serde_json::Value = serde_json::from_str(&raw).expect("gmail fixture parses");
+ let actions: Vec<ConnectedIntegrationTool> = parsed
+ .pointer("/result/result/tools")
+ .and_then(|t| t.as_array())
+ .expect("fixture tools")
+ .iter()
+ .map(|t| ConnectedIntegrationTool {
+ name: t
+ .pointer("/function/name")
+ .and_then(|n| n.as_str())
+ .unwrap_or_default()
+ .to_string(),
+ description: t
+ .pointer("/function/description")
+ .and_then(|d| d.as_str())
+ .unwrap_or_default()
+ .to_string(),
+ parameters: t.pointer("/function/parameters").cloned(),
+ })
+ .collect();
+
+ for prompt in [
+ "find job opportunities from the last 5 days",
+ "Search the user's Gmail inbox for job opportunity emails from the last 5 days and summarize sender, subject and date",
+ ] {
+ let candidates: Vec<_> = actions
+ .iter()
+ .map(|tool| SelectableTool::new(&tool.name, &tool.description))
+ .collect();
+ let hits = rank_tools_by_prompt(prompt, &candidates, 12);
+ let selected = select_actions_with_essentials("gmail", &actions, &hits, 12);
+ let names: Vec<&str> = selected.iter().map(|&i| actions[i].name.as_str()).collect();
+
+ assert!(
+ names.contains(&"GMAIL_FETCH_EMAILS"),
+ "prompt {prompt:?} must keep a content-returning action; got {names:?}"
+ );
+ assert!(
+ selected.len() <= 12,
+ "prompt {prompt:?} exceeded the budget"
+ );
+ assert_eq!(
+ selected.len(),
+ selected
+ .iter()
+ .collect::<std::collections::HashSet<_>>()
+ .len(),
+ "prompt {prompt:?} produced a duplicate index"
+ );
+ }
+}
+
+#[test]
+fn every_essential_action_is_read_only() {
+ // Essentials are forced onto a delegation whatever it asked for, so a
+ // write action here would hand a read task an unrequested
+ // side-effecting capability that the approval middleware does not gate
+ // (a ComposioActionTool does not override `external_effect`).
+ const WRITE_VERBS: &[&str] = &[
+ "SEND", "CREATE", "DELETE", "UPDATE", "PATCH", "MOVE", "MODIFY", "ADD", "REMOVE", "TRASH",
+ "REPLY", "FORWARD", "DRAFT",
+ ];
+ for (toolkit, essentials) in TOOLKIT_ESSENTIAL_ACTIONS {
+ for essential in *essentials {
+ let verb = essential
+ .split('_')
+ .nth(1)
+ .unwrap_or_default()
+ .to_ascii_uppercase();
+ assert!(
+ !WRITE_VERBS.contains(&verb.as_str()),
+ "{toolkit} essential {essential} is a write action; essentials must be read-only"
+ );
+ }
+ }
+}
+
+// ── Dynamic-tool spawn strip (#6157) ────────────────────────────────────
+
+use async_trait::async_trait;
+use tinytools::Tool;
+
+/// A tool that is nothing but its name — the strip reads no other field.
+struct NamedTool(&'static str);
+
+#[async_trait]
+impl Tool for NamedTool {
+ /// The caller-chosen name.
+ fn name(&self) -> &str {
+ self.0
+ }
+
+ /// Unused by the strip.
+ fn description(&self) -> &str {
+ "stub"
+ }
+
+ /// Unused by the strip.
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({})
+ }
+
+ /// Never called: the strip only inspects names.
+ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<tinytools::ToolResult> {
+ Ok(tinytools::ToolResult::success(String::new()))
+ }
+}
+
+/// A dynamic-tool list carrying exactly these names, in this order.
+fn dynamic(names: &[&'static str]) -> Vec<Box<dyn Tool>> {
+ names
+ .iter()
+ .map(|name| Box::new(NamedTool(name)) as Box<dyn Tool>)
+ .collect()
+}
+
+/// The surviving names, so a test can assert on content *and* order.
+fn names_of(tools: &[Box<dyn Tool>]) -> Vec<&str> {
+ tools.iter().map(|t| t.name()).collect()
+}
+
+/// The shape the runner actually builds: Composio actions plus the
+/// progressive-disclosure handoff tool, with spawn tools interleaved.
+#[test]
+fn dynamic_tools_keep_ordinary_actions_and_lose_spawn_tools() {
+ let mut tools = dynamic(&[
+ "GMAIL_FETCH_EMAILS",
+ "spawn_subagent",
+ "extract_from_result",
+ "delegate_graph",
+ "spawn_worker_thread",
+ "GMAIL_SEND_EMAIL",
+ "agent_prepare_context",
+ ]);
+ strip_spawn_tools_from_dynamic(&mut tools, "researcher");
+
+ assert_eq!(
+ names_of(&tools),
+ vec![
+ "GMAIL_FETCH_EMAILS",
+ "extract_from_result",
+ "GMAIL_SEND_EMAIL"
+ ],
+ "only spawn/delegate tools are dropped, and surviving order is preserved"
+ );
+}
+
+/// The whole reason the strip lives here rather than relying on the
+/// registration-time backstop: that backstop matches `delegate_*` by prefix and
+/// would keep `plan`, which is `planner`'s `delegate_name`.
+#[test]
+fn dynamic_tools_lose_unprefixed_delegate_name_overrides() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ crate::agent::harness::definition::AgentDefinitionRegistry::init_global(tmp.path()).unwrap();
+
+ let mut tools = dynamic(&["plan", "run_code", "shell", "web_fetch"]);
+ strip_spawn_tools_from_dynamic(&mut tools, "researcher");
+
+ assert_eq!(
+ names_of(&tools),
+ vec!["shell", "web_fetch"],
+ "`delegate_name` overrides are spawn tools even without the prefix"
+ );
+}
+
+/// The live case today: no dynamic tool is named after a spawn tool, so the
+/// strip must be a no-op rather than a silent narrowing of the surface.
+#[test]
+fn a_dynamic_tool_list_without_spawn_tools_is_untouched() {
+ let mut tools = dynamic(&["GMAIL_FETCH_EMAILS", "extract_from_result"]);
+ strip_spawn_tools_from_dynamic(&mut tools, "researcher");
+
+ assert_eq!(
+ names_of(&tools),
+ vec!["GMAIL_FETCH_EMAILS", "extract_from_result"]
+ );
+}
+
+/// Render the `## Tools` section the way a sub-agent prompt does, at `format`.
+fn render_tools_at(format: crate::agent::prompts::ToolCallFormat, instructions: &str) -> String {
+ use crate::agent::prompts::{LearnedContextData, PromptTool};
+ let tools = [PromptTool {
+ name: "composio_execute",
+ description: "Run one Composio action.",
+ parameters_schema: Some(
+ r#"{"type":"object","properties":{"action":{"type":"string"}}}"#.into(),
+ ),
+ }];
+ let visible = std::collections::HashSet::new();
+ let ctx = PromptContext {
+ workspace_dir: std::path::Path::new("/tmp"),
+ model_name: "test-model",
+ agent_id: "integrations_agent",
+ tools: &tools,
+ workflows: &[],
+ dispatcher_instructions: instructions,
+ learned: LearnedContextData::default(),
+ visible_tool_names: &visible,
+ tool_call_format: format,
+ connected_integrations: &[],
+ connected_identities_md: String::new(),
+ include_profile: false,
+ include_memory_md: false,
+ curated_snapshot: None,
+ user_identity: None,
+ personality_roster: vec![],
+ agents_md_global: None,
+ agents_md_local: None,
+ };
+ crate::agent::prompts::render_tools(&ctx).unwrap()
+}
+
+/// A text-mode child of a native-tool parent is sent no native `tools`, so its
+/// prompt must list them. Rendering at the parent's format is what used to
+/// happen: no catalogue at all, plus the native JSON protocol.
+#[test]
+fn text_mode_child_of_a_native_parent_renders_its_tool_catalogue() {
+ use crate::agent::prompts::ToolCallFormat;
+
+ let (format, instructions) = subagent_prompt_protocol(ToolCallFormat::Native, true);
+ assert_eq!(format, ToolCallFormat::PFormat);
+ assert!(
+ instructions.is_empty(),
+ "the runner appends the text-mode protocol itself; a second block conflicts: {instructions}"
+ );
+ let rendered = render_tools_at(format, &instructions);
+ assert!(
+ rendered.contains("- **composio_execute**:"),
+ "text-mode child has no tool catalogue: {rendered:?}"
+ );
+
+ let parents = render_tools_at(ToolCallFormat::Native, "");
+ assert!(
+ !parents.contains("- **composio_execute**:"),
+ "a native-format render is expected to omit the catalogue: {parents:?}"
+ );
+}
+
+#[test]
+fn native_child_keeps_the_parents_protocol() {
+ use crate::agent::prompts::ToolCallFormat;
+
+ for parent in [
+ ToolCallFormat::Native,
+ ToolCallFormat::PFormat,
+ ToolCallFormat::Json,
+ ] {
+ let (format, _) = subagent_prompt_protocol(parent, false);
+ assert_eq!(format, parent);
+ }
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/tool_ranking_tests.rs b/crates/openhuman-core/src/agent/subagent_host/tool_ranking_tests.rs
new file mode 100644
index 0000000000..9b2a13f4a9
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/tool_ranking_tests.rs
@@ -0,0 +1,323 @@
+//! Host-side coverage for direct tinyagents tool ranking.
+//!
+//! The ranking algorithm itself is tested upstream in
+//! `tinyagents_harness::tool::select`, against synthetic catalogues. What is
+//! tested here is the host fixture conversion from `ConnectedIntegrationTool`,
+//! exercised against the real Composio tool-list dumps in
+//! `tests/fixtures/` (1000 actions across nine toolkits). Those fixtures are
+//! host data about a specific integration provider and have no business in a
+//! provider-neutral library crate, so this suite stays here rather than
+//! moving up with the algorithm.
+
+use crate::agent::prompts::ConnectedIntegrationTool;
+use tinyagents_harness::tool::{rank_tools_by_prompt, SelectableTool, MIN_CONFIDENT_HITS};
+
+fn rank_actions_by_prompt(
+ prompt: &str,
+ actions: &[ConnectedIntegrationTool],
+ max_results: usize,
+) -> Vec<usize> {
+ let candidates: Vec<_> = actions
+ .iter()
+ .map(|tool| SelectableTool::new(&tool.name, &tool.description))
+ .collect();
+ rank_tools_by_prompt(prompt, &candidates, max_results)
+}
+
+// ── Real-dataset integration tests ────────────────────────────────
+//
+// These run the filter against the actual Composio tool-list dump
+// for each toolkit (1000 tools total) captured from a live sidecar
+// `openhuman.composio_list_tools` call. Fixtures live in
+// `tests/fixtures/composio_<toolkit>.json`.
+
+fn load_real_toolkit(toolkit: &str) -> Vec<ConnectedIntegrationTool> {
+ let path = format!(
+ "{}/tests/fixtures/composio_{}.json",
+ env!("OPENHUMAN_REPOSITORY_ROOT"),
+ toolkit
+ );
+ let raw = std::fs::read_to_string(&path)
+ .unwrap_or_else(|e| panic!("failed to read fixture {path}: {e}"));
+ let v: serde_json::Value =
+ serde_json::from_str(&raw).unwrap_or_else(|e| panic!("failed to parse {path}: {e}"));
+ let tools = v
+ .pointer("/result/result/tools")
+ .and_then(|t| t.as_array())
+ .unwrap_or_else(|| panic!("missing /result/result/tools in {path}"));
+ tools
+ .iter()
+ .map(|t| {
+ let f = &t["function"];
+ ConnectedIntegrationTool {
+ name: f["name"].as_str().unwrap_or("").to_string(),
+ description: f["description"].as_str().unwrap_or("").to_string(),
+ parameters: None,
+ }
+ })
+ .collect()
+}
+
+/// Assert `wanted` shows up in the top-K indices of the filter output.
+fn assert_in_top(actions: &[ConnectedIntegrationTool], hits: &[usize], wanted: &str, label: &str) {
+ let top_names: Vec<&str> = hits.iter().map(|&i| actions[i].name.as_str()).collect();
+ assert!(
+ top_names.iter().any(|n| *n == wanted),
+ "[{label}] '{wanted}' not in top {k}: {top_names:?}",
+ k = hits.len()
+ );
+}
+
+#[test]
+fn real_data_github_create_pr() {
+ let actions = load_real_toolkit("github");
+ assert!(actions.len() > 400, "github fixture should have ~500 tools");
+ let hits = rank_actions_by_prompt(
+ "Create a pull request from feature/auth-fix to main in the openhuman repo",
+ &actions,
+ 15,
+ );
+ assert!(hits.len() >= MIN_CONFIDENT_HITS);
+ assert!(
+ hits.len() < actions.len() / 5,
+ "filter should narrow by >80%, got {}/{}",
+ hits.len(),
+ actions.len()
+ );
+ assert_in_top(
+ &actions,
+ &hits,
+ "GITHUB_CREATE_A_PULL_REQUEST",
+ "github create PR",
+ );
+}
+
+#[test]
+fn real_data_github_list_prs() {
+ let actions = load_real_toolkit("github");
+ let hits = rank_actions_by_prompt(
+ "Find all open pull requests assigned to the current user in the openhuman repo",
+ &actions,
+ 15,
+ );
+ assert!(hits.len() >= MIN_CONFIDENT_HITS);
+ assert_in_top(
+ &actions,
+ &hits,
+ "GITHUB_FIND_PULL_REQUESTS",
+ "github list PRs",
+ );
+}
+
+#[test]
+fn real_data_gmail_send_email() {
+ let actions = load_real_toolkit("gmail");
+ let hits = rank_actions_by_prompt(
+ "Send an email to [email protected] with subject 'Q2 Report' and body attached",
+ &actions,
+ 10,
+ );
+ assert!(hits.len() >= MIN_CONFIDENT_HITS);
+ assert_in_top(&actions, &hits, "GMAIL_SEND_EMAIL", "gmail send email");
+ // Top 3 should all be send-related, not label/trash operations.
+ for &i in hits.iter().take(3) {
+ let n = &actions[i].name;
+ assert!(
+ n.contains("SEND") || n.contains("REPLY") || n.contains("DRAFT"),
+ "non-send tool in top 3: {n}"
+ );
+ }
+}
+
+#[test]
+fn real_data_gmail_delete_emails() {
+ let actions = load_real_toolkit("gmail");
+ let hits = rank_actions_by_prompt(
+ "Delete all promotional emails received in the last week",
+ &actions,
+ 10,
+ );
+ assert!(hits.len() >= MIN_CONFIDENT_HITS);
+ // All top results must be DELETE-flavoured, not send/fetch.
+ for &i in &hits {
+ let n = &actions[i].name;
+ assert!(
+ n.contains("DELETE") || n.contains("TRASH") || n.contains("REMOVE"),
+ "non-delete tool in delete query top-K: {n}"
+ );
+ }
+}
+
+#[test]
+fn real_data_slack_send_message() {
+ let actions = load_real_toolkit("slack");
+ let hits = rank_actions_by_prompt(
+ "Post a message to the #general channel saying the deploy is complete",
+ &actions,
+ 15,
+ );
+ assert!(hits.len() >= MIN_CONFIDENT_HITS);
+ assert_in_top(&actions, &hits, "SLACK_SEND_MESSAGE", "slack send message");
+}
+
+#[test]
+fn real_data_notion_create_page() {
+ let actions = load_real_toolkit("notion");
+ let hits = rank_actions_by_prompt(
+ "Create a new page in the Engineering workspace titled 'Sprint Plan'",
+ &actions,
+ 15,
+ );
+ assert!(hits.len() >= MIN_CONFIDENT_HITS);
+ assert_in_top(
+ &actions,
+ &hits,
+ "NOTION_CREATE_NOTION_PAGE",
+ "notion create page",
+ );
+}
+
+#[test]
+fn real_data_full_funnel_report() {
+ // Non-asserting report showing the reduction ratio across all toolkits
+ // for a representative query. Prints to stderr; run with
+ // `cargo test real_data_full_funnel_report -- --nocapture`.
+ let cases: &[(&str, &str)] = &[
+ ("gmail", "send an email to the team about the release"),
+ (
+ "github",
+ "create a pull request from feature branch to main",
+ ),
+ ("slack", "post a message to the general channel"),
+ ("notion", "create a new page in the engineering database"),
+ (
+ "googlesheets",
+ "add a row with today's sales to the revenue sheet",
+ ),
+ ("googledrive", "upload a file to the shared design folder"),
+ ("instagram", "schedule a post with this photo and caption"),
+ ("reddit", "comment on the top post in r/rust"),
+ ("facebook", "post a status update to my page"),
+ ];
+ let mut total_in = 0usize;
+ let mut total_out = 0usize;
+ for (tk, q) in cases {
+ let actions = load_real_toolkit(tk);
+ let hits = rank_actions_by_prompt(q, &actions, 15);
+ let kept = if hits.len() >= MIN_CONFIDENT_HITS {
+ hits.len()
+ } else {
+ actions.len() // fallback path
+ };
+ total_in += actions.len();
+ total_out += kept;
+ eprintln!(
+ "{:13} {:4} → {:3} ({:5.1}% kept) query: {}",
+ tk,
+ actions.len(),
+ kept,
+ 100.0 * kept as f64 / actions.len() as f64,
+ q
+ );
+ }
+ eprintln!(
+ "TOTAL {total_in:4} → {total_out:3} ({:5.1}% kept)",
+ 100.0 * total_out as f64 / total_in as f64
+ );
+ assert!(total_out < total_in / 3, "overall reduction should be >66%");
+}
+
+// ── Repro: issue #3152 — Composio write action unreachable ──────────
+//
+// `integrations_agent` asked to CREATE a Notion page. Notion is a
+// HEAVY_SCHEMA toolkit → production top_k = 12. The verb gate + score cull
+// advertise only read-leaning actions, so `NOTION_CREATE_NOTION_PAGE` never
+// reaches the model. Asserts DESIRED post-fix behaviour → RED until the
+// write-reservation fix lands.
+#[test]
+fn repro_3152_create_page_reachable_in_top_k() {
+ let actions = load_real_toolkit("notion");
+ let hits = rank_actions_by_prompt(
+ "create a notion page with the meeting notes and give me the link",
+ &actions,
+ 12,
+ );
+ assert_in_top(
+ &actions,
+ &hits,
+ "NOTION_CREATE_NOTION_PAGE",
+ "#3152 notion create-page",
+ );
+}
+
+// ── Ranking-drift guard ────────────────────────────────────────────
+//
+// Exact top-5 orderings captured from the pre-extraction implementation,
+// before the algorithm moved into `tinyagents`. The ranker decides which
+// actions a model is shown, so a scoring change is a silent behaviour change;
+// these pin the ordering through the adapter, over real catalogues.
+#[test]
+fn adapter_ranking_matches_the_pre_extraction_snapshot() {
+ let cases: &[(&str, &str, usize, &[&str])] = &[
+ (
+ "github",
+ "Create a pull request from feature/auth-fix to main in the openhuman repo",
+ 15,
+ &[
+ "GITHUB_CREATE_A_CODESPACE_FROM_A_PULL_REQUEST",
+ "GITHUB_CREATE_A_PULL_REQUEST",
+ "GITHUB_CREATE_REACTION_FOR_A_PULL_REQUEST_REVIEW_COMMENT",
+ "GITHUB_CREATE_A_REVIEW_COMMENT_FOR_A_PULL_REQUEST",
+ "GITHUB_CREATE_A_REVIEW_FOR_A_PULL_REQUEST",
+ ],
+ ),
+ (
+ "gmail",
+ "Send an email to [email protected] with subject 'Q2 Report' and body attached",
+ 10,
+ &[
+ "GMAIL_SEND_EMAIL",
+ "GMAIL_SEND_DRAFT",
+ "GMAIL_SETTINGS_SEND_AS_GET",
+ "GMAIL_REPLY_TO_THREAD",
+ "GMAIL_FORWARD_MESSAGE",
+ ],
+ ),
+ (
+ "slack",
+ "Post a message to the #general channel saying the deploy is complete",
+ 15,
+ &[
+ "SLACK_SEND_MESSAGE",
+ "SLACK_SEND_EPHEMERAL_MESSAGE",
+ "SLACK_SEND_ME_MESSAGE",
+ "SLACK_CREATE_CHANNEL",
+ "SLACK_CREATE_CHANNEL_BASED_CONVERSATION",
+ ],
+ ),
+ (
+ "notion",
+ "Create a new page in the Engineering workspace titled 'Sprint Plan'",
+ 15,
+ &[
+ "NOTION_CREATE_NOTION_PAGE",
+ "NOTION_CREATE_COMMENT",
+ "NOTION_ADD_MULTIPLE_PAGE_CONTENT",
+ "NOTION_ADD_PAGE_CONTENT",
+ "NOTION_CREATE_DATABASE",
+ ],
+ ),
+ ];
+ for (toolkit, prompt, top_k, expected) in cases {
+ let actions = load_real_toolkit(toolkit);
+ let got: Vec<&str> = rank_actions_by_prompt(prompt, &actions, *top_k)
+ .into_iter()
+ .take(expected.len())
+ .map(|i| actions[i].name.as_str())
+ .collect();
+ assert_eq!(
+ &got, expected,
+ "ranking drifted for {toolkit} prompt {prompt:?}"
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/types.rs b/crates/openhuman-core/src/agent/subagent_host/types.rs
new file mode 100644
index 0000000000..9dfe3b948b
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/types.rs
@@ -0,0 +1,356 @@
+//! Public types for the sub-agent runner: spawn options, outcome,
+//! execution mode, and error taxonomy. Pulled out of `ops.rs` so
+//! external callers importing these shapes don't drag in the full
+//! orchestration machinery.
+
+use std::path::PathBuf;
+use std::time::Duration;
+use thiserror::Error;
+use tinytools::WorkspaceDescriptor;
+
+use crate::agent::harness::definition::AgentTier;
+use crate::agent::messages::ChatMessage;
+
+/// Per-spawn options that override or augment what the
+/// [`AgentDefinition`] specifies. Built by `SpawnSubagentTool::execute`
+/// from the parent model's call arguments.
+#[derive(Clone, Default)]
+pub struct SubagentRunOptions {
+ /// Optional skill-id override (e.g. `"notion"`). When set, the
+ /// resolved tool list is further restricted to tools whose name
+ /// starts with `{skill}__`. Overrides `definition.skill_filter`.
+ pub skill_filter_override: Option<String>,
+
+ /// Optional Composio toolkit scope (e.g. `"gmail"`, `"notion"`).
+ /// When set, skill-category tools are further restricted to those
+ /// whose name starts with the uppercased `{toolkit}_` prefix, and
+ /// the sub-agent's rendered `Connected Integrations` section is
+ /// narrowed to only that toolkit's entry. Used by main/orchestrator
+ /// when spawning `integrations_agent` for a specific platform so the
+ /// sub-agent only sees one integration's tool catalogue.
+ pub toolkit_override: Option<String>,
+
+ /// Optional context blob the parent wants to inject before the
+ /// task prompt. Rendered as a `[Context]\n…\n` prefix.
+ pub context: Option<String>,
+
+ /// Optional exact model id for this single spawn. When present it
+ /// wins over the agent definition's model spec but keeps the
+ /// parent's provider/routing unchanged.
+ pub model_override: Option<String>,
+
+ /// Stable id for tracing / DomainEvents (defaults to a UUID).
+ pub task_id: Option<String>,
+
+ /// Explicit thread identity for the child run. Tool callers copy this from
+ /// their `ToolRunContext`; detached workers set the durable worker affinity
+ /// before crossing `tokio::spawn`. This is never recovered from a task-local.
+ pub thread_id: Option<String>,
+
+ /// Explicit host carrier for the child run. Recursive execution must use
+ /// this value rather than snapshotting task-local scopes after a spawn.
+ pub run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
+
+ /// Optional thread ID for persistent worker threads. When set,
+ /// every assistant message and tool result in the inner loop is
+ /// appended to this thread in the global ConversationStore.
+ pub worker_thread_id: Option<String>,
+
+ /// Pre-populated conversation history for resuming a paused
+ /// sub-agent (checkpoint + replay). When `Some`, the runner skips
+ /// system-prompt + user-message construction and uses this history
+ /// directly — it already contains the system prompt and all prior
+ /// turns including the clarification tool call/result.
+ pub initial_history: Option<Vec<ChatMessage>>,
+
+ /// Directory for writing/reading checkpoint files when the
+ /// sub-agent pauses for user input. Defaults to
+ /// `{workspace_dir}/.openhuman/subagent_checkpoints/`.
+ pub checkpoint_dir: Option<PathBuf>,
+
+ /// Per-worker isolated checkout for git-worktree isolation.
+ ///
+ /// When `Some`, the runner derives a [`WorkspaceDescriptor`] rooted at this
+ /// path (see `workspace_descriptor_for_subagent`) and threads it onto the
+ /// tinyagents run context, so acting tools (shell, git) resolve their CWD to
+ /// the worker's isolated worktree checkout via
+ /// `ToolExecutionContext.workspace` instead of the shared `Config.action_dir`.
+ /// When `None` (the default), behaviour is unchanged — tools fall through to
+ /// `security.action_dir`.
+ pub worktree_action_dir: Option<PathBuf>,
+
+ /// SDK workspace descriptor threaded into the TinyAgents tool-execution
+ /// context. When present it is attached to the run's `RunContext`
+ /// (`RunContext::with_workspace`) and surfaced per tool call via
+ /// `ToolExecutionContext::from_run_context`; acting tools read
+ /// `ToolExecutionContext.workspace` to route their CWD (issue #4249, 08.5).
+ pub workspace_descriptor: Option<WorkspaceDescriptor>,
+
+ /// Steering channel for a running (typically async) sub-agent. When set,
+ /// the tinyagents harness drains steer/collect messages from this queue at
+ /// iteration boundaries — exactly like the main agent loop — so the parent
+ /// can `steer_subagent` mid-flight. `None` keeps today's non-steerable
+ /// behaviour.
+ pub run_queue: Option<
+ std::sync::Arc<
+ tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>,
+ >,
+ >,
+}
+
+/// Terminal status of a sub-agent run.
+#[derive(Debug, Clone)]
+pub enum SubagentRunStatus {
+ /// The sub-agent completed normally with a final response.
+ Completed,
+ /// The sub-agent called `ask_user_clarification` and is waiting
+ /// for the orchestrator to relay the user's answer via
+ /// `continue_subagent`.
+ AwaitingUser {
+ question: String,
+ options: Option<Vec<String>>,
+ /// Where the paused conversation was persisted, or `None` when it
+ /// could not be.
+ ///
+ /// This used to be an unstated promise — the doc said "the checkpoint
+ /// file contains the full conversation history" while every write
+ /// failure in the runner was logged at `warn` and then reported as an
+ /// ordinary `AwaitingUser` anyway. The orchestrator relayed a question
+ /// and a `task_id`, and the failure only surfaced much later, when the
+ /// user had already answered and `continue_subagent` found nothing on
+ /// disk. Carrying the outcome here is what makes a failed write
+ /// visible at pause time rather than at resume time (#5928).
+ ///
+ /// `None` does not mean resumption is impossible: a sub-agent with a
+ /// durable session can still be continued from the
+ /// `[active_subagents]` roster. It means resumption *from this pause*
+ /// is not available, which is a different promise.
+ checkpoint: Option<PathBuf>,
+ },
+ /// The sub-agent stopped WITHOUT reaching its goal — a circuit breaker
+ /// halted it (stuck: repeated identical call / repeated output / repeated
+ /// failure) or it hit the iteration cap. The run's `output` carries whatever
+ /// partial progress / checkpoint summary it produced; `reason` is a short,
+ /// machine-set explanation of why it stopped. The delegating agent must NOT
+ /// treat this as a completed result, and must not re-run the identical
+ /// delegation unchanged.
+ Incomplete {
+ /// Short, machine-set reason the run stopped short (stuck vs. cap).
+ reason: String,
+ },
+ /// Cooperative cancellation won the subagent lifecycle. This is distinct
+ /// from an incomplete run so callers never publish a completed result for
+ /// work the user or host explicitly stopped.
+ Cancelled,
+}
+
+/// Outcome of a single sub-agent run, returned to the parent.
+#[derive(Debug, Clone)]
+pub struct SubagentRunOutcome {
+ /// Unique identifier for this sub-task run.
+ pub task_id: String,
+ /// The ID of the agent archetype used (e.g., `researcher`).
+ pub agent_id: String,
+ /// The final text response produced by the sub-agent.
+ pub output: String,
+ /// How many LLM round-trips were performed during the run.
+ pub iterations: usize,
+ /// Total wall-clock duration of the run.
+ pub elapsed: Duration,
+ /// Which execution mode was used (Typed vs. Fork).
+ pub mode: SubagentMode,
+ /// Whether the run completed or paused for user input.
+ pub status: SubagentRunStatus,
+ /// Final in-memory history after the run loop exits. Durable sub-agent
+ /// sessions persist this so an idle worker can resume without rebuilding
+ /// its context from only the parent transcript.
+ pub final_history: Vec<ChatMessage>,
+ /// Token + cost accounting accumulated across every provider call this
+ /// sub-agent made. Surfaced so the parent turn can roll child spend into
+ /// the session totals (tokens + USD) and the global cost tracker. See
+ /// [`SubagentUsage`].
+ pub usage: SubagentUsage,
+ /// `action_dir`-relative paths of artifacts this run handed to its parent
+ /// (#3883). Populated from the `[artifact]` pointers present in `output`,
+ /// whether the harness offloaded an oversized result itself or the worker
+ /// followed the prompt contract and wrote the file on its own.
+ ///
+ /// This is what makes the handoff carry **paths** rather than payloads: the
+ /// parent can read any of these with `file_read` to recover full fidelity
+ /// long after the child's context is gone. Empty for the common case of a
+ /// small, fully inline result.
+ pub artifact_paths: Vec<String>,
+ /// The neutral persistence boundary that produced this outcome. Event and
+ /// progress publishers must gate terminal effects on its committed variants
+ /// so replayed durable outcomes are not announced a second time.
+ pub persistence_disposition: tinyagents_orchestration::subagent::SubagentPersistenceDisposition,
+}
+
+impl SubagentRunOutcome {
+ /// Whether this invocation owns lifecycle-completion event/progress
+ /// effects after a successful durable commit.
+ pub const fn should_emit_lifecycle_effects(&self) -> bool {
+ self.persistence_disposition.should_emit_host_effects()
+ }
+}
+
+/// Token + cost totals for a single sub-agent run.
+///
+/// Mirrors the inner-loop `AggregatedUsage`, lifted into the public outcome so
+/// the parent turn can fold sub-agent spend into the session-level token/cost
+/// meters surfaced in the UI footer.
+#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct SubagentUsage {
+ pub input_tokens: u64,
+ pub output_tokens: u64,
+ pub cached_input_tokens: u64,
+ pub charged_amount_usd: f64,
+}
+
+/// Which prompt-construction path the runner took for a sub-agent.
+///
+/// Currently the only supported mode is `Typed` (narrow, archetype-specific
+/// prompt with filtered tools). Kept as an enum so future modes (e.g.
+/// background/swarm) can land without churning every call site that records
+/// the mode for telemetry.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SubagentMode {
+ /// Built a narrow, archetype-specific prompt with filtered tools.
+ Typed,
+}
+
+impl SubagentMode {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Typed => "typed",
+ }
+ }
+}
+
+/// Serialisable checkpoint written when a sub-agent pauses for user input.
+/// Contains everything needed to resume the run from where it left off.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct SubagentCheckpointData {
+ /// The original neutral key, recovered for continuation rather than
+ /// re-derived from a fresh child context.
+ #[serde(default)]
+ pub task_key: Option<tinyagents_orchestration::subagent::SubagentTaskKey>,
+ pub task_id: String,
+ pub agent_id: String,
+ pub worker_thread_id: Option<String>,
+ pub history: Vec<ChatMessage>,
+ pub question: String,
+ pub options: Option<Vec<String>>,
+ /// Composio toolkit override, if the paused run was scoped to one.
+ pub toolkit_override: Option<String>,
+ /// Workflow filter override, if the paused run was scoped to one.
+ pub skill_filter_override: Option<String>,
+ /// Model override, if one was set for this run.
+ pub model_override: Option<String>,
+ pub created_at: String,
+ #[serde(default)]
+ pub resume_checkpoint: Option<String>,
+ #[serde(default)]
+ pub resume_metadata: std::collections::BTreeMap<String, String>,
+ /// Visible outcome fields retained with a pause so an observer that loses
+ /// the lifecycle compare-and-swap can return the durable winner exactly.
+ #[serde(default)]
+ pub output: String,
+ #[serde(default)]
+ pub iterations: usize,
+ #[serde(default)]
+ pub usage: SubagentUsage,
+ #[serde(default)]
+ pub artifact_paths: Vec<String>,
+ /// Wall-clock duration of the durable winner. Kept with pause data so a
+ /// duplicate observer can reconstruct the original host outcome without
+ /// substituting its own elapsed time.
+ #[serde(default)]
+ pub elapsed_ms: u64,
+}
+
+/// Errors the runner can surface to the parent. The parent receives a
+/// stringified version inside a tool result block.
+#[derive(Debug, Error)]
+pub enum SubagentRunError {
+ #[error("spawn_subagent called outside of an agent turn — no parent context available")]
+ NoParentContext,
+
+ #[error("agent definition '{0}' not found in registry")]
+ DefinitionNotFound(String),
+
+ #[error("failed to load archetype prompt from '{path}': {source}")]
+ PromptLoad {
+ path: String,
+ #[source]
+ source: std::io::Error,
+ },
+
+ #[error("provider call failed: {0}")]
+ Provider(#[from] anyhow::Error),
+
+ #[error("sub-agent spawn depth exceeded: attempted depth {attempted_depth}, max {max_depth}")]
+ SpawnDepthExceeded {
+ attempted_depth: usize,
+ max_depth: usize,
+ },
+
+ #[error(
+ "delegation blocked by the spawn-hierarchy gate: a `{parent_tier}` agent may not \
+ delegate to a `{child_tier}` agent — {reason}"
+ )]
+ TierViolation {
+ parent_tier: AgentTier,
+ child_tier: AgentTier,
+ reason: String,
+ },
+
+ #[error("sub-agent exceeded maximum iterations ({0})")]
+ MaxIterationsExceeded(usize),
+
+ /// A configured `subagentStart` hook refused the spawn.
+ ///
+ /// Distinct from [`Self::TierViolation`] on purpose: a tier violation is a
+ /// fact about the agent graph the model cannot do anything about, while
+ /// this one carries a reason a human wrote and the model may be able to
+ /// satisfy — so the two must not read the same in a transcript.
+ #[error("delegation blocked by a configured hook: {0}")]
+ HookDenied(String),
+
+ /// The turn asked to pause gracefully at its model-call cap before this
+ /// dispatch was attempted (#5804).
+ ///
+ /// Distinct from the budget refusal below on purpose: this one is a fact
+ /// about the turn's *intent* — the loop is going to stop at its next
+ /// boundary no matter how much time is left — while the other is a
+ /// measured prediction. Reported to the model as a terminal instruction to
+ /// summarise, because further fan-out cannot reach the answer and can only
+ /// consume the budget the checkpoint summary needs.
+ #[error(
+ "delegation refused: this turn reached its model-call cap ({completed_model_calls}/{cap}) \
+ and has already requested a graceful pause. Do not delegate again — summarise the results \
+ you already have and finish the turn."
+ )]
+ PauseRequested {
+ completed_model_calls: u64,
+ cap: u64,
+ },
+
+ /// Less wall-clock remained than the slowest sub-agent this turn has
+ /// actually completed, so the dispatch could not have finished (#5804).
+ ///
+ /// The comparison is against this turn's own measured maximum, never a
+ /// configured constant, so the refusal means the same thing for a turn
+ /// with three fast children as for one with three hundred slow ones.
+ #[error(
+ "delegation refused: {remaining_ms} ms of this turn's wall-clock budget remain, but the \
+ slowest of its {observed_samples} completed sub-agent(s) took {observed_max_ms} ms, so a \
+ new delegation cannot finish in time. Summarise the results you already have and finish \
+ the turn."
+ )]
+ DispatchBudgetExhausted {
+ remaining_ms: u64,
+ observed_max_ms: u64,
+ observed_samples: u64,
+ },
+}