Skip to content

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

fix(agent): fall back on a blank clarification question, and unblock the layout gate\n\nTwo follow-ups to the `ask_user_clarification` pause, both found after the\noriginal push.\n\n`{"question":""}` is a legal call — the schema has no `minLength` — and\n`as_str()` answers `Some("")`, which slipped past the missing-argument\nfallback. That was survivable only while `[CLARIFICATION NEEDED]` kept the\noutput non-empty. Now that this output *is* the message the user reads, an\nempty one parks the turn on a blank prompt: a blank assistant reply on the\nchannel path, the empty-output final-summary branch on the session path, and an\n`AwaitingUser` sub-agent card with nothing in it. So blank now counts as\nabsent, trimmed, and takes the same generic fallback a missing argument does.\nRaised by @chatgpt-codex-connector in review; a regression this branch\nintroduced by removing the marker.\n\n`Rust Quality` was red, and not on formatting — `Check Rust formatting`\npassed and `Enforce OpenHuman Rust file layout` failed:\n\n src/openhuman/agent/harness/session/turn/core_session.rs: 758 lines (limit 750)\n\nThe file was at 744 and the early-exit branch pushed it over. Split per the\nrepo's own `_part_NN.rs` convention (85 files already use it) rather than\ntrimming the reasoning to buy eight lines: part 01 is the turn driver, part 02\nthe context injection it calls, each a self-contained `impl Agent` block\nspliced into `core.rs` as before. No behaviour moves.\n\nBecause the layout step fails before clippy runs, neither clippy lane had\nexecuted on this branch at all. Both are now run and clean.\n\nClaude-Session: https://claude.ai/code/session_01Fu3PXYSu3gV9u9kV6CwH1G\n

