The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(agent): reorganise definition and loader modules
Steven Enamakel607b0892d772
diff --git a/crates/openhuman-core/src/agent/harness/definition.rs b/crates/openhuman-core/src/agent/harness/definition.rsindex 1c09919cc0..63f5f66e03 100644--- a/crates/openhuman-core/src/agent/harness/definition.rs+++ b/crates/openhuman-core/src/agent/harness/definition.rs@@ -24,8 +24,25 @@#[cfg(test)]#[path = "definition_tests.rs"]mod tests;-include!("definition_part_01.rs");-include!("definition_part_02.rs");++mod agent_definition;+mod execution_spec;+mod prompt_source;+mod registry;+mod source;+mod subagents;+mod tier;++pub(crate) use agent_definition::defaults;+pub use agent_definition::{+ AgentDefinition, IterationPolicy, TriggerMemoryAgent, EXTENDED_MAX_TOOL_ITERATIONS,+};+pub use execution_spec::{ModelSpec, SandboxMode, ToolScope};+pub use prompt_source::{PromptBuilder, PromptSource};+pub use registry::AgentDefinitionRegistry;+pub use source::DefinitionSource;+pub use subagents::{SkillsWildcard, SubagentEntry};+pub use tier::{validate_tier_transition, AgentTier};/// Sentinel used to represent an explicit zero-tool scope.pub const NO_TOOLS_SENTINEL: &str = "__no_tools__";diff --git a/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs b/crates/openhuman-core/src/agent/harness/definition/agent_definition.rsindex 93babe6fa7..a4d7d03aa6 100644--- a/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs+++ b/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs@@ -275,7 +275,6 @@ pub struct AgentDefinition {pub graph: crate::agent::harness::agent_graph::AgentGraph,}-impl AgentDefinition {/// Display name with fallback to id.pub fn display_name(&self) -> &str {@@ -308,7 +307,6 @@ impl AgentDefinition {}}-// ─────────────────────────────────────────────────────────────────────────────// Defaults module — referenced by `#[serde(default = ...)]`// ─────────────────────────────────────────────────────────────────────────────diff --git a/crates/openhuman-core/src/agent/harness/definition/execution_spec.rs b/crates/openhuman-core/src/agent/harness/definition/execution_spec.rsindex e8b8657da3..546b132254 100644--- a/crates/openhuman-core/src/agent/harness/definition/execution_spec.rs+++ b/crates/openhuman-core/src/agent/harness/definition/execution_spec.rs@@ -4,7 +4,6 @@use serde::{Deserialize, Serialize};-/// Model selection for a sub-agent.#[derive(Debug, Clone, Serialize, Deserialize, Default)]#[serde(rename_all = "snake_case")]@@ -37,8 +36,6 @@ impl ModelSpec {}}--/// Which tools a sub-agent is allowed to call.#[derive(Debug, Clone, Serialize, Deserialize, Default)]#[serde(rename_all = "snake_case")]@@ -52,8 +49,6 @@ pub enum ToolScope {Named(Vec<String>),}--/// Sandbox mode for a sub-agent's tool execution. Serialises as a simple/// `snake_case` string in TOML (`none` / `read_only` / `sandboxed`). In/// the future this may map directly into a `SecurityPolicy` builder.@@ -68,4 +63,3 @@ pub enum SandboxMode {/// Drop privileges, restrict filesystem (Landlock / Bubblewrap).Sandboxed,}-diff --git a/crates/openhuman-core/src/agent/harness/definition/prompt_source.rs b/crates/openhuman-core/src/agent/harness/definition/prompt_source.rsindex e21ab7d8bf..64dbd834f3 100644--- a/crates/openhuman-core/src/agent/harness/definition/prompt_source.rs+++ b/crates/openhuman-core/src/agent/harness/definition/prompt_source.rs@@ -4,7 +4,6 @@use serde::ser::SerializeMap;use serde::{Deserialize, Serialize};-/// Builder function signature for [`PromptSource::Dynamic`]. Takes the/// full runtime [`crate::agent::context::prompt::PromptContext`]/// (tools, skills, memory, connected integrations, dispatcher, model,@@ -80,4 +79,3 @@ impl<'de> Deserialize<'de> for PromptSource {})}}-diff --git a/crates/openhuman-core/src/agent/harness/definition/registry.rs b/crates/openhuman-core/src/agent/harness/definition/registry.rsindex f7d96b450b..806d0ddaf9 100644--- a/crates/openhuman-core/src/agent/harness/definition/registry.rs+++ b/crates/openhuman-core/src/agent/harness/definition/registry.rs@@ -55,15 +55,13 @@ impl AgentDefinitionRegistry {// as the bundled set. See// [`crate::agent::registry::agents::loader::validate_tier_hierarchy`].let snapshot: Vec<AgentDefinition> = reg.list().into_iter().cloned().collect();- crate::agent::registry::agents::validate_tier_hierarchy(&snapshot).map_err(- |e| {- anyhow::anyhow!(- "agent registry rejected after merging workspace overrides from {}: {}",- workspace.display(),- e- )- },- )?;+ crate::agent::registry::agents::validate_tier_hierarchy(&snapshot).map_err(|e| {+ anyhow::anyhow!(+ "agent registry rejected after merging workspace overrides from {}: {}",+ workspace.display(),+ e+ )+ })?;Ok(reg)}diff --git a/crates/openhuman-core/src/agent/harness/definition/source.rs b/crates/openhuman-core/src/agent/harness/definition/source.rsindex b14aab2478..232f6c3cc7 100644--- a/crates/openhuman-core/src/agent/harness/definition/source.rs+++ b/crates/openhuman-core/src/agent/harness/definition/source.rs@@ -3,7 +3,7 @@use serde::{Deserialize, Serialize};-/// Where an [`AgentDefinition`] was loaded from. Used for telemetry and+/// Where an [`super::AgentDefinition`] was loaded from. Used for telemetry and/// the `agent::list_definitions` RPC reply.#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]#[serde(tag = "kind", content = "path")]@@ -23,4 +23,3 @@ pub enum DefinitionSource {/// belt).CustomRegistry,}-diff --git a/crates/openhuman-core/src/agent/harness/definition/subagents.rs b/crates/openhuman-core/src/agent/harness/definition/subagents.rsindex 186092a0ad..35626b21c8 100644--- a/crates/openhuman-core/src/agent/harness/definition/subagents.rs+++ b/crates/openhuman-core/src/agent/harness/definition/subagents.rs@@ -3,8 +3,6 @@use serde::{Deserialize, Deserializer, Serialize};--/// One entry in [`super::AgentDefinition::subagents`]. Parses from TOML as either/// a bare string (agent id) or an inline table (`{ skills = "*" }`) thanks/// to `#[serde(untagged)]`.@@ -67,4 +65,3 @@ impl SkillsWildcard {self.skills == "*"}}-diff --git a/crates/openhuman-core/src/agent/harness/definition/tier.rs b/crates/openhuman-core/src/agent/harness/definition/tier.rsindex 2cdfc2a7a2..b19a5b3c2e 100644--- a/crates/openhuman-core/src/agent/harness/definition/tier.rs+++ b/crates/openhuman-core/src/agent/harness/definition/tier.rs@@ -3,8 +3,6 @@use serde::{Deserialize, Serialize};--/// Role an agent plays in the spawn hierarchy.////// See [`super::AgentDefinition::agent_tier`] for the full contract. In short:@@ -102,4 +100,3 @@ pub fn validate_tier_transition(parent: AgentTier, child: AgentTier) -> Result<(_ => Ok(()),}}-diff --git a/crates/openhuman-core/src/agent/harness/definition_part_01.rs b/crates/openhuman-core/src/agent/harness/definition_part_01.rsdeleted file mode 100644index 293fe757d7..0000000000--- a/crates/openhuman-core/src/agent/harness/definition_part_01.rs+++ /dev/null@@ -1,674 +0,0 @@-use serde::ser::SerializeMap;-use serde::{Deserialize, Deserializer, Serialize};-use std::path::PathBuf;--use crate::inference::tokenjuice::AgentTokenjuiceCompression;--/// Iteration ceiling for an [`IterationPolicy::Extended`] agent — the higher-/// bound a long-running agent (orchestrator, deep research) is allowed to reach-/// before the harness stops it. Lives here, the sole consumer, since the legacy-/// `tool_loop` that originally defined it was removed in the tinyagents-/// migration (issue #4249).-pub const EXTENDED_MAX_TOOL_ITERATIONS: usize = 50;--/// Iteration-cap policy for a sub-agent.-///-/// Controls how the harness enforces [`AgentDefinition::max_iterations`]:-///-/// * **Strict** — hard-fail at `max_iterations` (the current default).-/// Right for short-running agents (summarizer, triage) where hitting-/// the cap signals a likely loop.-/// * **Extended** — the per-agent `max_iterations` is replaced at runtime-/// by a higher harness-wide constant-/// ([`EXTENDED_MAX_TOOL_ITERATIONS`])-/// so the agent can complete realistic multi-tool workflows. The-/// repeated-failure circuit breaker and cost budget still apply. The-/// UI omits the denominator ("step N" instead of "turn N/M") to avoid-/// a misleading terminal countdown.-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]-#[serde(rename_all = "snake_case")]-pub enum IterationPolicy {- /// Hard cap at `max_iterations`. Default for most agents.- #[default]- Strict,- /// Raised cap for multi-step specialists. Guards still apply.- Extended,-}--/// Policy for running the memory retrieval agent before a normal agent turn.-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]-#[serde(rename_all = "snake_case")]-pub enum TriggerMemoryAgent {- /// Do not run the memory agent automatically.- #[default]- Never,- /// Run `agent_memory` once before the user's prompt is sent to this agent.- Always,-}--// ─────────────────────────────────────────────────────────────────────────────-// Agent definition-// ─────────────────────────────────────────────────────────────────────────────--/// A fully specified sub-agent archetype: what it knows, what it can do, and how to prompt it.-///-/// Definitions are used by the `spawn_subagent` tool to initialize a new-/// specialized agent. They can be built-in or loaded from custom TOML files.-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AgentDefinition {- // ── identity ────────────────────────────────────────────────────────- /// Unique identifier for this archetype (e.g., `researcher`, `code_executor`).- pub id: String,-- /// Human-readable description explaining when this agent should be used.- /// Shown to the parent model to help it decide whether to delegate.- pub when_to_use: String,-- /// Optional display name for UI and log output.- #[serde(default)]- pub display_name: Option<String>,-- // ── prompt ──────────────────────────────────────────────────────────- /// The core system prompt body for this specialized agent.- #[serde(default = "defaults::empty_inline_prompt")]- pub system_prompt: PromptSource,-- /// If `true`, the parent's identity section is stripped from the prompt.- #[serde(default = "defaults::true_")]- pub omit_identity: bool,-- /// If `true`, the parent's memory context is stripped.- #[serde(default = "defaults::true_")]- pub omit_memory_context: bool,-- /// If `true`, the standard safety preamble is stripped.- #[serde(default = "defaults::true_")]- pub omit_safety_preamble: bool,-- /// If `true`, the user's `PROFILE.md` (generated by the onboarding- /// enrichment pipeline — LinkedIn scrape, etc.) is NOT injected into- /// the rendered prompt. Defaults to `true` so sub-agents stay lean:- /// only agents that need to personalise user-facing output (welcome,- /// orchestrator, the trigger pair) opt in with `omit_profile = false`.- #[serde(default = "defaults::true_")]- pub omit_profile: bool,-- /// If `true`, the archivist-curated `MEMORY.md` (long-term distilled- /// memory file) is NOT injected into the rendered prompt. Defaults- /// to `true` for the same reason as `omit_profile` — narrow- /// specialists stay lean; user-facing agents opt in.- ///- /// **KV-cache contract:** like every workspace file, once MEMORY.md- /// is rendered into a session's system prompt the bytes are frozen- /// for that session's lifetime. Archivist writes that land- /// mid-session do not retroactively update the in-flight prompt —- /// they are picked up on the next session. This matches the- /// byte-stability invariant documented on- /// [`crate::agent::context::prompt::render_subagent_system_prompt`].- #[serde(default = "defaults::true_")]- pub omit_memory_md: bool,-- // ── model ───────────────────────────────────────────────────────────- /// Strategy for picking which model to use for this sub-agent.- #[serde(default)]- pub model: ModelSpec,-- /// Sampling temperature for the model.- #[serde(default = "defaults::subagent_temperature")]- pub temperature: f64,-- // ── tools ───────────────────────────────────────────────────────────- /// Which tools from the parent's registry should be available to the sub-agent.- #[serde(default)]- pub tools: ToolScope,-- /// Explicit list of tool names to block, even if they match the scope.- #[serde(default)]- pub disallowed_tools: Vec<String>,-- /// Filter to only tools belonging to a specific skill (e.g., `notion`).- #[serde(default)]- pub skill_filter: Option<String>,-- /// Named tools that should always be visible to this agent in- /// addition to its [`ToolScope`]. Historically this was a bypass- /// list for the now-removed `category_filter`; kept as a generic- /// "also include these" hook for custom definitions.- ///- /// Entries are still subject to [`AgentDefinition::disallowed_tools`].- #[serde(default)]- pub extra_tools: Vec<String>,-- // ── runtime limits ──────────────────────────────────────────────────- /// Maximum number of tool iterations for this sub-agent's task.- #[serde(default = "defaults::max_iterations")]- pub max_iterations: usize,-- /// Iteration-cap policy. See [`IterationPolicy`] for semantics.- /// Defaults to [`IterationPolicy::Strict`]; long-running specialists- /// set `iteration_policy = "extended"` in their `agent.toml`.- #[serde(default)]- pub iteration_policy: IterationPolicy,-- /// Maximum character length for this sub-agent's output before the- /// harness truncates it before feeding it back as a tool result to the- /// parent. `None` means no cap (the default for most agents). Set to- /// a value for research/planner/code agents to prevent context flooding- /// from large outputs.- #[serde(default)]- pub max_result_chars: Option<usize>,-- /// Optional per-LLM-call output token cap for this agent. When unset, the- /// shared agent-turn cap is used. Narrow agents can set a smaller cap so- /// a single verbose turn cannot flood the sub-agent loop before the final- /// result is truncated.- #[serde(default)]- pub max_turn_output_tokens: Option<u32>,-- /// Wall-clock timeout for the sub-agent's execution (seconds).- #[serde(default)]- pub timeout_secs: Option<u64>,-- /// Sandbox level for tool execution.- #[serde(default)]- pub sandbox_mode: SandboxMode,-- /// Reserved for background (asynchronous) execution support.- #[serde(default)]- pub background: bool,-- /// Optional pre-turn memory retrieval hook. When set to `always`, the- /// harness runs the built-in `agent_memory` agent once with the user- /// prompt and prepends its result to the prompt sent to this agent.- #[serde(default)]- pub trigger_memory_agent: TriggerMemoryAgent,-- /// Per-agent TokenJuice tool-result compression profile.- ///- /// `auto` keeps compression on for normal agents, but resolves coding-model- /// agents to `light` so CCR-backed lossy compression does not replace raw- /// build/test/diff/search text that coding agents often need exactly.- #[serde(default)]- pub tokenjuice_compression: AgentTokenjuiceCompression,-- // ── delegation surface ─────────────────────────────────────────────- /// Subagents this agent is allowed to spawn via synthesised- /// `delegate_*` tools. Each entry expands at agent-build time into- /// one tool the LLM can call in its function-calling schema:- ///- /// * [`SubagentEntry::AgentId`] — one [`ArchetypeDelegationTool`]- /// whose name defaults to `delegate_{agent_id}` (or the target- /// agent's `delegate_name` override) and whose description is the- /// target agent's [`AgentDefinition::when_to_use`].- ///- /// * [`SubagentEntry::Skills`] — a single collapsed- /// [`SkillDelegationTool`] named `delegate_to_integrations_agent`- /// that takes the toolkit slug as an argument and routes to the- /// generic `integrations_agent` with the corresponding- /// `skill_filter` pre-populated (#1335).- ///- /// `subagents` is intentionally separate from [`AgentDefinition::tools`]- /// so that reading a TOML makes the distinction obvious: `tools` is- /// "what I execute directly", `subagents` is "what I can delegate to".- ///- /// [`ArchetypeDelegationTool`]: crate::agent::orchestration::tools::ArchetypeDelegationTool- /// [`SkillDelegationTool`]: crate::agent::orchestration::tools::SkillDelegationTool- #[serde(default, deserialize_with = "deserialize_subagent_entries")]- pub subagents: Vec<SubagentEntry>,-- /// Optional override for the tool name this agent is exposed as when- /// another agent lists it in its [`subagents`]. Defaults to- /// `delegate_{id}` when absent. Kept separate from `display_name` so- /// the UI display and the LLM tool name can diverge (e.g.- /// `display_name = "Researcher"`, `delegate_name = "research"`).- #[serde(default)]- pub delegate_name: Option<String>,-- // ── spawn hierarchy ────────────────────────────────────────────────- /// Tier this archetype occupies in the spawn hierarchy- /// (`chat` → `reasoning` → `worker`). Drives loader-time validation- /// of [`AgentDefinition::subagents`] and runtime depth gating in the- /// sub-agent runner. Defaults to [`AgentTier::Worker`] so existing- /// specialists fit the "leaf" role without per-file edits.- ///- /// **Hierarchy contract** (enforced by- /// [`super::super::agents::loader`] at registry build time):- ///- /// * `Chat` MUST NOT list another `Chat` agent in `subagents`. The- /// user-facing fast tier is a leaf in its own dimension — it- /// hands off to `Reasoning` or `Worker`, never to itself.- /// * `Reasoning` MUST NOT list another `Reasoning` agent in- /// `subagents`. Reasoning composes downward into `Worker`s.- /// * `Worker` MUST NOT list open-ended subagents. Workers execute;- /// they do not orchestrate. Pre-turn memory retrieval is configured- /// separately via [`AgentDefinition::trigger_memory_agent`].- /// * `{ skills = "*" }` entries expand to the generic- /// `integrations_agent` (a `Worker`) so they are always allowed.- ///- /// Combined with the harness's `MAX_SPAWN_DEPTH = 3` task-local- /// gate, this means any execution chain bottoms out within three- /// hops: `chat → reasoning → worker` (or `chat → worker` for the- /// fast path).- #[serde(default)]- pub agent_tier: AgentTier,-- // ── source bookkeeping ──────────────────────────────────────────────- /// Tracks where the definition was loaded from (Builtin vs. File).- #[serde(skip)]- pub source: DefinitionSource,-- // ── turn graph ──────────────────────────────────────────────────────- /// How this agent's turn is driven (issue #4249). Injected post-load from- /// the agent folder's `graph.rs::graph()` (mirrors how- /// [`PromptSource::Dynamic`] is injected from `prompt.rs::build`); TOML-- /// authored agents cannot set it, so it is `#[serde(skip)]` and defaults to- /// [`AgentGraph::Default`] (the shared default turn graph).- #[serde(skip, default)]- pub graph: super::agent_graph::AgentGraph,-}--// ─────────────────────────────────────────────────────────────────────────────-// Agent tier (spawn hierarchy)-// ─────────────────────────────────────────────────────────────────────────────--/// Role an agent plays in the spawn hierarchy.-///-/// See [`AgentDefinition::agent_tier`] for the full contract. In short:-///-/// ```text-/// Chat (fast, UX-focused)-/// └─► Reasoning (slow, deep-thinking)-/// └─► Worker (leaf executors)-/// └─► Worker (direct fast-path delegation)-/// ```-///-/// `Chat` and `Reasoning` are forbidden from spawning their own tier;-/// `Worker` is forbidden from spawning anything. Total depth is capped-/// at three hops by the harness regardless of tier (defence in depth-/// against custom TOMLs that drop the tier annotation).-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]-#[serde(rename_all = "snake_case")]-pub enum AgentTier {- /// User-facing fast-tier agent (e.g. the Orchestrator on the- /// `chat` model hint). Optimised for TTFT, not for long-horizon- /// reasoning. May delegate to `Reasoning` or `Worker`; must NOT- /// delegate to another `Chat` agent.- Chat,- /// Deep-thinking agent on a `reasoning-v1`-style model (e.g. the- /// Planner). Decomposes long-running tasks and delegates execution- /// to one or more `Worker`s. Must NOT delegate to another- /// `Reasoning` agent.- Reasoning,- /// Leaf executor — researchers, code executors, critics, archivists,- /// integration specialists, etc. Workers do the actual work and must- /// NOT spawn further subagents (a `Worker` with a non-empty- /// `subagents` list is rejected by the loader).- #[default]- Worker,-}--impl AgentTier {- /// Human-readable tier name used in error messages.- pub fn as_str(self) -> &'static str {- match self {- Self::Chat => "chat",- Self::Reasoning => "reasoning",- Self::Worker => "worker",- }- }-}--impl std::fmt::Display for AgentTier {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.write_str(self.as_str())- }-}--/// Single source of truth for the spawn-hierarchy rule: is a `parent`-tier-/// agent allowed to delegate to a `child`-tier agent?-///-/// Returns `Ok(())` for the legal handoffs and `Err(reason)` for the three-/// forbidden shapes, where `reason` is a tier-only human-readable explanation-/// (no agent ids — callers prepend their own context):-///-/// - `Worker → *` — workers are leaf executors and must not spawn anything.-/// - `Chat → Chat` — the chat tier is a leaf in its own dimension; cloning it-/// defeats the fast-path and risks unbounded `chat → chat → …` chains.-/// - `Reasoning → Reasoning` — reasoning agents compose downward into workers,-/// not into each other (a depth-blowing recursion of slow models).-///-/// Note this forbids same-tier and worker-as-parent hops, **not** upward hops:-/// `reasoning → chat` is a real, intentional builtin edge (the `subconscious`-/// reasoner can hand a follow-up back to the `orchestrator` chat agent), so it-/// must stay legal. The harness'es `MAX_SPAWN_DEPTH` cap bounds chain length-/// independently of tier direction.-///-/// This is the static authoring rule the loader walks over declared `subagents`-/// pairs at boot (see-/// [`crate::agent::registry::agents::validate_tier_hierarchy`]). The-/// runtime spawn gate (`run_subagent`) reuses it as defense-in-depth, but-/// deliberately exempts worker *parents* — at runtime a worker only reaches the-/// spawn chokepoint via the documented collapsed `delegate_to_integrations_agent`-/// path (→ `integrations_agent`, itself a worker), which the loader intentionally-/// leaves untouched.-pub fn validate_tier_transition(parent: AgentTier, child: AgentTier) -> Result<(), String> {- match (parent, child) {- (AgentTier::Worker, _) => Err(format!(- "a `worker` tier agent must not spawn `{}` — workers are leaf executors",- child.as_str()- )),- (AgentTier::Chat, AgentTier::Chat) => Err(- "the chat tier is a leaf in its own dimension — hand off to a `reasoning` or \- `worker` agent instead"- .to_string(),- ),- (AgentTier::Reasoning, AgentTier::Reasoning) => {- Err("reasoning agents compose downward into workers, not into each other".to_string())- }- _ => Ok(()),- }-}--// ─────────────────────────────────────────────────────────────────────────────-// Subagent delegation entries-// ─────────────────────────────────────────────────────────────────────────────--/// One entry in [`AgentDefinition::subagents`]. Parses from TOML as either-/// a bare string (agent id) or an inline table (`{ skills = "*" }`) thanks-/// to `#[serde(untagged)]`.-///-/// # TOML shapes-///-/// ```toml-/// [subagents]-/// allowlist = [-/// "researcher", # AgentId("researcher")-/// "code_executor", # AgentId("code_executor")-/// { skills = "*" }, # Skills { pattern: "*" }-/// ]-/// ```-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]-#[serde(untagged)]-pub enum SubagentEntry {- /// Delegate to a specific built-in or custom agent by id.- AgentId(String),- /// Expand at build time to a single collapsed- /// `delegate_to_integrations_agent` tool whose `toolkit` argument- /// selects which connected Composio toolkit to route to, with- /// `skill_filter` pre-set on the underlying `integrations_agent`- /// dispatch (#1335).- Skills(SkillsWildcard),-}--/// The `{ skills = "*" }` inline table in a `subagents` list.-///-/// Today only `"*"` is meaningful (expand to every connected toolkit).-/// Future: a `Vec<String>` variant to restrict expansion to specific-/// toolkit slugs (e.g. `{ skills = ["gmail", "notion"] }`).-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]-pub struct SkillsWildcard {- /// Glob / wildcard pattern. Only `"*"` is currently supported.- pub skills: String,-}--fn deserialize_subagent_entries<'de, D>(deserializer: D) -> Result<Vec<SubagentEntry>, D::Error>-where- D: Deserializer<'de>,-{- #[derive(Deserialize)]- #[serde(untagged)]- enum Wire {- Section { allowlist: Vec<SubagentEntry> },- LegacyList(Vec<SubagentEntry>),- }-- match Option::<Wire>::deserialize(deserializer)? {- Some(Wire::Section { allowlist }) => Ok(allowlist),- Some(Wire::LegacyList(entries)) => Ok(entries),- None => Ok(Vec::new()),- }-}--impl SkillsWildcard {- /// True when this wildcard should expand to every connected toolkit.- pub fn matches_all(&self) -> bool {- self.skills == "*"- }-}--impl AgentDefinition {- /// Display name with fallback to id.- pub fn display_name(&self) -> &str {- self.display_name.as_deref().unwrap_or(&self.id)- }-- /// Effective iteration cap after applying [`IterationPolicy`].- ///- /// * `Strict` → `self.max_iterations` unchanged.- /// * `Extended` → the higher of `self.max_iterations` and the- /// harness-wide [`EXTENDED_MAX_TOOL_ITERATIONS`].- pub fn effective_max_iterations(&self) -> usize {- match self.iteration_policy {- IterationPolicy::Strict => self.max_iterations,- IterationPolicy::Extended => self.max_iterations.max(EXTENDED_MAX_TOOL_ITERATIONS),- }- }-- /// Resolve the authored TokenJuice profile to the concrete per-call policy.- pub fn effective_tokenjuice_compression(&self) -> AgentTokenjuiceCompression {- match self.tokenjuice_compression {- AgentTokenjuiceCompression::Auto => match &self.model {- ModelSpec::Hint(hint) if hint.trim().eq_ignore_ascii_case("coding") => {- AgentTokenjuiceCompression::Light- }- _ => AgentTokenjuiceCompression::Full,- },- other => other,- }- }-}--// ─────────────────────────────────────────────────────────────────────────────-// Prompt source-// ─────────────────────────────────────────────────────────────────────────────--/// Builder function signature for [`PromptSource::Dynamic`]. Takes the-/// full runtime [`crate::agent::context::prompt::PromptContext`]-/// (tools, skills, memory, connected integrations, dispatcher, model,-/// …) and returns the final system prompt body — typically assembled-/// by calling the `render_*` section helpers in-/// [`crate::agent::context::prompt`] in the order the builder-/// wants.-pub type PromptBuilder =- fn(&crate::agent::context::prompt::PromptContext<'_>) -> anyhow::Result<String>;--/// Where the sub-agent's core system prompt comes from.-#[derive(Clone)]-pub enum PromptSource {- /// Inline prompt string (custom TOML-defined agents).- Inline(String),- /// Relative path under the workspace's `prompts/` directory or under- /// `crates/openhuman-core/src/agent/prompts/` for built-ins. Resolved by the runner- /// at spawn time.- File { path: String },- /// Function-driven prompt: the builder is invoked at spawn time with- /// a [`PromptContext`] so the returned body can depend on runtime- /// state (available tools, user profile, connected skills, etc.).- ///- /// Only constructed in-process (by built-in agent loaders). Not- /// deserializable from TOML — TOML-authored agents must use `inline`- /// or `file`.- Dynamic(PromptBuilder),-}--impl std::fmt::Debug for PromptSource {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- PromptSource::Inline(s) => f.debug_tuple("Inline").field(&s).finish(),- PromptSource::File { path } => f.debug_struct("File").field("path", path).finish(),- PromptSource::Dynamic(_) => f.debug_tuple("Dynamic").field(&"<fn>").finish(),- }- }-}--impl Serialize for PromptSource {- fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {- let mut map = serializer.serialize_map(Some(1))?;- match self {- PromptSource::Inline(s) => map.serialize_entry("inline", s)?,- PromptSource::File { path } => {- #[derive(Serialize)]- struct FileBody<'a> {- path: &'a str,- }- map.serialize_entry("file", &FileBody { path })?;- }- // Opaque marker — runtime-only. Round-trips back through- // Deserialize would produce an error (Dynamic is unsupported- // there) which is intentional: RPC consumers treat Dynamic- // sources as "built-in, runtime-generated".- PromptSource::Dynamic(_) => map.serialize_entry("dynamic", &serde_json::Value::Null)?,- }- map.end()- }-}--impl<'de> Deserialize<'de> for PromptSource {- fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {- #[derive(Deserialize)]- #[serde(rename_all = "snake_case")]- enum Shape {- Inline(String),- File { path: String },- }- Shape::deserialize(deserializer).map(|s| match s {- Shape::Inline(body) => PromptSource::Inline(body),- Shape::File { path } => PromptSource::File { path },- })- }-}--// ─────────────────────────────────────────────────────────────────────────────-// Model spec-// ─────────────────────────────────────────────────────────────────────────────--/// Model selection for a sub-agent.-#[derive(Debug, Clone, Serialize, Deserialize, Default)]-#[serde(rename_all = "snake_case")]-pub enum ModelSpec {- /// Use the parent agent's currently-selected model at spawn time.- #[default]- Inherit,- /// Exact model name (e.g. `"neocortex-mk1"`).- Exact(String),- /// Router hint (e.g. `"reasoning"`, `"coding"`, `"local"`). Resolved- /// to a real model by the routing provider.- Hint(String),-}--impl ModelSpec {- /// Resolve this spec into the model name string the provider expects.- /// `parent_model` is the model the parent agent is using right now.- ///- /// Hints are resolved to `{hint}-v1` (e.g. `"agentic"` → `"agentic-v1"`)- /// which matches the backend's standard model naming convention. When- /// a `RouterProvider` is present its route table takes priority over- /// this default; when no router is configured (empty `model_routes`)- /// the resolved name goes directly to the backend.- pub fn resolve(&self, parent_model: &str) -> String {- match self {- Self::Inherit => parent_model.to_string(),- Self::Exact(name) => name.clone(),- Self::Hint(hint) => format!("{hint}-v1"),- }- }-}--// ─────────────────────────────────────────────────────────────────────────────-// Tool scope-// ─────────────────────────────────────────────────────────────────────────────--/// Which tools a sub-agent is allowed to call.-#[derive(Debug, Clone, Serialize, Deserialize, Default)]-#[serde(rename_all = "snake_case")]-pub enum ToolScope {- /// All tools the parent has (subject to `disallowed_tools` and- /// `skill_filter`).- #[default]- Wildcard,- /// An explicit allowlist of tool names. Names not present in the parent- /// registry at spawn time are silently dropped (logged at debug).- Named(Vec<String>),-}--// ─────────────────────────────────────────────────────────────────────────────-// Sandbox mode-// ─────────────────────────────────────────────────────────────────────────────--/// Sandbox mode for a sub-agent's tool execution. Serialises as a simple-/// `snake_case` string in TOML (`none` / `read_only` / `sandboxed`). In-/// the future this may map directly into a `SecurityPolicy` builder.-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]-#[serde(rename_all = "snake_case")]-pub enum SandboxMode {- /// No additional sandboxing beyond what the parent already enforces.- #[default]- None,- /// Read-only — write/execute tools are filtered out.- ReadOnly,- /// Drop privileges, restrict filesystem (Landlock / Bubblewrap).- Sandboxed,-}--// ─────────────────────────────────────────────────────────────────────────────-// Definition source-// ─────────────────────────────────────────────────────────────────────────────--/// Where an [`AgentDefinition`] was loaded from. Used for telemetry and-/// the `agent::list_definitions` RPC reply.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]-#[serde(tag = "kind", content = "path")]-pub enum DefinitionSource {- /// Built-in definition shipped as part of the binary (loaded from- /// [`crate::agent::registry::agents`]).- #[default]- Builtin,- /// Loaded from a TOML file at the given absolute path.- File(PathBuf),- /// Synthesized at lookup time from a user-authored- /// [`AgentRegistryEntry`](crate::agent::registry::AgentRegistryEntry)- /// (`AgentRegistrySource::Custom`) by `agent_registry::defaults::definition_from_registry_entry`.- /// Never persisted in the [`AgentDefinitionRegistry`] — built fresh per- /// factory call so config edits take effect immediately (closes the gap- /// where custom agents ran persona-only instead of with their real tool- /// belt).- CustomRegistry,-}--// ─────────────────────────────────────────────────────────────────────────────-// Defaults module — referenced by `#[serde(default = ...)]`-// ─────────────────────────────────────────────────────────────────────────────--pub(crate) mod defaults {- use super::PromptSource;-- pub(crate) fn true_() -> bool {- true- }-- pub(crate) fn subagent_temperature() -> f64 {- 0.4- }-- pub(crate) fn max_iterations() -> usize {- 8- }-- /// Placeholder for [`super::AgentDefinition::system_prompt`] when the- /// TOML omits the field. The built-in loader overwrites this with- /// the rendered sibling `prompt.md`; custom TOMLs that omit the- /// field get a no-op empty prompt (and should not).- pub(crate) fn empty_inline_prompt() -> PromptSource {- PromptSource::Inline(String::new())- }-}diff --git a/crates/openhuman-core/src/agent/harness/definition_part_02.rs b/crates/openhuman-core/src/agent/harness/definition_part_02.rsdeleted file mode 100644index c73099062a..0000000000--- a/crates/openhuman-core/src/agent/harness/definition_part_02.rs+++ /dev/null@@ -1,149 +0,0 @@--// ─────────────────────────────────────────────────────────────────────────────-// Registry-// ─────────────────────────────────────────────────────────────────────────────--use anyhow::Result;-use std::collections::HashMap;-use std::path::Path;-use std::sync::OnceLock;--/// In-memory registry of all known [`AgentDefinition`]s.-///-/// One singleton instance is initialised at startup via-/// [`AgentDefinitionRegistry::init_global`]. Built-ins are registered-/// unconditionally; custom TOML definitions (if a workspace is provided)-/// are loaded next and override built-ins on `id` collision.-#[derive(Debug, Default)]-pub struct AgentDefinitionRegistry {- by_id: HashMap<String, AgentDefinition>,- /// Insertion-stable order for predictable `list()` output.- order: Vec<String>,-}--static GLOBAL: OnceLock<AgentDefinitionRegistry> = OnceLock::new();--impl AgentDefinitionRegistry {- /// Build a registry containing only the built-in definitions- /// (no TOML loading). Useful for tests.- pub fn builtins_only() -> Self {- let mut reg = Self::default();- for def in super::builtin_definitions::all() {- reg.insert(def);- }- reg- }-- /// Build a registry containing built-ins plus any custom TOML- /// definitions found under `<workspace>/agents/*.toml` (and the- /// `~/.openhuman/agents/*.toml` fallback). Custom definitions- /// override built-ins on `id` collision. Files that fail to parse- /// are logged and skipped rather than aborting startup.- pub fn load(workspace: &Path) -> Result<Self> {- let mut reg = Self::builtins_only();- let custom = super::definition_loader::load_from_workspace(workspace)?;- for def in custom {- tracing::info!(- id = %def.id,- source = ?def.source,- "[agent_defs] loaded custom definition (overrides any built-in with the same id)"- );- reg.insert(def);- }-- // Re-validate the tier hierarchy after custom overrides are- // merged in — a workspace TOML can legally replace a built-in- // (same id) and is held to the same spawn-hierarchy contract- // as the bundled set. See- // [`crate::agent::registry::agents::loader::validate_tier_hierarchy`].- let snapshot: Vec<AgentDefinition> = reg.list().into_iter().cloned().collect();- crate::agent::registry::agents::validate_tier_hierarchy(&snapshot).map_err(- |e| {- anyhow::anyhow!(- "agent registry rejected after merging workspace overrides from {}: {}",- workspace.display(),- e- )- },- )?;-- Ok(reg)- }-- /// Convenience: resolve the default workspace via- /// [`crate::config::Config::load_or_init`] and load from- /// it. Built for sync CLI call sites (`openhuman agent list`,- /// future inspection tools) so they don't re-implement the Config- /// → workspace resolution dance. Must NOT be called from an- /// existing tokio runtime — construct a runtime and `block_on`.- pub async fn load_for_default_workspace() -> Result<Self> {- let config = crate::config::Config::load_or_init().await?;- Self::load(&config.workspace_dir)- }-- /// Insert (or replace) a definition by id.- pub fn insert(&mut self, def: AgentDefinition) {- let id = def.id.clone();- if self.by_id.insert(id.clone(), def).is_none() {- self.order.push(id);- }- }-- /// Look up a definition by id.- pub fn get(&self, id: &str) -> Option<&AgentDefinition> {- self.by_id.get(id)- }-- /// All definitions, in insertion order.- pub fn list(&self) -> Vec<&AgentDefinition> {- self.order- .iter()- .filter_map(|id| self.by_id.get(id))- .collect()- }-- /// Number of registered definitions.- pub fn len(&self) -> usize {- self.by_id.len()- }-- /// True when the registry has no definitions.- pub fn is_empty(&self) -> bool {- self.by_id.is_empty()- }-- // ── singleton API ──────────────────────────────────────────────────-- /// Initialise the global registry. Subsequent calls are no-ops (the- /// `OnceLock` only fires once); use [`Self::reload_global`] to refresh- /// custom definitions during development.- pub fn init_global(workspace: &Path) -> Result<()> {- let registry = Self::load(workspace)?;- match GLOBAL.set(registry) {- Ok(()) => {- tracing::info!(- "[agent_defs] global registry initialised with {} definitions",- GLOBAL.get().map(|r| r.len()).unwrap_or(0)- );- Ok(())- }- Err(_) => {- tracing::debug!("[agent_defs] global registry already initialised; ignoring");- Ok(())- }- }- }-- /// Initialise the global registry with builtins only (no workspace- /// scan). Used by tests and by callers that don't have a workspace.- pub fn init_global_builtins() -> Result<()> {- let registry = Self::builtins_only();- let _ = GLOBAL.set(registry);- Ok(())- }-- /// Borrow the global registry, if initialised.- pub fn global() -> Option<&'static Self> {- GLOBAL.get()- }-}diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rsnew file mode 100644index 0000000000..0b2d821486--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs@@ -0,0 +1,192 @@+//! Pre-turn context injection: agent-experience retrieval and the triggered+//! memory-agent block prepended to the enriched user message.++use super::super::super::types::Agent;+use crate::agent::experience::{+ prepend_experience_block, render_experience_hits, retrieve_across_stores, AgentExperienceStore,+ ExperienceQuery,+};+use crate::agent::harness;+use crate::agent::harness::definition::TriggerMemoryAgent;+use crate::agent::harness::fork_context::ParentExecutionContext;+use crate::util::truncate_with_ellipsis;++impl Agent {+ pub(in crate::agent::harness::session::turn) 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+ }+ }+ }++ pub(super) 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/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rsnew file mode 100644index 0000000000..1dbdf6660b--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs@@ -0,0 +1,601 @@+//! The tinyagents-backed chat turn driver (`run_turn_via_tinyagents_session`).+//!+//! Converts the frozen history to provider messages, runs the harness loop over+//! the agent's tools, applies the deterministic cap / final-answer fallbacks,+//! persists the transcript, and fires post-turn hooks.++use super::super::super::types::Agent;+use super::{+ checkpoint_results_from_conversation, is_empty_assistant_chat, replace_last_assistant_reply,+ stamp_tool_failures, tool_records_from_conversation,+};+use crate::agent::harness::session::turn::graph;+use crate::agent::harness::session::turn_checkpoint;+use crate::agent::hooks::{self, TurnContext};+use crate::agent::messages::{ChatMessage, ConversationMessage};+use crate::agent::progress::AgentProgress;+use crate::memory::MemoryCategory;+use crate::util::truncate_with_ellipsis;+use anyhow::Result;++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.+ pub(super) async fn run_turn_via_tinyagents_session(+ &mut self,+ user_message: &str,+ effective_model: &str,+ temperature: f64,+ max_iterations: usize,+ artifact_store: Option<+ crate::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. A resumed session's replayed prefix is folded into that same+ // history first (see below), so there is exactly one sequence to read.+ self.absorb_resumed_transcript_prefix();+ let mut messages = self.tool_dispatcher.to_provider_messages(&self.history);++ // 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::agent::multimodal::has_image_placeholders(&messages)+ {+ messages = crate::agent::multimodal::rehydrate_image_placeholders(&messages);+ }+ let messages = crate::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::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::agent::harness::turn_subagent_usage::with_turn_collector(+ graph::run_chat_turn_graph(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::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::agent::harness::definition::AgentDefinitionRegistry::global()+ .and_then(|registry| registry.get(&self.agent_definition_id))+ .map(|definition| definition.sandbox_mode)+ .unwrap_or(crate::agent::harness::definition::SandboxMode::None),+ }),+ ),+ );+ let (outcome, subagent_usage_entries) =+ crate::agent::harness::turn_dispatch_guard::with_dispatch_guard(+ crate::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,+ 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() {+ 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::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,+ 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() {+ 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 the branches above that actually deliver one+ // (normal finish, cap checkpoint, #4093 synthesized close), since each+ // is 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`.+ //+ // NOT for a turn paused on `ask_user_clarification`. The reply there is+ // the question itself, which will not carry the required block, so+ // enforcement would spend a repair model call rewriting the very text+ // the user is being asked to answer — and `replace_last_assistant_reply`+ // would persist the rewrite, so the question in the transcript would+ // stop matching the one on screen. A paused turn delivers no reply for+ // downstream parsing to depend on; the contract applies to the answer+ // this agent gives after the user replies, not to the asking (#6213+ // review).+ let required_output = if outcome.early_exit_tool.is_some() {+ None+ } else {+ self.config+ .required_output+ .as_ref()+ .map(crate::agent::tinyagents::config::required_output_from)+ };+ let reply = if let Some(contract) = required_output {+ 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::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::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::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::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::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/crates/openhuman-core/src/agent/harness/session/turn/core/resumed_prefix.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/resumed_prefix.rsnew file mode 100644index 0000000000..25f82cfb79--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/resumed_prefix.rs@@ -0,0 +1,81 @@+//! Folding a resumed session's replayed transcript prefix into the live history.++use super::super::super::types::Agent;+use crate::agent::messages::ConversationMessage;++impl Agent {+ /// Fold a resumed session's replayed transcript prefix into [`Agent::history`].+ ///+ /// A no-op unless `cached_transcript_messages` is set, which happens only on+ /// the first turn after a resume.+ pub(in crate::agent::harness::session) fn absorb_resumed_transcript_prefix(&mut self) {+ let Some(cached) = self.cached_transcript_messages.take() else {+ return;+ };+ // A resumed session's replayed prefix is **absorbed into+ // `self.history`**, not merely prepended to this one request.+ //+ // It used to be prepended: the request was built from `history`,+ // the cached prefix was `take()`n and spliced in front, and+ // `history` was left holding only the new turn. That made the+ // replayed conversation visible to exactly one request, and it cost+ // the conversation twice over — both observed on the wire, not+ // reasoned about:+ //+ // 1. **The next turn lost it.** `take()` empties the field, and+ // nothing else ever re-read the transcript, so turn 2 after a+ // restart went out with only its own messages. A ten-message+ // thread answered its next question from four. That is+ // conversational amnesia first and a cache miss second.+ // 2. **The transcript written afterwards lost it.** Persistence+ // serializes `history` (see `run_turn_impl`'s+ // `persist_session_transcript` call), so the file produced after+ // a resume held only the new turn — and `latest_for_agent` hands+ // that file to the *next* resume. Each restart truncated the+ // thread a little further.+ //+ // Absorbing it makes `history` the single source of truth again, so+ // the request, the following turn and the durable record cannot+ // disagree. The bytes on the wire for *this* request are unchanged:+ // the prefix's entries are already provider-shaped `ChatMessage`s+ // and `Chat` is rendered verbatim, exactly as the splice did.+ //+ // The leading system message(s) built for this turn are dropped in+ // favour of the prefix's own, which is the whole point of resuming —+ // the stored prompt is the KV-cache prefix the backend has already+ // tokenised, and re-rendering it is what this path exists to avoid.+ //+ // `Chat` rather than the structured `AssistantToolCalls` /+ // `ToolResults` variants is deliberate: these entries have already+ // been through `bound_cached_transcript_messages`, which snaps the+ // window past an orphaned lead and strips a trailing unpaired+ // opener, so the cycle-pairing guard has nothing left to do. Lifting+ // them into the structured variants would mean re-deriving a pairing+ // that was already decided, with a second chance to get it wrong;+ // the native envelope they carry is parsed back into real tool calls+ // at the provider seam either way (see+ // `message_convert::parse_native_assistant_envelope`, which exists+ // for precisely this seeded-transcript case).+ // `bound_cached_transcript_messages` preserves a leading system+ // message only "when present" — a resumed transcript that was never+ // seeded with one (or was truncated ahead of it) hands back a+ // `cached` prefix with no system entry at all. Dropping this turn's+ // freshly-built system message(s) unconditionally would then leave+ // the absorbed history with none, not the cached one's — so only+ // drop them when the cached prefix actually supplies a replacement.+ let cached_has_system = matches!(cached.first(), Some(msg) if msg.role == "system");+ let tail: Vec<ConversationMessage> = self+ .history+ .drain(..)+ .skip_while(|entry| {+ cached_has_system+ && matches!(entry, ConversationMessage::Chat(chat) if chat.role == "system")+ })+ .collect();+ self.history = cached+ .into_iter()+ .map(ConversationMessage::Chat)+ .chain(tail)+ .collect();+ }+}diff --git a/crates/openhuman-core/src/config/ops/loader.rs b/crates/openhuman-core/src/config/ops/loader.rsindex 8651dcc10c..2ce2aef99f 100644--- a/crates/openhuman-core/src/config/ops/loader.rs+++ b/crates/openhuman-core/src/config/ops/loader.rs@@ -10,21 +10,21 @@ pub use load::{load_config_for_workspace_with_timeout, load_config_with_timeout, reload_config_from_paths,reload_config_snapshot_with_timeout,};-pub(crate) use paths::{- active_workspace_marker_path, config_openhuman_dir, default_openhuman_dir,- env_scoped_fallback_root_dir, fallback_workspace_dir,-};+pub(crate) use paths::fallback_workspace_dir;+#[cfg(test)]+pub(crate) use paths::{active_workspace_marker_path, config_openhuman_dir, default_openhuman_dir};+#[cfg(test)]+pub(crate) use reset_local_data::reset_local_data_for_paths;+#[cfg(all(test, windows))]+pub(crate) use reset_local_data::reset_local_data_remove_error;pub use reset_local_data::{get_data_paths, get_data_paths_for_user, reset_local_data};-pub(crate) use reset_local_data::{- is_windows_file_lock_error, reset_local_data_for_paths, reset_local_data_marker_remove_error,- reset_local_data_remove_error,-};pub use runtime_flags::{agent_server_status, core_rpc_url_from_env, get_runtime_flags, set_browser_allow_all,RuntimeFlagsOut,};+#[cfg(test)]pub(crate) use runtime_flags::{- env_flag_enabled, runtime_flags, BROWSER_ALLOW_ALL_ENV, BROWSER_ALLOW_ALL_RPC_ENABLE_ENV,+ env_flag_enabled, BROWSER_ALLOW_ALL_ENV, BROWSER_ALLOW_ALL_RPC_ENABLE_ENV,};pub use snapshot::{client_config_json, get_config_snapshot, get_dashboard_settings,diff --git a/crates/openhuman-core/src/config/ops/loader/load.rs b/crates/openhuman-core/src/config/ops/loader/load.rsindex 2fe992e618..71d16f77ab 100644--- a/crates/openhuman-core/src/config/ops/loader/load.rs+++ b/crates/openhuman-core/src/config/ops/loader/load.rs@@ -5,7 +5,7 @@ use std::path::Path;use crate::config::Config;-pub(crate) const CONFIG_LOAD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);+const CONFIG_LOAD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);/// Loads persisted config with a 30s timeout.///@@ -198,4 +198,3 @@ pub(super) fn seed_and_enrich_model_registry(config: &mut Config) {log::debug!("[config] backfilled pricing on {filled} model_registry entries from catalog");}}-diff --git a/crates/openhuman-core/src/config/ops/loader/paths.rs b/crates/openhuman-core/src/config/ops/loader/paths.rsindex ec7b0f80dd..c758907c27 100644--- a/crates/openhuman-core/src/config/ops/loader/paths.rs+++ b/crates/openhuman-core/src/config/ops/loader/paths.rs@@ -13,8 +13,7 @@ pub(crate) fn fallback_workspace_dir() -> PathBuf {/// Returns the default OpenHuman configuration directory (~/.openhuman).pub(crate) fn default_openhuman_dir() -> PathBuf {- crate::config::default_root_openhuman_dir()- .unwrap_or_else(|_| env_scoped_fallback_root_dir())+ crate::config::default_root_openhuman_dir().unwrap_or_else(|_| env_scoped_fallback_root_dir())}pub(crate) fn env_scoped_fallback_root_dir() -> PathBuf {diff --git a/crates/openhuman-core/src/config/ops/loader/reset_local_data.rs b/crates/openhuman-core/src/config/ops/loader/reset_local_data.rsindex aa516c0aed..c05b66e5f3 100644--- a/crates/openhuman-core/src/config/ops/loader/reset_local_data.rs+++ b/crates/openhuman-core/src/config/ops/loader/reset_local_data.rs@@ -10,7 +10,6 @@ use super::load::load_config_with_timeout;use super::paths::{active_workspace_marker_path, config_openhuman_dir, default_openhuman_dir};use crate::rpc::RpcOutcome;-pub(crate) fn is_windows_file_lock_error(error: &std::io::Error) -> bool {cfg!(windows) && matches!(error.raw_os_error(), Some(32 | 33))}@@ -75,8 +74,7 @@ pub(crate) async fn reset_local_data_for_paths(default_openhuman_dir: &Path,) -> Result<RpcOutcome<serde_json::Value>, String> {let active_workspace_marker = active_workspace_marker_path(default_openhuman_dir);- let active_user_marker =- crate::config::active_user_marker_path(default_openhuman_dir);+ let active_user_marker = crate::config::active_user_marker_path(default_openhuman_dir);tracing::debug!(current_dir = %current_openhuman_dir.display(),default_dir = %default_openhuman_dir.display(),@@ -135,7 +133,6 @@ pub(crate) async fn reset_local_data_for_paths())}-/// Deletes all local data directories and workspace markers.////// Runs **inside the core's tokio task**, which means the running core@@ -176,8 +173,7 @@ pub async fn get_data_paths() -> Result<RpcOutcome<serde_json::Value>, String> {// inside the per-user dir. A clear removes it (to sign the current user// out) but must leave the sibling `users/<other>` dirs and the root// itself intact — see `reset_local_data_for_paths`.- let active_user_marker =- crate::config::active_user_marker_path(&default_openhuman_dir);+ let active_user_marker = crate::config::active_user_marker_path(&default_openhuman_dir);Ok(RpcOutcome::new(json!({"current_openhuman_dir": current_openhuman_dir.display().to_string(),@@ -226,8 +222,7 @@ pub async fn get_data_paths_for_user());}let default_openhuman_dir = default_openhuman_dir();- let current_openhuman_dir =- crate::config::user_openhuman_dir(&default_openhuman_dir, user_id);+ let current_openhuman_dir = crate::config::user_openhuman_dir(&default_openhuman_dir, user_id);// Defense in depth: the resolved user dir MUST be a direct child of// `<root>/users`. Catches any platform-specific `join` quirk (e.g. a// Windows drive-relative id) that slipped past the string check above,@@ -241,8 +236,7 @@ pub async fn get_data_paths_for_user());}let active_workspace_marker = active_workspace_marker_path(&default_openhuman_dir);- let active_user_marker =- crate::config::active_user_marker_path(&default_openhuman_dir);+ let active_user_marker = crate::config::active_user_marker_path(&default_openhuman_dir);// Content-free logging only: the user id and the user-scoped paths are PII// (AGENTS.md: never log secrets/PII), so emit a boolean indicator instead of// the id or the resolved dirs. The paths are still returned in the JSONdiff --git a/crates/openhuman-core/src/config/ops/loader/snapshot.rs b/crates/openhuman-core/src/config/ops/loader/snapshot.rsindex 1006bb512f..a30fde5eda 100644--- a/crates/openhuman-core/src/config/ops/loader/snapshot.rs+++ b/crates/openhuman-core/src/config/ops/loader/snapshot.rs@@ -144,7 +144,6 @@ pub async fn load_and_get_config_snapshot() -> Result<RpcOutcome<serde_json::Valget_config_snapshot(&config).await}-/// Reads dashboard settings exposed to the desktop UI.pub async fn get_dashboard_settings() -> Result<RpcOutcome<serde_json::Value>, String> {let request_id = uuid::Uuid::new_v4().to_string();