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: split oversized inherent impls
Steven Enamakela52b903396bb
diff --git a/src/openhuman/agent/harness/session/runtime.rs b/src/openhuman/agent/harness/session/runtime.rsindex 4c0575357d..282e921ec4 100644--- a/src/openhuman/agent/harness/session/runtime.rs+++ b/src/openhuman/agent/harness/session/runtime.rs@@ -24,952 +24,8 @@ use crate::openhuman::util::truncate_with_ellipsis;use anyhow::Result;use std::collections::HashSet;use std::sync::Arc;--impl Agent {- const EVENT_ERROR_MAX_CHARS: usize = 256;-- // ─────────────────────────────────────────────────────────────────- // Small accessors used by `run_single` + `turn` + sub-agent runner- // ─────────────────────────────────────────────────────────────────-- pub(super) fn event_session_id(&self) -> &str {- &self.event_session_id- }-- pub(super) fn event_channel(&self) -> &str {- &self.event_channel- }-- /// The agent definition id this session is running- /// (`"welcome"`, `"orchestrator"`, `"integrations_agent"`, …).- ///- /// Exposed so callers that build sessions via- /// [`Agent::from_config_for_agent`] can stamp the resolved id onto- /// correlation logs and progress events without reaching for the- /// source `Config`. See [`AgentBuilder::agent_definition_name`]- /// for the full list of downstream surfaces (transcript filename,- /// transcript metadata header, and `PromptContext::agent_id`) that- /// read this field.- pub fn agent_definition_name(&self) -> &str {- &self.agent_definition_name- }-- /// Returns a new `AgentBuilder`.- pub fn builder() -> AgentBuilder {- AgentBuilder::new()- }-- /// Clone the agent's model source. Used by the sub-agent runner /- /// parent-context builder to share the parent's provider instance with- /// spawned sub-agents (so they share connection pools, retry budgets, and- /// rate-limit state) — issue #4249, Phase 3 / Motion A.- pub fn turn_model_source(&self) -> crate::openhuman::agent::tinyagents::TurnModelSource {- self.turn_model_source.clone()- }-- /// Borrow the agent's tools as a slice. Used by the sub-agent runner- /// to filter the parent's tool registry per-archetype.- pub fn tools(&self) -> &[Box<dyn Tool>] {- self.tools.as_slice()- }-- /// Clone the agent's tools `Arc` for sharing with sub-agents.- pub fn tools_arc(&self) -> Arc<Vec<Box<dyn Tool>>> {- Arc::clone(&self.tools)- }-- /// Borrow the agent's tool specs (pre-serialised). Captured at- /// turn-start so sub-agents can pass byte-identical schemas to the- /// provider for prefix-cache reuse.- pub fn tool_specs(&self) -> &[ToolSpec] {- self.tool_specs.as_slice()- }-- /// Clone the agent's tool specs `Arc` for sharing with sub-agents.- pub fn tool_specs_arc(&self) -> Arc<Vec<ToolSpec>> {- Arc::clone(&self.tool_specs)- }-- #[cfg(test)]- pub(crate) fn visible_tool_names_for_test(&self) -> &std::collections::HashSet<String> {- &self.visible_tool_names- }-- #[cfg(test)]- pub(crate) fn subagent_tool_ceiling_names_for_test(- &self,- ) -> &std::collections::HashSet<String> {- &self.subagent_tool_ceiling_names- }-- /// Borrow the agent's memory backing store as an `Arc`.- pub fn memory_arc(&self) -> Arc<dyn Memory> {- Arc::clone(&self.memory)- }-- /// The full host [`Config`](crate::openhuman::config::Config) this session- /// was built with, when it was built through the factory.- ///- /// `None` on the bare-builder path (`AgentBuilder` without- /// `AgentFactory`), which is used by tests and by callers assembling a- /// session by hand. Every capability adapter that needs host config treats- /// `None` as "not available" rather than loading one itself — see- /// [`Self::host_capabilities_available`].- pub fn runtime_config(&self) -> Option<Arc<crate::openhuman::config::Config>> {- self.runtime_config.clone()- }-- /// Whether the config-dependent capability adapters can be built from this- /// session.- ///- /// Four of the ten host capabilities (`BudgetGate`, `ContextComposer`,- /// `ModelResolver`, and the policy half of `SecurityGate`) need a full- /// `Config`, which only the factory path supplies. This is the one-line- /// check a caller uses before reaching for them, so "this session cannot- /// answer that" stays distinguishable from "the capability failed" — the- /// same absence-versus-failure rule the traits themselves are built on.- pub fn host_capabilities_available(&self) -> bool {- self.runtime_config.is_some()- }-- /// OpenHuman's [`AgentMemory`](tinyagents::harness::host::AgentMemory)- /// capability over this session's memory backend.- ///- /// Built on demand rather than stored: it is a thin adapter over an `Arc`- /// the session already holds, so constructing one is a refcount bump, and- /// storing it would create a second handle that could drift from- /// `self.memory` if the backend were ever swapped.- pub fn host_agent_memory(- &self,- ) -> crate::openhuman::agent::tinyagents::host::OpenHumanAgentMemory {- crate::openhuman::agent::tinyagents::host::OpenHumanAgentMemory::new(self.memory_arc())- }-- /// OpenHuman's [`ExperienceStore`](tinyagents::harness::host::ExperienceStore)- /// capability, scoped to this session's agent profile.- ///- /// Writes go to this session's own `memory`; recall additionally consults- /// `shared_experience_memory` when the session was given one.- ///- /// That asymmetry mirrors the live turn path in `session/turn/core.rs`. For- /// a dedicated-profile session `memory` is the profile-local store and- /// `shared_experience_memory` is the global one holding unstamped records- /// from pre-profile builds — so reading both is what keeps old experience- /// reachable, while writing only to the profile-local store is what keeps- /// new records inside the profile subtree.- pub fn host_experience_store(- &self,- ) -> crate::openhuman::agent::tinyagents::host::OpenHumanExperienceStore {- crate::openhuman::agent::tinyagents::host::OpenHumanExperienceStore::with_profile(- self.memory_arc(),- self.active_profile_id.clone(),- )- .with_shared_recall_memory(self.shared_experience_memory.clone())- }-- /// The agent's working directory.- pub fn workspace_dir(&self) -> &std::path::Path {- &self.workspace_dir- }-- /// The agent's currently-configured model name (before per-turn- /// auto-classification).- pub fn model_name(&self) -> &str {- &self.model_name- }-- /// Override the base model this session runs its top-level turns on. Set- /// once before running: per-turn classification is disabled (the main agent- /// is pinned to its configured model for KV-cache stability — see the model- /// pin in `turn/core.rs`), so this sticks for the session and is not flipped- /// mid-conversation. The realtime voice harness uses it to pin a fast,- /// non-thinking model within the provider's response-time ceiling.- pub fn set_model_name(&mut self, model_name: impl Into<String>) {- self.model_name = model_name.into();- }-- /// The agent's currently-configured temperature.- pub fn temperature(&self) -> f64 {- self.temperature- }-- /// The agent's loaded workflows, if any.- pub fn workflows(&self) -> &[crate::openhuman::skills::Workflow] {- &self.workflows- }-- /// Active Composio integrations fetched at session start.- pub fn connected_integrations(- &self,- ) -> &[crate::openhuman::agent::context::prompt::ConnectedIntegration] {- &self.connected_integrations- }-- /// This session's transcript key — `"{unix_ts}_{agent_id}"`,- /// generated once at build time. Sub-agents chain this into their- /// own transcript filenames so the parent → child hierarchy is- /// visible on disk.- pub fn session_key(&self) -> &str {- &self.session_key- }-- /// The ancestor chain of session keys for a sub-agent, joined with- /// `__`. `None` for a root session. Root + prefix together produce- /// the full transcript stem.- pub fn session_parent_prefix(&self) -> Option<&str> {- self.session_parent_prefix.as_deref()- }-- /// Replace the agent's connected integrations (e.g. from a cached- /// fetch result when the agent was built outside the normal turn loop).- pub fn set_connected_integrations(- &mut self,- integrations: Vec<crate::openhuman::agent::context::prompt::ConnectedIntegration>,- ) {- self.connected_integrations = integrations;- self.connected_integrations_initialized = true;- self.last_seen_integrations_hash =- crate::openhuman::integrations::composio::connected_set_hash(- &self.connected_integrations,- );- }-- /// The agent's runtime config snapshot.- pub fn agent_config(&self) -> &crate::openhuman::config::AgentConfig {- &self.config- }-- /// Override the agent's tool-iteration cap after construction.- ///- /// Issue #4868 — `build_session_agent_inner` now stamps every agent with- /// its `AgentDefinition::effective_max_iterations()`, which is the correct- /// behavior for direct-invocation call sites. A handful of callers need a- /// *different* cap than the definition's declared budget (e.g. long-running- /// workflow/task-dispatcher runs that intentionally exceed any single- /// agent's normal budget). Those callers should apply their override- /// AFTER construction via this setter, so the shared definition-cap logic- /// in the builder doesn't get silently clobbered by pre-construction- /// mutations (and vice versa).- pub fn set_max_tool_iterations(&mut self, cap: usize) {- self.config.max_tool_iterations = cap;- }-- /// Returns the current conversation history.- pub fn history(&self) -> &[ConversationMessage] {- &self.history- }-- pub fn set_event_context(&mut self, session_id: impl Into<String>, channel: impl Into<String>) {- self.event_session_id = session_id.into();- self.event_channel = channel.into();- self.rebuild_tool_policy_session();- }-- /// Override the agent definition name used for session transcript- /// file paths. Callers (e.g. the web channel) use this to scope- /// transcripts per thread so each conversation thread gets its own- /// transcript namespace instead of sharing one by agent type.- ///- /// Also rebuilds [`Self::session_key`] so the next call to- /// `persist_session_transcript` writes to a path keyed by the new- /// name. Without this, persist would keep using the builder-time- /// name (e.g. `"orchestrator"`) while- /// `find_latest_transcript` searches for the post-rename name (e.g.- /// `"orchestrator_thread-6ad6d"`), and resume on cold boot would- /// silently miss every prior transcript — the LLM would then run- /// each new turn with no conversation history.- pub fn set_agent_definition_name(&mut self, name: impl Into<String>) {- let name = name.into();- let sanitized: String = name- .chars()- .map(|c| {- if c.is_ascii_alphanumeric() || c == '_' || c == '-' {- c- } else {- '_'- }- })- .collect();- // Preserve the original unix-timestamp prefix from the builder- // so sub-agent spawn collisions remain impossible. Falls back- // to "0" if the existing key is in an unexpected shape.- let prefix = self- .session_key- .split_once('_')- .map(|(p, _)| p)- .filter(|p| !p.is_empty())- .unwrap_or("0");- self.session_key = format!("{prefix}_{sanitized}");- self.agent_definition_name = name;- self.rebuild_tool_policy_session();- }-- /// Attach a progress event sender for real-time turn updates.- ///- /// When set, the turn loop emits [`AgentProgress`] events so- /// callers (e.g. the web channel) can surface live tool-call and- /// iteration updates to the UI. Pass `None` to disable.- pub fn set_on_progress(- &mut self,- tx: Option<tokio::sync::mpsc::Sender<crate::openhuman::agent::progress::AgentProgress>>,- ) {- self.on_progress = tx;- }-- /// Bind this session's acting tools (shell / file / git) to `descriptor`'s- /// root as their default working directory.- ///- /// The post-build counterpart of- /// [`AgentBuilder::workspace_descriptor`](crate::openhuman::agent::AgentBuilder::workspace_descriptor),- /// for callers that construct the agent through- /// [`Agent::from_config`](crate::openhuman::agent::Agent::from_config) and- /// therefore never see the builder — notably the per-turn `cwd` of- /// [`agent_chat`](crate::openhuman::inference::local::ops::agent_chat).- ///- /// The descriptor is threaded onto the turn's run context, so it also- /// propagates to sub-agents spawned from this session (the same deliberate- /// isolation the per-profile descriptor has). `None` restores the shared- /// `action_dir` cwd.- ///- /// This only moves the *default* cwd: what the session may read and write is- /// still decided by its [`SecurityPolicy`](crate::openhuman::security::SecurityPolicy),- /// so a caller that wants tools rooted somewhere new must build the agent- /// from a config whose `action_dir` already permits it.- pub fn set_workspace_descriptor(- &mut self,- descriptor: Option<tinyagents::harness::workspace::WorkspaceDescriptor>,- ) {- self.workspace_descriptor = descriptor;- }-- /// Attach an active-run queue for mid-turn steering.- pub fn set_run_queue(- &mut self,- rq: Option<std::sync::Arc<crate::openhuman::agent::harness::run_queue::RunQueue>>,- ) {- self.run_queue = rq;- }-- /// Restrict which tools the main agent can see and call for this- /// session. An empty set restores the default "all visible" behavior,- /// still subject to the configured channel permission policy.- pub fn set_visible_tool_names(&mut self, names: HashSet<String>) {- self.visible_tool_names = names;- self.rebuild_tool_policy_session();- }-- /// Remove `names` from the main agent's callable set for this session,- /// leaving every other currently-visible tool untouched.- ///- /// The hidden names resolve to `Deny` at the tool-call boundary (via the- /// rebuilt [`ToolPolicySession`]), not merely absent from the prompt — a- /// hard execution guarantee even if the model requests the tool anyway.- ///- /// When the session currently has *no* visible-tool filter (empty set =- /// "all visible"), the filter is first seeded from every registered tool- /// spec so hiding actually **restricts** the set rather than no-opping into- /// the still-"all visible" empty state. Used by callers that need to drop a- /// specific dangerous tool from an otherwise-unchanged belt (e.g. the- /// `flows_build` builder path dropping the live-run `run_flow` tool).- ///- /// Caveat: because an empty set is the "all visible" sentinel, hiding *every*- /// remaining tool collapses back to "all visible". Callers use this to drop- /// a handful of tools from a much larger belt, where that can't happen.- pub fn hide_tools(&mut self, names: &[&str]) {- if self.visible_tool_names.is_empty() {- self.visible_tool_names = self- .tool_specs- .iter()- .map(|spec| spec.name.clone())- .collect();- }- for name in names {- self.visible_tool_names.remove(*name);- }- // Seeding from `tool_specs` above materialises the "all visible"- // sentinel into a concrete set, which would re-admit packed tools that- // the builder withheld. Re-apply the withholding.- crate::openhuman::tools::toolpacks::strip_packed_from_visible(- &mut self.visible_tool_names,- &self.agent_definition_name,- );- self.rebuild_tool_policy_session();- }-- pub(super) fn rebuild_tool_policy_session(&mut self) {- self.tool_policy_session = ToolPolicyEngine::build_session(- &self.agent_definition_name,- &self.event_channel,- "session",- &self.config.channel_permissions,- self.tools.as_slice(),- &self.visible_tool_names,- );- let visible_specs = super::builder::visible_tool_specs_for_policy(- self.tool_specs.as_slice(),- &self.visible_tool_names,- &self.tool_policy_session,- );- self.visible_tool_specs = Arc::new(super::builder::dedup_visible_tool_specs(visible_specs));- }-- /// Clears the agent's conversation history.- pub fn clear_history(&mut self) {- self.history.clear();- }-- /// Set the overrides applied to the **next** [`Self::turn`] call.- ///- /// The overrides are consumed at the top of the next turn (they apply to a- /// single turn, then reset to the default), so a caller running a chat /- /// small-talk turn calls this immediately before [`Self::turn`]. Callers- /// that never touch this get the unchanged full-agentic behaviour. See- /// [`TurnOverrides`](super::types::TurnOverrides) for the fields and the- /// motivating case (#1725: a bare greeting must not run the task loop nor- /// inherit a prior task's goal / tools / memory).- pub fn set_next_turn_overrides(&mut self, overrides: super::types::TurnOverrides) {- self.pending_turn_overrides = overrides;- }-- /// Seed the next turn's LLM context from an authoritative message- /// log (e.g. the web channel's per-thread conversation JSONL).- ///- /// Mirrors what [`Self::try_load_session_transcript`] does on a- /// transcript-file hit, but sources from a caller-supplied list so- /// resume works even when no transcript file exists for this- /// agent name (the typical situation right after the- /// `set_agent_definition_name` / `session_key` rename fix landed —- /// existing transcripts are written under the old name).- ///- /// `messages` is `(role, content)` pairs in chronological order.- /// Recognised roles: `"user"`, `"agent"` / `"assistant"`. Any- /// trailing user message that exactly matches `current_user_message`- /// is dropped — the caller is about to pass that text to- /// [`Self::run_single`], which will append it to history itself, so- /// keeping it here would duplicate it on the wire.- ///- /// No-ops if the agent already has a history or a cached transcript- /// (i.e. the per-process session cache is warm). Intended only for- /// cold-boot priming.- pub fn seed_resume_from_messages(- &mut self,- messages: Vec<(String, String)>,- current_user_message: &str,- ) -> Result<()> {- if !self.history.is_empty() || self.cached_transcript_messages.is_some() {- return Ok(());- }- let mut prior = messages;- if let Some(last) = prior.last() {- if last.0 == "user" && last.1.trim() == current_user_message.trim() {- prior.pop();- }- }- if prior.is_empty() {- return Ok(());- }-- // Build the system prompt fresh — there's no persisted prefix- // to preserve here, and learned-context decoration is skipped- // intentionally so this fallback path stays synchronous and- // doesn't fan out to the memory store on every cold-boot turn.- let learned = crate::openhuman::agent::prompts::LearnedContextData::default();- let system_prompt = self.build_system_prompt(learned)?;-- let mut cached: Vec<crate::openhuman::agent::messages::ChatMessage> =- Vec::with_capacity(prior.len() + 1);- cached.push(crate::openhuman::agent::messages::ChatMessage::system(- system_prompt,- ));- for (role, content) in prior {- let chat = match role.as_str() {- "user" => crate::openhuman::agent::messages::ChatMessage::user(content),- "agent" | "assistant" => {- crate::openhuman::agent::messages::ChatMessage::assistant(content)- }- // Fall back to user role for unknown senders rather than- // dropping the message — losing context is worse than- // mislabelling a system/tool message.- _ => crate::openhuman::agent::messages::ChatMessage::user(content),- };- cached.push(chat);- }-- let cached_len_before = cached.len();- let bounded = self.bound_cached_transcript_messages(cached);- if bounded.len() < cached_len_before {- log::warn!(- "[agent] seed_resume_from_messages — bounded cached transcript {} → {} (max_history_messages={})",- cached_len_before,- bounded.len(),- self.config.max_history_messages- );- }- log::info!(- "[agent] seed_resume_from_messages — primed cached transcript with {} prior messages",- bounded.len().saturating_sub(1)- );- self.cached_transcript_messages = Some(bounded);- Ok(())- }-- /// Cold-boot resume for the web-chat path: pre-populate this session's- /// LLM context from the **full-fidelity** `session_raw/{stem}.jsonl`- /// transcript for `thread_id`.- ///- /// This is the high-fidelity counterpart to- /// [`Self::seed_resume_from_messages`]. That fallback sources lossy- /// `(sender, content)` prose from the conversation log, so it drops every- /// tool call, tool-role result, and reasoning block — after an app restart- /// the model then "forgets" all its tool interactions. This path instead- /// routes thread → transcript via- /// [`transcript::find_root_transcript_for_thread`] and reuses the exact- /// [`transcript::read_transcript`] +- /// [`Self::bound_cached_transcript_messages`] machinery as- /// [`Self::try_load_session_transcript`], so `tool_calls`, `role:"tool"`- /// messages, and `reasoning_content` all survive the round-trip. The only- /// difference from `try_load_session_transcript` is the lookup key (thread- /// id vs. per-thread agent name), so a thread whose transcript was written- /// under a differently-scoped agent name still resumes.- ///- /// Returns `true` when a transcript was found, loaded, and seeded into- /// `cached_transcript_messages`; `false` (a no-op) when the agent is already- /// warm, no root transcript exists for the thread, the transcript is empty,- /// or it fails to parse — the caller then falls back to prose-pair seeding.- ///- /// Best-effort like `try_load_session_transcript`: read/parse failures are- /// logged and reported as `false` rather than propagated. The current turn's- /// user message is appended later by [`Self::run_single`] / `turn`, so it is- /// intentionally absent from the loaded prefix — no dedup is needed here (the- /// on-disk transcript ends at the previous completed turn).- ///- /// Goes through the S4 seam like `try_load_session_transcript` (see its doc- /// comment for why the read is `read_session` and not- /// `ChatHistory::messages()`), via the locator's `root_for_thread` — the- /// lookup that resolves by `_meta.thread_id` across *root* transcripts- /// only. That disambiguation is why it is a locator method rather than- /// anything a stem-bound handle could offer: several transcripts share one- /// thread id (every sub-agent spawned within it does).- pub fn seed_resume_from_thread_transcript(&mut self, thread_id: &str) -> bool {- if !self.history.is_empty() || self.cached_transcript_messages.is_some() {- log::debug!(- "[web-channel] seed_resume_from_thread_transcript no-op — agent already warm \- (history_len={}, cached={}) thread={thread_id}",- self.history.len(),- self.cached_transcript_messages.is_some()- );- return false;- }-- // The thread's conversation belongs to the THREAD, not the active- // profile: the locator resolves cross-dir, newest-wins across the- // shared `session_raw/` and every profile-scoped `session_raw-<id>/`- // (#5351), so switching profile mid-thread continues the same- // conversation. See `FileTranscriptLocator::root_for_thread` for why- // this must not be own-dir-first.- let Some(handle) = self.session_locator().root_for_thread(thread_id) else {- log::debug!(- "[web-channel] no root session_raw transcript for thread={thread_id} in any \- (shared or profile-scoped) session_raw dir — falling back to \- conversation-log prose seeding"- );- return false;- };- let path = handle.path().to_path_buf();-- log::info!(- "[web-channel] cold-boot resume — loading full-fidelity transcript for \- thread={thread_id} path={}",- path.display()- );-- match handle.read_session() {- // `Ok(None)` (file vanished between discovery and read) folds into- // the same empty-transcript branch, so the prose-seeding fallback- // triggers identically.- Ok(None) => {- log::debug!(- "[web-channel] root transcript for thread={thread_id} is empty — \- falling back to prose seeding"- );- false- }- Ok(Some(session)) => {- if session.messages.is_empty() {- log::debug!(- "[web-channel] root transcript for thread={thread_id} is empty — \- falling back to prose seeding"- );- return false;- }- let loaded_count = session.messages.len();- // Count the tool-role results carried into the resumed prefix —- // the fidelity the prose fallback would have silently dropped.- let tool_result_msgs = session.messages.iter().filter(|m| m.role == "tool").count();- let bounded = self.bound_cached_transcript_messages(session.messages);- if bounded.len() < loaded_count {- log::warn!(- "[web-channel] resume prefix trimmed from {} to {} messages \- (max_history_messages={}) for thread={thread_id}",- loaded_count,- bounded.len(),- self.config.max_history_messages- );- }- log::info!(- "[web-channel] cold-boot resume — primed {} transcript message(s) \- ({} tool-role result(s) preserved) for thread={thread_id}",- bounded.len(),- tool_result_msgs- );- self.cached_transcript_messages = Some(bounded);- true- }- Err(err) => {- log::warn!(- "[web-channel] failed to parse root transcript {} for thread={thread_id}: \- {err} — falling back to prose seeding",- path.display()- );- false- }- }- }-- /// Drain and return memory citations collected for the latest completed turn.- ///- /// Async because collection runs concurrently with the turn rather than- /// ahead of it (see `Agent::pending_citations`); this joins whatever is- /// still in flight. By the time a caller asks, the model round-trip has- /// already happened, so the recall has normally finished and this does not- /// wait.- pub async fn take_last_turn_citations(- &mut self,- ) -> Vec<crate::openhuman::memory::agent::memory_loader::MemoryCitation> {- if let Some(handle) = self.pending_citations.take() {- match handle.await {- Ok(citations) => self.last_turn_citations = citations,- // A panicked or aborted collection must not fail the turn — the- // citations are decorative, the reply is not.- Err(err) => {- log::warn!("[agent_loop] citation task did not complete: {err}");- self.last_turn_citations.clear();- }- }- }- std::mem::take(&mut self.last_turn_citations)- }-- /// Borrow the holistic token/cost/context totals for the latest completed- /// turn (parent + sub-agents) **without consuming them**. `None` until a- /// turn has run.- ///- /// This is the public, non-draining counterpart to- /// [`take_last_turn_usage_totals`](Self::take_last_turn_usage_totals): a- /// downstream crate embedding OpenHuman as a library (e.g. the OpenCompany- /// hosting platform's cost-metering hook) can read per-turn token and USD- /// totals after [`Agent::turn`](crate::openhuman::agent::Agent) returns,- /// while leaving the value in place for the web-channel drain path.- pub fn last_turn_usage(- &self,- ) -> Option<&crate::openhuman::agent::harness::turn_subagent_usage::LastTurnUsage> {- self.last_turn_usage_totals.as_ref()- }-- /// Drain and return the holistic token/cost/context totals for the latest- /// completed turn (parent + sub-agents). `None` until a turn has run.- /// Consumed by web-channel delivery to populate the `chat_done` usage fields.- pub(crate) fn take_last_turn_usage_totals(- &mut self,- ) -> Option<crate::openhuman::agent::harness::turn_subagent_usage::LastTurnUsage> {- self.last_turn_usage_totals.take()- }-- /// Whether the most recently completed [`Self::turn`] / [`Self::run_single`]- /// paused because it hit `max_tool_iterations`, rather than finishing- /// naturally (see the field doc on `last_turn_hit_cap`). `false` before- /// any turn has run. Not draining — unlike the usage totals above, a- /// caller may reasonably check this more than once per turn.- pub fn last_turn_hit_cap(&self) -> bool {- self.last_turn_hit_cap- }-- // ─────────────────────────────────────────────────────────────────- // Static helpers for turn parsing + telemetry- // ─────────────────────────────────────────────────────────────────-- pub(super) fn count_iterations(messages: &[ConversationMessage]) -> usize {- messages- .iter()- .filter(|message| matches!(message, ConversationMessage::AssistantToolCalls { .. }))- .count()- + 1- }-- fn conversation_message_eq(left: &ConversationMessage, right: &ConversationMessage) -> bool {- serde_json::to_string(left).ok() == serde_json::to_string(right).ok()- }-- fn message_slice_eq(left: &[ConversationMessage], right: &[ConversationMessage]) -> bool {- left.len() == right.len()- && left- .iter()- .zip(right.iter())- .all(|(left, right)| Self::conversation_message_eq(left, right))- }-- pub(super) fn new_entries_for_turn<'a>(- history_snapshot: &[ConversationMessage],- current_history: &'a [ConversationMessage],- ) -> &'a [ConversationMessage] {- let common_prefix_len = history_snapshot- .iter()- .zip(current_history.iter())- .take_while(|(left, right)| Self::conversation_message_eq(left, right))- .count();-- if common_prefix_len == history_snapshot.len() {- return ¤t_history[common_prefix_len..];- }-- let max_overlap = history_snapshot.len().min(current_history.len());- for overlap in (0..=max_overlap).rev() {- let snapshot_suffix = &history_snapshot[history_snapshot.len() - overlap..];- let current_prefix = ¤t_history[..overlap];- if Self::message_slice_eq(snapshot_suffix, current_prefix) {- return ¤t_history[overlap..];- }- }-- current_history- }-- pub(super) fn sanitize_event_error_message(err: &anyhow::Error) -> String {- let kind = match err.downcast_ref::<AgentError>() {- Some(AgentError::ProviderError { .. }) => Some("provider_error"),- Some(AgentError::ContextLimitExceeded { .. }) => Some("context_limit_exceeded"),- Some(AgentError::ToolExecutionError { .. }) => Some("tool_execution_error"),- Some(AgentError::CostBudgetExceeded { .. }) => Some("cost_budget_exceeded"),- Some(AgentError::MaxIterationsExceeded { .. }) => Some("max_iterations_exceeded"),- Some(AgentError::EmptyProviderResponse { .. }) => Some("empty_provider_response"),- Some(AgentError::CompactionFailed { .. }) => Some("compaction_failed"),- Some(AgentError::PermissionDenied { .. }) => Some("permission_denied"),- Some(AgentError::RegistryValidationFailed { .. }) => Some("registry_validation_failed"),- Some(AgentError::Other(_)) | None => None,- };-- if let Some(kind) = kind {- return kind.to_string();- }-- let scrubbed = provider::sanitize_api_error(&err.to_string())- .replace(['\n', '\r', '\t'], " ")- .split_whitespace()- .collect::<Vec<_>>()- .join(" ");- truncate_with_ellipsis(&scrubbed, Self::EVENT_ERROR_MAX_CHARS)- }-- /// Injects unique IDs into tool calls that are missing them.- ///- /// This is necessary for some tool dispatchers to correctly track and- /// associate results.- pub(super) fn with_fallback_tool_call_ids(- mut parsed_calls: Vec<ParsedToolCall>,- iteration: usize,- ) -> Vec<ParsedToolCall> {- for (idx, call) in parsed_calls.iter_mut().enumerate() {- if call.tool_call_id.is_none() {- call.tool_call_id = Some(format!("parsed-{}-{}", iteration + 1, idx + 1));- }- }- parsed_calls- }-- /// Converts parsed tool calls into the provider-standard `ToolCall` format.- ///- /// If the provider response already contains native tool calls, they are- /// returned as-is.- pub(super) fn persisted_tool_calls_for_history(- response: &crate::openhuman::inference::provider::ChatResponse,- parsed_calls: &[ParsedToolCall],- iteration: usize,- ) -> Vec<ToolCall> {- if !response.tool_calls.is_empty() {- return response.tool_calls.clone();- }-- parsed_calls- .iter()- .enumerate()- .map(|(idx, call)| ToolCall {- id: call- .tool_call_id- .clone()- .unwrap_or_else(|| format!("parsed-{}-{}", iteration + 1, idx + 1)),- name: call.name.clone(),- arguments: call.arguments.to_string(),- // Prompt-based tool calls carry no provider extra_content.- extra_content: None,- })- .collect()- }-- // ─────────────────────────────────────────────────────────────────- // Run helpers — single-shot and interactive loops- // ─────────────────────────────────────────────────────────────────-- /// Runs a single turn with the given message and returns the response.- ///- /// This is the primary high-level method for programmatic interaction with the agent.- /// It wraps the core `turn` logic with telemetry events (`AgentTurnStarted`,- /// `AgentTurnCompleted`) and error sanitization.- pub async fn run_single(&mut self, message: &str) -> Result<String> {- let guard = enforce_prompt_input(- message,- PromptEnforcementContext {- source: "agent.runtime.run_single",- request_id: None,- user_id: Some(self.event_channel()),- session_id: Some(self.event_session_id()),- },- );- if !matches!(guard.action, PromptEnforcementAction::Allow) {- let user_message = match guard.action {- PromptEnforcementAction::Allow => "Message accepted.",- PromptEnforcementAction::Blocked => "Prompt blocked by security policy.",- PromptEnforcementAction::ReviewBlocked => {- "Prompt flagged for security review and was not processed."- }- };- let action_tag = match guard.action {- PromptEnforcementAction::Allow => "allow",- PromptEnforcementAction::Blocked => "blocked",- PromptEnforcementAction::ReviewBlocked => "review_blocked",- };- crate::core::observability::report_error(- user_message,- "agent",- "prompt_injection_blocked",- &[- ("session_id", self.event_session_id()),- ("channel", self.event_channel()),- ("action", action_tag),- ],- );- BUS.publish(DomainEvent::AgentError {- session_id: self.event_session_id().to_string(),- message: user_message.to_string(),- recoverable: true,- });- return Err(anyhow::anyhow!(user_message));- }-- let history_snapshot = self.history.clone();- BUS.publish(DomainEvent::AgentTurnStarted {- session_id: self.event_session_id().to_string(),- channel: self.event_channel().to_string(),- });-- match self.turn(message).await {- Ok(response) => {- let new_entries = Self::new_entries_for_turn(&history_snapshot, &self.history);- BUS.publish(DomainEvent::AgentTurnCompleted {- session_id: self.event_session_id().to_string(),- text_chars: response.chars().count(),- iterations: Self::count_iterations(new_entries),- });- Ok(response)- }- Err(err) => {- let sanitized_message = Self::sanitize_event_error_message(&err);- // Some typed `AgentError` variants represent agent / user /- // provider state that the UI already surfaces — the- // max-tool-iterations cap (OPENHUMAN-TAURI-99 / -98,- // chat-rendered "Error: Agent exceeded maximum tool- // iterations") and the empty-provider-response degeneracy- // (TAURI-RUST-4JX, "The model returned an empty response.- // Please try again."). Skip the Sentry funnel for both- // and emit a structured `log::info!` instead. The- // suppressed set is owned by `AgentError::skips_sentry()`- // so the policy stays in one place.- //- // Other agent errors go through `report_error_or_expected`- // so OPENHUMAN-TAURI-5Z and the budget-noise cluster —- // upstream transient HTTP and backend budget-exhausted 400s- // that bubble up under `domain=agent` and escape the- // `domain=llm_provider` filter — get demoted to a- // warn/info-level breadcrumb without losing genuine bugs.- // `Err` propagation, the `AgentError` domain event, and- // downstream `recoverable=false` semantics are preserved.- let skips_sentry = err- .downcast_ref::<AgentError>()- .is_some_and(AgentError::skips_sentry);- if skips_sentry {- log::info!(- target: "agent",- "[agent.run_single] suppressed Sentry emission for user-state agent error \- session_id={} channel={} error_kind={} message={}",- self.event_session_id(),- self.event_channel(),- sanitized_message.as_str(),- err- );- } else {- crate::core::observability::report_error_or_expected(- &err,- "agent",- "run_single",- &[- ("session_id", self.event_session_id()),- ("channel", self.event_channel()),- ("error_kind", sanitized_message.as_str()),- ],- );- }- BUS.publish(DomainEvent::AgentError {- session_id: self.event_session_id().to_string(),- message: sanitized_message,- recoverable: false,- });- Err(err)- }- }- }-- /// Runs an interactive CLI loop, reading from standard input and printing to standard output.- ///- /// This method starts a persistent session where the user can chat with the agent- /// directly from the console. It handles input until a termination command- /// (e.g., `/quit`) is received.- pub async fn run_interactive(&mut self) -> Result<()> {- println!("🦀 OpenHuman Interactive Mode");- println!("Type /quit to exit.\n");-- let (tx, mut rx) = tokio::sync::mpsc::channel(32);- let cli = crate::openhuman::channels::CliChannel::new();-- let listen_handle = tokio::spawn(async move {- let _ = crate::openhuman::channels::Channel::listen(&cli, tx).await;- });-- while let Some(msg) = rx.recv().await {- match self.run_single(&msg.content).await {- Ok(response) => println!("\n{response}\n"),- Err(e) => {- // `run_single` already publishes `AgentError` and- // sanitises the payload; surface a concise line here- // for the CLI user and continue the loop.- eprintln!("\nError: {e}\n");- continue;- }- }- }-- listen_handle.abort();- Ok(())- }-}+include!("runtime_impl_01_part_01.rs");+include!("runtime_impl_01_part_02.rs");#[cfg(test)]#[path = "runtime_tests.rs"]diff --git a/src/openhuman/agent/harness/session/runtime_impl_01_part_01.rs b/src/openhuman/agent/harness/session/runtime_impl_01_part_01.rsnew file mode 100644index 0000000000..7f1f191a80--- /dev/null+++ b/src/openhuman/agent/harness/session/runtime_impl_01_part_01.rs@@ -0,0 +1,637 @@++impl Agent {++ const EVENT_ERROR_MAX_CHARS: usize = 256;++ // ─────────────────────────────────────────────────────────────────+ // Small accessors used by `run_single` + `turn` + sub-agent runner+ // ─────────────────────────────────────────────────────────────────++ pub(super) fn event_session_id(&self) -> &str {+ &self.event_session_id+ }++ pub(super) fn event_channel(&self) -> &str {+ &self.event_channel+ }++ /// The agent definition id this session is running+ /// (`"welcome"`, `"orchestrator"`, `"integrations_agent"`, …).+ ///+ /// Exposed so callers that build sessions via+ /// [`Agent::from_config_for_agent`] can stamp the resolved id onto+ /// correlation logs and progress events without reaching for the+ /// source `Config`. See [`AgentBuilder::agent_definition_name`]+ /// for the full list of downstream surfaces (transcript filename,+ /// transcript metadata header, and `PromptContext::agent_id`) that+ /// read this field.+ pub fn agent_definition_name(&self) -> &str {+ &self.agent_definition_name+ }++ /// Returns a new `AgentBuilder`.+ pub fn builder() -> AgentBuilder {+ AgentBuilder::new()+ }++ /// Clone the agent's model source. Used by the sub-agent runner /+ /// parent-context builder to share the parent's provider instance with+ /// spawned sub-agents (so they share connection pools, retry budgets, and+ /// rate-limit state) — issue #4249, Phase 3 / Motion A.+ pub fn turn_model_source(&self) -> crate::openhuman::agent::tinyagents::TurnModelSource {+ self.turn_model_source.clone()+ }++ /// Borrow the agent's tools as a slice. Used by the sub-agent runner+ /// to filter the parent's tool registry per-archetype.+ pub fn tools(&self) -> &[Box<dyn Tool>] {+ self.tools.as_slice()+ }++ /// Clone the agent's tools `Arc` for sharing with sub-agents.+ pub fn tools_arc(&self) -> Arc<Vec<Box<dyn Tool>>> {+ Arc::clone(&self.tools)+ }++ /// Borrow the agent's tool specs (pre-serialised). Captured at+ /// turn-start so sub-agents can pass byte-identical schemas to the+ /// provider for prefix-cache reuse.+ pub fn tool_specs(&self) -> &[ToolSpec] {+ self.tool_specs.as_slice()+ }++ /// Clone the agent's tool specs `Arc` for sharing with sub-agents.+ pub fn tool_specs_arc(&self) -> Arc<Vec<ToolSpec>> {+ Arc::clone(&self.tool_specs)+ }++ #[cfg(test)]+ pub(crate) fn visible_tool_names_for_test(&self) -> &std::collections::HashSet<String> {+ &self.visible_tool_names+ }++ #[cfg(test)]+ pub(crate) fn subagent_tool_ceiling_names_for_test(+ &self,+ ) -> &std::collections::HashSet<String> {+ &self.subagent_tool_ceiling_names+ }++ /// Borrow the agent's memory backing store as an `Arc`.+ pub fn memory_arc(&self) -> Arc<dyn Memory> {+ Arc::clone(&self.memory)+ }++ /// The full host [`Config`](crate::openhuman::config::Config) this session+ /// was built with, when it was built through the factory.+ ///+ /// `None` on the bare-builder path (`AgentBuilder` without+ /// `AgentFactory`), which is used by tests and by callers assembling a+ /// session by hand. Every capability adapter that needs host config treats+ /// `None` as "not available" rather than loading one itself — see+ /// [`Self::host_capabilities_available`].+ pub fn runtime_config(&self) -> Option<Arc<crate::openhuman::config::Config>> {+ self.runtime_config.clone()+ }++ /// Whether the config-dependent capability adapters can be built from this+ /// session.+ ///+ /// Four of the ten host capabilities (`BudgetGate`, `ContextComposer`,+ /// `ModelResolver`, and the policy half of `SecurityGate`) need a full+ /// `Config`, which only the factory path supplies. This is the one-line+ /// check a caller uses before reaching for them, so "this session cannot+ /// answer that" stays distinguishable from "the capability failed" — the+ /// same absence-versus-failure rule the traits themselves are built on.+ pub fn host_capabilities_available(&self) -> bool {+ self.runtime_config.is_some()+ }++ /// OpenHuman's [`AgentMemory`](tinyagents::harness::host::AgentMemory)+ /// capability over this session's memory backend.+ ///+ /// Built on demand rather than stored: it is a thin adapter over an `Arc`+ /// the session already holds, so constructing one is a refcount bump, and+ /// storing it would create a second handle that could drift from+ /// `self.memory` if the backend were ever swapped.+ pub fn host_agent_memory(+ &self,+ ) -> crate::openhuman::agent::tinyagents::host::OpenHumanAgentMemory {+ crate::openhuman::agent::tinyagents::host::OpenHumanAgentMemory::new(self.memory_arc())+ }++ /// OpenHuman's [`ExperienceStore`](tinyagents::harness::host::ExperienceStore)+ /// capability, scoped to this session's agent profile.+ ///+ /// Writes go to this session's own `memory`; recall additionally consults+ /// `shared_experience_memory` when the session was given one.+ ///+ /// That asymmetry mirrors the live turn path in `session/turn/core.rs`. For+ /// a dedicated-profile session `memory` is the profile-local store and+ /// `shared_experience_memory` is the global one holding unstamped records+ /// from pre-profile builds — so reading both is what keeps old experience+ /// reachable, while writing only to the profile-local store is what keeps+ /// new records inside the profile subtree.+ pub fn host_experience_store(+ &self,+ ) -> crate::openhuman::agent::tinyagents::host::OpenHumanExperienceStore {+ crate::openhuman::agent::tinyagents::host::OpenHumanExperienceStore::with_profile(+ self.memory_arc(),+ self.active_profile_id.clone(),+ )+ .with_shared_recall_memory(self.shared_experience_memory.clone())+ }++ /// The agent's working directory.+ pub fn workspace_dir(&self) -> &std::path::Path {+ &self.workspace_dir+ }++ /// The agent's currently-configured model name (before per-turn+ /// auto-classification).+ pub fn model_name(&self) -> &str {+ &self.model_name+ }++ /// Override the base model this session runs its top-level turns on. Set+ /// once before running: per-turn classification is disabled (the main agent+ /// is pinned to its configured model for KV-cache stability — see the model+ /// pin in `turn/core.rs`), so this sticks for the session and is not flipped+ /// mid-conversation. The realtime voice harness uses it to pin a fast,+ /// non-thinking model within the provider's response-time ceiling.+ pub fn set_model_name(&mut self, model_name: impl Into<String>) {+ self.model_name = model_name.into();+ }++ /// The agent's currently-configured temperature.+ pub fn temperature(&self) -> f64 {+ self.temperature+ }++ /// The agent's loaded workflows, if any.+ pub fn workflows(&self) -> &[crate::openhuman::skills::Workflow] {+ &self.workflows+ }++ /// Active Composio integrations fetched at session start.+ pub fn connected_integrations(+ &self,+ ) -> &[crate::openhuman::agent::context::prompt::ConnectedIntegration] {+ &self.connected_integrations+ }++ /// This session's transcript key — `"{unix_ts}_{agent_id}"`,+ /// generated once at build time. Sub-agents chain this into their+ /// own transcript filenames so the parent → child hierarchy is+ /// visible on disk.+ pub fn session_key(&self) -> &str {+ &self.session_key+ }++ /// The ancestor chain of session keys for a sub-agent, joined with+ /// `__`. `None` for a root session. Root + prefix together produce+ /// the full transcript stem.+ pub fn session_parent_prefix(&self) -> Option<&str> {+ self.session_parent_prefix.as_deref()+ }++ /// Replace the agent's connected integrations (e.g. from a cached+ /// fetch result when the agent was built outside the normal turn loop).+ pub fn set_connected_integrations(+ &mut self,+ integrations: Vec<crate::openhuman::agent::context::prompt::ConnectedIntegration>,+ ) {+ self.connected_integrations = integrations;+ self.connected_integrations_initialized = true;+ self.last_seen_integrations_hash =+ crate::openhuman::integrations::composio::connected_set_hash(+ &self.connected_integrations,+ );+ }++ /// The agent's runtime config snapshot.+ pub fn agent_config(&self) -> &crate::openhuman::config::AgentConfig {+ &self.config+ }++ /// Override the agent's tool-iteration cap after construction.+ ///+ /// Issue #4868 — `build_session_agent_inner` now stamps every agent with+ /// its `AgentDefinition::effective_max_iterations()`, which is the correct+ /// behavior for direct-invocation call sites. A handful of callers need a+ /// *different* cap than the definition's declared budget (e.g. long-running+ /// workflow/task-dispatcher runs that intentionally exceed any single+ /// agent's normal budget). Those callers should apply their override+ /// AFTER construction via this setter, so the shared definition-cap logic+ /// in the builder doesn't get silently clobbered by pre-construction+ /// mutations (and vice versa).+ pub fn set_max_tool_iterations(&mut self, cap: usize) {+ self.config.max_tool_iterations = cap;+ }++ /// Returns the current conversation history.+ pub fn history(&self) -> &[ConversationMessage] {+ &self.history+ }++ pub fn set_event_context(&mut self, session_id: impl Into<String>, channel: impl Into<String>) {+ self.event_session_id = session_id.into();+ self.event_channel = channel.into();+ self.rebuild_tool_policy_session();+ }++ /// Override the agent definition name used for session transcript+ /// file paths. Callers (e.g. the web channel) use this to scope+ /// transcripts per thread so each conversation thread gets its own+ /// transcript namespace instead of sharing one by agent type.+ ///+ /// Also rebuilds [`Self::session_key`] so the next call to+ /// `persist_session_transcript` writes to a path keyed by the new+ /// name. Without this, persist would keep using the builder-time+ /// name (e.g. `"orchestrator"`) while+ /// `find_latest_transcript` searches for the post-rename name (e.g.+ /// `"orchestrator_thread-6ad6d"`), and resume on cold boot would+ /// silently miss every prior transcript — the LLM would then run+ /// each new turn with no conversation history.+ pub fn set_agent_definition_name(&mut self, name: impl Into<String>) {+ let name = name.into();+ let sanitized: String = name+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '_' || c == '-' {+ c+ } else {+ '_'+ }+ })+ .collect();+ // Preserve the original unix-timestamp prefix from the builder+ // so sub-agent spawn collisions remain impossible. Falls back+ // to "0" if the existing key is in an unexpected shape.+ let prefix = self+ .session_key+ .split_once('_')+ .map(|(p, _)| p)+ .filter(|p| !p.is_empty())+ .unwrap_or("0");+ self.session_key = format!("{prefix}_{sanitized}");+ self.agent_definition_name = name;+ self.rebuild_tool_policy_session();+ }++ /// Attach a progress event sender for real-time turn updates.+ ///+ /// When set, the turn loop emits [`AgentProgress`] events so+ /// callers (e.g. the web channel) can surface live tool-call and+ /// iteration updates to the UI. Pass `None` to disable.+ pub fn set_on_progress(+ &mut self,+ tx: Option<tokio::sync::mpsc::Sender<crate::openhuman::agent::progress::AgentProgress>>,+ ) {+ self.on_progress = tx;+ }++ /// Bind this session's acting tools (shell / file / git) to `descriptor`'s+ /// root as their default working directory.+ ///+ /// The post-build counterpart of+ /// [`AgentBuilder::workspace_descriptor`](crate::openhuman::agent::AgentBuilder::workspace_descriptor),+ /// for callers that construct the agent through+ /// [`Agent::from_config`](crate::openhuman::agent::Agent::from_config) and+ /// therefore never see the builder — notably the per-turn `cwd` of+ /// [`agent_chat`](crate::openhuman::inference::local::ops::agent_chat).+ ///+ /// The descriptor is threaded onto the turn's run context, so it also+ /// propagates to sub-agents spawned from this session (the same deliberate+ /// isolation the per-profile descriptor has). `None` restores the shared+ /// `action_dir` cwd.+ ///+ /// This only moves the *default* cwd: what the session may read and write is+ /// still decided by its [`SecurityPolicy`](crate::openhuman::security::SecurityPolicy),+ /// so a caller that wants tools rooted somewhere new must build the agent+ /// from a config whose `action_dir` already permits it.+ pub fn set_workspace_descriptor(+ &mut self,+ descriptor: Option<tinyagents::harness::workspace::WorkspaceDescriptor>,+ ) {+ self.workspace_descriptor = descriptor;+ }++ /// Attach an active-run queue for mid-turn steering.+ pub fn set_run_queue(+ &mut self,+ rq: Option<std::sync::Arc<crate::openhuman::agent::harness::run_queue::RunQueue>>,+ ) {+ self.run_queue = rq;+ }++ /// Restrict which tools the main agent can see and call for this+ /// session. An empty set restores the default "all visible" behavior,+ /// still subject to the configured channel permission policy.+ pub fn set_visible_tool_names(&mut self, names: HashSet<String>) {+ self.visible_tool_names = names;+ self.rebuild_tool_policy_session();+ }++ /// Remove `names` from the main agent's callable set for this session,+ /// leaving every other currently-visible tool untouched.+ ///+ /// The hidden names resolve to `Deny` at the tool-call boundary (via the+ /// rebuilt [`ToolPolicySession`]), not merely absent from the prompt — a+ /// hard execution guarantee even if the model requests the tool anyway.+ ///+ /// When the session currently has *no* visible-tool filter (empty set =+ /// "all visible"), the filter is first seeded from every registered tool+ /// spec so hiding actually **restricts** the set rather than no-opping into+ /// the still-"all visible" empty state. Used by callers that need to drop a+ /// specific dangerous tool from an otherwise-unchanged belt (e.g. the+ /// `flows_build` builder path dropping the live-run `run_flow` tool).+ ///+ /// Caveat: because an empty set is the "all visible" sentinel, hiding *every*+ /// remaining tool collapses back to "all visible". Callers use this to drop+ /// a handful of tools from a much larger belt, where that can't happen.+ pub fn hide_tools(&mut self, names: &[&str]) {+ if self.visible_tool_names.is_empty() {+ self.visible_tool_names = self+ .tool_specs+ .iter()+ .map(|spec| spec.name.clone())+ .collect();+ }+ for name in names {+ self.visible_tool_names.remove(*name);+ }+ // Seeding from `tool_specs` above materialises the "all visible"+ // sentinel into a concrete set, which would re-admit packed tools that+ // the builder withheld. Re-apply the withholding.+ crate::openhuman::tools::toolpacks::strip_packed_from_visible(+ &mut self.visible_tool_names,+ &self.agent_definition_name,+ );+ self.rebuild_tool_policy_session();+ }++ pub(super) fn rebuild_tool_policy_session(&mut self) {+ self.tool_policy_session = ToolPolicyEngine::build_session(+ &self.agent_definition_name,+ &self.event_channel,+ "session",+ &self.config.channel_permissions,+ self.tools.as_slice(),+ &self.visible_tool_names,+ );+ let visible_specs = super::builder::visible_tool_specs_for_policy(+ self.tool_specs.as_slice(),+ &self.visible_tool_names,+ &self.tool_policy_session,+ );+ self.visible_tool_specs = Arc::new(super::builder::dedup_visible_tool_specs(visible_specs));+ }++ /// Clears the agent's conversation history.+ pub fn clear_history(&mut self) {+ self.history.clear();+ }++ /// Set the overrides applied to the **next** [`Self::turn`] call.+ ///+ /// The overrides are consumed at the top of the next turn (they apply to a+ /// single turn, then reset to the default), so a caller running a chat /+ /// small-talk turn calls this immediately before [`Self::turn`]. Callers+ /// that never touch this get the unchanged full-agentic behaviour. See+ /// [`TurnOverrides`](super::types::TurnOverrides) for the fields and the+ /// motivating case (#1725: a bare greeting must not run the task loop nor+ /// inherit a prior task's goal / tools / memory).+ pub fn set_next_turn_overrides(&mut self, overrides: super::types::TurnOverrides) {+ self.pending_turn_overrides = overrides;+ }++ /// Seed the next turn's LLM context from an authoritative message+ /// log (e.g. the web channel's per-thread conversation JSONL).+ ///+ /// Mirrors what [`Self::try_load_session_transcript`] does on a+ /// transcript-file hit, but sources from a caller-supplied list so+ /// resume works even when no transcript file exists for this+ /// agent name (the typical situation right after the+ /// `set_agent_definition_name` / `session_key` rename fix landed —+ /// existing transcripts are written under the old name).+ ///+ /// `messages` is `(role, content)` pairs in chronological order.+ /// Recognised roles: `"user"`, `"agent"` / `"assistant"`. Any+ /// trailing user message that exactly matches `current_user_message`+ /// is dropped — the caller is about to pass that text to+ /// [`Self::run_single`], which will append it to history itself, so+ /// keeping it here would duplicate it on the wire.+ ///+ /// No-ops if the agent already has a history or a cached transcript+ /// (i.e. the per-process session cache is warm). Intended only for+ /// cold-boot priming.+ pub fn seed_resume_from_messages(+ &mut self,+ messages: Vec<(String, String)>,+ current_user_message: &str,+ ) -> Result<()> {+ if !self.history.is_empty() || self.cached_transcript_messages.is_some() {+ return Ok(());+ }+ let mut prior = messages;+ if let Some(last) = prior.last() {+ if last.0 == "user" && last.1.trim() == current_user_message.trim() {+ prior.pop();+ }+ }+ if prior.is_empty() {+ return Ok(());+ }++ // Build the system prompt fresh — there's no persisted prefix+ // to preserve here, and learned-context decoration is skipped+ // intentionally so this fallback path stays synchronous and+ // doesn't fan out to the memory store on every cold-boot turn.+ let learned = crate::openhuman::agent::prompts::LearnedContextData::default();+ let system_prompt = self.build_system_prompt(learned)?;++ let mut cached: Vec<crate::openhuman::agent::messages::ChatMessage> =+ Vec::with_capacity(prior.len() + 1);+ cached.push(crate::openhuman::agent::messages::ChatMessage::system(+ system_prompt,+ ));+ for (role, content) in prior {+ let chat = match role.as_str() {+ "user" => crate::openhuman::agent::messages::ChatMessage::user(content),+ "agent" | "assistant" => {+ crate::openhuman::agent::messages::ChatMessage::assistant(content)+ }+ // Fall back to user role for unknown senders rather than+ // dropping the message — losing context is worse than+ // mislabelling a system/tool message.+ _ => crate::openhuman::agent::messages::ChatMessage::user(content),+ };+ cached.push(chat);+ }++ let cached_len_before = cached.len();+ let bounded = self.bound_cached_transcript_messages(cached);+ if bounded.len() < cached_len_before {+ log::warn!(+ "[agent] seed_resume_from_messages — bounded cached transcript {} → {} (max_history_messages={})",+ cached_len_before,+ bounded.len(),+ self.config.max_history_messages+ );+ }+ log::info!(+ "[agent] seed_resume_from_messages — primed cached transcript with {} prior messages",+ bounded.len().saturating_sub(1)+ );+ self.cached_transcript_messages = Some(bounded);+ Ok(())+ }++ /// Cold-boot resume for the web-chat path: pre-populate this session's+ /// LLM context from the **full-fidelity** `session_raw/{stem}.jsonl`+ /// transcript for `thread_id`.+ ///+ /// This is the high-fidelity counterpart to+ /// [`Self::seed_resume_from_messages`]. That fallback sources lossy+ /// `(sender, content)` prose from the conversation log, so it drops every+ /// tool call, tool-role result, and reasoning block — after an app restart+ /// the model then "forgets" all its tool interactions. This path instead+ /// routes thread → transcript via+ /// [`transcript::find_root_transcript_for_thread`] and reuses the exact+ /// [`transcript::read_transcript`] ++ /// [`Self::bound_cached_transcript_messages`] machinery as+ /// [`Self::try_load_session_transcript`], so `tool_calls`, `role:"tool"`+ /// messages, and `reasoning_content` all survive the round-trip. The only+ /// difference from `try_load_session_transcript` is the lookup key (thread+ /// id vs. per-thread agent name), so a thread whose transcript was written+ /// under a differently-scoped agent name still resumes.+ ///+ /// Returns `true` when a transcript was found, loaded, and seeded into+ /// `cached_transcript_messages`; `false` (a no-op) when the agent is already+ /// warm, no root transcript exists for the thread, the transcript is empty,+ /// or it fails to parse — the caller then falls back to prose-pair seeding.+ ///+ /// Best-effort like `try_load_session_transcript`: read/parse failures are+ /// logged and reported as `false` rather than propagated. The current turn's+ /// user message is appended later by [`Self::run_single`] / `turn`, so it is+ /// intentionally absent from the loaded prefix — no dedup is needed here (the+ /// on-disk transcript ends at the previous completed turn).+ ///+ /// Goes through the S4 seam like `try_load_session_transcript` (see its doc+ /// comment for why the read is `read_session` and not+ /// `ChatHistory::messages()`), via the locator's `root_for_thread` — the+ /// lookup that resolves by `_meta.thread_id` across *root* transcripts+ /// only. That disambiguation is why it is a locator method rather than+ /// anything a stem-bound handle could offer: several transcripts share one+ /// thread id (every sub-agent spawned within it does).+ pub fn seed_resume_from_thread_transcript(&mut self, thread_id: &str) -> bool {+ if !self.history.is_empty() || self.cached_transcript_messages.is_some() {+ log::debug!(+ "[web-channel] seed_resume_from_thread_transcript no-op — agent already warm \+ (history_len={}, cached={}) thread={thread_id}",+ self.history.len(),+ self.cached_transcript_messages.is_some()+ );+ return false;+ }++ // The thread's conversation belongs to the THREAD, not the active+ // profile: the locator resolves cross-dir, newest-wins across the+ // shared `session_raw/` and every profile-scoped `session_raw-<id>/`+ // (#5351), so switching profile mid-thread continues the same+ // conversation. See `FileTranscriptLocator::root_for_thread` for why+ // this must not be own-dir-first.+ let Some(handle) = self.session_locator().root_for_thread(thread_id) else {+ log::debug!(+ "[web-channel] no root session_raw transcript for thread={thread_id} in any \+ (shared or profile-scoped) session_raw dir — falling back to \+ conversation-log prose seeding"+ );+ return false;+ };+ let path = handle.path().to_path_buf();++ log::info!(+ "[web-channel] cold-boot resume — loading full-fidelity transcript for \+ thread={thread_id} path={}",+ path.display()+ );++ match handle.read_session() {+ // `Ok(None)` (file vanished between discovery and read) folds into+ // the same empty-transcript branch, so the prose-seeding fallback+ // triggers identically.+ Ok(None) => {+ log::debug!(+ "[web-channel] root transcript for thread={thread_id} is empty — \+ falling back to prose seeding"+ );+ false+ }+ Ok(Some(session)) => {+ if session.messages.is_empty() {+ log::debug!(+ "[web-channel] root transcript for thread={thread_id} is empty — \+ falling back to prose seeding"+ );+ return false;+ }+ let loaded_count = session.messages.len();+ // Count the tool-role results carried into the resumed prefix —+ // the fidelity the prose fallback would have silently dropped.+ let tool_result_msgs = session.messages.iter().filter(|m| m.role == "tool").count();+ let bounded = self.bound_cached_transcript_messages(session.messages);+ if bounded.len() < loaded_count {+ log::warn!(+ "[web-channel] resume prefix trimmed from {} to {} messages \+ (max_history_messages={}) for thread={thread_id}",+ loaded_count,+ bounded.len(),+ self.config.max_history_messages+ );+ }+ log::info!(+ "[web-channel] cold-boot resume — primed {} transcript message(s) \+ ({} tool-role result(s) preserved) for thread={thread_id}",+ bounded.len(),+ tool_result_msgs+ );+ self.cached_transcript_messages = Some(bounded);+ true+ }+ Err(err) => {+ log::warn!(+ "[web-channel] failed to parse root transcript {} for thread={thread_id}: \+ {err} — falling back to prose seeding",+ path.display()+ );+ false+ }+ }+ }++ /// Drain and return memory citations collected for the latest completed turn.+ ///+ /// Async because collection runs concurrently with the turn rather than+ /// ahead of it (see `Agent::pending_citations`); this joins whatever is+ /// still in flight. By the time a caller asks, the model round-trip has+ /// already happened, so the recall has normally finished and this does not+ /// wait.+ pub async fn take_last_turn_citations(+ &mut self,+ ) -> Vec<crate::openhuman::memory::agent::memory_loader::MemoryCitation> {+ if let Some(handle) = self.pending_citations.take() {+ match handle.await {+ Ok(citations) => self.last_turn_citations = citations,+ // A panicked or aborted collection must not fail the turn — the+ // citations are decorative, the reply is not.+ Err(err) => {+ log::warn!("[agent_loop] citation task did not complete: {err}");+ self.last_turn_citations.clear();+ }+ }+ }+ std::mem::take(&mut self.last_turn_citations)+ }+}diff --git a/src/openhuman/agent/harness/session/runtime_impl_01_part_02.rs b/src/openhuman/agent/harness/session/runtime_impl_01_part_02.rsnew file mode 100644index 0000000000..bced21fb6d--- /dev/null+++ b/src/openhuman/agent/harness/session/runtime_impl_01_part_02.rs@@ -0,0 +1,312 @@++impl Agent {+ /// Borrow the holistic token/cost/context totals for the latest completed+ /// turn (parent + sub-agents) **without consuming them**. `None` until a+ /// turn has run.+ ///+ /// This is the public, non-draining counterpart to+ /// [`take_last_turn_usage_totals`](Self::take_last_turn_usage_totals): a+ /// downstream crate embedding OpenHuman as a library (e.g. the OpenCompany+ /// hosting platform's cost-metering hook) can read per-turn token and USD+ /// totals after [`Agent::turn`](crate::openhuman::agent::Agent) returns,+ /// while leaving the value in place for the web-channel drain path.+ pub fn last_turn_usage(+ &self,+ ) -> Option<&crate::openhuman::agent::harness::turn_subagent_usage::LastTurnUsage> {+ self.last_turn_usage_totals.as_ref()+ }++ /// Drain and return the holistic token/cost/context totals for the latest+ /// completed turn (parent + sub-agents). `None` until a turn has run.+ /// Consumed by web-channel delivery to populate the `chat_done` usage fields.+ pub(crate) fn take_last_turn_usage_totals(+ &mut self,+ ) -> Option<crate::openhuman::agent::harness::turn_subagent_usage::LastTurnUsage> {+ self.last_turn_usage_totals.take()+ }++ /// Whether the most recently completed [`Self::turn`] / [`Self::run_single`]+ /// paused because it hit `max_tool_iterations`, rather than finishing+ /// naturally (see the field doc on `last_turn_hit_cap`). `false` before+ /// any turn has run. Not draining — unlike the usage totals above, a+ /// caller may reasonably check this more than once per turn.+ pub fn last_turn_hit_cap(&self) -> bool {+ self.last_turn_hit_cap+ }++ // ─────────────────────────────────────────────────────────────────+ // Static helpers for turn parsing + telemetry+ // ─────────────────────────────────────────────────────────────────++ pub(super) fn count_iterations(messages: &[ConversationMessage]) -> usize {+ messages+ .iter()+ .filter(|message| matches!(message, ConversationMessage::AssistantToolCalls { .. }))+ .count()+ + 1+ }++ fn conversation_message_eq(left: &ConversationMessage, right: &ConversationMessage) -> bool {+ serde_json::to_string(left).ok() == serde_json::to_string(right).ok()+ }++ fn message_slice_eq(left: &[ConversationMessage], right: &[ConversationMessage]) -> bool {+ left.len() == right.len()+ && left+ .iter()+ .zip(right.iter())+ .all(|(left, right)| Self::conversation_message_eq(left, right))+ }++ pub(super) fn new_entries_for_turn<'a>(+ history_snapshot: &[ConversationMessage],+ current_history: &'a [ConversationMessage],+ ) -> &'a [ConversationMessage] {+ let common_prefix_len = history_snapshot+ .iter()+ .zip(current_history.iter())+ .take_while(|(left, right)| Self::conversation_message_eq(left, right))+ .count();++ if common_prefix_len == history_snapshot.len() {+ return ¤t_history[common_prefix_len..];+ }++ let max_overlap = history_snapshot.len().min(current_history.len());+ for overlap in (0..=max_overlap).rev() {+ let snapshot_suffix = &history_snapshot[history_snapshot.len() - overlap..];+ let current_prefix = ¤t_history[..overlap];+ if Self::message_slice_eq(snapshot_suffix, current_prefix) {+ return ¤t_history[overlap..];+ }+ }++ current_history+ }++ pub(super) fn sanitize_event_error_message(err: &anyhow::Error) -> String {+ let kind = match err.downcast_ref::<AgentError>() {+ Some(AgentError::ProviderError { .. }) => Some("provider_error"),+ Some(AgentError::ContextLimitExceeded { .. }) => Some("context_limit_exceeded"),+ Some(AgentError::ToolExecutionError { .. }) => Some("tool_execution_error"),+ Some(AgentError::CostBudgetExceeded { .. }) => Some("cost_budget_exceeded"),+ Some(AgentError::MaxIterationsExceeded { .. }) => Some("max_iterations_exceeded"),+ Some(AgentError::EmptyProviderResponse { .. }) => Some("empty_provider_response"),+ Some(AgentError::CompactionFailed { .. }) => Some("compaction_failed"),+ Some(AgentError::PermissionDenied { .. }) => Some("permission_denied"),+ Some(AgentError::RegistryValidationFailed { .. }) => Some("registry_validation_failed"),+ Some(AgentError::Other(_)) | None => None,+ };++ if let Some(kind) = kind {+ return kind.to_string();+ }++ let scrubbed = provider::sanitize_api_error(&err.to_string())+ .replace(['\n', '\r', '\t'], " ")+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ");+ truncate_with_ellipsis(&scrubbed, Self::EVENT_ERROR_MAX_CHARS)+ }++ /// Injects unique IDs into tool calls that are missing them.+ ///+ /// This is necessary for some tool dispatchers to correctly track and+ /// associate results.+ pub(super) fn with_fallback_tool_call_ids(+ mut parsed_calls: Vec<ParsedToolCall>,+ iteration: usize,+ ) -> Vec<ParsedToolCall> {+ for (idx, call) in parsed_calls.iter_mut().enumerate() {+ if call.tool_call_id.is_none() {+ call.tool_call_id = Some(format!("parsed-{}-{}", iteration + 1, idx + 1));+ }+ }+ parsed_calls+ }++ /// Converts parsed tool calls into the provider-standard `ToolCall` format.+ ///+ /// If the provider response already contains native tool calls, they are+ /// returned as-is.+ pub(super) fn persisted_tool_calls_for_history(+ response: &crate::openhuman::inference::provider::ChatResponse,+ parsed_calls: &[ParsedToolCall],+ iteration: usize,+ ) -> Vec<ToolCall> {+ if !response.tool_calls.is_empty() {+ return response.tool_calls.clone();+ }++ parsed_calls+ .iter()+ .enumerate()+ .map(|(idx, call)| ToolCall {+ id: call+ .tool_call_id+ .clone()+ .unwrap_or_else(|| format!("parsed-{}-{}", iteration + 1, idx + 1)),+ name: call.name.clone(),+ arguments: call.arguments.to_string(),+ // Prompt-based tool calls carry no provider extra_content.+ extra_content: None,+ })+ .collect()+ }++ // ─────────────────────────────────────────────────────────────────+ // Run helpers — single-shot and interactive loops+ // ─────────────────────────────────────────────────────────────────++ /// Runs a single turn with the given message and returns the response.+ ///+ /// This is the primary high-level method for programmatic interaction with the agent.+ /// It wraps the core `turn` logic with telemetry events (`AgentTurnStarted`,+ /// `AgentTurnCompleted`) and error sanitization.+ pub async fn run_single(&mut self, message: &str) -> Result<String> {+ let guard = enforce_prompt_input(+ message,+ PromptEnforcementContext {+ source: "agent.runtime.run_single",+ request_id: None,+ user_id: Some(self.event_channel()),+ session_id: Some(self.event_session_id()),+ },+ );+ if !matches!(guard.action, PromptEnforcementAction::Allow) {+ let user_message = match guard.action {+ PromptEnforcementAction::Allow => "Message accepted.",+ PromptEnforcementAction::Blocked => "Prompt blocked by security policy.",+ PromptEnforcementAction::ReviewBlocked => {+ "Prompt flagged for security review and was not processed."+ }+ };+ let action_tag = match guard.action {+ PromptEnforcementAction::Allow => "allow",+ PromptEnforcementAction::Blocked => "blocked",+ PromptEnforcementAction::ReviewBlocked => "review_blocked",+ };+ crate::core::observability::report_error(+ user_message,+ "agent",+ "prompt_injection_blocked",+ &[+ ("session_id", self.event_session_id()),+ ("channel", self.event_channel()),+ ("action", action_tag),+ ],+ );+ BUS.publish(DomainEvent::AgentError {+ session_id: self.event_session_id().to_string(),+ message: user_message.to_string(),+ recoverable: true,+ });+ return Err(anyhow::anyhow!(user_message));+ }++ let history_snapshot = self.history.clone();+ BUS.publish(DomainEvent::AgentTurnStarted {+ session_id: self.event_session_id().to_string(),+ channel: self.event_channel().to_string(),+ });++ match self.turn(message).await {+ Ok(response) => {+ let new_entries = Self::new_entries_for_turn(&history_snapshot, &self.history);+ BUS.publish(DomainEvent::AgentTurnCompleted {+ session_id: self.event_session_id().to_string(),+ text_chars: response.chars().count(),+ iterations: Self::count_iterations(new_entries),+ });+ Ok(response)+ }+ Err(err) => {+ let sanitized_message = Self::sanitize_event_error_message(&err);+ // Some typed `AgentError` variants represent agent / user /+ // provider state that the UI already surfaces — the+ // max-tool-iterations cap (OPENHUMAN-TAURI-99 / -98,+ // chat-rendered "Error: Agent exceeded maximum tool+ // iterations") and the empty-provider-response degeneracy+ // (TAURI-RUST-4JX, "The model returned an empty response.+ // Please try again."). Skip the Sentry funnel for both+ // and emit a structured `log::info!` instead. The+ // suppressed set is owned by `AgentError::skips_sentry()`+ // so the policy stays in one place.+ //+ // Other agent errors go through `report_error_or_expected`+ // so OPENHUMAN-TAURI-5Z and the budget-noise cluster —+ // upstream transient HTTP and backend budget-exhausted 400s+ // that bubble up under `domain=agent` and escape the+ // `domain=llm_provider` filter — get demoted to a+ // warn/info-level breadcrumb without losing genuine bugs.+ // `Err` propagation, the `AgentError` domain event, and+ // downstream `recoverable=false` semantics are preserved.+ let skips_sentry = err+ .downcast_ref::<AgentError>()+ .is_some_and(AgentError::skips_sentry);+ if skips_sentry {+ log::info!(+ target: "agent",+ "[agent.run_single] suppressed Sentry emission for user-state agent error \+ session_id={} channel={} error_kind={} message={}",+ self.event_session_id(),+ self.event_channel(),+ sanitized_message.as_str(),+ err+ );+ } else {+ crate::core::observability::report_error_or_expected(+ &err,+ "agent",+ "run_single",+ &[+ ("session_id", self.event_session_id()),+ ("channel", self.event_channel()),+ ("error_kind", sanitized_message.as_str()),+ ],+ );+ }+ BUS.publish(DomainEvent::AgentError {+ session_id: self.event_session_id().to_string(),+ message: sanitized_message,+ recoverable: false,+ });+ Err(err)+ }+ }+ }++ /// Runs an interactive CLI loop, reading from standard input and printing to standard output.+ ///+ /// This method starts a persistent session where the user can chat with the agent+ /// directly from the console. It handles input until a termination command+ /// (e.g., `/quit`) is received.+ pub async fn run_interactive(&mut self) -> Result<()> {+ println!("🦀 OpenHuman Interactive Mode");+ println!("Type /quit to exit.\n");++ let (tx, mut rx) = tokio::sync::mpsc::channel(32);+ let cli = crate::openhuman::channels::CliChannel::new();++ let listen_handle = tokio::spawn(async move {+ let _ = crate::openhuman::channels::Channel::listen(&cli, tx).await;+ });++ while let Some(msg) = rx.recv().await {+ match self.run_single(&msg.content).await {+ Ok(response) => println!("\n{response}\n"),+ Err(e) => {+ // `run_single` already publishes `AgentError` and+ // sanitises the payload; surface a concise line here+ // for the CLI user and continue the loop.+ eprintln!("\nError: {e}\n");+ continue;+ }+ }+ }++ listen_handle.abort();+ Ok(())+ }+}diff --git a/src/openhuman/agent/harness/session/turn/session_io.rs b/src/openhuman/agent/harness/session/turn/session_io.rsindex 626f702937..7f440a88da 100644--- a/src/openhuman/agent/harness/session/turn/session_io.rs+++ b/src/openhuman/agent/harness/session/turn/session_io.rs@@ -14,921 +14,5 @@ use crate::openhuman::inference::provider::{};use futures::StreamExt;use tinyagents::harness::model::{ModelRequest, ModelStreamItem};--impl Agent {- // ─────────────────────────────────────────────────────────────────- // Session transcript helpers- // ─────────────────────────────────────────────────────────────────-- /// Try to load a previous session transcript for KV cache resume.- ///- /// Best-effort: failures are logged and silently ignored.- ///- /// # How this reaches the transcript (S4)- ///- /// Both halves of the turn path now go through the seam: writes through- /// [`SessionHistory::append_turn`][super::super::transcript_history::SessionHistory::append_turn],- /// reads through- /// [`SessionHistoryLocator`][super::super::transcript_history::SessionHistoryLocator]- /// + [`SessionTranscriptRead::read_session`][super::super::transcript_history::SessionTranscriptRead::read_session].- ///- /// The read is **not** `ChatHistory::messages()`, and that is settled, not- /// pending: `messages()` returns `Vec<Message>`, and converting back with- /// `message_to_chat_message` flattens `Assistant.tool_calls` into plain- /// text. That is precisely what- /// [`bound_cached_transcript_messages`][Agent::bound_cached_transcript_messages]'- /// TAURI-RUST-7 trailing strip inspects, and re-sending a flattened prefix- /// to a native provider is the `400 assistant message with 'tool_calls'- /// must be followed by tool messages` failure that strip exists to prevent.- /// `read_session` returns the whole [`SessionTranscript`][super::super::transcript::SessionTranscript]- /// instead — the same struct the free function returns, from the same- /// `read_transcript` call — so compaction replay, `interrupted: true`- /// partial skipping and the `_meta` header- /// [`maybe_shadow_read_session_store`][Agent::maybe_shadow_read_session_store]- /// needs all survive by construction.- ///- /// Discovery lives on the locator because it is a *lookup*, not a read:- /// this function's key is `(workspace, session_raw_subdir, agent name)`- /// (newest match, with a legacy `session_raw/DDMMYYYY/` fallback) and the- /// cold-boot sibling- /// [`seed_resume_from_thread_transcript`][Agent::seed_resume_from_thread_transcript]- /// keys off `_meta.thread_id`. Neither is a stem, and `ChatHistory` has no- /// discovery concept at all.- pub(in super::super) fn try_load_session_transcript(&mut self) {- let Some(handle) = self- .session_locator()- .latest_for_agent(&self.agent_definition_name)- else {- log::debug!(- "[transcript] no previous transcript found for agent={}",- self.agent_definition_name- );- return;- };- let path = handle.path().to_path_buf();- log::info!(- "[transcript] found previous transcript path={}",- path.display()- );- match handle.read_session() {- // `Ok(None)` (file vanished between discovery and read) folds into- // the same "nothing to resume from" branch as an empty transcript,- // so the caller's behaviour is unchanged either way.- Ok(None) => {- log::debug!("[transcript] previous transcript is empty — skipping resume");- }- Ok(Some(session)) => {- if session.messages.is_empty() {- log::debug!("[transcript] previous transcript is empty — skipping resume");- return;- }- let loaded_count = session.messages.len();- log::info!("[transcript] loaded {} messages for resume", loaded_count);- // Best-effort store-backed shadow read (issue #4249,- // 04.2 phase 2). Observes + logs divergence only; the- // legacy transcript just loaded stays authoritative and- // is what feeds the resume below. Gated OFF by default.- self.maybe_shadow_read_session_store(&path, &session);- let bounded = self.bound_cached_transcript_messages(session.messages);- if bounded.len() < loaded_count {- log::warn!(- "[transcript] resume prefix trimmed from {} to {} messages (max_history_messages={})",- loaded_count,- bounded.len(),- self.config.max_history_messages- );- }- self.cached_transcript_messages = Some(bounded);- }- Err(err) => {- log::warn!(- "[transcript] failed to parse previous transcript {}: {err}",- path.display()- );- }- }- }-- /// The transcript locator for this session — the injected one, or a- /// [`FileTranscriptLocator`] built from the agent's **current** workspace.- ///- /// Built per call rather than cached: `workspace_dir` and- /// `session_raw_subdir` are reassignable after `build()` (tests do exactly- /// that), and a locator frozen at build time would silently keep resolving- /// against the directory the agent no longer uses. The construction is two- /// clones of small strings — cheaper than the `read_dir` it precedes.- pub(in super::super) fn session_locator(&self) -> std::sync::Arc<dyn SessionHistoryLocator> {- match &self.session_history_locator {- Some(locator) => locator.clone(),- None => std::sync::Arc::new(FileTranscriptLocator::new(- self.workspace_dir.clone(),- self.session_raw_subdir.clone(),- )),- }- }-- /// Ask the provider for a short wrap-up message with native tools- /// **disabled** so the model returns prose rather than another tool call.- /// Buffers text deltas and forwards them to the progress sink (when- /// attached) only after the completed response is validated as prose, so- /// prompt-formatted tool calls cannot flash in the UI before fallback.- ///- /// `instruction` is the synthetic user turn that steers the wrap-up — the- /// tool-call-cap checkpoint (`MAX_ITER_CHECKPOINT_INSTRUCTION`) or the- /// no-final-answer close (`FINAL_ANSWER_INSTRUCTION`, issue #4093).- ///- /// Returns the summary text (empty when the provider call fails or- /// yields nothing — the caller then falls back to a deterministic builder- /// so the turn is never left without a well-formed assistant message,- /// bug-report-2026-05-26 A1 / issue #4093) **paired with the provider- /// usage** for this extra call, so the caller can fold it into the turn's- /// cumulative token/cost accounting instead of silently dropping it.- pub(super) async fn summarize_turn_wrapup(- &self,- base_messages: &[ChatMessage],- effective_model: &str,- iteration_for_stream: u32,- instruction: &str,- ) -> (String, Option<UsageInfo>) {- let mut messages = base_messages.to_vec();- messages.push(ChatMessage::user(instruction));-- let chat_model = match self- .turn_model_source- .build_summarizer(effective_model, self.temperature)- {- Ok(model) => model,- Err(error) => {- tracing::error!(- error = %error,- model = effective_model,- "[agent::session] failed to build wrap-up model"- );- return (String::new(), None);- }- };- let request = ModelRequest::new(- messages- .iter()- .map(crate::openhuman::agent::tinyagents::chat_message_to_message)- .collect(),- )- .with_model(effective_model)- .with_temperature(self.temperature)- .with_max_tokens(AGENT_TURN_MAX_OUTPUT_TOKENS);- let mut stream = match chat_model.stream(&(), request).await {- Ok(stream) => stream,- Err(error) => {- tracing::warn!(- error = %error,- model = effective_model,- "[agent::session] wrap-up stream failed to start"- );- return (String::new(), None);- }- };-- let mut streamed_text = String::new();- let mut completed = None;- while let Some(item) = stream.next().await {- match item {- ModelStreamItem::MessageDelta(delta) if !delta.text.is_empty() => {- streamed_text.push_str(&delta.text);- }- ModelStreamItem::Completed(response) => completed = Some(response),- ModelStreamItem::Failed(error) => {- tracing::warn!(%error, "[agent::session] wrap-up stream failed");- return (String::new(), None);- }- ModelStreamItem::ProviderFailed(error) => {- tracing::warn!(error = %error.message, "[agent::session] wrap-up provider failed");- return (String::new(), None);- }- _ => {}- }- }- let Some(response) = completed else {- tracing::warn!("[agent::session] wrap-up stream ended without completion");- return (String::new(), None);- };- let usage = crate::openhuman::agent::tinyagents::model::usage_info_from_response(&response);- let text = response.text();- // Tools are disabled for wrap-up calls, but text-protocol models can- // still ignore that instruction. Parse through the active dispatcher- // so XML/JSON and registry-backed P-Format calls are all rejected. The- // completed response and buffered deltas are checked independently:- // some providers only preserve one of those representations.- let parsed_call_count = |candidate: &str| {- self.tool_dispatcher- .parse_response(&ChatResponse {- text: Some(candidate.to_string()),- ..ChatResponse::default()- })- .1- .len()- };- let parsed_response_calls = parsed_call_count(&text);- let parsed_stream_calls = if streamed_text == text {- parsed_response_calls- } else {- parsed_call_count(&streamed_text)- };- let native_tool_calls = response.tool_calls().len();- let attempted_tool_call =- native_tool_calls > 0 || parsed_response_calls > 0 || parsed_stream_calls > 0;- let checkpoint = if attempted_tool_call {- tracing::warn!(- model = effective_model,- iteration = iteration_for_stream,- native_tool_calls,- parsed_response_calls,- parsed_stream_calls,- "[agent::session] wrap-up attempted a tool call; using deterministic fallback"- );- String::new()- } else if !text.trim().is_empty() {- tracing::debug!(- model = effective_model,- iteration = iteration_for_stream,- text_len = text.len(),- "[agent::session] wrap-up selected completed response text"- );- text- } else {- tracing::debug!(- model = effective_model,- iteration = iteration_for_stream,- text_len = streamed_text.len(),- "[agent::session] wrap-up selected buffered stream text"- );- streamed_text- };- // Hold wrap-up deltas until protocol validation completes. Otherwise a- // rejected XML/P-Format tool call briefly renders in chat even though- // the caller subsequently replaces it with a deterministic fallback.- if !checkpoint.is_empty() {- if let Some(sink) = &self.on_progress {- if let Err(error) = sink- .send(AgentProgress::TextDelta {- delta: checkpoint.clone(),- iteration: iteration_for_stream,- })- .await- {- tracing::debug!(- model = effective_model,- iteration = iteration_for_stream,- error = %error,- "[agent::session] wrap-up progress sink closed"- );- }- }- }- tracing::debug!(- model = effective_model,- iteration = iteration_for_stream,- checkpoint_len = checkpoint.len(),- used_deterministic_fallback = attempted_tool_call,- "[agent::session] wrap-up checkpoint selection complete"- );- (checkpoint, usage)- }-- /// Enforce this agent's required structured-output contract on the turn's- /// final `reply` (issue #4117), reconciling with streaming.- ///- /// When the contract is active and `reply` already carries a well-formed- /// leading block, returns `None` (the caller keeps `reply` unchanged). When- /// the block is omitted/invalid, the turn is **repaired** so downstream- /// parsing/routing always receives one, and the repaired text is returned as- /// `Some((repaired_text, usage))` so the caller can fold the extra call's- /// usage into the turn accounting and rewrite the trailing assistant message.- ///- /// ## Streaming reconciliation (the #4387 / sanil-23 blocker)- ///- /// The original reply is streamed to the client as `TextDelta`s *before* this- /// runs (via the harness event bridge, keyed on `on_progress`). #4387- /// repaired with a `stream: None` re-prompt whose result then *replaced* the- /// already-streamed reply — so the client watched one answer stream in and- /// silently got a different one back. This implementation makes the repair- /// **append-only**, so the returned/persisted reply is always exactly the- /// concatenation of deltas the client saw — the live preview is a *prefix* of- /// the final message, never contradicted:- ///- /// * **Streamed case** (`on_progress` attached — interactive/user-visible):- /// the corrective re-prompt runs *silently* (its raw output is never- /// streamed, so a malformed attempt is never shown), then the chosen- /// correction — the model's block if the concatenation validates, else a- /// deterministic [`synthesize_block`] — is streamed as a continuation and- /// appended after the original prose. Visible text == returned text, and- /// the appended block is the first JSON value (prose isn't JSON), so the- /// leading-position rule holds for the dominant omitted-block case.- /// * **Non-streamed case** (`on_progress` absent — background/cron/routing,- /// the "non-user-visible" scope sanil-23 offered as the alternative): no- /// client saw anything, so there is nothing to stay consistent with. The- /// strict #4387 **replace** design applies — recover via re-prompt, else- /// prepend a synthesized block to the prose — guaranteeing strict leading- /// position.- ///- /// `iteration_for_stream` labels the streamed continuation so the UI groups- /// it with the turn's other deltas.- ///- /// [`synthesize_block`]: harness::required_output::synthesize_block- pub(in super::super) async fn enforce_required_output(- &self,- reply: &str,- contract: &tinyagents::harness::config::RequiredOutput,- effective_model: &str,- iteration_for_stream: u32,- ) -> Option<(String, Option<UsageInfo>)> {- use harness::required_output as ro;-- if ro::output_satisfies_contract(reply, contract) {- return None;- }- log::warn!(- "[agent_loop] required output block `{}` omitted from turn reply — repairing (streamed={})",- contract.block_key,- self.on_progress.is_some(),- );-- // Corrective re-prompt (native tools disabled), seeded with the current- // history — which already carries the omitting assistant reply, so the- // model sees exactly what it left out. Run silently: we validate the- // result before deciding whether/what to show, so a malformed attempt is- // never streamed to the client.- let mut base = self.tool_dispatcher.to_provider_messages(&self.history);- base.push(ChatMessage::user(ro::repair_instruction(contract)));- let (repair_text, usage) = self- .reprompt_for_required_block(&base, effective_model)- .await;- let repair_text = repair_text.trim().to_string();-- // Non-streamed (replace) path: nothing was shown, so the repaired reply- // can stand alone with a strictly-leading block.- if self.on_progress.is_none() {- if !repair_text.is_empty() && ro::output_satisfies_contract(&repair_text, contract) {- log::info!(- "[agent_loop] required output block `{}` recovered via re-prompt (replace)",- contract.block_key- );- return Some((repair_text, usage));- }- log::warn!(- "[agent_loop] required output block `{}` still missing after re-prompt — prepending a synthesized block",- contract.block_key- );- let synthesized = format!("{}\n\n{}", ro::synthesize_block(contract), reply);- return Some((synthesized, usage));- }-- // Streamed (append) path: the original prose is already on the client, so- // never replace it — append a streamed correction and return the exact- // concatenation the client sees. Append ONLY the required block, not the- // whole re-prompt reply: `repair_instruction` asks the model to re-emit the- // block *and continue with its answer*, so appending the full reply would- // duplicate the already-streamed answer after the block (#4900). Prefer the- // model's own recovered block; fall back to a synthesized one otherwise.- let correction = match ro::find_required_block(&repair_text, contract) {- Some(block) => {- log::info!(- "[agent_loop] required output block `{}` recovered via re-prompt (append)",- contract.block_key- );- serde_json::to_string(&block).unwrap_or_else(|_| ro::synthesize_block(contract))- }- None => {- log::warn!(- "[agent_loop] required output block `{}` still missing after re-prompt — appending a synthesized block",- contract.block_key- );- ro::synthesize_block(contract)- }- };- // Stream only the correction as a continuation so the live preview stays- // a prefix of the final message (visible == returned).- let continuation = format!("\n\n{correction}");- self.stream_text_continuation(&continuation, iteration_for_stream)- .await;- let repaired = format!("{reply}{continuation}");- if !ro::output_satisfies_contract(&repaired, contract) {- // The only way to reach here is a reply that streamed a *non-conforming- // JSON object first*: append-only can't restore strict leading- // position without contradicting what the user already saw, so we- // accept the trailing valid block and keep stream consistency (the- // higher-priority invariant). Downstream still finds a conforming- // block via `extract_json_values`; only strict ordering is relaxed,- // and only for this pathological already-streamed case.- log::warn!(- "[agent_loop] required output block `{}` appended but not in leading position (streamed reply led with JSON) — accepting for stream consistency",- contract.block_key- );- }- Some((repaired, usage))- }-- /// Ask the provider once for a reply that includes the required- /// structured-output block, with native tools **disabled** and **without**- /// forwarding any delta to the progress sink. Returns the parsed prose paired- /// with the call's usage (empty text + `None` usage when the call fails or- /// yields only tool-call markup).- ///- /// Unlike [`summarize_turn_wrapup`](Self::summarize_turn_wrapup) this is- /// deliberately silent: `enforce_required_output` validates the result before- /// deciding what (if anything) to stream, so a malformed repair attempt is- /// never shown to the client.- async fn reprompt_for_required_block(- &self,- base_messages: &[ChatMessage],- effective_model: &str,- ) -> (String, Option<UsageInfo>) {- let chat_model = match self- .turn_model_source- .build_summarizer(effective_model, self.temperature)- {- Ok(model) => model,- Err(error) => {- tracing::error!(- error = %error,- model = effective_model,- "[agent::session] failed to build required-output re-prompt model"- );- return (String::new(), None);- }- };- let request = ModelRequest::new(- base_messages- .iter()- .map(crate::openhuman::agent::tinyagents::chat_message_to_message)- .collect(),- )- .with_model(effective_model)- .with_temperature(self.temperature)- .with_max_tokens(AGENT_TURN_MAX_OUTPUT_TOKENS);- let mut stream = match chat_model.stream(&(), request).await {- Ok(stream) => stream,- Err(error) => {- tracing::warn!(- error = %error,- model = effective_model,- "[agent::session] required-output re-prompt stream failed to start"- );- return (String::new(), None);- }- };-- let mut streamed_text = String::new();- let mut completed = None;- while let Some(item) = stream.next().await {- match item {- // Buffer only — deliberately NOT forwarded to `on_progress`.- ModelStreamItem::MessageDelta(delta) if !delta.text.is_empty() => {- streamed_text.push_str(&delta.text);- }- ModelStreamItem::Completed(response) => completed = Some(response),- ModelStreamItem::Failed(error) => {- tracing::warn!(%error, "[agent::session] required-output re-prompt stream failed");- return (String::new(), None);- }- ModelStreamItem::ProviderFailed(error) => {- tracing::warn!(error = %error.message, "[agent::session] required-output re-prompt provider failed");- return (String::new(), None);- }- _ => {}- }- }- let Some(response) = completed else {- tracing::warn!("[agent::session] required-output re-prompt ended without completion");- return (String::new(), None);- };- let usage = crate::openhuman::agent::tinyagents::model::usage_info_from_response(&response);- let text = response.text();- let out = if !text.trim().is_empty() {- text- } else if response.tool_calls().is_empty() {- streamed_text- } else {- // Only tool-call markup was present — no usable prose.- String::new()- };- (out, usage)- }-- /// Emit `text` to the progress sink as a `TextDelta` continuation so a- /// repaired required-output block appears in the UI appended after the- /// already-streamed reply (issue #4117). No-op when no sink is attached.- async fn stream_text_continuation(&self, text: &str, iteration: u32) {- if text.is_empty() {- return;- }- if let Some(sink) = &self.on_progress {- let _ = sink- .send(AgentProgress::TextDelta {- delta: text.to_string(),- iteration,- })- .await;- }- }-- /// Persist the exact provider messages as a session transcript.- ///- /// Writes JSONL as source of truth and re-renders the companion `.md`- /// for human readability. Best-effort: failures are logged and silently- /// ignored. The JSONL conversation store remains the authoritative- /// persistence layer; session transcripts are an optimization for KV- /// cache stability.- ///- /// `turn_usage` — when `Some`, attributes per-message token/cost figures- /// to the last assistant message in the written transcript.- pub(in super::super) fn persist_session_transcript(- &mut self,- messages: &[ChatMessage],- input_tokens: u64,- output_tokens: u64,- cached_input_tokens: u64,- charged_amount_usd: f64,- turn_usage: Option<&transcript::TurnUsage>,- ) {- let now = chrono::Utc::now().to_rfc3339();-- // This turn's `_meta`. Built before the path/handle binding below so it- // can double as the handle's `seed_meta`; it depends only on agent- // state and this turn's figures, never on the resolved path.- let meta = transcript::TranscriptMeta {- agent_name: self.agent_definition_name.clone(),- agent_id: Some(self.agent_definition_id.clone()),- agent_type: Some(if self.session_parent_prefix.is_some() {- "subagent".to_string()- } else {- "root".to_string()- }),- dispatcher: if self.tool_dispatcher.should_send_tool_specs() {- "native".into()- } else {- "xml".into()- },- provider: turn_usage.map(|usage| usage.provider.clone()),- model: turn_usage.map(|usage| usage.model.clone()),- created: now.clone(),- updated: now,- turn_count: self.context.stats().session_memory_current_turn as usize,- input_tokens,- output_tokens,- cached_input_tokens,- charged_amount_usd,- thread_id: crate::openhuman::agent::tinyagents::thread_context::current_thread_id(),- task_id: None,- };-- // Bind the write seam on first write. The stem is- // `{parent_prefix}__{session_key}` for sub-agents (producing a- // flat hierarchical filename) or just `{session_key}` for a- // root session. Prefix chaining is already done by the- // sub-agent runner when it populates `session_parent_prefix`.- //- // Path resolution is the locator's job, not this function's: it used to- // be duplicated here (a `resolve_keyed_transcript_path_in_dir` call- // that had to stay in lockstep with the identical one inside the- // handle's constructor). One call now yields both, and- // `session_transcript_path` is simply the bound handle's own path — so- // they cannot drift. The seed meta only matters when the file is absent- // and the caller supplies none; the turn path always passes its own- // freshly-computed meta below, so it never takes effect.- if self.session_transcript_path.is_none() {- let stem = match &self.session_parent_prefix {- Some(prefix) => format!("{}__{}", prefix, self.session_key),- None => self.session_key.clone(),- };- match self.session_locator().open_stem(&stem, meta.clone()) {- Ok(history) => {- log::info!(- "[transcript] new session transcript path={}",- history.path().display()- );- self.session_transcript_path = Some(history.path().to_path_buf());- self.session_history = Some(history);- }- Err(err) => {- log::warn!("[transcript] failed to bind session history: {err:#}");- self.session_transcript_path = None;- return;- }- }- }-- let path = self.session_transcript_path.clone().unwrap();- // Cloned out of `self` before the write so the later `&mut self`- // dual-write does not conflict with a live borrow of the handle.- let Some(history) = self.session_history.clone() else {- log::warn!("[transcript] no session history bound; skipping append");- return;- };-- // Append-only write (Phase A, transcript-derived view): diff this turn's- // logical messages against the previously-persisted set tracked in- // memory. A pure extension appends only the new tail; a context- // reduction appends a `compaction` record. The file is never rewritten,- // so pre-compaction history survives on disk for the display projection.- // `request_id` (web-chat only) stamps a turn boundary on each line.- //- // This goes through `SessionHistory::append_turn` rather than- // `transcript::append_transcript_turn` directly (S4). The handle is a- // pure forwarder of exactly these six values — it must be, because the- // crate's `ChatHistory` methods carry no channel for `request_id`,- // `turn_usage` or a caller-computed `TranscriptMeta`, and dropping any- // of them silently guts the transcript-view projection. See the header- // of `transcript_history.rs` for the full argument.- let prev = std::mem::take(&mut self.persisted_transcript_messages);- let request_id = crate::openhuman::agent::turn_origin::current_request_id();- match history.append_turn(TranscriptTurn {- prev: &prev,- next: messages,- meta: &meta,- turn_usage,- request_id: request_id.as_deref(),- }) {- Ok(()) => {- // Track the new persisted logical set for the next turn's diff.- self.persisted_transcript_messages = messages.to_vec();- // Best-effort, non-fatal dual-write into the TinyAgents store.- // Gated by the default-ON session dual-write flag- // (`OPENHUMAN_SESSION_DUAL_WRITE` is a kill switch). Only runs- // after the legacy JSONL append above succeeds; the legacy path- // is primary and untouched (issue #4249, 04.1).- self.maybe_dual_write_session_store(&path, messages, &meta, turn_usage);- }- Err(err) => {- // Restore the tracked state so a transient failure doesn't make- // the next turn mis-diff (and spuriously emit a compaction).- self.persisted_transcript_messages = prev;- log::warn!(- "[transcript] failed to append transcript {}: {err}",- path.display()- );- }- }- }-- /// Mirror the just-persisted turn into the TinyAgents session store.- ///- /// Additive and gated on the default-ON session dual-write flag- /// (`OPENHUMAN_SESSION_DUAL_WRITE` is a kill switch): when killed this is a- /// cheap early return — no store handle is constructed and behavior is- /// byte-identical to the legacy-only path. When on (the default), the- /// store write is fired best-effort on a background task and any error is- /// logged (`[session-store]`) and swallowed, so it can never fail or alter a- /// chat turn. Records reuse the importer's normalization- /// ([`crate::openhuman::agent::session_import`]) so live and imported records are- /// shape-identical. Reads stay 100% legacy until 04.2.- fn maybe_dual_write_session_store(- &self,- path: &std::path::Path,- messages: &[ChatMessage],- meta: &transcript::TranscriptMeta,- turn_usage: Option<&transcript::TurnUsage>,- ) {- use crate::openhuman::agent::session_import::live;-- // Config flag (default ON) gates the mirror; the env kill switch can- // still force it off. `self.config` is the effective per-agent config.- if !live::dual_write_enabled(self.config.session_dual_write) {- return;- }-- // The session key is the transcript stem — the same value the importer- // reads off the on-disk filename, so `stream_name`/descriptor keys match.- let Some(stem) = path- .file_stem()- .and_then(|s| s.to_str())- .map(str::to_string)- else {- log::warn!(- "[session-store] dual-write skipped: no file stem for {}",- path.display()- );- return;- };-- // Rebuild the exact message shape the importer sees after a JSONL- // round-trip: attach this turn's usage to the last assistant message so- // its `openhuman_turn_usage` metadata matches an imported record.- let mut msgs = messages.to_vec();- if let Some(usage) = turn_usage {- if let Some(idx) = msgs.iter().rposition(|m| m.role == "assistant") {- transcript::attach_turn_usage_metadata(&mut msgs[idx], usage);- }- }- let session_transcript = transcript::SessionTranscript {- meta: meta.clone(),- messages: msgs,- };- let workspace = self.workspace_dir.clone();-- log::debug!(- "[session-store] dual-write scheduled stem={stem} workspace={}",- workspace.display()- );- tokio::spawn(async move {- if let Err(err) = live::write_live_turn(&workspace, &stem, &session_transcript).await {- log::warn!("[session-store] dual-write failed stem={stem}: {err:#}");- }- });- }-- /// Store-backed **shadow read** of a just-loaded session transcript.- ///- /// Beside the legacy authoritative reader (`try_load_session_transcript`),- /// read the same session back from the TinyAgents journal store, normalize- /// both sides through the importer's `session_import::convert` machinery,- /// compare, and log any divergence (`[session_shadow_read]`, issue #4249,- /// 04.2 phase 2). Additive and gated on the default-**OFF**- /// `AgentConfig::session_shadow_reads` flag- /// (`OPENHUMAN_SESSION_SHADOW_READS` is a kill switch): when disabled this- /// is a cheap early return.- ///- /// The legacy transcript stays authoritative — this only observes. The- /// comparison runs on a spawned background task so it never slows the- /// authoritative read, and every store-read error is treated as "no shadow- /// available" (logged at debug), never propagated.- fn maybe_shadow_read_session_store(- &self,- path: &std::path::Path,- session: &transcript::SessionTranscript,- ) {- use crate::openhuman::agent::session_import::live;-- // Config flag (default OFF) gates the shadow read; the env kill switch- // can still force it off. `self.config` is the effective per-agent config.- if !live::shadow_reads_enabled(self.config.session_shadow_reads) {- return;- }-- // Same session key the write side / importer use: the transcript stem.- let Some(stem) = path- .file_stem()- .and_then(|s| s.to_str())- .map(str::to_string)- else {- log::debug!(- "[session_shadow_read] skipped: no file stem for {}",- path.display()- );- return;- };-- let workspace = self.workspace_dir.clone();- let transcript = session.clone();- log::debug!(- "[session_shadow_read] scheduled stem={stem} workspace={} legacy_messages={}",- workspace.display(),- transcript.messages.len()- );- tokio::spawn(async move {- let _ = live::shadow_read_compare(&workspace, &stem, &transcript).await;- });- }-- // ─────────────────────────────────────────────────────────────────- // Session-memory extraction.- // ─────────────────────────────────────────────────────────────────-- /// Spawn a background archivist sub-agent to extract durable facts- /// from the recent conversation into `MEMORY.md`. Fire-and-forget.- ///- /// Gated by [`context_pipeline::SessionMemoryState::should_extract`]- /// — see its docs for the threshold invariants. Safe to call from- /// inside `turn()` after the turn body has settled.- pub(in super::super) async fn spawn_session_memory_extraction(- &mut self,- parent_ctx: harness::ParentExecutionContext,- ) {- // ── Flush the trailing open segment before the session winds down ──- //- // The ArchivistHook manages per-turn segment lifecycle but cannot- // force-close the *last* open segment because there is no explicit- // "session end" event in the turn loop. `spawn_session_memory_extraction`- // is the closest available signal: it fires when the context manager- // decides the session has accumulated enough material to archive.- //- // GUARANTEE: the flush is *awaited* here (not fire-and-forget) so- // the trailing segment always receives its recap + embedding + tree- // ingest before the function returns, even during runtime wind-down.- // This honours the doc-comment guarantee on `flush_open_segment` in- // `archivist.rs`. No deadlock risk: no mutex guard is held across- // this await point.- if let Some(ref archivist) = self.archivist_hook {- let session_id = self.event_session_id.clone();- log::debug!(- "[archivist] awaiting flush_open_segment for session={session_id} at session wind-down"- );- archivist.flush_open_segment(&session_id).await;- }-- let Some(registry) = harness::AgentDefinitionRegistry::global() else {- log::debug!("[session_memory] registry not initialised — skipping extraction spawn");- return;- };- let Some(definition) = registry.get("archivist").cloned() else {- log::debug!(- "[session_memory] archivist definition not found — skipping extraction spawn"- );- return;- };-- let extraction_prompt = ARCHIVIST_EXTRACTION_PROMPT.to_string();-- // Flip the extraction state to "in-progress" so future- // should_extract checks return false until the archivist- // finishes. We then hand a shared handle to the spawned task- // so it can mark the extraction complete (resets deltas) on- // success, or failed (keeps deltas intact for retry) on error.- // This replaces the old optimistic `mark_complete` that- // silently dropped the retry window when extractions failed.- let stats_snapshot = self.context.stats();- self.context.mark_session_memory_started();- let sm_handle = self.context.session_memory_handle();-- log::info!(- "[session_memory] spawning background archivist extraction (turn={}, tokens={})",- stats_snapshot.session_memory_current_turn,- stats_snapshot.session_memory_total_tokens- );-- tokio::spawn(async move {- let options = harness::SubagentRunOptions::default();- let fut = harness::run_subagent(&definition, &extraction_prompt, options);- let result = harness::with_parent_context(parent_ctx, fut).await;- match result {- Ok(outcome) => {- tracing::info!(- agent_id = %outcome.agent_id,- task_id = %outcome.task_id,- iterations = outcome.iterations,- output_chars = outcome.output.chars().count(),- "[session_memory] archivist extraction completed"- );- if let Ok(mut sm) = sm_handle.lock() {- sm.mark_extraction_complete();- }- }- Err(err) => {- tracing::warn!(- error = %err,- "[session_memory] archivist extraction failed — will retry after next threshold crossing"- );- // Leave the deltas intact so the next threshold- // crossing schedules another attempt. Clearing- // `extraction_in_progress` lets the retry- // actually fire.- if let Ok(mut sm) = sm_handle.lock() {- sm.mark_extraction_failed();- }- }- }- });- }-- /// Spawn a background task that ingests the current session- /// transcript into the conversational-memory store.- ///- /// Issue #1399: complements `spawn_session_memory_extraction`. The- /// archivist path writes dense bullets into `MEMORY.md`; this path- /// extracts importance-tagged, provenance-bearing memories via the- /// heuristic [`crate::openhuman::agent::learning::transcript_ingest`]- /// pipeline. The two are deliberately independent so the prompt- /// retrieval layer can pull from `conversation_memory` without- /// needing the archivist's extraction to have fired this session.- ///- /// Fire-and-forget: failures are logged, never propagated.- pub(in super::super) fn spawn_transcript_ingestion(&self) {- let Some(path) = self.session_transcript_path.clone() else {- log::debug!("[transcript_ingest] no session transcript path yet — skipping spawn");- return;- };- let memory = std::sync::Arc::clone(&self.memory);-- tokio::spawn(async move {- match crate::openhuman::agent::learning::transcript_ingest::ingest_transcript_path(- memory.as_ref(),- &path,- )- .await- {- Ok(report) => tracing::info!(- transcript = %path.display(),- extracted = report.extracted,- stored = report.stored,- deduped = report.deduped,- reflections_stored = report.reflections_stored,- "[transcript_ingest] background ingest complete"- ),- Err(err) => tracing::warn!(- transcript = %path.display(),- error = %err,- "[transcript_ingest] background ingest failed — will retry next threshold window"- ),- }- });- }-}+include!("session_io_impl_01_part_01.rs");+include!("session_io_impl_01_part_02.rs");diff --git a/src/openhuman/agent/harness/session/turn/session_io_impl_01_part_01.rs b/src/openhuman/agent/harness/session/turn/session_io_impl_01_part_01.rsnew file mode 100644index 0000000000..f4d15e6be1--- /dev/null+++ b/src/openhuman/agent/harness/session/turn/session_io_impl_01_part_01.rs@@ -0,0 +1,518 @@++impl Agent {++ // ─────────────────────────────────────────────────────────────────+ // Session transcript helpers+ // ─────────────────────────────────────────────────────────────────++ /// Try to load a previous session transcript for KV cache resume.+ ///+ /// Best-effort: failures are logged and silently ignored.+ ///+ /// # How this reaches the transcript (S4)+ ///+ /// Both halves of the turn path now go through the seam: writes through+ /// [`SessionHistory::append_turn`][super::super::transcript_history::SessionHistory::append_turn],+ /// reads through+ /// [`SessionHistoryLocator`][super::super::transcript_history::SessionHistoryLocator]+ /// + [`SessionTranscriptRead::read_session`][super::super::transcript_history::SessionTranscriptRead::read_session].+ ///+ /// The read is **not** `ChatHistory::messages()`, and that is settled, not+ /// pending: `messages()` returns `Vec<Message>`, and converting back with+ /// `message_to_chat_message` flattens `Assistant.tool_calls` into plain+ /// text. That is precisely what+ /// [`bound_cached_transcript_messages`][Agent::bound_cached_transcript_messages]'+ /// TAURI-RUST-7 trailing strip inspects, and re-sending a flattened prefix+ /// to a native provider is the `400 assistant message with 'tool_calls'+ /// must be followed by tool messages` failure that strip exists to prevent.+ /// `read_session` returns the whole [`SessionTranscript`][super::super::transcript::SessionTranscript]+ /// instead — the same struct the free function returns, from the same+ /// `read_transcript` call — so compaction replay, `interrupted: true`+ /// partial skipping and the `_meta` header+ /// [`maybe_shadow_read_session_store`][Agent::maybe_shadow_read_session_store]+ /// needs all survive by construction.+ ///+ /// Discovery lives on the locator because it is a *lookup*, not a read:+ /// this function's key is `(workspace, session_raw_subdir, agent name)`+ /// (newest match, with a legacy `session_raw/DDMMYYYY/` fallback) and the+ /// cold-boot sibling+ /// [`seed_resume_from_thread_transcript`][Agent::seed_resume_from_thread_transcript]+ /// keys off `_meta.thread_id`. Neither is a stem, and `ChatHistory` has no+ /// discovery concept at all.+ pub(in super::super) fn try_load_session_transcript(&mut self) {+ let Some(handle) = self+ .session_locator()+ .latest_for_agent(&self.agent_definition_name)+ else {+ log::debug!(+ "[transcript] no previous transcript found for agent={}",+ self.agent_definition_name+ );+ return;+ };+ let path = handle.path().to_path_buf();+ log::info!(+ "[transcript] found previous transcript path={}",+ path.display()+ );+ match handle.read_session() {+ // `Ok(None)` (file vanished between discovery and read) folds into+ // the same "nothing to resume from" branch as an empty transcript,+ // so the caller's behaviour is unchanged either way.+ Ok(None) => {+ log::debug!("[transcript] previous transcript is empty — skipping resume");+ }+ Ok(Some(session)) => {+ if session.messages.is_empty() {+ log::debug!("[transcript] previous transcript is empty — skipping resume");+ return;+ }+ let loaded_count = session.messages.len();+ log::info!("[transcript] loaded {} messages for resume", loaded_count);+ // Best-effort store-backed shadow read (issue #4249,+ // 04.2 phase 2). Observes + logs divergence only; the+ // legacy transcript just loaded stays authoritative and+ // is what feeds the resume below. Gated OFF by default.+ self.maybe_shadow_read_session_store(&path, &session);+ let bounded = self.bound_cached_transcript_messages(session.messages);+ if bounded.len() < loaded_count {+ log::warn!(+ "[transcript] resume prefix trimmed from {} to {} messages (max_history_messages={})",+ loaded_count,+ bounded.len(),+ self.config.max_history_messages+ );+ }+ self.cached_transcript_messages = Some(bounded);+ }+ Err(err) => {+ log::warn!(+ "[transcript] failed to parse previous transcript {}: {err}",+ path.display()+ );+ }+ }+ }++ /// The transcript locator for this session — the injected one, or a+ /// [`FileTranscriptLocator`] built from the agent's **current** workspace.+ ///+ /// Built per call rather than cached: `workspace_dir` and+ /// `session_raw_subdir` are reassignable after `build()` (tests do exactly+ /// that), and a locator frozen at build time would silently keep resolving+ /// against the directory the agent no longer uses. The construction is two+ /// clones of small strings — cheaper than the `read_dir` it precedes.+ pub(in super::super) fn session_locator(&self) -> std::sync::Arc<dyn SessionHistoryLocator> {+ match &self.session_history_locator {+ Some(locator) => locator.clone(),+ None => std::sync::Arc::new(FileTranscriptLocator::new(+ self.workspace_dir.clone(),+ self.session_raw_subdir.clone(),+ )),+ }+ }++ /// Ask the provider for a short wrap-up message with native tools+ /// **disabled** so the model returns prose rather than another tool call.+ /// Buffers text deltas and forwards them to the progress sink (when+ /// attached) only after the completed response is validated as prose, so+ /// prompt-formatted tool calls cannot flash in the UI before fallback.+ ///+ /// `instruction` is the synthetic user turn that steers the wrap-up — the+ /// tool-call-cap checkpoint (`MAX_ITER_CHECKPOINT_INSTRUCTION`) or the+ /// no-final-answer close (`FINAL_ANSWER_INSTRUCTION`, issue #4093).+ ///+ /// Returns the summary text (empty when the provider call fails or+ /// yields nothing — the caller then falls back to a deterministic builder+ /// so the turn is never left without a well-formed assistant message,+ /// bug-report-2026-05-26 A1 / issue #4093) **paired with the provider+ /// usage** for this extra call, so the caller can fold it into the turn's+ /// cumulative token/cost accounting instead of silently dropping it.+ pub(super) async fn summarize_turn_wrapup(+ &self,+ base_messages: &[ChatMessage],+ effective_model: &str,+ iteration_for_stream: u32,+ instruction: &str,+ ) -> (String, Option<UsageInfo>) {+ let mut messages = base_messages.to_vec();+ messages.push(ChatMessage::user(instruction));++ let chat_model = match self+ .turn_model_source+ .build_summarizer(effective_model, self.temperature)+ {+ Ok(model) => model,+ Err(error) => {+ tracing::error!(+ error = %error,+ model = effective_model,+ "[agent::session] failed to build wrap-up model"+ );+ return (String::new(), None);+ }+ };+ let request = ModelRequest::new(+ messages+ .iter()+ .map(crate::openhuman::agent::tinyagents::chat_message_to_message)+ .collect(),+ )+ .with_model(effective_model)+ .with_temperature(self.temperature)+ .with_max_tokens(AGENT_TURN_MAX_OUTPUT_TOKENS);+ let mut stream = match chat_model.stream(&(), request).await {+ Ok(stream) => stream,+ Err(error) => {+ tracing::warn!(+ error = %error,+ model = effective_model,+ "[agent::session] wrap-up stream failed to start"+ );+ return (String::new(), None);+ }+ };++ let mut streamed_text = String::new();+ let mut completed = None;+ while let Some(item) = stream.next().await {+ match item {+ ModelStreamItem::MessageDelta(delta) if !delta.text.is_empty() => {+ streamed_text.push_str(&delta.text);+ }+ ModelStreamItem::Completed(response) => completed = Some(response),+ ModelStreamItem::Failed(error) => {+ tracing::warn!(%error, "[agent::session] wrap-up stream failed");+ return (String::new(), None);+ }+ ModelStreamItem::ProviderFailed(error) => {+ tracing::warn!(error = %error.message, "[agent::session] wrap-up provider failed");+ return (String::new(), None);+ }+ _ => {}+ }+ }+ let Some(response) = completed else {+ tracing::warn!("[agent::session] wrap-up stream ended without completion");+ return (String::new(), None);+ };+ let usage = crate::openhuman::agent::tinyagents::model::usage_info_from_response(&response);+ let text = response.text();+ // Tools are disabled for wrap-up calls, but text-protocol models can+ // still ignore that instruction. Parse through the active dispatcher+ // so XML/JSON and registry-backed P-Format calls are all rejected. The+ // completed response and buffered deltas are checked independently:+ // some providers only preserve one of those representations.+ let parsed_call_count = |candidate: &str| {+ self.tool_dispatcher+ .parse_response(&ChatResponse {+ text: Some(candidate.to_string()),+ ..ChatResponse::default()+ })+ .1+ .len()+ };+ let parsed_response_calls = parsed_call_count(&text);+ let parsed_stream_calls = if streamed_text == text {+ parsed_response_calls+ } else {+ parsed_call_count(&streamed_text)+ };+ let native_tool_calls = response.tool_calls().len();+ let attempted_tool_call =+ native_tool_calls > 0 || parsed_response_calls > 0 || parsed_stream_calls > 0;+ let checkpoint = if attempted_tool_call {+ tracing::warn!(+ model = effective_model,+ iteration = iteration_for_stream,+ native_tool_calls,+ parsed_response_calls,+ parsed_stream_calls,+ "[agent::session] wrap-up attempted a tool call; using deterministic fallback"+ );+ String::new()+ } else if !text.trim().is_empty() {+ tracing::debug!(+ model = effective_model,+ iteration = iteration_for_stream,+ text_len = text.len(),+ "[agent::session] wrap-up selected completed response text"+ );+ text+ } else {+ tracing::debug!(+ model = effective_model,+ iteration = iteration_for_stream,+ text_len = streamed_text.len(),+ "[agent::session] wrap-up selected buffered stream text"+ );+ streamed_text+ };+ // Hold wrap-up deltas until protocol validation completes. Otherwise a+ // rejected XML/P-Format tool call briefly renders in chat even though+ // the caller subsequently replaces it with a deterministic fallback.+ if !checkpoint.is_empty() {+ if let Some(sink) = &self.on_progress {+ if let Err(error) = sink+ .send(AgentProgress::TextDelta {+ delta: checkpoint.clone(),+ iteration: iteration_for_stream,+ })+ .await+ {+ tracing::debug!(+ model = effective_model,+ iteration = iteration_for_stream,+ error = %error,+ "[agent::session] wrap-up progress sink closed"+ );+ }+ }+ }+ tracing::debug!(+ model = effective_model,+ iteration = iteration_for_stream,+ checkpoint_len = checkpoint.len(),+ used_deterministic_fallback = attempted_tool_call,+ "[agent::session] wrap-up checkpoint selection complete"+ );+ (checkpoint, usage)+ }++ /// Enforce this agent's required structured-output contract on the turn's+ /// final `reply` (issue #4117), reconciling with streaming.+ ///+ /// When the contract is active and `reply` already carries a well-formed+ /// leading block, returns `None` (the caller keeps `reply` unchanged). When+ /// the block is omitted/invalid, the turn is **repaired** so downstream+ /// parsing/routing always receives one, and the repaired text is returned as+ /// `Some((repaired_text, usage))` so the caller can fold the extra call's+ /// usage into the turn accounting and rewrite the trailing assistant message.+ ///+ /// ## Streaming reconciliation (the #4387 / sanil-23 blocker)+ ///+ /// The original reply is streamed to the client as `TextDelta`s *before* this+ /// runs (via the harness event bridge, keyed on `on_progress`). #4387+ /// repaired with a `stream: None` re-prompt whose result then *replaced* the+ /// already-streamed reply — so the client watched one answer stream in and+ /// silently got a different one back. This implementation makes the repair+ /// **append-only**, so the returned/persisted reply is always exactly the+ /// concatenation of deltas the client saw — the live preview is a *prefix* of+ /// the final message, never contradicted:+ ///+ /// * **Streamed case** (`on_progress` attached — interactive/user-visible):+ /// the corrective re-prompt runs *silently* (its raw output is never+ /// streamed, so a malformed attempt is never shown), then the chosen+ /// correction — the model's block if the concatenation validates, else a+ /// deterministic [`synthesize_block`] — is streamed as a continuation and+ /// appended after the original prose. Visible text == returned text, and+ /// the appended block is the first JSON value (prose isn't JSON), so the+ /// leading-position rule holds for the dominant omitted-block case.+ /// * **Non-streamed case** (`on_progress` absent — background/cron/routing,+ /// the "non-user-visible" scope sanil-23 offered as the alternative): no+ /// client saw anything, so there is nothing to stay consistent with. The+ /// strict #4387 **replace** design applies — recover via re-prompt, else+ /// prepend a synthesized block to the prose — guaranteeing strict leading+ /// position.+ ///+ /// `iteration_for_stream` labels the streamed continuation so the UI groups+ /// it with the turn's other deltas.+ ///+ /// [`synthesize_block`]: harness::required_output::synthesize_block+ pub(in super::super) async fn enforce_required_output(+ &self,+ reply: &str,+ contract: &tinyagents::harness::config::RequiredOutput,+ effective_model: &str,+ iteration_for_stream: u32,+ ) -> Option<(String, Option<UsageInfo>)> {+ use harness::required_output as ro;++ if ro::output_satisfies_contract(reply, contract) {+ return None;+ }+ log::warn!(+ "[agent_loop] required output block `{}` omitted from turn reply — repairing (streamed={})",+ contract.block_key,+ self.on_progress.is_some(),+ );++ // Corrective re-prompt (native tools disabled), seeded with the current+ // history — which already carries the omitting assistant reply, so the+ // model sees exactly what it left out. Run silently: we validate the+ // result before deciding whether/what to show, so a malformed attempt is+ // never streamed to the client.+ let mut base = self.tool_dispatcher.to_provider_messages(&self.history);+ base.push(ChatMessage::user(ro::repair_instruction(contract)));+ let (repair_text, usage) = self+ .reprompt_for_required_block(&base, effective_model)+ .await;+ let repair_text = repair_text.trim().to_string();++ // Non-streamed (replace) path: nothing was shown, so the repaired reply+ // can stand alone with a strictly-leading block.+ if self.on_progress.is_none() {+ if !repair_text.is_empty() && ro::output_satisfies_contract(&repair_text, contract) {+ log::info!(+ "[agent_loop] required output block `{}` recovered via re-prompt (replace)",+ contract.block_key+ );+ return Some((repair_text, usage));+ }+ log::warn!(+ "[agent_loop] required output block `{}` still missing after re-prompt — prepending a synthesized block",+ contract.block_key+ );+ let synthesized = format!("{}\n\n{}", ro::synthesize_block(contract), reply);+ return Some((synthesized, usage));+ }++ // Streamed (append) path: the original prose is already on the client, so+ // never replace it — append a streamed correction and return the exact+ // concatenation the client sees. Append ONLY the required block, not the+ // whole re-prompt reply: `repair_instruction` asks the model to re-emit the+ // block *and continue with its answer*, so appending the full reply would+ // duplicate the already-streamed answer after the block (#4900). Prefer the+ // model's own recovered block; fall back to a synthesized one otherwise.+ let correction = match ro::find_required_block(&repair_text, contract) {+ Some(block) => {+ log::info!(+ "[agent_loop] required output block `{}` recovered via re-prompt (append)",+ contract.block_key+ );+ serde_json::to_string(&block).unwrap_or_else(|_| ro::synthesize_block(contract))+ }+ None => {+ log::warn!(+ "[agent_loop] required output block `{}` still missing after re-prompt — appending a synthesized block",+ contract.block_key+ );+ ro::synthesize_block(contract)+ }+ };+ // Stream only the correction as a continuation so the live preview stays+ // a prefix of the final message (visible == returned).+ let continuation = format!("\n\n{correction}");+ self.stream_text_continuation(&continuation, iteration_for_stream)+ .await;+ let repaired = format!("{reply}{continuation}");+ if !ro::output_satisfies_contract(&repaired, contract) {+ // The only way to reach here is a reply that streamed a *non-conforming+ // JSON object first*: append-only can't restore strict leading+ // position without contradicting what the user already saw, so we+ // accept the trailing valid block and keep stream consistency (the+ // higher-priority invariant). Downstream still finds a conforming+ // block via `extract_json_values`; only strict ordering is relaxed,+ // and only for this pathological already-streamed case.+ log::warn!(+ "[agent_loop] required output block `{}` appended but not in leading position (streamed reply led with JSON) — accepting for stream consistency",+ contract.block_key+ );+ }+ Some((repaired, usage))+ }++ /// Ask the provider once for a reply that includes the required+ /// structured-output block, with native tools **disabled** and **without**+ /// forwarding any delta to the progress sink. Returns the parsed prose paired+ /// with the call's usage (empty text + `None` usage when the call fails or+ /// yields only tool-call markup).+ ///+ /// Unlike [`summarize_turn_wrapup`](Self::summarize_turn_wrapup) this is+ /// deliberately silent: `enforce_required_output` validates the result before+ /// deciding what (if anything) to stream, so a malformed repair attempt is+ /// never shown to the client.+ async fn reprompt_for_required_block(+ &self,+ base_messages: &[ChatMessage],+ effective_model: &str,+ ) -> (String, Option<UsageInfo>) {+ let chat_model = match self+ .turn_model_source+ .build_summarizer(effective_model, self.temperature)+ {+ Ok(model) => model,+ Err(error) => {+ tracing::error!(+ error = %error,+ model = effective_model,+ "[agent::session] failed to build required-output re-prompt model"+ );+ return (String::new(), None);+ }+ };+ let request = ModelRequest::new(+ base_messages+ .iter()+ .map(crate::openhuman::agent::tinyagents::chat_message_to_message)+ .collect(),+ )+ .with_model(effective_model)+ .with_temperature(self.temperature)+ .with_max_tokens(AGENT_TURN_MAX_OUTPUT_TOKENS);+ let mut stream = match chat_model.stream(&(), request).await {+ Ok(stream) => stream,+ Err(error) => {+ tracing::warn!(+ error = %error,+ model = effective_model,+ "[agent::session] required-output re-prompt stream failed to start"+ );+ return (String::new(), None);+ }+ };++ let mut streamed_text = String::new();+ let mut completed = None;+ while let Some(item) = stream.next().await {+ match item {+ // Buffer only — deliberately NOT forwarded to `on_progress`.+ ModelStreamItem::MessageDelta(delta) if !delta.text.is_empty() => {+ streamed_text.push_str(&delta.text);+ }+ ModelStreamItem::Completed(response) => completed = Some(response),+ ModelStreamItem::Failed(error) => {+ tracing::warn!(%error, "[agent::session] required-output re-prompt stream failed");+ return (String::new(), None);+ }+ ModelStreamItem::ProviderFailed(error) => {+ tracing::warn!(error = %error.message, "[agent::session] required-output re-prompt provider failed");+ return (String::new(), None);+ }+ _ => {}+ }+ }+ let Some(response) = completed else {+ tracing::warn!("[agent::session] required-output re-prompt ended without completion");+ return (String::new(), None);+ };+ let usage = crate::openhuman::agent::tinyagents::model::usage_info_from_response(&response);+ let text = response.text();+ let out = if !text.trim().is_empty() {+ text+ } else if response.tool_calls().is_empty() {+ streamed_text+ } else {+ // Only tool-call markup was present — no usable prose.+ String::new()+ };+ (out, usage)+ }++ /// Emit `text` to the progress sink as a `TextDelta` continuation so a+ /// repaired required-output block appears in the UI appended after the+ /// already-streamed reply (issue #4117). No-op when no sink is attached.+ async fn stream_text_continuation(&self, text: &str, iteration: u32) {+ if text.is_empty() {+ return;+ }+ if let Some(sink) = &self.on_progress {+ let _ = sink+ .send(AgentProgress::TextDelta {+ delta: text.to_string(),+ iteration,+ })+ .await;+ }+ }+}diff --git a/src/openhuman/agent/harness/session/turn/session_io_impl_01_part_02.rs b/src/openhuman/agent/harness/session/turn/session_io_impl_01_part_02.rsnew file mode 100644index 0000000000..cd5644fa6d--- /dev/null+++ b/src/openhuman/agent/harness/session/turn/session_io_impl_01_part_02.rs@@ -0,0 +1,403 @@++impl Agent {+ /// Persist the exact provider messages as a session transcript.+ ///+ /// Writes JSONL as source of truth and re-renders the companion `.md`+ /// for human readability. Best-effort: failures are logged and silently+ /// ignored. The JSONL conversation store remains the authoritative+ /// persistence layer; session transcripts are an optimization for KV+ /// cache stability.+ ///+ /// `turn_usage` — when `Some`, attributes per-message token/cost figures+ /// to the last assistant message in the written transcript.+ pub(in super::super) fn persist_session_transcript(+ &mut self,+ messages: &[ChatMessage],+ input_tokens: u64,+ output_tokens: u64,+ cached_input_tokens: u64,+ charged_amount_usd: f64,+ turn_usage: Option<&transcript::TurnUsage>,+ ) {+ let now = chrono::Utc::now().to_rfc3339();++ // This turn's `_meta`. Built before the path/handle binding below so it+ // can double as the handle's `seed_meta`; it depends only on agent+ // state and this turn's figures, never on the resolved path.+ let meta = transcript::TranscriptMeta {+ agent_name: self.agent_definition_name.clone(),+ agent_id: Some(self.agent_definition_id.clone()),+ agent_type: Some(if self.session_parent_prefix.is_some() {+ "subagent".to_string()+ } else {+ "root".to_string()+ }),+ dispatcher: if self.tool_dispatcher.should_send_tool_specs() {+ "native".into()+ } else {+ "xml".into()+ },+ provider: turn_usage.map(|usage| usage.provider.clone()),+ model: turn_usage.map(|usage| usage.model.clone()),+ created: now.clone(),+ updated: now,+ turn_count: self.context.stats().session_memory_current_turn as usize,+ input_tokens,+ output_tokens,+ cached_input_tokens,+ charged_amount_usd,+ thread_id: crate::openhuman::agent::tinyagents::thread_context::current_thread_id(),+ task_id: None,+ };++ // Bind the write seam on first write. The stem is+ // `{parent_prefix}__{session_key}` for sub-agents (producing a+ // flat hierarchical filename) or just `{session_key}` for a+ // root session. Prefix chaining is already done by the+ // sub-agent runner when it populates `session_parent_prefix`.+ //+ // Path resolution is the locator's job, not this function's: it used to+ // be duplicated here (a `resolve_keyed_transcript_path_in_dir` call+ // that had to stay in lockstep with the identical one inside the+ // handle's constructor). One call now yields both, and+ // `session_transcript_path` is simply the bound handle's own path — so+ // they cannot drift. The seed meta only matters when the file is absent+ // and the caller supplies none; the turn path always passes its own+ // freshly-computed meta below, so it never takes effect.+ if self.session_transcript_path.is_none() {+ let stem = match &self.session_parent_prefix {+ Some(prefix) => format!("{}__{}", prefix, self.session_key),+ None => self.session_key.clone(),+ };+ match self.session_locator().open_stem(&stem, meta.clone()) {+ Ok(history) => {+ log::info!(+ "[transcript] new session transcript path={}",+ history.path().display()+ );+ self.session_transcript_path = Some(history.path().to_path_buf());+ self.session_history = Some(history);+ }+ Err(err) => {+ log::warn!("[transcript] failed to bind session history: {err:#}");+ self.session_transcript_path = None;+ return;+ }+ }+ }++ let path = self.session_transcript_path.clone().unwrap();+ // Cloned out of `self` before the write so the later `&mut self`+ // dual-write does not conflict with a live borrow of the handle.+ let Some(history) = self.session_history.clone() else {+ log::warn!("[transcript] no session history bound; skipping append");+ return;+ };++ // Append-only write (Phase A, transcript-derived view): diff this turn's+ // logical messages against the previously-persisted set tracked in+ // memory. A pure extension appends only the new tail; a context+ // reduction appends a `compaction` record. The file is never rewritten,+ // so pre-compaction history survives on disk for the display projection.+ // `request_id` (web-chat only) stamps a turn boundary on each line.+ //+ // This goes through `SessionHistory::append_turn` rather than+ // `transcript::append_transcript_turn` directly (S4). The handle is a+ // pure forwarder of exactly these six values — it must be, because the+ // crate's `ChatHistory` methods carry no channel for `request_id`,+ // `turn_usage` or a caller-computed `TranscriptMeta`, and dropping any+ // of them silently guts the transcript-view projection. See the header+ // of `transcript_history.rs` for the full argument.+ let prev = std::mem::take(&mut self.persisted_transcript_messages);+ let request_id = crate::openhuman::agent::turn_origin::current_request_id();+ match history.append_turn(TranscriptTurn {+ prev: &prev,+ next: messages,+ meta: &meta,+ turn_usage,+ request_id: request_id.as_deref(),+ }) {+ Ok(()) => {+ // Track the new persisted logical set for the next turn's diff.+ self.persisted_transcript_messages = messages.to_vec();+ // Best-effort, non-fatal dual-write into the TinyAgents store.+ // Gated by the default-ON session dual-write flag+ // (`OPENHUMAN_SESSION_DUAL_WRITE` is a kill switch). Only runs+ // after the legacy JSONL append above succeeds; the legacy path+ // is primary and untouched (issue #4249, 04.1).+ self.maybe_dual_write_session_store(&path, messages, &meta, turn_usage);+ }+ Err(err) => {+ // Restore the tracked state so a transient failure doesn't make+ // the next turn mis-diff (and spuriously emit a compaction).+ self.persisted_transcript_messages = prev;+ log::warn!(+ "[transcript] failed to append transcript {}: {err}",+ path.display()+ );+ }+ }+ }++ /// Mirror the just-persisted turn into the TinyAgents session store.+ ///+ /// Additive and gated on the default-ON session dual-write flag+ /// (`OPENHUMAN_SESSION_DUAL_WRITE` is a kill switch): when killed this is a+ /// cheap early return — no store handle is constructed and behavior is+ /// byte-identical to the legacy-only path. When on (the default), the+ /// store write is fired best-effort on a background task and any error is+ /// logged (`[session-store]`) and swallowed, so it can never fail or alter a+ /// chat turn. Records reuse the importer's normalization+ /// ([`crate::openhuman::agent::session_import`]) so live and imported records are+ /// shape-identical. Reads stay 100% legacy until 04.2.+ fn maybe_dual_write_session_store(+ &self,+ path: &std::path::Path,+ messages: &[ChatMessage],+ meta: &transcript::TranscriptMeta,+ turn_usage: Option<&transcript::TurnUsage>,+ ) {+ use crate::openhuman::agent::session_import::live;++ // Config flag (default ON) gates the mirror; the env kill switch can+ // still force it off. `self.config` is the effective per-agent config.+ if !live::dual_write_enabled(self.config.session_dual_write) {+ return;+ }++ // The session key is the transcript stem — the same value the importer+ // reads off the on-disk filename, so `stream_name`/descriptor keys match.+ let Some(stem) = path+ .file_stem()+ .and_then(|s| s.to_str())+ .map(str::to_string)+ else {+ log::warn!(+ "[session-store] dual-write skipped: no file stem for {}",+ path.display()+ );+ return;+ };++ // Rebuild the exact message shape the importer sees after a JSONL+ // round-trip: attach this turn's usage to the last assistant message so+ // its `openhuman_turn_usage` metadata matches an imported record.+ let mut msgs = messages.to_vec();+ if let Some(usage) = turn_usage {+ if let Some(idx) = msgs.iter().rposition(|m| m.role == "assistant") {+ transcript::attach_turn_usage_metadata(&mut msgs[idx], usage);+ }+ }+ let session_transcript = transcript::SessionTranscript {+ meta: meta.clone(),+ messages: msgs,+ };+ let workspace = self.workspace_dir.clone();++ log::debug!(+ "[session-store] dual-write scheduled stem={stem} workspace={}",+ workspace.display()+ );+ tokio::spawn(async move {+ if let Err(err) = live::write_live_turn(&workspace, &stem, &session_transcript).await {+ log::warn!("[session-store] dual-write failed stem={stem}: {err:#}");+ }+ });+ }++ /// Store-backed **shadow read** of a just-loaded session transcript.+ ///+ /// Beside the legacy authoritative reader (`try_load_session_transcript`),+ /// read the same session back from the TinyAgents journal store, normalize+ /// both sides through the importer's `session_import::convert` machinery,+ /// compare, and log any divergence (`[session_shadow_read]`, issue #4249,+ /// 04.2 phase 2). Additive and gated on the default-**OFF**+ /// `AgentConfig::session_shadow_reads` flag+ /// (`OPENHUMAN_SESSION_SHADOW_READS` is a kill switch): when disabled this+ /// is a cheap early return.+ ///+ /// The legacy transcript stays authoritative — this only observes. The+ /// comparison runs on a spawned background task so it never slows the+ /// authoritative read, and every store-read error is treated as "no shadow+ /// available" (logged at debug), never propagated.+ fn maybe_shadow_read_session_store(+ &self,+ path: &std::path::Path,+ session: &transcript::SessionTranscript,+ ) {+ use crate::openhuman::agent::session_import::live;++ // Config flag (default OFF) gates the shadow read; the env kill switch+ // can still force it off. `self.config` is the effective per-agent config.+ if !live::shadow_reads_enabled(self.config.session_shadow_reads) {+ return;+ }++ // Same session key the write side / importer use: the transcript stem.+ let Some(stem) = path+ .file_stem()+ .and_then(|s| s.to_str())+ .map(str::to_string)+ else {+ log::debug!(+ "[session_shadow_read] skipped: no file stem for {}",+ path.display()+ );+ return;+ };++ let workspace = self.workspace_dir.clone();+ let transcript = session.clone();+ log::debug!(+ "[session_shadow_read] scheduled stem={stem} workspace={} legacy_messages={}",+ workspace.display(),+ transcript.messages.len()+ );+ tokio::spawn(async move {+ let _ = live::shadow_read_compare(&workspace, &stem, &transcript).await;+ });+ }++ // ─────────────────────────────────────────────────────────────────+ // Session-memory extraction.+ // ─────────────────────────────────────────────────────────────────++ /// Spawn a background archivist sub-agent to extract durable facts+ /// from the recent conversation into `MEMORY.md`. Fire-and-forget.+ ///+ /// Gated by [`context_pipeline::SessionMemoryState::should_extract`]+ /// — see its docs for the threshold invariants. Safe to call from+ /// inside `turn()` after the turn body has settled.+ pub(in super::super) async fn spawn_session_memory_extraction(+ &mut self,+ parent_ctx: harness::ParentExecutionContext,+ ) {+ // ── Flush the trailing open segment before the session winds down ──+ //+ // The ArchivistHook manages per-turn segment lifecycle but cannot+ // force-close the *last* open segment because there is no explicit+ // "session end" event in the turn loop. `spawn_session_memory_extraction`+ // is the closest available signal: it fires when the context manager+ // decides the session has accumulated enough material to archive.+ //+ // GUARANTEE: the flush is *awaited* here (not fire-and-forget) so+ // the trailing segment always receives its recap + embedding + tree+ // ingest before the function returns, even during runtime wind-down.+ // This honours the doc-comment guarantee on `flush_open_segment` in+ // `archivist.rs`. No deadlock risk: no mutex guard is held across+ // this await point.+ if let Some(ref archivist) = self.archivist_hook {+ let session_id = self.event_session_id.clone();+ log::debug!(+ "[archivist] awaiting flush_open_segment for session={session_id} at session wind-down"+ );+ archivist.flush_open_segment(&session_id).await;+ }++ let Some(registry) = harness::AgentDefinitionRegistry::global() else {+ log::debug!("[session_memory] registry not initialised — skipping extraction spawn");+ return;+ };+ let Some(definition) = registry.get("archivist").cloned() else {+ log::debug!(+ "[session_memory] archivist definition not found — skipping extraction spawn"+ );+ return;+ };++ let extraction_prompt = ARCHIVIST_EXTRACTION_PROMPT.to_string();++ // Flip the extraction state to "in-progress" so future+ // should_extract checks return false until the archivist+ // finishes. We then hand a shared handle to the spawned task+ // so it can mark the extraction complete (resets deltas) on+ // success, or failed (keeps deltas intact for retry) on error.+ // This replaces the old optimistic `mark_complete` that+ // silently dropped the retry window when extractions failed.+ let stats_snapshot = self.context.stats();+ self.context.mark_session_memory_started();+ let sm_handle = self.context.session_memory_handle();++ log::info!(+ "[session_memory] spawning background archivist extraction (turn={}, tokens={})",+ stats_snapshot.session_memory_current_turn,+ stats_snapshot.session_memory_total_tokens+ );++ tokio::spawn(async move {+ let options = harness::SubagentRunOptions::default();+ let fut = harness::run_subagent(&definition, &extraction_prompt, options);+ let result = harness::with_parent_context(parent_ctx, fut).await;+ match result {+ Ok(outcome) => {+ tracing::info!(+ agent_id = %outcome.agent_id,+ task_id = %outcome.task_id,+ iterations = outcome.iterations,+ output_chars = outcome.output.chars().count(),+ "[session_memory] archivist extraction completed"+ );+ if let Ok(mut sm) = sm_handle.lock() {+ sm.mark_extraction_complete();+ }+ }+ Err(err) => {+ tracing::warn!(+ error = %err,+ "[session_memory] archivist extraction failed — will retry after next threshold crossing"+ );+ // Leave the deltas intact so the next threshold+ // crossing schedules another attempt. Clearing+ // `extraction_in_progress` lets the retry+ // actually fire.+ if let Ok(mut sm) = sm_handle.lock() {+ sm.mark_extraction_failed();+ }+ }+ }+ });+ }++ /// Spawn a background task that ingests the current session+ /// transcript into the conversational-memory store.+ ///+ /// Issue #1399: complements `spawn_session_memory_extraction`. The+ /// archivist path writes dense bullets into `MEMORY.md`; this path+ /// extracts importance-tagged, provenance-bearing memories via the+ /// heuristic [`crate::openhuman::agent::learning::transcript_ingest`]+ /// pipeline. The two are deliberately independent so the prompt+ /// retrieval layer can pull from `conversation_memory` without+ /// needing the archivist's extraction to have fired this session.+ ///+ /// Fire-and-forget: failures are logged, never propagated.+ pub(in super::super) fn spawn_transcript_ingestion(&self) {+ let Some(path) = self.session_transcript_path.clone() else {+ log::debug!("[transcript_ingest] no session transcript path yet — skipping spawn");+ return;+ };+ let memory = std::sync::Arc::clone(&self.memory);++ tokio::spawn(async move {+ match crate::openhuman::agent::learning::transcript_ingest::ingest_transcript_path(+ memory.as_ref(),+ &path,+ )+ .await+ {+ Ok(report) => tracing::info!(+ transcript = %path.display(),+ extracted = report.extracted,+ stored = report.stored,+ deduped = report.deduped,+ reflections_stored = report.reflections_stored,+ "[transcript_ingest] background ingest complete"+ ),+ Err(err) => tracing::warn!(+ transcript = %path.display(),+ error = %err,+ "[transcript_ingest] background ingest failed — will retry next threshold window"+ ),+ }+ });+ }+}diff --git a/src/openhuman/agent/orchestration/tools/spawn_subagent.rs b/src/openhuman/agent/orchestration/tools/spawn_subagent.rsindex 909d0dad9f..4a05157962 100644--- a/src/openhuman/agent/orchestration/tools/spawn_subagent.rs+++ b/src/openhuman/agent/orchestration/tools/spawn_subagent.rs@@ -69,6 +69,7 @@ impl SpawnSubagentTool {#[async_trait]impl Tool for SpawnSubagentTool {+fn name(&self) -> &str {"spawn_subagent"}diff --git a/src/openhuman/agent/progress_tracing.rs b/src/openhuman/agent/progress_tracing.rsindex 4390703b22..54847bdee6 100644--- a/src/openhuman/agent/progress_tracing.rs+++ b/src/openhuman/agent/progress_tracing.rs@@ -359,905 +359,8 @@ pub struct SpanCollector {/// Live subagents keyed by `task_id`.subagents: BTreeMap<String, SubagentState>,}--impl SpanCollector {- pub fn new(ctx: TraceContext) -> Self {- Self {- ctx,- spans: Vec::new(),- next_span_seq: 0,- id_prefix: uuid::Uuid::new_v4().simple().to_string(),- turn_span_id: None,- turn_span_index: None,- current_iteration_span_id: None,- current_iteration_index: None,- open_tools: BTreeMap::new(),- subagents: BTreeMap::new(),- }- }-- /// Opt into attaching content to spans (prompt/reply, generation- /// request/completion, tool + subagent I/O). Wire this to- /// `observability.agent_tracing.capture_content`. Equivalent to setting- /// [`TraceContext::with_capture_content`] before construction — there is a- /// single storage-level gate (`ctx.capture_content`), so content dropped- /// here can never reach any exporter.- pub fn with_content_capture(mut self, capture_content: bool) -> Self {- self.ctx.capture_content = capture_content;- self- }-- /// All spans recorded so far (finished and in-flight).- pub fn spans(&self) -> &[TraceSpan] {- &self.spans- }-- /// Index of the span with `span_id`, if any.- fn span_index_by_id(&self, span_id: &str) -> Option<usize> {- self.spans.iter().position(|sp| sp.span_id == span_id)- }-- /// Consume the collector and return its spans.- #[cfg(test)]- pub fn into_spans(self) -> Vec<TraceSpan> {- self.spans- }-- /// OTel-style 16-hex span id derived from a monotonic sequence. Stable- /// and deterministic within a run, which keeps the tests reproducible.- fn mint_span_id(&mut self) -> String {- self.next_span_seq += 1;- // Nonce prefix keeps the id globally unique across turns (Langfuse- // dedupes observations by id project-wide).- format!("{}-{:016x}", self.id_prefix, self.next_span_seq)- }-- fn open_span(- &mut self,- kind: SpanKind,- name: impl Into<String>,- parent_span_id: Option<String>,- start_unix_ms: u64,- attributes: BTreeMap<String, serde_json::Value>,- ) -> (String, usize) {- let span_id = self.mint_span_id();- let index = self.spans.len();- self.spans.push(TraceSpan {- trace_id: self.ctx.session_id.clone(),- span_id: span_id.clone(),- parent_span_id,- name: name.into(),- kind,- start_unix_ms,- end_unix_ms: None,- status: SpanStatus::Unset,- attributes,- input: None,- output: None,- });- (span_id, index)- }-- /// Seal a span: set its end timestamp + status and merge in any extra- /// attributes. A no-op if `index` is out of range (defensive).- fn close_span(- &mut self,- index: usize,- end_unix_ms: u64,- status: SpanStatus,- extra: BTreeMap<String, serde_json::Value>,- ) {- if let Some(span) = self.spans.get_mut(index) {- // Don't let a late event drag end before start.- span.end_unix_ms = Some(end_unix_ms.max(span.start_unix_ms));- span.status = status;- span.attributes.extend(extra);- }- }-- /// Lazily open the root turn span so a stream that begins mid-flight- /// (or never sends `TurnStarted`) still produces a correlated tree.- fn ensure_turn_span(&mut self, start_unix_ms: u64) -> String {- if let Some(id) = &self.turn_span_id {- return id.clone();- }- let mut attrs = BTreeMap::new();- attrs.insert(- "session.id".to_string(),- serde_json::Value::String(self.ctx.session_id.clone()),- );- if let Some(user) = &self.ctx.user_id {- attrs.insert(- "user.id".to_string(),- serde_json::Value::String(user.clone()),- );- }- if let Some(client) = &self.ctx.client_id {- attrs.insert(- "client.id".to_string(),- serde_json::Value::String(client.clone()),- );- }- if let Some(agent) = &self.ctx.agent_id {- attrs.insert(- "agent.id".to_string(),- serde_json::Value::String(agent.clone()),- );- }- if let Some(source) = &self.ctx.channel_source {- attrs.insert(- "channel.source".to_string(),- serde_json::Value::String(source.clone()),- );- }- attrs.insert(- "run.type".to_string(),- serde_json::Value::String(self.ctx.run_type.as_str().to_string()),- );- // Every trace must end up with a Langfuse sessionId: prefer the- // explicit grouping key (thread/conversation id), else fall back to- // the trace id itself so the trace is never left session-less.- let group = self- .ctx- .session_group- .clone()- .unwrap_or_else(|| self.ctx.session_id.clone());- attrs.insert("thread.id".to_string(), serde_json::Value::String(group));- // Trace/root-span name carries agent attribution when known.- let name = match &self.ctx.agent_id {- Some(agent) => format!("agent.turn:{agent}"),- None => "agent.turn".to_string(),- };- log::debug!(- "[agent-tracing] opening turn span trace_id={} name={} user_attributed={} client_attributed={} source={:?}",- self.ctx.session_id,- name,- self.ctx.user_id.is_some(),- self.ctx.client_id.is_some(),- self.ctx.channel_source,- );- let (id, index) = self.open_span(SpanKind::Turn, name, None, start_unix_ms, attrs);- self.turn_span_id = Some(id.clone());- self.turn_span_index = Some(index);- id- }-- /// The parent any iteration / tool / subagent span should hang off:- /// the current iteration if one is open, else the turn root.- fn active_parent_id(&mut self, now_unix_ms: u64) -> String {- if let Some(id) = &self.current_iteration_span_id {- return id.clone();- }- self.ensure_turn_span(now_unix_ms)- }-- /// Record a tool call's arguments as the span's `input`, truncated to- /// [`MAX_TOOL_CONTENT_CHARS`]. A no-op unless content capture is on- /// (`observability.agent_tracing.capture_content`) — when off, tool I/O- /// never even reaches the in-memory span. `Null` arguments are skipped.- fn capture_tool_arguments(&mut self, index: usize, arguments: &serde_json::Value) {- if !self.ctx.capture_content || arguments.is_null() {- return;- }- let serialized = arguments.to_string();- let chars = serialized.chars().count();- if let Some(span) = self.spans.get_mut(index) {- span.input = Some(serde_json::Value::String(truncate_capture_text(- &serialized,- )));- log::trace!(- "[agent-tracing] captured tool input span={} chars={chars} truncated={}",- span.name,- chars > MAX_TOOL_CONTENT_CHARS,- );- }- }-- /// Record a tool call's result as the span's `output`, truncated to- /// [`MAX_TOOL_CONTENT_CHARS`]. Same capture gate as- /// [`Self::capture_tool_arguments`]. Empty output is skipped.- fn capture_tool_output(&mut self, index: usize, output: &str) {- if !self.ctx.capture_content || output.is_empty() {- return;- }- let chars = output.chars().count();- if let Some(span) = self.spans.get_mut(index) {- span.output = Some(serde_json::Value::String(truncate_capture_text(output)));- log::trace!(- "[agent-tracing] captured tool output span={} chars={chars} truncated={}",- span.name,- chars > MAX_TOOL_CONTENT_CHARS,- );- }- }-- /// Fold a per-call `ModelCallCompleted` into the tree:- ///- /// 1. emit a closed [`SpanKind::Generation`] span (name `llm.<model>`)- /// parented under the current iteration — or, for a child call- /// (`subagent_task_id` set), under the owning subagent's current- /// iteration — carrying exact per-call model/usage/cost plus provenance- /// (`gen_ai.provider`) and the pricing basis the local estimator uses;- /// 2. record the captured request messages (incl. the system prompt) and- /// completion as the generation's input/output, gated on- /// `capture_content` and truncated to [`MAX_MODEL_CONTENT_CHARS`];- /// 3. accumulate reasoning / cache-creation tokens onto the root turn- /// span, which `TurnCostUpdated` (cumulative rollup) does not carry —- /// and, for child calls, roll model + usage onto the subagent span so- /// a delegation (e.g. the Context Scout) surfaces its model natively.- ///- /// The Langfuse-facing model label is `{provider_id}.{model}` (e.g.- /// `managed.chat-v1`, `openai.gpt-4o`).- ///- /// Generation start is approximated by the enclosing iteration span's- /// start (the iteration opens on `ModelStarted`); end is the observation- /// time of the usage record.- #[allow(clippy::too_many_arguments)]- fn record_model_call(- &mut self,- model: &str,- provider_id: &str,- subagent_task_id: Option<&str>,- input: Option<&serde_json::Value>,- output: Option<&serde_json::Value>,- iteration: u32,- input_tokens: u64,- output_tokens: u64,- cached_input_tokens: u64,- cache_creation_tokens: u64,- reasoning_tokens: u64,- cost_usd: f64,- now_unix_ms: u64,- ) {- // Resolve the parent + start basis: a child call nests under its- // subagent's current iteration (else the subagent span itself); a- // parent call nests under the turn's current iteration (else root).- let subagent_state = subagent_task_id.and_then(|id| self.subagents.get(id));- let (parent, start_basis_index) = match subagent_state {- Some(state) => match &state.current_iteration_span_id {- Some(id) => {- let idx = self.span_index_by_id(id);- (id.clone(), idx)- }- None => (- self.spans[state.span_index].span_id.clone(),- Some(state.span_index),- ),- },- None => {- let parent = self.active_parent_id(now_unix_ms);- (parent, self.current_iteration_index)- }- };- let start_unix_ms = start_basis_index- .and_then(|idx| self.spans.get(idx))- .map(|span| span.start_unix_ms)- .unwrap_or(now_unix_ms);-- let labeled_model = format!("{provider_id}.{model}");- let pricing = crate::openhuman::agent::cost::lookup_pricing(model);-- let mut attrs = BTreeMap::new();- attrs.insert("gen_ai.request.model".to_string(), json_str(&labeled_model));- attrs.insert("gen_ai.provider".to_string(), json_str(provider_id));- attrs.insert("agent.iteration".to_string(), json_u32(iteration));- attrs.insert(- "gen_ai.usage.input_tokens".to_string(),- json_u64(input_tokens),- );- attrs.insert(- "gen_ai.usage.output_tokens".to_string(),- json_u64(output_tokens),- );- // Cache reads always flow (even 0) so usageDetails stay complete.- attrs.insert(- "gen_ai.usage.cached_input_tokens".to_string(),- json_u64(cached_input_tokens),- );- if cache_creation_tokens > 0 {- attrs.insert(- "gen_ai.usage.cache_creation_tokens".to_string(),- json_u64(cache_creation_tokens),- );- }- if reasoning_tokens > 0 {- attrs.insert(- "gen_ai.usage.reasoning_tokens".to_string(),- json_u64(reasoning_tokens),- );- }- attrs.insert("gen_ai.usage.cost_usd".to_string(), json_f64(cost_usd));- // Pricing basis so Langfuse cost figures are auditable against the- // client-side estimator (USD per million tokens).- attrs.insert(- "gen_ai.pricing.input_per_mtok_usd".to_string(),- json_f64(pricing.input_per_mtok_usd),- );- attrs.insert(- "gen_ai.pricing.cached_input_per_mtok_usd".to_string(),- json_f64(pricing.cached_input_per_mtok_usd),- );- attrs.insert(- "gen_ai.pricing.output_per_mtok_usd".to_string(),- json_f64(pricing.output_per_mtok_usd),- );-- log::debug!(- "[agent-tracing] generation span model={labeled_model} \- iteration={iteration} child={} in={input_tokens} out={output_tokens} \- cost_usd={cost_usd:.6} input_captured={} output_captured={}",- subagent_task_id.is_some(),- input.is_some(),- output.is_some(),- );- let (_, index) = self.open_span(- SpanKind::Generation,- format!("llm.{model}"),- Some(parent),- start_unix_ms,- attrs,- );- // Captured request messages (incl. system prompt) + completion become- // the generation's input/output — only while content capture is on,- // truncated so one huge context window can't bloat the trace batch.- if self.ctx.capture_content {- if let Some(span) = self.spans.get_mut(index) {- if let Some(value) = input {- span.input = Some(capture_model_content(value));- }- if let Some(value) = output {- span.output = Some(capture_model_content(value));- }- }- }- self.close_span(index, now_unix_ms, SpanStatus::Ok, BTreeMap::new());-- // Child call: roll model + usage + cost onto the owning subagent span- // so the delegation row (e.g. `subagent.Context Scout`) natively shows- // which model served it and what it cost.- if let Some(state_index) = subagent_task_id- .and_then(|id| self.subagents.get(id))- .map(|state| state.span_index)- {- if let Some(span) = self.spans.get_mut(state_index) {- span.attributes- .insert("gen_ai.request.model".to_string(), json_str(&labeled_model));- span.attributes- .insert("gen_ai.provider".to_string(), json_str(provider_id));- for (key, add) in [- ("gen_ai.usage.input_tokens", input_tokens),- ("gen_ai.usage.output_tokens", output_tokens),- ("gen_ai.usage.cached_input_tokens", cached_input_tokens),- ] {- let prior = span- .attributes- .get(key)- .and_then(serde_json::Value::as_u64)- .unwrap_or(0);- span.attributes- .insert(key.to_string(), json_u64(prior.saturating_add(add)));- }- let prior_cost = span- .attributes- .get("gen_ai.usage.cost_usd")- .and_then(serde_json::Value::as_f64)- .unwrap_or(0.0);- span.attributes.insert(- "gen_ai.usage.cost_usd".to_string(),- json_f64(prior_cost + cost_usd),- );- }- return;- }-- // Root rollup for the usage dimensions the cumulative TurnCostUpdated- // event does not carry (reasoning / cache-creation), plus provenance- // and the provider-labeled model (TurnCostUpdated only knows the raw- // model handle and can fire before the first per-call event).- let root = match self.turn_span_index {- Some(idx) => idx,- None => {- self.ensure_turn_span(now_unix_ms);- self.turn_span_index.expect("turn span just created")- }- };- if let Some(span) = self.spans.get_mut(root) {- span.attributes- .insert("gen_ai.provider".to_string(), json_str(provider_id));- span.attributes- .insert("gen_ai.request.model".to_string(), json_str(&labeled_model));- for (key, add) in [- ("gen_ai.usage.reasoning_tokens", reasoning_tokens),- ("gen_ai.usage.cache_creation_tokens", cache_creation_tokens),- ] {- if add == 0 && !span.attributes.contains_key(key) {- continue;- }- let prior = span- .attributes- .get(key)- .and_then(serde_json::Value::as_u64)- .unwrap_or(0);- span.attributes- .insert(key.to_string(), json_u64(prior.saturating_add(add)));- }- }- }-- fn close_current_iteration(&mut self, end_unix_ms: u64) {- if let Some(index) = self.current_iteration_index.take() {- self.close_span(index, end_unix_ms, SpanStatus::Ok, BTreeMap::new());- }- self.current_iteration_span_id = None;- }-- /// Fold a single progress event into the span tree, stamped at- /// `now_unix_ms` (the consumer's wall clock when it observed the event).- pub fn record(&mut self, event: &AgentProgress, now_unix_ms: u64) {- match event {- AgentProgress::TurnStarted => {- self.ensure_turn_span(now_unix_ms);- }-- AgentProgress::IterationStarted {- iteration,- max_iterations,- } => {- self.close_current_iteration(now_unix_ms);- let parent = self.ensure_turn_span(now_unix_ms);- let mut attrs = BTreeMap::new();- attrs.insert("agent.iteration".to_string(), json_u32(*iteration));- attrs.insert(- "agent.max_iterations".to_string(),- json_u32(*max_iterations),- );- let (id, index) = self.open_span(- SpanKind::Iteration,- format!("agent.iteration#{iteration}"),- Some(parent),- now_unix_ms,- attrs,- );- self.current_iteration_span_id = Some(id);- self.current_iteration_index = Some(index);- }-- AgentProgress::ToolCallStarted {- call_id,- tool_name,- arguments,- iteration,- ..- } => {- let parent = self.active_parent_id(now_unix_ms);- let mut attrs = BTreeMap::new();- attrs.insert("tool.name".to_string(), json_str(tool_name));- attrs.insert("tool.call_id".to_string(), json_str(call_id));- attrs.insert("agent.iteration".to_string(), json_u32(*iteration));- let (_, index) = self.open_span(- SpanKind::Tool,- format!("tool.{tool_name}"),- Some(parent),- now_unix_ms,- attrs,- );- self.capture_tool_arguments(index, arguments);- self.open_tools.insert(call_id.clone(), index);- }-- AgentProgress::ToolCallCompleted {- call_id,- success,- output_chars,- output,- arguments,- elapsed_ms,- failure,- ..- } => {- if let Some(index) = self.open_tools.remove(call_id) {- // The tinyagents path emits `Null` arguments on the started- // event and the real captured arguments on completion —- // backfill the span input when it's still empty.- if self.spans[index].input.is_none() {- if let Some(arguments) = arguments {- self.capture_tool_arguments(index, arguments);- }- }- self.capture_tool_output(index, output);- let start = self.spans[index].start_unix_ms;- let mut extra = BTreeMap::new();- extra.insert(- "tool.success".to_string(),- serde_json::Value::Bool(*success),- );- extra.insert("tool.output_chars".to_string(), json_usize(*output_chars));- extra.insert("tool.elapsed_ms".to_string(), json_u64(*elapsed_ms));- // Failed tool calls surface a Langfuse statusMessage: the- // classified plain-language cause, truncated, gated on- // content capture (it can quote user data / paths).- if let Some(failure) = failure {- if self.ctx.capture_content {- extra.insert(- "error.message".to_string(),- serde_json::Value::String(truncate_chars(- &failure.cause_plain,- MAX_ERROR_MESSAGE_CHARS,- )),- );- }- }- self.close_span(index, start + elapsed_ms, status_of(*success), extra);- }- }-- AgentProgress::ModelCallCompleted {- model,- provider_id,- subagent_task_id,- input,- output,- iteration,- input_tokens,- output_tokens,- cached_input_tokens,- cache_creation_tokens,- reasoning_tokens,- cost_usd,- } => {- self.record_model_call(- model,- provider_id,- subagent_task_id.as_deref(),- input.as_ref(),- output.as_ref(),- *iteration,- *input_tokens,- *output_tokens,- *cached_input_tokens,- *cache_creation_tokens,- *reasoning_tokens,- *cost_usd,- now_unix_ms,- );- }-- AgentProgress::SubagentSpawned {- agent_id,- task_id,- mode,- dedicated_thread,- prompt_chars,- prompt,- display_name,- ..- } => {- let parent = self.active_parent_id(now_unix_ms);- let label = display_name.clone().unwrap_or_else(|| agent_id.clone());- let mut attrs = BTreeMap::new();- attrs.insert("subagent.agent_id".to_string(), json_str(agent_id));- attrs.insert("subagent.task_id".to_string(), json_str(task_id));- attrs.insert("subagent.mode".to_string(), json_str(mode));- attrs.insert(- "subagent.dedicated_thread".to_string(),- serde_json::Value::Bool(*dedicated_thread),- );- attrs.insert(- "subagent.prompt_chars".to_string(),- json_usize(*prompt_chars),- );- if let Some(name) = display_name {- attrs.insert("subagent.display_name".to_string(), json_str(name));- }- let (_, index) = self.open_span(- SpanKind::Subagent,- format!("subagent.{label}"),- Some(parent),- now_unix_ms,- attrs,- );- // The delegated prompt is the subagent span's input (gated +- // truncated like model content — scout prompts run 10k+ chars).- if self.ctx.capture_content && !prompt.is_empty() {- if let Some(span) = self.spans.get_mut(index) {- span.input = Some(serde_json::Value::String(truncate_chars(- prompt,- MAX_MODEL_CONTENT_CHARS,- )));- }- }- self.subagents.insert(- task_id.clone(),- SubagentState {- span_index: index,- current_iteration_span_id: None,- open_tools: BTreeMap::new(),- },- );- }-- AgentProgress::SubagentIterationStarted {- task_id,- iteration,- max_iterations,- extended_policy,- ..- } => {- // Resolve parent + prior child iteration up front so we don't- // hold a borrow across the mutating open_span call.- let (parent_id, prior_iteration_id) = match self.subagents.get(task_id) {- Some(state) => (- self.spans[state.span_index].span_id.clone(),- state.current_iteration_span_id.clone(),- ),- None => return,- };- if let Some(prior) = prior_iteration_id {- if let Some(idx) = self.span_index_by_id(&prior) {- self.close_span(idx, now_unix_ms, SpanStatus::Ok, BTreeMap::new());- }- }- let mut attrs = BTreeMap::new();- attrs.insert("agent.iteration".to_string(), json_u32(*iteration));- attrs.insert(- "agent.max_iterations".to_string(),- json_u32(*max_iterations),- );- attrs.insert(- "agent.extended_policy".to_string(),- serde_json::Value::Bool(*extended_policy),- );- let (id, _) = self.open_span(- SpanKind::SubagentIteration,- format!("subagent.iteration#{iteration}"),- Some(parent_id),- now_unix_ms,- attrs,- );- if let Some(state) = self.subagents.get_mut(task_id) {- state.current_iteration_span_id = Some(id);- }- }-- AgentProgress::SubagentToolCallStarted {- task_id,- call_id,- tool_name,- arguments,- iteration,- ..- } => {- let parent_id = match self.subagents.get(task_id) {- Some(state) => match &state.current_iteration_span_id {- Some(id) => id.clone(),- None => self.spans[state.span_index].span_id.clone(),- },- None => return,- };- let mut attrs = BTreeMap::new();- attrs.insert("tool.name".to_string(), json_str(tool_name));- attrs.insert("tool.call_id".to_string(), json_str(call_id));- attrs.insert("agent.iteration".to_string(), json_u32(*iteration));- let (_, index) = self.open_span(- SpanKind::Tool,- format!("tool.{tool_name}"),- Some(parent_id),- now_unix_ms,- attrs,- );- self.capture_tool_arguments(index, arguments);- if let Some(state) = self.subagents.get_mut(task_id) {- state.open_tools.insert(call_id.clone(), index);- }- }-- AgentProgress::SubagentToolCallCompleted {- task_id,- call_id,- success,- output_chars,- output,- arguments,- elapsed_ms,- ..- } => {- let Some(index) = self- .subagents- .get_mut(task_id)- .and_then(|state| state.open_tools.remove(call_id))- else {- return;- };- if self.spans[index].input.is_none() {- if let Some(arguments) = arguments {- self.capture_tool_arguments(index, arguments);- }- }- self.capture_tool_output(index, output);- let start = self.spans[index].start_unix_ms;- let mut extra = BTreeMap::new();- extra.insert(- "tool.success".to_string(),- serde_json::Value::Bool(*success),- );- extra.insert("tool.output_chars".to_string(), json_usize(*output_chars));- extra.insert("tool.elapsed_ms".to_string(), json_u64(*elapsed_ms));- self.close_span(index, start + elapsed_ms, status_of(*success), extra);- }-- AgentProgress::SubagentCompleted {- task_id,- elapsed_ms,- iterations,- output_chars,- output,- ..- } => {- let Some(state) = self.subagents.remove(task_id) else {- return;- };- if let Some(id) = state.current_iteration_span_id.clone() {- if let Some(idx) = self.span_index_by_id(&id) {- self.close_span(idx, now_unix_ms, SpanStatus::Ok, BTreeMap::new());- }- }- // The subagent's final assistant text is the span's output- // (same gate + cap as its prompt input).- if self.ctx.capture_content && !output.is_empty() {- if let Some(span) = self.spans.get_mut(state.span_index) {- span.output = Some(serde_json::Value::String(truncate_chars(- output,- MAX_MODEL_CONTENT_CHARS,- )));- }- }- let start = self.spans[state.span_index].start_unix_ms;- let mut extra = BTreeMap::new();- extra.insert("subagent.iterations".to_string(), json_u32(*iterations));- extra.insert(- "subagent.output_chars".to_string(),- json_usize(*output_chars),- );- extra.insert("subagent.elapsed_ms".to_string(), json_u64(*elapsed_ms));- self.close_span(state.span_index, start + elapsed_ms, SpanStatus::Ok, extra);- }-- AgentProgress::SubagentFailed { task_id, error, .. } => {- let Some(state) = self.subagents.remove(task_id) else {- return;- };- if let Some(id) = state.current_iteration_span_id.clone() {- if let Some(idx) = self.span_index_by_id(&id) {- self.close_span(idx, now_unix_ms, SpanStatus::Error, BTreeMap::new());- }- }- let mut extra = BTreeMap::new();- // Always record that an error occurred and its length. The raw- // error text (may embed paths / payloads) is recorded — truncated- // — only when content capture is on, and surfaces in Langfuse as- // the observation statusMessage.- extra.insert("error".to_string(), serde_json::Value::Bool(true));- extra.insert("error.length".to_string(), json_usize(error.len()));- if self.ctx.capture_content {- extra.insert(- "error.message".to_string(),- serde_json::Value::String(truncate_chars(error, MAX_ERROR_MESSAGE_CHARS)),- );- }- self.close_span(state.span_index, now_unix_ms, SpanStatus::Error, extra);- }-- AgentProgress::TurnCostUpdated {- model,- input_tokens,- output_tokens,- cached_input_tokens,- total_usd,- ..- } => {- // Cumulative cost/usage rides on the root turn span so a trace- // viewer shows the whole-run total at the top.- let index = match self.turn_span_index {- Some(idx) => idx,- None => {- self.ensure_turn_span(now_unix_ms);- self.turn_span_index.expect("turn span just created")- }- };- if let Some(span) = self.spans.get_mut(index) {- span.attributes- .insert("gen_ai.request.model".to_string(), json_str(model));- span.attributes.insert(- "gen_ai.usage.input_tokens".to_string(),- json_u64(*input_tokens),- );- span.attributes.insert(- "gen_ai.usage.output_tokens".to_string(),- json_u64(*output_tokens),- );- span.attributes.insert(- "gen_ai.usage.cached_input_tokens".to_string(),- json_u64(*cached_input_tokens),- );- span.attributes- .insert("gen_ai.usage.cost_usd".to_string(), json_f64(*total_usd));- }- }-- AgentProgress::TurnContent { input, output } => {- // Storage-level privacy gate (#4454): prompt/reply text is- // attached to the span ONLY when content capture is opted in.- // With the gate off (default), the content is dropped here so no- // exporter — NDJSON file, app log, or Langfuse push — can ever- // serialize it. This is the single choke point; the exporters- // deliberately do not re-check the flag.- if !self.ctx.capture_content {- log::debug!(- target: "agent-tracing",- "[agent-tracing] TurnContent dropped at storage (capture_content=false)"- );- return;- }- let index = match self.turn_span_index {- Some(idx) => idx,- None => {- self.ensure_turn_span(now_unix_ms);- self.turn_span_index.expect("turn span just created")- }- };- if let Some(span) = self.spans.get_mut(index) {- if let Some(text) = input {- span.input = Some(serde_json::Value::String(text.clone()));- }- if let Some(text) = output {- span.output = Some(serde_json::Value::String(text.clone()));- }- log::debug!(- target: "agent-tracing",- "[agent-tracing] TurnContent attached to turn span (capture_content=true)"- );- }- }-- AgentProgress::TurnCompleted { iterations } => {- self.close_current_iteration(now_unix_ms);- if let Some(index) = self.turn_span_index {- let mut extra = BTreeMap::new();- extra.insert("agent.iterations".to_string(), json_u32(*iterations));- self.close_span(index, now_unix_ms, SpanStatus::Ok, extra);- }- }-- // Content-bearing / streaming events carry prompt text, tool- // arguments, or model output — never exported (privacy rule).- AgentProgress::TextDelta { .. }- | AgentProgress::ThinkingDelta { .. }- | AgentProgress::ToolCallArgsDelta { .. }- | AgentProgress::SubagentTextDelta { .. }- | AgentProgress::SubagentThinkingDelta { .. }- | AgentProgress::SubagentAwaitingUser { .. }- | AgentProgress::TaskBoardUpdated { .. } => {}- }- }-- /// Seal every span still open after the stream closes. Idempotent.- pub fn finish(&mut self, now_unix_ms: u64) {- let open: Vec<usize> = self- .spans- .iter()- .enumerate()- .filter(|(_, span)| span.end_unix_ms.is_none())- .map(|(idx, _)| idx)- .collect();- for idx in open {- self.close_span(idx, now_unix_ms, SpanStatus::Unset, BTreeMap::new());- }- self.current_iteration_span_id = None;- self.current_iteration_index = None;- self.open_tools.clear();- self.subagents.clear();- }-}+include!("progress_tracing_impl_01_part_01.rs");+include!("progress_tracing_impl_01_part_02.rs");/// Cap on tool arguments / tool output recorded onto spans when content/// capture is on. Keeps a single runaway tool result from bloating the tracediff --git a/src/openhuman/agent/progress_tracing_impl_01_part_01.rs b/src/openhuman/agent/progress_tracing_impl_01_part_01.rsnew file mode 100644index 0000000000..d6668cd67b--- /dev/null+++ b/src/openhuman/agent/progress_tracing_impl_01_part_01.rs@@ -0,0 +1,433 @@++impl SpanCollector {++ pub fn new(ctx: TraceContext) -> Self {+ Self {+ ctx,+ spans: Vec::new(),+ next_span_seq: 0,+ id_prefix: uuid::Uuid::new_v4().simple().to_string(),+ turn_span_id: None,+ turn_span_index: None,+ current_iteration_span_id: None,+ current_iteration_index: None,+ open_tools: BTreeMap::new(),+ subagents: BTreeMap::new(),+ }+ }++ /// Opt into attaching content to spans (prompt/reply, generation+ /// request/completion, tool + subagent I/O). Wire this to+ /// `observability.agent_tracing.capture_content`. Equivalent to setting+ /// [`TraceContext::with_capture_content`] before construction — there is a+ /// single storage-level gate (`ctx.capture_content`), so content dropped+ /// here can never reach any exporter.+ pub fn with_content_capture(mut self, capture_content: bool) -> Self {+ self.ctx.capture_content = capture_content;+ self+ }++ /// All spans recorded so far (finished and in-flight).+ pub fn spans(&self) -> &[TraceSpan] {+ &self.spans+ }++ /// Index of the span with `span_id`, if any.+ fn span_index_by_id(&self, span_id: &str) -> Option<usize> {+ self.spans.iter().position(|sp| sp.span_id == span_id)+ }++ /// Consume the collector and return its spans.+ #[cfg(test)]+ pub fn into_spans(self) -> Vec<TraceSpan> {+ self.spans+ }++ /// OTel-style 16-hex span id derived from a monotonic sequence. Stable+ /// and deterministic within a run, which keeps the tests reproducible.+ fn mint_span_id(&mut self) -> String {+ self.next_span_seq += 1;+ // Nonce prefix keeps the id globally unique across turns (Langfuse+ // dedupes observations by id project-wide).+ format!("{}-{:016x}", self.id_prefix, self.next_span_seq)+ }++ fn open_span(+ &mut self,+ kind: SpanKind,+ name: impl Into<String>,+ parent_span_id: Option<String>,+ start_unix_ms: u64,+ attributes: BTreeMap<String, serde_json::Value>,+ ) -> (String, usize) {+ let span_id = self.mint_span_id();+ let index = self.spans.len();+ self.spans.push(TraceSpan {+ trace_id: self.ctx.session_id.clone(),+ span_id: span_id.clone(),+ parent_span_id,+ name: name.into(),+ kind,+ start_unix_ms,+ end_unix_ms: None,+ status: SpanStatus::Unset,+ attributes,+ input: None,+ output: None,+ });+ (span_id, index)+ }++ /// Seal a span: set its end timestamp + status and merge in any extra+ /// attributes. A no-op if `index` is out of range (defensive).+ fn close_span(+ &mut self,+ index: usize,+ end_unix_ms: u64,+ status: SpanStatus,+ extra: BTreeMap<String, serde_json::Value>,+ ) {+ if let Some(span) = self.spans.get_mut(index) {+ // Don't let a late event drag end before start.+ span.end_unix_ms = Some(end_unix_ms.max(span.start_unix_ms));+ span.status = status;+ span.attributes.extend(extra);+ }+ }++ /// Lazily open the root turn span so a stream that begins mid-flight+ /// (or never sends `TurnStarted`) still produces a correlated tree.+ fn ensure_turn_span(&mut self, start_unix_ms: u64) -> String {+ if let Some(id) = &self.turn_span_id {+ return id.clone();+ }+ let mut attrs = BTreeMap::new();+ attrs.insert(+ "session.id".to_string(),+ serde_json::Value::String(self.ctx.session_id.clone()),+ );+ if let Some(user) = &self.ctx.user_id {+ attrs.insert(+ "user.id".to_string(),+ serde_json::Value::String(user.clone()),+ );+ }+ if let Some(client) = &self.ctx.client_id {+ attrs.insert(+ "client.id".to_string(),+ serde_json::Value::String(client.clone()),+ );+ }+ if let Some(agent) = &self.ctx.agent_id {+ attrs.insert(+ "agent.id".to_string(),+ serde_json::Value::String(agent.clone()),+ );+ }+ if let Some(source) = &self.ctx.channel_source {+ attrs.insert(+ "channel.source".to_string(),+ serde_json::Value::String(source.clone()),+ );+ }+ attrs.insert(+ "run.type".to_string(),+ serde_json::Value::String(self.ctx.run_type.as_str().to_string()),+ );+ // Every trace must end up with a Langfuse sessionId: prefer the+ // explicit grouping key (thread/conversation id), else fall back to+ // the trace id itself so the trace is never left session-less.+ let group = self+ .ctx+ .session_group+ .clone()+ .unwrap_or_else(|| self.ctx.session_id.clone());+ attrs.insert("thread.id".to_string(), serde_json::Value::String(group));+ // Trace/root-span name carries agent attribution when known.+ let name = match &self.ctx.agent_id {+ Some(agent) => format!("agent.turn:{agent}"),+ None => "agent.turn".to_string(),+ };+ log::debug!(+ "[agent-tracing] opening turn span trace_id={} name={} user_attributed={} client_attributed={} source={:?}",+ self.ctx.session_id,+ name,+ self.ctx.user_id.is_some(),+ self.ctx.client_id.is_some(),+ self.ctx.channel_source,+ );+ let (id, index) = self.open_span(SpanKind::Turn, name, None, start_unix_ms, attrs);+ self.turn_span_id = Some(id.clone());+ self.turn_span_index = Some(index);+ id+ }++ /// The parent any iteration / tool / subagent span should hang off:+ /// the current iteration if one is open, else the turn root.+ fn active_parent_id(&mut self, now_unix_ms: u64) -> String {+ if let Some(id) = &self.current_iteration_span_id {+ return id.clone();+ }+ self.ensure_turn_span(now_unix_ms)+ }++ /// Record a tool call's arguments as the span's `input`, truncated to+ /// [`MAX_TOOL_CONTENT_CHARS`]. A no-op unless content capture is on+ /// (`observability.agent_tracing.capture_content`) — when off, tool I/O+ /// never even reaches the in-memory span. `Null` arguments are skipped.+ fn capture_tool_arguments(&mut self, index: usize, arguments: &serde_json::Value) {+ if !self.ctx.capture_content || arguments.is_null() {+ return;+ }+ let serialized = arguments.to_string();+ let chars = serialized.chars().count();+ if let Some(span) = self.spans.get_mut(index) {+ span.input = Some(serde_json::Value::String(truncate_capture_text(+ &serialized,+ )));+ log::trace!(+ "[agent-tracing] captured tool input span={} chars={chars} truncated={}",+ span.name,+ chars > MAX_TOOL_CONTENT_CHARS,+ );+ }+ }++ /// Record a tool call's result as the span's `output`, truncated to+ /// [`MAX_TOOL_CONTENT_CHARS`]. Same capture gate as+ /// [`Self::capture_tool_arguments`]. Empty output is skipped.+ fn capture_tool_output(&mut self, index: usize, output: &str) {+ if !self.ctx.capture_content || output.is_empty() {+ return;+ }+ let chars = output.chars().count();+ if let Some(span) = self.spans.get_mut(index) {+ span.output = Some(serde_json::Value::String(truncate_capture_text(output)));+ log::trace!(+ "[agent-tracing] captured tool output span={} chars={chars} truncated={}",+ span.name,+ chars > MAX_TOOL_CONTENT_CHARS,+ );+ }+ }++ /// Fold a per-call `ModelCallCompleted` into the tree:+ ///+ /// 1. emit a closed [`SpanKind::Generation`] span (name `llm.<model>`)+ /// parented under the current iteration — or, for a child call+ /// (`subagent_task_id` set), under the owning subagent's current+ /// iteration — carrying exact per-call model/usage/cost plus provenance+ /// (`gen_ai.provider`) and the pricing basis the local estimator uses;+ /// 2. record the captured request messages (incl. the system prompt) and+ /// completion as the generation's input/output, gated on+ /// `capture_content` and truncated to [`MAX_MODEL_CONTENT_CHARS`];+ /// 3. accumulate reasoning / cache-creation tokens onto the root turn+ /// span, which `TurnCostUpdated` (cumulative rollup) does not carry —+ /// and, for child calls, roll model + usage onto the subagent span so+ /// a delegation (e.g. the Context Scout) surfaces its model natively.+ ///+ /// The Langfuse-facing model label is `{provider_id}.{model}` (e.g.+ /// `managed.chat-v1`, `openai.gpt-4o`).+ ///+ /// Generation start is approximated by the enclosing iteration span's+ /// start (the iteration opens on `ModelStarted`); end is the observation+ /// time of the usage record.+ #[allow(clippy::too_many_arguments)]+ fn record_model_call(+ &mut self,+ model: &str,+ provider_id: &str,+ subagent_task_id: Option<&str>,+ input: Option<&serde_json::Value>,+ output: Option<&serde_json::Value>,+ iteration: u32,+ input_tokens: u64,+ output_tokens: u64,+ cached_input_tokens: u64,+ cache_creation_tokens: u64,+ reasoning_tokens: u64,+ cost_usd: f64,+ now_unix_ms: u64,+ ) {+ // Resolve the parent + start basis: a child call nests under its+ // subagent's current iteration (else the subagent span itself); a+ // parent call nests under the turn's current iteration (else root).+ let subagent_state = subagent_task_id.and_then(|id| self.subagents.get(id));+ let (parent, start_basis_index) = match subagent_state {+ Some(state) => match &state.current_iteration_span_id {+ Some(id) => {+ let idx = self.span_index_by_id(id);+ (id.clone(), idx)+ }+ None => (+ self.spans[state.span_index].span_id.clone(),+ Some(state.span_index),+ ),+ },+ None => {+ let parent = self.active_parent_id(now_unix_ms);+ (parent, self.current_iteration_index)+ }+ };+ let start_unix_ms = start_basis_index+ .and_then(|idx| self.spans.get(idx))+ .map(|span| span.start_unix_ms)+ .unwrap_or(now_unix_ms);++ let labeled_model = format!("{provider_id}.{model}");+ let pricing = crate::openhuman::agent::cost::lookup_pricing(model);++ let mut attrs = BTreeMap::new();+ attrs.insert("gen_ai.request.model".to_string(), json_str(&labeled_model));+ attrs.insert("gen_ai.provider".to_string(), json_str(provider_id));+ attrs.insert("agent.iteration".to_string(), json_u32(iteration));+ attrs.insert(+ "gen_ai.usage.input_tokens".to_string(),+ json_u64(input_tokens),+ );+ attrs.insert(+ "gen_ai.usage.output_tokens".to_string(),+ json_u64(output_tokens),+ );+ // Cache reads always flow (even 0) so usageDetails stay complete.+ attrs.insert(+ "gen_ai.usage.cached_input_tokens".to_string(),+ json_u64(cached_input_tokens),+ );+ if cache_creation_tokens > 0 {+ attrs.insert(+ "gen_ai.usage.cache_creation_tokens".to_string(),+ json_u64(cache_creation_tokens),+ );+ }+ if reasoning_tokens > 0 {+ attrs.insert(+ "gen_ai.usage.reasoning_tokens".to_string(),+ json_u64(reasoning_tokens),+ );+ }+ attrs.insert("gen_ai.usage.cost_usd".to_string(), json_f64(cost_usd));+ // Pricing basis so Langfuse cost figures are auditable against the+ // client-side estimator (USD per million tokens).+ attrs.insert(+ "gen_ai.pricing.input_per_mtok_usd".to_string(),+ json_f64(pricing.input_per_mtok_usd),+ );+ attrs.insert(+ "gen_ai.pricing.cached_input_per_mtok_usd".to_string(),+ json_f64(pricing.cached_input_per_mtok_usd),+ );+ attrs.insert(+ "gen_ai.pricing.output_per_mtok_usd".to_string(),+ json_f64(pricing.output_per_mtok_usd),+ );++ log::debug!(+ "[agent-tracing] generation span model={labeled_model} \+ iteration={iteration} child={} in={input_tokens} out={output_tokens} \+ cost_usd={cost_usd:.6} input_captured={} output_captured={}",+ subagent_task_id.is_some(),+ input.is_some(),+ output.is_some(),+ );+ let (_, index) = self.open_span(+ SpanKind::Generation,+ format!("llm.{model}"),+ Some(parent),+ start_unix_ms,+ attrs,+ );+ // Captured request messages (incl. system prompt) + completion become+ // the generation's input/output — only while content capture is on,+ // truncated so one huge context window can't bloat the trace batch.+ if self.ctx.capture_content {+ if let Some(span) = self.spans.get_mut(index) {+ if let Some(value) = input {+ span.input = Some(capture_model_content(value));+ }+ if let Some(value) = output {+ span.output = Some(capture_model_content(value));+ }+ }+ }+ self.close_span(index, now_unix_ms, SpanStatus::Ok, BTreeMap::new());++ // Child call: roll model + usage + cost onto the owning subagent span+ // so the delegation row (e.g. `subagent.Context Scout`) natively shows+ // which model served it and what it cost.+ if let Some(state_index) = subagent_task_id+ .and_then(|id| self.subagents.get(id))+ .map(|state| state.span_index)+ {+ if let Some(span) = self.spans.get_mut(state_index) {+ span.attributes+ .insert("gen_ai.request.model".to_string(), json_str(&labeled_model));+ span.attributes+ .insert("gen_ai.provider".to_string(), json_str(provider_id));+ for (key, add) in [+ ("gen_ai.usage.input_tokens", input_tokens),+ ("gen_ai.usage.output_tokens", output_tokens),+ ("gen_ai.usage.cached_input_tokens", cached_input_tokens),+ ] {+ let prior = span+ .attributes+ .get(key)+ .and_then(serde_json::Value::as_u64)+ .unwrap_or(0);+ span.attributes+ .insert(key.to_string(), json_u64(prior.saturating_add(add)));+ }+ let prior_cost = span+ .attributes+ .get("gen_ai.usage.cost_usd")+ .and_then(serde_json::Value::as_f64)+ .unwrap_or(0.0);+ span.attributes.insert(+ "gen_ai.usage.cost_usd".to_string(),+ json_f64(prior_cost + cost_usd),+ );+ }+ return;+ }++ // Root rollup for the usage dimensions the cumulative TurnCostUpdated+ // event does not carry (reasoning / cache-creation), plus provenance+ // and the provider-labeled model (TurnCostUpdated only knows the raw+ // model handle and can fire before the first per-call event).+ let root = match self.turn_span_index {+ Some(idx) => idx,+ None => {+ self.ensure_turn_span(now_unix_ms);+ self.turn_span_index.expect("turn span just created")+ }+ };+ if let Some(span) = self.spans.get_mut(root) {+ span.attributes+ .insert("gen_ai.provider".to_string(), json_str(provider_id));+ span.attributes+ .insert("gen_ai.request.model".to_string(), json_str(&labeled_model));+ for (key, add) in [+ ("gen_ai.usage.reasoning_tokens", reasoning_tokens),+ ("gen_ai.usage.cache_creation_tokens", cache_creation_tokens),+ ] {+ if add == 0 && !span.attributes.contains_key(key) {+ continue;+ }+ let prior = span+ .attributes+ .get(key)+ .and_then(serde_json::Value::as_u64)+ .unwrap_or(0);+ span.attributes+ .insert(key.to_string(), json_u64(prior.saturating_add(add)));+ }+ }+ }++ fn close_current_iteration(&mut self, end_unix_ms: u64) {+ if let Some(index) = self.current_iteration_index.take() {+ self.close_span(index, end_unix_ms, SpanStatus::Ok, BTreeMap::new());+ }+ self.current_iteration_span_id = None;+ }+}diff --git a/src/openhuman/agent/progress_tracing_impl_01_part_02.rs b/src/openhuman/agent/progress_tracing_impl_01_part_02.rsnew file mode 100644index 0000000000..294c2e9dc0--- /dev/null+++ b/src/openhuman/agent/progress_tracing_impl_01_part_02.rs@@ -0,0 +1,469 @@++impl SpanCollector {+ /// Fold a single progress event into the span tree, stamped at+ /// `now_unix_ms` (the consumer's wall clock when it observed the event).+ pub fn record(&mut self, event: &AgentProgress, now_unix_ms: u64) {+ match event {+ AgentProgress::TurnStarted => {+ self.ensure_turn_span(now_unix_ms);+ }++ AgentProgress::IterationStarted {+ iteration,+ max_iterations,+ } => {+ self.close_current_iteration(now_unix_ms);+ let parent = self.ensure_turn_span(now_unix_ms);+ let mut attrs = BTreeMap::new();+ attrs.insert("agent.iteration".to_string(), json_u32(*iteration));+ attrs.insert(+ "agent.max_iterations".to_string(),+ json_u32(*max_iterations),+ );+ let (id, index) = self.open_span(+ SpanKind::Iteration,+ format!("agent.iteration#{iteration}"),+ Some(parent),+ now_unix_ms,+ attrs,+ );+ self.current_iteration_span_id = Some(id);+ self.current_iteration_index = Some(index);+ }++ AgentProgress::ToolCallStarted {+ call_id,+ tool_name,+ arguments,+ iteration,+ ..+ } => {+ let parent = self.active_parent_id(now_unix_ms);+ let mut attrs = BTreeMap::new();+ attrs.insert("tool.name".to_string(), json_str(tool_name));+ attrs.insert("tool.call_id".to_string(), json_str(call_id));+ attrs.insert("agent.iteration".to_string(), json_u32(*iteration));+ let (_, index) = self.open_span(+ SpanKind::Tool,+ format!("tool.{tool_name}"),+ Some(parent),+ now_unix_ms,+ attrs,+ );+ self.capture_tool_arguments(index, arguments);+ self.open_tools.insert(call_id.clone(), index);+ }++ AgentProgress::ToolCallCompleted {+ call_id,+ success,+ output_chars,+ output,+ arguments,+ elapsed_ms,+ failure,+ ..+ } => {+ if let Some(index) = self.open_tools.remove(call_id) {+ // The tinyagents path emits `Null` arguments on the started+ // event and the real captured arguments on completion —+ // backfill the span input when it's still empty.+ if self.spans[index].input.is_none() {+ if let Some(arguments) = arguments {+ self.capture_tool_arguments(index, arguments);+ }+ }+ self.capture_tool_output(index, output);+ let start = self.spans[index].start_unix_ms;+ let mut extra = BTreeMap::new();+ extra.insert(+ "tool.success".to_string(),+ serde_json::Value::Bool(*success),+ );+ extra.insert("tool.output_chars".to_string(), json_usize(*output_chars));+ extra.insert("tool.elapsed_ms".to_string(), json_u64(*elapsed_ms));+ // Failed tool calls surface a Langfuse statusMessage: the+ // classified plain-language cause, truncated, gated on+ // content capture (it can quote user data / paths).+ if let Some(failure) = failure {+ if self.ctx.capture_content {+ extra.insert(+ "error.message".to_string(),+ serde_json::Value::String(truncate_chars(+ &failure.cause_plain,+ MAX_ERROR_MESSAGE_CHARS,+ )),+ );+ }+ }+ self.close_span(index, start + elapsed_ms, status_of(*success), extra);+ }+ }++ AgentProgress::ModelCallCompleted {+ model,+ provider_id,+ subagent_task_id,+ input,+ output,+ iteration,+ input_tokens,+ output_tokens,+ cached_input_tokens,+ cache_creation_tokens,+ reasoning_tokens,+ cost_usd,+ } => {+ self.record_model_call(+ model,+ provider_id,+ subagent_task_id.as_deref(),+ input.as_ref(),+ output.as_ref(),+ *iteration,+ *input_tokens,+ *output_tokens,+ *cached_input_tokens,+ *cache_creation_tokens,+ *reasoning_tokens,+ *cost_usd,+ now_unix_ms,+ );+ }++ AgentProgress::SubagentSpawned {+ agent_id,+ task_id,+ mode,+ dedicated_thread,+ prompt_chars,+ prompt,+ display_name,+ ..+ } => {+ let parent = self.active_parent_id(now_unix_ms);+ let label = display_name.clone().unwrap_or_else(|| agent_id.clone());+ let mut attrs = BTreeMap::new();+ attrs.insert("subagent.agent_id".to_string(), json_str(agent_id));+ attrs.insert("subagent.task_id".to_string(), json_str(task_id));+ attrs.insert("subagent.mode".to_string(), json_str(mode));+ attrs.insert(+ "subagent.dedicated_thread".to_string(),+ serde_json::Value::Bool(*dedicated_thread),+ );+ attrs.insert(+ "subagent.prompt_chars".to_string(),+ json_usize(*prompt_chars),+ );+ if let Some(name) = display_name {+ attrs.insert("subagent.display_name".to_string(), json_str(name));+ }+ let (_, index) = self.open_span(+ SpanKind::Subagent,+ format!("subagent.{label}"),+ Some(parent),+ now_unix_ms,+ attrs,+ );+ // The delegated prompt is the subagent span's input (gated ++ // truncated like model content — scout prompts run 10k+ chars).+ if self.ctx.capture_content && !prompt.is_empty() {+ if let Some(span) = self.spans.get_mut(index) {+ span.input = Some(serde_json::Value::String(truncate_chars(+ prompt,+ MAX_MODEL_CONTENT_CHARS,+ )));+ }+ }+ self.subagents.insert(+ task_id.clone(),+ SubagentState {+ span_index: index,+ current_iteration_span_id: None,+ open_tools: BTreeMap::new(),+ },+ );+ }++ AgentProgress::SubagentIterationStarted {+ task_id,+ iteration,+ max_iterations,+ extended_policy,+ ..+ } => {+ // Resolve parent + prior child iteration up front so we don't+ // hold a borrow across the mutating open_span call.+ let (parent_id, prior_iteration_id) = match self.subagents.get(task_id) {+ Some(state) => (+ self.spans[state.span_index].span_id.clone(),+ state.current_iteration_span_id.clone(),+ ),+ None => return,+ };+ if let Some(prior) = prior_iteration_id {+ if let Some(idx) = self.span_index_by_id(&prior) {+ self.close_span(idx, now_unix_ms, SpanStatus::Ok, BTreeMap::new());+ }+ }+ let mut attrs = BTreeMap::new();+ attrs.insert("agent.iteration".to_string(), json_u32(*iteration));+ attrs.insert(+ "agent.max_iterations".to_string(),+ json_u32(*max_iterations),+ );+ attrs.insert(+ "agent.extended_policy".to_string(),+ serde_json::Value::Bool(*extended_policy),+ );+ let (id, _) = self.open_span(+ SpanKind::SubagentIteration,+ format!("subagent.iteration#{iteration}"),+ Some(parent_id),+ now_unix_ms,+ attrs,+ );+ if let Some(state) = self.subagents.get_mut(task_id) {+ state.current_iteration_span_id = Some(id);+ }+ }++ AgentProgress::SubagentToolCallStarted {+ task_id,+ call_id,+ tool_name,+ arguments,+ iteration,+ ..+ } => {+ let parent_id = match self.subagents.get(task_id) {+ Some(state) => match &state.current_iteration_span_id {+ Some(id) => id.clone(),+ None => self.spans[state.span_index].span_id.clone(),+ },+ None => return,+ };+ let mut attrs = BTreeMap::new();+ attrs.insert("tool.name".to_string(), json_str(tool_name));+ attrs.insert("tool.call_id".to_string(), json_str(call_id));+ attrs.insert("agent.iteration".to_string(), json_u32(*iteration));+ let (_, index) = self.open_span(+ SpanKind::Tool,+ format!("tool.{tool_name}"),+ Some(parent_id),+ now_unix_ms,+ attrs,+ );+ self.capture_tool_arguments(index, arguments);+ if let Some(state) = self.subagents.get_mut(task_id) {+ state.open_tools.insert(call_id.clone(), index);+ }+ }++ AgentProgress::SubagentToolCallCompleted {+ task_id,+ call_id,+ success,+ output_chars,+ output,+ arguments,+ elapsed_ms,+ ..+ } => {+ let Some(index) = self+ .subagents+ .get_mut(task_id)+ .and_then(|state| state.open_tools.remove(call_id))+ else {+ return;+ };+ if self.spans[index].input.is_none() {+ if let Some(arguments) = arguments {+ self.capture_tool_arguments(index, arguments);+ }+ }+ self.capture_tool_output(index, output);+ let start = self.spans[index].start_unix_ms;+ let mut extra = BTreeMap::new();+ extra.insert(+ "tool.success".to_string(),+ serde_json::Value::Bool(*success),+ );+ extra.insert("tool.output_chars".to_string(), json_usize(*output_chars));+ extra.insert("tool.elapsed_ms".to_string(), json_u64(*elapsed_ms));+ self.close_span(index, start + elapsed_ms, status_of(*success), extra);+ }++ AgentProgress::SubagentCompleted {+ task_id,+ elapsed_ms,+ iterations,+ output_chars,+ output,+ ..+ } => {+ let Some(state) = self.subagents.remove(task_id) else {+ return;+ };+ if let Some(id) = state.current_iteration_span_id.clone() {+ if let Some(idx) = self.span_index_by_id(&id) {+ self.close_span(idx, now_unix_ms, SpanStatus::Ok, BTreeMap::new());+ }+ }+ // The subagent's final assistant text is the span's output+ // (same gate + cap as its prompt input).+ if self.ctx.capture_content && !output.is_empty() {+ if let Some(span) = self.spans.get_mut(state.span_index) {+ span.output = Some(serde_json::Value::String(truncate_chars(+ output,+ MAX_MODEL_CONTENT_CHARS,+ )));+ }+ }+ let start = self.spans[state.span_index].start_unix_ms;+ let mut extra = BTreeMap::new();+ extra.insert("subagent.iterations".to_string(), json_u32(*iterations));+ extra.insert(+ "subagent.output_chars".to_string(),+ json_usize(*output_chars),+ );+ extra.insert("subagent.elapsed_ms".to_string(), json_u64(*elapsed_ms));+ self.close_span(state.span_index, start + elapsed_ms, SpanStatus::Ok, extra);+ }++ AgentProgress::SubagentFailed { task_id, error, .. } => {+ let Some(state) = self.subagents.remove(task_id) else {+ return;+ };+ if let Some(id) = state.current_iteration_span_id.clone() {+ if let Some(idx) = self.span_index_by_id(&id) {+ self.close_span(idx, now_unix_ms, SpanStatus::Error, BTreeMap::new());+ }+ }+ let mut extra = BTreeMap::new();+ // Always record that an error occurred and its length. The raw+ // error text (may embed paths / payloads) is recorded — truncated+ // — only when content capture is on, and surfaces in Langfuse as+ // the observation statusMessage.+ extra.insert("error".to_string(), serde_json::Value::Bool(true));+ extra.insert("error.length".to_string(), json_usize(error.len()));+ if self.ctx.capture_content {+ extra.insert(+ "error.message".to_string(),+ serde_json::Value::String(truncate_chars(error, MAX_ERROR_MESSAGE_CHARS)),+ );+ }+ self.close_span(state.span_index, now_unix_ms, SpanStatus::Error, extra);+ }++ AgentProgress::TurnCostUpdated {+ model,+ input_tokens,+ output_tokens,+ cached_input_tokens,+ total_usd,+ ..+ } => {+ // Cumulative cost/usage rides on the root turn span so a trace+ // viewer shows the whole-run total at the top.+ let index = match self.turn_span_index {+ Some(idx) => idx,+ None => {+ self.ensure_turn_span(now_unix_ms);+ self.turn_span_index.expect("turn span just created")+ }+ };+ if let Some(span) = self.spans.get_mut(index) {+ span.attributes+ .insert("gen_ai.request.model".to_string(), json_str(model));+ span.attributes.insert(+ "gen_ai.usage.input_tokens".to_string(),+ json_u64(*input_tokens),+ );+ span.attributes.insert(+ "gen_ai.usage.output_tokens".to_string(),+ json_u64(*output_tokens),+ );+ span.attributes.insert(+ "gen_ai.usage.cached_input_tokens".to_string(),+ json_u64(*cached_input_tokens),+ );+ span.attributes+ .insert("gen_ai.usage.cost_usd".to_string(), json_f64(*total_usd));+ }+ }++ AgentProgress::TurnContent { input, output } => {+ // Storage-level privacy gate (#4454): prompt/reply text is+ // attached to the span ONLY when content capture is opted in.+ // With the gate off (default), the content is dropped here so no+ // exporter — NDJSON file, app log, or Langfuse push — can ever+ // serialize it. This is the single choke point; the exporters+ // deliberately do not re-check the flag.+ if !self.ctx.capture_content {+ log::debug!(+ target: "agent-tracing",+ "[agent-tracing] TurnContent dropped at storage (capture_content=false)"+ );+ return;+ }+ let index = match self.turn_span_index {+ Some(idx) => idx,+ None => {+ self.ensure_turn_span(now_unix_ms);+ self.turn_span_index.expect("turn span just created")+ }+ };+ if let Some(span) = self.spans.get_mut(index) {+ if let Some(text) = input {+ span.input = Some(serde_json::Value::String(text.clone()));+ }+ if let Some(text) = output {+ span.output = Some(serde_json::Value::String(text.clone()));+ }+ log::debug!(+ target: "agent-tracing",+ "[agent-tracing] TurnContent attached to turn span (capture_content=true)"+ );+ }+ }++ AgentProgress::TurnCompleted { iterations } => {+ self.close_current_iteration(now_unix_ms);+ if let Some(index) = self.turn_span_index {+ let mut extra = BTreeMap::new();+ extra.insert("agent.iterations".to_string(), json_u32(*iterations));+ self.close_span(index, now_unix_ms, SpanStatus::Ok, extra);+ }+ }++ // Content-bearing / streaming events carry prompt text, tool+ // arguments, or model output — never exported (privacy rule).+ AgentProgress::TextDelta { .. }+ | AgentProgress::ThinkingDelta { .. }+ | AgentProgress::ToolCallArgsDelta { .. }+ | AgentProgress::SubagentTextDelta { .. }+ | AgentProgress::SubagentThinkingDelta { .. }+ | AgentProgress::SubagentAwaitingUser { .. }+ | AgentProgress::TaskBoardUpdated { .. } => {}+ }+ }++ /// Seal every span still open after the stream closes. Idempotent.+ pub fn finish(&mut self, now_unix_ms: u64) {+ let open: Vec<usize> = self+ .spans+ .iter()+ .enumerate()+ .filter(|(_, span)| span.end_unix_ms.is_none())+ .map(|(idx, _)| idx)+ .collect();+ for idx in open {+ self.close_span(idx, now_unix_ms, SpanStatus::Unset, BTreeMap::new());+ }+ self.current_iteration_span_id = None;+ self.current_iteration_index = None;+ self.open_tools.clear();+ self.subagents.clear();+ }+}diff --git a/src/openhuman/config/schema/load/env_overlay.rs b/src/openhuman/config/schema/load/env_overlay.rsindex b9d894ebf6..0eabc3ac89 100644--- a/src/openhuman/config/schema/load/env_overlay.rs+++ b/src/openhuman/config/schema/load/env_overlay.rs@@ -31,1053 +31,5 @@ pub(super) fn classify_shell_hide_window(raw: &str) -> ShellHideWindowParse {_ => ShellHideWindowParse::Unrecognized,}}--impl Config {- pub fn apply_env_overrides(&mut self) {- use super::env::ProcessEnv;- self.apply_env_overrides_from(&ProcessEnv);- }-- pub(super) fn apply_env_overrides_from(- &mut self,- env: &(dyn super::env::EnvLookup + Send + Sync),- ) {- self.apply_env_overlay_with(env);-- if self.proxy.enabled && self.proxy.scope == ProxyScope::Environment {- self.proxy.apply_to_process_env();- }-- set_runtime_proxy_config(self.proxy.clone());-- crate::openhuman::inference::embeddings::rate_limit::set_embedding_rate_limit(- self.memory.embedding_rate_limit_per_min,- );-- // Launch flags are process-local and intentionally win over both the- // persisted file and ordinary environment overlays. They are applied- // after loading so `openhuman -p <provider> -m <model>` never mutates- // config.toml and desktop launches remain unaffected.- super::super::cli_overrides::apply_cli_inference_overrides(self);- }-- /// Pure-ish env overlay: applies overrides read from `env` to `self`.- ///- /// "Pure-ish" because it still emits `tracing` logs and calls- /// `self.proxy.validate()` (which only reads). Crucially, it does- /// **not** write to the process environment nor the- /// `set_runtime_proxy_config` global — those stay in the public- /// [`Self::apply_env_overrides`] wrapper so unit tests can call this- /// with a [`HashMapEnv`] (see tests) without requiring the- /// `TEST_ENV_LOCK` or tainting sibling tests.- pub(crate) fn apply_env_overlay_with<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- // Only the namespaced `OPENHUMAN_MODEL` is honoured. The bare `MODEL`- // env var used to be accepted as an alias but collides with vendor- // asset-tag env vars (e.g. Dell OptiPlex sets `MODEL=7080`), which- // silently clobbered the LLM model and 400'd every backend call- // (Sentry OPENHUMAN-TAURI-J8).- if let Some(model) = env.get("OPENHUMAN_MODEL") {- let trimmed = model.trim();- if !trimmed.is_empty() {- self.default_model = Some(trimmed.to_string());- }- }-- if let Some(workspace) = env.get("OPENHUMAN_WORKSPACE") {- if !workspace.is_empty() {- let (_, workspace_dir) =- super::dirs::resolve_config_dir_for_workspace(&PathBuf::from(workspace));- self.workspace_dir = workspace_dir;- }- }-- if let Some(v) = env.get("OPENHUMAN_ACTION_DIR") {- let trimmed = v.trim();- if !trimmed.is_empty() {- self.action_dir = PathBuf::from(trimmed);- }- }-- if let Some(temp_str) = env.get("OPENHUMAN_TEMPERATURE") {- if let Ok(temp) = temp_str.parse::<f64>() {- if (0.0..=2.0).contains(&temp) {- self.default_temperature = temp;- }- }- }-- if let Some(raw) = env.get("OPENHUMAN_MAX_ACTIONS_PER_HOUR") {- let trimmed = raw.trim();- if !trimmed.is_empty() {- match trimmed.parse::<u32>() {- Ok(limit) => self.autonomy.max_actions_per_hour = limit,- Err(_) => tracing::warn!(- value = %raw,- "invalid OPENHUMAN_MAX_ACTIONS_PER_HOUR ignored; expected an unsigned integer"- ),- }- }- }-- if let Some(raw) = env.get(MEMORY_SYNC_INTERVAL_SECS_ENV_VAR) {- let trimmed = raw.trim();- if !trimmed.is_empty() {- match trimmed.parse::<u64>() {- Ok(secs) => self.memory_sync_interval_secs = Some(secs),- Err(_) => tracing::warn!(- env = %MEMORY_SYNC_INTERVAL_SECS_ENV_VAR,- value = %raw,- "invalid memory-sync interval ignored; expected an unsigned integer (0 = manual)"- ),- }- }- }-- if let Some(language) = env.get("OPENHUMAN_OUTPUT_LANGUAGE") {- let language = language.trim();- if !language.is_empty() {- self.output_language = Some(language.to_string());- }- }-- if let Some(flag) = env.get_any(&["OPENHUMAN_REASONING_ENABLED", "REASONING_ENABLED"]) {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.runtime.reasoning_enabled = Some(true),- "0" | "false" | "no" | "off" => self.runtime.reasoning_enabled = Some(false),- _ => {}- }- }-- if let Some(flag) = env.get_any(&["OPENHUMAN_SHELL_HIDE_WINDOW", "SHELL_HIDE_WINDOW"]) {- match classify_shell_hide_window(&flag) {- // An empty / whitespace-only value means the var is present but- // unset (common when a `.env` or launcher exports `VAR=`). Treat- // it as absent — keep the current value rather than warning on- // every boot. Trace-level so the no-op stays diagnosable without- // the INFO/WARN noise this change exists to remove.- ShellHideWindowParse::Unset => tracing::trace!(- "[config][shell] OPENHUMAN_SHELL_HIDE_WINDOW empty value treated as unset; \- keeping hide_window={}",- self.shell.hide_window- ),- ShellHideWindowParse::Set(value) => {- self.shell.hide_window = value;- tracing::debug!(- value = %flag,- "[config][shell] OPENHUMAN_SHELL_HIDE_WINDOW applied: hide_window={value}"- );- }- ShellHideWindowParse::Unrecognized => tracing::warn!(- value = %flag,- "[config][shell] OPENHUMAN_SHELL_HIDE_WINDOW unrecognized value ignored; \- keeping current hide_window={}",- self.shell.hide_window- ),- }- }-- self.apply_search_env(env);- self.apply_proxy_env(env);- self.apply_runtime_env(env);- self.apply_observability_env(env);- self.apply_learning_env(env);- self.apply_memory_tree_env(env);- self.apply_subsystems_env(env);- self.apply_update_env(env);- self.apply_dictation_env(env);- self.apply_context_env(env);- }-- fn apply_search_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- if let Some(key) = env.get_any(&["OPENHUMAN_SELTZ_API_KEY", "SELTZ_API_KEY"]) {- if !key.is_empty() {- self.seltz.api_key = Some(key);- self.seltz.enabled = true;- }- }- if let Some(url) = env.get_any(&["OPENHUMAN_SELTZ_API_URL", "SELTZ_API_URL"]) {- if !url.is_empty() {- self.seltz.api_url = Some(url);- }- }- if let Some(max) = env.get_any(&["OPENHUMAN_SELTZ_MAX_RESULTS", "SELTZ_MAX_RESULTS"]) {- if let Ok(n) = max.parse::<usize>() {- if (1..=20).contains(&n) {- self.seltz.max_results = n;- }- }- }-- if let Some(flag) = env.get_any(&["OPENHUMAN_SEARXNG_ENABLED", "SEARXNG_ENABLED"]) {- if let Some(enabled) = parse_env_bool("OPENHUMAN_SEARXNG_ENABLED", &flag) {- self.searxng.enabled = enabled;- }- }- if let Some(url) = env.get_any(&["OPENHUMAN_SEARXNG_BASE_URL", "SEARXNG_BASE_URL"]) {- let url = url.trim();- if !url.is_empty() {- self.searxng.base_url = url.to_string();- }- }- if let Some(max) = env.get_any(&["OPENHUMAN_SEARXNG_MAX_RESULTS", "SEARXNG_MAX_RESULTS"]) {- if let Ok(n) = max.parse::<usize>() {- if (1..=50).contains(&n) {- self.searxng.max_results = n;- }- }- }- if let Some(language) = env.get_any(&[- "OPENHUMAN_SEARXNG_DEFAULT_LANGUAGE",- "SEARXNG_DEFAULT_LANGUAGE",- ]) {- let language = language.trim();- if !language.is_empty() {- self.searxng.default_language = language.to_string();- }- }- if let Some(timeout_secs) = env.get_any(&[- "OPENHUMAN_SEARXNG_TIMEOUT_SECS",- "OPENHUMAN_SEARXNG_TIMEOUT_SECONDS",- "SEARXNG_TIMEOUT_SECS",- "SEARXNG_TIMEOUT_SECONDS",- ]) {- if let Ok(timeout_secs) = timeout_secs.parse::<u64>() {- if timeout_secs > 0 {- self.searxng.timeout_secs = timeout_secs;- }- }- }-- if let Some(engine) = env.get_any(&["OPENHUMAN_SEARCH_ENGINE", "SEARCH_ENGINE"]) {- let engine = engine.trim().to_ascii_lowercase();- if !engine.is_empty() {- self.search.engine = engine;- }- }- if let Some(key) = env.get_any(&["OPENHUMAN_PARALLEL_API_KEY", "PARALLEL_API_KEY"]) {- if !key.trim().is_empty() {- self.search.parallel.api_key = Some(key);- }- }- if let Some(key) = env.get_any(&["OPENHUMAN_BRAVE_API_KEY", "BRAVE_API_KEY"]) {- if !key.trim().is_empty() {- self.search.brave.api_key = Some(key);- }- }- if let Some(key) = env.get_any(&["OPENHUMAN_QUERIT_API_KEY", "QUERIT_API_KEY"]) {- if !key.trim().is_empty() {- self.search.querit.api_key = Some(key);- }- }- if let Some(key) = env.get_any(&["OPENHUMAN_EXA_API_KEY", "EXA_API_KEY"]) {- if !key.trim().is_empty() {- self.search.exa.api_key = Some(key);- }- }- if let Some(max) = env.get_any(&["OPENHUMAN_SEARCH_MAX_RESULTS", "SEARCH_MAX_RESULTS"]) {- if let Ok(n) = max.parse::<usize>() {- if (1..=20).contains(&n) {- self.search.max_results = n;- }- }- }- if let Some(t) = env.get_any(&["OPENHUMAN_SEARCH_TIMEOUT_SECS", "SEARCH_TIMEOUT_SECS"]) {- if let Ok(n) = t.parse::<u64>() {- if n > 0 {- self.search.timeout_secs = n;- }- }- }-- if env.contains("OPENHUMAN_WEB_SEARCH_ENABLED") {- log::warn!(- "[config] OPENHUMAN_WEB_SEARCH_ENABLED is deprecated and ignored — \- web search is always registered; provider/API-key overrides were removed."- );- }-- if let Some(max_results) =- env.get_any(&["OPENHUMAN_WEB_SEARCH_MAX_RESULTS", "WEB_SEARCH_MAX_RESULTS"])- {- if let Ok(max_results) = max_results.parse::<usize>() {- if (1..=10).contains(&max_results) {- self.web_search.max_results = max_results;- }- }- }-- if let Some(timeout_secs) = env.get_any(&[- "OPENHUMAN_WEB_SEARCH_TIMEOUT_SECS",- "WEB_SEARCH_TIMEOUT_SECS",- ]) {- if let Ok(timeout_secs) = timeout_secs.parse::<u64>() {- if timeout_secs > 0 {- self.web_search.timeout_secs = timeout_secs;- }- }- }- }-- fn apply_proxy_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- let explicit_proxy_enabled = env- .get("OPENHUMAN_PROXY_ENABLED")- .as_deref()- .and_then(parse_proxy_enabled);- if let Some(enabled) = explicit_proxy_enabled {- self.proxy.enabled = enabled;- }-- let mut proxy_url_overridden = false;- if let Some(proxy_url) = env.get_any(&["OPENHUMAN_HTTP_PROXY", "HTTP_PROXY"]) {- self.proxy.http_proxy = normalize_proxy_url_option(Some(&proxy_url));- proxy_url_overridden = true;- }- if let Some(proxy_url) = env.get_any(&["OPENHUMAN_HTTPS_PROXY", "HTTPS_PROXY"]) {- self.proxy.https_proxy = normalize_proxy_url_option(Some(&proxy_url));- proxy_url_overridden = true;- }- if let Some(proxy_url) = env.get_any(&["OPENHUMAN_ALL_PROXY", "ALL_PROXY"]) {- self.proxy.all_proxy = normalize_proxy_url_option(Some(&proxy_url));- proxy_url_overridden = true;- }- if let Some(no_proxy) = env.get_any(&["OPENHUMAN_NO_PROXY", "NO_PROXY"]) {- self.proxy.no_proxy = normalize_no_proxy_list(vec![no_proxy]);- }-- if explicit_proxy_enabled.is_none()- && proxy_url_overridden- && self.proxy.has_any_proxy_url()- {- self.proxy.enabled = true;- }-- if let Some(scope_raw) = env.get("OPENHUMAN_PROXY_SCOPE") {- let trimmed = scope_raw.trim();- if !trimmed.is_empty() {- match parse_proxy_scope(trimmed) {- Some(scope) => self.proxy.scope = scope,- None => {- tracing::warn!("Invalid OPENHUMAN_PROXY_SCOPE value {:?} ignored", trimmed);- }- }- }- }-- if let Some(services_raw) = env.get("OPENHUMAN_PROXY_SERVICES") {- self.proxy.services = normalize_service_list(vec![services_raw]);- }-- if let Err(error) = self.proxy.validate() {- tracing::warn!("Invalid proxy configuration ignored: {error}");- self.proxy.enabled = false;- }- }-- fn apply_runtime_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- if let Some(tier_str) = env.get("OPENHUMAN_LOCAL_AI_TIER") {- let tier_str = tier_str.trim().to_ascii_lowercase();- if !tier_str.is_empty() {- if let Some(tier) =- crate::openhuman::inference::presets::ModelTier::from_str_opt(&tier_str)- {- if tier == crate::openhuman::inference::presets::ModelTier::Custom {- tracing::warn!(- tier = %tier_str,- "ignoring custom OPENHUMAN_LOCAL_AI_TIER; only built-in presets are supported"- );- } else if !tier.is_mvp_allowed() {- tracing::warn!(- tier = %tier_str,- "ignoring OPENHUMAN_LOCAL_AI_TIER outside the 1B local-model allowlist"- );- } else {- crate::openhuman::inference::presets::apply_preset_to_config(- &mut self.local_ai,- tier,- );- tracing::debug!(- tier = %tier_str,- "applied local AI tier from OPENHUMAN_LOCAL_AI_TIER"- );- }- } else {- tracing::warn!(- tier = %tier_str,- "ignoring invalid OPENHUMAN_LOCAL_AI_TIER (valid: ram_2_4gb)"- );- }- }- }-- if let Some(flag) = env.get("OPENHUMAN_NODE_ENABLED") {- if let Some(enabled) = parse_env_bool("OPENHUMAN_NODE_ENABLED", &flag) {- self.node.enabled = enabled;- }- }- if let Some(version) = env.get("OPENHUMAN_NODE_VERSION") {- let trimmed = version.trim();- if !trimmed.is_empty() {- self.node.version = trimmed.to_string();- }- }- if let Some(dir) = env.get("OPENHUMAN_NODE_CACHE_DIR") {- let trimmed = dir.trim();- if !trimmed.is_empty() {- self.node.cache_dir = trimmed.to_string();- }- }- if let Some(flag) = env.get("OPENHUMAN_NODE_PREFER_SYSTEM") {- if let Some(prefer_system) = parse_env_bool("OPENHUMAN_NODE_PREFER_SYSTEM", &flag) {- self.node.prefer_system = prefer_system;- }- }-- if let Some(flag) = env.get("OPENHUMAN_RUNTIME_PYTHON_ENABLED") {- if let Some(enabled) = parse_env_bool("OPENHUMAN_RUNTIME_PYTHON_ENABLED", &flag) {- self.runtime_python.enabled = enabled;- }- }- if let Some(version) = env.get("OPENHUMAN_RUNTIME_PYTHON_MINIMUM_VERSION") {- let trimmed = version.trim();- if !trimmed.is_empty() {- self.runtime_python.minimum_version = trimmed.to_string();- }- }- if let Some(dir) = env.get("OPENHUMAN_RUNTIME_PYTHON_CACHE_DIR") {- self.runtime_python.cache_dir = dir.trim().to_string();- }- if let Some(tag) = env.get("OPENHUMAN_RUNTIME_PYTHON_MANAGED_RELEASE_TAG") {- self.runtime_python.managed_release_tag = tag.trim().to_string();- }- if let Some(flag) = env.get("OPENHUMAN_RUNTIME_PYTHON_PREFER_SYSTEM") {- if let Some(prefer_system) =- parse_env_bool("OPENHUMAN_RUNTIME_PYTHON_PREFER_SYSTEM", &flag)- {- self.runtime_python.prefer_system = prefer_system;- }- }- if let Some(command) = env.get("OPENHUMAN_RUNTIME_PYTHON_PREFERRED_COMMAND") {- self.runtime_python.preferred_command = command.trim().to_string();- }-- // --- Shared language-runtime pool (#5106) --------------------------- if let Some(flag) = env.get("OPENHUMAN_RUNTIME_POOL_ENABLED") {- if let Some(enabled) = parse_env_bool("OPENHUMAN_RUNTIME_POOL_ENABLED", &flag) {- self.runtime_pool.enabled = enabled;- }- }- if let Some(raw) = env.get("OPENHUMAN_RUNTIME_POOL_NODE_MAX_WORKERS") {- match raw.trim().parse::<usize>() {- Ok(n) => self.runtime_pool.node.max_workers = n,- Err(e) => tracing::warn!(- value = %raw,- error = %e,- "[config] ignoring invalid OPENHUMAN_RUNTIME_POOL_NODE_MAX_WORKERS"- ),- }- }- if let Some(raw) = env.get("OPENHUMAN_RUNTIME_POOL_PYTHON_MAX_WORKERS") {- match raw.trim().parse::<usize>() {- Ok(n) => self.runtime_pool.python.max_workers = n,- Err(e) => tracing::warn!(- value = %raw,- error = %e,- "[config] ignoring invalid OPENHUMAN_RUNTIME_POOL_PYTHON_MAX_WORKERS"- ),- }- }-- // --- TokenJuice content router -------------------------------------- if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_ENABLED") {- if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_ENABLED", &flag) {- self.tokenjuice.router_enabled = v;- }- }- if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_CCR_ENABLED") {- if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_CCR_ENABLED", &flag) {- self.tokenjuice.ccr_enabled = v;- }- }- if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_CCR_DISK_ENABLED") {- if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_CCR_DISK_ENABLED", &flag) {- self.tokenjuice.ccr_disk_enabled = v;- }- }- if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_SEARCH_ENABLED") {- if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_SEARCH_ENABLED", &flag) {- self.tokenjuice.search_enabled = v;- }- }- if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_CODE_ENABLED") {- if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_CODE_ENABLED", &flag) {- self.tokenjuice.code_enabled = v;- }- }- if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_HTML_ENABLED") {- if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_HTML_ENABLED", &flag) {- self.tokenjuice.html_enabled = v;- }- }- if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_MAX_CACHE_ENTRIES") {- if let Ok(v) = s.trim().parse::<usize>() {- self.tokenjuice.max_cache_entries = v;- }- }- if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_MAX_CACHE_BYTES") {- if let Ok(v) = s.trim().parse::<usize>() {- self.tokenjuice.max_cache_bytes = v;- }- }- if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_CCR_TTL_SECS") {- if let Ok(v) = s.trim().parse::<u64>() {- self.tokenjuice.ccr_ttl_secs = Some(v);- }- }- if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_CCR_MIN_TOKENS") {- if let Ok(v) = s.trim().parse::<usize>() {- self.tokenjuice.ccr_min_tokens = v;- }- }- // ML plain-text compressor (Kompress).- if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_ML_COMPRESSION_ENABLED") {- if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_ML_COMPRESSION_ENABLED", &flag) {- self.tokenjuice.ml_compression_enabled = v;- }- }- if let Some(m) = env.get("OPENHUMAN_TOKENJUICE_ML_MODEL_ID") {- let t = m.trim();- if !t.is_empty() {- self.tokenjuice.ml_model_id = t.to_string();- }- }- if let Some(d) = env.get("OPENHUMAN_TOKENJUICE_ML_DEVICE") {- let t = d.trim();- if !t.is_empty() {- self.tokenjuice.ml_device = t.to_string();- }- }- if let Some(r) = env.get("OPENHUMAN_TOKENJUICE_ML_TARGET_RATIO") {- if let Ok(v) = r.trim().parse::<f64>() {- if (0.0..=1.0).contains(&v) {- self.tokenjuice.ml_target_ratio = v;- }- }- }- if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_ML_SIDECAR_IDLE_TIMEOUT_SECS") {- if let Ok(v) = s.trim().parse::<u64>() {- self.tokenjuice.ml_sidecar_idle_timeout_secs = v;- }- }- if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_ML_MAX_INPUT_CHARS") {- if let Ok(v) = s.trim().parse::<usize>() {- self.tokenjuice.ml_max_input_chars = v;- }- }- }-- fn apply_observability_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- let dsn_value = env- .get("OPENHUMAN_CORE_SENTRY_DSN")- .or_else(|| env.get("OPENHUMAN_SENTRY_DSN"))- .or_else(|| option_env!("OPENHUMAN_CORE_SENTRY_DSN").map(|s| s.to_string()))- .or_else(|| option_env!("OPENHUMAN_SENTRY_DSN").map(|s| s.to_string()));- if let Some(dsn) = dsn_value {- let dsn = dsn.trim();- if !dsn.is_empty() {- self.observability.sentry_dsn = Some(dsn.to_string());- }- }-- if let Some(flag) = env.get("OPENHUMAN_ANALYTICS_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.observability.analytics_enabled = true,- "0" | "false" | "no" | "off" => self.observability.analytics_enabled = false,- _ => {}- }- }-- // Opt-in: export prompt/reply content on trace spans (default off — a- // deliberate PII reversal). Token/cost export is unaffected by this flag.- if let Some(flag) = env.get("OPENHUMAN_AGENT_TRACING_CAPTURE_CONTENT") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => {- self.observability.agent_tracing.capture_content = true- }- "0" | "false" | "no" | "off" => {- self.observability.agent_tracing.capture_content = false- }- _ => {}- }- }- }-- fn apply_learning_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- if let Some(flag) = env.get("OPENHUMAN_LEARNING_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.enabled = true,- "0" | "false" | "no" | "off" => self.learning.enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_REFLECTION_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.reflection_enabled = true,- "0" | "false" | "no" | "off" => self.learning.reflection_enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_USER_PROFILE_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.user_profile_enabled = true,- "0" | "false" | "no" | "off" => self.learning.user_profile_enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_TOOL_TRACKING_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.tool_tracking_enabled = true,- "0" | "false" | "no" | "off" => self.learning.tool_tracking_enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_TOOL_MEMORY_CAPTURE_ENABLED") {- if let Some(enabled) = parse_env_bool(- "OPENHUMAN_LEARNING_TOOL_MEMORY_CAPTURE_ENABLED",- flag.as_str(),- ) {- self.learning.tool_memory_capture_enabled = enabled;- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_EXPLICIT_PREFERENCES_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.explicit_preferences_enabled = true,- "0" | "false" | "no" | "off" => self.learning.explicit_preferences_enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_GOALS_ENRICHMENT_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.learning.goals_enrichment_enabled = true,- "0" | "false" | "no" | "off" => self.learning.goals_enrichment_enabled = false,- _ => {}- }- }- if let Some(source) = env.get("OPENHUMAN_LEARNING_REFLECTION_SOURCE") {- let normalized = source.trim().to_ascii_lowercase();- match normalized.as_str() {- "local" => {- self.learning.reflection_source =- crate::openhuman::config::ReflectionSource::Local- }- "cloud" => {- self.learning.reflection_source =- crate::openhuman::config::ReflectionSource::Cloud- }- _ => {- tracing::warn!(- source = %source,- "ignoring invalid OPENHUMAN_LEARNING_REFLECTION_SOURCE (valid: local, cloud)"- );- }- }- }- if let Some(val) = env.get("OPENHUMAN_LEARNING_MAX_REFLECTIONS_PER_SESSION") {- if let Ok(max) = val.trim().parse::<usize>() {- self.learning.max_reflections_per_session = max;- }- }- if let Some(val) = env.get("OPENHUMAN_LEARNING_MIN_TURN_COMPLEXITY") {- if let Ok(min) = val.trim().parse::<usize>() {- self.learning.min_turn_complexity = min;- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_EPISODIC_CAPTURE_ENABLED") {- if let Some(enabled) =- parse_env_bool("OPENHUMAN_LEARNING_EPISODIC_CAPTURE_ENABLED", flag.as_str())- {- self.learning.episodic_capture_enabled = enabled;- }- }- if let Some(flag) = env.get("OPENHUMAN_LEARNING_STM_RECALL_ENABLED") {- if let Some(enabled) =- parse_env_bool("OPENHUMAN_LEARNING_STM_RECALL_ENABLED", flag.as_str())- {- self.learning.stm_recall_enabled = enabled;- }- }- }-- fn apply_memory_tree_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- if let Ok(endpoint) = std::env::var("OPENHUMAN_MEMORY_EMBED_ENDPOINT") {- let trimmed = endpoint.trim();- self.memory_tree.embedding_endpoint = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(model) = std::env::var("OPENHUMAN_MEMORY_EMBED_MODEL") {- let trimmed = model.trim();- self.memory_tree.embedding_model = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(val) = std::env::var("OPENHUMAN_MEMORY_EMBED_TIMEOUT_MS") {- if let Ok(timeout_ms) = val.trim().parse::<u64>() {- if timeout_ms > 0 {- self.memory_tree.embedding_timeout_ms = Some(timeout_ms);- }- }- }- if let Ok(flag) = std::env::var("OPENHUMAN_MEMORY_EMBED_STRICT") {- if let Some(strict) = parse_env_bool("OPENHUMAN_MEMORY_EMBED_STRICT", &flag) {- self.memory_tree.embedding_strict = strict;- }- }- if let Some(val) = env.get("OPENHUMAN_MEMORY_EMBED_RATE_LIMIT") {- if let Ok(per_min) = val.trim().parse::<u32>() {- self.memory.embedding_rate_limit_per_min = per_min;- }- }-- if let Ok(endpoint) = std::env::var("OPENHUMAN_MEMORY_EXTRACT_ENDPOINT") {- let trimmed = endpoint.trim();- self.memory_tree.llm_extractor_endpoint = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(model) = std::env::var("OPENHUMAN_MEMORY_EXTRACT_MODEL") {- let trimmed = model.trim();- self.memory_tree.llm_extractor_model = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(val) = std::env::var("OPENHUMAN_MEMORY_EXTRACT_TIMEOUT_MS") {- if let Ok(ms) = val.trim().parse::<u64>() {- if ms > 0 {- self.memory_tree.llm_extractor_timeout_ms = Some(ms);- }- }- }-- if let Ok(endpoint) = std::env::var("OPENHUMAN_MEMORY_SUMMARISE_ENDPOINT") {- let trimmed = endpoint.trim();- self.memory_tree.llm_summariser_endpoint = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(model) = std::env::var("OPENHUMAN_MEMORY_SUMMARISE_MODEL") {- let trimmed = model.trim();- self.memory_tree.llm_summariser_model = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }- if let Ok(val) = std::env::var("OPENHUMAN_MEMORY_SUMMARISE_TIMEOUT_MS") {- if let Ok(ms) = val.trim().parse::<u64>() {- if ms > 0 {- self.memory_tree.llm_summariser_timeout_ms = Some(ms);- }- }- }-- if let Some(dir) = env.get("OPENHUMAN_MEMORY_TREE_CONTENT_DIR") {- let trimmed = dir.trim();- self.memory_tree.content_dir = if trimmed.is_empty() {- None- } else {- Some(std::path::PathBuf::from(trimmed))- };- }-- if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_LLM_BACKEND") {- let trimmed = raw.trim();- if !trimmed.is_empty() {- match crate::openhuman::config::LlmBackend::parse(trimmed) {- Ok(b) => {- log::debug!(- "[memory_tree] OPENHUMAN_MEMORY_TREE_LLM_BACKEND override applied: {}",- b.as_str()- );- self.memory_tree.llm_backend = b;- }- Err(e) => {- tracing::warn!(- value = trimmed,- error = %e,- "ignoring invalid OPENHUMAN_MEMORY_TREE_LLM_BACKEND (valid: cloud, local)"- );- }- }- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_CLOUD_LLM_MODEL") {- let trimmed = raw.trim();- self.memory_tree.cloud_llm_model = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }-- if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_SMART_WALK_MODEL") {- let trimmed = raw.trim();- self.memory_tree.smart_walk_model = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- }-- if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_CLOUD_SUMMARIZATION") {- if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_TREE_CLOUD_SUMMARIZATION", &raw) {- self.memory_tree.cloud_summarization_opt_in = val;- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_SPACY_ENABLED") {- if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_TREE_SPACY_ENABLED", &raw) {- self.memory_tree.spacy_enabled = val;- }- }- }-- /// `[subsystems.memory]` overrides — kernel.md §3.6 / plan-memory.md §4.5. Mirrors- /// the `apply_memory_tree_env` reading pattern above. GREENFIELD: nothing- /// reads `self.subsystems` yet, so these overrides have no runtime effect- /// beyond making the field settable via env for forward compatibility.- fn apply_subsystems_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- if let Some(raw) = env.get("OPENHUMAN_MEMORY_DRIVER") {- let trimmed = raw.trim();- if !trimmed.is_empty() {- self.subsystems.memory.driver = trimmed.to_string();- }- }-- if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_AUTO_RECALL") {- if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_HOOKS_AUTO_RECALL", &raw) {- self.subsystems.memory.hooks.auto_recall = val;- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_AUTO_CAPTURE") {- if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_HOOKS_AUTO_CAPTURE", &raw) {- self.subsystems.memory.hooks.auto_capture = val;- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_MAX_CONTEXT_TOKENS") {- let trimmed = raw.trim();- if !trimmed.is_empty() {- match trimmed.parse::<usize>() {- Ok(v) => self.subsystems.memory.hooks.max_context_tokens = v,- Err(_) => tracing::warn!(- value = %raw,- "invalid OPENHUMAN_MEMORY_HOOKS_MAX_CONTEXT_TOKENS ignored; expected an unsigned integer"- ),- }- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_RECALL_MAX_CHARS") {- let trimmed = raw.trim();- if !trimmed.is_empty() {- match trimmed.parse::<usize>() {- Ok(v) => self.subsystems.memory.hooks.recall_max_chars = v,- Err(_) => tracing::warn!(- value = %raw,- "invalid OPENHUMAN_MEMORY_HOOKS_RECALL_MAX_CHARS ignored; expected an unsigned integer"- ),- }- }- }- if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_CAPTURE_MAX_CHARS") {- let trimmed = raw.trim();- if !trimmed.is_empty() {- match trimmed.parse::<usize>() {- Ok(v) => self.subsystems.memory.hooks.capture_max_chars = v,- Err(_) => tracing::warn!(- value = %raw,- "invalid OPENHUMAN_MEMORY_HOOKS_CAPTURE_MAX_CHARS ignored; expected an unsigned integer"- ),- }- }- }- }-- fn apply_update_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- if let Some(flag) = env.get("OPENHUMAN_AUTO_UPDATE_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.update.enabled = true,- "0" | "false" | "no" | "off" => self.update.enabled = false,- _ => {}- }- }- if let Some(val) = env.get("OPENHUMAN_AUTO_UPDATE_INTERVAL_MINUTES") {- if let Ok(minutes) = val.trim().parse::<u32>() {- self.update.interval_minutes = minutes;- }- }- if let Some(raw) = env.get("OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY") {- match raw.trim().to_ascii_lowercase().as_str() {- "self_replace" | "self-replace" | "self" => {- self.update.restart_strategy = UpdateRestartStrategy::SelfReplace;- }- "supervisor" | "stage_only" | "stage-only" => {- self.update.restart_strategy = UpdateRestartStrategy::Supervisor;- }- other => {- tracing::warn!(- value = other,- "ignoring invalid OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY \- (valid: self_replace, supervisor)"- );- }- }- }- if let Some(flag) = env.get("OPENHUMAN_AUTO_UPDATE_RPC_MUTATIONS_ENABLED") {- if let Some(enabled) =- parse_env_bool("OPENHUMAN_AUTO_UPDATE_RPC_MUTATIONS_ENABLED", &flag)- {- self.update.rpc_mutations_enabled = enabled;- }- }- }-- fn apply_dictation_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- if let Some(flag) = env.get("OPENHUMAN_DICTATION_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.dictation.enabled = true,- "0" | "false" | "no" | "off" => self.dictation.enabled = false,- _ => {}- }- }- if let Some(hotkey) = env.get("OPENHUMAN_DICTATION_HOTKEY") {- let hotkey = hotkey.trim();- if !hotkey.is_empty() {- self.dictation.hotkey = hotkey.to_string();- }- }- if let Some(mode) = env.get("OPENHUMAN_DICTATION_ACTIVATION_MODE") {- let normalized = mode.trim().to_ascii_lowercase();- match normalized.as_str() {- "toggle" => {- self.dictation.activation_mode =- crate::openhuman::config::DictationActivationMode::Toggle- }- "push" => {- self.dictation.activation_mode =- crate::openhuman::config::DictationActivationMode::Push- }- _ => {- tracing::warn!(- mode = %mode,- "ignoring invalid OPENHUMAN_DICTATION_ACTIVATION_MODE (valid: toggle, push)"- );- }- }- }- if let Some(flag) = env.get("OPENHUMAN_DICTATION_LLM_REFINEMENT") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.dictation.llm_refinement = true,- "0" | "false" | "no" | "off" => self.dictation.llm_refinement = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_DICTATION_STREAMING") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.dictation.streaming = true,- "0" | "false" | "no" | "off" => self.dictation.streaming = false,- _ => {}- }- }- if let Some(val) = env.get("OPENHUMAN_DICTATION_STREAMING_INTERVAL_MS") {- if let Ok(ms) = val.trim().parse::<u64>() {- self.dictation.streaming_interval_ms = ms;- }- }- }-- fn apply_context_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- if let Some(flag) = env.get("OPENHUMAN_CONTEXT_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.context.enabled = true,- "0" | "false" | "no" | "off" => self.context.enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_CONTEXT_MICROCOMPACT_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.context.microcompact_enabled = true,- "0" | "false" | "no" | "off" => self.context.microcompact_enabled = false,- _ => {}- }- }- if let Some(flag) = env.get("OPENHUMAN_CONTEXT_AUTOCOMPACT_ENABLED") {- let normalized = flag.trim().to_ascii_lowercase();- match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.context.autocompact_enabled = true,- "0" | "false" | "no" | "off" => self.context.autocompact_enabled = false,- _ => {}- }- }- if let Some(val) = env.get("OPENHUMAN_CONTEXT_TOOL_RESULT_BUDGET_BYTES") {- if let Ok(n) = val.trim().parse::<usize>() {- self.context.tool_result_budget_bytes = n;- }- }- // Kill-switch for native tool-output compaction (Stage 1a). On by- // default; `OPENHUMAN_COMPACTION=0` disables it for a support/A-B- // bisect. Accepts the canonical short name and the namespaced form.- if let Some(flag) = env- .get("OPENHUMAN_COMPACTION")- .or_else(|| env.get("OPENHUMAN_CONTEXT_COMPACTION_ENABLED"))- {- match flag.trim().to_ascii_lowercase().as_str() {- "1" | "true" | "yes" | "on" => self.context.compaction_enabled = true,- "0" | "false" | "no" | "off" => self.context.compaction_enabled = false,- _ => {}- }- }- if let Some(model) = env.get("OPENHUMAN_CONTEXT_SUMMARIZER_MODEL") {- let model = model.trim();- if !model.is_empty() {- self.context.summarizer_model = Some(model.to_string());- }- }- let context_default = crate::openhuman::agent::context::DEFAULT_TOOL_RESULT_BUDGET_BYTES;- let context_env_set = env.contains("OPENHUMAN_CONTEXT_TOOL_RESULT_BUDGET_BYTES");- if !context_env_set- && self.context.tool_result_budget_bytes == context_default- && self.agent.tool_result_budget_bytes != context_default- {- tracing::warn!(- old = self.agent.tool_result_budget_bytes,- "[context:config] `agent.tool_result_budget_bytes` is \- deprecated — please move it to \- `context.tool_result_budget_bytes` in your config.toml"- );- self.context.tool_result_budget_bytes = self.agent.tool_result_budget_bytes;- }- }-}+include!("env_overlay_impl_01_part_01.rs");+include!("env_overlay_impl_01_part_02.rs");diff --git a/src/openhuman/config/schema/load/env_overlay_impl_01_part_01.rs b/src/openhuman/config/schema/load/env_overlay_impl_01_part_01.rsnew file mode 100644index 0000000000..5b9c17f72d--- /dev/null+++ b/src/openhuman/config/schema/load/env_overlay_impl_01_part_01.rs@@ -0,0 +1,584 @@++impl Config {++ pub fn apply_env_overrides(&mut self) {+ use super::env::ProcessEnv;+ self.apply_env_overrides_from(&ProcessEnv);+ }++ pub(super) fn apply_env_overrides_from(+ &mut self,+ env: &(dyn super::env::EnvLookup + Send + Sync),+ ) {+ self.apply_env_overlay_with(env);++ if self.proxy.enabled && self.proxy.scope == ProxyScope::Environment {+ self.proxy.apply_to_process_env();+ }++ set_runtime_proxy_config(self.proxy.clone());++ crate::openhuman::inference::embeddings::rate_limit::set_embedding_rate_limit(+ self.memory.embedding_rate_limit_per_min,+ );++ // Launch flags are process-local and intentionally win over both the+ // persisted file and ordinary environment overlays. They are applied+ // after loading so `openhuman -p <provider> -m <model>` never mutates+ // config.toml and desktop launches remain unaffected.+ super::super::cli_overrides::apply_cli_inference_overrides(self);+ }++ /// Pure-ish env overlay: applies overrides read from `env` to `self`.+ ///+ /// "Pure-ish" because it still emits `tracing` logs and calls+ /// `self.proxy.validate()` (which only reads). Crucially, it does+ /// **not** write to the process environment nor the+ /// `set_runtime_proxy_config` global — those stay in the public+ /// [`Self::apply_env_overrides`] wrapper so unit tests can call this+ /// with a [`HashMapEnv`] (see tests) without requiring the+ /// `TEST_ENV_LOCK` or tainting sibling tests.+ pub(crate) fn apply_env_overlay_with<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {+ // Only the namespaced `OPENHUMAN_MODEL` is honoured. The bare `MODEL`+ // env var used to be accepted as an alias but collides with vendor+ // asset-tag env vars (e.g. Dell OptiPlex sets `MODEL=7080`), which+ // silently clobbered the LLM model and 400'd every backend call+ // (Sentry OPENHUMAN-TAURI-J8).+ if let Some(model) = env.get("OPENHUMAN_MODEL") {+ let trimmed = model.trim();+ if !trimmed.is_empty() {+ self.default_model = Some(trimmed.to_string());+ }+ }++ if let Some(workspace) = env.get("OPENHUMAN_WORKSPACE") {+ if !workspace.is_empty() {+ let (_, workspace_dir) =+ super::dirs::resolve_config_dir_for_workspace(&PathBuf::from(workspace));+ self.workspace_dir = workspace_dir;+ }+ }++ if let Some(v) = env.get("OPENHUMAN_ACTION_DIR") {+ let trimmed = v.trim();+ if !trimmed.is_empty() {+ self.action_dir = PathBuf::from(trimmed);+ }+ }++ if let Some(temp_str) = env.get("OPENHUMAN_TEMPERATURE") {+ if let Ok(temp) = temp_str.parse::<f64>() {+ if (0.0..=2.0).contains(&temp) {+ self.default_temperature = temp;+ }+ }+ }++ if let Some(raw) = env.get("OPENHUMAN_MAX_ACTIONS_PER_HOUR") {+ let trimmed = raw.trim();+ if !trimmed.is_empty() {+ match trimmed.parse::<u32>() {+ Ok(limit) => self.autonomy.max_actions_per_hour = limit,+ Err(_) => tracing::warn!(+ value = %raw,+ "invalid OPENHUMAN_MAX_ACTIONS_PER_HOUR ignored; expected an unsigned integer"+ ),+ }+ }+ }++ if let Some(raw) = env.get(MEMORY_SYNC_INTERVAL_SECS_ENV_VAR) {+ let trimmed = raw.trim();+ if !trimmed.is_empty() {+ match trimmed.parse::<u64>() {+ Ok(secs) => self.memory_sync_interval_secs = Some(secs),+ Err(_) => tracing::warn!(+ env = %MEMORY_SYNC_INTERVAL_SECS_ENV_VAR,+ value = %raw,+ "invalid memory-sync interval ignored; expected an unsigned integer (0 = manual)"+ ),+ }+ }+ }++ if let Some(language) = env.get("OPENHUMAN_OUTPUT_LANGUAGE") {+ let language = language.trim();+ if !language.is_empty() {+ self.output_language = Some(language.to_string());+ }+ }++ if let Some(flag) = env.get_any(&["OPENHUMAN_REASONING_ENABLED", "REASONING_ENABLED"]) {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.runtime.reasoning_enabled = Some(true),+ "0" | "false" | "no" | "off" => self.runtime.reasoning_enabled = Some(false),+ _ => {}+ }+ }++ if let Some(flag) = env.get_any(&["OPENHUMAN_SHELL_HIDE_WINDOW", "SHELL_HIDE_WINDOW"]) {+ match classify_shell_hide_window(&flag) {+ // An empty / whitespace-only value means the var is present but+ // unset (common when a `.env` or launcher exports `VAR=`). Treat+ // it as absent — keep the current value rather than warning on+ // every boot. Trace-level so the no-op stays diagnosable without+ // the INFO/WARN noise this change exists to remove.+ ShellHideWindowParse::Unset => tracing::trace!(+ "[config][shell] OPENHUMAN_SHELL_HIDE_WINDOW empty value treated as unset; \+ keeping hide_window={}",+ self.shell.hide_window+ ),+ ShellHideWindowParse::Set(value) => {+ self.shell.hide_window = value;+ tracing::debug!(+ value = %flag,+ "[config][shell] OPENHUMAN_SHELL_HIDE_WINDOW applied: hide_window={value}"+ );+ }+ ShellHideWindowParse::Unrecognized => tracing::warn!(+ value = %flag,+ "[config][shell] OPENHUMAN_SHELL_HIDE_WINDOW unrecognized value ignored; \+ keeping current hide_window={}",+ self.shell.hide_window+ ),+ }+ }++ self.apply_search_env(env);+ self.apply_proxy_env(env);+ self.apply_runtime_env(env);+ self.apply_observability_env(env);+ self.apply_learning_env(env);+ self.apply_memory_tree_env(env);+ self.apply_subsystems_env(env);+ self.apply_update_env(env);+ self.apply_dictation_env(env);+ self.apply_context_env(env);+ }++ fn apply_search_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {+ if let Some(key) = env.get_any(&["OPENHUMAN_SELTZ_API_KEY", "SELTZ_API_KEY"]) {+ if !key.is_empty() {+ self.seltz.api_key = Some(key);+ self.seltz.enabled = true;+ }+ }+ if let Some(url) = env.get_any(&["OPENHUMAN_SELTZ_API_URL", "SELTZ_API_URL"]) {+ if !url.is_empty() {+ self.seltz.api_url = Some(url);+ }+ }+ if let Some(max) = env.get_any(&["OPENHUMAN_SELTZ_MAX_RESULTS", "SELTZ_MAX_RESULTS"]) {+ if let Ok(n) = max.parse::<usize>() {+ if (1..=20).contains(&n) {+ self.seltz.max_results = n;+ }+ }+ }++ if let Some(flag) = env.get_any(&["OPENHUMAN_SEARXNG_ENABLED", "SEARXNG_ENABLED"]) {+ if let Some(enabled) = parse_env_bool("OPENHUMAN_SEARXNG_ENABLED", &flag) {+ self.searxng.enabled = enabled;+ }+ }+ if let Some(url) = env.get_any(&["OPENHUMAN_SEARXNG_BASE_URL", "SEARXNG_BASE_URL"]) {+ let url = url.trim();+ if !url.is_empty() {+ self.searxng.base_url = url.to_string();+ }+ }+ if let Some(max) = env.get_any(&["OPENHUMAN_SEARXNG_MAX_RESULTS", "SEARXNG_MAX_RESULTS"]) {+ if let Ok(n) = max.parse::<usize>() {+ if (1..=50).contains(&n) {+ self.searxng.max_results = n;+ }+ }+ }+ if let Some(language) = env.get_any(&[+ "OPENHUMAN_SEARXNG_DEFAULT_LANGUAGE",+ "SEARXNG_DEFAULT_LANGUAGE",+ ]) {+ let language = language.trim();+ if !language.is_empty() {+ self.searxng.default_language = language.to_string();+ }+ }+ if let Some(timeout_secs) = env.get_any(&[+ "OPENHUMAN_SEARXNG_TIMEOUT_SECS",+ "OPENHUMAN_SEARXNG_TIMEOUT_SECONDS",+ "SEARXNG_TIMEOUT_SECS",+ "SEARXNG_TIMEOUT_SECONDS",+ ]) {+ if let Ok(timeout_secs) = timeout_secs.parse::<u64>() {+ if timeout_secs > 0 {+ self.searxng.timeout_secs = timeout_secs;+ }+ }+ }++ if let Some(engine) = env.get_any(&["OPENHUMAN_SEARCH_ENGINE", "SEARCH_ENGINE"]) {+ let engine = engine.trim().to_ascii_lowercase();+ if !engine.is_empty() {+ self.search.engine = engine;+ }+ }+ if let Some(key) = env.get_any(&["OPENHUMAN_PARALLEL_API_KEY", "PARALLEL_API_KEY"]) {+ if !key.trim().is_empty() {+ self.search.parallel.api_key = Some(key);+ }+ }+ if let Some(key) = env.get_any(&["OPENHUMAN_BRAVE_API_KEY", "BRAVE_API_KEY"]) {+ if !key.trim().is_empty() {+ self.search.brave.api_key = Some(key);+ }+ }+ if let Some(key) = env.get_any(&["OPENHUMAN_QUERIT_API_KEY", "QUERIT_API_KEY"]) {+ if !key.trim().is_empty() {+ self.search.querit.api_key = Some(key);+ }+ }+ if let Some(key) = env.get_any(&["OPENHUMAN_EXA_API_KEY", "EXA_API_KEY"]) {+ if !key.trim().is_empty() {+ self.search.exa.api_key = Some(key);+ }+ }+ if let Some(max) = env.get_any(&["OPENHUMAN_SEARCH_MAX_RESULTS", "SEARCH_MAX_RESULTS"]) {+ if let Ok(n) = max.parse::<usize>() {+ if (1..=20).contains(&n) {+ self.search.max_results = n;+ }+ }+ }+ if let Some(t) = env.get_any(&["OPENHUMAN_SEARCH_TIMEOUT_SECS", "SEARCH_TIMEOUT_SECS"]) {+ if let Ok(n) = t.parse::<u64>() {+ if n > 0 {+ self.search.timeout_secs = n;+ }+ }+ }++ if env.contains("OPENHUMAN_WEB_SEARCH_ENABLED") {+ log::warn!(+ "[config] OPENHUMAN_WEB_SEARCH_ENABLED is deprecated and ignored — \+ web search is always registered; provider/API-key overrides were removed."+ );+ }++ if let Some(max_results) =+ env.get_any(&["OPENHUMAN_WEB_SEARCH_MAX_RESULTS", "WEB_SEARCH_MAX_RESULTS"])+ {+ if let Ok(max_results) = max_results.parse::<usize>() {+ if (1..=10).contains(&max_results) {+ self.web_search.max_results = max_results;+ }+ }+ }++ if let Some(timeout_secs) = env.get_any(&[+ "OPENHUMAN_WEB_SEARCH_TIMEOUT_SECS",+ "WEB_SEARCH_TIMEOUT_SECS",+ ]) {+ if let Ok(timeout_secs) = timeout_secs.parse::<u64>() {+ if timeout_secs > 0 {+ self.web_search.timeout_secs = timeout_secs;+ }+ }+ }+ }++ fn apply_proxy_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {+ let explicit_proxy_enabled = env+ .get("OPENHUMAN_PROXY_ENABLED")+ .as_deref()+ .and_then(parse_proxy_enabled);+ if let Some(enabled) = explicit_proxy_enabled {+ self.proxy.enabled = enabled;+ }++ let mut proxy_url_overridden = false;+ if let Some(proxy_url) = env.get_any(&["OPENHUMAN_HTTP_PROXY", "HTTP_PROXY"]) {+ self.proxy.http_proxy = normalize_proxy_url_option(Some(&proxy_url));+ proxy_url_overridden = true;+ }+ if let Some(proxy_url) = env.get_any(&["OPENHUMAN_HTTPS_PROXY", "HTTPS_PROXY"]) {+ self.proxy.https_proxy = normalize_proxy_url_option(Some(&proxy_url));+ proxy_url_overridden = true;+ }+ if let Some(proxy_url) = env.get_any(&["OPENHUMAN_ALL_PROXY", "ALL_PROXY"]) {+ self.proxy.all_proxy = normalize_proxy_url_option(Some(&proxy_url));+ proxy_url_overridden = true;+ }+ if let Some(no_proxy) = env.get_any(&["OPENHUMAN_NO_PROXY", "NO_PROXY"]) {+ self.proxy.no_proxy = normalize_no_proxy_list(vec![no_proxy]);+ }++ if explicit_proxy_enabled.is_none()+ && proxy_url_overridden+ && self.proxy.has_any_proxy_url()+ {+ self.proxy.enabled = true;+ }++ if let Some(scope_raw) = env.get("OPENHUMAN_PROXY_SCOPE") {+ let trimmed = scope_raw.trim();+ if !trimmed.is_empty() {+ match parse_proxy_scope(trimmed) {+ Some(scope) => self.proxy.scope = scope,+ None => {+ tracing::warn!("Invalid OPENHUMAN_PROXY_SCOPE value {:?} ignored", trimmed);+ }+ }+ }+ }++ if let Some(services_raw) = env.get("OPENHUMAN_PROXY_SERVICES") {+ self.proxy.services = normalize_service_list(vec![services_raw]);+ }++ if let Err(error) = self.proxy.validate() {+ tracing::warn!("Invalid proxy configuration ignored: {error}");+ self.proxy.enabled = false;+ }+ }++ fn apply_runtime_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {+ if let Some(tier_str) = env.get("OPENHUMAN_LOCAL_AI_TIER") {+ let tier_str = tier_str.trim().to_ascii_lowercase();+ if !tier_str.is_empty() {+ if let Some(tier) =+ crate::openhuman::inference::presets::ModelTier::from_str_opt(&tier_str)+ {+ if tier == crate::openhuman::inference::presets::ModelTier::Custom {+ tracing::warn!(+ tier = %tier_str,+ "ignoring custom OPENHUMAN_LOCAL_AI_TIER; only built-in presets are supported"+ );+ } else if !tier.is_mvp_allowed() {+ tracing::warn!(+ tier = %tier_str,+ "ignoring OPENHUMAN_LOCAL_AI_TIER outside the 1B local-model allowlist"+ );+ } else {+ crate::openhuman::inference::presets::apply_preset_to_config(+ &mut self.local_ai,+ tier,+ );+ tracing::debug!(+ tier = %tier_str,+ "applied local AI tier from OPENHUMAN_LOCAL_AI_TIER"+ );+ }+ } else {+ tracing::warn!(+ tier = %tier_str,+ "ignoring invalid OPENHUMAN_LOCAL_AI_TIER (valid: ram_2_4gb)"+ );+ }+ }+ }++ if let Some(flag) = env.get("OPENHUMAN_NODE_ENABLED") {+ if let Some(enabled) = parse_env_bool("OPENHUMAN_NODE_ENABLED", &flag) {+ self.node.enabled = enabled;+ }+ }+ if let Some(version) = env.get("OPENHUMAN_NODE_VERSION") {+ let trimmed = version.trim();+ if !trimmed.is_empty() {+ self.node.version = trimmed.to_string();+ }+ }+ if let Some(dir) = env.get("OPENHUMAN_NODE_CACHE_DIR") {+ let trimmed = dir.trim();+ if !trimmed.is_empty() {+ self.node.cache_dir = trimmed.to_string();+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_NODE_PREFER_SYSTEM") {+ if let Some(prefer_system) = parse_env_bool("OPENHUMAN_NODE_PREFER_SYSTEM", &flag) {+ self.node.prefer_system = prefer_system;+ }+ }++ if let Some(flag) = env.get("OPENHUMAN_RUNTIME_PYTHON_ENABLED") {+ if let Some(enabled) = parse_env_bool("OPENHUMAN_RUNTIME_PYTHON_ENABLED", &flag) {+ self.runtime_python.enabled = enabled;+ }+ }+ if let Some(version) = env.get("OPENHUMAN_RUNTIME_PYTHON_MINIMUM_VERSION") {+ let trimmed = version.trim();+ if !trimmed.is_empty() {+ self.runtime_python.minimum_version = trimmed.to_string();+ }+ }+ if let Some(dir) = env.get("OPENHUMAN_RUNTIME_PYTHON_CACHE_DIR") {+ self.runtime_python.cache_dir = dir.trim().to_string();+ }+ if let Some(tag) = env.get("OPENHUMAN_RUNTIME_PYTHON_MANAGED_RELEASE_TAG") {+ self.runtime_python.managed_release_tag = tag.trim().to_string();+ }+ if let Some(flag) = env.get("OPENHUMAN_RUNTIME_PYTHON_PREFER_SYSTEM") {+ if let Some(prefer_system) =+ parse_env_bool("OPENHUMAN_RUNTIME_PYTHON_PREFER_SYSTEM", &flag)+ {+ self.runtime_python.prefer_system = prefer_system;+ }+ }+ if let Some(command) = env.get("OPENHUMAN_RUNTIME_PYTHON_PREFERRED_COMMAND") {+ self.runtime_python.preferred_command = command.trim().to_string();+ }++ // --- Shared language-runtime pool (#5106) --------------------------+ if let Some(flag) = env.get("OPENHUMAN_RUNTIME_POOL_ENABLED") {+ if let Some(enabled) = parse_env_bool("OPENHUMAN_RUNTIME_POOL_ENABLED", &flag) {+ self.runtime_pool.enabled = enabled;+ }+ }+ if let Some(raw) = env.get("OPENHUMAN_RUNTIME_POOL_NODE_MAX_WORKERS") {+ match raw.trim().parse::<usize>() {+ Ok(n) => self.runtime_pool.node.max_workers = n,+ Err(e) => tracing::warn!(+ value = %raw,+ error = %e,+ "[config] ignoring invalid OPENHUMAN_RUNTIME_POOL_NODE_MAX_WORKERS"+ ),+ }+ }+ if let Some(raw) = env.get("OPENHUMAN_RUNTIME_POOL_PYTHON_MAX_WORKERS") {+ match raw.trim().parse::<usize>() {+ Ok(n) => self.runtime_pool.python.max_workers = n,+ Err(e) => tracing::warn!(+ value = %raw,+ error = %e,+ "[config] ignoring invalid OPENHUMAN_RUNTIME_POOL_PYTHON_MAX_WORKERS"+ ),+ }+ }++ // --- TokenJuice content router -------------------------------------+ if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_ENABLED") {+ if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_ENABLED", &flag) {+ self.tokenjuice.router_enabled = v;+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_CCR_ENABLED") {+ if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_CCR_ENABLED", &flag) {+ self.tokenjuice.ccr_enabled = v;+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_CCR_DISK_ENABLED") {+ if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_CCR_DISK_ENABLED", &flag) {+ self.tokenjuice.ccr_disk_enabled = v;+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_SEARCH_ENABLED") {+ if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_SEARCH_ENABLED", &flag) {+ self.tokenjuice.search_enabled = v;+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_CODE_ENABLED") {+ if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_CODE_ENABLED", &flag) {+ self.tokenjuice.code_enabled = v;+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_HTML_ENABLED") {+ if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_HTML_ENABLED", &flag) {+ self.tokenjuice.html_enabled = v;+ }+ }+ if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_MAX_CACHE_ENTRIES") {+ if let Ok(v) = s.trim().parse::<usize>() {+ self.tokenjuice.max_cache_entries = v;+ }+ }+ if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_MAX_CACHE_BYTES") {+ if let Ok(v) = s.trim().parse::<usize>() {+ self.tokenjuice.max_cache_bytes = v;+ }+ }+ if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_CCR_TTL_SECS") {+ if let Ok(v) = s.trim().parse::<u64>() {+ self.tokenjuice.ccr_ttl_secs = Some(v);+ }+ }+ if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_CCR_MIN_TOKENS") {+ if let Ok(v) = s.trim().parse::<usize>() {+ self.tokenjuice.ccr_min_tokens = v;+ }+ }+ // ML plain-text compressor (Kompress).+ if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_ML_COMPRESSION_ENABLED") {+ if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_ML_COMPRESSION_ENABLED", &flag) {+ self.tokenjuice.ml_compression_enabled = v;+ }+ }+ if let Some(m) = env.get("OPENHUMAN_TOKENJUICE_ML_MODEL_ID") {+ let t = m.trim();+ if !t.is_empty() {+ self.tokenjuice.ml_model_id = t.to_string();+ }+ }+ if let Some(d) = env.get("OPENHUMAN_TOKENJUICE_ML_DEVICE") {+ let t = d.trim();+ if !t.is_empty() {+ self.tokenjuice.ml_device = t.to_string();+ }+ }+ if let Some(r) = env.get("OPENHUMAN_TOKENJUICE_ML_TARGET_RATIO") {+ if let Ok(v) = r.trim().parse::<f64>() {+ if (0.0..=1.0).contains(&v) {+ self.tokenjuice.ml_target_ratio = v;+ }+ }+ }+ if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_ML_SIDECAR_IDLE_TIMEOUT_SECS") {+ if let Ok(v) = s.trim().parse::<u64>() {+ self.tokenjuice.ml_sidecar_idle_timeout_secs = v;+ }+ }+ if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_ML_MAX_INPUT_CHARS") {+ if let Ok(v) = s.trim().parse::<usize>() {+ self.tokenjuice.ml_max_input_chars = v;+ }+ }+ }++ fn apply_observability_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {+ let dsn_value = env+ .get("OPENHUMAN_CORE_SENTRY_DSN")+ .or_else(|| env.get("OPENHUMAN_SENTRY_DSN"))+ .or_else(|| option_env!("OPENHUMAN_CORE_SENTRY_DSN").map(|s| s.to_string()))+ .or_else(|| option_env!("OPENHUMAN_SENTRY_DSN").map(|s| s.to_string()));+ if let Some(dsn) = dsn_value {+ let dsn = dsn.trim();+ if !dsn.is_empty() {+ self.observability.sentry_dsn = Some(dsn.to_string());+ }+ }++ if let Some(flag) = env.get("OPENHUMAN_ANALYTICS_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.observability.analytics_enabled = true,+ "0" | "false" | "no" | "off" => self.observability.analytics_enabled = false,+ _ => {}+ }+ }++ // Opt-in: export prompt/reply content on trace spans (default off — a+ // deliberate PII reversal). Token/cost export is unaffected by this flag.+ if let Some(flag) = env.get("OPENHUMAN_AGENT_TRACING_CAPTURE_CONTENT") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => {+ self.observability.agent_tracing.capture_content = true+ }+ "0" | "false" | "no" | "off" => {+ self.observability.agent_tracing.capture_content = false+ }+ _ => {}+ }+ }+ }+}diff --git a/src/openhuman/config/schema/load/env_overlay_impl_01_part_02.rs b/src/openhuman/config/schema/load/env_overlay_impl_01_part_02.rsnew file mode 100644index 0000000000..d42b66a232--- /dev/null+++ b/src/openhuman/config/schema/load/env_overlay_impl_01_part_02.rs@@ -0,0 +1,469 @@++impl Config {+ fn apply_learning_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {+ if let Some(flag) = env.get("OPENHUMAN_LEARNING_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.learning.enabled = true,+ "0" | "false" | "no" | "off" => self.learning.enabled = false,+ _ => {}+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_LEARNING_REFLECTION_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.learning.reflection_enabled = true,+ "0" | "false" | "no" | "off" => self.learning.reflection_enabled = false,+ _ => {}+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_LEARNING_USER_PROFILE_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.learning.user_profile_enabled = true,+ "0" | "false" | "no" | "off" => self.learning.user_profile_enabled = false,+ _ => {}+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_LEARNING_TOOL_TRACKING_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.learning.tool_tracking_enabled = true,+ "0" | "false" | "no" | "off" => self.learning.tool_tracking_enabled = false,+ _ => {}+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_LEARNING_TOOL_MEMORY_CAPTURE_ENABLED") {+ if let Some(enabled) = parse_env_bool(+ "OPENHUMAN_LEARNING_TOOL_MEMORY_CAPTURE_ENABLED",+ flag.as_str(),+ ) {+ self.learning.tool_memory_capture_enabled = enabled;+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_LEARNING_EXPLICIT_PREFERENCES_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.learning.explicit_preferences_enabled = true,+ "0" | "false" | "no" | "off" => self.learning.explicit_preferences_enabled = false,+ _ => {}+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_LEARNING_GOALS_ENRICHMENT_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.learning.goals_enrichment_enabled = true,+ "0" | "false" | "no" | "off" => self.learning.goals_enrichment_enabled = false,+ _ => {}+ }+ }+ if let Some(source) = env.get("OPENHUMAN_LEARNING_REFLECTION_SOURCE") {+ let normalized = source.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "local" => {+ self.learning.reflection_source =+ crate::openhuman::config::ReflectionSource::Local+ }+ "cloud" => {+ self.learning.reflection_source =+ crate::openhuman::config::ReflectionSource::Cloud+ }+ _ => {+ tracing::warn!(+ source = %source,+ "ignoring invalid OPENHUMAN_LEARNING_REFLECTION_SOURCE (valid: local, cloud)"+ );+ }+ }+ }+ if let Some(val) = env.get("OPENHUMAN_LEARNING_MAX_REFLECTIONS_PER_SESSION") {+ if let Ok(max) = val.trim().parse::<usize>() {+ self.learning.max_reflections_per_session = max;+ }+ }+ if let Some(val) = env.get("OPENHUMAN_LEARNING_MIN_TURN_COMPLEXITY") {+ if let Ok(min) = val.trim().parse::<usize>() {+ self.learning.min_turn_complexity = min;+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_LEARNING_EPISODIC_CAPTURE_ENABLED") {+ if let Some(enabled) =+ parse_env_bool("OPENHUMAN_LEARNING_EPISODIC_CAPTURE_ENABLED", flag.as_str())+ {+ self.learning.episodic_capture_enabled = enabled;+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_LEARNING_STM_RECALL_ENABLED") {+ if let Some(enabled) =+ parse_env_bool("OPENHUMAN_LEARNING_STM_RECALL_ENABLED", flag.as_str())+ {+ self.learning.stm_recall_enabled = enabled;+ }+ }+ }++ fn apply_memory_tree_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {+ if let Ok(endpoint) = std::env::var("OPENHUMAN_MEMORY_EMBED_ENDPOINT") {+ let trimmed = endpoint.trim();+ self.memory_tree.embedding_endpoint = if trimmed.is_empty() {+ None+ } else {+ Some(trimmed.to_string())+ };+ }+ if let Ok(model) = std::env::var("OPENHUMAN_MEMORY_EMBED_MODEL") {+ let trimmed = model.trim();+ self.memory_tree.embedding_model = if trimmed.is_empty() {+ None+ } else {+ Some(trimmed.to_string())+ };+ }+ if let Ok(val) = std::env::var("OPENHUMAN_MEMORY_EMBED_TIMEOUT_MS") {+ if let Ok(timeout_ms) = val.trim().parse::<u64>() {+ if timeout_ms > 0 {+ self.memory_tree.embedding_timeout_ms = Some(timeout_ms);+ }+ }+ }+ if let Ok(flag) = std::env::var("OPENHUMAN_MEMORY_EMBED_STRICT") {+ if let Some(strict) = parse_env_bool("OPENHUMAN_MEMORY_EMBED_STRICT", &flag) {+ self.memory_tree.embedding_strict = strict;+ }+ }+ if let Some(val) = env.get("OPENHUMAN_MEMORY_EMBED_RATE_LIMIT") {+ if let Ok(per_min) = val.trim().parse::<u32>() {+ self.memory.embedding_rate_limit_per_min = per_min;+ }+ }++ if let Ok(endpoint) = std::env::var("OPENHUMAN_MEMORY_EXTRACT_ENDPOINT") {+ let trimmed = endpoint.trim();+ self.memory_tree.llm_extractor_endpoint = if trimmed.is_empty() {+ None+ } else {+ Some(trimmed.to_string())+ };+ }+ if let Ok(model) = std::env::var("OPENHUMAN_MEMORY_EXTRACT_MODEL") {+ let trimmed = model.trim();+ self.memory_tree.llm_extractor_model = if trimmed.is_empty() {+ None+ } else {+ Some(trimmed.to_string())+ };+ }+ if let Ok(val) = std::env::var("OPENHUMAN_MEMORY_EXTRACT_TIMEOUT_MS") {+ if let Ok(ms) = val.trim().parse::<u64>() {+ if ms > 0 {+ self.memory_tree.llm_extractor_timeout_ms = Some(ms);+ }+ }+ }++ if let Ok(endpoint) = std::env::var("OPENHUMAN_MEMORY_SUMMARISE_ENDPOINT") {+ let trimmed = endpoint.trim();+ self.memory_tree.llm_summariser_endpoint = if trimmed.is_empty() {+ None+ } else {+ Some(trimmed.to_string())+ };+ }+ if let Ok(model) = std::env::var("OPENHUMAN_MEMORY_SUMMARISE_MODEL") {+ let trimmed = model.trim();+ self.memory_tree.llm_summariser_model = if trimmed.is_empty() {+ None+ } else {+ Some(trimmed.to_string())+ };+ }+ if let Ok(val) = std::env::var("OPENHUMAN_MEMORY_SUMMARISE_TIMEOUT_MS") {+ if let Ok(ms) = val.trim().parse::<u64>() {+ if ms > 0 {+ self.memory_tree.llm_summariser_timeout_ms = Some(ms);+ }+ }+ }++ if let Some(dir) = env.get("OPENHUMAN_MEMORY_TREE_CONTENT_DIR") {+ let trimmed = dir.trim();+ self.memory_tree.content_dir = if trimmed.is_empty() {+ None+ } else {+ Some(std::path::PathBuf::from(trimmed))+ };+ }++ if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_LLM_BACKEND") {+ let trimmed = raw.trim();+ if !trimmed.is_empty() {+ match crate::openhuman::config::LlmBackend::parse(trimmed) {+ Ok(b) => {+ log::debug!(+ "[memory_tree] OPENHUMAN_MEMORY_TREE_LLM_BACKEND override applied: {}",+ b.as_str()+ );+ self.memory_tree.llm_backend = b;+ }+ Err(e) => {+ tracing::warn!(+ value = trimmed,+ error = %e,+ "ignoring invalid OPENHUMAN_MEMORY_TREE_LLM_BACKEND (valid: cloud, local)"+ );+ }+ }+ }+ }+ if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_CLOUD_LLM_MODEL") {+ let trimmed = raw.trim();+ self.memory_tree.cloud_llm_model = if trimmed.is_empty() {+ None+ } else {+ Some(trimmed.to_string())+ };+ }++ if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_SMART_WALK_MODEL") {+ let trimmed = raw.trim();+ self.memory_tree.smart_walk_model = if trimmed.is_empty() {+ None+ } else {+ Some(trimmed.to_string())+ };+ }++ if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_CLOUD_SUMMARIZATION") {+ if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_TREE_CLOUD_SUMMARIZATION", &raw) {+ self.memory_tree.cloud_summarization_opt_in = val;+ }+ }+ if let Some(raw) = env.get("OPENHUMAN_MEMORY_TREE_SPACY_ENABLED") {+ if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_TREE_SPACY_ENABLED", &raw) {+ self.memory_tree.spacy_enabled = val;+ }+ }+ }++ /// `[subsystems.memory]` overrides — kernel.md §3.6 / plan-memory.md §4.5. Mirrors+ /// the `apply_memory_tree_env` reading pattern above. GREENFIELD: nothing+ /// reads `self.subsystems` yet, so these overrides have no runtime effect+ /// beyond making the field settable via env for forward compatibility.+ fn apply_subsystems_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {+ if let Some(raw) = env.get("OPENHUMAN_MEMORY_DRIVER") {+ let trimmed = raw.trim();+ if !trimmed.is_empty() {+ self.subsystems.memory.driver = trimmed.to_string();+ }+ }++ if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_AUTO_RECALL") {+ if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_HOOKS_AUTO_RECALL", &raw) {+ self.subsystems.memory.hooks.auto_recall = val;+ }+ }+ if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_AUTO_CAPTURE") {+ if let Some(val) = parse_env_bool("OPENHUMAN_MEMORY_HOOKS_AUTO_CAPTURE", &raw) {+ self.subsystems.memory.hooks.auto_capture = val;+ }+ }+ if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_MAX_CONTEXT_TOKENS") {+ let trimmed = raw.trim();+ if !trimmed.is_empty() {+ match trimmed.parse::<usize>() {+ Ok(v) => self.subsystems.memory.hooks.max_context_tokens = v,+ Err(_) => tracing::warn!(+ value = %raw,+ "invalid OPENHUMAN_MEMORY_HOOKS_MAX_CONTEXT_TOKENS ignored; expected an unsigned integer"+ ),+ }+ }+ }+ if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_RECALL_MAX_CHARS") {+ let trimmed = raw.trim();+ if !trimmed.is_empty() {+ match trimmed.parse::<usize>() {+ Ok(v) => self.subsystems.memory.hooks.recall_max_chars = v,+ Err(_) => tracing::warn!(+ value = %raw,+ "invalid OPENHUMAN_MEMORY_HOOKS_RECALL_MAX_CHARS ignored; expected an unsigned integer"+ ),+ }+ }+ }+ if let Some(raw) = env.get("OPENHUMAN_MEMORY_HOOKS_CAPTURE_MAX_CHARS") {+ let trimmed = raw.trim();+ if !trimmed.is_empty() {+ match trimmed.parse::<usize>() {+ Ok(v) => self.subsystems.memory.hooks.capture_max_chars = v,+ Err(_) => tracing::warn!(+ value = %raw,+ "invalid OPENHUMAN_MEMORY_HOOKS_CAPTURE_MAX_CHARS ignored; expected an unsigned integer"+ ),+ }+ }+ }+ }++ fn apply_update_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {+ if let Some(flag) = env.get("OPENHUMAN_AUTO_UPDATE_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.update.enabled = true,+ "0" | "false" | "no" | "off" => self.update.enabled = false,+ _ => {}+ }+ }+ if let Some(val) = env.get("OPENHUMAN_AUTO_UPDATE_INTERVAL_MINUTES") {+ if let Ok(minutes) = val.trim().parse::<u32>() {+ self.update.interval_minutes = minutes;+ }+ }+ if let Some(raw) = env.get("OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY") {+ match raw.trim().to_ascii_lowercase().as_str() {+ "self_replace" | "self-replace" | "self" => {+ self.update.restart_strategy = UpdateRestartStrategy::SelfReplace;+ }+ "supervisor" | "stage_only" | "stage-only" => {+ self.update.restart_strategy = UpdateRestartStrategy::Supervisor;+ }+ other => {+ tracing::warn!(+ value = other,+ "ignoring invalid OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY \+ (valid: self_replace, supervisor)"+ );+ }+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_AUTO_UPDATE_RPC_MUTATIONS_ENABLED") {+ if let Some(enabled) =+ parse_env_bool("OPENHUMAN_AUTO_UPDATE_RPC_MUTATIONS_ENABLED", &flag)+ {+ self.update.rpc_mutations_enabled = enabled;+ }+ }+ }++ fn apply_dictation_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {+ if let Some(flag) = env.get("OPENHUMAN_DICTATION_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.dictation.enabled = true,+ "0" | "false" | "no" | "off" => self.dictation.enabled = false,+ _ => {}+ }+ }+ if let Some(hotkey) = env.get("OPENHUMAN_DICTATION_HOTKEY") {+ let hotkey = hotkey.trim();+ if !hotkey.is_empty() {+ self.dictation.hotkey = hotkey.to_string();+ }+ }+ if let Some(mode) = env.get("OPENHUMAN_DICTATION_ACTIVATION_MODE") {+ let normalized = mode.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "toggle" => {+ self.dictation.activation_mode =+ crate::openhuman::config::DictationActivationMode::Toggle+ }+ "push" => {+ self.dictation.activation_mode =+ crate::openhuman::config::DictationActivationMode::Push+ }+ _ => {+ tracing::warn!(+ mode = %mode,+ "ignoring invalid OPENHUMAN_DICTATION_ACTIVATION_MODE (valid: toggle, push)"+ );+ }+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_DICTATION_LLM_REFINEMENT") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.dictation.llm_refinement = true,+ "0" | "false" | "no" | "off" => self.dictation.llm_refinement = false,+ _ => {}+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_DICTATION_STREAMING") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.dictation.streaming = true,+ "0" | "false" | "no" | "off" => self.dictation.streaming = false,+ _ => {}+ }+ }+ if let Some(val) = env.get("OPENHUMAN_DICTATION_STREAMING_INTERVAL_MS") {+ if let Ok(ms) = val.trim().parse::<u64>() {+ self.dictation.streaming_interval_ms = ms;+ }+ }+ }++ fn apply_context_env<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {+ if let Some(flag) = env.get("OPENHUMAN_CONTEXT_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.context.enabled = true,+ "0" | "false" | "no" | "off" => self.context.enabled = false,+ _ => {}+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_CONTEXT_MICROCOMPACT_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.context.microcompact_enabled = true,+ "0" | "false" | "no" | "off" => self.context.microcompact_enabled = false,+ _ => {}+ }+ }+ if let Some(flag) = env.get("OPENHUMAN_CONTEXT_AUTOCOMPACT_ENABLED") {+ let normalized = flag.trim().to_ascii_lowercase();+ match normalized.as_str() {+ "1" | "true" | "yes" | "on" => self.context.autocompact_enabled = true,+ "0" | "false" | "no" | "off" => self.context.autocompact_enabled = false,+ _ => {}+ }+ }+ if let Some(val) = env.get("OPENHUMAN_CONTEXT_TOOL_RESULT_BUDGET_BYTES") {+ if let Ok(n) = val.trim().parse::<usize>() {+ self.context.tool_result_budget_bytes = n;+ }+ }+ // Kill-switch for native tool-output compaction (Stage 1a). On by+ // default; `OPENHUMAN_COMPACTION=0` disables it for a support/A-B+ // bisect. Accepts the canonical short name and the namespaced form.+ if let Some(flag) = env+ .get("OPENHUMAN_COMPACTION")+ .or_else(|| env.get("OPENHUMAN_CONTEXT_COMPACTION_ENABLED"))+ {+ match flag.trim().to_ascii_lowercase().as_str() {+ "1" | "true" | "yes" | "on" => self.context.compaction_enabled = true,+ "0" | "false" | "no" | "off" => self.context.compaction_enabled = false,+ _ => {}+ }+ }+ if let Some(model) = env.get("OPENHUMAN_CONTEXT_SUMMARIZER_MODEL") {+ let model = model.trim();+ if !model.is_empty() {+ self.context.summarizer_model = Some(model.to_string());+ }+ }+ let context_default = crate::openhuman::agent::context::DEFAULT_TOOL_RESULT_BUDGET_BYTES;+ let context_env_set = env.contains("OPENHUMAN_CONTEXT_TOOL_RESULT_BUDGET_BYTES");+ if !context_env_set+ && self.context.tool_result_budget_bytes == context_default+ && self.agent.tool_result_budget_bytes != context_default+ {+ tracing::warn!(+ old = self.agent.tool_result_budget_bytes,+ "[context:config] `agent.tool_result_budget_bytes` is \+ deprecated — please move it to \+ `context.tool_result_budget_bytes` in your config.toml"+ );+ self.context.tool_result_budget_bytes = self.agent.tool_result_budget_bytes;+ }+ }+}diff --git a/src/openhuman/inference/local/service/assets.rs b/src/openhuman/inference/local/service/assets.rsindex 7030e11f03..478d2db3b3 100644--- a/src/openhuman/inference/local/service/assets.rs+++ b/src/openhuman/inference/local/service/assets.rs@@ -14,755 +14,5 @@ use crate::openhuman::inference::types::{};use super::LocalAiService;--impl LocalAiService {- pub async fn assets_status(&self, config: &Config) -> Result<LocalAiAssetsStatus, String> {- let chat_model = model_ids::effective_chat_model_id(config);- let vision_model = model_ids::effective_vision_model_id(config);- let embedding_model = model_ids::effective_embedding_model_id(config);- let tts_voice = model_ids::effective_tts_voice_id(config);-- let provider = provider_from_config(config);- let correlation_id = uuid::Uuid::new_v4().to_string();- trace!(- target: "local_ai::assets",- %correlation_id,- provider = %provider.as_str(),- chat_model = %chat_model,- vision_model = %vision_model,- embedding_model = %embedding_model,- "[local_ai:assets:provider_routing] entry"- );-- // External-runtime precondition: OpenHuman no longer installs or- // starts Ollama itself, so the interesting question is whether the- // user-managed runtime is reachable right now.- let uses_ollama_assets = matches!(- provider,- LocalAiProvider::Ollama | LocalAiProvider::LmStudio- );- let ollama_available = if uses_ollama_assets {- let base_url = crate::openhuman::inference::local::ollama_base_url_from_config(config);- let present = self.ollama_healthy_at(&base_url).await;- debug!(- target: "local_ai::assets",- %correlation_id,- provider = %provider.as_str(),- ollama_available = present,- "[local_ai:assets:provider_routing] ollama runtime check"- );- present- } else {- true- };- let (chat_ready, vision_ready, embedding_ready) = if provider == LocalAiProvider::LmStudio {- trace!(- target: "local_ai::assets",- %correlation_id,- branch = "lm_studio",- "[local_ai:assets:provider_routing] selected provider branch"- );- let chat_ready = match self.has_lm_studio_model(config, &chat_model).await {- Ok(ready) => {- debug!(- target: "local_ai::assets",- %correlation_id,- provider = "lm_studio",- model = %chat_model,- ready,- "[local_ai:assets:provider_routing] lm studio chat model check"- );- ready- }- Err(err) => {- debug!(- target: "local_ai::assets",- %correlation_id,- provider = "lm_studio",- model = %chat_model,- error = %err,- "[local_ai:assets:provider_routing] lm studio chat model check failed"- );- false- }- };- let embedding_ready = if ollama_available {- match self.has_model_for_config(config, &embedding_model).await {- Ok(ready) => {- debug!(- target: "local_ai::assets",- %correlation_id,- provider = "ollama",- model = %embedding_model,- ready,- "[local_ai:assets:provider_routing] lm studio embedding ollama model check"- );- ready- }- Err(err) => {- debug!(- target: "local_ai::assets",- %correlation_id,- provider = "ollama",- model = %embedding_model,- error = %err,- "[local_ai:assets:provider_routing] lm studio embedding ollama model check failed"- );- false- }- }- } else {- debug!(- target: "local_ai::assets",- %correlation_id,- provider = "ollama",- model = %embedding_model,- "[local_ai:assets:provider_routing] lm studio embedding check skipped; ollama runtime unavailable"- );- false- };- (chat_ready, false, embedding_ready)- } else if ollama_available {- trace!(- target: "local_ai::assets",- %correlation_id,- branch = "ollama",- "[local_ai:assets:provider_routing] selected provider branch"- );- let chat_ready = match self.has_model_for_config(config, &chat_model).await {- Ok(ready) => {- debug!(- target: "local_ai::assets",- %correlation_id,- provider = "ollama",- capability = "chat",- model = %chat_model,- ready,- "[local_ai:assets:provider_routing] ollama model check"- );- ready- }- Err(err) => {- debug!(- target: "local_ai::assets",- %correlation_id,- provider = "ollama",- capability = "chat",- model = %chat_model,- error = %err,- "[local_ai:assets:provider_routing] ollama model check failed"- );- false- }- };- let vision_ready = match self.has_model_for_config(config, &vision_model).await {- Ok(ready) => {- debug!(- target: "local_ai::assets",- %correlation_id,- provider = "ollama",- capability = "vision",- model = %vision_model,- ready,- "[local_ai:assets:provider_routing] ollama model check"- );- ready- }- Err(err) => {- debug!(- target: "local_ai::assets",- %correlation_id,- provider = "ollama",- capability = "vision",- model = %vision_model,- error = %err,- "[local_ai:assets:provider_routing] ollama model check failed"- );- false- }- };- let embedding_ready = match self.has_model_for_config(config, &embedding_model).await {- Ok(ready) => {- debug!(- target: "local_ai::assets",- %correlation_id,- provider = "ollama",- capability = "embedding",- model = %embedding_model,- ready,- "[local_ai:assets:provider_routing] ollama model check"- );- ready- }- Err(err) => {- debug!(- target: "local_ai::assets",- %correlation_id,- provider = "ollama",- capability = "embedding",- model = %embedding_model,- error = %err,- "[local_ai:assets:provider_routing] ollama model check failed"- );- false- }- };- (chat_ready, vision_ready, embedding_ready)- } else {- trace!(- target: "local_ai::assets",- %correlation_id,- branch = "ollama_runtime_unavailable",- "[local_ai:assets:provider_routing] selected provider branch"- );- (false, false, false)- };- trace!(- target: "local_ai::assets",- %correlation_id,- chat_ready,- vision_ready,- embedding_ready,- ollama_available,- "[local_ai:assets:provider_routing] exit"- );- let tts_resolve = resolve_tts_voice_path(config);-- let tts_path = tts_resolve.as_ref().ok().cloned();-- // TTS is downloaded on demand (first synthesis). When the model file- // is not yet on disk but a download URL is configured, report- // "ondemand" instead of "missing" so the UI can treat it as- // non-blocking.- let has_tts_url = config- .local_ai- .tts_download_url- .as_deref()- .is_some_and(|v| !v.trim().is_empty());-- let tts_state = if tts_path.is_some() {- "ready"- } else if has_tts_url {- "ondemand"- } else {- "missing"- };-- if let Err(ref err) = tts_resolve {- debug!("[local_ai::assets_status] TTS resolve failed (state={tts_state}): {err}");- }-- let tts_warning = match tts_state {- "ondemand" => Some("TTS voice will download on first synthesis request.".to_string()),- _ => None,- };-- let vision_mode = presets::vision_mode_for_config(&config.local_ai);- let embedding_path = Some(format!("ollama://{embedding_model}"));- Ok(LocalAiAssetsStatus {- chat: LocalAiAssetStatus {- state: if chat_ready { "ready" } else { "missing" }.to_string(),- id: chat_model,- provider: provider.as_str().to_string(),- path: None,- warning: (provider == LocalAiProvider::LmStudio && !chat_ready).then(|| {- "Load this model in LM Studio or update local_ai.chat_model_id.".to_string()- }),- },- vision: LocalAiAssetStatus {- state: if provider == LocalAiProvider::LmStudio {- "disabled".to_string()- } else {- match vision_mode {- VisionMode::Disabled => "disabled",- VisionMode::Ondemand if vision_ready => "ready",- VisionMode::Ondemand => "ondemand",- VisionMode::Bundled if vision_ready => "ready",- VisionMode::Bundled => "missing",- }- .to_string()- },- id: vision_model,- provider: provider.as_str().to_string(),- path: None,- warning: if provider == LocalAiProvider::LmStudio {- Some("Vision is not part of the first LM Studio provider slice.".to_string())- } else {- match vision_mode {- VisionMode::Disabled => {- Some("Vision is disabled for this RAM tier.".to_string())- }- VisionMode::Ondemand if !vision_ready => {- Some("Vision model will download on first vision request.".to_string())- }- _ => None,- }- },- },- embedding: LocalAiAssetStatus {- state: if embedding_ready { "ready" } else { "missing" }.to_string(),- id: embedding_model,- provider: if provider == LocalAiProvider::LmStudio {- "ollama".to_string()- } else {- provider.as_str().to_string()- },- path: embedding_path,- warning: (provider == LocalAiProvider::LmStudio).then(|| {- "Embeddings still use the existing Ollama path in this first LM Studio slice."- .to_string()- }),- },- tts: LocalAiAssetStatus {- state: tts_state.to_string(),- id: tts_voice,- provider: "piper".to_string(),- path: tts_path,- warning: tts_warning,- },- quantization: model_ids::effective_quantization(config),- ollama_available,- })- }-- pub async fn downloads_progress(- &self,- config: &Config,- ) -> Result<LocalAiDownloadsProgress, String> {- let assets = self.assets_status(config).await?;- let status = self.status();-- let mut chat = LocalAiDownloadProgressItem {- id: assets.chat.id,- provider: assets.chat.provider,- state: assets.chat.state,- progress: None,- downloaded_bytes: None,- total_bytes: None,- speed_bps: None,- eta_seconds: None,- warning: assets.chat.warning,- path: assets.chat.path,- };- let mut vision = LocalAiDownloadProgressItem {- id: assets.vision.id,- provider: assets.vision.provider,- state: assets.vision.state,- progress: None,- downloaded_bytes: None,- total_bytes: None,- speed_bps: None,- eta_seconds: None,- warning: assets.vision.warning,- path: assets.vision.path,- };- let mut embedding = LocalAiDownloadProgressItem {- id: assets.embedding.id,- provider: assets.embedding.provider,- state: assets.embedding.state,- progress: None,- downloaded_bytes: None,- total_bytes: None,- speed_bps: None,- eta_seconds: None,- warning: assets.embedding.warning,- path: assets.embedding.path,- };- let mut tts = LocalAiDownloadProgressItem {- id: assets.tts.id,- provider: assets.tts.provider,- state: assets.tts.state,- progress: None,- downloaded_bytes: None,- total_bytes: None,- speed_bps: None,- eta_seconds: None,- warning: assets.tts.warning,- path: assets.tts.path,- };-- if status.state == "downloading" {- let active = if status.tts_state == "downloading" {- "tts"- } else if status.vision_state == "downloading" {- "vision"- } else if status.embedding_state == "downloading" {- "embedding"- } else {- "chat"- };-- let apply = |item: &mut LocalAiDownloadProgressItem| {- item.state = "downloading".to_string();- item.progress = status.download_progress;- item.downloaded_bytes = status.downloaded_bytes;- item.total_bytes = status.total_bytes;- item.speed_bps = status.download_speed_bps;- item.eta_seconds = status.eta_seconds;- item.warning = status.warning.clone();- };-- match active {- "tts" => apply(&mut tts),- "vision" => apply(&mut vision),- "embedding" => apply(&mut embedding),- _ => apply(&mut chat),- }- }-- Ok(LocalAiDownloadsProgress {- state: status.state,- warning: status.warning,- progress: status.download_progress,- downloaded_bytes: status.downloaded_bytes,- total_bytes: status.total_bytes,- speed_bps: status.download_speed_bps,- eta_seconds: status.eta_seconds,- chat,- vision,- embedding,- tts,- ollama_available: assets.ollama_available,- })- }-- fn finalize_lm_studio_download_status(- &self,- config: &Config,- embedding_state: Option<&'static str>,- tts_state: Option<&'static str>,- warning: Option<String>,- ) {- let mut status = self.status.lock();- status.state = "ready".to_string();- status.vision_state = "disabled".to_string();- if let Some(state) = embedding_state {- status.embedding_state = state.to_string();- } else if !config.local_ai.preload_embedding_model {- status.embedding_state = "idle".to_string();- } else if status.embedding_state != "ready" {- status.embedding_state = "missing".to_string();- }- if let Some(state) = tts_state {- status.tts_state = state.to_string();- } else if !config.local_ai.preload_tts_voice {- status.tts_state = "idle".to_string();- }- status.warning = warning;- status.error_detail = None;- status.error_category = None;- status.download_progress = None;- status.downloaded_bytes = None;- status.total_bytes = None;- status.download_speed_bps = None;- status.eta_seconds = None;- }-- pub async fn download_all_models(&self, config: &Config) -> Result<(), String> {- if !config.local_ai.runtime_enabled {- return Err("local ai is disabled".to_string());- }- let _guard = self.bootstrap_lock.lock().await;-- if provider_from_config(config) == LocalAiProvider::LmStudio {- self.ensure_lm_studio_available(config).await?;- let mut embedding_state = None;- if config.local_ai.preload_embedding_model {- let model_id = model_ids::effective_embedding_model_id(config);- {- let mut status = self.status.lock();- status.state = "downloading".to_string();- status.embedding_state = "downloading".to_string();- status.warning = Some(format!(- "Downloading embedding model via Ollama: `{model_id}`"- ));- }- if let Err(err) = async {- self.ensure_ollama_server(config).await?;- self.ensure_ollama_model_available(config, &model_id, "embedding")- .await- }- .await- {- log::warn!(- "[local_ai] LM Studio download_all_models embedding preload failed: {err}"- );- self.finalize_lm_studio_download_status(config, Some("missing"), None, None);- return Err(err);- }- embedding_state = Some("ready");- }- let mut tts_warning = None;- let mut tts_state = None;- if config.local_ai.preload_tts_voice {- if let Err(err) = self.ensure_tts_asset_available(config).await {- log::warn!(- "[local_ai] LM Studio download_all_models TTS preload failed: {err}"- );- tts_state = Some("missing");- tts_warning = Some(err);- } else {- tts_state = Some("ready");- }- }- let warning = tts_warning;- self.finalize_lm_studio_download_status(config, embedding_state, tts_state, warning);- return Ok(());- }-- self.ensure_ollama_server(config).await?;-- let mut steps = vec![- ("chat", model_ids::effective_chat_model_id(config)),- ("embedding", model_ids::effective_embedding_model_id(config)),- ];- if matches!(- presets::vision_mode_for_config(&config.local_ai),- VisionMode::Bundled- ) {- steps.insert(1, ("vision", model_ids::effective_vision_model_id(config)));- }-- let total = steps.len();- for (index, (label, model_id)) in steps.into_iter().enumerate() {- {- let mut status = self.status.lock();- status.state = "downloading".to_string();- status.warning = Some(format!(- "Downloading {} model {}/{}: `{}`",- label,- index + 1,- total,- model_id- ));- match label {- "vision" => status.vision_state = "downloading".to_string(),- "embedding" => status.embedding_state = "downloading".to_string(),- _ => {}- }- }- self.ensure_ollama_model_available(config, &model_id, label)- .await?;- }-- let mut tts_warning = None;- if let Err(err) = self.ensure_tts_asset_available(config).await {- self.status.lock().tts_state = "missing".to_string();- tts_warning = Some(err);- }-- {- let mut status = self.status.lock();- status.state = "ready".to_string();- status.vision_state = match presets::vision_mode_for_config(&config.local_ai) {- VisionMode::Disabled => "disabled".to_string(),- VisionMode::Ondemand => "idle".to_string(),- VisionMode::Bundled => "ready".to_string(),- };- status.download_progress = Some(1.0);- status.downloaded_bytes = None;- status.total_bytes = None;- status.download_speed_bps = None;- status.eta_seconds = None;- status.warning = tts_warning;- }-- Ok(())- }-- pub async fn download_asset(- &self,- config: &Config,- capability: &str,- ) -> Result<LocalAiAssetsStatus, String> {- if !config.local_ai.runtime_enabled {- return Err("local ai is disabled".to_string());- }- let _guard = self.bootstrap_lock.lock().await;-- let capability = capability.trim().to_ascii_lowercase();- if provider_from_config(config) == LocalAiProvider::LmStudio- && matches!(capability.as_str(), "chat" | "vision")- {- return Err(- "LM Studio manages chat and vision model downloads. Load the model in LM Studio, then retry."- .to_string(),- );- }- match capability.as_str() {- "chat" => {- self.ensure_ollama_server(config).await?;- let model = model_ids::effective_chat_model_id(config);- self.ensure_ollama_model_available(config, &model, "chat")- .await?;- }- "vision" => {- if matches!(- presets::vision_mode_for_config(&config.local_ai),- VisionMode::Disabled- ) {- return Err(- "Vision is disabled for this RAM tier. Switch to the 4-8 GB tier or above to enable it."- .to_string(),- );- }- // Resolve rather than take the effective id: the latter blanks- // a chat-only model, and a blank id makes- // `ensure_ollama_model_available` answer "no vision model is- // configured" to a user who configured one. Naming the model- // that cannot accept images is the whole point of #5146 P1.- //- // Before probing Ollama, too: a misconfigured id is answerable- // without the network, and reaching the server first would hand- // back a connection error for a problem that is purely local.- let model = model_ids::resolve_vision_model_id(config)?;- self.ensure_ollama_server(config).await?;- self.ensure_ollama_model_available(config, &model, "vision")- .await?;- }- "embedding" | "embeddings" => {- self.ensure_ollama_server(config).await?;- let model = model_ids::effective_embedding_model_id(config);- self.ensure_ollama_model_available(config, &model, "embedding")- .await?;- }- "tts" => {- self.ensure_tts_asset_available(config).await?;- }- _ => {- return Err(- "Unknown capability. Use one of: chat, vision, embedding, tts.".to_string(),- )- }- }-- self.assets_status(config).await- }-- pub(in crate::openhuman::inference::local::service) async fn ensure_tts_asset_available(- &self,- config: &Config,- ) -> Result<(), String> {- if resolve_tts_voice_path(config).is_ok() {- self.status.lock().tts_state = "ready".to_string();- return Ok(());- }-- let url = config- .local_ai- .tts_download_url- .as_deref()- .filter(|v| !v.trim().is_empty())- .ok_or_else(|| {- "TTS voice missing and no local_ai.tts_download_url configured".to_string()- })?;- let dest = tts_model_target_path(config);- self.download_file_with_progress(url, &dest, "tts").await?;-- if let Some(config_url) = config- .local_ai- .tts_config_download_url- .as_deref()- .filter(|v| !v.trim().is_empty())- {- let config_dest = std::path::PathBuf::from(format!("{}.json", dest.display()));- let _ = self- .download_file_with_progress(config_url, &config_dest, "tts-config")- .await;- }-- self.status.lock().tts_state = "ready".to_string();- Ok(())- }-- async fn download_file_with_progress(- &self,- url: &str,- dest: &Path,- label: &str,- ) -> Result<(), String> {- if let Some(parent) = dest.parent() {- tokio::fs::create_dir_all(parent)- .await- .map_err(|e| format!("failed to create destination directory: {e}"))?;- }-- let response = self- .http- .get(url)- // Large model assets (STT/TTS) can take minutes on slower links.- // Avoid inheriting the short default client timeout for these streams.- .timeout(std::time::Duration::from_secs(30 * 60))- .send()- .await- .map_err(|e| format!("failed to start {label} download: {e}"))?;- if !response.status().is_success() {- return Err(format!(- "failed to download {label} asset, status {}",- response.status()- ));- }-- {- let mut status = self.status.lock();- status.state = "downloading".to_string();- status.warning = Some(format!("Downloading {label} asset"));- match label {- "stt" => status.stt_state = "downloading".to_string(),- "tts" | "tts-config" => status.tts_state = "downloading".to_string(),- _ => {}- }- status.download_progress = Some(0.0);- status.downloaded_bytes = Some(0);- status.total_bytes = response.content_length();- status.download_speed_bps = Some(0);- status.eta_seconds = None;- }-- let total = response.content_length();- let mut downloaded: u64 = 0;- let started_at = std::time::Instant::now();- let mut file = tokio::fs::File::create(dest)- .await- .map_err(|e| format!("failed to create destination file: {e}"))?;- let mut stream = response.bytes_stream();- while let Some(chunk) = stream- .try_next()- .await- .map_err(|e| format!("download stream error for {label}: {e}"))?- {- use tokio::io::AsyncWriteExt;- file.write_all(&chunk)- .await- .map_err(|e| format!("failed writing {label} file: {e}"))?;- downloaded = downloaded.saturating_add(chunk.len() as u64);- let elapsed = started_at.elapsed().as_secs_f64().max(0.001);- let speed_bps = (downloaded as f64 / elapsed).round().max(0.0) as u64;- let eta_seconds = total.and_then(|t| {- if downloaded >= t || speed_bps == 0 {- None- } else {- Some((t.saturating_sub(downloaded)) / speed_bps.max(1))- }- });-- let mut status = self.status.lock();- status.state = "downloading".to_string();- status.warning = Some(format!("Downloading {label} asset"));- match label {- "stt" => status.stt_state = "downloading".to_string(),- "tts" | "tts-config" => status.tts_state = "downloading".to_string(),- _ => {}- }- status.downloaded_bytes = Some(downloaded);- status.total_bytes = total;- status.download_speed_bps = Some(speed_bps);- status.eta_seconds = eta_seconds;- status.download_progress = total- .map(|t| (downloaded as f32 / t as f32).clamp(0.0, 1.0))- .or(Some(0.0));- }-- Ok(())- }-}+include!("assets_impl_01_part_01.rs");+include!("assets_impl_01_part_02.rs");diff --git a/src/openhuman/inference/local/service/assets_impl_01_part_01.rs b/src/openhuman/inference/local/service/assets_impl_01_part_01.rsnew file mode 100644index 0000000000..9cd564a3f8--- /dev/null+++ b/src/openhuman/inference/local/service/assets_impl_01_part_01.rs@@ -0,0 +1,626 @@++impl LocalAiService {++ pub async fn assets_status(&self, config: &Config) -> Result<LocalAiAssetsStatus, String> {+ let chat_model = model_ids::effective_chat_model_id(config);+ let vision_model = model_ids::effective_vision_model_id(config);+ let embedding_model = model_ids::effective_embedding_model_id(config);+ let tts_voice = model_ids::effective_tts_voice_id(config);++ let provider = provider_from_config(config);+ let correlation_id = uuid::Uuid::new_v4().to_string();+ trace!(+ target: "local_ai::assets",+ %correlation_id,+ provider = %provider.as_str(),+ chat_model = %chat_model,+ vision_model = %vision_model,+ embedding_model = %embedding_model,+ "[local_ai:assets:provider_routing] entry"+ );++ // External-runtime precondition: OpenHuman no longer installs or+ // starts Ollama itself, so the interesting question is whether the+ // user-managed runtime is reachable right now.+ let uses_ollama_assets = matches!(+ provider,+ LocalAiProvider::Ollama | LocalAiProvider::LmStudio+ );+ let ollama_available = if uses_ollama_assets {+ let base_url = crate::openhuman::inference::local::ollama_base_url_from_config(config);+ let present = self.ollama_healthy_at(&base_url).await;+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = %provider.as_str(),+ ollama_available = present,+ "[local_ai:assets:provider_routing] ollama runtime check"+ );+ present+ } else {+ true+ };+ let (chat_ready, vision_ready, embedding_ready) = if provider == LocalAiProvider::LmStudio {+ trace!(+ target: "local_ai::assets",+ %correlation_id,+ branch = "lm_studio",+ "[local_ai:assets:provider_routing] selected provider branch"+ );+ let chat_ready = match self.has_lm_studio_model(config, &chat_model).await {+ Ok(ready) => {+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = "lm_studio",+ model = %chat_model,+ ready,+ "[local_ai:assets:provider_routing] lm studio chat model check"+ );+ ready+ }+ Err(err) => {+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = "lm_studio",+ model = %chat_model,+ error = %err,+ "[local_ai:assets:provider_routing] lm studio chat model check failed"+ );+ false+ }+ };+ let embedding_ready = if ollama_available {+ match self.has_model_for_config(config, &embedding_model).await {+ Ok(ready) => {+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = "ollama",+ model = %embedding_model,+ ready,+ "[local_ai:assets:provider_routing] lm studio embedding ollama model check"+ );+ ready+ }+ Err(err) => {+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = "ollama",+ model = %embedding_model,+ error = %err,+ "[local_ai:assets:provider_routing] lm studio embedding ollama model check failed"+ );+ false+ }+ }+ } else {+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = "ollama",+ model = %embedding_model,+ "[local_ai:assets:provider_routing] lm studio embedding check skipped; ollama runtime unavailable"+ );+ false+ };+ (chat_ready, false, embedding_ready)+ } else if ollama_available {+ trace!(+ target: "local_ai::assets",+ %correlation_id,+ branch = "ollama",+ "[local_ai:assets:provider_routing] selected provider branch"+ );+ let chat_ready = match self.has_model_for_config(config, &chat_model).await {+ Ok(ready) => {+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = "ollama",+ capability = "chat",+ model = %chat_model,+ ready,+ "[local_ai:assets:provider_routing] ollama model check"+ );+ ready+ }+ Err(err) => {+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = "ollama",+ capability = "chat",+ model = %chat_model,+ error = %err,+ "[local_ai:assets:provider_routing] ollama model check failed"+ );+ false+ }+ };+ let vision_ready = match self.has_model_for_config(config, &vision_model).await {+ Ok(ready) => {+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = "ollama",+ capability = "vision",+ model = %vision_model,+ ready,+ "[local_ai:assets:provider_routing] ollama model check"+ );+ ready+ }+ Err(err) => {+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = "ollama",+ capability = "vision",+ model = %vision_model,+ error = %err,+ "[local_ai:assets:provider_routing] ollama model check failed"+ );+ false+ }+ };+ let embedding_ready = match self.has_model_for_config(config, &embedding_model).await {+ Ok(ready) => {+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = "ollama",+ capability = "embedding",+ model = %embedding_model,+ ready,+ "[local_ai:assets:provider_routing] ollama model check"+ );+ ready+ }+ Err(err) => {+ debug!(+ target: "local_ai::assets",+ %correlation_id,+ provider = "ollama",+ capability = "embedding",+ model = %embedding_model,+ error = %err,+ "[local_ai:assets:provider_routing] ollama model check failed"+ );+ false+ }+ };+ (chat_ready, vision_ready, embedding_ready)+ } else {+ trace!(+ target: "local_ai::assets",+ %correlation_id,+ branch = "ollama_runtime_unavailable",+ "[local_ai:assets:provider_routing] selected provider branch"+ );+ (false, false, false)+ };+ trace!(+ target: "local_ai::assets",+ %correlation_id,+ chat_ready,+ vision_ready,+ embedding_ready,+ ollama_available,+ "[local_ai:assets:provider_routing] exit"+ );+ let tts_resolve = resolve_tts_voice_path(config);++ let tts_path = tts_resolve.as_ref().ok().cloned();++ // TTS is downloaded on demand (first synthesis). When the model file+ // is not yet on disk but a download URL is configured, report+ // "ondemand" instead of "missing" so the UI can treat it as+ // non-blocking.+ let has_tts_url = config+ .local_ai+ .tts_download_url+ .as_deref()+ .is_some_and(|v| !v.trim().is_empty());++ let tts_state = if tts_path.is_some() {+ "ready"+ } else if has_tts_url {+ "ondemand"+ } else {+ "missing"+ };++ if let Err(ref err) = tts_resolve {+ debug!("[local_ai::assets_status] TTS resolve failed (state={tts_state}): {err}");+ }++ let tts_warning = match tts_state {+ "ondemand" => Some("TTS voice will download on first synthesis request.".to_string()),+ _ => None,+ };++ let vision_mode = presets::vision_mode_for_config(&config.local_ai);+ let embedding_path = Some(format!("ollama://{embedding_model}"));+ Ok(LocalAiAssetsStatus {+ chat: LocalAiAssetStatus {+ state: if chat_ready { "ready" } else { "missing" }.to_string(),+ id: chat_model,+ provider: provider.as_str().to_string(),+ path: None,+ warning: (provider == LocalAiProvider::LmStudio && !chat_ready).then(|| {+ "Load this model in LM Studio or update local_ai.chat_model_id.".to_string()+ }),+ },+ vision: LocalAiAssetStatus {+ state: if provider == LocalAiProvider::LmStudio {+ "disabled".to_string()+ } else {+ match vision_mode {+ VisionMode::Disabled => "disabled",+ VisionMode::Ondemand if vision_ready => "ready",+ VisionMode::Ondemand => "ondemand",+ VisionMode::Bundled if vision_ready => "ready",+ VisionMode::Bundled => "missing",+ }+ .to_string()+ },+ id: vision_model,+ provider: provider.as_str().to_string(),+ path: None,+ warning: if provider == LocalAiProvider::LmStudio {+ Some("Vision is not part of the first LM Studio provider slice.".to_string())+ } else {+ match vision_mode {+ VisionMode::Disabled => {+ Some("Vision is disabled for this RAM tier.".to_string())+ }+ VisionMode::Ondemand if !vision_ready => {+ Some("Vision model will download on first vision request.".to_string())+ }+ _ => None,+ }+ },+ },+ embedding: LocalAiAssetStatus {+ state: if embedding_ready { "ready" } else { "missing" }.to_string(),+ id: embedding_model,+ provider: if provider == LocalAiProvider::LmStudio {+ "ollama".to_string()+ } else {+ provider.as_str().to_string()+ },+ path: embedding_path,+ warning: (provider == LocalAiProvider::LmStudio).then(|| {+ "Embeddings still use the existing Ollama path in this first LM Studio slice."+ .to_string()+ }),+ },+ tts: LocalAiAssetStatus {+ state: tts_state.to_string(),+ id: tts_voice,+ provider: "piper".to_string(),+ path: tts_path,+ warning: tts_warning,+ },+ quantization: model_ids::effective_quantization(config),+ ollama_available,+ })+ }++ pub async fn downloads_progress(+ &self,+ config: &Config,+ ) -> Result<LocalAiDownloadsProgress, String> {+ let assets = self.assets_status(config).await?;+ let status = self.status();++ let mut chat = LocalAiDownloadProgressItem {+ id: assets.chat.id,+ provider: assets.chat.provider,+ state: assets.chat.state,+ progress: None,+ downloaded_bytes: None,+ total_bytes: None,+ speed_bps: None,+ eta_seconds: None,+ warning: assets.chat.warning,+ path: assets.chat.path,+ };+ let mut vision = LocalAiDownloadProgressItem {+ id: assets.vision.id,+ provider: assets.vision.provider,+ state: assets.vision.state,+ progress: None,+ downloaded_bytes: None,+ total_bytes: None,+ speed_bps: None,+ eta_seconds: None,+ warning: assets.vision.warning,+ path: assets.vision.path,+ };+ let mut embedding = LocalAiDownloadProgressItem {+ id: assets.embedding.id,+ provider: assets.embedding.provider,+ state: assets.embedding.state,+ progress: None,+ downloaded_bytes: None,+ total_bytes: None,+ speed_bps: None,+ eta_seconds: None,+ warning: assets.embedding.warning,+ path: assets.embedding.path,+ };+ let mut tts = LocalAiDownloadProgressItem {+ id: assets.tts.id,+ provider: assets.tts.provider,+ state: assets.tts.state,+ progress: None,+ downloaded_bytes: None,+ total_bytes: None,+ speed_bps: None,+ eta_seconds: None,+ warning: assets.tts.warning,+ path: assets.tts.path,+ };++ if status.state == "downloading" {+ let active = if status.tts_state == "downloading" {+ "tts"+ } else if status.vision_state == "downloading" {+ "vision"+ } else if status.embedding_state == "downloading" {+ "embedding"+ } else {+ "chat"+ };++ let apply = |item: &mut LocalAiDownloadProgressItem| {+ item.state = "downloading".to_string();+ item.progress = status.download_progress;+ item.downloaded_bytes = status.downloaded_bytes;+ item.total_bytes = status.total_bytes;+ item.speed_bps = status.download_speed_bps;+ item.eta_seconds = status.eta_seconds;+ item.warning = status.warning.clone();+ };++ match active {+ "tts" => apply(&mut tts),+ "vision" => apply(&mut vision),+ "embedding" => apply(&mut embedding),+ _ => apply(&mut chat),+ }+ }++ Ok(LocalAiDownloadsProgress {+ state: status.state,+ warning: status.warning,+ progress: status.download_progress,+ downloaded_bytes: status.downloaded_bytes,+ total_bytes: status.total_bytes,+ speed_bps: status.download_speed_bps,+ eta_seconds: status.eta_seconds,+ chat,+ vision,+ embedding,+ tts,+ ollama_available: assets.ollama_available,+ })+ }++ fn finalize_lm_studio_download_status(+ &self,+ config: &Config,+ embedding_state: Option<&'static str>,+ tts_state: Option<&'static str>,+ warning: Option<String>,+ ) {+ let mut status = self.status.lock();+ status.state = "ready".to_string();+ status.vision_state = "disabled".to_string();+ if let Some(state) = embedding_state {+ status.embedding_state = state.to_string();+ } else if !config.local_ai.preload_embedding_model {+ status.embedding_state = "idle".to_string();+ } else if status.embedding_state != "ready" {+ status.embedding_state = "missing".to_string();+ }+ if let Some(state) = tts_state {+ status.tts_state = state.to_string();+ } else if !config.local_ai.preload_tts_voice {+ status.tts_state = "idle".to_string();+ }+ status.warning = warning;+ status.error_detail = None;+ status.error_category = None;+ status.download_progress = None;+ status.downloaded_bytes = None;+ status.total_bytes = None;+ status.download_speed_bps = None;+ status.eta_seconds = None;+ }++ pub async fn download_all_models(&self, config: &Config) -> Result<(), String> {+ if !config.local_ai.runtime_enabled {+ return Err("local ai is disabled".to_string());+ }+ let _guard = self.bootstrap_lock.lock().await;++ if provider_from_config(config) == LocalAiProvider::LmStudio {+ self.ensure_lm_studio_available(config).await?;+ let mut embedding_state = None;+ if config.local_ai.preload_embedding_model {+ let model_id = model_ids::effective_embedding_model_id(config);+ {+ let mut status = self.status.lock();+ status.state = "downloading".to_string();+ status.embedding_state = "downloading".to_string();+ status.warning = Some(format!(+ "Downloading embedding model via Ollama: `{model_id}`"+ ));+ }+ if let Err(err) = async {+ self.ensure_ollama_server(config).await?;+ self.ensure_ollama_model_available(config, &model_id, "embedding")+ .await+ }+ .await+ {+ log::warn!(+ "[local_ai] LM Studio download_all_models embedding preload failed: {err}"+ );+ self.finalize_lm_studio_download_status(config, Some("missing"), None, None);+ return Err(err);+ }+ embedding_state = Some("ready");+ }+ let mut tts_warning = None;+ let mut tts_state = None;+ if config.local_ai.preload_tts_voice {+ if let Err(err) = self.ensure_tts_asset_available(config).await {+ log::warn!(+ "[local_ai] LM Studio download_all_models TTS preload failed: {err}"+ );+ tts_state = Some("missing");+ tts_warning = Some(err);+ } else {+ tts_state = Some("ready");+ }+ }+ let warning = tts_warning;+ self.finalize_lm_studio_download_status(config, embedding_state, tts_state, warning);+ return Ok(());+ }++ self.ensure_ollama_server(config).await?;++ let mut steps = vec![+ ("chat", model_ids::effective_chat_model_id(config)),+ ("embedding", model_ids::effective_embedding_model_id(config)),+ ];+ if matches!(+ presets::vision_mode_for_config(&config.local_ai),+ VisionMode::Bundled+ ) {+ steps.insert(1, ("vision", model_ids::effective_vision_model_id(config)));+ }++ let total = steps.len();+ for (index, (label, model_id)) in steps.into_iter().enumerate() {+ {+ let mut status = self.status.lock();+ status.state = "downloading".to_string();+ status.warning = Some(format!(+ "Downloading {} model {}/{}: `{}`",+ label,+ index + 1,+ total,+ model_id+ ));+ match label {+ "vision" => status.vision_state = "downloading".to_string(),+ "embedding" => status.embedding_state = "downloading".to_string(),+ _ => {}+ }+ }+ self.ensure_ollama_model_available(config, &model_id, label)+ .await?;+ }++ let mut tts_warning = None;+ if let Err(err) = self.ensure_tts_asset_available(config).await {+ self.status.lock().tts_state = "missing".to_string();+ tts_warning = Some(err);+ }++ {+ let mut status = self.status.lock();+ status.state = "ready".to_string();+ status.vision_state = match presets::vision_mode_for_config(&config.local_ai) {+ VisionMode::Disabled => "disabled".to_string(),+ VisionMode::Ondemand => "idle".to_string(),+ VisionMode::Bundled => "ready".to_string(),+ };+ status.download_progress = Some(1.0);+ status.downloaded_bytes = None;+ status.total_bytes = None;+ status.download_speed_bps = None;+ status.eta_seconds = None;+ status.warning = tts_warning;+ }++ Ok(())+ }++ pub async fn download_asset(+ &self,+ config: &Config,+ capability: &str,+ ) -> Result<LocalAiAssetsStatus, String> {+ if !config.local_ai.runtime_enabled {+ return Err("local ai is disabled".to_string());+ }+ let _guard = self.bootstrap_lock.lock().await;++ let capability = capability.trim().to_ascii_lowercase();+ if provider_from_config(config) == LocalAiProvider::LmStudio+ && matches!(capability.as_str(), "chat" | "vision")+ {+ return Err(+ "LM Studio manages chat and vision model downloads. Load the model in LM Studio, then retry."+ .to_string(),+ );+ }+ match capability.as_str() {+ "chat" => {+ self.ensure_ollama_server(config).await?;+ let model = model_ids::effective_chat_model_id(config);+ self.ensure_ollama_model_available(config, &model, "chat")+ .await?;+ }+ "vision" => {+ if matches!(+ presets::vision_mode_for_config(&config.local_ai),+ VisionMode::Disabled+ ) {+ return Err(+ "Vision is disabled for this RAM tier. Switch to the 4-8 GB tier or above to enable it."+ .to_string(),+ );+ }+ // Resolve rather than take the effective id: the latter blanks+ // a chat-only model, and a blank id makes+ // `ensure_ollama_model_available` answer "no vision model is+ // configured" to a user who configured one. Naming the model+ // that cannot accept images is the whole point of #5146 P1.+ //+ // Before probing Ollama, too: a misconfigured id is answerable+ // without the network, and reaching the server first would hand+ // back a connection error for a problem that is purely local.+ let model = model_ids::resolve_vision_model_id(config)?;+ self.ensure_ollama_server(config).await?;+ self.ensure_ollama_model_available(config, &model, "vision")+ .await?;+ }+ "embedding" | "embeddings" => {+ self.ensure_ollama_server(config).await?;+ let model = model_ids::effective_embedding_model_id(config);+ self.ensure_ollama_model_available(config, &model, "embedding")+ .await?;+ }+ "tts" => {+ self.ensure_tts_asset_available(config).await?;+ }+ _ => {+ return Err(+ "Unknown capability. Use one of: chat, vision, embedding, tts.".to_string(),+ )+ }+ }++ self.assets_status(config).await+ }+}diff --git a/src/openhuman/inference/local/service/assets_impl_01_part_02.rs b/src/openhuman/inference/local/service/assets_impl_01_part_02.rsnew file mode 100644index 0000000000..2c359262eb--- /dev/null+++ b/src/openhuman/inference/local/service/assets_impl_01_part_02.rs@@ -0,0 +1,129 @@++impl LocalAiService {+ pub(in crate::openhuman::inference::local::service) async fn ensure_tts_asset_available(+ &self,+ config: &Config,+ ) -> Result<(), String> {+ if resolve_tts_voice_path(config).is_ok() {+ self.status.lock().tts_state = "ready".to_string();+ return Ok(());+ }++ let url = config+ .local_ai+ .tts_download_url+ .as_deref()+ .filter(|v| !v.trim().is_empty())+ .ok_or_else(|| {+ "TTS voice missing and no local_ai.tts_download_url configured".to_string()+ })?;+ let dest = tts_model_target_path(config);+ self.download_file_with_progress(url, &dest, "tts").await?;++ if let Some(config_url) = config+ .local_ai+ .tts_config_download_url+ .as_deref()+ .filter(|v| !v.trim().is_empty())+ {+ let config_dest = std::path::PathBuf::from(format!("{}.json", dest.display()));+ let _ = self+ .download_file_with_progress(config_url, &config_dest, "tts-config")+ .await;+ }++ self.status.lock().tts_state = "ready".to_string();+ Ok(())+ }++ async fn download_file_with_progress(+ &self,+ url: &str,+ dest: &Path,+ label: &str,+ ) -> Result<(), String> {+ if let Some(parent) = dest.parent() {+ tokio::fs::create_dir_all(parent)+ .await+ .map_err(|e| format!("failed to create destination directory: {e}"))?;+ }++ let response = self+ .http+ .get(url)+ // Large model assets (STT/TTS) can take minutes on slower links.+ // Avoid inheriting the short default client timeout for these streams.+ .timeout(std::time::Duration::from_secs(30 * 60))+ .send()+ .await+ .map_err(|e| format!("failed to start {label} download: {e}"))?;+ if !response.status().is_success() {+ return Err(format!(+ "failed to download {label} asset, status {}",+ response.status()+ ));+ }++ {+ let mut status = self.status.lock();+ status.state = "downloading".to_string();+ status.warning = Some(format!("Downloading {label} asset"));+ match label {+ "stt" => status.stt_state = "downloading".to_string(),+ "tts" | "tts-config" => status.tts_state = "downloading".to_string(),+ _ => {}+ }+ status.download_progress = Some(0.0);+ status.downloaded_bytes = Some(0);+ status.total_bytes = response.content_length();+ status.download_speed_bps = Some(0);+ status.eta_seconds = None;+ }++ let total = response.content_length();+ let mut downloaded: u64 = 0;+ let started_at = std::time::Instant::now();+ let mut file = tokio::fs::File::create(dest)+ .await+ .map_err(|e| format!("failed to create destination file: {e}"))?;+ let mut stream = response.bytes_stream();+ while let Some(chunk) = stream+ .try_next()+ .await+ .map_err(|e| format!("download stream error for {label}: {e}"))?+ {+ use tokio::io::AsyncWriteExt;+ file.write_all(&chunk)+ .await+ .map_err(|e| format!("failed writing {label} file: {e}"))?;+ downloaded = downloaded.saturating_add(chunk.len() as u64);+ let elapsed = started_at.elapsed().as_secs_f64().max(0.001);+ let speed_bps = (downloaded as f64 / elapsed).round().max(0.0) as u64;+ let eta_seconds = total.and_then(|t| {+ if downloaded >= t || speed_bps == 0 {+ None+ } else {+ Some((t.saturating_sub(downloaded)) / speed_bps.max(1))+ }+ });++ let mut status = self.status.lock();+ status.state = "downloading".to_string();+ status.warning = Some(format!("Downloading {label} asset"));+ match label {+ "stt" => status.stt_state = "downloading".to_string(),+ "tts" | "tts-config" => status.tts_state = "downloading".to_string(),+ _ => {}+ }+ status.downloaded_bytes = Some(downloaded);+ status.total_bytes = total;+ status.download_speed_bps = Some(speed_bps);+ status.eta_seconds = eta_seconds;+ status.download_progress = total+ .map(|t| (downloaded as f32 / t as f32).clamp(0.0, 1.0))+ .or(Some(0.0));+ }++ Ok(())+ }+}diff --git a/src/openhuman/security/credentials/profiles.rs b/src/openhuman/security/credentials/profiles.rsindex 0235fe4b5b..d01b1b9e97 100644--- a/src/openhuman/security/credentials/profiles.rs+++ b/src/openhuman/security/credentials/profiles.rs@@ -252,1278 +252,9 @@ pub struct AuthProfilesStore {#[cfg(test)]force_lock_unwritable: Arc<AtomicBool>,}--impl AuthProfilesStore {- pub fn new(state_dir: &Path, encrypt_secrets: bool) -> Self {- let user_id = user_id_from_state_dir(state_dir);- let policy = crate::openhuman::security::keyring_consent::policy::check_secret_access();- let use_keychain = policy- == crate::openhuman::security::keyring_consent::PolicyDecision::Proceed- && crate::openhuman::security::keyring::is_available();- log::debug!(- "[auth] AuthProfilesStore::new state_dir={} user_id={user_id} use_keychain={use_keychain} policy={policy:?}",- state_dir.display()- );- match policy {- crate::openhuman::security::keyring_consent::PolicyDecision::Proceed => {- if !use_keychain {- // OS keychain unavailable despite Proceed policy (probe failed).- log::info!(- "[auth] OS keychain unavailable — using encrypted JSON for auth profiles user_id={user_id}"- );- }- }- crate::openhuman::security::keyring_consent::PolicyDecision::ConsentRequired => {- log::warn!(- "[auth] keyring consent has not been given — secrets will NOT be persisted \- to the OS keychain until the user grants consent. \- Falling back to encrypted JSON for auth profiles user_id={user_id}"- );- }- crate::openhuman::security::keyring_consent::PolicyDecision::Declined => {- log::warn!(- "[auth] user explicitly declined OS keychain storage — \- using encrypted JSON for auth profiles user_id={user_id}"- );- }- }- Self {- path: state_dir.join(PROFILES_FILENAME),- lock_path: state_dir.join(LOCK_FILENAME),- secret_store: SecretStore::new(state_dir, encrypt_secrets),- user_id,- use_keychain,- #[cfg(test)]- force_transient_failures_write: Arc::new(AtomicUsize::new(0)),- #[cfg(test)]- force_transient_failures_rename: Arc::new(AtomicUsize::new(0)),- #[cfg(test)]- force_lock_unwritable: Arc::new(AtomicBool::new(false)),- }- }-- /// Build a keychain key for an auth profile's combined secret payload.- fn keychain_key_for_profile(&self, profile_id: &str) -> String {- format!("{KEYCHAIN_AUTH_PREFIX}{profile_id}")- }-- /// Store auth secrets for a profile in the OS keychain.- ///- /// The secrets are serialized as a compact JSON object so a single- /// keychain entry holds all token fields for the profile.- fn keychain_store_secrets(&self, profile: &AuthProfile) -> anyhow::Result<()> {- let key = self.keychain_key_for_profile(&profile.id);- let secrets = serde_json::json!({- "token": profile.token,- "access_token": profile.token_set.as_ref().map(|ts| &ts.access_token),- "refresh_token": profile.token_set.as_ref().and_then(|ts| ts.refresh_token.as_deref()),- "id_token": profile.token_set.as_ref().and_then(|ts| ts.id_token.as_deref()),- });- let payload = serde_json::to_string(&secrets)- .context("Failed to serialize auth secrets for keychain")?;- crate::openhuman::security::keyring::set(&self.user_id, &key, &payload).map_err(|e| {- anyhow::anyhow!(- "Keychain set failed for profile {}: {e} | detail={}",- profile.id,- e.diagnostic()- )- })?;- log::debug!(- "[auth] keychain_store_secrets stored profile_id={} user_id={}",- profile.id,- self.user_id- );- Ok(())- }-- /// Load auth secrets for a profile from the OS keychain.- ///- /// Returns `None` if no keychain entry exists for the profile.- fn keychain_load_secrets(&self, profile_id: &str) -> anyhow::Result<Option<KeychainSecrets>> {- let key = self.keychain_key_for_profile(profile_id);- let payload = match crate::openhuman::security::keyring::get(&self.user_id, &key) {- Ok(Some(p)) => p,- Ok(None) => {- log::debug!(- "[auth] keychain_load_secrets miss profile_id={profile_id} user_id={}",- self.user_id- );- return Ok(None);- }- Err(e) => {- log::warn!(- "[auth] keychain_load_secrets error profile_id={profile_id} user_id={}: {e} | detail={}",- self.user_id,- e.diagnostic()- );- return Ok(None);- }- };- let secrets: KeychainSecrets = serde_json::from_str(&payload).map_err(|e| {- anyhow::anyhow!("Keychain payload for profile {profile_id} is not valid JSON: {e}")- })?;- log::debug!(- "[auth] keychain_load_secrets hit profile_id={profile_id} user_id={}",- self.user_id- );- Ok(Some(secrets))- }-- /// Delete keychain secrets for a profile (called on profile removal).- fn keychain_delete_secrets(&self, profile_id: &str) {- let key = self.keychain_key_for_profile(profile_id);- if let Err(e) = crate::openhuman::security::keyring::delete(&self.user_id, &key) {- log::warn!(- "[auth] keychain_delete_secrets error profile_id={profile_id} user_id={}: {e} | detail={}",- self.user_id,- e.diagnostic()- );- } else {- log::debug!(- "[auth] keychain_delete_secrets ok profile_id={profile_id} user_id={}",- self.user_id- );- }- }-- pub fn path(&self) -> &Path {- &self.path- }-- pub fn load(&self) -> Result<AuthProfilesData> {- match self.acquire_lock() {- Ok(_lock) => self.load_locked(),- Err(e) if is_lock_create_unwritable_fs(&e) => {- // RCA Sentry TAURI-RUST-4SZ: a full / read-only filesystem- // can't create the exclusive lock file, but the store already- // exists and writers publish via atomic tmp+rename, so a- // lock-free read is still consistent. The read path is the- // hot caller here (`app_state_snapshot` polls it every tick),- // so failing it strands the UI AND floods Sentry once per- // poll. Degrade to a lock-free read-only load instead — the- // user keeps their session view, and because no error is- // produced the noise stops at the source rather than being- // suppressed downstream. Opportunistic migrations are skipped- // (they couldn't persist on a full disk anyway).- log::warn!(- "[auth] auth-profile lock could not be created ({e}); \- serving lock-free read-only load (likely disk full / read-only FS)"- );- self.load_unlocked_readonly()- }- Err(e) => Err(e),- }- }-- pub fn upsert_profile(&self, mut profile: AuthProfile, set_active: bool) -> Result<()> {- let _lock = self.acquire_lock()?;- let mut data = self.load_locked()?;-- profile.updated_at = Utc::now();- if let Some(existing) = data.profiles.get(&profile.id) {- profile.created_at = existing.created_at;- }-- if set_active {- data.active_profiles- .insert(profile.provider.clone(), profile.id.clone());- }-- data.profiles.insert(profile.id.clone(), profile);- data.updated_at = Utc::now();-- self.save_locked(&data)- }-- pub fn remove_profile(&self, profile_id: &str) -> Result<bool> {- let _lock = self.acquire_lock()?;- let mut data = self.load_locked()?;-- let removed = data.profiles.remove(profile_id).is_some();- if !removed {- return Ok(false);- }-- data.active_profiles- .retain(|_, active| active != profile_id);- data.updated_at = Utc::now();- self.save_locked(&data)?;-- // Clean up keychain entry for this profile (idempotent if keychain- // is unavailable or no entry exists).- if self.use_keychain {- self.keychain_delete_secrets(profile_id);- }-- Ok(true)- }-- pub fn set_active_profile(&self, provider: &str, profile_id: &str) -> Result<()> {- let _lock = self.acquire_lock()?;- let mut data = self.load_locked()?;-- if !data.profiles.contains_key(profile_id) {- anyhow::bail!("Auth profile not found: {profile_id}");- }-- data.active_profiles- .insert(provider.to_string(), profile_id.to_string());- data.updated_at = Utc::now();- self.save_locked(&data)- }-- pub fn clear_active_profile(&self, provider: &str) -> Result<()> {- let _lock = self.acquire_lock()?;- let mut data = self.load_locked()?;- data.active_profiles.remove(provider);- data.updated_at = Utc::now();- self.save_locked(&data)- }-- pub fn update_profile<F>(&self, profile_id: &str, mut updater: F) -> Result<AuthProfile>- where- F: FnMut(&mut AuthProfile) -> Result<()>,- {- let _lock = self.acquire_lock()?;- let mut data = self.load_locked()?;-- let profile = data- .profiles- .get_mut(profile_id)- .ok_or_else(|| anyhow::anyhow!("Auth profile not found: {profile_id}"))?;-- updater(profile)?;- profile.updated_at = Utc::now();- let updated_profile = profile.clone();- data.updated_at = Utc::now();- self.save_locked(&data)?;- Ok(updated_profile)- }-- fn load_locked(&self) -> Result<AuthProfilesData> {- self.load_resolved(true)- }-- /// Lock-free read-only load used as the [`AuthProfilesStore::load`]- /// fallback when the exclusive lock can't be created because the- /// filesystem won't accept the lock file (disk full / read-only mount —- /// Sentry TAURI-RUST-4SZ). Safe without the lock because writers publish- /// the store atomically (tmp + `fs::rename`), so a bare read always sees- /// a complete file. Skips the opportunistic migration / dropped-profile- /// rewrite that `load_locked` performs — that write needs both the lock- /// and a writable disk, and this path runs precisely when neither holds.- fn load_unlocked_readonly(&self) -> Result<AuthProfilesData> {- self.load_resolved(false)- }-- /// Shared read + in-memory resolution worker. Reads the persisted store,- /// resolves/migrates secrets and drops unrecoverable profiles in memory,- /// and — only when `persist` is true — writes back any resulting cleanup.- /// The returned `AuthProfilesData` reflects the in-memory cleanup either- /// way, so the lock-free read path (`persist = false`) still returns a- /// correct, fully-resolved view without touching disk.- fn load_resolved(&self, persist: bool) -> Result<AuthProfilesData> {- let mut persisted = self.read_persisted_locked()?;- // `migrated` tracks enc: → enc2: XOR-cipher upgrades (original behavior).- let mut migrated = false;- // `keychain_migrated` tracks enc2: → keychain promotions: when true the- // persisted JSON must be rewritten with secret fields cleared.- let mut keychain_migrated = false;- let mut dropped_ids: Vec<String> = Vec::new();-- let mut profiles = BTreeMap::new();- for (id, p) in &mut persisted.profiles {- // ── Step 1: Resolve secrets ───────────────────────────────────────- //- // Priority order:- // (a) OS keychain — preferred when available.- // (b) enc2:/enc: JSON fields — legacy; decrypt and optionally- // migrate to keychain on this read.- // (c) Plaintext JSON fields — oldest legacy path; pass through.- //- // A decrypt failure (wrong key / tampered data) drops the profile- // rather than poisoning every reader — the user falls back to a- // clean logged-out state and re-authenticates cleanly.-- let (access_token, refresh_token, id_token, token) = if self.use_keychain {- // ── (a) Keychain path ──────────────────────────────────────- match self.keychain_load_secrets(id) {- Ok(Some(secrets)) => {- // Keychain has the entry — use it directly. Clear the- // JSON secret fields so they're wiped on next save.- let had_enc_fields = p.access_token.is_some()- || p.refresh_token.is_some()- || p.id_token.is_some()- || p.token.is_some();- if had_enc_fields {- log::info!(- "[auth] load: clearing legacy enc fields for profile_id={id} (already in keychain)"- );- p.access_token = None;- p.refresh_token = None;- p.id_token = None;- p.token = None;- keychain_migrated = true;- }- (- secrets.access_token,- secrets.refresh_token,- secrets.id_token,- secrets.token,- )- }- Ok(None) => {- // ── (b) No keychain entry yet — decrypt JSON fields and migrate ──- let decrypted = (|| -> Result<_> {- let (access_token, access_mig) =- self.decrypt_optional(p.access_token.as_deref())?;- let (refresh_token, refresh_mig) =- self.decrypt_optional(p.refresh_token.as_deref())?;- let (id_token, id_mig) =- self.decrypt_optional(p.id_token.as_deref())?;- let (token, token_mig) = self.decrypt_optional(p.token.as_deref())?;- Ok((- access_token,- access_mig,- refresh_token,- refresh_mig,- id_token,- id_mig,- token,- token_mig,- ))- })();- let (at, at_mig, rt, rt_mig, it, it_mig, tok, tok_mig) = match decrypted {- Ok(v) => v,- Err(e) => {- log::warn!(- "[auth] dropping unrecoverable profile provider={}: {e}. \- Most likely cause: .secret_key was regenerated. \- Re-authenticate to restore the session.",- p.provider- );- dropped_ids.push(id.clone());- continue;- }- };- // Track XOR→enc2 cipher upgrades (existing behavior).- if at_mig.is_some() {- p.access_token = at_mig;- migrated = true;- }- if rt_mig.is_some() {- p.refresh_token = rt_mig;- migrated = true;- }- if it_mig.is_some() {- p.id_token = it_mig;- migrated = true;- }- if tok_mig.is_some() {- p.token = tok_mig;- migrated = true;- }-- // If any secrets were found in JSON, promote them to keychain- // and clear the JSON fields so the next write is clean.- let has_secrets =- at.is_some() || rt.is_some() || it.is_some() || tok.is_some();- if has_secrets {- log::info!(- "[auth] load: migrating enc fields to keychain profile_id={id} user_id={}",- self.user_id- );- let dummy_profile = AuthProfile {- id: id.clone(),- provider: p.provider.clone(),- profile_name: p.profile_name.clone(),- kind: parse_profile_kind(&p.kind).unwrap_or(AuthProfileKind::Token),- account_id: p.account_id.clone(),- workspace_id: p.workspace_id.clone(),- token_set: at.clone().map(|access| TokenSet {- access_token: access,- refresh_token: rt.clone(),- id_token: it.clone(),- expires_at: None,- token_type: None,- scope: None,- }),- token: tok.clone(),- metadata: Default::default(),- created_at: Utc::now(),- updated_at: Utc::now(),- };- if let Err(e) = self.keychain_store_secrets(&dummy_profile) {- // Non-fatal: keep the enc2: fields in JSON so the- // next load can try again.- log::warn!(- "[auth] load: keychain migration failed profile_id={id}: {e}; \- keeping enc fields in JSON"- );- } else {- // Wipe JSON secret fields now that keychain has them.- p.access_token = None;- p.refresh_token = None;- p.id_token = None;- p.token = None;- keychain_migrated = true;- }- }- (at, rt, it, tok)- }- Err(_e) => {- // Keychain I/O error — fall through to JSON decrypt path.- log::warn!(- "[auth] keychain error for profile_id={id}; falling back to JSON"- );- let decrypted = (|| -> Result<_> {- let (at, _) = self.decrypt_optional(p.access_token.as_deref())?;- let (rt, _) = self.decrypt_optional(p.refresh_token.as_deref())?;- let (it, _) = self.decrypt_optional(p.id_token.as_deref())?;- let (tok, _) = self.decrypt_optional(p.token.as_deref())?;- Ok((at, rt, it, tok))- })();- match decrypted {- Ok(v) => v,- Err(e) => {- log::warn!(- "[auth] dropping unrecoverable profile provider={}: {e}",- p.provider- );- dropped_ids.push(id.clone());- continue;- }- }- }- }- } else {- // ── (b/c) No keychain — use existing JSON decrypt path ────────- let decrypted = (|| -> Result<_> {- let (access_token, access_migrated) =- self.decrypt_optional(p.access_token.as_deref())?;- let (refresh_token, refresh_migrated) =- self.decrypt_optional(p.refresh_token.as_deref())?;- let (id_token, id_migrated) = self.decrypt_optional(p.id_token.as_deref())?;- let (token, token_migrated) = self.decrypt_optional(p.token.as_deref())?;- Ok((- access_token,- access_migrated,- refresh_token,- refresh_migrated,- id_token,- id_migrated,- token,- token_migrated,- ))- })();-- let (- access_token,- access_migrated,- refresh_token,- refresh_migrated,- id_token,- id_migrated,- token,- token_migrated,- ) = match decrypted {- Ok(v) => v,- Err(e) => {- log::warn!(- "[auth] dropping unrecoverable profile provider={}: {e}. \- Most likely cause: .secret_key was regenerated after this profile \- was stored. The store will be rewritten without this entry; \- re-authenticate to restore the session.",- p.provider- );- dropped_ids.push(id.clone());- continue;- }- };-- if let Some(value) = access_migrated {- p.access_token = Some(value);- migrated = true;- }- if let Some(value) = refresh_migrated {- p.refresh_token = Some(value);- migrated = true;- }- if let Some(value) = id_migrated {- p.id_token = Some(value);- migrated = true;- }- if let Some(value) = token_migrated {- p.token = Some(value);- migrated = true;- }- (access_token, refresh_token, id_token, token)- };-- let kind = match parse_profile_kind(&p.kind) {- Ok(k) => k,- Err(e) => {- // A single profile with an unrecognized `kind` (e.g. a legacy value- // like "OAuth" written before the kebab-case rename, or "api_key"- // written by an older code path) must not poison the whole store —- // otherwise every reader fails the entire load and the user is- // locked out of *all* their auth profiles. Drop just this entry,- // matching the decrypt-failure recovery pattern above; the next- // login re-encodes the kind correctly.- log::warn!(- "[auth] dropping profile with unrecognized kind={:?} provider={}: {e}. \- This usually means the profile was written by an older version of \- OpenHuman. Re-authenticate to restore the session.",- p.kind,- p.provider- );- dropped_ids.push(id.clone());- continue;- }- };- let token_set = match kind {- AuthProfileKind::OAuth => {- let access = match access_token {- Some(a) => a,- None => {- log::warn!(- "[auth] dropping OAuth profile with missing access_token: \- provider={}. Re-authenticate to restore.",- p.provider- );- dropped_ids.push(id.clone());- continue;- }- };- Some(TokenSet {- access_token: access,- refresh_token,- id_token,- expires_at: parse_optional_datetime(p.expires_at.as_deref())?,- token_type: p.token_type.clone(),- scope: p.scope.clone(),- })- }- AuthProfileKind::Token => None,- };-- profiles.insert(- id.clone(),- AuthProfile {- id: id.clone(),- provider: p.provider.clone(),- profile_name: p.profile_name.clone(),- kind,- account_id: p.account_id.clone(),- workspace_id: p.workspace_id.clone(),- token_set,- token,- metadata: p.metadata.clone(),- created_at: parse_datetime_with_fallback(&p.created_at),- updated_at: parse_datetime_with_fallback(&p.updated_at),- },- );- }-- // Purge dropped profiles from the on-disk persisted view AND- // any `active_profiles` pointers that referenced them, so the- // next read returns a clean "no active session" state.- if !dropped_ids.is_empty() {- // Always apply the cleanup to the in-memory view so the returned- // data is correct even on the lock-free read path; the on-disk- // rewrite below is what's gated by `persist`.- for id in &dropped_ids {- persisted.profiles.remove(id);- }- persisted- .active_profiles- .retain(|_, profile_id| !dropped_ids.contains(profile_id));- persisted.updated_at = Utc::now().to_rfc3339();- log::warn!(- "[auth] purged {} unrecoverable profile(s) from store at {} \- (provider list redacted to avoid leaking PII)",- dropped_ids.len(),- self.path.display(),- );- }- // Persist opportunistic cleanup / migrations only on the locked write- // path. The lock-free read-only fallback (`persist = false`, used when- // the disk can't accept the lock file) intentionally skips this — the- // write would fail on a full disk anyway, and the in-memory view above- // is already correct.- if persist && (!dropped_ids.is_empty() || migrated || keychain_migrated) {- self.write_persisted_locked(&persisted)?;- }-- Ok(AuthProfilesData {- schema_version: persisted.schema_version,- updated_at: parse_datetime_with_fallback(&persisted.updated_at),- active_profiles: persisted.active_profiles,- profiles,- })- }-- fn save_locked(&self, data: &AuthProfilesData) -> Result<()> {- let mut persisted = PersistedAuthProfiles {- schema_version: CURRENT_SCHEMA_VERSION,- updated_at: data.updated_at.to_rfc3339(),- active_profiles: data.active_profiles.clone(),- profiles: BTreeMap::new(),- };-- for (id, profile) in &data.profiles {- // When the OS keychain is available, store all secret fields there and- // leave them absent from the JSON file. This is the preferred path on- // macOS / Windows / Linux-with-Secret-Service.- //- // When the keychain is unavailable (Linux headless / CI), fall back to- // the existing ChaCha20-Poly1305 encrypted JSON fields.- let (access_token, refresh_token, id_token, token, expires_at, token_type, scope) =- if self.use_keychain {- // Store secrets in the OS keychain — JSON gets no secret fields.- if let Err(e) = self.keychain_store_secrets(profile) {- // Non-fatal: fall back to encrypted JSON so data is not lost.- log::warn!(- "[auth] save: keychain store failed for profile_id={id}: {e}; \- falling back to encrypted JSON"- );- self.encrypt_for_json(profile)?- } else {- log::debug!("[auth] save: secrets stored in keychain profile_id={id}");- let (expires_at, token_type, scope) = match &profile.token_set {- Some(ts) => (- ts.expires_at.as_ref().map(DateTime::to_rfc3339),- ts.token_type.clone(),- ts.scope.clone(),- ),- None => (None, None, None),- };- // Secret fields deliberately omitted from JSON.- (None, None, None, None, expires_at, token_type, scope)- }- } else {- // Headless / no keychain — encrypt and store in JSON.- self.encrypt_for_json(profile)?- };-- persisted.profiles.insert(- id.clone(),- PersistedAuthProfile {- provider: profile.provider.clone(),- profile_name: profile.profile_name.clone(),- kind: profile_kind_to_string(profile.kind).to_string(),- account_id: profile.account_id.clone(),- workspace_id: profile.workspace_id.clone(),- access_token,- refresh_token,- id_token,- token,- expires_at,- token_type,- scope,- metadata: profile.metadata.clone(),- created_at: profile.created_at.to_rfc3339(),- updated_at: profile.updated_at.to_rfc3339(),- },- );- }-- self.write_persisted_locked(&persisted)- }-- /// Encrypt a profile's secret fields for JSON storage (keychain-unavailable path).- fn encrypt_for_json(&self, profile: &AuthProfile) -> Result<EncryptedProfileFields> {- let (access_token, refresh_token, id_token, expires_at, token_type, scope) =- match (&profile.kind, &profile.token_set) {- (AuthProfileKind::OAuth, Some(token_set)) => (- self.encrypt_optional(Some(&token_set.access_token))?,- self.encrypt_optional(token_set.refresh_token.as_deref())?,- self.encrypt_optional(token_set.id_token.as_deref())?,- token_set.expires_at.as_ref().map(DateTime::to_rfc3339),- token_set.token_type.clone(),- token_set.scope.clone(),- ),- _ => (None, None, None, None, None, None),- };- let token = self.encrypt_optional(profile.token.as_deref())?;- Ok((- access_token,- refresh_token,- id_token,- token,- expires_at,- token_type,- scope,- ))- }-- fn read_persisted_locked(&self) -> Result<PersistedAuthProfiles> {- if !self.path.exists() {- return Ok(PersistedAuthProfiles::default());- }-- let bytes = fs::read(&self.path).with_context(|| {- format!(- "Failed to read auth profile store at {}",- self.path.display()- )- })?;-- if bytes.is_empty() {- return Ok(PersistedAuthProfiles::default());- }-- let mut persisted: PersistedAuthProfiles = match serde_json::from_slice(&bytes) {- Ok(p) => p,- Err(err) => {- let quarantined = quarantine_corrupt_store(&self.path)?;- let quarantined_file = quarantined- .file_name()- .and_then(|s| s.to_str())- .unwrap_or("auth-profiles.corrupt");- tracing::warn!(- path_file = PROFILES_FILENAME,- quarantined_file = quarantined_file,- error = %err,- "[credentials] auth profile store unparseable; quarantined and reset to empty"- );- return Ok(PersistedAuthProfiles::default());- }- };-- if persisted.schema_version == 0 {- persisted.schema_version = CURRENT_SCHEMA_VERSION;- }-- if persisted.schema_version > CURRENT_SCHEMA_VERSION {- anyhow::bail!(- "Unsupported auth profile schema version {} (max supported: {})",- persisted.schema_version,- CURRENT_SCHEMA_VERSION- );- }-- Ok(persisted)- }-- fn write_persisted_locked(&self, persisted: &PersistedAuthProfiles) -> Result<()> {- if let Some(parent) = self.path.parent() {- fs::create_dir_all(parent).with_context(|| {- format!(- "Failed to create auth profile directory at {}",- parent.display()- )- })?;- }-- let json =- serde_json::to_vec_pretty(persisted).context("Failed to serialize auth profiles")?;- let tmp_name = format!(- "{}.tmp.{}.{}",- PROFILES_FILENAME,- std::process::id(),- Utc::now().timestamp_nanos_opt().unwrap_or_default()- );- let tmp_path = self.path.with_file_name(tmp_name);-- // Windows AV / Search-Indexer / Defender may briefly hold a handle on- // the destination, returning transient `ERROR_SHARING_VIOLATION (32)`,- // `ERROR_ACCESS_DENIED (5)`, or `ERROR_DELETE_PENDING (303)` —- // recognised as retryable by `is_transient_fs_error`. Mirror the- // lock-create retry budget at the bottom of `acquire_lock` so the- // JSON write+rename path absorbs the same transient family that- // closed Sentry OPENHUMAN-TAURI-H1 / H8 for the lock path. Outer- // `with_context` preserved so the Sentry fingerprint shape is stable- // across releases. (Sentry TAURI-RUST-92J / #3355.)- retry_with_backoff(- "write auth profile tmp",- PERSIST_RETRY_ATTEMPTS,- PERSIST_RETRY_BASE_MS,- || {- self.consume_test_transient_failure_write()?;- fs::write(&tmp_path, &json).context("write auth profile tmp")- },- )- .with_context(|| {- format!(- "Failed to write temporary auth profile file at {}",- tmp_path.display()- )- })?;-- let rename_result = retry_with_backoff(- "replace auth profile store",- PERSIST_RETRY_ATTEMPTS,- PERSIST_RETRY_BASE_MS,- || {- self.consume_test_transient_failure_rename()?;- fs::rename(&tmp_path, &self.path).context("rename auth profile tmp -> store")- },- )- .with_context(|| {- format!(- "Failed to replace auth profile store at {}",- self.path.display()- )- });-- if rename_result.is_err() {- // Best-effort orphan cleanup: `tmp_path` is `…tmp.{pid}.{nanos}`- // — unique per call — so a permanently-failing rename otherwise- // leaks one tmp file per `app_state_snapshot` poll (~2s cadence)- // under sustained Windows AV / Search-Indexer holds. Cleaning- // here keeps the directory tidy; the cleanup itself can fail- // (the same AV that blocked the rename may block the unlink),- // which is why we deliberately drop the result.- let _ = fs::remove_file(&tmp_path);- }-- rename_result- }-- /// Consume one test-injected transient FS failure for the **write**- /// stage if any are queued. No-op in production builds.- #[cfg(test)]- fn consume_test_transient_failure_write(&self) -> Result<()> {- consume_one(&self.force_transient_failures_write)- }-- /// Consume one test-injected transient FS failure for the **rename**- /// stage if any are queued. No-op in production builds.- #[cfg(test)]- fn consume_test_transient_failure_rename(&self) -> Result<()> {- consume_one(&self.force_transient_failures_rename)- }-- #[cfg(not(test))]- #[inline(always)]- fn consume_test_transient_failure_write(&self) -> Result<()> {- Ok(())- }-- #[cfg(not(test))]- #[inline(always)]- fn consume_test_transient_failure_rename(&self) -> Result<()> {- Ok(())- }-- /// Queue `n` test-only forced transient FS failures for the write- /// stage. The next `n` calls inside the `fs::write(tmp)` retry loop- /// return a `__TEST_TRANSIENT__` error before the underlying FS op- /// runs; the retry helper treats them as retryable.- #[cfg(test)]- pub(super) fn force_next_write_failures(&self, n: usize) {- self.force_transient_failures_write- .store(n, Ordering::SeqCst);- }-- /// Queue `n` test-only forced transient FS failures for the rename- /// stage. Separate from the write counter so tests can exercise the- /// rename retry loop in isolation (PR #3364 review feedback).- #[cfg(test)]- pub(super) fn force_next_rename_failures(&self, n: usize) {- self.force_transient_failures_rename- .store(n, Ordering::SeqCst);- }-- /// Test introspection: how many forced write-stage failures are still- /// queued.- #[cfg(test)]- pub(super) fn remaining_forced_write_failures(&self) -> usize {- self.force_transient_failures_write.load(Ordering::SeqCst)- }-- /// Test introspection: how many forced rename-stage failures are still- /// queued.- #[cfg(test)]- pub(super) fn remaining_forced_rename_failures(&self) -> usize {- self.force_transient_failures_rename.load(Ordering::SeqCst)- }-- /// Queue a single test-only forced `StorageFull` lock-create failure. The- /// next `acquire_lock` returns the synthetic disk-full error so tests can- /// drive the lock-free read-only fallback in [`AuthProfilesStore::load`].- #[cfg(test)]- pub(super) fn force_next_lock_unwritable(&self) {- self.force_lock_unwritable.store(true, Ordering::SeqCst);- }-- fn encrypt_optional(&self, value: Option<&str>) -> Result<Option<String>> {- match value {- Some(value) if !value.is_empty() => self.secret_store.encrypt(value).map(Some),- Some(_) | None => Ok(None),- }- }-- fn decrypt_optional(&self, value: Option<&str>) -> Result<(Option<String>, Option<String>)> {- match value {- Some(value) if !value.is_empty() => {- let (plaintext, migrated) = self.secret_store.decrypt_and_migrate(value)?;- Ok((Some(plaintext), migrated))- }- Some(_) | None => Ok((None, None)),- }- }-- fn acquire_lock(&self) -> Result<AuthProfileLockGuard> {- // Test-only: simulate a full / read-only filesystem that can't create- // the lock file, to drive the read-only fallback in `load`.- #[cfg(test)]- if self.force_lock_unwritable.swap(false, Ordering::SeqCst) {- let io = std::io::Error::from(std::io::ErrorKind::StorageFull);- return Err(annotate_lock_create_failure(- anyhow::Error::new(io).context("open lock file"),- ));- }-- if let Some(parent) = self.lock_path.parent() {- fs::create_dir_all(parent)- .with_context(|| "Failed to create auth profile lock directory".to_string())?;- }-- // Drive timeout + stale-recheck off wall-clock elapsed time, not the- // sum of explicit `thread::sleep(LOCK_WAIT_MS)` calls. The earlier- // counter-based approach excluded time spent inside- // `retry_with_backoff` (which can sleep up to ~30s on its own- // schedule before returning AlreadyExists) and the lock-file I/O- // syscalls. Under Windows AV contention that drift could push- // both `LOCK_TIMEOUT_MS` and `next_stale_recheck_ms` significantly- // later than intended.- let started_at = Instant::now();-- // Serialize same-process acquirers on an in-memory lock keyed by this- // path before we ever touch the on-disk lock file. Two things depend on- // holding it: (1) concurrent `app_state_snapshot` calls in this process- // queue here instead of racing `create_new`/`Drop` on the file, and- // (2) it lets us treat an on-disk lock recording our own pid as a leaked- // `Drop` unlink and reclaim it immediately — no other thread in this- // process can hold a live guard while we own this in-memory lock (see- // `reclaim_self_owned_lock`). Held for the lifetime of the returned- // guard.- //- // Use `try_lock` against the *same* `LOCK_TIMEOUT_MS` budget as the- // on-disk wait rather than a blocking `lock()`: a wedged in-process- // holder must not be able to strand an RPC/blocking worker past the- // timeout the caller (e.g. `app_state_snapshot`) expects. Poison is- // recoverable — the `()` payload carries no invariant.- let in_process_lock = in_process_lock_for(&self.lock_path);- let in_process_guard = loop {- match in_process_lock.try_lock() {- Ok(guard) => break guard,- Err(TryLockError::Poisoned(poisoned)) => break poisoned.into_inner(),- Err(TryLockError::WouldBlock) => {- if started_at.elapsed().as_millis() as u64 >= LOCK_TIMEOUT_MS {- anyhow::bail!("Timed out waiting for auth profile lock");- }- thread::sleep(Duration::from_millis(LOCK_WAIT_MS));- }- }- };-- let mut cleared_stale = false;- // Periodically re-probe for stale locks during the busy-wait. A- // lock that started fresh (live pid, recent mtime) can age past- // STALE_LOCK_AGE_MS while we wait, and we want to recover from- // that without bailing at the LOCK_TIMEOUT_MS boundary.- let mut next_stale_recheck_ms: u64 = 1_000;- loop {- let open_result = crate::openhuman::util::retry_with_backoff(- "create auth profile lock",- 6,- 100,- || {- OpenOptions::new()- .create_new(true)- .write(true)- .open(&self.lock_path)- .context("open lock file")- },- );-- match open_result {- Ok(mut file) => {- // Issue #1612 — writing the pid line is what later lets- // a future acquirer recognise a crashed owner; if the- // write fails we must NOT report the lock as held with- // a malformed/empty file behind us, or stale recovery- // would silently degrade to the full 10s timeout for- // every subsequent acquire.- if let Err(e) = writeln!(file, "pid={}", std::process::id()) {- let _ = fs::remove_file(&self.lock_path);- return Err(e).with_context(|| {- "Failed to write auth profile lock owner".to_string()- });- }- return Ok(AuthProfileLockGuard {- lock_path: self.lock_path.clone(),- _in_process: in_process_guard,- });- }- Err(e) => {- let is_already_exists = e- .chain()- .find_map(|e| e.downcast_ref::<std::io::Error>())- .is_some_and(|ioe| ioe.kind() == std::io::ErrorKind::AlreadyExists);-- if is_already_exists {- // A lock file recording our own pid can only be a- // leaked `Drop` unlink: we hold the in-process lock, so- // no live same-process guard exists. Reclaim it- // immediately rather than spinning the 30s age floor- // (`STALE_LOCK_AGE_MS`) that sits *behind* the ~10s RPC- // timeout — that gap is what produced the sustained- // "Timed out waiting for auth profile lock" retry storm- // (Sentry TAURI-RUST-B1 / #2318). Cheap enough (one tiny- // read) to re-probe every spin, which also self-heals a- // lock our own `Drop` leaks mid-wait.- if self.reclaim_self_owned_lock() {- continue;- }- // Issue #1612 — a previous openhuman crash can leave a- // stale auth-profiles.lock behind (a *different*, now-dead- // pid, or an aged leak), after which every RPC path that- // touches the auth profile store fails for the- // `LOCK_TIMEOUT_MS` window and the user gets stuck in a- // retry storm. Before falling back to the busy-wait, try- // once to peek at the writer's recorded PID and remove- // the lock if that process is no longer alive. Flag is- // flipped on the first probe (not only on success) so a- // live-pid / malformed / unreadable lock doesn't trigger- // a fresh sysinfo probe + log line on every busy-wait- // iteration.- if !cleared_stale {- cleared_stale = true;- if self.clear_lock_if_stale() {- continue;- }- } else {- let elapsed_ms = started_at.elapsed().as_millis() as u64;- if elapsed_ms >= next_stale_recheck_ms {- // The age-based reclaim check is cheap (one- // `fs::metadata` call in the common case) and- // safely no-ops on fresh, legitimate locks.- // Re-probing periodically lets us recover from- // a leaked-mid-wait lock without bailing at- // the 10s timeout.- next_stale_recheck_ms = next_stale_recheck_ms.saturating_add(1_000);- if self.clear_lock_if_stale() {- continue;- }- }- }- if started_at.elapsed().as_millis() as u64 >= LOCK_TIMEOUT_MS {- anyhow::bail!("Timed out waiting for auth profile lock");- }- thread::sleep(Duration::from_millis(LOCK_WAIT_MS));- } else {- // Sentry OPENHUMAN-TAURI-H8 collapses every- // non-AlreadyExists, non-transient `create_new`- // failure into a single fingerprint with no- // breadcrumb of which OS code actually fired.- // `annotate_lock_create_failure` embeds the- // underlying `io::ErrorKind` + `raw_os_error()` so- // future events split by root cause and we can- // widen `is_transient_fs_error` (or fix the- // underlying condition) for whichever code is hot.- return Err(annotate_lock_create_failure(e));- }- }- }- }- }-- /// Returns `true` if an existing lock file was detected as stale and- /// successfully removed. Two cases reclaim:- ///- /// 1. The recorded `pid=` line points at a process that is no longer- /// running — classic crashed-owner recovery (Issue #1612).- /// 2. The lock file's mtime is older than [`STALE_LOCK_AGE_MS`]. This- /// catches a *different* still-alive process that leaked its lock (its- /// `AuthProfileLockGuard::drop` could not unlink the file — e.g. Windows- /// AV / indexer briefly held a handle — and orphaned it with that live- /// pid inside). No legitimate auth-profile op holds the lock long enough- /// to be affected, so a too-old lock is unambiguously a leak. A lock- /// leaked by *this* process is handled far sooner — immediately, without- /// the age floor — by [`reclaim_self_owned_lock`](Self::reclaim_self_owned_lock),- /// which is sound because acquirers serialize on the in-process lock.- ///- /// 3. The lock file has no parseable `pid=` line and is older than- /// [`MALFORMED_LOCK_GRACE_MS`]. A healthy holder writes its pid within- /// microseconds of `create_new`, so a pidless lock past that short- /// grace is an abandoned in-flight writer (crashed/killed between- /// `create_new` and the `pid=` write) — reclaim it rather than make- /// every reader spin the full [`STALE_LOCK_AGE_MS`]/`LOCK_TIMEOUT_MS`- /// window (the ~30s "stuck on Initializing OpenHuman" after a- /// kill+reopen). The grace is short but non-zero so we never reclaim a- /// live writer that is mid-`create_new`/`pid=`.- fn clear_lock_if_stale(&self) -> bool {- let metadata = match fs::metadata(&self.lock_path) {- Ok(m) => m,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return false,- Err(e) => {- tracing::warn!(- target: "auth-profiles",- "[credentials] failed to stat lock file at {} for stale check: {e}",- self.lock_path.display()- );- return false;- }- };-- let age = metadata- .modified()- .ok()- .and_then(|mtime| std::time::SystemTime::now().duration_since(mtime).ok());- let too_old = age.is_some_and(|a| a >= Duration::from_millis(STALE_LOCK_AGE_MS));- // A pidless lock needs only a short grace: no healthy holder leaves the- // file without a `pid=` line for more than the microsecond gap between- // `create_new` and the write, so anything older is abandoned. If mtime- // is unreadable (clock skew, platform limitation) default to stale —- // no legitimate in-flight writer would be undetectable for that long.- let malformed_too_old =- age.is_none_or(|a| a >= Duration::from_millis(MALFORMED_LOCK_GRACE_MS));-- let content = match fs::read_to_string(&self.lock_path) {- Ok(s) => s,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return false,- Err(e) => {- tracing::warn!(- target: "auth-profiles",- "[credentials] failed to read lock file at {} for stale check: {e}",- self.lock_path.display()- );- return false;- }- };-- let pid = content- .lines()- .find_map(|line| line.trim().strip_prefix("pid=")?.trim().parse::<u32>().ok());-- let reclaim_reason: Option<String> = match pid {- Some(pid) if !is_pid_alive(pid) => Some(format!("pid {pid} not alive")),- Some(pid) if too_old => Some(format!(- "lock file older than {STALE_LOCK_AGE_MS}ms (recorded pid {pid}, presumed leaked)"- )),- None if malformed_too_old => Some(format!(- "no parseable pid and older than {MALFORMED_LOCK_GRACE_MS}ms \- (abandoned in-flight lock, reclaiming)"- )),- Some(_) => return false,- None => {- tracing::warn!(- target: "auth-profiles",- "[credentials] lock at {} has no parseable pid line and is younger than \- {MALFORMED_LOCK_GRACE_MS}ms; leaving in place briefly",- self.lock_path.display()- );- return false;- }- };-- let Some(reason) = reclaim_reason else {- return false;- };-- match fs::remove_file(&self.lock_path) {- Ok(()) => {- tracing::info!(- target: "auth-profiles",- "[credentials] removed stale auth profile lock at {} ({reason})",- self.lock_path.display()- );- true- }- Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,- Err(e) => {- tracing::warn!(- target: "auth-profiles",- "[credentials] failed to remove stale lock at {} ({reason}): {e}",- self.lock_path.display()- );- false- }- }- }-- /// Remove the on-disk lock file **iff** it records this process's own pid.- /// Returns `true` when a self-owned lock was found and removed.- ///- /// MUST only be called while holding this path's in-process lock (acquired- /// at the top of [`acquire_lock`](Self::acquire_lock) via- /// [`in_process_lock_for`]). That invariant is what makes the removal safe:- /// same-process acquirers serialize on the in-process lock, so no other- /// thread in this process can be holding a live `AuthProfileLockGuard` while- /// we run. A lock file carrying our own pid is therefore necessarily a leak- /// — a previous guard's `Drop` could not unlink it (on Windows, AV / the- /// Search indexer briefly hold a handle on the just-written file) and- /// orphaned it with our still-alive pid inside.- ///- /// This is the fast self-heal for Sentry TAURI-RUST-B1 (#2318): without it- /// the only recovery for a leaked-but-live-pid lock is the age branch in- /// [`clear_lock_if_stale`](Self::clear_lock_if_stale), whose- /// [`STALE_LOCK_AGE_MS`] floor (30s) is far longer than the ~10s RPC- /// timeout, so every `app_state_snapshot` timed out and retry-stormed for- /// the whole 30s window before age-reclaim kicked in.- fn reclaim_self_owned_lock(&self) -> bool {- let me = std::process::id();- tracing::trace!(- target: "auth-profiles",- "[credentials] probing for self-owned leaked lock at {} (our pid {me})",- self.lock_path.display()- );- let content = match fs::read_to_string(&self.lock_path) {- Ok(s) => s,- // NotFound: already gone (raced with another reclaim / the guard's- // own Drop). Any other read error: fall back to the age-based and- // busy-wait paths rather than guess at ownership.- Err(e) => {- tracing::debug!(- target: "auth-profiles",- "[credentials] self-owned probe could not read lock at {} ({e}); \- deferring to stale/busy-wait recovery",- self.lock_path.display()- );- return false;- }- };-- let pid = content- .lines()- .find_map(|line| line.trim().strip_prefix("pid=")?.trim().parse::<u32>().ok());- if pid != Some(me) {- tracing::trace!(- target: "auth-profiles",- "[credentials] lock at {} is not self-owned (recorded {pid:?}, our pid {me}); \- deferring to stale/busy-wait recovery",- self.lock_path.display()- );- return false;- }-- match fs::remove_file(&self.lock_path) {- Ok(()) => {- tracing::info!(- target: "auth-profiles",- "[credentials] reclaimed leaked self-owned auth profile lock at {} \- (recorded our own live pid {me}; a prior guard's Drop unlink was blocked, \- most likely by Windows AV/indexer)",- self.lock_path.display()- );- true- }- Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,- Err(e) => {- tracing::warn!(- target: "auth-profiles",- "[credentials] failed to reclaim self-owned auth profile lock at {}: {e}",- self.lock_path.display()- );- false- }- }- }-}+include!("profiles_impl_01_part_01.rs");+include!("profiles_impl_01_part_02.rs");+include!("profiles_impl_01_part_03.rs");/// Cross-platform best-effort check that a given OS process id is currently/// running. Used by [`AuthProfilesStore::clear_lock_if_stale`] to decidediff --git a/src/openhuman/security/credentials/profiles_impl_01_part_01.rs b/src/openhuman/security/credentials/profiles_impl_01_part_01.rsnew file mode 100644index 0000000000..661650b7f0--- /dev/null+++ b/src/openhuman/security/credentials/profiles_impl_01_part_01.rs@@ -0,0 +1,612 @@++impl AuthProfilesStore {++ pub fn new(state_dir: &Path, encrypt_secrets: bool) -> Self {+ let user_id = user_id_from_state_dir(state_dir);+ let policy = crate::openhuman::security::keyring_consent::policy::check_secret_access();+ let use_keychain = policy+ == crate::openhuman::security::keyring_consent::PolicyDecision::Proceed+ && crate::openhuman::security::keyring::is_available();+ log::debug!(+ "[auth] AuthProfilesStore::new state_dir={} user_id={user_id} use_keychain={use_keychain} policy={policy:?}",+ state_dir.display()+ );+ match policy {+ crate::openhuman::security::keyring_consent::PolicyDecision::Proceed => {+ if !use_keychain {+ // OS keychain unavailable despite Proceed policy (probe failed).+ log::info!(+ "[auth] OS keychain unavailable — using encrypted JSON for auth profiles user_id={user_id}"+ );+ }+ }+ crate::openhuman::security::keyring_consent::PolicyDecision::ConsentRequired => {+ log::warn!(+ "[auth] keyring consent has not been given — secrets will NOT be persisted \+ to the OS keychain until the user grants consent. \+ Falling back to encrypted JSON for auth profiles user_id={user_id}"+ );+ }+ crate::openhuman::security::keyring_consent::PolicyDecision::Declined => {+ log::warn!(+ "[auth] user explicitly declined OS keychain storage — \+ using encrypted JSON for auth profiles user_id={user_id}"+ );+ }+ }+ Self {+ path: state_dir.join(PROFILES_FILENAME),+ lock_path: state_dir.join(LOCK_FILENAME),+ secret_store: SecretStore::new(state_dir, encrypt_secrets),+ user_id,+ use_keychain,+ #[cfg(test)]+ force_transient_failures_write: Arc::new(AtomicUsize::new(0)),+ #[cfg(test)]+ force_transient_failures_rename: Arc::new(AtomicUsize::new(0)),+ #[cfg(test)]+ force_lock_unwritable: Arc::new(AtomicBool::new(false)),+ }+ }++ /// Build a keychain key for an auth profile's combined secret payload.+ fn keychain_key_for_profile(&self, profile_id: &str) -> String {+ format!("{KEYCHAIN_AUTH_PREFIX}{profile_id}")+ }++ /// Store auth secrets for a profile in the OS keychain.+ ///+ /// The secrets are serialized as a compact JSON object so a single+ /// keychain entry holds all token fields for the profile.+ fn keychain_store_secrets(&self, profile: &AuthProfile) -> anyhow::Result<()> {+ let key = self.keychain_key_for_profile(&profile.id);+ let secrets = serde_json::json!({+ "token": profile.token,+ "access_token": profile.token_set.as_ref().map(|ts| &ts.access_token),+ "refresh_token": profile.token_set.as_ref().and_then(|ts| ts.refresh_token.as_deref()),+ "id_token": profile.token_set.as_ref().and_then(|ts| ts.id_token.as_deref()),+ });+ let payload = serde_json::to_string(&secrets)+ .context("Failed to serialize auth secrets for keychain")?;+ crate::openhuman::security::keyring::set(&self.user_id, &key, &payload).map_err(|e| {+ anyhow::anyhow!(+ "Keychain set failed for profile {}: {e} | detail={}",+ profile.id,+ e.diagnostic()+ )+ })?;+ log::debug!(+ "[auth] keychain_store_secrets stored profile_id={} user_id={}",+ profile.id,+ self.user_id+ );+ Ok(())+ }++ /// Load auth secrets for a profile from the OS keychain.+ ///+ /// Returns `None` if no keychain entry exists for the profile.+ fn keychain_load_secrets(&self, profile_id: &str) -> anyhow::Result<Option<KeychainSecrets>> {+ let key = self.keychain_key_for_profile(profile_id);+ let payload = match crate::openhuman::security::keyring::get(&self.user_id, &key) {+ Ok(Some(p)) => p,+ Ok(None) => {+ log::debug!(+ "[auth] keychain_load_secrets miss profile_id={profile_id} user_id={}",+ self.user_id+ );+ return Ok(None);+ }+ Err(e) => {+ log::warn!(+ "[auth] keychain_load_secrets error profile_id={profile_id} user_id={}: {e} | detail={}",+ self.user_id,+ e.diagnostic()+ );+ return Ok(None);+ }+ };+ let secrets: KeychainSecrets = serde_json::from_str(&payload).map_err(|e| {+ anyhow::anyhow!("Keychain payload for profile {profile_id} is not valid JSON: {e}")+ })?;+ log::debug!(+ "[auth] keychain_load_secrets hit profile_id={profile_id} user_id={}",+ self.user_id+ );+ Ok(Some(secrets))+ }++ /// Delete keychain secrets for a profile (called on profile removal).+ fn keychain_delete_secrets(&self, profile_id: &str) {+ let key = self.keychain_key_for_profile(profile_id);+ if let Err(e) = crate::openhuman::security::keyring::delete(&self.user_id, &key) {+ log::warn!(+ "[auth] keychain_delete_secrets error profile_id={profile_id} user_id={}: {e} | detail={}",+ self.user_id,+ e.diagnostic()+ );+ } else {+ log::debug!(+ "[auth] keychain_delete_secrets ok profile_id={profile_id} user_id={}",+ self.user_id+ );+ }+ }++ pub fn path(&self) -> &Path {+ &self.path+ }++ pub fn load(&self) -> Result<AuthProfilesData> {+ match self.acquire_lock() {+ Ok(_lock) => self.load_locked(),+ Err(e) if is_lock_create_unwritable_fs(&e) => {+ // RCA Sentry TAURI-RUST-4SZ: a full / read-only filesystem+ // can't create the exclusive lock file, but the store already+ // exists and writers publish via atomic tmp+rename, so a+ // lock-free read is still consistent. The read path is the+ // hot caller here (`app_state_snapshot` polls it every tick),+ // so failing it strands the UI AND floods Sentry once per+ // poll. Degrade to a lock-free read-only load instead — the+ // user keeps their session view, and because no error is+ // produced the noise stops at the source rather than being+ // suppressed downstream. Opportunistic migrations are skipped+ // (they couldn't persist on a full disk anyway).+ log::warn!(+ "[auth] auth-profile lock could not be created ({e}); \+ serving lock-free read-only load (likely disk full / read-only FS)"+ );+ self.load_unlocked_readonly()+ }+ Err(e) => Err(e),+ }+ }++ pub fn upsert_profile(&self, mut profile: AuthProfile, set_active: bool) -> Result<()> {+ let _lock = self.acquire_lock()?;+ let mut data = self.load_locked()?;++ profile.updated_at = Utc::now();+ if let Some(existing) = data.profiles.get(&profile.id) {+ profile.created_at = existing.created_at;+ }++ if set_active {+ data.active_profiles+ .insert(profile.provider.clone(), profile.id.clone());+ }++ data.profiles.insert(profile.id.clone(), profile);+ data.updated_at = Utc::now();++ self.save_locked(&data)+ }++ pub fn remove_profile(&self, profile_id: &str) -> Result<bool> {+ let _lock = self.acquire_lock()?;+ let mut data = self.load_locked()?;++ let removed = data.profiles.remove(profile_id).is_some();+ if !removed {+ return Ok(false);+ }++ data.active_profiles+ .retain(|_, active| active != profile_id);+ data.updated_at = Utc::now();+ self.save_locked(&data)?;++ // Clean up keychain entry for this profile (idempotent if keychain+ // is unavailable or no entry exists).+ if self.use_keychain {+ self.keychain_delete_secrets(profile_id);+ }++ Ok(true)+ }++ pub fn set_active_profile(&self, provider: &str, profile_id: &str) -> Result<()> {+ let _lock = self.acquire_lock()?;+ let mut data = self.load_locked()?;++ if !data.profiles.contains_key(profile_id) {+ anyhow::bail!("Auth profile not found: {profile_id}");+ }++ data.active_profiles+ .insert(provider.to_string(), profile_id.to_string());+ data.updated_at = Utc::now();+ self.save_locked(&data)+ }++ pub fn clear_active_profile(&self, provider: &str) -> Result<()> {+ let _lock = self.acquire_lock()?;+ let mut data = self.load_locked()?;+ data.active_profiles.remove(provider);+ data.updated_at = Utc::now();+ self.save_locked(&data)+ }++ pub fn update_profile<F>(&self, profile_id: &str, mut updater: F) -> Result<AuthProfile>+ where+ F: FnMut(&mut AuthProfile) -> Result<()>,+ {+ let _lock = self.acquire_lock()?;+ let mut data = self.load_locked()?;++ let profile = data+ .profiles+ .get_mut(profile_id)+ .ok_or_else(|| anyhow::anyhow!("Auth profile not found: {profile_id}"))?;++ updater(profile)?;+ profile.updated_at = Utc::now();+ let updated_profile = profile.clone();+ data.updated_at = Utc::now();+ self.save_locked(&data)?;+ Ok(updated_profile)+ }++ fn load_locked(&self) -> Result<AuthProfilesData> {+ self.load_resolved(true)+ }++ /// Lock-free read-only load used as the [`AuthProfilesStore::load`]+ /// fallback when the exclusive lock can't be created because the+ /// filesystem won't accept the lock file (disk full / read-only mount —+ /// Sentry TAURI-RUST-4SZ). Safe without the lock because writers publish+ /// the store atomically (tmp + `fs::rename`), so a bare read always sees+ /// a complete file. Skips the opportunistic migration / dropped-profile+ /// rewrite that `load_locked` performs — that write needs both the lock+ /// and a writable disk, and this path runs precisely when neither holds.+ fn load_unlocked_readonly(&self) -> Result<AuthProfilesData> {+ self.load_resolved(false)+ }++ /// Shared read + in-memory resolution worker. Reads the persisted store,+ /// resolves/migrates secrets and drops unrecoverable profiles in memory,+ /// and — only when `persist` is true — writes back any resulting cleanup.+ /// The returned `AuthProfilesData` reflects the in-memory cleanup either+ /// way, so the lock-free read path (`persist = false`) still returns a+ /// correct, fully-resolved view without touching disk.+ fn load_resolved(&self, persist: bool) -> Result<AuthProfilesData> {+ let mut persisted = self.read_persisted_locked()?;+ // `migrated` tracks enc: → enc2: XOR-cipher upgrades (original behavior).+ let mut migrated = false;+ // `keychain_migrated` tracks enc2: → keychain promotions: when true the+ // persisted JSON must be rewritten with secret fields cleared.+ let mut keychain_migrated = false;+ let mut dropped_ids: Vec<String> = Vec::new();++ let mut profiles = BTreeMap::new();+ for (id, p) in &mut persisted.profiles {+ // ── Step 1: Resolve secrets ───────────────────────────────────────+ //+ // Priority order:+ // (a) OS keychain — preferred when available.+ // (b) enc2:/enc: JSON fields — legacy; decrypt and optionally+ // migrate to keychain on this read.+ // (c) Plaintext JSON fields — oldest legacy path; pass through.+ //+ // A decrypt failure (wrong key / tampered data) drops the profile+ // rather than poisoning every reader — the user falls back to a+ // clean logged-out state and re-authenticates cleanly.++ let (access_token, refresh_token, id_token, token) = if self.use_keychain {+ // ── (a) Keychain path ──────────────────────────────────────+ match self.keychain_load_secrets(id) {+ Ok(Some(secrets)) => {+ // Keychain has the entry — use it directly. Clear the+ // JSON secret fields so they're wiped on next save.+ let had_enc_fields = p.access_token.is_some()+ || p.refresh_token.is_some()+ || p.id_token.is_some()+ || p.token.is_some();+ if had_enc_fields {+ log::info!(+ "[auth] load: clearing legacy enc fields for profile_id={id} (already in keychain)"+ );+ p.access_token = None;+ p.refresh_token = None;+ p.id_token = None;+ p.token = None;+ keychain_migrated = true;+ }+ (+ secrets.access_token,+ secrets.refresh_token,+ secrets.id_token,+ secrets.token,+ )+ }+ Ok(None) => {+ // ── (b) No keychain entry yet — decrypt JSON fields and migrate ──+ let decrypted = (|| -> Result<_> {+ let (access_token, access_mig) =+ self.decrypt_optional(p.access_token.as_deref())?;+ let (refresh_token, refresh_mig) =+ self.decrypt_optional(p.refresh_token.as_deref())?;+ let (id_token, id_mig) =+ self.decrypt_optional(p.id_token.as_deref())?;+ let (token, token_mig) = self.decrypt_optional(p.token.as_deref())?;+ Ok((+ access_token,+ access_mig,+ refresh_token,+ refresh_mig,+ id_token,+ id_mig,+ token,+ token_mig,+ ))+ })();+ let (at, at_mig, rt, rt_mig, it, it_mig, tok, tok_mig) = match decrypted {+ Ok(v) => v,+ Err(e) => {+ log::warn!(+ "[auth] dropping unrecoverable profile provider={}: {e}. \+ Most likely cause: .secret_key was regenerated. \+ Re-authenticate to restore the session.",+ p.provider+ );+ dropped_ids.push(id.clone());+ continue;+ }+ };+ // Track XOR→enc2 cipher upgrades (existing behavior).+ if at_mig.is_some() {+ p.access_token = at_mig;+ migrated = true;+ }+ if rt_mig.is_some() {+ p.refresh_token = rt_mig;+ migrated = true;+ }+ if it_mig.is_some() {+ p.id_token = it_mig;+ migrated = true;+ }+ if tok_mig.is_some() {+ p.token = tok_mig;+ migrated = true;+ }++ // If any secrets were found in JSON, promote them to keychain+ // and clear the JSON fields so the next write is clean.+ let has_secrets =+ at.is_some() || rt.is_some() || it.is_some() || tok.is_some();+ if has_secrets {+ log::info!(+ "[auth] load: migrating enc fields to keychain profile_id={id} user_id={}",+ self.user_id+ );+ let dummy_profile = AuthProfile {+ id: id.clone(),+ provider: p.provider.clone(),+ profile_name: p.profile_name.clone(),+ kind: parse_profile_kind(&p.kind).unwrap_or(AuthProfileKind::Token),+ account_id: p.account_id.clone(),+ workspace_id: p.workspace_id.clone(),+ token_set: at.clone().map(|access| TokenSet {+ access_token: access,+ refresh_token: rt.clone(),+ id_token: it.clone(),+ expires_at: None,+ token_type: None,+ scope: None,+ }),+ token: tok.clone(),+ metadata: Default::default(),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ };+ if let Err(e) = self.keychain_store_secrets(&dummy_profile) {+ // Non-fatal: keep the enc2: fields in JSON so the+ // next load can try again.+ log::warn!(+ "[auth] load: keychain migration failed profile_id={id}: {e}; \+ keeping enc fields in JSON"+ );+ } else {+ // Wipe JSON secret fields now that keychain has them.+ p.access_token = None;+ p.refresh_token = None;+ p.id_token = None;+ p.token = None;+ keychain_migrated = true;+ }+ }+ (at, rt, it, tok)+ }+ Err(_e) => {+ // Keychain I/O error — fall through to JSON decrypt path.+ log::warn!(+ "[auth] keychain error for profile_id={id}; falling back to JSON"+ );+ let decrypted = (|| -> Result<_> {+ let (at, _) = self.decrypt_optional(p.access_token.as_deref())?;+ let (rt, _) = self.decrypt_optional(p.refresh_token.as_deref())?;+ let (it, _) = self.decrypt_optional(p.id_token.as_deref())?;+ let (tok, _) = self.decrypt_optional(p.token.as_deref())?;+ Ok((at, rt, it, tok))+ })();+ match decrypted {+ Ok(v) => v,+ Err(e) => {+ log::warn!(+ "[auth] dropping unrecoverable profile provider={}: {e}",+ p.provider+ );+ dropped_ids.push(id.clone());+ continue;+ }+ }+ }+ }+ } else {+ // ── (b/c) No keychain — use existing JSON decrypt path ────────+ let decrypted = (|| -> Result<_> {+ let (access_token, access_migrated) =+ self.decrypt_optional(p.access_token.as_deref())?;+ let (refresh_token, refresh_migrated) =+ self.decrypt_optional(p.refresh_token.as_deref())?;+ let (id_token, id_migrated) = self.decrypt_optional(p.id_token.as_deref())?;+ let (token, token_migrated) = self.decrypt_optional(p.token.as_deref())?;+ Ok((+ access_token,+ access_migrated,+ refresh_token,+ refresh_migrated,+ id_token,+ id_migrated,+ token,+ token_migrated,+ ))+ })();++ let (+ access_token,+ access_migrated,+ refresh_token,+ refresh_migrated,+ id_token,+ id_migrated,+ token,+ token_migrated,+ ) = match decrypted {+ Ok(v) => v,+ Err(e) => {+ log::warn!(+ "[auth] dropping unrecoverable profile provider={}: {e}. \+ Most likely cause: .secret_key was regenerated after this profile \+ was stored. The store will be rewritten without this entry; \+ re-authenticate to restore the session.",+ p.provider+ );+ dropped_ids.push(id.clone());+ continue;+ }+ };++ if let Some(value) = access_migrated {+ p.access_token = Some(value);+ migrated = true;+ }+ if let Some(value) = refresh_migrated {+ p.refresh_token = Some(value);+ migrated = true;+ }+ if let Some(value) = id_migrated {+ p.id_token = Some(value);+ migrated = true;+ }+ if let Some(value) = token_migrated {+ p.token = Some(value);+ migrated = true;+ }+ (access_token, refresh_token, id_token, token)+ };++ let kind = match parse_profile_kind(&p.kind) {+ Ok(k) => k,+ Err(e) => {+ // A single profile with an unrecognized `kind` (e.g. a legacy value+ // like "OAuth" written before the kebab-case rename, or "api_key"+ // written by an older code path) must not poison the whole store —+ // otherwise every reader fails the entire load and the user is+ // locked out of *all* their auth profiles. Drop just this entry,+ // matching the decrypt-failure recovery pattern above; the next+ // login re-encodes the kind correctly.+ log::warn!(+ "[auth] dropping profile with unrecognized kind={:?} provider={}: {e}. \+ This usually means the profile was written by an older version of \+ OpenHuman. Re-authenticate to restore the session.",+ p.kind,+ p.provider+ );+ dropped_ids.push(id.clone());+ continue;+ }+ };+ let token_set = match kind {+ AuthProfileKind::OAuth => {+ let access = match access_token {+ Some(a) => a,+ None => {+ log::warn!(+ "[auth] dropping OAuth profile with missing access_token: \+ provider={}. Re-authenticate to restore.",+ p.provider+ );+ dropped_ids.push(id.clone());+ continue;+ }+ };+ Some(TokenSet {+ access_token: access,+ refresh_token,+ id_token,+ expires_at: parse_optional_datetime(p.expires_at.as_deref())?,+ token_type: p.token_type.clone(),+ scope: p.scope.clone(),+ })+ }+ AuthProfileKind::Token => None,+ };++ profiles.insert(+ id.clone(),+ AuthProfile {+ id: id.clone(),+ provider: p.provider.clone(),+ profile_name: p.profile_name.clone(),+ kind,+ account_id: p.account_id.clone(),+ workspace_id: p.workspace_id.clone(),+ token_set,+ token,+ metadata: p.metadata.clone(),+ created_at: parse_datetime_with_fallback(&p.created_at),+ updated_at: parse_datetime_with_fallback(&p.updated_at),+ },+ );+ }++ // Purge dropped profiles from the on-disk persisted view AND+ // any `active_profiles` pointers that referenced them, so the+ // next read returns a clean "no active session" state.+ if !dropped_ids.is_empty() {+ // Always apply the cleanup to the in-memory view so the returned+ // data is correct even on the lock-free read path; the on-disk+ // rewrite below is what's gated by `persist`.+ for id in &dropped_ids {+ persisted.profiles.remove(id);+ }+ persisted+ .active_profiles+ .retain(|_, profile_id| !dropped_ids.contains(profile_id));+ persisted.updated_at = Utc::now().to_rfc3339();+ log::warn!(+ "[auth] purged {} unrecoverable profile(s) from store at {} \+ (provider list redacted to avoid leaking PII)",+ dropped_ids.len(),+ self.path.display(),+ );+ }+ // Persist opportunistic cleanup / migrations only on the locked write+ // path. The lock-free read-only fallback (`persist = false`, used when+ // the disk can't accept the lock file) intentionally skips this — the+ // write would fail on a full disk anyway, and the in-memory view above+ // is already correct.+ if persist && (!dropped_ids.is_empty() || migrated || keychain_migrated) {+ self.write_persisted_locked(&persisted)?;+ }++ Ok(AuthProfilesData {+ schema_version: persisted.schema_version,+ updated_at: parse_datetime_with_fallback(&persisted.updated_at),+ active_profiles: persisted.active_profiles,+ profiles,+ })+ }+}diff --git a/src/openhuman/security/credentials/profiles_impl_01_part_02.rs b/src/openhuman/security/credentials/profiles_impl_01_part_02.rsnew file mode 100644index 0000000000..48dbf4d070--- /dev/null+++ b/src/openhuman/security/credentials/profiles_impl_01_part_02.rs@@ -0,0 +1,585 @@++impl AuthProfilesStore {+ fn save_locked(&self, data: &AuthProfilesData) -> Result<()> {+ let mut persisted = PersistedAuthProfiles {+ schema_version: CURRENT_SCHEMA_VERSION,+ updated_at: data.updated_at.to_rfc3339(),+ active_profiles: data.active_profiles.clone(),+ profiles: BTreeMap::new(),+ };++ for (id, profile) in &data.profiles {+ // When the OS keychain is available, store all secret fields there and+ // leave them absent from the JSON file. This is the preferred path on+ // macOS / Windows / Linux-with-Secret-Service.+ //+ // When the keychain is unavailable (Linux headless / CI), fall back to+ // the existing ChaCha20-Poly1305 encrypted JSON fields.+ let (access_token, refresh_token, id_token, token, expires_at, token_type, scope) =+ if self.use_keychain {+ // Store secrets in the OS keychain — JSON gets no secret fields.+ if let Err(e) = self.keychain_store_secrets(profile) {+ // Non-fatal: fall back to encrypted JSON so data is not lost.+ log::warn!(+ "[auth] save: keychain store failed for profile_id={id}: {e}; \+ falling back to encrypted JSON"+ );+ self.encrypt_for_json(profile)?+ } else {+ log::debug!("[auth] save: secrets stored in keychain profile_id={id}");+ let (expires_at, token_type, scope) = match &profile.token_set {+ Some(ts) => (+ ts.expires_at.as_ref().map(DateTime::to_rfc3339),+ ts.token_type.clone(),+ ts.scope.clone(),+ ),+ None => (None, None, None),+ };+ // Secret fields deliberately omitted from JSON.+ (None, None, None, None, expires_at, token_type, scope)+ }+ } else {+ // Headless / no keychain — encrypt and store in JSON.+ self.encrypt_for_json(profile)?+ };++ persisted.profiles.insert(+ id.clone(),+ PersistedAuthProfile {+ provider: profile.provider.clone(),+ profile_name: profile.profile_name.clone(),+ kind: profile_kind_to_string(profile.kind).to_string(),+ account_id: profile.account_id.clone(),+ workspace_id: profile.workspace_id.clone(),+ access_token,+ refresh_token,+ id_token,+ token,+ expires_at,+ token_type,+ scope,+ metadata: profile.metadata.clone(),+ created_at: profile.created_at.to_rfc3339(),+ updated_at: profile.updated_at.to_rfc3339(),+ },+ );+ }++ self.write_persisted_locked(&persisted)+ }++ /// Encrypt a profile's secret fields for JSON storage (keychain-unavailable path).+ fn encrypt_for_json(&self, profile: &AuthProfile) -> Result<EncryptedProfileFields> {+ let (access_token, refresh_token, id_token, expires_at, token_type, scope) =+ match (&profile.kind, &profile.token_set) {+ (AuthProfileKind::OAuth, Some(token_set)) => (+ self.encrypt_optional(Some(&token_set.access_token))?,+ self.encrypt_optional(token_set.refresh_token.as_deref())?,+ self.encrypt_optional(token_set.id_token.as_deref())?,+ token_set.expires_at.as_ref().map(DateTime::to_rfc3339),+ token_set.token_type.clone(),+ token_set.scope.clone(),+ ),+ _ => (None, None, None, None, None, None),+ };+ let token = self.encrypt_optional(profile.token.as_deref())?;+ Ok((+ access_token,+ refresh_token,+ id_token,+ token,+ expires_at,+ token_type,+ scope,+ ))+ }++ fn read_persisted_locked(&self) -> Result<PersistedAuthProfiles> {+ if !self.path.exists() {+ return Ok(PersistedAuthProfiles::default());+ }++ let bytes = fs::read(&self.path).with_context(|| {+ format!(+ "Failed to read auth profile store at {}",+ self.path.display()+ )+ })?;++ if bytes.is_empty() {+ return Ok(PersistedAuthProfiles::default());+ }++ let mut persisted: PersistedAuthProfiles = match serde_json::from_slice(&bytes) {+ Ok(p) => p,+ Err(err) => {+ let quarantined = quarantine_corrupt_store(&self.path)?;+ let quarantined_file = quarantined+ .file_name()+ .and_then(|s| s.to_str())+ .unwrap_or("auth-profiles.corrupt");+ tracing::warn!(+ path_file = PROFILES_FILENAME,+ quarantined_file = quarantined_file,+ error = %err,+ "[credentials] auth profile store unparseable; quarantined and reset to empty"+ );+ return Ok(PersistedAuthProfiles::default());+ }+ };++ if persisted.schema_version == 0 {+ persisted.schema_version = CURRENT_SCHEMA_VERSION;+ }++ if persisted.schema_version > CURRENT_SCHEMA_VERSION {+ anyhow::bail!(+ "Unsupported auth profile schema version {} (max supported: {})",+ persisted.schema_version,+ CURRENT_SCHEMA_VERSION+ );+ }++ Ok(persisted)+ }++ fn write_persisted_locked(&self, persisted: &PersistedAuthProfiles) -> Result<()> {+ if let Some(parent) = self.path.parent() {+ fs::create_dir_all(parent).with_context(|| {+ format!(+ "Failed to create auth profile directory at {}",+ parent.display()+ )+ })?;+ }++ let json =+ serde_json::to_vec_pretty(persisted).context("Failed to serialize auth profiles")?;+ let tmp_name = format!(+ "{}.tmp.{}.{}",+ PROFILES_FILENAME,+ std::process::id(),+ Utc::now().timestamp_nanos_opt().unwrap_or_default()+ );+ let tmp_path = self.path.with_file_name(tmp_name);++ // Windows AV / Search-Indexer / Defender may briefly hold a handle on+ // the destination, returning transient `ERROR_SHARING_VIOLATION (32)`,+ // `ERROR_ACCESS_DENIED (5)`, or `ERROR_DELETE_PENDING (303)` —+ // recognised as retryable by `is_transient_fs_error`. Mirror the+ // lock-create retry budget at the bottom of `acquire_lock` so the+ // JSON write+rename path absorbs the same transient family that+ // closed Sentry OPENHUMAN-TAURI-H1 / H8 for the lock path. Outer+ // `with_context` preserved so the Sentry fingerprint shape is stable+ // across releases. (Sentry TAURI-RUST-92J / #3355.)+ retry_with_backoff(+ "write auth profile tmp",+ PERSIST_RETRY_ATTEMPTS,+ PERSIST_RETRY_BASE_MS,+ || {+ self.consume_test_transient_failure_write()?;+ fs::write(&tmp_path, &json).context("write auth profile tmp")+ },+ )+ .with_context(|| {+ format!(+ "Failed to write temporary auth profile file at {}",+ tmp_path.display()+ )+ })?;++ let rename_result = retry_with_backoff(+ "replace auth profile store",+ PERSIST_RETRY_ATTEMPTS,+ PERSIST_RETRY_BASE_MS,+ || {+ self.consume_test_transient_failure_rename()?;+ fs::rename(&tmp_path, &self.path).context("rename auth profile tmp -> store")+ },+ )+ .with_context(|| {+ format!(+ "Failed to replace auth profile store at {}",+ self.path.display()+ )+ });++ if rename_result.is_err() {+ // Best-effort orphan cleanup: `tmp_path` is `…tmp.{pid}.{nanos}`+ // — unique per call — so a permanently-failing rename otherwise+ // leaks one tmp file per `app_state_snapshot` poll (~2s cadence)+ // under sustained Windows AV / Search-Indexer holds. Cleaning+ // here keeps the directory tidy; the cleanup itself can fail+ // (the same AV that blocked the rename may block the unlink),+ // which is why we deliberately drop the result.+ let _ = fs::remove_file(&tmp_path);+ }++ rename_result+ }++ /// Consume one test-injected transient FS failure for the **write**+ /// stage if any are queued. No-op in production builds.+ #[cfg(test)]+ fn consume_test_transient_failure_write(&self) -> Result<()> {+ consume_one(&self.force_transient_failures_write)+ }++ /// Consume one test-injected transient FS failure for the **rename**+ /// stage if any are queued. No-op in production builds.+ #[cfg(test)]+ fn consume_test_transient_failure_rename(&self) -> Result<()> {+ consume_one(&self.force_transient_failures_rename)+ }++ #[cfg(not(test))]+ #[inline(always)]+ fn consume_test_transient_failure_write(&self) -> Result<()> {+ Ok(())+ }++ #[cfg(not(test))]+ #[inline(always)]+ fn consume_test_transient_failure_rename(&self) -> Result<()> {+ Ok(())+ }++ /// Queue `n` test-only forced transient FS failures for the write+ /// stage. The next `n` calls inside the `fs::write(tmp)` retry loop+ /// return a `__TEST_TRANSIENT__` error before the underlying FS op+ /// runs; the retry helper treats them as retryable.+ #[cfg(test)]+ pub(super) fn force_next_write_failures(&self, n: usize) {+ self.force_transient_failures_write+ .store(n, Ordering::SeqCst);+ }++ /// Queue `n` test-only forced transient FS failures for the rename+ /// stage. Separate from the write counter so tests can exercise the+ /// rename retry loop in isolation (PR #3364 review feedback).+ #[cfg(test)]+ pub(super) fn force_next_rename_failures(&self, n: usize) {+ self.force_transient_failures_rename+ .store(n, Ordering::SeqCst);+ }++ /// Test introspection: how many forced write-stage failures are still+ /// queued.+ #[cfg(test)]+ pub(super) fn remaining_forced_write_failures(&self) -> usize {+ self.force_transient_failures_write.load(Ordering::SeqCst)+ }++ /// Test introspection: how many forced rename-stage failures are still+ /// queued.+ #[cfg(test)]+ pub(super) fn remaining_forced_rename_failures(&self) -> usize {+ self.force_transient_failures_rename.load(Ordering::SeqCst)+ }++ /// Queue a single test-only forced `StorageFull` lock-create failure. The+ /// next `acquire_lock` returns the synthetic disk-full error so tests can+ /// drive the lock-free read-only fallback in [`AuthProfilesStore::load`].+ #[cfg(test)]+ pub(super) fn force_next_lock_unwritable(&self) {+ self.force_lock_unwritable.store(true, Ordering::SeqCst);+ }++ fn encrypt_optional(&self, value: Option<&str>) -> Result<Option<String>> {+ match value {+ Some(value) if !value.is_empty() => self.secret_store.encrypt(value).map(Some),+ Some(_) | None => Ok(None),+ }+ }++ fn decrypt_optional(&self, value: Option<&str>) -> Result<(Option<String>, Option<String>)> {+ match value {+ Some(value) if !value.is_empty() => {+ let (plaintext, migrated) = self.secret_store.decrypt_and_migrate(value)?;+ Ok((Some(plaintext), migrated))+ }+ Some(_) | None => Ok((None, None)),+ }+ }++ fn acquire_lock(&self) -> Result<AuthProfileLockGuard> {+ // Test-only: simulate a full / read-only filesystem that can't create+ // the lock file, to drive the read-only fallback in `load`.+ #[cfg(test)]+ if self.force_lock_unwritable.swap(false, Ordering::SeqCst) {+ let io = std::io::Error::from(std::io::ErrorKind::StorageFull);+ return Err(annotate_lock_create_failure(+ anyhow::Error::new(io).context("open lock file"),+ ));+ }++ if let Some(parent) = self.lock_path.parent() {+ fs::create_dir_all(parent)+ .with_context(|| "Failed to create auth profile lock directory".to_string())?;+ }++ // Drive timeout + stale-recheck off wall-clock elapsed time, not the+ // sum of explicit `thread::sleep(LOCK_WAIT_MS)` calls. The earlier+ // counter-based approach excluded time spent inside+ // `retry_with_backoff` (which can sleep up to ~30s on its own+ // schedule before returning AlreadyExists) and the lock-file I/O+ // syscalls. Under Windows AV contention that drift could push+ // both `LOCK_TIMEOUT_MS` and `next_stale_recheck_ms` significantly+ // later than intended.+ let started_at = Instant::now();++ // Serialize same-process acquirers on an in-memory lock keyed by this+ // path before we ever touch the on-disk lock file. Two things depend on+ // holding it: (1) concurrent `app_state_snapshot` calls in this process+ // queue here instead of racing `create_new`/`Drop` on the file, and+ // (2) it lets us treat an on-disk lock recording our own pid as a leaked+ // `Drop` unlink and reclaim it immediately — no other thread in this+ // process can hold a live guard while we own this in-memory lock (see+ // `reclaim_self_owned_lock`). Held for the lifetime of the returned+ // guard.+ //+ // Use `try_lock` against the *same* `LOCK_TIMEOUT_MS` budget as the+ // on-disk wait rather than a blocking `lock()`: a wedged in-process+ // holder must not be able to strand an RPC/blocking worker past the+ // timeout the caller (e.g. `app_state_snapshot`) expects. Poison is+ // recoverable — the `()` payload carries no invariant.+ let in_process_lock = in_process_lock_for(&self.lock_path);+ let in_process_guard = loop {+ match in_process_lock.try_lock() {+ Ok(guard) => break guard,+ Err(TryLockError::Poisoned(poisoned)) => break poisoned.into_inner(),+ Err(TryLockError::WouldBlock) => {+ if started_at.elapsed().as_millis() as u64 >= LOCK_TIMEOUT_MS {+ anyhow::bail!("Timed out waiting for auth profile lock");+ }+ thread::sleep(Duration::from_millis(LOCK_WAIT_MS));+ }+ }+ };++ let mut cleared_stale = false;+ // Periodically re-probe for stale locks during the busy-wait. A+ // lock that started fresh (live pid, recent mtime) can age past+ // STALE_LOCK_AGE_MS while we wait, and we want to recover from+ // that without bailing at the LOCK_TIMEOUT_MS boundary.+ let mut next_stale_recheck_ms: u64 = 1_000;+ loop {+ let open_result = crate::openhuman::util::retry_with_backoff(+ "create auth profile lock",+ 6,+ 100,+ || {+ OpenOptions::new()+ .create_new(true)+ .write(true)+ .open(&self.lock_path)+ .context("open lock file")+ },+ );++ match open_result {+ Ok(mut file) => {+ // Issue #1612 — writing the pid line is what later lets+ // a future acquirer recognise a crashed owner; if the+ // write fails we must NOT report the lock as held with+ // a malformed/empty file behind us, or stale recovery+ // would silently degrade to the full 10s timeout for+ // every subsequent acquire.+ if let Err(e) = writeln!(file, "pid={}", std::process::id()) {+ let _ = fs::remove_file(&self.lock_path);+ return Err(e).with_context(|| {+ "Failed to write auth profile lock owner".to_string()+ });+ }+ return Ok(AuthProfileLockGuard {+ lock_path: self.lock_path.clone(),+ _in_process: in_process_guard,+ });+ }+ Err(e) => {+ let is_already_exists = e+ .chain()+ .find_map(|e| e.downcast_ref::<std::io::Error>())+ .is_some_and(|ioe| ioe.kind() == std::io::ErrorKind::AlreadyExists);++ if is_already_exists {+ // A lock file recording our own pid can only be a+ // leaked `Drop` unlink: we hold the in-process lock, so+ // no live same-process guard exists. Reclaim it+ // immediately rather than spinning the 30s age floor+ // (`STALE_LOCK_AGE_MS`) that sits *behind* the ~10s RPC+ // timeout — that gap is what produced the sustained+ // "Timed out waiting for auth profile lock" retry storm+ // (Sentry TAURI-RUST-B1 / #2318). Cheap enough (one tiny+ // read) to re-probe every spin, which also self-heals a+ // lock our own `Drop` leaks mid-wait.+ if self.reclaim_self_owned_lock() {+ continue;+ }+ // Issue #1612 — a previous openhuman crash can leave a+ // stale auth-profiles.lock behind (a *different*, now-dead+ // pid, or an aged leak), after which every RPC path that+ // touches the auth profile store fails for the+ // `LOCK_TIMEOUT_MS` window and the user gets stuck in a+ // retry storm. Before falling back to the busy-wait, try+ // once to peek at the writer's recorded PID and remove+ // the lock if that process is no longer alive. Flag is+ // flipped on the first probe (not only on success) so a+ // live-pid / malformed / unreadable lock doesn't trigger+ // a fresh sysinfo probe + log line on every busy-wait+ // iteration.+ if !cleared_stale {+ cleared_stale = true;+ if self.clear_lock_if_stale() {+ continue;+ }+ } else {+ let elapsed_ms = started_at.elapsed().as_millis() as u64;+ if elapsed_ms >= next_stale_recheck_ms {+ // The age-based reclaim check is cheap (one+ // `fs::metadata` call in the common case) and+ // safely no-ops on fresh, legitimate locks.+ // Re-probing periodically lets us recover from+ // a leaked-mid-wait lock without bailing at+ // the 10s timeout.+ next_stale_recheck_ms = next_stale_recheck_ms.saturating_add(1_000);+ if self.clear_lock_if_stale() {+ continue;+ }+ }+ }+ if started_at.elapsed().as_millis() as u64 >= LOCK_TIMEOUT_MS {+ anyhow::bail!("Timed out waiting for auth profile lock");+ }+ thread::sleep(Duration::from_millis(LOCK_WAIT_MS));+ } else {+ // Sentry OPENHUMAN-TAURI-H8 collapses every+ // non-AlreadyExists, non-transient `create_new`+ // failure into a single fingerprint with no+ // breadcrumb of which OS code actually fired.+ // `annotate_lock_create_failure` embeds the+ // underlying `io::ErrorKind` + `raw_os_error()` so+ // future events split by root cause and we can+ // widen `is_transient_fs_error` (or fix the+ // underlying condition) for whichever code is hot.+ return Err(annotate_lock_create_failure(e));+ }+ }+ }+ }+ }++ /// Returns `true` if an existing lock file was detected as stale and+ /// successfully removed. Two cases reclaim:+ ///+ /// 1. The recorded `pid=` line points at a process that is no longer+ /// running — classic crashed-owner recovery (Issue #1612).+ /// 2. The lock file's mtime is older than [`STALE_LOCK_AGE_MS`]. This+ /// catches a *different* still-alive process that leaked its lock (its+ /// `AuthProfileLockGuard::drop` could not unlink the file — e.g. Windows+ /// AV / indexer briefly held a handle — and orphaned it with that live+ /// pid inside). No legitimate auth-profile op holds the lock long enough+ /// to be affected, so a too-old lock is unambiguously a leak. A lock+ /// leaked by *this* process is handled far sooner — immediately, without+ /// the age floor — by [`reclaim_self_owned_lock`](Self::reclaim_self_owned_lock),+ /// which is sound because acquirers serialize on the in-process lock.+ ///+ /// 3. The lock file has no parseable `pid=` line and is older than+ /// [`MALFORMED_LOCK_GRACE_MS`]. A healthy holder writes its pid within+ /// microseconds of `create_new`, so a pidless lock past that short+ /// grace is an abandoned in-flight writer (crashed/killed between+ /// `create_new` and the `pid=` write) — reclaim it rather than make+ /// every reader spin the full [`STALE_LOCK_AGE_MS`]/`LOCK_TIMEOUT_MS`+ /// window (the ~30s "stuck on Initializing OpenHuman" after a+ /// kill+reopen). The grace is short but non-zero so we never reclaim a+ /// live writer that is mid-`create_new`/`pid=`.+ fn clear_lock_if_stale(&self) -> bool {+ let metadata = match fs::metadata(&self.lock_path) {+ Ok(m) => m,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return false,+ Err(e) => {+ tracing::warn!(+ target: "auth-profiles",+ "[credentials] failed to stat lock file at {} for stale check: {e}",+ self.lock_path.display()+ );+ return false;+ }+ };++ let age = metadata+ .modified()+ .ok()+ .and_then(|mtime| std::time::SystemTime::now().duration_since(mtime).ok());+ let too_old = age.is_some_and(|a| a >= Duration::from_millis(STALE_LOCK_AGE_MS));+ // A pidless lock needs only a short grace: no healthy holder leaves the+ // file without a `pid=` line for more than the microsecond gap between+ // `create_new` and the write, so anything older is abandoned. If mtime+ // is unreadable (clock skew, platform limitation) default to stale —+ // no legitimate in-flight writer would be undetectable for that long.+ let malformed_too_old =+ age.is_none_or(|a| a >= Duration::from_millis(MALFORMED_LOCK_GRACE_MS));++ let content = match fs::read_to_string(&self.lock_path) {+ Ok(s) => s,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return false,+ Err(e) => {+ tracing::warn!(+ target: "auth-profiles",+ "[credentials] failed to read lock file at {} for stale check: {e}",+ self.lock_path.display()+ );+ return false;+ }+ };++ let pid = content+ .lines()+ .find_map(|line| line.trim().strip_prefix("pid=")?.trim().parse::<u32>().ok());++ let reclaim_reason: Option<String> = match pid {+ Some(pid) if !is_pid_alive(pid) => Some(format!("pid {pid} not alive")),+ Some(pid) if too_old => Some(format!(+ "lock file older than {STALE_LOCK_AGE_MS}ms (recorded pid {pid}, presumed leaked)"+ )),+ None if malformed_too_old => Some(format!(+ "no parseable pid and older than {MALFORMED_LOCK_GRACE_MS}ms \+ (abandoned in-flight lock, reclaiming)"+ )),+ Some(_) => return false,+ None => {+ tracing::warn!(+ target: "auth-profiles",+ "[credentials] lock at {} has no parseable pid line and is younger than \+ {MALFORMED_LOCK_GRACE_MS}ms; leaving in place briefly",+ self.lock_path.display()+ );+ return false;+ }+ };++ let Some(reason) = reclaim_reason else {+ return false;+ };++ match fs::remove_file(&self.lock_path) {+ Ok(()) => {+ tracing::info!(+ target: "auth-profiles",+ "[credentials] removed stale auth profile lock at {} ({reason})",+ self.lock_path.display()+ );+ true+ }+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,+ Err(e) => {+ tracing::warn!(+ target: "auth-profiles",+ "[credentials] failed to remove stale lock at {} ({reason}): {e}",+ self.lock_path.display()+ );+ false+ }+ }+ }+}diff --git a/src/openhuman/security/credentials/profiles_impl_01_part_03.rs b/src/openhuman/security/credentials/profiles_impl_01_part_03.rsnew file mode 100644index 0000000000..f7653f4715--- /dev/null+++ b/src/openhuman/security/credentials/profiles_impl_01_part_03.rs@@ -0,0 +1,80 @@++impl AuthProfilesStore {+ /// Remove the on-disk lock file **iff** it records this process's own pid.+ /// Returns `true` when a self-owned lock was found and removed.+ ///+ /// MUST only be called while holding this path's in-process lock (acquired+ /// at the top of [`acquire_lock`](Self::acquire_lock) via+ /// [`in_process_lock_for`]). That invariant is what makes the removal safe:+ /// same-process acquirers serialize on the in-process lock, so no other+ /// thread in this process can be holding a live `AuthProfileLockGuard` while+ /// we run. A lock file carrying our own pid is therefore necessarily a leak+ /// — a previous guard's `Drop` could not unlink it (on Windows, AV / the+ /// Search indexer briefly hold a handle on the just-written file) and+ /// orphaned it with our still-alive pid inside.+ ///+ /// This is the fast self-heal for Sentry TAURI-RUST-B1 (#2318): without it+ /// the only recovery for a leaked-but-live-pid lock is the age branch in+ /// [`clear_lock_if_stale`](Self::clear_lock_if_stale), whose+ /// [`STALE_LOCK_AGE_MS`] floor (30s) is far longer than the ~10s RPC+ /// timeout, so every `app_state_snapshot` timed out and retry-stormed for+ /// the whole 30s window before age-reclaim kicked in.+ fn reclaim_self_owned_lock(&self) -> bool {+ let me = std::process::id();+ tracing::trace!(+ target: "auth-profiles",+ "[credentials] probing for self-owned leaked lock at {} (our pid {me})",+ self.lock_path.display()+ );+ let content = match fs::read_to_string(&self.lock_path) {+ Ok(s) => s,+ // NotFound: already gone (raced with another reclaim / the guard's+ // own Drop). Any other read error: fall back to the age-based and+ // busy-wait paths rather than guess at ownership.+ Err(e) => {+ tracing::debug!(+ target: "auth-profiles",+ "[credentials] self-owned probe could not read lock at {} ({e}); \+ deferring to stale/busy-wait recovery",+ self.lock_path.display()+ );+ return false;+ }+ };++ let pid = content+ .lines()+ .find_map(|line| line.trim().strip_prefix("pid=")?.trim().parse::<u32>().ok());+ if pid != Some(me) {+ tracing::trace!(+ target: "auth-profiles",+ "[credentials] lock at {} is not self-owned (recorded {pid:?}, our pid {me}); \+ deferring to stale/busy-wait recovery",+ self.lock_path.display()+ );+ return false;+ }++ match fs::remove_file(&self.lock_path) {+ Ok(()) => {+ tracing::info!(+ target: "auth-profiles",+ "[credentials] reclaimed leaked self-owned auth profile lock at {} \+ (recorded our own live pid {me}; a prior guard's Drop unlink was blocked, \+ most likely by Windows AV/indexer)",+ self.lock_path.display()+ );+ true+ }+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,+ Err(e) => {+ tracing::warn!(+ target: "auth-profiles",+ "[credentials] failed to reclaim self-owned auth profile lock at {}: {e}",+ self.lock_path.display()+ );+ false+ }+ }+ }+}