M3gA-Mind3ed99ecb074e
diff --git a/src/openhuman/agent/harness/session/turn/core_session.rs b/src/openhuman/agent/harness/session/turn/core_session.rs
index f324a7af90..da6402057d 100644
--- a/src/openhuman/agent/harness/session/turn/core_session.rs
+++ b/src/openhuman/agent/harness/session/turn/core_session.rs
@@ -1,758 +1,10 @@
-impl Agent {
- /// Drive a full chat turn through the `tinyagents` harness (issue #4249).
- ///
- /// The frozen system+prior history is converted to provider messages, the
- /// user turn appended, and the loop run over the agent's resolved tools. The
- /// final reply + the user turn are recorded into `history`, the transcript
- /// is persisted, and `TurnCompleted` is emitted so the UI stops spinning.
- ///
- /// Full-fidelity with the legacy `run_turn_engine`: live tool-timeline /
- /// text-delta progress and the cost/token footer are mirrored from the
- /// harness event stream via `OpenhumanEventBridge` (tinyagents harness),
- /// `[IMAGE:…]`/`[FILE:…]` markers are expanded for the provider, and history
- /// is trimmed to the provider's context window.
- async fn run_turn_via_tinyagents_session(
- &mut self,
- user_message: &str,
- effective_model: &str,
- temperature: f64,
- max_iterations: usize,
- artifact_store: Option<
- crate::openhuman::agent::harness::tool_result_artifacts::ToolResultArtifactStore,
- >,
- suppress_tools: bool,
- ) -> Result<String> {
- let turn_started = std::time::Instant::now();
- // This turn's stamped user message is already the last entry in
- // `self.history` (pushed by `turn()` before the engine branch), so build
- // the provider messages straight from history — do NOT push the user
- // again. When a cached transcript prefix is present (a resumed session's
- // KV-cache warm-up), prepend it and clear it so the first request reuses
- // the cached prefix exactly once.
- let mut messages = self.tool_dispatcher.to_provider_messages(&self.history);
- if let Some(cached) = self.cached_transcript_messages.take() {
- // The cached prefix already carries the system prompt + prior
- // conversation, so drop the freshly-rendered leading system
- // message(s) and append only this turn's new (user) messages.
- let tail = messages
- .into_iter()
- .skip_while(|m| m.role == "system")
- .collect::<Vec<_>>();
- let mut combined = cached;
- combined.extend(tail);
- messages = combined;
- }
-
- // Multimodal prep (parity with the legacy engine): rehydrate image
- // placeholders for vision-capable providers, then expand `[IMAGE:…]` /
- // `[FILE:…]` markers into provider-ready content before dispatch. The
- // expanded copy is provider-only and never persisted to `history`.
- let multimodal = self
- .runtime_config
- .as_ref()
- .map(|c| c.multimodal.clone())
- .unwrap_or_default();
- let multimodal_files = self
- .runtime_config
- .as_ref()
- .map(|c| c.multimodal_files.clone())
- .unwrap_or_default();
- // Resolve the effective context window and build the turn's tiered crate
- // `ChatModel` set from the session source up front (issue #4249, Phase 3 /
- // Motion A) — the harness holds crate model types, and the vision read
- // below comes off the built models, not a raw provider.
- let context_window = self
- .turn_model_source
- .effective_context_window(effective_model)
- .await;
- let turn_models =
- self.turn_model_source
- .build(effective_model, temperature, context_window)?;
-
- // Honor custom/BYOK vision models too: they can set `model_vision` even
- // when the provider capability bit is false, and must still rehydrate
- // `[IMAGE:…]` placeholders (else image chat silently degrades to text).
- if (turn_models.supports_vision() || self.model_vision)
- && crate::openhuman::agent::multimodal::has_image_placeholders(&messages)
- {
- messages = crate::openhuman::agent::multimodal::rehydrate_image_placeholders(&messages);
- }
- let messages = crate::openhuman::agent::multimodal::prepare_messages_for_provider(
- &messages,
- &multimodal,
- &multimodal_files,
- )
- .await
- .map(|prepared| prepared.messages)
- .unwrap_or(messages);
-
- // Per-turn tool scope (#1725). A chat / small-talk turn runs with an
- // EMPTY tool set: the provider request carries no tool schema, so the
- // model cannot enter the tool loop and answers in a single call. The
- // agent's durable `self.tools` / `self.visible_tool_names` are left
- // untouched — the next un-overridden turn gets the full toolbelt back.
- let (turn_tools, turn_synthesized_tools, turn_visible_tool_names) =
- self.turn_tool_sets(suppress_tools);
-
- tracing::info!(
- model = %effective_model,
- max_iterations,
- tools = turn_tools.len() + turn_synthesized_tools.len(),
- suppress_tools,
- "[agent_loop] routing chat turn through the tinyagents harness"
- );
-
- // Dispatch through the chat turn graph (this folder's `graph.rs`): a thin
- // wrapper over the shared tinyagents seam that pins the chat path's fixed
- // arguments (no child scope, no early-exit tools, graceful cap pause,
- // per-turn output cap) and runs the context-window summarization step.
- // Context middlewares sourced from this session's ContextManager: the
- // per-tool-result byte cap + payload summarizer (after_tool) and
- // microcompact tool-body clearing (before_model). KV-cache-prefix drift
- // detection is owned by the crate `PromptCacheGuardMiddleware` (fed by
- // `PromptCacheSegmentMiddleware`); the warn-only `CacheAlignMiddleware`
- // was deleted in C3.
- let context_mw = crate::openhuman::agent::tinyagents::TurnContextMiddleware {
- tool_result_budget_bytes: self.context.tool_result_budget_bytes(),
- payload_summarizer: self.payload_summarizer.clone(),
- artifact_store,
- tokenjuice_compaction_enabled: self.context.compaction_enabled(),
- tokenjuice_compression: self.tokenjuice_compression,
- microcompact_keep_recent: self.context.microcompact_keep_recent(),
- // Honor the [context].enabled / autocompact_enabled opt-outs: when off,
- // the summarization middleware is not installed (no summarizer tokens,
- // no history rewrite).
- autocompact_enabled: self.context.autocompact_enabled(),
- // Progressive-disclosure handoff is a sub-agent (integrations_agent)
- // concern; the top-level chat turn never sets it.
- handoff: None,
- // Live transcript snapshotting is a sub-agent error-recovery concern
- // (#4466); the chat path persists its transcript post-run.
- transcript_snapshot: None,
- };
-
- // Gather any sub-agent spend delegated during this turn (synchronous
- // `spawn_subagent` runs inline on this task and records into the collector)
- // so the turn's usage meters + the `chat_done` per-child breakdown include
- // it — the collector scope the legacy engine installed.
- // Install the turn's sub-agent dispatch guard around the same future
- // (#5804). It records two facts the turn already produces but never
- // wrote down — that a graceful pause has been requested at the
- // model-call cap, and how long this turn's sub-agents actually take —
- // so `run_subagent` can refuse a dispatch that cannot finish inside the
- // remaining wall-clock budget instead of taking the whole turn down
- // with it. Boxed at the call site: `with_dispatch_guard` takes its
- // future by value, and the collector future wraps the entire turn
- // generator, so passing it unboxed would move hundreds of KiB through
- // this frame — the same hazard `with_turn_collector`'s own comment
- // documents, with the gdb measurements behind it.
- let turn_future = Box::pin(
- crate::openhuman::agent::harness::turn_subagent_usage::with_turn_collector(
- super::graph::run_chat_turn_graph(super::graph::ChatTurnGraph {
- turn_models,
- model: effective_model.to_string(),
- messages,
- tools: turn_tools,
- synthesized_tools: turn_synthesized_tools,
- visible_tool_names: turn_visible_tool_names,
- max_iterations,
- on_progress: self.on_progress.clone(),
- context_window,
- run_queue: self.run_queue.clone(),
- context_mw,
- // Enforce the builder-configured tool policy at the tool
- // boundary (the tinyagents path otherwise bypasses it).
- tool_policy: Some(crate::openhuman::agent::tinyagents::ToolPolicyEnforcement {
- policy: self.tool_policy.clone(),
- session: self.tool_policy_session.clone(),
- session_id: self.event_session_id.clone(),
- channel: self.event_channel().to_string(),
- agent_definition_id: self.agent_definition_id.clone(),
- }),
- // Section D: forward the session's per-profile workspace
- // descriptor (if any) so the top-level chat turn's acting
- // tools default their cwd to the profile's dedicated dir.
- workspace_descriptor: self.workspace_descriptor.clone(),
- // Scope direct Master-Agent calls under its declared
- // sandbox. `agent_definition_name` can carry a thread
- // suffix, so resolve with the stable definition id.
- sandbox_mode: crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::global()
- .and_then(|registry| registry.get(&self.agent_definition_id))
- .map(|definition| definition.sandbox_mode)
- .unwrap_or(crate::openhuman::agent::harness::definition::SandboxMode::None),
- }),
- ),
- );
- let (outcome, subagent_usage_entries) =
- crate::openhuman::agent::harness::turn_dispatch_guard::with_dispatch_guard(
- crate::openhuman::agent::tinyagents::agent_turn_wall_clock_ms()
- .map(std::time::Duration::from_millis),
- turn_future,
- )
- .await;
- let outcome = outcome?;
-
- // Record whether this turn paused at the tool-call cap (vs. finishing
- // naturally) BEFORE anything below can early-return, so a caller
- // inspecting `last_turn_hit_cap()` after `run_single` always reflects
- // this turn, never a stale value from a prior one.
- self.last_turn_hit_cap = outcome.hit_cap;
-
- // The stamped user turn is already in `self.history` (pushed by `turn()`),
- // so append only the structured messages this turn produced — assistant
- // tool calls + tool results + (for a clean finish) the final assistant —
- // preserving tool-call history fidelity for the UI, persisted transcript,
- // and the next turn's KV-cache prefix.
- self.history.extend(outcome.conversation.iter().cloned());
-
- // Token accounting for the turn (the cap checkpoint call below folds in
- // its own usage).
- // Seed from the turn outcome (the harness observed real usage incl. cached
- // tokens and an estimated cost) rather than zero, so a normal non-cap turn
- // persists real cost instead of $0. The cap-checkpoint branch below folds
- // in its extra call's usage on top.
- let mut input_tokens = outcome.input_tokens;
- let mut output_tokens = outcome.output_tokens;
- let mut cached_input_tokens = outcome.cached_input_tokens;
- let mut charged_amount_usd = outcome.charged_amount_usd;
-
- let reply = if outcome.hit_cap && outcome.wrap_up_injected && !outcome.text.trim().is_empty()
- {
- // The conclusion was produced INSIDE the loop (issue #6014):
- // `FinalCallWrapUpMiddleware` withdrew the tools on the last
- // permitted model call and appended the wrap-up instruction, so this
- // turn's own final response already is the capped turn's answer.
- // There is nothing left to ask for, and asking anyway would spend a
- // second call to re-summarise text the model has just written.
- //
- // No `history.push` either: unlike the out-of-band path below, this
- // response came from the loop, so it was already folded into
- // `self.history` by the `extend(outcome.conversation)` above. Pushing
- // it again would duplicate the assistant turn in the transcript and
- // in the next request's prefix.
- log::info!(
- "[agent_loop] turn capped at {} model call(s); the loop's final call produced the \
- conclusion ({} chars) — no out-of-band wrap-up needed",
- outcome.model_calls,
- outcome.text.chars().count()
- );
- outcome.text.clone()
- } else if outcome.hit_cap {
- // The loop paused at the tool-call cap. Ask the model for a resumable
- // checkpoint (tools disabled), falling back to a deterministic
- // done/next summary so the thread never ends on a dangling tool
- // cycle. Fold the extra call's usage into the turn accounting.
- //
- // Reached when the in-loop conclusion above did not happen or came
- // back empty: a run with the middleware uninstalled, a budget of one
- // model call, or a concluding call that answered with nothing. Kept
- // intact so no path loses the behaviour it had before #6014.
- // The concluding call answered with nothing, and the `extend` above
- // folded that empty assistant message into `self.history`. Anthropic
- // rejects empty content, so sending it would turn "the model said
- // nothing" into a failed turn (CodeRabbit on #6068).
- if self.history.last().is_some_and(is_empty_assistant_chat) {
- self.history.pop();
- }
- let base = self.tool_dispatcher.to_provider_messages(&self.history);
- let (summary, summary_usage) = self
- .summarize_turn_wrapup(
- &base,
- effective_model,
- outcome.model_calls as u32 + 1,
- super::super::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
- )
- .await;
- if let Some(u) = summary_usage {
- input_tokens += u.input_tokens;
- output_tokens += u.output_tokens;
- cached_input_tokens += u.cached_input_tokens;
- charged_amount_usd += u.charged_amount_usd;
- }
- let checkpoint = if summary.trim().is_empty() {
- super::super::turn_checkpoint::build_deterministic_checkpoint(
- &checkpoint_results_from_conversation(
- &outcome.conversation,
- &outcome.tool_outcomes,
- ),
- max_iterations,
- )
- } else {
- summary
- };
- self.history
- .push(ConversationMessage::Chat(ChatMessage::assistant(
- checkpoint.clone(),
- )));
- checkpoint
- } else if outcome.text.trim().is_empty() && outcome.tool_calls == 0 {
- // A completion with no text and no tool calls is never a valid final
- // answer — surface it as an error instead of wedging the thread on a
- // blank reply (bug-report-2026-05-26 A1, defect B).
- //
- // #4457 (defect A): the empty terminal assistant response was already
- // folded into `self.history` via `outcome.conversation` at the
- // `history.extend` above (an empty `Chat(assistant(""))`). The #4093
- // branch below pops that dangling blank row before re-prompting, but
- // this `tool_calls == 0` path returned the error with the empty row
- // still in history — so the *next* request carried an empty-content
- // assistant message and strict providers (Anthropic: "text content
- // blocks must be non-empty") 400 the whole thread, not just this turn.
- // Pop the trailing empty assistant row before returning so a retry
- // sends a clean transcript.
- if matches!(
- self.history.last(),
- Some(ConversationMessage::Chat(msg))
- if msg.role == "assistant" && msg.content.trim().is_empty()
- ) {
- log::debug!(
- "[agent_loop] EmptyProviderResponse at iteration {}: popping dangling empty assistant row before returning — #4457 defect A",
- outcome.model_calls
- );
- self.history.pop();
- }
- return Err(anyhow::Error::new(
- crate::openhuman::agent::error::AgentError::EmptyProviderResponse {
- iteration: outcome.model_calls,
- },
- ));
- } else if outcome.text.trim().is_empty() {
- // #4093: the loop ran tool calls (tool_calls > 0, so the branch
- // above did not fire) and then yielded a terminating response with
- // no final text — the turn did work but would otherwise end
- // silently, leaving the user with nothing. Enforce the
- // "must produce a final response" terminal step: re-prompt the
- // model (tools disabled) for a closing summary of what it did,
- // falling back to a deterministic summary of the tool calls so the
- // synthesized message is never itself empty. Fold the extra call's
- // usage into the turn accounting, exactly like the cap path above.
- let base = self.tool_dispatcher.to_provider_messages(&self.history);
- let (summary, summary_usage) = self
- .summarize_turn_wrapup(
- &base,
- effective_model,
- outcome.model_calls as u32 + 1,
- super::super::turn_checkpoint::FINAL_ANSWER_INSTRUCTION,
- )
- .await;
- if let Some(u) = summary_usage {
- input_tokens += u.input_tokens;
- output_tokens += u.output_tokens;
- cached_input_tokens += u.cached_input_tokens;
- charged_amount_usd += u.charged_amount_usd;
- }
- let final_answer = if summary.trim().is_empty() {
- super::super::turn_checkpoint::build_deterministic_final_summary(
- &tool_records_from_conversation(&outcome.conversation, &outcome.tool_outcomes),
- )
- } else {
- summary
- };
- log::info!(
- "[agent_loop] turn produced no final text after {} tool call(s); synthesized a closing summary ({} chars) — #4093",
- outcome.tool_calls,
- final_answer.chars().count()
- );
- // The empty terminal assistant response was already folded into
- // `self.history` via `outcome.conversation` above (an empty
- // `Chat(assistant(""))` — see `messages_to_conversation`). Drop that
- // blank turn before appending the synthesized answer so the
- // transcript and the next prompt don't carry a dangling empty
- // assistant message immediately before the real reply (Codex review).
- if matches!(
- self.history.last(),
- Some(ConversationMessage::Chat(msg))
- if msg.role == "assistant" && msg.content.trim().is_empty()
- ) {
- self.history.pop();
- }
- self.history
- .push(ConversationMessage::Chat(ChatMessage::assistant(
- final_answer.clone(),
- )));
- final_answer
- } else if outcome.early_exit_tool.is_some() {
- // Paused on `ask_user_clarification`. The run stopped right after the
- // tool round, so `outcome.conversation` ends on a tool result and
- // carries no final assistant turn — `outcome.text` (the question) is
- // standing in for one. Push it, or the reply the user is looking at
- // would be missing from the next request's prefix and the model would
- // have to infer that it asked anything from its own tool result.
- // The sub-agent path makes the same substitution when it persists a
- // paused child's transcript (`subagent_runner/ops/graph_part_01.rs`).
- self.history
- .push(ConversationMessage::Chat(ChatMessage::assistant(
- outcome.text.clone(),
- )));
- outcome.text.clone()
- } else {
- outcome.text.clone()
- };
-
- // Enforce the required structured-output contract (issue #4117) on the
- // accepted reply — for ALL of the branches above (normal finish, cap
- // checkpoint, #4093 synthesized close), since each delivers a reply
- // downstream parsing depends on. When this agent must emit a JSON block
- // every turn and the reply omitted it, validate-and-repair before the
- // turn is accepted, reconciling with streaming (append-only when a live
- // stream is attached, replace otherwise — see `enforce_required_output`).
- // The trailing assistant message is rewritten to match, and the repair
- // call's usage is folded into the turn accounting. `required_output`
- // defaults to `None`, so existing agents are entirely unaffected.
- // Converted to the crate contract at the read site: the enforcement
- // helpers below are part of the runtime slated to move into TinyAgents
- // and so speak the crate type, while the session still holds the host's
- // `AgentConfig`. See `tinyagents::config::required_output_from`.
- let reply = if let Some(contract) = self
- .config
- .required_output
- .as_ref()
- .map(crate::openhuman::agent::tinyagents::config::required_output_from)
- {
- match self
- .enforce_required_output(
- &reply,
- &contract,
- effective_model,
- outcome.model_calls as u32 + 1,
- )
- .await
- {
- Some((repaired, repair_usage)) => {
- if let Some(u) = repair_usage {
- input_tokens += u.input_tokens;
- output_tokens += u.output_tokens;
- cached_input_tokens += u.cached_input_tokens;
- charged_amount_usd += u.charged_amount_usd;
- }
- replace_last_assistant_reply(&mut self.history, &repaired);
- repaired
- }
- None => reply,
- }
- } else {
- reply
- };
- self.trim_history();
-
- // Fold this turn's sub-agent spend into the cumulative meters and capture
- // the holistic per-turn usage the web channel surfaces on `chat_done` (it
- // calls `take_last_turn_usage_totals()` right after the turn). Without this
- // the event reported `usage: None` despite the transcript being persisted
- // with real numbers.
- for entry in &subagent_usage_entries {
- input_tokens = input_tokens.saturating_add(entry.usage.input_tokens);
- output_tokens = output_tokens.saturating_add(entry.usage.output_tokens);
- cached_input_tokens =
- cached_input_tokens.saturating_add(entry.usage.cached_input_tokens);
- charged_amount_usd += entry.usage.charged_amount_usd;
- }
- self.last_turn_usage_totals = Some(
- crate::openhuman::agent::harness::turn_subagent_usage::LastTurnUsage {
- input_tokens,
- output_tokens,
- cached_input_tokens,
- cost_usd: charged_amount_usd,
- context_window: context_window.unwrap_or(0),
- subagents: subagent_usage_entries,
- },
- );
-
- let mut persisted = self.tool_dispatcher.to_provider_messages(&self.history);
- // Re-attach per-call failure outcomes (dropped when the engine folded
- // each tool result into a `role:"tool"` message) so the derived
- // transcript view renders failed tools as errors, not successes.
- stamp_tool_failures(&mut persisted, &outcome.tool_outcomes);
- // Carry the turn's provider (event channel) + effective model and usage
- // into the persisted transcript meta. Passing `None` here dropped
- // `provider`/`model` from every transcript (they are `TranscriptMeta`
- // fields sourced from the turn usage) — parity with the legacy engine,
- // which handed `self.last_turn_usage.as_ref()` to this call.
- let turn_usage = crate::openhuman::agent::harness::session::transcript::TurnUsage {
- provider: self.event_channel().to_string(),
- // The model that actually ran this turn (a per-turn override can
- // diverge from `self.model_name`); attribute usage to it.
- model: effective_model.to_string(),
- usage: crate::openhuman::agent::harness::session::transcript::MessageUsage {
- input: input_tokens,
- output: output_tokens,
- cached_input: cached_input_tokens,
- context_window: context_window.unwrap_or(0),
- cost_usd: charged_amount_usd,
- },
- ts: chrono::Utc::now().to_rfc3339(),
- reasoning_content: None,
- tool_calls: Vec::new(),
- iteration: outcome.model_calls as u32,
- };
- self.persist_session_transcript(
- &persisted,
- input_tokens,
- output_tokens,
- cached_input_tokens,
- charged_amount_usd,
- Some(&turn_usage),
- );
-
- // Charge this turn's usage against the thread's active goal (parity with
- // the legacy engine) so budgeted goals progress to `budget_limited` and
- // continuation scheduling reads a live budget. Self-guarding + best-effort
- // — a no-op when there is no active goal for the ambient thread.
- crate::openhuman::threads::goals::runtime::account_turn_against_goal(
- &self.workspace_dir,
- input_tokens,
- output_tokens,
- turn_started.elapsed().as_secs(),
- )
- .await;
-
- // Content (prompt + reply) rides its own event so a tracing consumer can
- // attach it to the turn span. Gated on the opt-in
- // `observability.agent_tracing.capture_content` flag (#4454): with the
- // default off, we don't even emit the content event, so prompt/reply text
- // never reaches the span store or any exporter. The collector applies the
- // same storage-level gate as defense in depth.
- let capture_content = self
- .runtime_config
- .as_ref()
- .map(|c| c.observability.agent_tracing.capture_content)
- .unwrap_or(false);
- if capture_content {
- log::debug!(
- target: "agent-tracing",
- "[agent-tracing] emitting TurnContent (capture_content=true)"
- );
- self.emit_progress(AgentProgress::TurnContent {
- input: Some(user_message.to_string()),
- output: Some(reply.clone()),
- })
- .await;
- } else {
- log::debug!(
- target: "agent-tracing",
- "[agent-tracing] skipping TurnContent emit (capture_content=false)"
- );
- }
-
- self.emit_progress(AgentProgress::TurnCompleted {
- iterations: outcome.model_calls as u32,
- })
- .await;
-
- if self.auto_save {
- let summary = truncate_with_ellipsis(&reply, 100);
- let autosave_key = format!("assistant_resp:{}", uuid::Uuid::new_v4());
- let _ = self
- .memory
- .store(
- crate::openhuman::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,
- &autosave_key,
- &summary,
- MemoryCategory::Daily,
- None,
- )
- .await;
- }
-
- // Fire post-turn hooks (non-blocking), matching the legacy engine.
- if !self.post_turn_hooks.is_empty() {
- let ctx = TurnContext {
- user_message: user_message.to_string(),
- assistant_response: reply.clone(),
- tool_calls: tool_records_from_conversation(
- &outcome.conversation,
- &outcome.tool_outcomes,
- ),
- turn_duration_ms: turn_started.elapsed().as_millis() as u64,
- session_id: Some(self.event_session_id.clone())
- .filter(|session_id| !session_id.trim().is_empty()),
- agent_id: Some(self.agent_definition_id.clone())
- .filter(|agent_id| !agent_id.trim().is_empty()),
- entrypoint: Some(self.event_channel.clone())
- .filter(|entrypoint| !entrypoint.trim().is_empty()),
- iteration_count: outcome.model_calls,
- };
- hooks::fire_hooks(&self.post_turn_hooks, ctx);
- }
-
- Ok(reply)
- }
-
- pub(super) async fn inject_agent_experience_context(
- &self,
- user_message: &str,
- enriched: String,
- ) -> String {
- const MAX_EXPERIENCE_HITS: usize = 3;
- const MAX_EXPERIENCE_BLOCK_BYTES: usize = 2048;
-
- if !self.learning_enabled {
- return enriched;
- }
-
- let tools = self
- .visible_tool_specs
- .iter()
- .map(|spec| spec.name.clone())
- .collect();
- let mut stores = vec![AgentExperienceStore::new(self.memory.clone())];
- if let Some(shared_memory) = &self.shared_experience_memory {
- stores.push(AgentExperienceStore::new(shared_memory.clone()));
- }
- let query = ExperienceQuery {
- query: user_message.to_string(),
- tools,
- tags: Vec::new(),
- agent_id: Some(self.agent_definition_id.clone()).filter(|id| !id.trim().is_empty()),
- entrypoint: Some(self.event_channel.clone())
- .filter(|entrypoint| !entrypoint.trim().is_empty()),
- // 1c — partition recall by the active profile: this turn sees records
- // stamped with its profile plus unstamped legacy records, and never a
- // sibling profile's. `None` (profile-less) recalls the whole pool.
- profile_id: self.active_profile_id.clone(),
- max_hits: MAX_EXPERIENCE_HITS,
- };
-
- match retrieve_across_stores(&stores, query).await {
- Ok(hits) => {
- let matched_hits: Vec<_> = hits
- .into_iter()
- .filter(|hit| !hit.match_reasons.is_empty())
- .collect();
- let block = render_experience_hits(&matched_hits, MAX_EXPERIENCE_BLOCK_BYTES);
- if block.is_empty() {
- return enriched;
- }
- log::debug!(
- "[agent-experience] injected {} experience hit(s) bytes={}",
- matched_hits.len(),
- block.len()
- );
- prepend_experience_block(&enriched, &block)
- }
- Err(err) => {
- log::warn!("[agent-experience] retrieval failed (non-fatal): {err}");
- enriched
- }
- }
- }
-
- async fn inject_triggered_memory_agent_context(
- &self,
- user_message: &str,
- enriched: String,
- parent_context: &ParentExecutionContext,
- force_skip: bool,
- ) -> (String, bool) {
- const MEMORY_AGENT_ID: &str = "agent_memory";
- const MAX_MEMORY_AGENT_BLOCK_CHARS: usize = 8000;
-
- if force_skip {
- // Per-turn override (#1725): a chat / small-talk turn skips the
- // pre-turn memory-agent retrieval even when this agent's policy is
- // `Always`, so a greeting never pulls a prior task's remembered
- // context into an unrelated reply.
- log::debug!(
- "[agent_memory:trigger] skipped agent_id={} (per-turn suppress_memory_agent override)",
- self.agent_definition_id
- );
- return (enriched, false);
- }
-
- if self.trigger_memory_agent != TriggerMemoryAgent::Always {
- log::debug!(
- "[agent_memory:trigger] skipped agent_id={} policy={:?}",
- self.agent_definition_id,
- self.trigger_memory_agent
- );
- return (enriched, false);
- }
-
- if self.agent_definition_id == MEMORY_AGENT_ID {
- log::debug!("[agent_memory:trigger] skipped recursive memory agent invocation");
- return (enriched, false);
- }
-
- let Some(registry) = harness::AgentDefinitionRegistry::global() else {
- log::warn!(
- "[agent_memory:trigger] AgentDefinitionRegistry unavailable; continuing without memory agent context"
- );
- return (enriched, false);
- };
- let Some(definition) = registry.get(MEMORY_AGENT_ID).cloned() else {
- log::warn!(
- "[agent_memory:trigger] `{MEMORY_AGENT_ID}` definition unavailable; continuing without memory agent context"
- );
- return (enriched, false);
- };
-
- let task_id = format!("mem-trigger-{}", uuid::Uuid::new_v4());
- let prompt = format!(
- "Search the user's memory tree and return only context relevant to the next agent turn.\n\nUser prompt:\n{user_message}"
- );
- let options = harness::SubagentRunOptions {
- task_id: Some(task_id.clone()),
- model_override: Some(parent_context.model_name.clone()),
- ..Default::default()
- };
-
- log::debug!(
- "[agent_memory:trigger] starting agent_id={} task_id={} user_message_chars={}",
- self.agent_definition_id,
- task_id,
- user_message.chars().count()
- );
-
- let started = std::time::Instant::now();
- let result = harness::with_parent_context(parent_context.clone(), async move {
- harness::run_subagent(&definition, &prompt, options).await
- })
- .await;
-
- match result {
- Ok(outcome) => {
- log::info!(
- "[agent_memory:trigger] completed agent_id={} task_id={} iterations={} elapsed={:?} status={:?} output_chars={}",
- self.agent_definition_id,
- task_id,
- outcome.iterations,
- started.elapsed(),
- outcome.status,
- outcome.output.chars().count()
- );
- let mut output =
- truncate_with_ellipsis(&outcome.output, MAX_MEMORY_AGENT_BLOCK_CHARS);
- if let harness::subagent_runner::SubagentRunStatus::AwaitingUser {
- question, ..
- } = &outcome.status
- {
- let question = question.trim();
- if !question.is_empty() {
- output.push_str("\n\nMemory agent needs clarification: ");
- output.push_str(question);
- }
- }
- output = truncate_with_ellipsis(&output, MAX_MEMORY_AGENT_BLOCK_CHARS);
- if output.trim().is_empty() {
- return (enriched, false);
- }
- (
- format!(
- "## Memory agent context\n\n{}\n\n---\n\n{}",
- output.trim(),
- enriched
- ),
- true,
- )
- }
- Err(err) => {
- log::warn!(
- "[agent_memory:trigger] failed agent_id={} task_id={}: {err:#}",
- self.agent_definition_id,
- task_id
- );
- (enriched, false)
- }
- }
- }
-}
+// `Agent`'s tinyagents-backed chat turn, split per the repo's
+// `_part_NN.rs` convention because the combined body exceeds the 750-line
+// ceiling enforced by `scripts/ci/check-openhuman-rust-layout.mjs`.
+//
+// Part 01 is the turn driver (`run_turn_via_tinyagents_session`); part 02 is
+// the agent-experience / triggered-memory context injection it calls. Both
+// are `impl Agent` blocks spliced into `core.rs`, so this file is text, not
+// a module — the fragments' own line numbers are the ones to cite.
+include!("core_session_part_01.rs");
+include!("core_session_part_02.rs");
diff --git a/src/openhuman/agent/harness/session/turn/core_session_part_01.rs b/src/openhuman/agent/harness/session/turn/core_session_part_01.rs
new file mode 100644
index 0000000000..5bbba62f1f
--- /dev/null
+++ b/src/openhuman/agent/harness/session/turn/core_session_part_01.rs
@@ -0,0 +1,580 @@
+impl Agent {
+ /// Drive a full chat turn through the `tinyagents` harness (issue #4249).
+ ///
+ /// The frozen system+prior history is converted to provider messages, the
+ /// user turn appended, and the loop run over the agent's resolved tools. The
+ /// final reply + the user turn are recorded into `history`, the transcript
+ /// is persisted, and `TurnCompleted` is emitted so the UI stops spinning.
+ ///
+ /// Full-fidelity with the legacy `run_turn_engine`: live tool-timeline /
+ /// text-delta progress and the cost/token footer are mirrored from the
+ /// harness event stream via `OpenhumanEventBridge` (tinyagents harness),
+ /// `[IMAGE:…]`/`[FILE:…]` markers are expanded for the provider, and history
+ /// is trimmed to the provider's context window.
+ async fn run_turn_via_tinyagents_session(
+ &mut self,
+ user_message: &str,
+ effective_model: &str,
+ temperature: f64,
+ max_iterations: usize,
+ artifact_store: Option<
+ crate::openhuman::agent::harness::tool_result_artifacts::ToolResultArtifactStore,
+ >,
+ suppress_tools: bool,
+ ) -> Result<String> {
+ let turn_started = std::time::Instant::now();
+ // This turn's stamped user message is already the last entry in
+ // `self.history` (pushed by `turn()` before the engine branch), so build
+ // the provider messages straight from history — do NOT push the user
+ // again. When a cached transcript prefix is present (a resumed session's
+ // KV-cache warm-up), prepend it and clear it so the first request reuses
+ // the cached prefix exactly once.
+ let mut messages = self.tool_dispatcher.to_provider_messages(&self.history);
+ if let Some(cached) = self.cached_transcript_messages.take() {
+ // The cached prefix already carries the system prompt + prior
+ // conversation, so drop the freshly-rendered leading system
+ // message(s) and append only this turn's new (user) messages.
+ let tail = messages
+ .into_iter()
+ .skip_while(|m| m.role == "system")
+ .collect::<Vec<_>>();
+ let mut combined = cached;
+ combined.extend(tail);
+ messages = combined;
+ }
+
+ // Multimodal prep (parity with the legacy engine): rehydrate image
+ // placeholders for vision-capable providers, then expand `[IMAGE:…]` /
+ // `[FILE:…]` markers into provider-ready content before dispatch. The
+ // expanded copy is provider-only and never persisted to `history`.
+ let multimodal = self
+ .runtime_config
+ .as_ref()
+ .map(|c| c.multimodal.clone())
+ .unwrap_or_default();
+ let multimodal_files = self
+ .runtime_config
+ .as_ref()
+ .map(|c| c.multimodal_files.clone())
+ .unwrap_or_default();
+ // Resolve the effective context window and build the turn's tiered crate
+ // `ChatModel` set from the session source up front (issue #4249, Phase 3 /
+ // Motion A) — the harness holds crate model types, and the vision read
+ // below comes off the built models, not a raw provider.
+ let context_window = self
+ .turn_model_source
+ .effective_context_window(effective_model)
+ .await;
+ let turn_models =
+ self.turn_model_source
+ .build(effective_model, temperature, context_window)?;
+
+ // Honor custom/BYOK vision models too: they can set `model_vision` even
+ // when the provider capability bit is false, and must still rehydrate
+ // `[IMAGE:…]` placeholders (else image chat silently degrades to text).
+ if (turn_models.supports_vision() || self.model_vision)
+ && crate::openhuman::agent::multimodal::has_image_placeholders(&messages)
+ {
+ messages = crate::openhuman::agent::multimodal::rehydrate_image_placeholders(&messages);
+ }
+ let messages = crate::openhuman::agent::multimodal::prepare_messages_for_provider(
+ &messages,
+ &multimodal,
+ &multimodal_files,
+ )
+ .await
+ .map(|prepared| prepared.messages)
+ .unwrap_or(messages);
+
+ // Per-turn tool scope (#1725). A chat / small-talk turn runs with an
+ // EMPTY tool set: the provider request carries no tool schema, so the
+ // model cannot enter the tool loop and answers in a single call. The
+ // agent's durable `self.tools` / `self.visible_tool_names` are left
+ // untouched — the next un-overridden turn gets the full toolbelt back.
+ let (turn_tools, turn_synthesized_tools, turn_visible_tool_names) =
+ self.turn_tool_sets(suppress_tools);
+
+ tracing::info!(
+ model = %effective_model,
+ max_iterations,
+ tools = turn_tools.len() + turn_synthesized_tools.len(),
+ suppress_tools,
+ "[agent_loop] routing chat turn through the tinyagents harness"
+ );
+
+ // Dispatch through the chat turn graph (this folder's `graph.rs`): a thin
+ // wrapper over the shared tinyagents seam that pins the chat path's fixed
+ // arguments (no child scope, no early-exit tools, graceful cap pause,
+ // per-turn output cap) and runs the context-window summarization step.
+ // Context middlewares sourced from this session's ContextManager: the
+ // per-tool-result byte cap + payload summarizer (after_tool) and
+ // microcompact tool-body clearing (before_model). KV-cache-prefix drift
+ // detection is owned by the crate `PromptCacheGuardMiddleware` (fed by
+ // `PromptCacheSegmentMiddleware`); the warn-only `CacheAlignMiddleware`
+ // was deleted in C3.
+ let context_mw = crate::openhuman::agent::tinyagents::TurnContextMiddleware {
+ tool_result_budget_bytes: self.context.tool_result_budget_bytes(),
+ payload_summarizer: self.payload_summarizer.clone(),
+ artifact_store,
+ tokenjuice_compaction_enabled: self.context.compaction_enabled(),
+ tokenjuice_compression: self.tokenjuice_compression,
+ microcompact_keep_recent: self.context.microcompact_keep_recent(),
+ // Honor the [context].enabled / autocompact_enabled opt-outs: when off,
+ // the summarization middleware is not installed (no summarizer tokens,
+ // no history rewrite).
+ autocompact_enabled: self.context.autocompact_enabled(),
+ // Progressive-disclosure handoff is a sub-agent (integrations_agent)
+ // concern; the top-level chat turn never sets it.
+ handoff: None,
+ // Live transcript snapshotting is a sub-agent error-recovery concern
+ // (#4466); the chat path persists its transcript post-run.
+ transcript_snapshot: None,
+ };
+
+ // Gather any sub-agent spend delegated during this turn (synchronous
+ // `spawn_subagent` runs inline on this task and records into the collector)
+ // so the turn's usage meters + the `chat_done` per-child breakdown include
+ // it — the collector scope the legacy engine installed.
+ // Install the turn's sub-agent dispatch guard around the same future
+ // (#5804). It records two facts the turn already produces but never
+ // wrote down — that a graceful pause has been requested at the
+ // model-call cap, and how long this turn's sub-agents actually take —
+ // so `run_subagent` can refuse a dispatch that cannot finish inside the
+ // remaining wall-clock budget instead of taking the whole turn down
+ // with it. Boxed at the call site: `with_dispatch_guard` takes its
+ // future by value, and the collector future wraps the entire turn
+ // generator, so passing it unboxed would move hundreds of KiB through
+ // this frame — the same hazard `with_turn_collector`'s own comment
+ // documents, with the gdb measurements behind it.
+ let turn_future = Box::pin(
+ crate::openhuman::agent::harness::turn_subagent_usage::with_turn_collector(
+ super::graph::run_chat_turn_graph(super::graph::ChatTurnGraph {
+ turn_models,
+ model: effective_model.to_string(),
+ messages,
+ tools: turn_tools,
+ synthesized_tools: turn_synthesized_tools,
+ visible_tool_names: turn_visible_tool_names,
+ max_iterations,
+ on_progress: self.on_progress.clone(),
+ context_window,
+ run_queue: self.run_queue.clone(),
+ context_mw,
+ // Enforce the builder-configured tool policy at the tool
+ // boundary (the tinyagents path otherwise bypasses it).
+ tool_policy: Some(crate::openhuman::agent::tinyagents::ToolPolicyEnforcement {
+ policy: self.tool_policy.clone(),
+ session: self.tool_policy_session.clone(),
+ session_id: self.event_session_id.clone(),
+ channel: self.event_channel().to_string(),
+ agent_definition_id: self.agent_definition_id.clone(),
+ }),
+ // Section D: forward the session's per-profile workspace
+ // descriptor (if any) so the top-level chat turn's acting
+ // tools default their cwd to the profile's dedicated dir.
+ workspace_descriptor: self.workspace_descriptor.clone(),
+ // Scope direct Master-Agent calls under its declared
+ // sandbox. `agent_definition_name` can carry a thread
+ // suffix, so resolve with the stable definition id.
+ sandbox_mode: crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::global()
+ .and_then(|registry| registry.get(&self.agent_definition_id))
+ .map(|definition| definition.sandbox_mode)
+ .unwrap_or(crate::openhuman::agent::harness::definition::SandboxMode::None),
+ }),
+ ),
+ );
+ let (outcome, subagent_usage_entries) =
+ crate::openhuman::agent::harness::turn_dispatch_guard::with_dispatch_guard(
+ crate::openhuman::agent::tinyagents::agent_turn_wall_clock_ms()
+ .map(std::time::Duration::from_millis),
+ turn_future,
+ )
+ .await;
+ let outcome = outcome?;
+
+ // Record whether this turn paused at the tool-call cap (vs. finishing
+ // naturally) BEFORE anything below can early-return, so a caller
+ // inspecting `last_turn_hit_cap()` after `run_single` always reflects
+ // this turn, never a stale value from a prior one.
+ self.last_turn_hit_cap = outcome.hit_cap;
+
+ // The stamped user turn is already in `self.history` (pushed by `turn()`),
+ // so append only the structured messages this turn produced — assistant
+ // tool calls + tool results + (for a clean finish) the final assistant —
+ // preserving tool-call history fidelity for the UI, persisted transcript,
+ // and the next turn's KV-cache prefix.
+ self.history.extend(outcome.conversation.iter().cloned());
+
+ // Token accounting for the turn (the cap checkpoint call below folds in
+ // its own usage).
+ // Seed from the turn outcome (the harness observed real usage incl. cached
+ // tokens and an estimated cost) rather than zero, so a normal non-cap turn
+ // persists real cost instead of $0. The cap-checkpoint branch below folds
+ // in its extra call's usage on top.
+ let mut input_tokens = outcome.input_tokens;
+ let mut output_tokens = outcome.output_tokens;
+ let mut cached_input_tokens = outcome.cached_input_tokens;
+ let mut charged_amount_usd = outcome.charged_amount_usd;
+
+ let reply = if outcome.hit_cap && outcome.wrap_up_injected && !outcome.text.trim().is_empty()
+ {
+ // The conclusion was produced INSIDE the loop (issue #6014):
+ // `FinalCallWrapUpMiddleware` withdrew the tools on the last
+ // permitted model call and appended the wrap-up instruction, so this
+ // turn's own final response already is the capped turn's answer.
+ // There is nothing left to ask for, and asking anyway would spend a
+ // second call to re-summarise text the model has just written.
+ //
+ // No `history.push` either: unlike the out-of-band path below, this
+ // response came from the loop, so it was already folded into
+ // `self.history` by the `extend(outcome.conversation)` above. Pushing
+ // it again would duplicate the assistant turn in the transcript and
+ // in the next request's prefix.
+ log::info!(
+ "[agent_loop] turn capped at {} model call(s); the loop's final call produced the \
+ conclusion ({} chars) — no out-of-band wrap-up needed",
+ outcome.model_calls,
+ outcome.text.chars().count()
+ );
+ outcome.text.clone()
+ } else if outcome.hit_cap {
+ // The loop paused at the tool-call cap. Ask the model for a resumable
+ // checkpoint (tools disabled), falling back to a deterministic
+ // done/next summary so the thread never ends on a dangling tool
+ // cycle. Fold the extra call's usage into the turn accounting.
+ //
+ // Reached when the in-loop conclusion above did not happen or came
+ // back empty: a run with the middleware uninstalled, a budget of one
+ // model call, or a concluding call that answered with nothing. Kept
+ // intact so no path loses the behaviour it had before #6014.
+ // The concluding call answered with nothing, and the `extend` above
+ // folded that empty assistant message into `self.history`. Anthropic
+ // rejects empty content, so sending it would turn "the model said
+ // nothing" into a failed turn (CodeRabbit on #6068).
+ if self.history.last().is_some_and(is_empty_assistant_chat) {
+ self.history.pop();
+ }
+ let base = self.tool_dispatcher.to_provider_messages(&self.history);
+ let (summary, summary_usage) = self
+ .summarize_turn_wrapup(
+ &base,
+ effective_model,
+ outcome.model_calls as u32 + 1,
+ super::super::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
+ )
+ .await;
+ if let Some(u) = summary_usage {
+ input_tokens += u.input_tokens;
+ output_tokens += u.output_tokens;
+ cached_input_tokens += u.cached_input_tokens;
+ charged_amount_usd += u.charged_amount_usd;
+ }
+ let checkpoint = if summary.trim().is_empty() {
+ super::super::turn_checkpoint::build_deterministic_checkpoint(
+ &checkpoint_results_from_conversation(
+ &outcome.conversation,
+ &outcome.tool_outcomes,
+ ),
+ max_iterations,
+ )
+ } else {
+ summary
+ };
+ self.history
+ .push(ConversationMessage::Chat(ChatMessage::assistant(
+ checkpoint.clone(),
+ )));
+ checkpoint
+ } else if outcome.text.trim().is_empty() && outcome.tool_calls == 0 {
+ // A completion with no text and no tool calls is never a valid final
+ // answer — surface it as an error instead of wedging the thread on a
+ // blank reply (bug-report-2026-05-26 A1, defect B).
+ //
+ // #4457 (defect A): the empty terminal assistant response was already
+ // folded into `self.history` via `outcome.conversation` at the
+ // `history.extend` above (an empty `Chat(assistant(""))`). The #4093
+ // branch below pops that dangling blank row before re-prompting, but
+ // this `tool_calls == 0` path returned the error with the empty row
+ // still in history — so the *next* request carried an empty-content
+ // assistant message and strict providers (Anthropic: "text content
+ // blocks must be non-empty") 400 the whole thread, not just this turn.
+ // Pop the trailing empty assistant row before returning so a retry
+ // sends a clean transcript.
+ if matches!(
+ self.history.last(),
+ Some(ConversationMessage::Chat(msg))
+ if msg.role == "assistant" && msg.content.trim().is_empty()
+ ) {
+ log::debug!(
+ "[agent_loop] EmptyProviderResponse at iteration {}: popping dangling empty assistant row before returning — #4457 defect A",
+ outcome.model_calls
+ );
+ self.history.pop();
+ }
+ return Err(anyhow::Error::new(
+ crate::openhuman::agent::error::AgentError::EmptyProviderResponse {
+ iteration: outcome.model_calls,
+ },
+ ));
+ } else if outcome.text.trim().is_empty() {
+ // #4093: the loop ran tool calls (tool_calls > 0, so the branch
+ // above did not fire) and then yielded a terminating response with
+ // no final text — the turn did work but would otherwise end
+ // silently, leaving the user with nothing. Enforce the
+ // "must produce a final response" terminal step: re-prompt the
+ // model (tools disabled) for a closing summary of what it did,
+ // falling back to a deterministic summary of the tool calls so the
+ // synthesized message is never itself empty. Fold the extra call's
+ // usage into the turn accounting, exactly like the cap path above.
+ let base = self.tool_dispatcher.to_provider_messages(&self.history);
+ let (summary, summary_usage) = self
+ .summarize_turn_wrapup(
+ &base,
+ effective_model,
+ outcome.model_calls as u32 + 1,
+ super::super::turn_checkpoint::FINAL_ANSWER_INSTRUCTION,
+ )
+ .await;
+ if let Some(u) = summary_usage {
+ input_tokens += u.input_tokens;
+ output_tokens += u.output_tokens;
+ cached_input_tokens += u.cached_input_tokens;
+ charged_amount_usd += u.charged_amount_usd;
+ }
+ let final_answer = if summary.trim().is_empty() {
+ super::super::turn_checkpoint::build_deterministic_final_summary(
+ &tool_records_from_conversation(&outcome.conversation, &outcome.tool_outcomes),
+ )
+ } else {
+ summary
+ };
+ log::info!(
+ "[agent_loop] turn produced no final text after {} tool call(s); synthesized a closing summary ({} chars) — #4093",
+ outcome.tool_calls,
+ final_answer.chars().count()
+ );
+ // The empty terminal assistant response was already folded into
+ // `self.history` via `outcome.conversation` above (an empty
+ // `Chat(assistant(""))` — see `messages_to_conversation`). Drop that
+ // blank turn before appending the synthesized answer so the
+ // transcript and the next prompt don't carry a dangling empty
+ // assistant message immediately before the real reply (Codex review).
+ if matches!(
+ self.history.last(),
+ Some(ConversationMessage::Chat(msg))
+ if msg.role == "assistant" && msg.content.trim().is_empty()
+ ) {
+ self.history.pop();
+ }
+ self.history
+ .push(ConversationMessage::Chat(ChatMessage::assistant(
+ final_answer.clone(),
+ )));
+ final_answer
+ } else if outcome.early_exit_tool.is_some() {
+ // Paused on `ask_user_clarification`. The run stopped right after the
+ // tool round, so `outcome.conversation` ends on a tool result and
+ // carries no final assistant turn — `outcome.text` (the question) is
+ // standing in for one. Push it, or the reply the user is looking at
+ // would be missing from the next request's prefix and the model would
+ // have to infer that it asked anything from its own tool result.
+ // The sub-agent path makes the same substitution when it persists a
+ // paused child's transcript (`subagent_runner/ops/graph_part_01.rs`).
+ self.history
+ .push(ConversationMessage::Chat(ChatMessage::assistant(
+ outcome.text.clone(),
+ )));
+ outcome.text.clone()
+ } else {
+ outcome.text.clone()
+ };
+
+ // Enforce the required structured-output contract (issue #4117) on the
+ // accepted reply — for ALL of the branches above (normal finish, cap
+ // checkpoint, #4093 synthesized close), since each delivers a reply
+ // downstream parsing depends on. When this agent must emit a JSON block
+ // every turn and the reply omitted it, validate-and-repair before the
+ // turn is accepted, reconciling with streaming (append-only when a live
+ // stream is attached, replace otherwise — see `enforce_required_output`).
+ // The trailing assistant message is rewritten to match, and the repair
+ // call's usage is folded into the turn accounting. `required_output`
+ // defaults to `None`, so existing agents are entirely unaffected.
+ // Converted to the crate contract at the read site: the enforcement
+ // helpers below are part of the runtime slated to move into TinyAgents
+ // and so speak the crate type, while the session still holds the host's
+ // `AgentConfig`. See `tinyagents::config::required_output_from`.
+ let reply = if let Some(contract) = self
+ .config
+ .required_output
+ .as_ref()
+ .map(crate::openhuman::agent::tinyagents::config::required_output_from)
+ {
+ match self
+ .enforce_required_output(
+ &reply,
+ &contract,
+ effective_model,
+ outcome.model_calls as u32 + 1,
+ )
+ .await
+ {
+ Some((repaired, repair_usage)) => {
+ if let Some(u) = repair_usage {
+ input_tokens += u.input_tokens;
+ output_tokens += u.output_tokens;
+ cached_input_tokens += u.cached_input_tokens;
+ charged_amount_usd += u.charged_amount_usd;
+ }
+ replace_last_assistant_reply(&mut self.history, &repaired);
+ repaired
+ }
+ None => reply,
+ }
+ } else {
+ reply
+ };
+ self.trim_history();
+
+ // Fold this turn's sub-agent spend into the cumulative meters and capture
+ // the holistic per-turn usage the web channel surfaces on `chat_done` (it
+ // calls `take_last_turn_usage_totals()` right after the turn). Without this
+ // the event reported `usage: None` despite the transcript being persisted
+ // with real numbers.
+ for entry in &subagent_usage_entries {
+ input_tokens = input_tokens.saturating_add(entry.usage.input_tokens);
+ output_tokens = output_tokens.saturating_add(entry.usage.output_tokens);
+ cached_input_tokens =
+ cached_input_tokens.saturating_add(entry.usage.cached_input_tokens);
+ charged_amount_usd += entry.usage.charged_amount_usd;
+ }
+ self.last_turn_usage_totals = Some(
+ crate::openhuman::agent::harness::turn_subagent_usage::LastTurnUsage {
+ input_tokens,
+ output_tokens,
+ cached_input_tokens,
+ cost_usd: charged_amount_usd,
+ context_window: context_window.unwrap_or(0),
+ subagents: subagent_usage_entries,
+ },
+ );
+
+ let mut persisted = self.tool_dispatcher.to_provider_messages(&self.history);
+ // Re-attach per-call failure outcomes (dropped when the engine folded
+ // each tool result into a `role:"tool"` message) so the derived
+ // transcript view renders failed tools as errors, not successes.
+ stamp_tool_failures(&mut persisted, &outcome.tool_outcomes);
+ // Carry the turn's provider (event channel) + effective model and usage
+ // into the persisted transcript meta. Passing `None` here dropped
+ // `provider`/`model` from every transcript (they are `TranscriptMeta`
+ // fields sourced from the turn usage) — parity with the legacy engine,
+ // which handed `self.last_turn_usage.as_ref()` to this call.
+ let turn_usage = crate::openhuman::agent::harness::session::transcript::TurnUsage {
+ provider: self.event_channel().to_string(),
+ // The model that actually ran this turn (a per-turn override can
+ // diverge from `self.model_name`); attribute usage to it.
+ model: effective_model.to_string(),
+ usage: crate::openhuman::agent::harness::session::transcript::MessageUsage {
+ input: input_tokens,
+ output: output_tokens,
+ cached_input: cached_input_tokens,
+ context_window: context_window.unwrap_or(0),
+ cost_usd: charged_amount_usd,
+ },
+ ts: chrono::Utc::now().to_rfc3339(),
+ reasoning_content: None,
+ tool_calls: Vec::new(),
+ iteration: outcome.model_calls as u32,
+ };
+ self.persist_session_transcript(
+ &persisted,
+ input_tokens,
+ output_tokens,
+ cached_input_tokens,
+ charged_amount_usd,
+ Some(&turn_usage),
+ );
+
+ // Charge this turn's usage against the thread's active goal (parity with
+ // the legacy engine) so budgeted goals progress to `budget_limited` and
+ // continuation scheduling reads a live budget. Self-guarding + best-effort
+ // — a no-op when there is no active goal for the ambient thread.
+ crate::openhuman::threads::goals::runtime::account_turn_against_goal(
+ &self.workspace_dir,
+ input_tokens,
+ output_tokens,
+ turn_started.elapsed().as_secs(),
+ )
+ .await;
+
+ // Content (prompt + reply) rides its own event so a tracing consumer can
+ // attach it to the turn span. Gated on the opt-in
+ // `observability.agent_tracing.capture_content` flag (#4454): with the
+ // default off, we don't even emit the content event, so prompt/reply text
+ // never reaches the span store or any exporter. The collector applies the
+ // same storage-level gate as defense in depth.
+ let capture_content = self
+ .runtime_config
+ .as_ref()
+ .map(|c| c.observability.agent_tracing.capture_content)
+ .unwrap_or(false);
+ if capture_content {
+ log::debug!(
+ target: "agent-tracing",
+ "[agent-tracing] emitting TurnContent (capture_content=true)"
+ );
+ self.emit_progress(AgentProgress::TurnContent {
+ input: Some(user_message.to_string()),
+ output: Some(reply.clone()),
+ })
+ .await;
+ } else {
+ log::debug!(
+ target: "agent-tracing",
+ "[agent-tracing] skipping TurnContent emit (capture_content=false)"
+ );
+ }
+
+ self.emit_progress(AgentProgress::TurnCompleted {
+ iterations: outcome.model_calls as u32,
+ })
+ .await;
+
+ if self.auto_save {
+ let summary = truncate_with_ellipsis(&reply, 100);
+ let autosave_key = format!("assistant_resp:{}", uuid::Uuid::new_v4());
+ let _ = self
+ .memory
+ .store(
+ crate::openhuman::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,
+ &autosave_key,
+ &summary,
+ MemoryCategory::Daily,
+ None,
+ )
+ .await;
+ }
+
+ // Fire post-turn hooks (non-blocking), matching the legacy engine.
+ if !self.post_turn_hooks.is_empty() {
+ let ctx = TurnContext {
+ user_message: user_message.to_string(),
+ assistant_response: reply.clone(),
+ tool_calls: tool_records_from_conversation(
+ &outcome.conversation,
+ &outcome.tool_outcomes,
+ ),
+ turn_duration_ms: turn_started.elapsed().as_millis() as u64,
+ session_id: Some(self.event_session_id.clone())
+ .filter(|session_id| !session_id.trim().is_empty()),
+ agent_id: Some(self.agent_definition_id.clone())
+ .filter(|agent_id| !agent_id.trim().is_empty()),
+ entrypoint: Some(self.event_channel.clone())
+ .filter(|entrypoint| !entrypoint.trim().is_empty()),
+ iteration_count: outcome.model_calls,
+ };
+ hooks::fire_hooks(&self.post_turn_hooks, ctx);
+ }
+
+ Ok(reply)
+ }
+}
diff --git a/src/openhuman/agent/harness/session/turn/core_session_part_02.rs b/src/openhuman/agent/harness/session/turn/core_session_part_02.rs
new file mode 100644
index 0000000000..91c330c004
--- /dev/null
+++ b/src/openhuman/agent/harness/session/turn/core_session_part_02.rs
@@ -0,0 +1,179 @@
+impl Agent {
+ pub(super) async fn inject_agent_experience_context(
+ &self,
+ user_message: &str,
+ enriched: String,
+ ) -> String {
+ const MAX_EXPERIENCE_HITS: usize = 3;
+ const MAX_EXPERIENCE_BLOCK_BYTES: usize = 2048;
+
+ if !self.learning_enabled {
+ return enriched;
+ }
+
+ let tools = self
+ .visible_tool_specs
+ .iter()
+ .map(|spec| spec.name.clone())
+ .collect();
+ let mut stores = vec![AgentExperienceStore::new(self.memory.clone())];
+ if let Some(shared_memory) = &self.shared_experience_memory {
+ stores.push(AgentExperienceStore::new(shared_memory.clone()));
+ }
+ let query = ExperienceQuery {
+ query: user_message.to_string(),
+ tools,
+ tags: Vec::new(),
+ agent_id: Some(self.agent_definition_id.clone()).filter(|id| !id.trim().is_empty()),
+ entrypoint: Some(self.event_channel.clone())
+ .filter(|entrypoint| !entrypoint.trim().is_empty()),
+ // 1c — partition recall by the active profile: this turn sees records
+ // stamped with its profile plus unstamped legacy records, and never a
+ // sibling profile's. `None` (profile-less) recalls the whole pool.
+ profile_id: self.active_profile_id.clone(),
+ max_hits: MAX_EXPERIENCE_HITS,
+ };
+
+ match retrieve_across_stores(&stores, query).await {
+ Ok(hits) => {
+ let matched_hits: Vec<_> = hits
+ .into_iter()
+ .filter(|hit| !hit.match_reasons.is_empty())
+ .collect();
+ let block = render_experience_hits(&matched_hits, MAX_EXPERIENCE_BLOCK_BYTES);
+ if block.is_empty() {
+ return enriched;
+ }
+ log::debug!(
+ "[agent-experience] injected {} experience hit(s) bytes={}",
+ matched_hits.len(),
+ block.len()
+ );
+ prepend_experience_block(&enriched, &block)
+ }
+ Err(err) => {
+ log::warn!("[agent-experience] retrieval failed (non-fatal): {err}");
+ enriched
+ }
+ }
+ }
+
+ async fn inject_triggered_memory_agent_context(
+ &self,
+ user_message: &str,
+ enriched: String,
+ parent_context: &ParentExecutionContext,
+ force_skip: bool,
+ ) -> (String, bool) {
+ const MEMORY_AGENT_ID: &str = "agent_memory";
+ const MAX_MEMORY_AGENT_BLOCK_CHARS: usize = 8000;
+
+ if force_skip {
+ // Per-turn override (#1725): a chat / small-talk turn skips the
+ // pre-turn memory-agent retrieval even when this agent's policy is
+ // `Always`, so a greeting never pulls a prior task's remembered
+ // context into an unrelated reply.
+ log::debug!(
+ "[agent_memory:trigger] skipped agent_id={} (per-turn suppress_memory_agent override)",
+ self.agent_definition_id
+ );
+ return (enriched, false);
+ }
+
+ if self.trigger_memory_agent != TriggerMemoryAgent::Always {
+ log::debug!(
+ "[agent_memory:trigger] skipped agent_id={} policy={:?}",
+ self.agent_definition_id,
+ self.trigger_memory_agent
+ );
+ return (enriched, false);
+ }
+
+ if self.agent_definition_id == MEMORY_AGENT_ID {
+ log::debug!("[agent_memory:trigger] skipped recursive memory agent invocation");
+ return (enriched, false);
+ }
+
+ let Some(registry) = harness::AgentDefinitionRegistry::global() else {
+ log::warn!(
+ "[agent_memory:trigger] AgentDefinitionRegistry unavailable; continuing without memory agent context"
+ );
+ return (enriched, false);
+ };
+ let Some(definition) = registry.get(MEMORY_AGENT_ID).cloned() else {
+ log::warn!(
+ "[agent_memory:trigger] `{MEMORY_AGENT_ID}` definition unavailable; continuing without memory agent context"
+ );
+ return (enriched, false);
+ };
+
+ let task_id = format!("mem-trigger-{}", uuid::Uuid::new_v4());
+ let prompt = format!(
+ "Search the user's memory tree and return only context relevant to the next agent turn.\n\nUser prompt:\n{user_message}"
+ );
+ let options = harness::SubagentRunOptions {
+ task_id: Some(task_id.clone()),
+ model_override: Some(parent_context.model_name.clone()),
+ ..Default::default()
+ };
+
+ log::debug!(
+ "[agent_memory:trigger] starting agent_id={} task_id={} user_message_chars={}",
+ self.agent_definition_id,
+ task_id,
+ user_message.chars().count()
+ );
+
+ let started = std::time::Instant::now();
+ let result = harness::with_parent_context(parent_context.clone(), async move {
+ harness::run_subagent(&definition, &prompt, options).await
+ })
+ .await;
+
+ match result {
+ Ok(outcome) => {
+ log::info!(
+ "[agent_memory:trigger] completed agent_id={} task_id={} iterations={} elapsed={:?} status={:?} output_chars={}",
+ self.agent_definition_id,
+ task_id,
+ outcome.iterations,
+ started.elapsed(),
+ outcome.status,
+ outcome.output.chars().count()
+ );
+ let mut output =
+ truncate_with_ellipsis(&outcome.output, MAX_MEMORY_AGENT_BLOCK_CHARS);
+ if let harness::subagent_runner::SubagentRunStatus::AwaitingUser {
+ question, ..
+ } = &outcome.status
+ {
+ let question = question.trim();
+ if !question.is_empty() {
+ output.push_str("\n\nMemory agent needs clarification: ");
+ output.push_str(question);
+ }
+ }
+ output = truncate_with_ellipsis(&output, MAX_MEMORY_AGENT_BLOCK_CHARS);
+ if output.trim().is_empty() {
+ return (enriched, false);
+ }
+ (
+ format!(
+ "## Memory agent context\n\n{}\n\n---\n\n{}",
+ output.trim(),
+ enriched
+ ),
+ true,
+ )
+ }
+ Err(err) => {
+ log::warn!(
+ "[agent_memory:trigger] failed agent_id={} task_id={}: {err:#}",
+ self.agent_definition_id,
+ task_id
+ );
+ (enriched, false)
+ }
+ }
+ }
+}
diff --git a/src/openhuman/agent/tools/ask_clarification.rs b/src/openhuman/agent/tools/ask_clarification.rs
index 9dc30eb478..b4a99bec77 100644
--- a/src/openhuman/agent/tools/ask_clarification.rs
+++ b/src/openhuman/agent/tools/ask_clarification.rs
@@ -67,9 +67,20 @@ impl Tool for AskClarificationTool {
}
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ // Blank counts as absent. The schema has no `minLength`, so
+ // `{"question":""}` is a legal call, and `as_str()` answers `Some("")` —
+ // which slipped past the missing-argument fallback below. That was
+ // survivable only while the `[CLARIFICATION NEEDED]` prefix kept the
+ // output non-empty; now that this output *is* the message the user
+ // reads, an empty one would park the turn on a blank prompt: a blank
+ // assistant reply on the channel path, and an `AwaitingUser` sub-agent
+ // card with nothing in it. Trimmed for the same reason — a whitespace
+ // question is a blank one (#6213 review).
let question = args
.get("question")
.and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|q| !q.is_empty())
.unwrap_or("Could you clarify?");
let options = args.get("options").and_then(|v| v.as_array()).map(|arr| {
diff --git a/src/openhuman/agent/tools/ask_clarification_tests.rs b/src/openhuman/agent/tools/ask_clarification_tests.rs
index da77015dc5..0ccecae671 100644
--- a/src/openhuman/agent/tools/ask_clarification_tests.rs
+++ b/src/openhuman/agent/tools/ask_clarification_tests.rs
@@ -79,3 +79,43 @@ async fn output_is_the_bare_question_with_no_marker() {
.unwrap();
assert_eq!(result.output(), "Which branch should I target?");
}
+
+/// A blank question must fall back to the generic prompt, not park the turn on
+/// an empty one (#6213 review).
+///
+/// The schema has no `minLength`, so `{"question":""}` is a legal call. The
+/// early-exit hook captures this output verbatim as the pause question, so an
+/// empty one reaches the user as a blank assistant reply on the channel path
+/// and an empty answer box on a delegated sub-agent's card. The old
+/// `[CLARIFICATION NEEDED]` prefix masked this by keeping the string non-empty.
+#[tokio::test]
+async fn a_blank_question_falls_back_to_the_generic_prompt() {
+ let tool = AskClarificationTool::new();
+ for blank in ["", " ", "\n\t "] {
+ let result = tool
+ .execute(serde_json::json!({ "question": blank }))
+ .await
+ .expect("execute");
+ assert!(
+ !result.output().trim().is_empty(),
+ "a blank question must never produce an empty pause prompt, got {:?}",
+ result.output()
+ );
+ assert_eq!(
+ result.output(),
+ "Could you clarify?",
+ "a blank question must use the same fallback as a missing one"
+ );
+ }
+}
+
+/// The fallback must not swallow a real question that merely has padding.
+#[tokio::test]
+async fn a_padded_question_is_trimmed_but_kept() {
+ let tool = AskClarificationTool::new();
+ let result = tool
+ .execute(serde_json::json!({ "question": " Which three sources? " }))
+ .await
+ .expect("execute");
+ assert_eq!(result.output(), "Which three sources?");
+}