Skip to content

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

chore: files changed crates/openhuman-core/src/config/schema/load/env_overlay.rs,crates/openhuman-co

Steven Enamakel0cb8cc8a7abe
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/jsonl.rs b/crates/openhuman-core/src/agent/harness/session/transcript/jsonl.rs
new file mode 100644
index 0000000000..7faa914410
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/session/transcript/jsonl.rs
@@ -0,0 +1,379 @@
+//! JSONL line shapes (`_meta`, message, and compaction records) and the
+//! conversions between them and the public [`ChatMessage`] /
+//! [`TranscriptMeta`] / [`DisplayMessage`] types.
+
+use super::metadata::{attach_turn_usage_metadata, take_tool_failure};
+use super::types::{
+ DisplayMessage, MessageUsage, TranscriptMeta, TurnUsage, TRANSCRIPT_SCHEMA_VERSION,
+};
+use crate::agent::messages::ChatMessage;
+use crate::inference::provider::ToolCall;
+use anyhow::{Context, Result};
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+
+/// Discriminator value for a compaction record's `kind` field.
+pub(super) const COMPACTION_KIND: &str = "compaction";
+
+#[allow(clippy::trivially_copy_pass_by_ref)]
+fn is_false(b: &bool) -> bool {
+ !*b
+}
+
+// ── Internal JSONL types ─────────────────────────────────────────────
+
+/// The `_meta` line serialisation shape.
+#[derive(Serialize, Deserialize)]
+pub(super) struct MetaLine {
+ #[serde(rename = "_meta")]
+ pub(super) meta: MetaPayload,
+}
+
+#[derive(Serialize, Deserialize)]
+pub(super) struct MetaPayload {
+ /// Schema version of the transcript record format (see
+ /// [`TRANSCRIPT_SCHEMA_VERSION`]). Absent (deserialises to `0`) on files
+ /// written before the append-only migration.
+ #[serde(default)]
+ pub(super) version: u32,
+ pub(super) agent: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) agent_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) agent_type: Option<String>,
+ pub(super) dispatcher: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) provider: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) model: Option<String>,
+ pub(super) created: String,
+ pub(super) updated: String,
+ pub(super) turn_count: usize,
+ pub(super) input_tokens: u64,
+ pub(super) output_tokens: u64,
+ pub(super) cached_input_tokens: u64,
+ pub(super) charged_amount_usd: f64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) thread_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) task_id: Option<String>,
+}
+
+/// One message line in the JSONL — only `role` and `content` are required.
+/// All other fields are optional; unknown fields are flattened to preserve
+/// forward-compatibility.
+#[derive(Serialize, Deserialize)]
+pub(super) struct MessageLine {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) id: Option<String>,
+ pub(super) role: String,
+ pub(super) content: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) extra_metadata: Option<serde_json::Value>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub(super) provider: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub(super) model: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub(super) usage: Option<MessageUsage>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub(super) reasoning_content: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub(super) tool_calls: Option<Vec<ToolCall>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub(super) iteration: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub(super) ts: Option<String>,
+ /// Turn boundary marker: the web-chat `request_id` this message belongs to,
+ /// when available. Stamped on every line of a turn so the display projection
+ /// can group a turn's messages. Absent for CLI / non-request-scoped runs.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) request_id: Option<String>,
+ /// `true` when this line is a *partial* assistant answer captured because
+ /// the turn was interrupted/cancelled mid-stream. Present for **display
+ /// only** — the model-context reader skips these so a resumed context never
+ /// carries a truncated answer.
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub(super) interrupted: bool,
+ /// `true` when this tool-result line's tool call **failed**
+ /// (`ToolResult::is_error`). Additive + optional: legacy lines and every
+ /// non-tool line omit it and default to success. Lifted from the tool
+ /// message's failure metadata by [`build_message_line`]; consumed by the
+ /// display projection to render an error tool row instead of success.
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub(super) failure: bool,
+ /// Optional short, single-line reason for a failed tool call (the head of
+ /// the error output). Present only alongside `failure: true`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) failure_detail: Option<String>,
+ /// Absorb any unknown fields so forward-compat reads don't error.
+ #[serde(flatten)]
+ pub(super) _extra: HashMap<String, serde_json::Value>,
+}
+
+/// A compaction record: `{"kind":"compaction","replacement":[…]}`.
+///
+/// Appended when the harness reduces context (post-compaction / trim) so the
+/// model-context reader can reconstruct the reduced set without the file being
+/// destructively rewritten. `replacement` is the **full** logical message set
+/// that supersedes everything before it — an explicit replacement list
+/// (mirroring Codex's `Compacted { replacement_history }`) rather than
+/// surviving-message ids, because our writer already holds the reduced
+/// `messages` slice on each persist call and message ids are optional, so an
+/// id-reference scheme would be less robust for no gain.
+#[derive(Serialize, Deserialize)]
+pub(super) struct CompactionLine {
+ pub(super) kind: String,
+ pub(super) replacement: Vec<MessageLine>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) ts: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) request_id: Option<String>,
+ #[serde(flatten)]
+ pub(super) _extra: HashMap<String, serde_json::Value>,
+}
+
+/// Build the serialised `_meta` header line for `meta`, stamping the current
+/// [`TRANSCRIPT_SCHEMA_VERSION`].
+fn meta_payload_from(meta: &TranscriptMeta) -> MetaPayload {
+ MetaPayload {
+ version: TRANSCRIPT_SCHEMA_VERSION,
+ agent: meta.agent_name.clone(),
+ agent_id: meta.agent_id.clone(),
+ agent_type: meta.agent_type.clone(),
+ dispatcher: meta.dispatcher.clone(),
+ provider: meta.provider.clone(),
+ model: meta.model.clone(),
+ created: meta.created.clone(),
+ updated: meta.updated.clone(),
+ turn_count: meta.turn_count,
+ input_tokens: meta.input_tokens,
+ output_tokens: meta.output_tokens,
+ cached_input_tokens: meta.cached_input_tokens,
+ charged_amount_usd: meta.charged_amount_usd,
+ thread_id: meta.thread_id.clone(),
+ task_id: meta.task_id.clone(),
+ }
+}
+
+pub(super) fn meta_line_json(meta: &TranscriptMeta) -> Result<String> {
+ let meta_line = MetaLine {
+ meta: meta_payload_from(meta),
+ };
+ serde_json::to_string(&meta_line).context("serialise transcript meta header")
+}
+
+/// Build a [`MessageLine`] for `msg`, folding in `turn_usage` (assistant rows)
+/// and stamping the `request_id` turn boundary when supplied.
+pub(super) fn build_message_line(
+ msg: &ChatMessage,
+ turn_usage: Option<&TurnUsage>,
+ request_id: Option<&str>,
+ interrupted: bool,
+) -> MessageLine {
+ let assistant_usage = if msg.role == "assistant" {
+ turn_usage
+ } else {
+ None
+ };
+ // Lift any tool-failure marker off a cloned `extra_metadata` onto the
+ // additive top-level `failure` / `failure_detail` line fields, stripping it
+ // so it is not persisted twice.
+ let mut extra_metadata = msg.extra_metadata.clone();
+ let (failure, failure_detail) = match take_tool_failure(&mut extra_metadata) {
+ Some((failed, detail)) => (failed, detail),
+ None => (false, None),
+ };
+ let message_reasoning = (msg.role == "assistant")
+ .then(|| {
+ extra_metadata
+ .as_ref()
+ .and_then(|meta| meta.get(crate::agent::message_convert::REASONING_EXT_KEY))
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_string)
+ })
+ .flatten();
+ let native_envelope = (msg.role == "assistant")
+ .then(|| serde_json::from_str::<serde_json::Value>(&msg.content).ok())
+ .flatten();
+ let envelope_reasoning = native_envelope
+ .as_ref()
+ .and_then(|value| value.get("reasoning_content"))
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_string);
+ let envelope_tool_calls = native_envelope
+ .as_ref()
+ .and_then(|value| value.get("tool_calls"))
+ .and_then(|value| serde_json::from_value::<Vec<ToolCall>>(value.clone()).ok())
+ .filter(|calls| !calls.is_empty());
+ MessageLine {
+ id: msg.id.clone(),
+ role: msg.role.clone(),
+ content: msg.content.clone(),
+ extra_metadata,
+ provider: assistant_usage.map(|tu| tu.provider.clone()),
+ model: assistant_usage.map(|tu| tu.model.clone()),
+ usage: assistant_usage.map(|tu| tu.usage.clone()),
+ reasoning_content: message_reasoning
+ .or(envelope_reasoning)
+ .or_else(|| assistant_usage.and_then(|tu| tu.reasoning_content.clone())),
+ tool_calls: envelope_tool_calls.or_else(|| {
+ assistant_usage.and_then(|tu| {
+ if tu.tool_calls.is_empty() {
+ None
+ } else {
+ Some(tu.tool_calls.clone())
+ }
+ })
+ }),
+ iteration: assistant_usage.map(|tu| tu.iteration),
+ ts: assistant_usage.map(|tu| tu.ts.clone()),
+ request_id: request_id.map(str::to_string),
+ interrupted,
+ failure,
+ failure_detail,
+ _extra: HashMap::new(),
+ }
+}
+
+/// Serialise `messages` into JSONL message lines, attributing
+/// `last_assistant_turn_usage` (or per-message embedded usage) to the last
+/// assistant row and stamping `request_id` on every line.
+pub(super) fn serialise_message_lines(
+ messages: &[ChatMessage],
+ last_assistant_turn_usage: Option<&TurnUsage>,
+ request_id: Option<&str>,
+ buf: &mut String,
+) -> Result<()> {
+ let last_assistant_idx = messages.iter().rposition(|m| m.role == "assistant");
+ for (i, msg) in messages.iter().enumerate() {
+ let turn_usage = if Some(i) == last_assistant_idx {
+ last_assistant_turn_usage
+ .cloned()
+ .or_else(|| turn_usage_from_metadata(msg))
+ } else {
+ turn_usage_from_metadata(msg)
+ };
+ let line = build_message_line(msg, turn_usage.as_ref(), request_id, false);
+ let line_json =
+ serde_json::to_string(&line).with_context(|| format!("serialise message line {i}"))?;
+ buf.push_str(&line_json);
+ buf.push('\n');
+ }
+ Ok(())
+}
+
+/// Convert a parsed `MetaPayload` into the public [`TranscriptMeta`].
+pub(super) fn meta_from_payload(mp: MetaPayload) -> TranscriptMeta {
+ TranscriptMeta {
+ agent_name: mp.agent,
+ agent_id: mp.agent_id,
+ agent_type: mp.agent_type,
+ dispatcher: mp.dispatcher,
+ provider: mp.provider,
+ model: mp.model,
+ created: mp.created,
+ updated: mp.updated,
+ turn_count: mp.turn_count,
+ input_tokens: mp.input_tokens,
+ output_tokens: mp.output_tokens,
+ cached_input_tokens: mp.cached_input_tokens,
+ charged_amount_usd: mp.charged_amount_usd,
+ thread_id: mp.thread_id,
+ task_id: mp.task_id,
+ }
+}
+
+/// Recover the [`TurnUsage`] a message line carried (assistant rows only).
+fn turn_usage_from_line(ml: &MessageLine) -> Option<TurnUsage> {
+ match (
+ ml.provider.clone(),
+ ml.model.clone(),
+ ml.usage.clone(),
+ ml.ts.clone(),
+ ) {
+ (Some(provider), Some(model), Some(usage), Some(ts)) if ml.role == "assistant" => {
+ Some(TurnUsage {
+ provider,
+ model,
+ usage,
+ ts,
+ reasoning_content: ml.reasoning_content.clone(),
+ tool_calls: ml.tool_calls.clone().unwrap_or_default(),
+ iteration: ml.iteration.unwrap_or_default(),
+ })
+ }
+ _ => None,
+ }
+}
+
+/// Reconstruct a [`ChatMessage`] from a message line, re-attaching turn-usage
+/// metadata so the round-trip is lossless for the model-context path.
+pub(super) fn message_from_line(ml: MessageLine) -> ChatMessage {
+ let turn_usage = turn_usage_from_line(&ml);
+ let mut message = ChatMessage {
+ id: ml.id,
+ role: ml.role,
+ content: ml.content,
+ extra_metadata: ml.extra_metadata,
+ cache_breakpoints: Vec::new(),
+ };
+ if let Some(turn_usage) = turn_usage.as_ref() {
+ attach_turn_usage_metadata(&mut message, turn_usage);
+ }
+ message
+}
+
+/// Classification of one non-empty JSONL line.
+pub(super) enum LineKind {
+ Meta(MetaLine),
+ Compaction(CompactionLine),
+ Message(MessageLine),
+}
+
+/// Classify a raw line: a `_meta` header/update, a `compaction` record, or a
+/// message line. Returns `Err` only when the line is malformed for its
+/// apparent kind; the caller decides whether that is fatal (first line) or a
+/// skippable warning (later lines).
+pub(super) fn classify_line(line: &str) -> Result<LineKind, serde_json::Error> {
+ // Cheap structural peek. Unknown/other shapes fall through to MessageLine,
+ // whose required `role`/`content` gate rejects genuinely foreign lines.
+ let value: serde_json::Value = serde_json::from_str(line)?;
+ if value.get("_meta").is_some() {
+ return serde_json::from_str::<MetaLine>(line).map(LineKind::Meta);
+ }
+ if value.get("kind").and_then(|k| k.as_str()) == Some(COMPACTION_KIND) {
+ return serde_json::from_str::<CompactionLine>(line).map(LineKind::Compaction);
+ }
+ serde_json::from_str::<MessageLine>(line).map(LineKind::Message)
+}
+
+// ── Display read ──────────────────────────────────────────────────────
+
+/// Reconstruct a [`DisplayMessage`] from a message line, preserving the
+/// turn-boundary + partial flags the model-context path discards.
+pub(super) fn display_message_from_line(ml: MessageLine) -> DisplayMessage {
+ let turn_usage = turn_usage_from_line(&ml);
+ let reasoning_content = ml.reasoning_content.clone().or_else(|| {
+ turn_usage
+ .as_ref()
+ .and_then(|tu| tu.reasoning_content.clone())
+ });
+ DisplayMessage {
+ interrupted: ml.interrupted,
+ request_id: ml.request_id.clone(),
+ iteration: ml.iteration,
+ ts: ml.ts.clone(),
+ turn_usage,
+ reasoning_content,
+ failure: ml.failure,
+ failure_detail: ml.failure_detail.clone(),
+ message: ChatMessage {
+ id: ml.id,
+ role: ml.role,
+ content: ml.content,
+ extra_metadata: ml.extra_metadata,
+ cache_breakpoints: Vec::new(),
+ },
+ }
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/legacy_md.rs b/crates/openhuman-core/src/agent/harness/session/transcript/legacy_md.rs
new file mode 100644
index 0000000000..5428461fa9
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/session/transcript/legacy_md.rs
@@ -0,0 +1,139 @@
+//! Legacy HTML-comment `.md` transcript reader (one-release migration
+//! compat for sessions written before the JSONL source of truth).
+
+use super::types::{SessionTranscript, TranscriptMeta};
+use crate::agent::messages::ChatMessage;
+use anyhow::{Context, Result};
+use std::fs;
+use std::path::Path;
+
+/// Read a legacy HTML-comment `.md` transcript. Used as a fallback when
+/// only a `.md` exists (no `.jsonl` sibling).
+///
+/// Returns a `SessionTranscript` with whatever fields the `.md` tracked;
+/// fields the old format didn't carry are defaulted.
+pub fn read_transcript_legacy_md(path: &Path) -> Result<SessionTranscript> {
+ let raw = fs::read_to_string(path)
+ .with_context(|| format!("read legacy transcript {}", path.display()))?;
+
+ let meta = parse_legacy_meta(&raw)
+ .with_context(|| format!("parse legacy transcript meta in {}", path.display()))?;
+
+ let messages = parse_legacy_messages(&raw)
+ .with_context(|| format!("parse legacy transcript messages in {}", path.display()))?;
+
+ log::debug!(
+ "[transcript] loaded {} messages (legacy md) from {}",
+ messages.len(),
+ path.display()
+ );
+
+ Ok(SessionTranscript { meta, messages })
+}
+
+const LEGACY_MSG_OPEN_PREFIX: &str = "<!--MSG role=\"";
+const LEGACY_MSG_OPEN_SUFFIX: &str = "\"-->";
+const LEGACY_MSG_CLOSE: &str = "<!--/MSG-->";
+const LEGACY_MSG_CLOSE_ESCAPED: &str = "<!--\\/MSG-->";
+
+fn parse_legacy_meta(raw: &str) -> Result<TranscriptMeta> {
+ let header_start = raw
+ .find("<!-- session_transcript")
+ .context("missing session_transcript header")?;
+ let header_end = raw[header_start..]
+ .find("-->")
+ .context("unclosed session_transcript header")?;
+ let header = &raw[header_start..header_start + header_end + 3];
+
+ let get = |key: &str| -> Option<String> {
+ header.lines().find_map(|line| {
+ let line = line.trim();
+ if line.starts_with(&format!("{key}:")) {
+ Some(line[key.len() + 1..].trim().to_string())
+ } else {
+ None
+ }
+ })
+ };
+
+ Ok(TranscriptMeta {
+ agent_name: get("agent").unwrap_or_else(|| "unknown".into()),
+ dispatcher: get("dispatcher").unwrap_or_else(|| "native".into()),
+ agent_id: None,
+ agent_type: None,
+ provider: None,
+ model: None,
+ created: get("created").unwrap_or_default(),
+ updated: get("updated").unwrap_or_default(),
+ turn_count: get("turn_count").and_then(|s| s.parse().ok()).unwrap_or(0),
+ input_tokens: get("input_tokens")
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(0),
+ output_tokens: get("output_tokens")
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(0),
+ cached_input_tokens: get("cached_input_tokens")
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(0),
+ charged_amount_usd: get("charged_usd")
+ .and_then(|s| s.trim_start_matches('$').parse().ok())
+ .unwrap_or(0.0),
+ thread_id: get("thread_id").filter(|s| !s.is_empty()),
+ task_id: None,
+ })
+}
+
+fn parse_legacy_messages(raw: &str) -> Result<Vec<ChatMessage>> {
+ let mut messages = Vec::new();
+ let mut search_from = 0;
+
+ loop {
+ let Some(open_start) = raw[search_from..].find(LEGACY_MSG_OPEN_PREFIX) else {
+ break;
+ };
+ let open_start = search_from + open_start;
+ let after_prefix = open_start + LEGACY_MSG_OPEN_PREFIX.len();
+
+ let Some(role_end) = raw[after_prefix..].find(LEGACY_MSG_OPEN_SUFFIX) else {
+ break;
+ };
+ let role = raw[after_prefix..after_prefix + role_end].to_string();
+
+ let content_start = after_prefix + role_end + LEGACY_MSG_OPEN_SUFFIX.len();
+ let content_start = if raw[content_start..].starts_with('\n') {
+ content_start + 1
+ } else {
+ content_start
+ };
+
+ let close_tag = format!("\n{LEGACY_MSG_CLOSE}");
+ let Some(content_end_rel) = raw[content_start..].find(&close_tag) else {
+ let Some(content_end_rel) = raw[content_start..].find(LEGACY_MSG_CLOSE) else {
+ break;
+ };
+ let content = &raw[content_start..content_start + content_end_rel];
+ messages.push(ChatMessage {
+ id: None,
+ role,
+ content: content.replace(LEGACY_MSG_CLOSE_ESCAPED, LEGACY_MSG_CLOSE),
+ extra_metadata: None,
+ cache_breakpoints: Vec::new(),
+ });
+ search_from = content_start + content_end_rel + LEGACY_MSG_CLOSE.len();
+ continue;
+ };
+
+ let content = &raw[content_start..content_start + content_end_rel];
+ messages.push(ChatMessage {
+ id: None,
+ role,
+ content: content.replace(LEGACY_MSG_CLOSE_ESCAPED, LEGACY_MSG_CLOSE),
+ extra_metadata: None,
+ cache_breakpoints: Vec::new(),
+ });
+
+ search_from = content_start + content_end_rel + close_tag.len();
+ }
+
+ Ok(messages)
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/markdown.rs b/crates/openhuman-core/src/agent/harness/session/transcript/markdown.rs
new file mode 100644
index 0000000000..5be99cecd6
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/session/transcript/markdown.rs
@@ -0,0 +1,92 @@
+//! Human-readable markdown rendering of a transcript (the `.md` companion).
+
+use super::types::{TranscriptMeta, TurnUsage};
+use crate::agent::messages::ChatMessage;
+use std::collections::HashMap;
+use std::fmt::Write as FmtWrite;
+
+/// Render a human-readable markdown representation of the transcript.
+///
+/// This output is **for humans only** — it is never read back by the
+/// application. All resume / round-trip logic uses the JSONL source of truth.
+pub(super) fn render_markdown(
+ messages: &[ChatMessage],
+ meta: &TranscriptMeta,
+ per_message_usage: &HashMap<usize, &TurnUsage>,
+) -> String {
+ let mut buf = String::new();
+
+ let _ = writeln!(buf, "# Session transcript — {}", meta.agent_name);
+ buf.push('\n');
+ let _ = writeln!(buf, "- Dispatcher: {}", meta.dispatcher);
+ if let Some(agent_id) = meta.agent_id.as_deref() {
+ let _ = writeln!(buf, "- Agent ID: `{agent_id}`");
+ }
+ if let Some(agent_type) = meta.agent_type.as_deref() {
+ let _ = writeln!(buf, "- Agent type: `{agent_type}`");
+ }
+ if let Some(provider) = meta.provider.as_deref() {
+ let _ = writeln!(buf, "- Provider: `{provider}`");
+ }
+ if let Some(model) = meta.model.as_deref() {
+ let _ = writeln!(buf, "- Model: `{model}`");
+ }
+ if let Some(task_id) = meta.task_id.as_deref() {
+ let _ = writeln!(buf, "- Task: `{task_id}`");
+ }
+ if let Some(tid) = meta.thread_id.as_deref() {
+ let _ = writeln!(buf, "- Thread: `{tid}`");
+ }
+ let _ = writeln!(buf, "- Turns: {}", meta.turn_count);
+ if meta.input_tokens > 0 || meta.output_tokens > 0 {
+ let cache_pct = if meta.input_tokens > 0 {
+ (meta.cached_input_tokens as f64 / meta.input_tokens as f64) * 100.0
+ } else {
+ 0.0
+ };
+ let _ = writeln!(
+ buf,
+ "- Tokens: {} in / {} out / {} cached ({:.1}% hit)",
+ meta.input_tokens, meta.output_tokens, meta.cached_input_tokens, cache_pct
+ );
+ }
+ if meta.charged_amount_usd > 0.0 {
+ let _ = writeln!(buf, "- Charged: ${:.6}", meta.charged_amount_usd);
+ }
+ let _ = writeln!(buf, "- Updated: {}", meta.updated);
+
+ for (i, msg) in messages.iter().enumerate() {
+ buf.push_str("\n---\n\n");
+
+ if let Some(tu) = per_message_usage.get(&i) {
+ let _ = writeln!(
+ buf,
+ "## [{}] · {} · {} in / {} out / {} cached · ${:.6}",
+ msg.role,
+ tu.model,
+ tu.usage.input,
+ tu.usage.output,
+ tu.usage.cached_input,
+ tu.usage.cost_usd
+ );
+ if !tu.provider.is_empty() || tu.usage.context_window > 0 {
+ let _ = writeln!(
+ buf,
+ "_provider: `{}` · iteration: {} · context window: {}_",
+ tu.provider, tu.iteration, tu.usage.context_window
+ );
+ }
+ if let Some(reasoning) = tu.reasoning_content.as_deref().filter(|s| !s.is_empty()) {
+ let _ = writeln!(buf, "\n### Thoughts\n\n{reasoning}\n");
+ }
+ } else {
+ let _ = writeln!(buf, "## [{}]", msg.role);
+ }
+
+ buf.push('\n');
+ buf.push_str(&msg.content);
+ buf.push('\n');
+ }
+
+ buf
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/metadata.rs b/crates/openhuman-core/src/agent/harness/session/transcript/metadata.rs
new file mode 100644
index 0000000000..882a293ea6
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/session/transcript/metadata.rs
@@ -0,0 +1,114 @@
+//! `extra_metadata` side-channel keys on [`ChatMessage`]: turn usage /
+//! provenance and tool-failure markers that the turn loop stamps before
+//! persistence and the transcript writer lifts onto line fields.
+
+use super::types::TurnUsage;
+use crate::agent::messages::ChatMessage;
+
+const TURN_USAGE_METADATA_KEY: &str = "openhuman_turn_usage";
+
+/// `extra_metadata` key carrying a tool-result message's failure marker. The
+/// harness folds a tool result into a `role:"tool"` message that drops the
+/// per-call failure flag (`ToolResult::is_error`), so the turn loop re-attaches
+/// the outcome here — from the captured `ToolCallOutcome` side-channel — before
+/// persistence. `extra_metadata` is `#[serde(skip_serializing)]` on
+/// [`ChatMessage`], so this never reaches the provider; the transcript writer
+/// lifts it onto the additive [`MessageLine::failure`] / `failure_detail` line
+/// fields and strips it from the persisted `extra_metadata`.
+const TOOL_FAILURE_METADATA_KEY: &str = "openhuman_tool_failure";
+
+/// Stamp a tool-result [`ChatMessage`] with its failure outcome so the
+/// transcript writer can persist an explicit failure flag. `detail` is an
+/// optional short, single-line reason (e.g. the head of the error output).
+/// No-op semantics: pass this only for genuinely failed tool calls.
+pub(crate) fn attach_tool_failure_metadata(message: &mut ChatMessage, detail: Option<&str>) {
+ let mut payload = serde_json::Map::new();
+ payload.insert("failure".to_string(), serde_json::Value::Bool(true));
+ if let Some(detail) = detail.map(str::trim).filter(|s| !s.is_empty()) {
+ payload.insert(
+ "detail".to_string(),
+ serde_json::Value::String(detail.to_string()),
+ );
+ }
+ let marker = serde_json::Value::Object(payload);
+
+ match message.extra_metadata.take() {
+ Some(serde_json::Value::Object(mut map)) => {
+ map.insert(TOOL_FAILURE_METADATA_KEY.to_string(), marker);
+ message.extra_metadata = Some(serde_json::Value::Object(map));
+ }
+ Some(existing) => {
+ let mut map = serde_json::Map::new();
+ map.insert("value".to_string(), existing);
+ map.insert(TOOL_FAILURE_METADATA_KEY.to_string(), marker);
+ message.extra_metadata = Some(serde_json::Value::Object(map));
+ }
+ None => {
+ let mut map = serde_json::Map::new();
+ map.insert(TOOL_FAILURE_METADATA_KEY.to_string(), marker);
+ message.extra_metadata = Some(serde_json::Value::Object(map));
+ }
+ }
+}
+
+/// Pop the tool-failure marker out of a cloned `extra_metadata` map, returning
+/// `Some((true, detail))` when it was present. Strips the key so it is not
+/// duplicated into the persisted `extra_metadata` alongside the top-level
+/// `failure` line field. Legacy lines without the marker return `None`.
+pub(super) fn take_tool_failure(
+ extra: &mut Option<serde_json::Value>,
+) -> Option<(bool, Option<String>)> {
+ let serde_json::Value::Object(map) = extra.as_mut()? else {
+ return None;
+ };
+ let marker = map.remove(TOOL_FAILURE_METADATA_KEY)?;
+ // If removing the marker emptied the object, drop `extra_metadata` entirely
+ // so a legacy-identical line stays legacy-identical.
+ if map.is_empty() {
+ *extra = None;
+ }
+ let detail = marker
+ .get("detail")
+ .and_then(|d| d.as_str())
+ .map(str::to_string);
+ Some((true, detail))
+}
+
+pub(crate) fn attach_turn_usage_metadata(message: &mut ChatMessage, turn_usage: &TurnUsage) {
+ let Ok(payload) = serde_json::to_value(turn_usage) else {
+ log::warn!("[transcript] failed to serialize turn usage metadata");
+ return;
+ };
+
+ match message.extra_metadata.take() {
+ Some(serde_json::Value::Object(mut map)) => {
+ map.insert(TURN_USAGE_METADATA_KEY.to_string(), payload);
+ message.extra_metadata = Some(serde_json::Value::Object(map));
+ }
+ Some(existing) => {
+ let mut map = serde_json::Map::new();
+ map.insert("value".to_string(), existing);
+ map.insert(TURN_USAGE_METADATA_KEY.to_string(), payload);
+ message.extra_metadata = Some(serde_json::Value::Object(map));
+ }
+ None => {
+ let mut map = serde_json::Map::new();
+ map.insert(TURN_USAGE_METADATA_KEY.to_string(), payload);
+ message.extra_metadata = Some(serde_json::Value::Object(map));
+ }
+ }
+}
+
+pub(crate) fn turn_usage_extra_metadata(turn_usage: &TurnUsage) -> Option<serde_json::Value> {
+ let mut message = ChatMessage::assistant("");
+ attach_turn_usage_metadata(&mut message, turn_usage);
+ message.extra_metadata
+}
+
+pub(super) fn turn_usage_from_metadata(message: &ChatMessage) -> Option<TurnUsage> {
+ let payload = message
+ .extra_metadata
+ .as_ref()?
+ .get(TURN_USAGE_METADATA_KEY)?;
+ serde_json::from_value(payload.clone()).ok()
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/paths.rs b/crates/openhuman-core/src/agent/harness/session/transcript/paths.rs
new file mode 100644
index 0000000000..49c316cf08
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/session/transcript/paths.rs
@@ -0,0 +1,323 @@
+//! Transcript path resolution: the flat `session_raw/{stem}.jsonl` layout,
+//! the dated `.md` companion, legacy date-grouped fallbacks, and the
+//! newest-transcript scan used for resume.
+
+use anyhow::{Context, Result};
+use std::fs;
+use std::path::{Path, PathBuf};
+
+/// Resolve a transcript path under `session_raw/{stem}.jsonl` — a
+/// *flat* directory keyed only by stem. Used by the session-key flow:
+/// the stem is `"{unix_ts}_{agent_id}"` for a root session, or
+/// `"{parent_chain}__{session_key}"` for a sub-agent, so nested
+/// delegations still produce a single flat filename that encodes the
+/// parent → child path.
+///
+/// Creates the directory if needed. Overwrites are intentional: the
+/// `Agent` persists the same transcript file across every turn of a
+/// session, and every sub-agent spawn gets a unique timestamp in its
+/// own key so collisions are effectively impossible.
+pub fn resolve_keyed_transcript_path(workspace_dir: &Path, stem: &str) -> Result<PathBuf> {
+ let raw_dir = raw_session_dir(workspace_dir);
+ resolve_keyed_transcript_path_in_dir(&raw_dir, stem)
+}
+
+pub fn resolve_keyed_transcript_path_in_dir(raw_dir: &Path, stem: &str) -> Result<PathBuf> {
+ fs::create_dir_all(raw_dir)
+ .with_context(|| format!("create session_raw dir {}", raw_dir.display()))?;
+ let sanitized = sanitize_stem(stem);
+ Ok(raw_dir.join(format!("{sanitized}.jsonl")))
+}
+
+/// Sanitize a user-supplied transcript stem so it never escapes the
+/// `session_raw/` directory. Allows ASCII alphanumerics plus a small
+/// punctuation set (`_`, `-`, `.`); every other byte is replaced with
+/// `_`. Empty inputs fall back to `"session"`.
+fn sanitize_stem(stem: &str) -> String {
+ let cleaned: String = stem
+ .chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' {
+ c
+ } else {
+ '_'
+ }
+ })
+ .collect();
+ if cleaned.is_empty() {
+ "session".to_string()
+ } else {
+ cleaned
+ }
+}
+
+pub fn resolve_new_transcript_path(workspace_dir: &Path, agent_name: &str) -> Result<PathBuf> {
+ let raw_dir = raw_session_dir(workspace_dir);
+ fs::create_dir_all(&raw_dir)
+ .with_context(|| format!("create session_raw dir {}", raw_dir.display()))?;
+
+ let sanitized = sanitize_agent_name(agent_name);
+ let idx_raw = next_index(&raw_dir, &sanitized)?;
+ // Also consider today's md companion dir so a stale .md from this
+ // session doesn't cause an index collision when only .md exists.
+ let md_dir = today_md_session_dir(workspace_dir);
+ let idx_md = next_index(&md_dir, &sanitized)?;
+ let next_idx = idx_raw.max(idx_md);
+ let filename = format!("{}_{}.jsonl", sanitized, next_idx);
+
+ Ok(raw_dir.join(filename))
+}
+
+/// Find the most recent transcript for `agent_name`.
+///
+/// **Primary**: scan the flat `session_raw/` directory and pick the
+/// newest matching stem (root sessions only — sub-agents are skipped).
+/// **Fallback**: scan the legacy `session_raw/DDMMYYYY/` dirs (today
+/// and yesterday) and the legacy `sessions/DDMMYYYY/` markdown dirs so
+/// users upgrading from the date-grouped layout don't lose resume.
+/// The fallback is one-release transitional and can be removed once
+/// existing transcripts have rolled forward.
+pub fn find_latest_transcript(workspace_dir: &Path, agent_name: &str) -> Option<PathBuf> {
+ find_latest_transcript_in_subdir(workspace_dir, "session_raw", agent_name)
+}
+
+/// Find the most recent transcript inside a session's configured raw subtree.
+/// Scoped profile sessions must never fall back to shared transcripts; the
+/// legacy date-grouped/markdown fallback applies only to `session_raw`.
+pub fn find_latest_transcript_in_subdir(
+ workspace_dir: &Path,
+ session_raw_subdir: &str,
+ agent_name: &str,
+) -> Option<PathBuf> {
+ let sanitized = sanitize_agent_name(agent_name);
+ let raw_root = workspace_dir.join(session_raw_subdir);
+ let sessions_root = workspace_dir.join("sessions");
+
+ // Primary path: flat session_raw/ directory. The stem-suffix scan
+ // is naturally date-independent, so an idle thread resumes the same
+ // way today as it did weeks ago.
+ if raw_root.is_dir() {
+ if let Some(path) = latest_in_dir(&raw_root, &sanitized) {
+ return Some(path);
+ }
+ }
+
+ if session_raw_subdir != "session_raw" {
+ return None;
+ }
+
+ // Fallback: legacy date-grouped layout (one-release migration
+ // window). Today first, then yesterday — matches the previous
+ // behaviour so we don't regress while users still have files in
+ // the old structure.
+ let today = chrono::Local::now().format("%d%m%Y").to_string();
+ let yesterday = (chrono::Local::now() - chrono::Duration::days(1))
+ .format("%d%m%Y")
+ .to_string();
+
+ for date_str in [&today, &yesterday] {
+ let raw_dir = raw_root.join(date_str);
+ if raw_dir.is_dir() {
+ if let Some(path) = latest_in_dir(&raw_dir, &sanitized) {
+ return Some(path);
+ }
+ }
+ let legacy_dir = sessions_root.join(date_str);
+ if legacy_dir.is_dir() {
+ if let Some(path) = latest_in_dir(&legacy_dir, &sanitized) {
+ return Some(path);
+ }
+ }
+ }
+
+ None
+}
+
+/// Date-grouped directory for human-readable `.md` companions, e.g.
+/// `{workspace}/sessions/2026_05_02`. ISO-style `YYYY_MM_DD` so the
+/// listing sorts lexicographically by date.
+pub(super) fn today_md_session_dir(workspace_dir: &Path) -> PathBuf {
+ let date = chrono::Local::now().format("%Y_%m_%d").to_string();
+ workspace_dir.join("sessions").join(date)
+}
+
+/// Flat directory for the JSONL source of truth, e.g.
+/// `{workspace}/session_raw`. Stems start with `{unix_ts}` so the
+/// listing is naturally time-ordered without a date subdirectory.
+pub(super) fn raw_session_dir(workspace_dir: &Path) -> PathBuf {
+ workspace_dir.join("session_raw")
+}
+
+/// Given a `session_raw/{stem}.jsonl` path, derive the companion
+/// `sessions/YYYY_MM_DD/{stem}.md` path. The date is taken from the
+/// local clock at write time — fine for browsing because the source
+/// of truth lives in the flat raw dir; the `.md` is purely a view.
+///
+/// Legacy `session_raw/DDMMYYYY/{stem}.jsonl` paths (still on disk
+/// from older releases until they roll forward) keep their date
+/// component when generating the companion so we don't accidentally
+/// stamp old transcripts with today's date.
+///
+/// If no `session_raw` component is present (tests using a flat
+/// tempdir), the companion sits alongside as a sibling `.md`.
+pub(super) fn md_companion_path(jsonl_path: &Path) -> PathBuf {
+ let components: Vec<_> = jsonl_path.components().collect();
+
+ let raw_idx = components
+ .iter()
+ .position(|comp| matches!(comp, std::path::Component::Normal(s) if *s == "session_raw"));
+
+ let Some(raw_idx) = raw_idx else {
+ return jsonl_path.with_extension("md");
+ };
+
+ let mut out = PathBuf::new();
+ for comp in &components[..raw_idx] {
+ out.push(comp.as_os_str());
+ }
+ out.push("sessions");
+
+ // Tail after `session_raw`:
+ // * Flat: ["{stem}.jsonl"] — prepend today's YYYY_MM_DD.
+ // * Legacy: ["DDMMYYYY", "{stem}.jsonl"] — keep the existing
+ // date dir so we don't relabel old transcripts.
+ let tail = &components[raw_idx + 1..];
+ if tail.len() <= 1 {
+ out.push(chrono::Local::now().format("%Y_%m_%d").to_string());
+ }
+ for comp in tail {
+ out.push(comp.as_os_str());
+ }
+
+ out.with_extension("md")
+}
+
+pub(super) fn sanitize_agent_name(name: &str) -> String {
+ name.chars()
+ .map(|c| {
+ if c.is_alphanumeric() || c == '-' || c == '_' {
+ c
+ } else {
+ '_'
+ }
+ })
+ .collect()
+}
+
+/// Compute the next free index for `agent_prefix` in `dir`.
+///
+/// Considers both `.jsonl` and `.md` files so that indices stay unique
+/// during the one-release migration window when both extensions may exist.
+pub(super) fn next_index(dir: &Path, agent_prefix: &str) -> Result<usize> {
+ let prefix = format!("{}_", agent_prefix);
+ let mut max_idx: Option<usize> = None;
+
+ if let Ok(entries) = fs::read_dir(dir) {
+ for entry in entries.flatten() {
+ let name = entry.file_name();
+ let name = name.to_string_lossy();
+ if !name.starts_with(&prefix) {
+ continue;
+ }
+ // Accept both extensions.
+ let stem_end = if name.ends_with(".jsonl") {
+ name.len() - 6
+ } else if name.ends_with(".md") {
+ name.len() - 3
+ } else {
+ continue;
+ };
+ let idx_str = &name[prefix.len()..stem_end];
+ if let Ok(idx) = idx_str.parse::<usize>() {
+ max_idx = Some(max_idx.map_or(idx, |m: usize| m.max(idx)));
+ }
+ }
+ }
+
+ Ok(max_idx.map_or(0, |m| m + 1))
+}
+
+/// Find the latest transcript file for `agent_prefix` in `dir`.
+///
+/// Prefers `.jsonl` files; falls back to `.md` if no `.jsonl` exists
+/// (legacy sessions). When both exist for the same index the `.jsonl`
+/// wins.
+pub(super) fn latest_in_dir(dir: &Path, agent_prefix: &str) -> Option<PathBuf> {
+ // Two transcript-naming schemes coexist on disk:
+ // * Legacy: `{agent}_{index}.jsonl|.md` — strictly increasing
+ // index, used by the now-removed `resolve_new_transcript_path`.
+ // * Keyed: `{unix_ts}_{agent}.jsonl` (root session) or
+ // `{parent_chain}__{unix_ts}_{agent}.jsonl` (sub-agent). The
+ // root stem starts with `{unix_ts}_{agent}` and has no `__`
+ // prefix segment.
+ //
+ // For resume we only care about root sessions (sub-agents rebuild
+ // from scratch), so we scan for filenames matching either scheme
+ // and pick the newest. "Newest" is the largest sort key — indices
+ // and unix timestamps both order naturally as integers.
+ let legacy_prefix = format!("{}_", agent_prefix);
+ let keyed_suffix = format!("_{}", agent_prefix);
+ let mut best_jsonl: Option<(u64, PathBuf)> = None;
+ let mut best_md: Option<(u64, PathBuf)> = None;
+
+ let entries = fs::read_dir(dir).ok()?;
+ for entry in entries.flatten() {
+ let name = entry.file_name();
+ let name_str = name.to_string_lossy();
+ // Extract the stem minus extension.
+ let (stem, is_jsonl) = if let Some(s) = name_str.strip_suffix(".jsonl") {
+ (s, true)
+ } else if let Some(s) = name_str.strip_suffix(".md") {
+ (s, false)
+ } else {
+ continue;
+ };
+ // Skip sub-agent transcripts — they carry at least one `__`
+ // separator in their stem (e.g.
+ // `{orch_key}__{planner_key}`). Root resume never targets a
+ // sub-agent's transcript directly.
+ if stem.contains("__") {
+ continue;
+ }
+ // Determine sort key. Keyed filenames end with
+ // `_{agent_prefix}`: everything before that is the unix
+ // timestamp. Legacy filenames start with `{agent_prefix}_`:
+ // everything after is the numeric index.
+ let sort_key: u64 = if let Some(ts_part) = stem.strip_suffix(&keyed_suffix) {
+ match ts_part.parse::<u64>() {
+ Ok(ts) => ts,
+ Err(_) => continue,
+ }
+ } else if let Some(idx_part) = stem.strip_prefix(&legacy_prefix) {
+ match idx_part.parse::<u64>() {
+ Ok(idx) => idx,
+ Err(_) => continue,
+ }
+ } else {
+ continue;
+ };
+ let slot = if is_jsonl {
+ &mut best_jsonl
+ } else {
+ &mut best_md
+ };
+ if slot.as_ref().is_none_or(|(best, _)| sort_key > *best) {
+ *slot = Some((sort_key, entry.path()));
+ }
+ }
+
+ // Prefer the best .jsonl; fall back to .md if no .jsonl exists.
+ match (best_jsonl, best_md) {
+ (Some(jsonl), Some(md)) => {
+ // Take the one with the higher index; on a tie prefer .jsonl.
+ if md.0 > jsonl.0 {
+ Some(md.1)
+ } else {
+ Some(jsonl.1)
+ }
+ }
+ (Some(jsonl), None) => Some(jsonl.1),
+ (None, Some(md)) => Some(md.1),
+ (None, None) => None,
+ }
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/reader.rs b/crates/openhuman-core/src/agent/harness/session/transcript/reader.rs
new file mode 100644
index 0000000000..f5c868288a
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/session/transcript/reader.rs
@@ -0,0 +1,287 @@
+//! Transcript readers: the model-context replay ([`read_transcript`]), the
+//! display projection ([`read_transcript_display`]), and the cheap
+//! meta-only / last-usage scans used by thread summaries.
+
+use super::jsonl::{
+ classify_line, display_message_from_line, message_from_line, meta_from_payload, LineKind,
+ MetaLine,
+};
+use super::legacy_md::read_transcript_legacy_md;
+use super::types::{
+ CompactionMarker, DisplayRecord, DisplaySessionTranscript, MessageUsage, SessionTranscript,
+ TranscriptMeta,
+};
+use crate::agent::messages::ChatMessage;
+use anyhow::{Context, Result};
+use std::fs;
+use std::path::Path;
+
+/// Read a session transcript.
+///
+/// **Primary path**: reads the `.jsonl` source of truth.
+/// **Fallback**: if the `.jsonl` does not exist but the legacy `.md` does
+/// (migration path — old sessions), reads it via the legacy HTML-comment
+/// parser and returns a `SessionTranscript` with default meta where the
+/// `.md` format didn't track a field.
+pub fn read_transcript(path: &Path) -> Result<SessionTranscript> {
+ // Route by extension first: a legacy `.md` path (returned by
+ // `find_latest_transcript` when only legacy files exist) must go to
+ // the legacy parser, never to the JSONL parser.
+ if path.extension().and_then(|s| s.to_str()) == Some("md") {
+ log::debug!(
+ "[transcript] reading legacy .md transcript: {}",
+ path.display()
+ );
+ return read_transcript_legacy_md(path);
+ }
+
+ if path.exists() {
+ read_transcript_jsonl(path)
+ } else {
+ // Fallback: try the .md sibling (legacy one-release compat).
+ let md_path = path.with_extension("md");
+ if md_path.exists() {
+ log::debug!(
+ "[transcript] .jsonl not found, falling back to legacy .md: {}",
+ md_path.display()
+ );
+ read_transcript_legacy_md(&md_path)
+ } else {
+ // Neither exists — propagate the original jsonl error.
+ read_transcript_jsonl(path)
+ }
+ }
+}
+
+fn read_transcript_jsonl(path: &Path) -> Result<SessionTranscript> {
+ let raw = fs::read_to_string(path)
+ .with_context(|| format!("read transcript jsonl {}", path.display()))?;
+
+ let mut meta: Option<TranscriptMeta> = None;
+ let mut messages: Vec<ChatMessage> = Vec::new();
+ let mut compactions_replayed = 0usize;
+ let mut interrupted_skipped = 0usize;
+
+ // Append-only log replay (Phase A): the first non-empty line MUST be the
+ // `_meta` header; subsequent lines are messages, `compaction` records
+ // (which *replace* the accumulated context), interrupted partials (skipped
+ // for the model-context path), or refreshed `_meta` lines (last wins).
+ let mut seen_first = false;
+ for (line_no, line) in raw.lines().enumerate() {
+ let line = line.trim();
+ if line.is_empty() {
+ continue;
+ }
+
+ if !seen_first {
+ seen_first = true;
+ let ml: MetaLine = serde_json::from_str(line).map_err(|err| {
+ anyhow::anyhow!(
+ "first non-empty line of {} (line {}) is not a valid _meta object: {err}",
+ path.display(),
+ line_no + 1,
+ )
+ })?;
+ meta = Some(meta_from_payload(ml.meta));
+ continue;
+ }
+
+ match classify_line(line) {
+ Ok(LineKind::Meta(ml)) => {
+ // Refreshed cumulative meta — last one wins.
+ meta = Some(meta_from_payload(ml.meta));
+ }
+ Ok(LineKind::Compaction(cl)) => {
+ // Reduction record: the reduced context REPLACES everything
+ // accumulated so far, exactly reproducing the old full-rewrite.
+ let replacement: Vec<ChatMessage> =
+ cl.replacement.into_iter().map(message_from_line).collect();
+ log::debug!(
+ "[transcript] replay: compaction at line {} replaces {} accumulated message(s) with {} (request_id={:?}) in {}",
+ line_no + 1,
+ messages.len(),
+ replacement.len(),
+ cl.request_id,
+ path.display()
+ );
+ messages = replacement;
+ compactions_replayed += 1;
+ }
+ Ok(LineKind::Message(ml)) => {
+ if ml.interrupted {
+ // Display-only partial — never part of the model context.
+ interrupted_skipped += 1;
+ log::debug!(
+ "[transcript] replay: skipping interrupted partial line {} (display only) in {}",
+ line_no + 1,
+ path.display()
+ );
+ continue;
+ }
+ messages.push(message_from_line(ml));
+ }
+ Err(err) => {
+ log::warn!(
+ "[transcript] skipping malformed/unknown record line {} in {}: {err}",
+ line_no + 1,
+ path.display()
+ );
+ }
+ }
+ }
+
+ let meta = meta.with_context(|| {
+ format!(
+ "missing _meta header line in jsonl transcript {}",
+ path.display()
+ )
+ })?;
+
+ log::debug!(
+ "[transcript] loaded {} messages (jsonl, {} compaction(s) replayed, {} interrupted skipped) from {}",
+ messages.len(),
+ compactions_replayed,
+ interrupted_skipped,
+ path.display()
+ );
+
+ Ok(SessionTranscript { meta, messages })
+}
+
+/// Read a transcript for **display**: returns *every* record in file order,
+/// including pre-compaction history, compaction markers, and interrupted
+/// partials — the counterpart to the model-context [`read_transcript`], which
+/// collapses the log into the reduced context.
+///
+/// `meta` reflects the newest `_meta` line (cumulative totals stay current).
+pub fn read_transcript_display(path: &Path) -> Result<DisplaySessionTranscript> {
+ let raw = fs::read_to_string(path)
+ .with_context(|| format!("read transcript jsonl (display) {}", path.display()))?;
+
+ let mut meta: Option<TranscriptMeta> = None;
+ let mut records: Vec<DisplayRecord> = Vec::new();
+ let mut seen_first = false;
+
+ for (line_no, line) in raw.lines().enumerate() {
+ let line = line.trim();
+ if line.is_empty() {
+ continue;
+ }
+ if !seen_first {
+ seen_first = true;
+ let ml: MetaLine = serde_json::from_str(line).map_err(|err| {
+ anyhow::anyhow!(
+ "first non-empty line of {} (line {}) is not a valid _meta object: {err}",
+ path.display(),
+ line_no + 1,
+ )
+ })?;
+ meta = Some(meta_from_payload(ml.meta));
+ continue;
+ }
+ match classify_line(line) {
+ Ok(LineKind::Meta(ml)) => meta = Some(meta_from_payload(ml.meta)),
+ Ok(LineKind::Compaction(cl)) => {
+ let replacement = cl
+ .replacement
+ .into_iter()
+ .map(display_message_from_line)
+ .collect();
+ records.push(DisplayRecord::Compaction(CompactionMarker {
+ replacement,
+ ts: cl.ts,
+ request_id: cl.request_id,
+ }));
+ }
+ Ok(LineKind::Message(ml)) => {
+ records.push(DisplayRecord::Message(display_message_from_line(ml)));
+ }
+ Err(err) => {
+ log::warn!(
+ "[transcript] display: skipping malformed/unknown record line {} in {}: {err}",
+ line_no + 1,
+ path.display()
+ );
+ }
+ }
+ }
+
+ let meta = meta.with_context(|| {
+ format!(
+ "missing _meta header line in jsonl transcript {}",
+ path.display()
+ )
+ })?;
+
+ log::debug!(
+ "[transcript] display-loaded {} record(s) from {}",
+ records.len(),
+ path.display()
+ );
+
+ Ok(DisplaySessionTranscript { meta, records })
+}
+
+/// Parse the authoritative `_meta` of a root transcript JSONL.
+///
+/// Append-only files carry the immutable header on line 1 plus a refreshed
+/// `_meta` line per turn (cumulative totals). The **last** `_meta` line wins,
+/// so a multi-turn session reports its running totals — not just the first
+/// turn's. Falls back to line 1 for legacy single-header files.
+pub(super) fn read_transcript_meta_only(path: &Path) -> Option<TranscriptMeta> {
+ let raw = fs::read_to_string(path).ok()?;
+ let mut latest: Option<TranscriptMeta> = None;
+ for line in raw.lines() {
+ let line = line.trim();
+ if line.is_empty() {
+ continue;
+ }
+ if let Ok(ml) = serde_json::from_str::<MetaLine>(line) {
+ latest = Some(meta_from_payload(ml.meta));
+ } else if latest.is_none() {
+ // The first non-empty line must be a valid meta header.
+ return None;
+ }
+ }
+ latest
+}
+
+/// Extract the last assistant message's usage + model from a transcript JSONL.
+/// Only the final assistant message of a turn carries these (see the JSONL
+/// format docs at the top of this module). Compaction records and refreshed
+/// `_meta` lines are skipped; a `compaction` record's `replacement` assistant
+/// rows are considered so a compacted transcript still surfaces its latest
+/// usage.
+pub(super) fn read_last_assistant_usage(path: &Path) -> Option<(MessageUsage, Option<String>)> {
+ let raw = fs::read_to_string(path).ok()?;
+ let mut result = None;
+ let mut seen_first = false;
+ for line in raw.lines() {
+ let line = line.trim();
+ if line.is_empty() {
+ continue;
+ }
+ if !seen_first {
+ seen_first = true; // first non-empty line is the `_meta` header
+ continue;
+ }
+ match classify_line(line) {
+ Ok(LineKind::Message(ml)) if ml.role == "assistant" && !ml.interrupted => {
+ if let Some(usage) = ml.usage {
+ result = Some((usage, ml.model));
+ }
+ }
+ Ok(LineKind::Compaction(cl)) => {
+ for ml in &cl.replacement {
+ if ml.role == "assistant" {
+ if let Some(usage) = ml.usage.clone() {
+ result = Some((usage, ml.model.clone()));
+ }
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ result
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/thread_lookup.rs b/crates/openhuman-core/src/agent/harness/session/transcript/thread_lookup.rs
new file mode 100644
index 0000000000..abbc99d53c
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/session/transcript/thread_lookup.rs
@@ -0,0 +1,211 @@
+//! Thread-keyed lookups over the `session_raw*` stores: locating a thread's
+//! root transcripts and summing its token / cost usage.
+
+use super::paths::raw_session_dir;
+use super::reader::{read_last_assistant_usage, read_transcript, read_transcript_meta_only};
+use super::types::{SubagentArchetypeUsage, ThreadUsageSummary};
+use std::collections::BTreeMap;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+/// Find the newest root transcript whose metadata declares `thread_id`, across
+/// the shared `session_raw/` store and every profile-scoped
+/// `session_raw-<id>/` store.
+///
+/// Root transcripts live directly under `session_raw/` and do not carry
+/// the `__` separator used for sub-agent siblings. This helper is the
+/// bridge PR-2 can use to route UI thread reads to the canonical root
+/// transcript without accidentally folding delegated worker transcripts
+/// into the main chat timeline.
+pub fn find_root_transcript_for_thread(workspace_dir: &Path, thread_id: &str) -> Option<PathBuf> {
+ find_root_transcripts_for_thread(workspace_dir, thread_id).pop()
+}
+
+pub fn find_root_transcripts_for_thread(workspace_dir: &Path, thread_id: &str) -> Vec<PathBuf> {
+ let mut matches = Vec::new();
+ for raw_dir in raw_session_dirs(workspace_dir) {
+ matches.extend(root_transcripts_for_thread_in_dir(&raw_dir, thread_id));
+ }
+ // Already chronological within each directory (see
+ // `root_transcripts_for_thread_in_dir`); re-key across directories on the
+ // same `created` stamp rather than the file name.
+ matches.sort_by_cached_key(|path| {
+ let created = read_transcript(path)
+ .ok()
+ .map(|transcript| transcript.meta.created)
+ .unwrap_or_default();
+ (created, path.clone())
+ });
+ matches
+}
+
+fn raw_session_dirs(workspace_dir: &Path) -> Vec<PathBuf> {
+ let mut raw_dirs = vec![raw_session_dir(workspace_dir)];
+ if let Ok(entries) = fs::read_dir(workspace_dir) {
+ raw_dirs.extend(entries.flatten().map(|entry| entry.path()).filter(|path| {
+ path.is_dir()
+ && path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .is_some_and(|name| {
+ name.strip_prefix("session_raw-")
+ .is_some_and(|suffix| !suffix.is_empty())
+ })
+ }));
+ }
+ raw_dirs.sort();
+ raw_dirs
+}
+
+pub fn find_root_transcript_for_thread_in_dir(raw_dir: &Path, thread_id: &str) -> Option<PathBuf> {
+ root_transcripts_for_thread_in_dir(raw_dir, thread_id).pop()
+}
+
+fn root_transcripts_for_thread_in_dir(raw_dir: &Path, thread_id: &str) -> Vec<PathBuf> {
+ let thread_id = thread_id.trim();
+ if thread_id.is_empty() {
+ return Vec::new();
+ }
+
+ let Ok(entries) = fs::read_dir(raw_dir) else {
+ return Vec::new();
+ };
+ // Keyed by `meta.created` so the order is chronological rather than
+ // lexicographic. Modern stems are `{unix_ts}_{agent_id}` and sort the same
+ // either way, but a legacy `{agent}_{index}` root encodes no time at all —
+ // and because digits sort before letters, every legacy root sorted *after*
+ // every modern one regardless of when it was written. `project_from_files`
+ // concatenates these in order, so that reordered the rendered view and
+ // could attach a sub-agent trail to the wrong turn.
+ let mut matches: Vec<(String, PathBuf)> = entries
+ .flatten()
+ .map(|entry| entry.path())
+ .filter(|path| {
+ path.extension().and_then(|s| s.to_str()) == Some("jsonl")
+ && path
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .is_some_and(|stem| !stem.contains("__"))
+ })
+ .filter_map(|path| match read_transcript(&path) {
+ Ok(transcript) if transcript.meta.thread_id.as_deref() == Some(thread_id) => {
+ Some((transcript.meta.created.clone(), path))
+ }
+ Ok(_) => None,
+ Err(err) => {
+ log::warn!(
+ "[transcript] skipping unreadable root transcript candidate {}: {err}",
+ path.display()
+ );
+ None
+ }
+ })
+ .collect();
+
+ // Path is the tiebreak so the order stays total and deterministic when two
+ // transcripts share a `created` stamp.
+ matches.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1)));
+ matches.into_iter().map(|(_, path)| path).collect()
+}
+
+/// Summed token/cost usage for `thread_id` across its root transcripts, or
+/// `None` when the thread has no persisted turns yet.
+pub fn read_thread_usage_summary(
+ workspace_dir: &Path,
+ thread_id: &str,
+) -> Option<ThreadUsageSummary> {
+ let thread_id = thread_id.trim();
+ if thread_id.is_empty() {
+ return None;
+ }
+
+ // Single scan: split the thread's transcripts into root (orchestrator) and
+ // `__` sub-agent files. Root totals stay the parent's; sub-agent files are
+ // grouped by archetype for the per-agent breakdown.
+ let mut root_matches: Vec<PathBuf> = Vec::new();
+ let mut sub_matches: Vec<PathBuf> = Vec::new();
+ for raw_dir in raw_session_dirs(workspace_dir) {
+ let Ok(entries) = fs::read_dir(&raw_dir) else {
+ continue;
+ };
+ for path in entries.flatten().map(|entry| entry.path()) {
+ if path.extension().and_then(|s| s.to_str()) != Some("jsonl") {
+ continue;
+ }
+ let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
+ continue;
+ };
+ let is_subagent = stem.contains("__");
+ let matches_thread = read_transcript_meta_only(&path)
+ .map(|m| m.thread_id.as_deref() == Some(thread_id))
+ .unwrap_or(false);
+ if !matches_thread {
+ continue;
+ }
+ if is_subagent {
+ sub_matches.push(path);
+ } else {
+ root_matches.push(path);
+ }
+ }
+ }
+
+ if root_matches.is_empty() && sub_matches.is_empty() {
+ return None;
+ }
+ root_matches.sort_by(|left, right| left.file_name().cmp(&right.file_name()));
+
+ let mut summary = ThreadUsageSummary::default();
+ for path in &root_matches {
+ if let Some(meta) = read_transcript_meta_only(path) {
+ summary.input_tokens = summary.input_tokens.saturating_add(meta.input_tokens);
+ summary.output_tokens = summary.output_tokens.saturating_add(meta.output_tokens);
+ summary.cached_input_tokens = summary
+ .cached_input_tokens
+ .saturating_add(meta.cached_input_tokens);
+ summary.cost_usd += meta.charged_amount_usd;
+ summary.turn_count = summary.turn_count.saturating_add(meta.turn_count);
+ }
+ }
+
+ // Newest root transcript drives the last-turn gauge + model + updated stamp.
+ if let Some(newest) = root_matches.last() {
+ if let Some(meta) = read_transcript_meta_only(newest) {
+ summary.updated = meta.updated;
+ }
+ if let Some((usage, model)) = read_last_assistant_usage(newest) {
+ summary.last_turn_input_tokens = usage.input;
+ summary.last_turn_output_tokens = usage.output;
+ summary.model = model;
+ }
+ }
+
+ // Group sub-agent transcripts by archetype (`agent_name`).
+ let mut groups: BTreeMap<String, SubagentArchetypeUsage> = BTreeMap::new();
+ for path in &sub_matches {
+ let Some(meta) = read_transcript_meta_only(path) else {
+ continue;
+ };
+ let group =
+ groups
+ .entry(meta.agent_name.clone())
+ .or_insert_with(|| SubagentArchetypeUsage {
+ agent_id: meta.agent_name.clone(),
+ ..Default::default()
+ });
+ group.input_tokens = group.input_tokens.saturating_add(meta.input_tokens);
+ group.output_tokens = group.output_tokens.saturating_add(meta.output_tokens);
+ group.cached_input_tokens = group
+ .cached_input_tokens
+ .saturating_add(meta.cached_input_tokens);
+ group.runs = group.runs.saturating_add(1);
+ if group.model.is_none() {
+ if let Some((_, model)) = read_last_assistant_usage(path) {
+ group.model = model;
+ }
+ }
+ }
+ summary.subagents = groups.into_values().collect();
+
+ Some(summary)
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/types.rs b/crates/openhuman-core/src/agent/harness/session/transcript/types.rs
new file mode 100644
index 0000000000..7f91b8d462
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/session/transcript/types.rs
@@ -0,0 +1,192 @@
+//! Public transcript domain types: per-message usage, the `_meta` header,
+//! the model-context and display projections, and thread usage summaries.
+
+use crate::agent::messages::ChatMessage;
+use crate::inference::provider::ToolCall;
+use serde::{Deserialize, Serialize};
+
+/// Per-message usage figures attributed to the last assistant turn.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MessageUsage {
+ pub input: u64,
+ pub output: u64,
+ pub cached_input: u64,
+ #[serde(default)]
+ pub context_window: u64,
+ pub cost_usd: f64,
+}
+
+/// Usage + provenance for one provider response, attached to the last
+/// assistant message in a turn.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TurnUsage {
+ #[serde(default)]
+ pub provider: String,
+ #[serde(default)]
+ pub model: String,
+ pub usage: MessageUsage,
+ /// RFC-3339 timestamp of the response.
+ #[serde(default)]
+ pub ts: String,
+ /// Raw reasoning/thinking content returned by thinking models. This is
+ /// persisted as metadata so the later transcript view can show the model's
+ /// thoughts without depending on the live stream still being open.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub reasoning_content: Option<String>,
+ /// Native tool calls emitted in this provider response, if any. Text-mode
+ /// calls remain present in `content` as the raw markup the model emitted.
+ #[serde(default)]
+ pub tool_calls: Vec<ToolCall>,
+ /// One-based engine iteration for this provider response.
+ #[serde(default)]
+ pub iteration: u32,
+}
+
+/// Schema version stamped on the `_meta` header line. Bumped when the JSONL
+/// record shape changes in a way future readers may need to branch on. `0`
+/// (absent) denotes pre-append-only files written before this field existed.
+pub const TRANSCRIPT_SCHEMA_VERSION: u32 = 1;
+
+/// Metadata header for a session transcript file.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TranscriptMeta {
+ pub agent_name: String,
+ /// Canonical registry id for the agent that produced this transcript.
+ /// `agent_name` may be per-thread renamed for file names; this remains the
+ /// stable archetype id when available.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub agent_id: Option<String>,
+ /// Coarse runtime kind (`root`, `subagent`, `extractor`, ...).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub agent_type: Option<String>,
+ pub dispatcher: String,
+ /// Provider label used for the most recent recorded response.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub provider: Option<String>,
+ /// Model id used for the most recent recorded response.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub model: Option<String>,
+ pub created: String,
+ pub updated: String,
+ pub turn_count: usize,
+ /// Cumulative input tokens across all provider calls this session.
+ pub input_tokens: u64,
+ /// Cumulative output tokens across all provider calls this session.
+ pub output_tokens: u64,
+ /// Cumulative input tokens served from the KV cache.
+ pub cached_input_tokens: u64,
+ /// Cumulative amount charged in USD.
+ pub charged_amount_usd: f64,
+ /// Backend-side LLM thread identifier (the `thread_id` forwarded on
+ /// `/openai/v1/chat/completions` so the OpenHuman backend can group
+ /// `InferenceLog` entries and align KV-cache keys with the same logical
+ /// chat thread the user sees in the UI). `None` for runs that don't
+ /// originate from a thread-scoped channel (e.g. CLI-only sessions).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub thread_id: Option<String>,
+ /// Sub-agent task id, when this transcript belongs to a spawned worker.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub task_id: Option<String>,
+}
+
+/// A parsed session transcript: metadata + exact message array.
+#[derive(Debug, Clone)]
+pub struct SessionTranscript {
+ pub meta: TranscriptMeta,
+ pub messages: Vec<ChatMessage>,
+}
+
+// ── Display read types ───────────────────────────────────────────────
+
+/// One message in a display projection, carrying the turn-boundary + partial
+/// flags the model-context [`SessionTranscript`] discards.
+#[derive(Debug, Clone)]
+pub struct DisplayMessage {
+ pub message: ChatMessage,
+ /// `true` when this is an interrupted partial answer (display only).
+ pub interrupted: bool,
+ /// Turn boundary marker (`request_id`), when stamped.
+ pub request_id: Option<String>,
+ pub iteration: Option<u32>,
+ pub ts: Option<String>,
+ /// Usage/provenance for assistant messages that carried it.
+ pub turn_usage: Option<TurnUsage>,
+ /// Raw reasoning/thinking captured for this line, when present. Mirrors the
+ /// line's `reasoning_content` directly so it survives even on lines without
+ /// full turn-usage provenance (e.g. an interrupted partial, which carries no
+ /// provider/model/usage). Prefer this over digging into [`Self::turn_usage`]
+ /// for display: it is populated from `turn_usage.reasoning_content` too.
+ pub reasoning_content: Option<String>,
+ /// `true` when this is a **failed** tool-result line (`ToolResult::is_error`
+ /// at execution time). The display projection renders an error tool row
+ /// instead of success. Always `false` for non-tool lines and legacy files.
+ pub failure: bool,
+ /// Optional short reason for a failed tool call (present only with
+ /// `failure: true`).
+ pub failure_detail: Option<String>,
+}
+
+/// A compaction marker in a display projection.
+#[derive(Debug, Clone)]
+pub struct CompactionMarker {
+ /// The reduced message set this compaction installed as the new context.
+ pub replacement: Vec<DisplayMessage>,
+ pub ts: Option<String>,
+ pub request_id: Option<String>,
+}
+
+/// One record in a display projection, in file order.
+#[derive(Debug, Clone)]
+pub enum DisplayRecord {
+ Message(DisplayMessage),
+ Compaction(CompactionMarker),
+}
+
+/// A display projection of a transcript: **all** records, including
+/// pre-compaction history, compaction markers, and interrupted partials.
+#[derive(Debug, Clone)]
+pub struct DisplaySessionTranscript {
+ pub meta: TranscriptMeta,
+ pub records: Vec<DisplayRecord>,
+}
+
+/// Aggregated token/cost usage for a chat thread, summed across **all** of the
+/// thread's root session transcripts (a thread reopened across days/restarts
+/// produces several files). `last_turn_*`, `model`, and `updated` come from the
+/// newest transcript so the UI can render a context-window gauge for the most
+/// recent turn. Returns `None` when no transcript exists yet (a brand-new
+/// thread with no completed turns).
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct ThreadUsageSummary {
+ /// Orchestrator (parent) token totals — the root transcript(s) only. Root
+ /// transcripts never include sub-agent calls (those go to a separate
+ /// observer + their own `__` transcript files); see [`Self::subagents`].
+ pub input_tokens: u64,
+ pub output_tokens: u64,
+ pub cached_input_tokens: u64,
+ pub cost_usd: f64,
+ pub turn_count: usize,
+ /// Input/output tokens of the most recent assistant turn (context gauge).
+ pub last_turn_input_tokens: u64,
+ pub last_turn_output_tokens: u64,
+ /// Model that served the most recent turn, if recorded.
+ pub model: Option<String>,
+ /// RFC-3339 `updated` of the newest transcript.
+ pub updated: String,
+ /// Per-archetype sub-agent spend, reconstructed from the thread's `__`
+ /// sub-agent transcripts (grouped by `agent_name`).
+ pub subagents: Vec<SubagentArchetypeUsage>,
+}
+
+/// One sub-agent archetype's summed spend within a thread (e.g. all `coder`
+/// runs). `model` is the model that served one of its runs, used to price it.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct SubagentArchetypeUsage {
+ pub agent_id: String,
+ pub input_tokens: u64,
+ pub output_tokens: u64,
+ pub cached_input_tokens: u64,
+ /// How many sub-agent runs of this archetype contributed.
+ pub runs: usize,
+ pub model: Option<String>,
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/writer.rs b/crates/openhuman-core/src/agent/harness/session/transcript/writer.rs
new file mode 100644
index 0000000000..57c54cc036
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/session/transcript/writer.rs
@@ -0,0 +1,292 @@
+//! Transcript writers: the one-shot full rewrite, the append-only per-turn
+//! delta (message tail or compaction record), interrupted partials, and the
+//! derived `.md` companion.
+
+use super::jsonl::{
+ build_message_line, meta_line_json, serialise_message_lines, CompactionLine, MessageLine,
+ COMPACTION_KIND,
+};
+use super::markdown::render_markdown;
+use super::metadata::turn_usage_from_metadata;
+use super::paths::md_companion_path;
+use super::types::{TranscriptMeta, TurnUsage};
+use crate::agent::messages::ChatMessage;
+use anyhow::{Context, Result};
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+/// Write JSONL as source of truth **and** re-render the companion `.md`.
+///
+/// `jsonl_path` must end in `.jsonl`; the `.md` companion is derived by
+/// swapping the extension. **Full rewrite** on every call — this is the
+/// one-shot writer used by migrations, the sub-agent runners, and tests.
+/// The incremental session-persistence path uses [`append_transcript_turn`]
+/// instead, which never rewrites existing lines.
+pub fn write_transcript(
+ jsonl_path: &Path,
+ messages: &[ChatMessage],
+ meta: &TranscriptMeta,
+ last_assistant_turn_usage: Option<&TurnUsage>,
+) -> Result<()> {
+ if let Some(parent) = jsonl_path.parent() {
+ fs::create_dir_all(parent)
+ .with_context(|| format!("create transcript dir {}", parent.display()))?;
+ }
+
+ // ── JSONL ────────────────────────────────────────────────────────
+ let mut jsonl_buf = String::new();
+ jsonl_buf.push_str(&meta_line_json(meta)?);
+ jsonl_buf.push('\n');
+ serialise_message_lines(messages, last_assistant_turn_usage, None, &mut jsonl_buf)?;
+
+ fs::write(jsonl_path, jsonl_buf.as_bytes())
+ .with_context(|| format!("write transcript {}", jsonl_path.display()))?;
+
+ log::debug!(
+ "[transcript] wrote {} messages (jsonl, full rewrite) to {}",
+ messages.len(),
+ jsonl_path.display()
+ );
+
+ render_md_companion(jsonl_path, messages, meta, last_assistant_turn_usage);
+ Ok(())
+}
+
+/// Append this turn's delta to an **append-only** transcript, never rewriting
+/// existing lines.
+///
+/// `prev_persisted` is the logical message set the previous call left on disk
+/// (empty on the first call for a fresh file). The incoming `messages` is the
+/// current full logical set for this turn:
+///
+/// - **Pure extension** (`prev_persisted` is a prefix of `messages`): only the
+/// new tail is appended as message lines.
+/// - **Reduction / rewrite** (context reduction changed or dropped earlier
+/// turns): a single `compaction` record carrying the full reduced
+/// `messages` is appended; earlier lines are left untouched on disk.
+///
+/// A fresh `_meta` line is appended so cumulative totals stay current without a
+/// full rewrite. The `.md` companion is re-rendered from `messages` (derived
+/// view — always the reduced/current set). Returns nothing; the caller updates
+/// its tracked `prev_persisted` to `messages` on success.
+///
+/// `request_id` (when available from the web-chat path) is stamped on every
+/// appended line as a turn boundary marker.
+pub fn append_transcript_turn(
+ jsonl_path: &Path,
+ prev_persisted: &[ChatMessage],
+ messages: &[ChatMessage],
+ meta: &TranscriptMeta,
+ turn_usage: Option<&TurnUsage>,
+ request_id: Option<&str>,
+) -> Result<()> {
+ if let Some(parent) = jsonl_path.parent() {
+ fs::create_dir_all(parent)
+ .with_context(|| format!("create transcript dir {}", parent.display()))?;
+ }
+
+ let file_exists = jsonl_path.exists();
+
+ // First write for this file: create it with meta + all message lines.
+ if !file_exists {
+ let mut buf = String::new();
+ buf.push_str(&meta_line_json(meta)?);
+ buf.push('\n');
+ serialise_message_lines(messages, turn_usage, request_id, &mut buf)?;
+ fs::write(jsonl_path, buf.as_bytes())
+ .with_context(|| format!("create transcript {}", jsonl_path.display()))?;
+ log::debug!(
+ "[transcript] created append-only transcript with {} message(s) at {}",
+ messages.len(),
+ jsonl_path.display()
+ );
+ render_md_companion(jsonl_path, messages, meta, turn_usage);
+ return Ok(());
+ }
+
+ // Subsequent writes: diff against the previously-persisted logical set.
+ let common = common_prefix_len(prev_persisted, messages);
+ let mut buf = String::new();
+
+ if common == prev_persisted.len() {
+ // Pure extension — append only the new tail.
+ let tail = &messages[common..];
+ log::debug!(
+ "[transcript] append: extending on-disk set (prev={}, new={}, appending {} tail line(s)) {}",
+ prev_persisted.len(),
+ messages.len(),
+ tail.len(),
+ jsonl_path.display()
+ );
+ serialise_message_lines(tail, turn_usage, request_id, &mut buf)?;
+ } else {
+ // Reduction / rewrite — the on-disk set is no longer a prefix. Append a
+ // compaction record carrying the full reduced context so the
+ // model-context reader can replay it, without destroying earlier lines.
+ log::debug!(
+ "[transcript] append: context reduced (prev={}, new={}, common_prefix={}) — writing compaction record {}",
+ prev_persisted.len(),
+ messages.len(),
+ common,
+ jsonl_path.display()
+ );
+ let last_assistant_idx = messages.iter().rposition(|m| m.role == "assistant");
+ let replacement: Vec<MessageLine> = messages
+ .iter()
+ .enumerate()
+ .map(|(i, msg)| {
+ let tu = if Some(i) == last_assistant_idx {
+ turn_usage
+ .cloned()
+ .or_else(|| turn_usage_from_metadata(msg))
+ } else {
+ turn_usage_from_metadata(msg)
+ };
+ build_message_line(msg, tu.as_ref(), request_id, false)
+ })
+ .collect();
+ let compaction = CompactionLine {
+ kind: COMPACTION_KIND.to_string(),
+ replacement,
+ ts: Some(chrono::Utc::now().to_rfc3339()),
+ request_id: request_id.map(str::to_string),
+ _extra: HashMap::new(),
+ };
+ let line = serde_json::to_string(&compaction).context("serialise compaction record")?;
+ buf.push_str(&line);
+ buf.push('\n');
+ }
+
+ // Refresh cumulative meta by appending a new `_meta` line (readers take the
+ // last one). Keeps append-only + O(1)-per-turn (no full-file rewrite).
+ buf.push_str(&meta_line_json(meta)?);
+ buf.push('\n');
+
+ append_bytes(jsonl_path, buf.as_bytes())?;
+ render_md_companion(jsonl_path, messages, meta, turn_usage);
+ Ok(())
+}
+
+/// Append a partial assistant answer, flagged `interrupted: true`, captured
+/// when a streaming turn was cancelled/interrupted before completion.
+///
+/// **Display only**: the model-context reader skips interrupted lines, so a
+/// resumed context never carries a truncated answer. Does not affect the
+/// caller's tracked `prev_persisted` (nothing about the logical model context
+/// changed). No-op when `partial_content` is empty.
+pub fn append_interrupted_partial(
+ jsonl_path: &Path,
+ partial_content: &str,
+ request_id: Option<&str>,
+ iteration: Option<u32>,
+ reasoning_content: Option<&str>,
+) -> Result<()> {
+ if partial_content.is_empty() {
+ return Ok(());
+ }
+ if let Some(parent) = jsonl_path.parent() {
+ fs::create_dir_all(parent)
+ .with_context(|| format!("create transcript dir {}", parent.display()))?;
+ }
+ let mut line = build_message_line(
+ &ChatMessage::assistant(partial_content),
+ None,
+ request_id,
+ true,
+ );
+ line.iteration = iteration;
+ line.reasoning_content = reasoning_content
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ line.ts = Some(chrono::Utc::now().to_rfc3339());
+ let mut buf = serde_json::to_string(&line).context("serialise interrupted partial line")?;
+ buf.push('\n');
+ append_bytes(jsonl_path, buf.as_bytes())?;
+ log::debug!(
+ "[transcript] appended interrupted partial ({} chars, request_id={:?}) to {}",
+ partial_content.len(),
+ request_id,
+ jsonl_path.display()
+ );
+ Ok(())
+}
+
+/// Longest common prefix length between two message slices, comparing on the
+/// stable, serialised fields (`role`, `content`, `id`). `ChatMessage` does not
+/// derive `PartialEq`, and `extra_metadata` is intentionally excluded because
+/// it is enriched (turn usage) between the in-memory history and the persisted
+/// line, which must not count as a divergence.
+fn common_prefix_len(a: &[ChatMessage], b: &[ChatMessage]) -> usize {
+ a.iter()
+ .zip(b.iter())
+ .take_while(|(x, y)| x.role == y.role && x.content == y.content && x.id == y.id)
+ .count()
+}
+
+/// Append raw bytes to a file, opening in append mode (O(1), no read-back).
+fn append_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
+ use std::io::Write;
+ let mut file = fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(path)
+ .with_context(|| format!("open transcript for append {}", path.display()))?;
+ file.write_all(bytes)
+ .with_context(|| format!("append transcript {}", path.display()))?;
+ Ok(())
+}
+
+/// Re-render the derived `.md` companion from the current (reduced) message set.
+///
+/// Best-effort — the JSONL is the source of truth; a companion write failure is
+/// logged and swallowed so it can never take down state persistence.
+fn render_md_companion(
+ jsonl_path: &Path,
+ messages: &[ChatMessage],
+ meta: &TranscriptMeta,
+ last_assistant_turn_usage: Option<&TurnUsage>,
+) {
+ let last_assistant_idx = messages.iter().rposition(|m| m.role == "assistant");
+ let mut owned_usage: Vec<(usize, TurnUsage)> = Vec::new();
+ for (idx, msg) in messages.iter().enumerate() {
+ let usage = if Some(idx) == last_assistant_idx {
+ last_assistant_turn_usage
+ .cloned()
+ .or_else(|| turn_usage_from_metadata(msg))
+ } else {
+ turn_usage_from_metadata(msg)
+ };
+ if let Some(usage) = usage {
+ owned_usage.push((idx, usage));
+ }
+ }
+ let per_msg_usage: HashMap<usize, &TurnUsage> = owned_usage
+ .iter()
+ .map(|(idx, usage)| (*idx, usage))
+ .collect();
+
+ let md_path = md_companion_path(jsonl_path);
+ if let Some(parent) = md_path.parent() {
+ if let Err(err) = fs::create_dir_all(parent) {
+ log::warn!(
+ "[transcript] failed to create md companion dir {}: {err}",
+ parent.display()
+ );
+ return;
+ }
+ }
+ let md = render_markdown(messages, meta, &per_msg_usage);
+ if let Err(err) = fs::write(&md_path, md.as_bytes()) {
+ log::warn!(
+ "[transcript] failed to write markdown companion {}: {err}",
+ md_path.display()
+ );
+ return;
+ }
+ log::debug!(
+ "[transcript] wrote markdown companion to {}",
+ md_path.display()
+ );
+}
diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay.rs b/crates/openhuman-core/src/config/schema/load/env_overlay.rs
index 0eabc3ac89..e3604977e8 100644
--- a/crates/openhuman-core/src/config/schema/load/env_overlay.rs
+++ b/crates/openhuman-core/src/config/schema/load/env_overlay.rs
@@ -1,10 +1,19 @@
-use super::super::proxy::{
- normalize_no_proxy_list, normalize_proxy_url_option, normalize_service_list,
- parse_proxy_enabled, parse_proxy_scope, set_runtime_proxy_config, ProxyScope,
-};
-use super::super::{Config, UpdateRestartStrategy};
+//! Environment-variable overlay applied on top of the persisted config.
+//!
+//! The entry points and the process-wide side effects live here; each
+//! config section's overrides live in a submodule below.
+
+mod dictation_context;
+mod learning_memory;
+mod observability;
+mod proxy;
+mod runtime;
+mod search;
+mod subsystems_update;
+
+use super::super::proxy::{set_runtime_proxy_config, ProxyScope};
+use super::super::Config;
use super::dirs::MEMORY_SYNC_INTERVAL_SECS_ENV_VAR;
-use super::env::parse_env_bool;
use std::path::PathBuf;
/// Classification of an `OPENHUMAN_SHELL_HIDE_WINDOW` env value. Split out from
@@ -31,5 +40,161 @@ pub(super) fn classify_shell_hide_window(raw: &str) -> ShellHideWindowParse {
_ => ShellHideWindowParse::Unrecognized,
}
}
-include!("env_overlay_impl_01_part_01.rs");
-include!("env_overlay_impl_01_part_02.rs");
+
+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::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);
+ }
+}
diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/dictation_context.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/dictation_context.rs
new file mode 100644
index 0000000000..f94040d7b0
--- /dev/null
+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/dictation_context.rs
@@ -0,0 +1,126 @@
+//! Env overrides for dictation and the context-management budget.
+
+use crate::config::schema::load::env::EnvLookup;
+use crate::config::schema::Config;
+
+impl Config {
+ pub(super) fn apply_dictation_env<E: 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::config::DictationActivationMode::Toggle
+ }
+ "push" => {
+ self.dictation.activation_mode = crate::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;
+ }
+ }
+ }
+
+ pub(super) fn apply_context_env<E: 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::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/crates/openhuman-core/src/config/schema/load/env_overlay/learning_memory.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/learning_memory.rs
new file mode 100644
index 0000000000..708d30c850
--- /dev/null
+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/learning_memory.rs
@@ -0,0 +1,246 @@
+//! Env overrides for the learning subsystem and the memory tree.
+
+use crate::config::schema::load::env::parse_env_bool;
+use crate::config::schema::load::env::EnvLookup;
+use crate::config::schema::Config;
+
+impl Config {
+ pub(super) fn apply_learning_env<E: 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::config::ReflectionSource::Local,
+ "cloud" => self.learning.reflection_source = crate::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;
+ }
+ }
+ }
+
+ pub(super) fn apply_memory_tree_env<E: 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::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;
+ }
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/observability.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/observability.rs
new file mode 100644
index 0000000000..6f46e197d2
--- /dev/null
+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/observability.rs
@@ -0,0 +1,44 @@
+//! Env overrides for Sentry, analytics, and agent-tracing content capture.
+
+use crate::config::schema::load::env::EnvLookup;
+use crate::config::schema::Config;
+
+impl Config {
+ pub(super) fn apply_observability_env<E: 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/crates/openhuman-core/src/config/schema/load/env_overlay/proxy.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/proxy.rs
new file mode 100644
index 0000000000..3379093763
--- /dev/null
+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/proxy.rs
@@ -0,0 +1,66 @@
+//! Env overrides for the outbound proxy configuration.
+
+use crate::config::schema::load::env::parse_env_bool;
+use crate::config::schema::load::env::EnvLookup;
+use crate::config::schema::proxy::{
+ normalize_no_proxy_list, normalize_proxy_url_option, normalize_service_list,
+ parse_proxy_enabled, parse_proxy_scope,
+};
+use crate::config::schema::Config;
+
+impl Config {
+ pub(super) fn apply_proxy_env<E: 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;
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rs
new file mode 100644
index 0000000000..2276c6815a
--- /dev/null
+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rs
@@ -0,0 +1,204 @@
+//! Env overrides for the local-AI tier preset and the Node, Python, runtime-pool, and tokenjuice runtimes.
+
+use crate::config::schema::load::env::parse_env_bool;
+use crate::config::schema::load::env::EnvLookup;
+use crate::config::schema::Config;
+
+impl Config {
+ pub(super) fn apply_runtime_env<E: 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::inference::presets::ModelTier::from_str_opt(&tier_str) {
+ if tier == crate::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::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;
+ }
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs
new file mode 100644
index 0000000000..7fb132de80
--- /dev/null
+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs
@@ -0,0 +1,141 @@
+//! Env overrides for web search: SearXNG, Seltz, Tavily, and the search engine selection.
+
+use crate::config::schema::load::env::EnvLookup;
+use crate::config::schema::Config;
+
+impl Config {
+ pub(super) fn apply_search_env<E: 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(key) = env.get_any(&["OPENHUMAN_TAVILY_API_KEY", "TAVILY_API_KEY"]) {
+ if !key.trim().is_empty() {
+ self.search.tavily.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;
+ }
+ }
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/subsystems_update.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/subsystems_update.rs
new file mode 100644
index 0000000000..8badc9320b
--- /dev/null
+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/subsystems_update.rs
@@ -0,0 +1,108 @@
+//! Env overrides for the `[subsystems]` drivers and the auto-updater.
+
+use crate::config::schema::load::env::parse_env_bool;
+use crate::config::schema::load::env::EnvLookup;
+use crate::config::schema::Config;
+use crate::config::schema::UpdateRestartStrategy;
+
+impl Config {
+ /// `[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.
+ pub(super) fn apply_subsystems_env<E: 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"
+ ),
+ }
+ }
+ }
+ }
+
+ pub(super) fn apply_update_env<E: 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;
+ }
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay_impl_01_part_01.rs b/crates/openhuman-core/src/config/schema/load/env_overlay_impl_01_part_01.rs
deleted file mode 100644
index a8b3e76293..0000000000
--- a/crates/openhuman-core/src/config/schema/load/env_overlay_impl_01_part_01.rs
+++ /dev/null
@@ -1,589 +0,0 @@
-
-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::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(key) = env.get_any(&["OPENHUMAN_TAVILY_API_KEY", "TAVILY_API_KEY"]) {
- if !key.trim().is_empty() {
- self.search.tavily.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::inference::presets::ModelTier::from_str_opt(&tier_str)
- {
- if tier == crate::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::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/crates/openhuman-core/src/config/schema/load/env_overlay_impl_01_part_02.rs b/crates/openhuman-core/src/config/schema/load/env_overlay_impl_01_part_02.rs
deleted file mode 100644
index e022e9bee3..0000000000
--- a/crates/openhuman-core/src/config/schema/load/env_overlay_impl_01_part_02.rs
+++ /dev/null
@@ -1,469 +0,0 @@
-
-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::config::ReflectionSource::Local
- }
- "cloud" => {
- self.learning.reflection_source =
- crate::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::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::config::DictationActivationMode::Toggle
- }
- "push" => {
- self.dictation.activation_mode =
- crate::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::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/crates/openhuman-core/src/flows/builder_tools_draft_id_tests.rs b/crates/openhuman-core/src/flows/builder_tools_draft_id_tests.rs
index 0b3c47466b..5026cbaa19 100644
--- a/crates/openhuman-core/src/flows/builder_tools_draft_id_tests.rs
+++ b/crates/openhuman-core/src/flows/builder_tools_draft_id_tests.rs
@@ -227,13 +227,18 @@ async fn revise_workflow_proposal_is_marked_unpersisted() {
fn module_doc_tool_table_matches_registered_tools() {
const SOURCE: &str = concat!(
include_str!("builder_tools.rs"),
- include_str!("builder_tools_part_01.rs"),
- include_str!("builder_tools_part_02.rs"),
- include_str!("builder_tools_part_03.rs"),
- include_str!("builder_tools_part_04.rs"),
- include_str!("builder_tools_part_05.rs"),
- include_str!("builder_tools_part_06.rs"),
- include_str!("builder_tools_part_07.rs"),
+ include_str!("builder_tools/catalog_search.rs"),
+ include_str!("builder_tools/connection_reads.rs"),
+ include_str!("builder_tools/draft_edit.rs"),
+ include_str!("builder_tools/draft_revise.rs"),
+ include_str!("builder_tools/draft_validate.rs"),
+ include_str!("builder_tools/dry_run.rs"),
+ include_str!("builder_tools/dry_run_diagnostics.rs"),
+ include_str!("builder_tools/flow_reads.rs"),
+ include_str!("builder_tools/kind_reads.rs"),
+ include_str!("builder_tools/persistence.rs"),
+ include_str!("builder_tools/run_control.rs"),
+ include_str!("builder_tools/tool_contract.rs"),
);
let module_doc: String = SOURCE
diff --git a/crates/openhuman-core/src/inference/provider/factory.rs b/crates/openhuman-core/src/inference/provider/factory.rs
index 4496155609..8f647d4927 100644
--- a/crates/openhuman-core/src/inference/provider/factory.rs
+++ b/crates/openhuman-core/src/inference/provider/factory.rs
@@ -22,6 +22,93 @@
//! the built provider. The model id sent upstream never includes the suffix.
//!
//! Unknown slugs and missing-creds configurations produce actionable errors.
+//!
+//! ## Module layout
+//!
+//! - [`tiers`] — managed tier / `hint:*` vocabulary and capability lookups.
+//! - [`routing`] — role → configured provider string resolution.
+//! - [`primary_cloud`] — `primary_cloud` / legacy `inference_url` resolution.
+//! - [`access_gates`] — privacy-mode, session, and egress chokepoints.
+//! - [`credentials`] — auth-profile key lookup for cloud slugs.
+//! - [`managed_backend`] — the managed OpenHuman backend model.
+//! - [`local_runtime`] — Ollama / LM Studio / MLX / OMLX / local-openai.
+//! - [`cloud_slug`] — `<slug>:<model>` BYOK cloud providers.
+//! - [`subprocess_providers`] — Claude Agent SDK and Claude Code CLI.
+//! - [`chat_model`] — the one-shot `create_chat_model*` entry points.
+//! - [`turn_model`] — the per-turn `create_turn_chat_model*` entry points.
+
+mod access_gates;
+mod chat_model;
+mod cloud_slug;
+mod credentials;
+mod local_runtime;
+mod managed_backend;
+mod primary_cloud;
+mod routing;
+mod subprocess_providers;
+mod tiers;
+mod turn_model;
+
+pub use chat_model::{
+ create_chat_model, create_chat_model_from_string, create_chat_model_from_string_with_model_id,
+ create_chat_model_with_model_id, probe_inference_readiness,
+};
+pub(crate) use chat_model::resolves_to_managed_backend;
+pub use credentials::{auth_key_for_slug, lookup_key_for_slug, redact_endpoint};
+pub(crate) use credentials::openai_bearer_is_oauth;
+pub use routing::{provider_for_role, role_bypasses_managed_credits};
+pub(crate) use routing::role_uses_implicit_cloud_fallback;
+pub use tiers::{resolve_model_for_hint, role_for_model_tier};
+pub(crate) use tiers::{is_known_openhuman_tier, is_raw_passthrough_model, oh_tier_supports_vision};
+pub(crate) use access_gates::{
+ current_host_requires_session, verify_backend_session_active, verify_session_active,
+};
+pub(crate) use local_runtime::create_local_chat_model_from_string;
+pub(crate) use managed_backend::{make_openhuman_backend_model, summarization_tier_model};
+pub(crate) use turn_model::{
+ create_turn_chat_model, create_turn_chat_model_from_string,
+ create_turn_chat_model_from_string_with_native_tools,
+ create_turn_chat_model_from_string_with_native_tools_and_route,
+ create_turn_chat_model_with_native_tools, create_turn_chat_model_with_native_tools_and_route,
+};
+
+// Factory-internal helpers shared across the submodules (and their tests)
+// through `use super::*`.
+use access_gates::{
+ emit_inference_egress, enforce_local_only_inference, external_provider_label,
+ host_requires_session, local_only_violation,
+};
+use chat_model::{
+ create_chat_model_from_string_with_model_id_inner, create_chat_model_with_model_id_inner,
+ unresolved_chat_model_error, with_default_temperature, DefaultTemperatureChatModel,
+};
+use cloud_slug::{
+ resolve_cloud_slug, try_create_cloud_slug_chat_model,
+ try_create_cloud_slug_chat_model_from_string,
+ try_create_cloud_slug_chat_model_from_string_with_native_tools,
+ try_create_cloud_slug_chat_model_with_native_tools, CloudSlugResolution,
+};
+use local_runtime::{
+ try_create_local_runtime_chat_model, try_create_local_runtime_chat_model_from_string,
+ OptionalChatModelResult, ResolvedChatModel,
+};
+use managed_backend::{
+ managed_tier_for_role, resolve_managed_backend, resolve_managed_backend_with_model_override,
+};
+use primary_cloud::{
+ cloud_entry_provider_string, has_custom_inference_intent, is_openhuman_cloud_entry,
+ legacy_custom_inference_provider_string, legacy_inference_slug, looks_like_openhuman_backend,
+ normalize_endpoint_for_compare, redact_inference_url, resolve_primary_cloud_provider_string,
+};
+use routing::{configured_route_for_role, route_has_usable_credentials, split_model_and_temperature};
+use subprocess_providers::{
+ claude_agent_sdk_model_from_string, prepare_claude_agent_sdk_chat_model,
+ try_create_claude_agent_sdk_chat_model, try_create_claude_agent_sdk_chat_model_from_string,
+ try_create_claude_code_chat_model, try_create_claude_code_chat_model_from_string,
+};
+use tiers::is_abstract_tier_model;
+use turn_model::create_turn_chat_model_with_native_tools_and_route_inner;
+
/// Test-only seam: inject a mock [`ChatModel`] so e2e tests can drive the
/// autonomous run paths (`spawn_workflow_run_background`, the task dispatcher)
@@ -40,8 +127,50 @@ pub mod test_provider_override;
#[cfg(test)]
#[path = "factory_tests.rs"]
-mod factory_tests;
-include!("factory_part_01.rs");
-include!("factory_part_02.rs");
-include!("factory_part_03.rs");
-include!("factory_part_04.rs");
+
+use crate::config::schema::cloud_providers::AuthStyle;
+use crate::config::Config;
+use crate::inference::provider::auth::AuthStyle as CompatAuthStyle;
+use crate::inference::provider::claude_agent_sdk::subprocess::ClaudeAgentSdkProvider;
+use crate::inference::provider::openai_codex::{
+ openai_codex_client_version, openai_codex_user_agent, resolve_openai_codex_routing,
+ OPENAI_CODEX_ACCOUNT_HEADER, OPENAI_CODEX_ORIGINATOR, OPENAI_CODEX_ORIGINATOR_HEADER,
+};
+use crate::inference::provider::openhuman_backend_model::OpenHumanBackendModel;
+use crate::inference::provider::ProviderRuntimeOptions;
+use crate::security::credentials::AuthService;
+use std::sync::Arc;
+use tinyinference::model::{ChatModel, ModelRequest, ModelResponse, ModelStream};
+
+/// Sentinel meaning "use the OpenHuman backend session JWT".
+pub const PROVIDER_OPENHUMAN: &str = "openhuman";
+/// Prefix for Ollama-local providers: `"ollama:<model>"`.
+pub const OLLAMA_PROVIDER_PREFIX: &str = "ollama:";
+/// Prefix for LM Studio-local providers: `"lmstudio:<model>"`.
+pub const LM_STUDIO_PROVIDER_PREFIX: &str = "lmstudio:";
+/// Prefix for MLX-compatible local providers: `"mlx:<model>"`.
+pub const MLX_PROVIDER_PREFIX: &str = "mlx:";
+/// Prefix for OMLX local providers: `"omlx:<model>"`.
+pub const OMLX_PROVIDER_PREFIX: &str = "omlx:";
+/// Prefix for generic local OpenAI-compatible providers: `"local-openai:<model>"`.
+pub const LOCAL_OPENAI_PROVIDER_PREFIX: &str = "local-openai:";
+/// Prefix for the Claude Agent SDK subprocess provider: `"claude_agent_sdk:<model>"`.
+pub const CLAUDE_AGENT_SDK_PREFIX: &str = "claude_agent_sdk:";
+/// Sentinel for the Claude Agent SDK provider without a model suffix.
+pub const CLAUDE_AGENT_SDK_PROVIDER: &str = "claude_agent_sdk";
+/// Sentinel returned when a user has expressed custom/BYOK inference intent
+/// (via a non-openhuman `inference_url`) but no matching `cloud_providers`
+/// entry was found. Passed through `provider_for_role` and caught early in
+/// `create_chat_model_from_string` to produce a clear configuration error
+/// instead of silently routing through the managed OpenHuman backend.
+pub const BYOK_INCOMPLETE_SENTINEL: &str = "__byok_incomplete__";
+
+/// Interpolation-free substring of the empty-model bail emitted by
+/// cloud-slug resolution when a `<slug>` provider string carries
+/// no model and the `cloud_providers` entry has no `default_model` (the
+/// #2784 guard). The Sentry-demotion + user-copy classifier
+/// [`super::is_provider_config_rejection_message`] keys on this exact literal,
+/// and a round-trip test in `factory_tests.rs` asserts the bail body still
+/// contains it — so a wording drift fails CI instead of silently re-flooding
+/// Sentry (TAURI-RUST-GKV).
+pub(crate) const NO_MODEL_CONFIGURED_ANCHOR: &str = "resolved to an empty model id";
diff --git a/crates/openhuman-core/src/inference/provider/factory/access_gates.rs b/crates/openhuman-core/src/inference/provider/factory/access_gates.rs
new file mode 100644
index 0000000000..1dcd11c628
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/factory/access_gates.rs
@@ -0,0 +1,193 @@
+use super::*;
+
+/// Human-readable label for an *external* provider string, used in the
+/// LocalOnly privacy-mode block message so the user knows what was refused.
+pub(super) fn external_provider_label(provider: &str) -> String {
+ let p = provider.trim();
+ if p == PROVIDER_OPENHUMAN {
+ return "OpenHuman (managed cloud)".to_string();
+ }
+ if p == BYOK_INCOMPLETE_SENTINEL {
+ return "cloud (incomplete BYOK config)".to_string();
+ }
+ if p == CLAUDE_AGENT_SDK_PROVIDER || p.starts_with(CLAUDE_AGENT_SDK_PREFIX) {
+ return "Claude Agent SDK".to_string();
+ }
+ if p.starts_with(crate::inference::provider::claude_code::PROVIDER_PREFIX) {
+ return "Claude Code CLI".to_string();
+ }
+ // Concrete cloud slug "<slug>:<model>" → surface just the slug.
+ match p.split_once(':') {
+ Some((slug, _)) if !slug.trim().is_empty() => slug.trim().to_string(),
+ _ => p.to_string(),
+ }
+}
+
+/// Privacy Mode (#4435) pure decision: under `mode`, is constructing chat
+/// provider `provider` a local-only violation? Returns `Some(label)` naming the
+/// blocked external provider when refused, else `None`.
+///
+/// Only `LocalOnly` restricts anything. Local runtimes (Ollama / LM Studio / MLX
+/// / local-openai) are always permitted. Re-resolving sentinels (`""` / `"cloud"`)
+/// return `None` here — they are resolved before model construction and
+/// re-checked with the concrete
+/// resolved string. Extracted as a pure fn so it is unit-testable without the
+/// process-global live policy.
+pub(super) fn local_only_violation(
+ mode: crate::config::PrivacyMode,
+ provider: &str,
+) -> Option<String> {
+ use crate::config::PrivacyMode;
+ if mode != PrivacyMode::LocalOnly {
+ return None;
+ }
+ let p = provider.trim();
+ if p.is_empty() || p == "cloud" {
+ // Deferred: re-resolves to a concrete string on the recursive call.
+ return None;
+ }
+ if crate::inference::local::profile::is_local_provider_string(p) {
+ return None;
+ }
+ Some(external_provider_label(p))
+}
+
+/// Enforce Privacy Mode `LocalOnly` at the inference chokepoint: refuse to build
+/// an external chat provider when the live policy is local-only. Reads the live
+/// privacy mode (defaults to `Standard`/allow when no session policy is
+/// installed). See [`local_only_violation`] for the pure decision.
+pub(super) fn enforce_local_only_inference(role: &str, provider: &str) -> anyhow::Result<()> {
+ let mode = crate::security::live_policy::current_privacy_mode();
+ match local_only_violation(mode, provider) {
+ None => {
+ log::debug!(
+ "[privacy][chat-factory] privacy_mode={:?} role={} provider='{}' — inference permitted",
+ mode,
+ role,
+ provider.trim()
+ );
+ Ok(())
+ }
+ Some(label) => {
+ log::warn!(
+ "[privacy][chat-factory] LocalOnly BLOCK: role={} external provider='{}' ({}) refused",
+ role,
+ provider.trim(),
+ label
+ );
+ anyhow::bail!(
+ "Local-only privacy mode is active: this action needs external provider {label}. \
+ Switch to a local model (Ollama/LM Studio/etc.) or change privacy mode in Settings."
+ )
+ }
+ }
+}
+
+/// Egress spine (privacy epic S2, #4436): emit an [`EgressDescriptor`] for a
+/// concrete inference provider string. `provider` is expected to be already
+/// resolved (no `""` / `"cloud"` / BYOK sentinels — those are handled before
+/// this is called). Local runtimes are marked non-external, so
+/// [`emit_external_transfer`](crate::security::egress::emit_external_transfer)
+/// discloses them without firing the external-transfer event.
+pub(super) fn emit_inference_egress(role: &str, provider: &str) {
+ let p = provider.trim();
+ if p.is_empty() || p == "cloud" {
+ // Defensive: a sentinel would re-resolve on recursion; don't emit here.
+ return;
+ }
+ if p == PROVIDER_OPENHUMAN {
+ // Managed backend is emitted centrally in `resolve_managed_backend`,
+ // the universal managed ChatModel funnel. Skipping here avoids a
+ // duplicate descriptor.
+ return;
+ }
+ let is_local = crate::inference::local::profile::is_local_provider_string(p);
+ let (slug, model) = match p.split_once(':') {
+ Some((s, m)) if !s.trim().is_empty() => (s.trim().to_string(), m.trim().to_string()),
+ _ => (p.to_string(), String::new()),
+ };
+ // Fall back to the workload role when the provider string carries no model
+ // component (e.g. a bare `"openhuman"` / `"ollama"` slug).
+ let service = if model.is_empty() {
+ role.to_string()
+ } else {
+ model
+ };
+ crate::security::egress::emit_external_transfer(
+ crate::security::egress::EgressDescriptor::inference(slug, service, !is_local),
+ );
+}
+
+/// Verify the user has an active OpenHuman backend session.
+///
+/// Without this check, an unregistered user can configure every workload
+/// to use a custom cloud provider and bypass the session requirement
+/// entirely. This function ensures that custom providers (Ollama,
+/// `<slug>:<model>`) are only reachable when the workspace holds a valid
+/// `app-session` JWT.
+///
+/// `pub(crate)`: also reused directly by the flows provider-connectivity
+/// author gate (issue B45, `openhuman::flows::ops::evaluate_inference_readiness`)
+/// as its Layer 1 sync session check, so the author-time gate and this
+/// construction-time chokepoint can never diverge on what "session active"
+/// means.
+pub(crate) fn verify_session_active(config: &Config) -> anyhow::Result<()> {
+ // An in-process library host is given its provider URL and credential by
+ // its caller. It does not participate in the OpenHuman app's registration
+ // or auth-profile lifecycle, so requiring a fabricated local session here
+ // would mix desktop product policy into the library contract. The ambient
+ // context is installed by the dispatch chokepoint; all other host kinds
+ // retain the registration gate below.
+ if !current_host_requires_session() {
+ return Ok(());
+ }
+
+ verify_backend_session_active(config)
+}
+
+/// Managed `OpenhumanJwt` inference always needs the backend bearer, including
+/// in a Library host. Library mode exempts caller-owned provider credentials;
+/// it cannot manufacture a TinyHumans account credential.
+pub(crate) fn verify_backend_session_active(config: &Config) -> anyhow::Result<()> {
+ // Fast path: the scheduler gate already knows the session is dead.
+ if crate::cron::scheduler_gate::is_signed_out() {
+ anyhow::bail!(
+ "SESSION_EXPIRED: backend session not active — sign in to use custom providers"
+ );
+ }
+ // Verify the app-session JWT actually exists in auth-profiles.
+ let state_dir = config
+ .config_path
+ .parent()
+ .map(std::path::PathBuf::from)
+ .unwrap_or_else(|| {
+ directories::UserDirs::new()
+ .map(|d| d.home_dir().join(".openhuman"))
+ .unwrap_or_else(|| std::path::PathBuf::from(".openhuman"))
+ });
+ let auth = AuthService::new(&state_dir, config.secrets.encrypt);
+ let has_session = auth
+ .get_provider_bearer_token(
+ crate::security::credentials::APP_SESSION_PROVIDER,
+ None,
+ )?
+ .filter(|s| !s.trim().is_empty())
+ .is_some();
+ if !has_session {
+ anyhow::bail!("SESSION_EXPIRED: no backend session — sign in to use OpenHuman")
+ }
+ Ok(())
+}
+
+/// Whether inference in the ambient host participates in OpenHuman app login.
+/// Library hosts receive their provider configuration from the embedding
+/// process; every other host retains the product session policy.
+pub(crate) fn current_host_requires_session() -> bool {
+ crate::core::runtime::context::CoreContext::current()
+ .map(|ctx| host_requires_session(ctx.host_kind()))
+ .unwrap_or(true)
+}
+
+pub(super) fn host_requires_session(host_kind: crate::core::types::HostKind) -> bool {
+ host_kind != crate::core::types::HostKind::Library
+}
diff --git a/crates/openhuman-core/src/inference/provider/factory/chat_model.rs b/crates/openhuman-core/src/inference/provider/factory/chat_model.rs
new file mode 100644
index 0000000000..9fb2d2a01d
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/factory/chat_model.rs
@@ -0,0 +1,367 @@
+use super::*;
+
+/// Build an `Arc<dyn ChatModel>` for the given workload role.
+///
+/// The crate [`ChatModel`] is the model interface for the harness and one-shot
+/// inference callers. Production and tests both inject this native interface;
+/// `temperature` is applied as the request default while an explicit per-call
+/// value still wins.
+pub fn create_chat_model(
+ role: &str,
+ config: &Config,
+ temperature: f64,
+) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
+ Ok(create_chat_model_with_model_id(role, config, temperature)?.0)
+}
+
+/// Like [`create_chat_model`], but also returns the resolved model id.
+///
+/// One-shot callers that persist or log the concrete model (e.g. the memory
+/// summarise audit) need the id the role resolved to; the plain
+/// [`create_chat_model`] drops it.
+pub fn create_chat_model_with_model_id(
+ role: &str,
+ config: &Config,
+ temperature: f64,
+) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {
+ let (model, model_id) = create_chat_model_with_model_id_inner(role, config)?;
+ Ok((with_default_temperature(model, temperature), model_id))
+}
+
+pub(super) fn create_chat_model_with_model_id_inner(
+ role: &str,
+ config: &Config,
+) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {
+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
+ if let Some(model) = test_provider_override::current() {
+ return Ok((model, "mock-model".to_string()));
+ }
+ // Managed OpenHuman backend → crate-native host `ChatModel`
+ // ([`OpenHumanBackendModel`], issue #4727 Motion B) instead of a
+ // adapted provider. A native test-model override must still win, so only
+ // take this path when no
+ // override is installed. The public wrapper supplies the construction-time
+ // default while preserving an explicit per-call `ModelRequest` temperature.
+ let test_override_active = {
+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
+ {
+ test_provider_override::current().is_some()
+ }
+ #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]
+ {
+ false
+ }
+ };
+ if !test_override_active {
+ if resolves_to_managed_backend(role, config) {
+ return make_openhuman_backend_model(role, config);
+ }
+ if let Some(result) = try_create_claude_agent_sdk_chat_model(role, config) {
+ return result;
+ }
+ if let Some(result) = try_create_claude_code_chat_model(role, config, None) {
+ return result;
+ }
+ // Local OpenAI-compatible runtimes (Ollama / LM Studio / MLX / OMLX /
+ // local-openai) → crate-native `ChatModel` (issue #4727 Motion B) instead
+ // of a crate-adapted host provider. Cloud/BYOK/bespoke providers
+ // return `None` here and fall through to the `Provider` path below.
+ if let Some(result) = try_create_local_runtime_chat_model(role, config) {
+ return result;
+ }
+ // Wire-equivalent BYOK cloud slugs (Anthropic / None / plain-Bearer, no
+ // codex-oauth or `/v1/responses` fallback) → crate-native `ChatModel`
+ // (issue #4727 Phase 3, conservative subset). `openai`/codex, custom
+ // proxy slugs, and the managed entry return `None` and fall through.
+ if let Some(result) = try_create_cloud_slug_chat_model(role, config) {
+ return result;
+ }
+ }
+ Err(unresolved_chat_model_error(
+ role,
+ &provider_for_role(role, config),
+ config,
+ ))
+}
+
+/// Whether `role` resolves to the managed OpenHuman backend (vs BYOK / local /
+/// claude-code). Uses the same empty/`cloud`/`openhuman` normalization as
+/// [`create_chat_model_from_string`] so every managed role shares one path.
+pub(crate) fn resolves_to_managed_backend(role: &str, config: &Config) -> bool {
+ let mut resolved = provider_for_role(role, config);
+ let trimmed = resolved.trim();
+ if trimmed.is_empty() || trimmed == "cloud" {
+ resolved = resolve_primary_cloud_provider_string(config);
+ }
+ resolved.trim() == PROVIDER_OPENHUMAN
+}
+
+/// Probe whether `role` can actually complete an inference call right now
+/// (issue B45 — the flows provider-connectivity author gate).
+///
+/// Two-stage check, mirroring the two ways a `role` can be un-runnable:
+///
+/// 1. **Construction** — [`create_chat_model_with_model_id_inner`] must
+/// succeed. This is the existing Layer 1 check (BYOK-incomplete config,
+/// unknown provider slug, local-only privacy-mode block, …) reused
+/// verbatim so this probe never re-implements it.
+/// 2. **Managed-backend readiness** — when `role` resolves to the managed
+/// OpenHuman backend, [`OpenHumanBackendModel::probe_readiness`] makes one
+/// cheap real completion attempt to catch the "account has no provider API
+/// key configured" class of failure that construction alone cannot see
+/// (construction only builds the client; it never calls the backend).
+/// BYOK/local models have no such hidden failure mode — their construction
+/// step already validates what it can, so they return `Ok(())` here
+/// unconditionally.
+///
+/// Respects the [`test_provider_override`] test seam: when a mock model is
+/// installed, construction returns it immediately and this function returns
+/// `Ok(())` without ever touching the network or resolving `role` again —
+/// `resolves_to_managed_backend` is a pure config read that would otherwise
+/// still call this "managed" in a test with a bare default `Config`.
+pub async fn probe_inference_readiness(role: &str, config: &Config) -> Result<(), String> {
+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
+ if test_provider_override::current().is_some() {
+ log::debug!(
+ "[flows][inference-probe] role={role} test model override active — skipping probe"
+ );
+ return Ok(());
+ }
+
+ log::debug!("[flows][inference-probe] role={role} verifying model construction");
+ if let Err(e) = create_chat_model_with_model_id_inner(role, config) {
+ log::debug!("[flows][inference-probe] role={role} construction failed: {e}");
+ return Err(e.to_string());
+ }
+
+ if !resolves_to_managed_backend(role, config) {
+ log::debug!(
+ "[flows][inference-probe] role={role} resolves to a non-managed provider — \
+ construction succeeded, nothing further to probe"
+ );
+ return Ok(());
+ }
+
+ log::debug!(
+ "[flows][inference-probe] role={role} resolves to the managed OpenHuman backend — \
+ probing readiness"
+ );
+ let (managed_model, model_id) =
+ resolve_managed_backend(role, config).map_err(|e| e.to_string())?;
+ let result = managed_model.probe_readiness().await;
+ log::debug!(
+ "[flows][inference-probe] role={role} model={model_id} probe result: {}",
+ if result.is_ok() { "ready" } else { "not ready" }
+ );
+ result
+}
+
+/// Build an `Arc<dyn ChatModel>` from an explicit provider string and config.
+///
+/// The explicit-string counterpart of [`create_chat_model`].
+pub fn create_chat_model_from_string(
+ role: &str,
+ provider: &str,
+ config: &Config,
+ temperature: f64,
+) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
+ create_chat_model_from_string_with_model_id(role, provider, config, temperature)
+ .map(|(model, _)| model)
+}
+
+/// Build a crate [`ChatModel`] from an explicit provider string and return the
+/// concrete model id selected by that provider.
+///
+/// Managed, local-runtime, configured cloud-slug, Claude SDK/Code, and Codex
+/// strings all construct native `ChatModel` implementations directly.
+pub fn create_chat_model_from_string_with_model_id(
+ role: &str,
+ provider: &str,
+ config: &Config,
+ temperature: f64,
+) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {
+ let (model, model_id) =
+ create_chat_model_from_string_with_model_id_inner(role, provider, config)?;
+ Ok((with_default_temperature(model, temperature), model_id))
+}
+
+pub(super) fn create_chat_model_from_string_with_model_id_inner(
+ role: &str,
+ provider: &str,
+ config: &Config,
+) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {
+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
+ if let Some(model) = test_provider_override::current() {
+ return Ok((model, "mock-model".to_string()));
+ }
+ let test_override_active = {
+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
+ {
+ test_provider_override::current().is_some()
+ }
+ #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]
+ {
+ false
+ }
+ };
+ if !test_override_active {
+ let mut resolved = provider.trim().to_string();
+ if resolved.is_empty() || resolved == "cloud" {
+ resolved = resolve_primary_cloud_provider_string(config);
+ }
+ if resolved == PROVIDER_OPENHUMAN {
+ return make_openhuman_backend_model(role, config);
+ }
+ if let Some(result) =
+ try_create_claude_agent_sdk_chat_model_from_string(role, &resolved, config)
+ {
+ return result;
+ }
+ if let Some(result) =
+ try_create_claude_code_chat_model_from_string(role, &resolved, config, None)
+ {
+ return result;
+ }
+ if let Some(result) =
+ try_create_local_runtime_chat_model_from_string(role, &resolved, config, true)
+ {
+ return result;
+ }
+ if let Some(result) = try_create_cloud_slug_chat_model_from_string(role, &resolved, config)
+ {
+ return result;
+ }
+ }
+ Err(unresolved_chat_model_error(role, provider, config))
+}
+
+pub(super) struct DefaultTemperatureChatModel {
+ inner: Arc<dyn ChatModel<()>>,
+ temperature: f64,
+}
+
+#[async_trait::async_trait]
+impl ChatModel<()> for DefaultTemperatureChatModel {
+ fn profile(&self) -> Option<&tinyinference::model::ModelProfile> {
+ self.inner.profile()
+ }
+
+ fn cache_identity(&self) -> Option<String> {
+ self.inner.cache_identity()
+ }
+
+ async fn invoke(
+ &self,
+ state: &(),
+ mut request: ModelRequest,
+ ) -> tinyinference::Result<ModelResponse> {
+ if request.temperature.is_none() {
+ request.temperature = Some(self.temperature);
+ }
+ self.inner.invoke(state, request).await
+ }
+
+ async fn stream(
+ &self,
+ state: &(),
+ mut request: ModelRequest,
+ ) -> tinyinference::Result<ModelStream> {
+ if request.temperature.is_none() {
+ request.temperature = Some(self.temperature);
+ }
+ self.inner.stream(state, request).await
+ }
+}
+
+pub(super) fn with_default_temperature(
+ model: Arc<dyn ChatModel<()>>,
+ temperature: f64,
+) -> Arc<dyn ChatModel<()>> {
+ Arc::new(DefaultTemperatureChatModel {
+ inner: model,
+ temperature,
+ })
+}
+
+/// Reproduce the legacy provider factory's access gates and diagnostics for a
+/// provider string that none of the crate-native model constructors accepted.
+///
+/// Successful production routes never reach this function. Keeping error
+/// resolution separate means `create_chat_model*` no longer constructs a
+/// legacy `Provider` merely to discover that a route is invalid.
+pub(super) fn unresolved_chat_model_error(role: &str, provider: &str, config: &Config) -> anyhow::Error {
+ let p = provider.trim();
+
+ if let Err(error) = enforce_local_only_inference(role, p) {
+ return error;
+ }
+
+ if p == BYOK_INCOMPLETE_SENTINEL {
+ let inference_url = config
+ .inference_url
+ .as_deref()
+ .filter(|value| !value.trim().is_empty())
+ .unwrap_or("<unset>");
+ return anyhow::anyhow!(
+ "[chat-factory] BYOK_INCOMPLETE: inference_url is set to a custom/direct endpoint \
+ ({inference_url}) but no matching cloud_providers entry was found for role '{role}'. \
+ To complete BYOK setup add a cloud_providers entry whose endpoint matches \
+ {inference_url} (or use a workload-specific route). \
+ To use the OpenHuman managed backend instead, clear inference_url from config."
+ );
+ }
+
+ if p.is_empty() || p == "cloud" {
+ return unresolved_chat_model_error(
+ role,
+ &resolve_primary_cloud_provider_string(config),
+ config,
+ );
+ }
+
+ #[cfg(not(test))]
+ if let Err(error) = verify_session_active(config) {
+ return error;
+ }
+
+ // Preserve the legacy chokepoint's disclosure ordering for invalid custom
+ // routes: after both gates pass, the attempted external destination is
+ // visible even when configuration validation then fails.
+ emit_inference_egress(role, p);
+
+ if let Some((slug, model_with_temperature)) = p.split_once(':') {
+ if slug.trim().is_empty() {
+ return anyhow::anyhow!(
+ "[chat-factory] provider string '{}' for role '{}' has an empty slug",
+ p,
+ role
+ );
+ }
+ let (model, _) = split_model_and_temperature(model_with_temperature);
+ return match resolve_cloud_slug(role, slug.trim(), &model, config) {
+ Err(error) => error,
+ Ok(_) => anyhow::anyhow!(
+ "[chat-factory] configured provider '{}' for role '{}' did not produce a crate-native chat model",
+ p,
+ role
+ ),
+ };
+ }
+
+ anyhow::anyhow!(
+ "[chat-factory] unrecognised provider string '{}' for role '{}'. \
+ Valid forms: openhuman, ollama:<model>, lmstudio:<model>, mlx:<model>, omlx:<model>, \
+ local-openai:<model>, claude_agent_sdk, claude_agent_sdk:<model>, <slug>:<model>. \
+ Configured slugs: [{}]",
+ p,
+ role,
+ config
+ .cloud_providers
+ .iter()
+ .map(|entry| entry.slug.as_str())
+ .collect::<Vec<_>>()
+ .join(", ")
+ )
+}
+
+// ── Internal helpers ──────────────────────────────────────────────────────────
diff --git a/crates/openhuman-core/src/inference/provider/factory_part_04.rs b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs
similarity index 61%
rename from crates/openhuman-core/src/inference/provider/factory_part_04.rs
rename to crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs
index ced8599127..8ca42aec06 100644
--- a/crates/openhuman-core/src/inference/provider/factory_part_04.rs
+++ b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs
@@ -1,117 +1,18 @@
-
-/// Resolve the slug of the cloud-provider entry that represents the legacy
-/// direct-inference route — the entry whose endpoint matches the configured
-/// custom `inference_url`.
-///
-/// Top-level `config.api_key` was historically paired with `inference_url`
-/// for direct endpoint routing, so it is scoped to this single provider. The
-/// `lookup_key_for_slug` fallback uses this to avoid leaking the global key to
-/// any other provider slug whose auth-profile lookup returned empty.
-fn legacy_inference_slug(config: &Config) -> Option<&str> {
- let inference_url = config
- .inference_url
- .as_deref()
- .map(str::trim)
- .filter(|url| !url.is_empty())?;
-
- if looks_like_openhuman_backend(inference_url) {
- return None;
- }
-
- let normalized_inference = normalize_endpoint_for_compare(inference_url);
- config
- .cloud_providers
- .iter()
- .find(|entry| {
- !is_openhuman_cloud_entry(entry)
- && normalize_endpoint_for_compare(&entry.endpoint) == normalized_inference
- })
- .map(|entry| entry.slug.as_str())
-}
-
-fn cloud_entry_provider_string(
- entry: &crate::config::schema::cloud_providers::CloudProviderCreds,
- config: &Config,
-) -> String {
- if is_openhuman_cloud_entry(entry) {
- return PROVIDER_OPENHUMAN.to_string();
- }
-
- let model = entry
- .default_model
- .as_deref()
- .map(str::trim)
- .filter(|model| !model.is_empty())
- .or_else(|| {
- config
- .default_model
- .as_deref()
- .map(str::trim)
- .filter(|model| !model.is_empty())
- })
- .unwrap_or(crate::config::DEFAULT_MODEL);
-
- format!("{}:{model}", entry.slug)
-}
-
-fn is_openhuman_cloud_entry(
- entry: &crate::config::schema::cloud_providers::CloudProviderCreds,
-) -> bool {
- entry.slug == PROVIDER_OPENHUMAN
- || matches!(entry.auth_style, AuthStyle::OpenhumanJwt)
- || looks_like_openhuman_backend(&entry.endpoint)
-}
-
-fn normalize_endpoint_for_compare(url: &str) -> String {
- url.trim().trim_end_matches('/').to_ascii_lowercase()
-}
-
-fn looks_like_openhuman_backend(url: &str) -> bool {
- let lower = url.trim().to_ascii_lowercase();
- let without_scheme = lower.split("://").nth(1).unwrap_or(&lower);
- let authority = without_scheme.split('/').next().unwrap_or("");
- let host = authority.split('@').next_back().unwrap_or(authority);
- let host_no_port = host.split(':').next().unwrap_or(host);
- matches!(
- host_no_port,
- "api.openhuman.ai" | "api.tinyhumans.ai" | "staging-api.tinyhumans.ai" | "openhuman"
- ) || host_no_port.ends_with(".openhuman.ai")
- || host_no_port.ends_with(".tinyhumans.ai")
-}
-
-/// Parse a `<model>[@<temp>]` tail into `(model, override)`.
-///
-/// Tolerates whitespace around the components. Returns `temperature = None`
-/// when the suffix is absent or unparseable — the model text is taken as-is.
-fn split_model_and_temperature(raw: &str) -> (String, Option<f64>) {
- let trimmed = raw.trim();
- if let Some(at_pos) = trimmed.rfind('@') {
- let head = trimmed[..at_pos].trim();
- let tail = trimmed[at_pos + 1..].trim();
- if !head.is_empty() {
- if let Ok(parsed) = tail.parse::<f64>() {
- if parsed.is_finite() {
- return (head.to_string(), Some(parsed));
- }
- }
- }
- }
- (trimmed.to_string(), None)
-}
+use super::*;
/// Look up a `cloud_providers` entry by slug and build the provider.
/// The shared resolution for a `<slug>:<model>` cloud provider — the cloud
/// `cloud_providers` entry, the effective model id (with `default_model`
/// fallback + abstract-tier remapping), the resolved API key, and the OpenAI
/// codex-oauth routing shared by every cloud `ChatModel` constructor.
-struct CloudSlugResolution<'a> {
+pub(super) struct CloudSlugResolution<'a> {
entry: &'a crate::config::schema::cloud_providers::CloudProviderCreds,
effective_model: String,
key: String,
codex: crate::inference::provider::openai_codex::OpenAiCodexRouting,
}
-fn resolve_cloud_slug<'a>(
+pub(super) fn resolve_cloud_slug<'a>(
role: &str,
slug: &str,
model: &str,
@@ -295,11 +196,11 @@ fn resolve_cloud_slug<'a>(
/// `verify_session_active`) runs before building. Temperature rides the per-call
/// `ModelRequest` (managed/local parity; the `@<temp>` suffix still bakes a fixed
/// override).
-fn try_create_cloud_slug_chat_model(role: &str, config: &Config) -> OptionalChatModelResult {
+pub(super) fn try_create_cloud_slug_chat_model(role: &str, config: &Config) -> OptionalChatModelResult {
try_create_cloud_slug_chat_model_with_native_tools(role, config, true)
}
-fn try_create_cloud_slug_chat_model_with_native_tools(
+pub(super) fn try_create_cloud_slug_chat_model_with_native_tools(
role: &str,
config: &Config,
native_tool_calling: bool,
@@ -318,7 +219,7 @@ fn try_create_cloud_slug_chat_model_with_native_tools(
)
}
-fn try_create_cloud_slug_chat_model_from_string(
+pub(super) fn try_create_cloud_slug_chat_model_from_string(
role: &str,
provider: &str,
config: &Config,
@@ -326,7 +227,7 @@ fn try_create_cloud_slug_chat_model_from_string(
try_create_cloud_slug_chat_model_from_string_with_native_tools(role, provider, config, true)
}
-fn try_create_cloud_slug_chat_model_from_string_with_native_tools(
+pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(
role: &str,
provider: &str,
config: &Config,
@@ -511,165 +412,3 @@ fn try_create_cloud_slug_chat_model_from_string_with_native_tools(
});
Some(Ok((chat, effective_model)))
}
-
-/// Whether the openai bearer that [`lookup_key_for_slug`] resolves is an OAuth
-/// (Codex-subscription) credential rather than a standard API key.
-///
-/// OAuth and API-key credentials share the same `provider:openai` profile store
-/// and differ only by [`AuthProfileKind`], so the bearer *string* cannot reveal
-/// its source — which is exactly why the old `access_token == bearer_key` compare
-/// broke under token rotation (#5353). This mirrors `lookup_key_for_slug`'s
-/// precedence (`provider:openai`, then the legacy bare `openai`) and reports the
-/// *kind* of the profile that would win. With no stored openai profile carrying a
-/// credential, the only bearer source is the OAuth fallback, so a present OAuth
-/// credential means the bearer is OAuth.
-pub(crate) fn openai_bearer_is_oauth(config: &Config) -> bool {
- use crate::security::credentials::profiles::AuthProfileKind;
-
- let auth = AuthService::from_config(config);
- for provider in [auth_key_for_slug("openai"), "openai".to_string()] {
- if let Ok(Some(profile)) = auth.get_profile(&provider, None) {
- // A profile with an empty credential is skipped by
- // `lookup_key_for_slug`, so fall through to the next precedence level.
- let has_credential = match profile.kind {
- AuthProfileKind::Token => profile
- .token
- .as_deref()
- .is_some_and(|t| !t.trim().is_empty()),
- AuthProfileKind::OAuth => profile
- .token_set
- .as_ref()
- .is_some_and(|t| !t.access_token.trim().is_empty()),
- };
- if has_credential {
- return matches!(profile.kind, AuthProfileKind::OAuth);
- }
- }
- }
- // No stored openai profile with a credential → the bearer, if any, comes from
- // the OAuth fallback (`lookup_openai_bearer_token`).
- crate::inference::openai_oauth::lookup_openai_oauth_credentials(config)
- .ok()
- .flatten()
- .is_some()
-}
-
-/// Fetch the bearer token for a slug from the workspace `auth-profiles.json`.
-///
-/// Tries `provider:<slug>` first (new key format), then the bare `<slug>`
-/// (legacy format where keys were stored as `"openai"`, `"anthropic"`, etc.).
-/// Missing or empty keys return `Ok(String::new())` — callers treat that as
-/// "no auth", which surfaces an authentication error at first call rather than
-/// at factory build time.
-pub fn lookup_key_for_slug(slug: &str, config: &Config) -> anyhow::Result<String> {
- // Ahead of the stored profiles, and scoped to the one slug the per-call
- // route registers. A caller that named an endpoint and a bearer for this
- // turn has said where the credential comes from, and there is nothing on
- // disk to find for a slug that exists only in this `Config` copy. Scoping it
- // by slug is what keeps the bearer from reaching a provider the caller never
- // named — the same containment the legacy `config.api_key` fallback below
- // gets from `legacy_inference_slug`.
- if slug == crate::config::schema::EPHEMERAL_ROUTE_SLUG {
- if let Some(route) = config.ephemeral_route.as_ref() {
- log::debug!(
- "[providers][chat-factory] auth lookup slug={} key_present={} (per-call route)",
- slug,
- !route.api_key.trim().is_empty()
- );
- return Ok(route.api_key.trim().to_string());
- }
- }
-
- let auth = AuthService::from_config(config);
- // Try new-style key first.
- let new_key = auth_key_for_slug(slug);
- if let Ok(Some(k)) = auth.get_provider_bearer_token(&new_key, None) {
- if !k.is_empty() {
- log::debug!(
- "[providers][chat-factory] auth lookup slug={} key_present=true (new-style)",
- slug
- );
- return Ok(k);
- }
- }
- // Fall back to legacy bare slug.
- let key = auth
- .get_provider_bearer_token(slug, None)
- .map_err(|e| {
- anyhow::anyhow!(
- "[chat-factory] failed to read API key for slug '{}': {}",
- slug,
- e
- )
- })?
- .unwrap_or_default();
- if !key.is_empty() {
- log::debug!(
- "[providers][chat-factory] auth lookup slug={} key_present=true",
- slug
- );
- return Ok(key);
- }
-
- // OAuth fallback for `openai` runs only after standard API-key resolution
- // returns empty, so env/audit/metrics in the standard path always execute
- // and the OAuth path never silently bypasses provider-agnostic logic.
- if slug == "openai" {
- match crate::inference::openai_oauth::lookup_openai_bearer_token(config) {
- Ok(Some(token)) if !token.is_empty() => {
- log::debug!(
- "[providers][chat-factory] auth lookup slug={} key_present=true (oauth)",
- slug
- );
- return Ok(token);
- }
- Ok(_) => {}
- Err(e) => {
- return Err(anyhow::anyhow!(
- "[chat-factory] openai oauth lookup failed: {e}"
- ));
- }
- }
- }
-
- // Fallback: read from top-level config.api_key (direct config.toml api_key).
- // This handles the case where a key was set in config.toml but not saved
- // through the UI into auth-profiles.json.
- //
- // Scoped to the legacy direct-inference provider only — the cloud-provider
- // slug whose endpoint matches `config.inference_url`. `config.api_key` was
- // historically paired with `inference_url` for direct endpoint routing, so
- // an unscoped fallback would leak this global key to any other provider
- // whose auth-profile lookup returned empty (cross-provider credential leak
- // flagged by CodeRabbit + maintainers on #2724).
- if legacy_inference_slug(config) == Some(slug) {
- if let Some(config_key) = config.api_key.as_ref() {
- if !config_key.trim().is_empty() {
- log::debug!(
- "[providers][chat-factory] auth lookup slug={} key_present=true (config.toml fallback for legacy inference_url)",
- slug
- );
- return Ok(config_key.trim().to_string());
- }
- }
- }
-
- log::debug!(
- "[providers][chat-factory] auth lookup slug={} key_present=false",
- slug
- );
- Ok(String::new())
-}
-
-/// Return a safe-to-log representation of a URL endpoint: `scheme://host` only.
-pub fn redact_endpoint(url: &str) -> String {
- let trimmed = url.trim();
- if let Some(rest) = trimmed.split_once("://") {
- let scheme = rest.0;
- let authority = rest.1.split('/').next().unwrap_or("");
- let host = authority.split('@').next_back().unwrap_or(authority);
- let host_no_query = host.split('?').next().unwrap_or(host);
- return format!("{}://{}", scheme, host_no_query);
- }
- "<endpoint>".to_string()
-}
diff --git a/crates/openhuman-core/src/inference/provider/factory/credentials.rs b/crates/openhuman-core/src/inference/provider/factory/credentials.rs
new file mode 100644
index 0000000000..fa4a11f4b8
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/factory/credentials.rs
@@ -0,0 +1,171 @@
+use super::*;
+
+/// Auth-profile storage key for a slug-keyed provider.
+///
+/// New writes use `"provider:<slug>"`. Lookups also try the bare `<slug>`
+/// as a legacy fallback (old configs stored keys as e.g. `"openai:default"`).
+pub fn auth_key_for_slug(slug: &str) -> String {
+ format!("provider:{slug}")
+}
+
+/// Whether the openai bearer that [`lookup_key_for_slug`] resolves is an OAuth
+/// (Codex-subscription) credential rather than a standard API key.
+///
+/// OAuth and API-key credentials share the same `provider:openai` profile store
+/// and differ only by [`AuthProfileKind`], so the bearer *string* cannot reveal
+/// its source — which is exactly why the old `access_token == bearer_key` compare
+/// broke under token rotation (#5353). This mirrors `lookup_key_for_slug`'s
+/// precedence (`provider:openai`, then the legacy bare `openai`) and reports the
+/// *kind* of the profile that would win. With no stored openai profile carrying a
+/// credential, the only bearer source is the OAuth fallback, so a present OAuth
+/// credential means the bearer is OAuth.
+pub(crate) fn openai_bearer_is_oauth(config: &Config) -> bool {
+ use crate::security::credentials::profiles::AuthProfileKind;
+
+ let auth = AuthService::from_config(config);
+ for provider in [auth_key_for_slug("openai"), "openai".to_string()] {
+ if let Ok(Some(profile)) = auth.get_profile(&provider, None) {
+ // A profile with an empty credential is skipped by
+ // `lookup_key_for_slug`, so fall through to the next precedence level.
+ let has_credential = match profile.kind {
+ AuthProfileKind::Token => profile
+ .token
+ .as_deref()
+ .is_some_and(|t| !t.trim().is_empty()),
+ AuthProfileKind::OAuth => profile
+ .token_set
+ .as_ref()
+ .is_some_and(|t| !t.access_token.trim().is_empty()),
+ };
+ if has_credential {
+ return matches!(profile.kind, AuthProfileKind::OAuth);
+ }
+ }
+ }
+ // No stored openai profile with a credential → the bearer, if any, comes from
+ // the OAuth fallback (`lookup_openai_bearer_token`).
+ crate::inference::openai_oauth::lookup_openai_oauth_credentials(config)
+ .ok()
+ .flatten()
+ .is_some()
+}
+
+/// Fetch the bearer token for a slug from the workspace `auth-profiles.json`.
+///
+/// Tries `provider:<slug>` first (new key format), then the bare `<slug>`
+/// (legacy format where keys were stored as `"openai"`, `"anthropic"`, etc.).
+/// Missing or empty keys return `Ok(String::new())` — callers treat that as
+/// "no auth", which surfaces an authentication error at first call rather than
+/// at factory build time.
+pub fn lookup_key_for_slug(slug: &str, config: &Config) -> anyhow::Result<String> {
+ // Ahead of the stored profiles, and scoped to the one slug the per-call
+ // route registers. A caller that named an endpoint and a bearer for this
+ // turn has said where the credential comes from, and there is nothing on
+ // disk to find for a slug that exists only in this `Config` copy. Scoping it
+ // by slug is what keeps the bearer from reaching a provider the caller never
+ // named — the same containment the legacy `config.api_key` fallback below
+ // gets from `legacy_inference_slug`.
+ if slug == crate::config::schema::EPHEMERAL_ROUTE_SLUG {
+ if let Some(route) = config.ephemeral_route.as_ref() {
+ log::debug!(
+ "[providers][chat-factory] auth lookup slug={} key_present={} (per-call route)",
+ slug,
+ !route.api_key.trim().is_empty()
+ );
+ return Ok(route.api_key.trim().to_string());
+ }
+ }
+
+ let auth = AuthService::from_config(config);
+ // Try new-style key first.
+ let new_key = auth_key_for_slug(slug);
+ if let Ok(Some(k)) = auth.get_provider_bearer_token(&new_key, None) {
+ if !k.is_empty() {
+ log::debug!(
+ "[providers][chat-factory] auth lookup slug={} key_present=true (new-style)",
+ slug
+ );
+ return Ok(k);
+ }
+ }
+ // Fall back to legacy bare slug.
+ let key = auth
+ .get_provider_bearer_token(slug, None)
+ .map_err(|e| {
+ anyhow::anyhow!(
+ "[chat-factory] failed to read API key for slug '{}': {}",
+ slug,
+ e
+ )
+ })?
+ .unwrap_or_default();
+ if !key.is_empty() {
+ log::debug!(
+ "[providers][chat-factory] auth lookup slug={} key_present=true",
+ slug
+ );
+ return Ok(key);
+ }
+
+ // OAuth fallback for `openai` runs only after standard API-key resolution
+ // returns empty, so env/audit/metrics in the standard path always execute
+ // and the OAuth path never silently bypasses provider-agnostic logic.
+ if slug == "openai" {
+ match crate::inference::openai_oauth::lookup_openai_bearer_token(config) {
+ Ok(Some(token)) if !token.is_empty() => {
+ log::debug!(
+ "[providers][chat-factory] auth lookup slug={} key_present=true (oauth)",
+ slug
+ );
+ return Ok(token);
+ }
+ Ok(_) => {}
+ Err(e) => {
+ return Err(anyhow::anyhow!(
+ "[chat-factory] openai oauth lookup failed: {e}"
+ ));
+ }
+ }
+ }
+
+ // Fallback: read from top-level config.api_key (direct config.toml api_key).
+ // This handles the case where a key was set in config.toml but not saved
+ // through the UI into auth-profiles.json.
+ //
+ // Scoped to the legacy direct-inference provider only — the cloud-provider
+ // slug whose endpoint matches `config.inference_url`. `config.api_key` was
+ // historically paired with `inference_url` for direct endpoint routing, so
+ // an unscoped fallback would leak this global key to any other provider
+ // whose auth-profile lookup returned empty (cross-provider credential leak
+ // flagged by CodeRabbit + maintainers on #2724).
+ if legacy_inference_slug(config) == Some(slug) {
+ if let Some(config_key) = config.api_key.as_ref() {
+ if !config_key.trim().is_empty() {
+ log::debug!(
+ "[providers][chat-factory] auth lookup slug={} key_present=true (config.toml fallback for legacy inference_url)",
+ slug
+ );
+ return Ok(config_key.trim().to_string());
+ }
+ }
+ }
+
+ log::debug!(
+ "[providers][chat-factory] auth lookup slug={} key_present=false",
+ slug
+ );
+ Ok(String::new())
+}
+
+/// Return a safe-to-log representation of a URL endpoint: `scheme://host` only.
+pub fn redact_endpoint(url: &str) -> String {
+ let trimmed = url.trim();
+ if let Some(rest) = trimmed.split_once("://") {
+ let scheme = rest.0;
+ let authority = rest.1.split('/').next().unwrap_or("");
+ let host = authority.split('@').next_back().unwrap_or(authority);
+ let host_no_query = host.split('?').next().unwrap_or(host);
+ return format!("{}://{}", scheme, host_no_query);
+ }
+ "<endpoint>".to_string()
+}
diff --git a/crates/openhuman-core/src/inference/provider/factory/local_runtime.rs b/crates/openhuman-core/src/inference/provider/factory/local_runtime.rs
new file mode 100644
index 0000000000..62a8246ab6
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/factory/local_runtime.rs
@@ -0,0 +1,199 @@
+use super::*;
+
+/// Local OpenAI-compatible runtimes (Ollama / LM Studio / MLX / OMLX /
+/// local-openai) as a crate-native [`ChatModel`] (issue #4727).
+///
+/// Returns `None` when `role` does not resolve to a local runtime, allowing
+/// [`create_chat_model_with_model_id`] to try cloud/BYOK/CLI constructors.
+///
+/// Endpoint/auth/`num_ctx` resolution uses the shared
+/// `ollama_base_url_from_config` / `lm_studio_base_url` / profile helpers. It
+/// runs the host access gates for custom/local providers —
+/// [`enforce_local_only_inference`] (privacy mode) +
+/// [`verify_session_active`] (session requirement) — so routing a local runtime
+/// here cannot bypass either. Temperature rides the per-call `ModelRequest` on
+/// the crate path (parity with the managed-backend cutover; the `@<temp>` suffix
+/// still bakes a fixed override).
+///
+pub(super) type ResolvedChatModel = (Arc<dyn ChatModel<()>>, String);
+
+pub(super) type OptionalChatModelResult = Option<anyhow::Result<ResolvedChatModel>>;
+
+pub(super) fn try_create_local_runtime_chat_model(role: &str, config: &Config) -> OptionalChatModelResult {
+ let resolved = provider_for_role(role, config);
+ try_create_local_runtime_chat_model_from_string(role, &resolved, config, true)
+}
+
+pub(super) fn try_create_local_runtime_chat_model_from_string(
+ role: &str,
+ provider: &str,
+ config: &Config,
+ require_session: bool,
+) -> OptionalChatModelResult {
+ use crate::inference::local::profile::{
+ LOCAL_OPENAI_PROFILE, MLX_PROFILE, OMLX_PROFILE,
+ };
+
+ let p = provider.trim().to_string();
+ let is_local = p.starts_with(OLLAMA_PROVIDER_PREFIX)
+ || p.starts_with(LM_STUDIO_PROVIDER_PREFIX)
+ || p.starts_with(MLX_PROVIDER_PREFIX)
+ || p.starts_with(OMLX_PROVIDER_PREFIX)
+ || p.starts_with(LOCAL_OPENAI_PROVIDER_PREFIX);
+ if !is_local {
+ return None;
+ }
+
+ // Preserve host privacy-mode refusal + the session requirement for
+ // custom/local providers.
+ if let Err(e) = enforce_local_only_inference(role, &p) {
+ return Some(Err(e));
+ }
+ if require_session {
+ #[cfg(not(test))]
+ if let Err(e) = verify_session_active(config) {
+ return Some(Err(e));
+ }
+ }
+
+ // Egress spine (privacy epic S2, #4436): committed to a local runtime here
+ // (past the non-local `None` return + access gates). Disclose it as
+ // NON-external — local inference never leaves the device, so
+ // `emit_external_transfer` records it without firing a pending event. This
+ // is the single local chokepoint for every ChatModel/turn entry.
+ emit_inference_egress(role, &p);
+
+ let unsupported = config.temperature_unsupported_models.clone();
+ let empty_model_err = |p: &str, form: &str| {
+ anyhow::anyhow!("[chat-factory] provider string '{p}' has an empty model — use '{form}'")
+ };
+
+ // Resolve the local `api_key` + auth style shared by lmstudio/omlx/local-openai
+ // (Bearer when a key is configured, else no auth — same as the host builders).
+ let keyed_auth = || {
+ let api_key = config.local_ai.api_key.as_deref().unwrap_or("").to_string();
+ let auth = if api_key.trim().is_empty() {
+ CompatAuthStyle::None
+ } else {
+ CompatAuthStyle::Bearer
+ };
+ (api_key, auth)
+ };
+ // First env override, else `local_ai.base_url`, else the profile default.
+ let env_or_config_url = |env: &str, default: &str| {
+ std::env::var("OPENHUMAN_LOCAL_INFERENCE_URL")
+ .ok()
+ .filter(|s| !s.trim().is_empty())
+ .or_else(|| std::env::var(env).ok().filter(|s| !s.trim().is_empty()))
+ .or_else(|| config.local_ai.base_url.clone())
+ .unwrap_or_else(|| default.to_string())
+ };
+
+ if let Some(rest) = p.strip_prefix(OLLAMA_PROVIDER_PREFIX) {
+ let (model, temp) = split_model_and_temperature(rest);
+ if model.is_empty() {
+ return Some(Err(empty_model_err(&p, "ollama:<model-id>")));
+ }
+ // Ollama exposes the OpenAI-compatible endpoint at `/v1`.
+ let base_url = crate::inference::local::ollama_base_url_from_config(config);
+ let normalized = base_url.trim_end_matches('/').trim_end_matches("/v1");
+ let endpoint = format!("{normalized}/v1");
+ let chat = super::crate_openai::make_crate_local_runtime_chat_model(
+ "ollama",
+ &endpoint,
+ "",
+ CompatAuthStyle::None,
+ &model,
+ &unsupported,
+ temp,
+ config.local_ai.num_ctx,
+ );
+ return Some(Ok((chat, model)));
+ }
+ if let Some(rest) = p.strip_prefix(LM_STUDIO_PROVIDER_PREFIX) {
+ let (model, temp) = split_model_and_temperature(rest);
+ if model.is_empty() {
+ return Some(Err(empty_model_err(&p, "lmstudio:<model-id>")));
+ }
+ let endpoint = crate::inference::local::lm_studio::lm_studio_base_url(config);
+ let (api_key, auth) = keyed_auth();
+ let chat = super::crate_openai::make_crate_local_runtime_chat_model(
+ "lmstudio",
+ &endpoint,
+ &api_key,
+ auth,
+ &model,
+ &unsupported,
+ temp,
+ None,
+ );
+ return Some(Ok((chat, model)));
+ }
+ if let Some(rest) = p.strip_prefix(MLX_PROVIDER_PREFIX) {
+ let (model, temp) = split_model_and_temperature(rest);
+ if model.is_empty() {
+ return Some(Err(empty_model_err(&p, "mlx:<model-id>")));
+ }
+ let endpoint = env_or_config_url("MLX_SERVER_URL", MLX_PROFILE.default_base_url);
+ let chat = super::crate_openai::make_crate_local_runtime_chat_model(
+ "mlx",
+ &endpoint,
+ "",
+ CompatAuthStyle::None,
+ &model,
+ &unsupported,
+ temp,
+ None,
+ );
+ return Some(Ok((chat, model)));
+ }
+ if let Some(rest) = p.strip_prefix(OMLX_PROVIDER_PREFIX) {
+ let (model, temp) = split_model_and_temperature(rest);
+ if model.is_empty() {
+ return Some(Err(empty_model_err(&p, "omlx:<model-id>")));
+ }
+ let endpoint = env_or_config_url("OMLX_SERVER_URL", OMLX_PROFILE.default_base_url);
+ let (api_key, auth) = keyed_auth();
+ let chat = super::crate_openai::make_crate_local_runtime_chat_model(
+ "omlx",
+ &endpoint,
+ &api_key,
+ auth,
+ &model,
+ &unsupported,
+ temp,
+ None,
+ );
+ return Some(Ok((chat, model)));
+ }
+ if let Some(rest) = p.strip_prefix(LOCAL_OPENAI_PROVIDER_PREFIX) {
+ let (model, temp) = split_model_and_temperature(rest);
+ if model.is_empty() {
+ return Some(Err(empty_model_err(&p, "local-openai:<model-id>")));
+ }
+ let endpoint = env_or_config_url("LOCAL_OPENAI_URL", LOCAL_OPENAI_PROFILE.default_base_url);
+ let (api_key, auth) = keyed_auth();
+ let chat = super::crate_openai::make_crate_local_runtime_chat_model(
+ "local-openai",
+ &endpoint,
+ &api_key,
+ auth,
+ &model,
+ &unsupported,
+ temp,
+ None,
+ );
+ return Some(Ok((chat, model)));
+ }
+ None
+}
+
+/// Build a crate-native local-runtime model for setup/probe calls that run
+/// before the desktop session gate is established.
+pub(crate) fn create_local_chat_model_from_string(
+ provider: &str,
+ config: &Config,
+) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {
+ try_create_local_runtime_chat_model_from_string("chat", provider, config, false)
+ .ok_or_else(|| anyhow::anyhow!("unsupported local provider string '{provider}'"))?
+}
diff --git a/crates/openhuman-core/src/inference/provider/factory/managed_backend.rs b/crates/openhuman-core/src/inference/provider/factory/managed_backend.rs
new file mode 100644
index 0000000000..99c69cd7f7
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/factory/managed_backend.rs
@@ -0,0 +1,240 @@
+use super::*;
+
+/// Canonical managed-backend tier for a specialised workload role.
+///
+/// The managed backend otherwise derives its model from `config.default_model`
+/// (which defaults to the `chat-v1` tier), so a tier-specific workload whose
+/// per-workload provider is unset would silently inherit the global default —
+/// e.g. the `code_executor` sub-agent (`hint = "coding"`) would run on `chat-v1`
+/// instead of the dedicated `coding-v1` tier, defeating the whole point of the
+/// hint. The `hint:<tier>` translation in [`make_openhuman_backend`] only fires
+/// when the *model string itself* is `hint:coding`; here the model originates
+/// from `default_model`, so the workload role is the only signal left and must
+/// be mapped explicitly.
+///
+/// Returns `Some(tier)` for the specialised roles that map 1:1 to a managed
+/// tier (`reasoning`, `agentic`, `coding`, `vision`, `subconscious`). Returns
+/// `None` for:
+///
+/// - the generic `chat` role (and any other background/unknown role), which
+/// keeps inheriting `default_model`: the front-line chat turn and legacy
+/// `default_model = "reasoning-v1"` installs deliberately fall through to the
+/// `chat` role (see the session builder) and rely on `default_model` driving
+/// the model — pinning `chat` here would regress them.
+/// - `summarization` / `memory`, which are pinned in a dedicated branch of
+/// [`make_openhuman_backend`] via [`summarization_tier_model`] (fixed at
+/// `summarization-v1`) rather than here, only so the `memory` alias and the
+/// role string share one resolution site. They do **not** fall through to
+/// `default_model`.
+///
+/// `subconscious` IS pinned (to the lightweight `chat-v1` tier) even though it
+/// is a background workload: the cloud subconscious tick builds via the session
+/// builder with `default_model = "hint:subconscious"` (a role-routing marker, not
+/// a real tier), so "inherit `default_model`" would forward that marker to the
+/// backend. Pinning here resolves the managed model declaratively to `chat-v1` —
+/// the cheap monitoring tier the workload wants — independent of `default_model`,
+/// while [`provider_for_role`] still lets `subconscious_provider` choose the
+/// provider (managed / BYOK / local).
+///
+/// For `vision` the default-inheritance mismatch is not just suboptimal but
+/// fatal: an unset `vision_provider` would resolve to `chat-v1`,
+/// `model_supports_vision` would report `false`, and the turn engine would strip
+/// every attached image — leaving the managed vision sub-agent blind.
+pub(super) fn managed_tier_for_role(role: &str) -> Option<&'static str> {
+ use crate::config::{
+ MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1, MODEL_CODING_V1, MODEL_REASONING_V1,
+ MODEL_VISION_V1,
+ };
+ match role {
+ "reasoning" => Some(MODEL_REASONING_V1),
+ "agentic" => Some(MODEL_AGENTIC_V1),
+ "coding" => Some(MODEL_CODING_V1),
+ // Burst rides the managed backend's high-throughput tier. Pinned here
+ // (rather than collapsing to `default_model`) so `hint = "burst"`
+ // workers actually reach `burst-v1`.
+ // There is no `burst_provider` knob: burst is managed-only.
+ "burst" => Some(MODEL_BURST_V1),
+ "vision" => Some(MODEL_VISION_V1),
+ // Background subconscious tick/triage: pinned to the lightweight chat
+ // tier (see the doc above for why it is pinned despite being background).
+ "subconscious" => Some(MODEL_CHAT_V1),
+ _ => None,
+ }
+}
+
+/// The **managed-backend** summarization tier model — fixed at
+/// [`MODEL_SUMMARIZATION_V1`] (`summarization-v1`).
+///
+/// Read **only** on the managed OpenHuman path (inside [`make_openhuman_backend`]),
+/// so it is consumed iff the `summarization`/`memory` role actually resolves to
+/// the managed backend — BYOK and local routes carry their own model in the
+/// provider string and never reach here.
+///
+/// The managed summarization tier is intentionally **not** user-overridable: the
+/// hosted backend serves exactly one tier (`summarization-v1`) for this workload,
+/// so there is nothing else valid to point it at. Users who want a different
+/// model run summarization on a BYOK/local `memory_provider`, where the model
+/// rides in the provider string. (`memory_tree.cloud_llm_model` is no longer
+/// consumed — see its config doc.)
+pub(crate) fn summarization_tier_model() -> &'static str {
+ crate::config::MODEL_SUMMARIZATION_V1
+}
+
+/// Build the OpenHuman backend provider (session-JWT auth).
+///
+/// `role` is the workload name (e.g. `"chat"`, `"coding"`, `"vision"`). A
+/// specialised workload role is pinned to its canonical managed tier via
+/// [`managed_tier_for_role`] so the `hint = "..."` a sub-agent declares actually
+/// reaches the matching backend tier instead of collapsing to `default_model`.
+/// The `summarization`/`memory` roles resolve their tier from
+/// [`summarization_tier_model`] (fixed at `summarization-v1`) so they never
+/// collapse to `default_model`. The generic `chat` role (and background roles)
+/// keep inheriting `config.default_model`.
+/// Resolve the managed OpenHuman backend for `role` — the model id (tier /
+/// summarization / default, with `hint:<tier>` translation) plus a configured
+/// [`OpenHumanBackendModel`]. Shared by both the `Provider` path
+/// ([`make_openhuman_backend`]) and the crate `ChatModel` path
+/// ([`make_openhuman_backend_model`], issue #4727 Motion B).
+pub(super) fn resolve_managed_backend(
+ role: &str,
+ config: &Config,
+) -> anyhow::Result<(OpenHumanBackendModel, String)> {
+ resolve_managed_backend_with_model_override(role, config, None)
+}
+
+pub(super) fn resolve_managed_backend_with_model_override(
+ role: &str,
+ config: &Config,
+ model_override: Option<&str>,
+) -> anyhow::Result<(OpenHumanBackendModel, String)> {
+ let model = if let Some(tier) = managed_tier_for_role(role) {
+ log::debug!(
+ "[providers][chat-factory] role={} pinned to managed tier model={}",
+ role,
+ tier
+ );
+ tier.to_string()
+ } else if matches!(role, "summarization" | "memory") {
+ // Managed summarization/memory tier — fixed at `summarization-v1` rather
+ // than inherited from `config.default_model`, so every managed
+ // summarization caller — the memory tree, the chat-turn payload
+ // summarizer, meeting summaries, and any `hint = "summarization"`
+ // sub-agent — reaches the dedicated tier instead of silently collapsing
+ // to `chat-v1`. BYOK/local routes never reach here — they build from the
+ // provider string.
+ let tier = summarization_tier_model().to_string();
+ log::debug!(
+ "[providers][chat-factory] role={} resolved managed summarization tier model={}",
+ role,
+ tier
+ );
+ tier
+ } else {
+ config
+ .default_model
+ .clone()
+ .filter(|m| !m.trim().is_empty())
+ .unwrap_or_else(|| "reasoning-v1".to_string())
+ };
+ // Critical: pass the *config's* workspace directory through so the
+ // provider's `AuthService` reads `auth-profiles.json` from the
+ // same dir login wrote to. Without this, `ProviderRuntimeOptions::default()`
+ // leaves `openhuman_dir = None`, the provider falls back to
+ // `~/.openhuman`, and reads an unrelated (or empty)
+ // profile store — surfacing as "No backend session: store a JWT
+ // via auth (app-session)" even though login just succeeded in the
+ // user's actual workspace (e.g. test workspaces under OPENHUMAN_WORKSPACE).
+ let options = ProviderRuntimeOptions {
+ openhuman_dir: config.config_path.parent().map(std::path::PathBuf::from),
+ secrets_encrypt: config.secrets.encrypt,
+ ..ProviderRuntimeOptions::default()
+ };
+ log::debug!(
+ "[providers][chat-factory] building openhuman backend provider model={} state_dir={:?} secrets_encrypt={}",
+ model,
+ options.openhuman_dir,
+ options.secrets_encrypt
+ );
+ // Translate `hint:<tier>` model strings into the OpenHuman backend's
+ // canonical tier names. Unrecognised `hint:*` strings (e.g. `hint:reaction`
+ // for lightweight models) are forwarded as-is — the backend is authoritative
+ // over which hint values it accepts, and the web-chat model_override path
+ // uses these verbatim. Only non-hint strings that are not a known canonical
+ // tier (stale `default_model` values written by older UI versions, e.g.
+ // "deepseek-v4-pro", "claude-opus-4-7") fall back to the platform default.
+ let model = match model.strip_prefix("hint:") {
+ Some("reasoning") => crate::config::MODEL_REASONING_V1.to_string(),
+ Some("chat") => crate::config::MODEL_CHAT_V1.to_string(),
+ Some("agentic") => crate::config::MODEL_AGENTIC_V1.to_string(),
+ Some("burst") => crate::config::MODEL_BURST_V1.to_string(),
+ Some("coding") => crate::config::MODEL_CODING_V1.to_string(),
+ Some("summarization") => crate::config::MODEL_SUMMARIZATION_V1.to_string(),
+ Some("vision") => crate::config::MODEL_VISION_V1.to_string(),
+ Some(_) => {
+ // Unrecognised hint — forward verbatim; the backend decides validity.
+ model
+ }
+ None => {
+ // `model` is guaranteed non-empty here: an empty/whitespace
+ // `default_model` was already normalised to `reasoning-v1` above, and
+ // the managed-tier / summarization branches yield non-empty tier
+ // constants. So a non-`hint:` id is either a known canonical tier or a
+ // raw/BYOK id the user pinned — both forward verbatim; only the log
+ // line differs.
+ if is_known_openhuman_tier(&model) {
+ model
+ } else {
+ // Unrecognised NON-empty model id — a raw/BYOK model the user
+ // pinned (e.g. `claude-opus-4`, written into `default_model` or
+ // a per-agent model pin). Forward it verbatim so the selected
+ // model actually reaches provider construction instead of the
+ // core silently collapsing it onto `reasoning-v1`. The managed
+ // backend is authoritative over validity and returns a clear
+ // error for a genuinely bad id (issue #4598).
+ log::debug!(
+ "[providers][chat-factory] forwarding raw/BYOK model '{}' verbatim to the \
+ OpenHuman backend (not a managed tier); the backend validates it",
+ model
+ );
+ model
+ }
+ }
+ };
+ let model = model_override
+ .map(str::trim)
+ .filter(|model| !model.is_empty())
+ .map(ToOwned::to_owned)
+ .unwrap_or(model);
+
+ // Egress spine (privacy epic S2, #4436): managed backend resolution is the
+ // universal chokepoint for EVERY managed-backend inference construction —
+ // the direct ChatModel path and both turn paths
+ // (`create_turn_chat_model[_from_string]_with_native_tools`) resolve here.
+ // Emitting once here guarantees the default managed chat turn discloses
+ // egress exactly once (see `emit_inference_egress`).
+ crate::security::egress::emit_external_transfer(
+ crate::security::egress::EgressDescriptor::inference("openhuman", &model, true),
+ );
+ Ok((
+ OpenHumanBackendModel::new(config.api_url.as_deref(), &options, model.clone()),
+ model,
+ ))
+}
+
+/// The managed OpenHuman backend as a crate-native host `ChatModel`
+/// ([`OpenHumanBackendModel`], issue #4727 Motion B) — the cutover replacement
+/// for the `Provider` path. Same resolution; wraps the backend so the harness
+/// holds a crate `ChatModel` and the dynamic JWT + `thread_id` + billing envelope
+/// are bridged onto the crate wire client per call.
+pub(crate) fn make_openhuman_backend_model(
+ role: &str,
+ config: &Config,
+) -> anyhow::Result<(
+ std::sync::Arc<dyn tinyinference::model::ChatModel<()>>,
+ String,
+)> {
+ let (model_client, model) = resolve_managed_backend(role, config)?;
+ let chat: std::sync::Arc<dyn tinyinference::model::ChatModel<()>> =
+ std::sync::Arc::new(model_client);
+ Ok((chat, model))
+}
diff --git a/crates/openhuman-core/src/inference/provider/factory/primary_cloud.rs b/crates/openhuman-core/src/inference/provider/factory/primary_cloud.rs
new file mode 100644
index 0000000000..049303f1c0
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/factory/primary_cloud.rs
@@ -0,0 +1,189 @@
+use super::*;
+
+pub(super) fn resolve_primary_cloud_provider_string(config: &Config) -> String {
+ let primary = config
+ .primary_cloud
+ .as_deref()
+ .and_then(|id| config.cloud_providers.iter().find(|entry| entry.id == id));
+
+ if primary.is_some_and(is_openhuman_cloud_entry) {
+ if let Some(legacy) = legacy_custom_inference_provider_string(config) {
+ return legacy;
+ }
+ // Primary is explicitly OpenHuman but inference_url points at a custom
+ // endpoint with no matching provider entry — this is a half-migrated BYOK
+ // config. Fail closed so the user sees an actionable error rather than
+ // silently routing through the managed backend.
+ if has_custom_inference_intent(config) {
+ log::debug!(
+ "[providers][chat-factory] BYOK intent detected (host={}) \
+ but no matching cloud_providers entry found; returning fail-closed sentinel",
+ redact_inference_url(config.inference_url.as_deref())
+ );
+ return BYOK_INCOMPLETE_SENTINEL.to_string();
+ }
+ }
+
+ if let Some(entry) = primary {
+ return cloud_entry_provider_string(entry, config);
+ }
+
+ // No explicit primary configured. If inference_url signals custom intent but
+ // no matching provider entry exists, fail closed instead of falling back to
+ // the managed backend.
+ legacy_custom_inference_provider_string(config).unwrap_or_else(|| {
+ if has_custom_inference_intent(config) {
+ log::debug!(
+ "[providers][chat-factory] BYOK intent detected (host={}) \
+ with no primary_cloud and no matching provider entry; returning fail-closed sentinel",
+ redact_inference_url(config.inference_url.as_deref())
+ );
+ BYOK_INCOMPLETE_SENTINEL.to_string()
+ } else {
+ PROVIDER_OPENHUMAN.to_string()
+ }
+ })
+}
+
+/// Extract the host portion of an inference URL for safe logging.
+///
+/// Returns the host (e.g. `"api.example.com"`) so log lines are grep-friendly
+/// without exposing tokens or credentials that may appear in query-string or
+/// path components of a bearer-auth URL (e.g. `"https://host/v1?key=…"`).
+/// Falls back to `"<redacted>"` when the URL cannot be parsed or is absent.
+pub(super) fn redact_inference_url(url: Option<&str>) -> &str {
+ url.and_then(|u| {
+ // Minimal host extraction: find the authority after "://".
+ let after_scheme = u.find("://").map(|i| &u[i + 3..])?;
+ // Authority ends at '/', '?', '#', or end-of-string.
+ let host_end = after_scheme
+ .find(['/', '?', '#'])
+ .unwrap_or(after_scheme.len());
+ let authority = &after_scheme[..host_end];
+ // Strip optional "user:pass@" and port.
+ let host = authority
+ .rfind('@')
+ .map_or(authority, |i| &authority[i + 1..]);
+ let host = host.rfind(':').map_or(host, |i| &host[..i]);
+ if host.is_empty() {
+ None
+ } else {
+ Some(host)
+ }
+ })
+ .unwrap_or("<redacted>")
+}
+
+/// Return `true` when the config contains a non-openhuman `inference_url`,
+/// indicating the user intends custom/BYOK routing rather than the managed
+/// backend.
+pub(super) fn has_custom_inference_intent(config: &Config) -> bool {
+ config
+ .inference_url
+ .as_deref()
+ .map(str::trim)
+ .filter(|url| !url.is_empty())
+ .is_some_and(|url| !looks_like_openhuman_backend(url))
+}
+
+pub(super) fn legacy_custom_inference_provider_string(config: &Config) -> Option<String> {
+ let inference_url = config
+ .inference_url
+ .as_deref()
+ .map(str::trim)
+ .filter(|url| !url.is_empty())?;
+
+ if looks_like_openhuman_backend(inference_url) {
+ return None;
+ }
+
+ let normalized_inference = normalize_endpoint_for_compare(inference_url);
+ config
+ .cloud_providers
+ .iter()
+ .find(|entry| {
+ !is_openhuman_cloud_entry(entry)
+ && normalize_endpoint_for_compare(&entry.endpoint) == normalized_inference
+ })
+ .map(|entry| cloud_entry_provider_string(entry, config))
+}
+
+/// Resolve the slug of the cloud-provider entry that represents the legacy
+/// direct-inference route — the entry whose endpoint matches the configured
+/// custom `inference_url`.
+///
+/// Top-level `config.api_key` was historically paired with `inference_url`
+/// for direct endpoint routing, so it is scoped to this single provider. The
+/// `lookup_key_for_slug` fallback uses this to avoid leaking the global key to
+/// any other provider slug whose auth-profile lookup returned empty.
+pub(super) fn legacy_inference_slug(config: &Config) -> Option<&str> {
+ let inference_url = config
+ .inference_url
+ .as_deref()
+ .map(str::trim)
+ .filter(|url| !url.is_empty())?;
+
+ if looks_like_openhuman_backend(inference_url) {
+ return None;
+ }
+
+ let normalized_inference = normalize_endpoint_for_compare(inference_url);
+ config
+ .cloud_providers
+ .iter()
+ .find(|entry| {
+ !is_openhuman_cloud_entry(entry)
+ && normalize_endpoint_for_compare(&entry.endpoint) == normalized_inference
+ })
+ .map(|entry| entry.slug.as_str())
+}
+
+pub(super) fn cloud_entry_provider_string(
+ entry: &crate::config::schema::cloud_providers::CloudProviderCreds,
+ config: &Config,
+) -> String {
+ if is_openhuman_cloud_entry(entry) {
+ return PROVIDER_OPENHUMAN.to_string();
+ }
+
+ let model = entry
+ .default_model
+ .as_deref()
+ .map(str::trim)
+ .filter(|model| !model.is_empty())
+ .or_else(|| {
+ config
+ .default_model
+ .as_deref()
+ .map(str::trim)
+ .filter(|model| !model.is_empty())
+ })
+ .unwrap_or(crate::config::DEFAULT_MODEL);
+
+ format!("{}:{model}", entry.slug)
+}
+
+pub(super) fn is_openhuman_cloud_entry(
+ entry: &crate::config::schema::cloud_providers::CloudProviderCreds,
+) -> bool {
+ entry.slug == PROVIDER_OPENHUMAN
+ || matches!(entry.auth_style, AuthStyle::OpenhumanJwt)
+ || looks_like_openhuman_backend(&entry.endpoint)
+}
+
+pub(super) fn normalize_endpoint_for_compare(url: &str) -> String {
+ url.trim().trim_end_matches('/').to_ascii_lowercase()
+}
+
+pub(super) fn looks_like_openhuman_backend(url: &str) -> bool {
+ let lower = url.trim().to_ascii_lowercase();
+ let without_scheme = lower.split("://").nth(1).unwrap_or(&lower);
+ let authority = without_scheme.split('/').next().unwrap_or("");
+ let host = authority.split('@').next_back().unwrap_or(authority);
+ let host_no_port = host.split(':').next().unwrap_or(host);
+ matches!(
+ host_no_port,
+ "api.openhuman.ai" | "api.tinyhumans.ai" | "staging-api.tinyhumans.ai" | "openhuman"
+ ) || host_no_port.ends_with(".openhuman.ai")
+ || host_no_port.ends_with(".tinyhumans.ai")
+}
diff --git a/crates/openhuman-core/src/inference/provider/factory/routing.rs b/crates/openhuman-core/src/inference/provider/factory/routing.rs
new file mode 100644
index 0000000000..2a15fb6f1f
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/factory/routing.rs
@@ -0,0 +1,206 @@
+use super::*;
+
+/// The provider route a role has **explicitly** configured, before any
+/// fallback.
+///
+/// Split out of [`provider_for_role`] so the fallback machinery can ask the
+/// same question the router asks — "did the user route this role anywhere?" —
+/// without re-deriving the role→config-field mapping and drifting from it.
+pub(super) fn configured_route_for_role<'a>(role: &str, config: &'a Config) -> Option<&'a str> {
+ match role {
+ "chat" => config.chat_provider.as_deref(),
+ "reasoning" => config.reasoning_provider.as_deref(),
+ "agentic" => config.agentic_provider.as_deref(),
+ "coding" => config.coding_provider.as_deref(),
+ // Burst uses the existing Agentic workload route for BYOK/local parity.
+ // If unset, it falls through to the managed backend and is pinned to
+ // `burst-v1` by `managed_tier_for_role`.
+ "burst" => config.agentic_provider.as_deref(),
+ // Tier-specific multimodal model; when unset it falls through to
+ // `primary_cloud` (→ managed `vision-v1`), as every unset route now does.
+ "vision" => config.vision_provider.as_deref(),
+ // `memory_provider` covers both the memory-tree extract path and
+ // the summarizer sub-agent (whose definition declares
+ // `hint = "summarization"`). Both are "produce a condensed
+ // representation of input text" — same model class, no reason
+ // for a separate config knob.
+ "memory" | "summarization" => config.memory_provider.as_deref(),
+ "embeddings" => config.embeddings_provider.as_deref(),
+ "heartbeat" => config.heartbeat_provider.as_deref(),
+ "learning" => config.learning_provider.as_deref(),
+ "subconscious" => config.subconscious_provider.as_deref(),
+ _ => None,
+ }
+}
+
+/// Whether `role` reached a cloud slug by *implicit fallback* rather than by an
+/// explicit route.
+///
+/// True only when the role is one of the cloud-fallback background roles **and**
+/// its own route is unset (or the literal `"cloud"`). An explicitly configured
+/// cloud route — say `vision_provider = "anthropic:claude-…"` — is not a
+/// fallback, so a credential failure there must not be explained as "your local
+/// chat model cannot do this".
+pub(crate) fn role_uses_implicit_cloud_fallback(role: &str, config: &Config) -> bool {
+ if !super::fallback_diagnostics::role_falls_back_to_cloud(role) {
+ return false;
+ }
+ let route = configured_route_for_role(role, config).unwrap_or("").trim();
+ route.is_empty() || route == "cloud"
+}
+
+/// Return the configured provider string for a named workload role.
+///
+/// Empty / `"cloud"` resolves through `primary_cloud`. **Every** role behaves
+/// this way, and no role uses a sibling's BYOK provider as a fallback.
+///
+/// "Resolves through `primary_cloud`" is not the same as "goes to the managed
+/// backend": [`resolve_primary_cloud_provider_string`] may yield a legacy
+/// external `inference_url` (see below), or the fail-closed sentinel for a
+/// half-migrated BYOK config. The guarantee here is narrower and exact — an
+/// unset route does not borrow a *sibling's* configured provider.
+///
+/// The deliberate *aliases* in [`configured_route_for_role`] are unaffected and
+/// remain: `burst` reads `agentic_provider` and `summarization` reads
+/// `memory_provider`. Those are two names for one configured route, which is a
+/// different thing from an unset route borrowing a set one.
+///
+/// Until #6109 the three chat-tier roles (`chat`, `reasoning`, `coding`) took a
+/// configured BYOK provider from *any* sibling first, so setting one route moved
+/// the other two onto that key — a user who pointed only `coding_provider` at
+/// their own OpenRouter account found ordinary chat billed there too, with no
+/// setting saying so. Each route now stands alone.
+///
+/// For backwards compatibility, a legacy external `inference_url` takes
+/// precedence when `primary_cloud` still points at OpenHuman because
+/// migration 1→2 preserved the URL as a custom provider entry but older
+/// configs did not explicitly set per-workload routes.
+pub fn provider_for_role(role: &str, config: &Config) -> String {
+ let opt = configured_route_for_role(role, config);
+ let s = opt.unwrap_or("").trim();
+ if s.is_empty() || s == "cloud" {
+ // #6109: an unset chat-tier route no longer inherits a sibling's BYOK
+ // provider. Setting only `coding_provider` used to move `chat` and
+ // `reasoning` onto that key too — ordinary conversations silently billed
+ // to the user's own account, with no settings field saying so. Each
+ // route now stands alone and an unset one falls through to the managed
+ // backend, the same as every other workload.
+
+ let resolved = resolve_primary_cloud_provider_string(config);
+
+ // #5146 §2.1: the fallback itself is correct and stays — background
+ // workloads run tier-specific models that local runtimes don't serve,
+ // and a local-chat + managed-subscription user genuinely wants them on
+ // the cloud. What was missing is the *explanation*: when this route
+ // later fails for want of a key, the user saw a bare slug-level auth
+ // error naming a provider they never configured. Emit the same
+ // user-facing sentence the error path uses, so the routing decision is
+ // visible in logs and support transcripts before anything goes wrong.
+ if super::fallback_diagnostics::role_falls_back_to_cloud(role) {
+ if let Some(chat) = config.chat_provider.as_deref() {
+ if crate::inference::local::profile::is_local_provider_string(chat) {
+ log::info!(
+ "[providers][local-fallback] role={} {}",
+ role,
+ super::fallback_diagnostics::cloud_fallback_notice(role, chat, &resolved)
+ );
+ }
+ }
+ }
+
+ resolved
+ } else {
+ s.to_string()
+ }
+}
+
+/// #3767: Whether the OpenHuman managed-credits gate should be bypassed for a
+/// single workload role.
+///
+/// Returns true when `role` resolves (via [`provider_for_role`]) to a non-managed
+/// provider the user funds themselves — a BYO cloud key (incl. OpenAI OAuth), a
+/// local runtime, or claude-code — with usable credentials. When the role is on
+/// the OpenHuman managed backend, or a BYO route has no usable key, it returns
+/// false (the gate stays on; #3767: "BYO key present but invalid/unverified →
+/// still gated").
+///
+/// The gate is evaluated per-tier so the UI can check the tier the user actually
+/// selected: the chat header's "Quick" mode runs on the `chat` tier and
+/// "Reasoning" mode on the `reasoning` tier, so each is checked respectively.
+/// These per-role results are surfaced under `credits_bypass` in the
+/// client-config snapshot. Tiers that stay managed and run anyway surface the
+/// per-call `USER_INSUFFICIENT_CREDITS` (402) error reactively.
+pub fn role_bypasses_managed_credits(role: &str, config: &Config) -> bool {
+ let resolved = provider_for_role(role, config);
+ let r = resolved.trim();
+ let is_managed =
+ r.is_empty() || r == "cloud" || r == PROVIDER_OPENHUMAN || r == BYOK_INCOMPLETE_SENTINEL;
+ let usable_byo = !is_managed && route_has_usable_credentials(r, config);
+ log::debug!(
+ "[billing] role_bypasses_managed_credits role={role} resolved={resolved} \
+ is_managed={is_managed} usable_byo={usable_byo}"
+ );
+ usable_byo
+}
+
+/// True when a resolved chat-tier provider string can actually run on the
+/// user's own funding: local runtimes / claude-code carry their own creds; a
+/// concrete cloud slug requires a non-empty stored key. Managed/sentinel
+/// strings are filtered by the caller and never reach here as "usable".
+pub(super) fn route_has_usable_credentials(resolved: &str, config: &Config) -> bool {
+ let r = resolved.trim();
+ // Local runtimes (ollama/lmstudio/mlx/local-openai) and the local CLI
+ // delegates carry their own credentials / run on-device.
+ if crate::inference::local::profile::is_local_provider_string(r)
+ || r.starts_with(crate::inference::provider::claude_code::PROVIDER_PREFIX)
+ || r == CLAUDE_AGENT_SDK_PROVIDER
+ || r.starts_with(CLAUDE_AGENT_SDK_PREFIX)
+ {
+ return true;
+ }
+ // Concrete cloud slug "<slug>:<model>" — require a usable stored key.
+ if let Some((slug, _)) = r.split_once(':') {
+ let slug = slug.trim();
+ if !slug.is_empty() {
+ // Don't silently swallow auth-store / OAuth lookup failures — a
+ // transient Err would otherwise keep the credits gate on for a
+ // valid BYO setup with no diagnostics. Log and treat as not-usable.
+ match lookup_key_for_slug(slug, config) {
+ Ok(key) => {
+ let usable = !key.trim().is_empty();
+ log::debug!(
+ "[billing] route_has_usable_credentials slug={slug} usable={usable}"
+ );
+ return usable;
+ }
+ Err(e) => {
+ log::debug!(
+ "[billing] route_has_usable_credentials slug={slug} lookup_error={e}"
+ );
+ return false;
+ }
+ }
+ }
+ }
+ false
+}
+
+/// Parse a `<model>[@<temp>]` tail into `(model, override)`.
+///
+/// Tolerates whitespace around the components. Returns `temperature = None`
+/// when the suffix is absent or unparseable — the model text is taken as-is.
+pub(super) fn split_model_and_temperature(raw: &str) -> (String, Option<f64>) {
+ let trimmed = raw.trim();
+ if let Some(at_pos) = trimmed.rfind('@') {
+ let head = trimmed[..at_pos].trim();
+ let tail = trimmed[at_pos + 1..].trim();
+ if !head.is_empty() {
+ if let Ok(parsed) = tail.parse::<f64>() {
+ if parsed.is_finite() {
+ return (head.to_string(), Some(parsed));
+ }
+ }
+ }
+ }
+ (trimmed.to_string(), None)
+}
diff --git a/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs b/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs
new file mode 100644
index 0000000000..7179333511
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs
@@ -0,0 +1,116 @@
+use super::*;
+
+/// Build the Claude Agent SDK subprocess directly as a crate model. This is a
+/// prompt-guided model: TinyAgents owns its text-tool protocol, while the
+/// provider owns only subprocess transport and NDJSON decoding.
+pub(super) fn try_create_claude_agent_sdk_chat_model(role: &str, config: &Config) -> OptionalChatModelResult {
+ let resolved = provider_for_role(role, config);
+ try_create_claude_agent_sdk_chat_model_from_string(role, &resolved, config)
+}
+
+pub(super) fn try_create_claude_agent_sdk_chat_model_from_string(
+ role: &str,
+ provider: &str,
+ config: &Config,
+) -> OptionalChatModelResult {
+ let model = match prepare_claude_agent_sdk_chat_model(role, provider, config)? {
+ Ok(model) => model,
+ Err(error) => return Some(Err(error)),
+ };
+ emit_inference_egress(role, &format!("{CLAUDE_AGENT_SDK_PREFIX}{model}"));
+ let chat: Arc<dyn ChatModel<()>> = Arc::new(ClaudeAgentSdkProvider::for_model(
+ config.claude_agent_sdk.clone(),
+ model.clone(),
+ ));
+ Some(Ok((chat, model)))
+}
+
+pub(super) fn prepare_claude_agent_sdk_chat_model(
+ role: &str,
+ provider: &str,
+ config: &Config,
+) -> Option<anyhow::Result<String>> {
+ let model = claude_agent_sdk_model_from_string(provider, config)?;
+ if let Err(error) = enforce_local_only_inference(role, provider) {
+ return Some(Err(error));
+ }
+ #[cfg(not(test))]
+ if let Err(error) = verify_session_active(config) {
+ return Some(Err(error));
+ }
+ Some(Ok(model))
+}
+
+pub(super) fn claude_agent_sdk_model_from_string(provider: &str, config: &Config) -> Option<String> {
+ let provider = provider.trim();
+ let model = if provider == CLAUDE_AGENT_SDK_PROVIDER {
+ config.claude_agent_sdk.default_model.clone()
+ } else if let Some(model) = provider.strip_prefix(CLAUDE_AGENT_SDK_PREFIX) {
+ model.trim().to_string()
+ } else {
+ return None;
+ };
+ Some(model)
+}
+
+pub(super) fn try_create_claude_code_chat_model(
+ role: &str,
+ config: &Config,
+ model_override: Option<&str>,
+) -> OptionalChatModelResult {
+ let resolved = provider_for_role(role, config);
+ try_create_claude_code_chat_model_from_string(role, &resolved, config, model_override)
+}
+
+pub(super) fn try_create_claude_code_chat_model_from_string(
+ role: &str,
+ provider: &str,
+ config: &Config,
+ model_override: Option<&str>,
+) -> OptionalChatModelResult {
+ let provider = provider.trim();
+ let model_with_temp = provider
+ .strip_prefix(crate::inference::provider::claude_code::PROVIDER_PREFIX)?;
+ let (configured_model, temperature_override) = split_model_and_temperature(model_with_temp);
+ if temperature_override.is_some() {
+ log::warn!(
+ "[providers][chat-factory] claude-code provider: per-model temperature override \
+ is accepted but not wired through to the CLI — the @<temp> suffix is ignored"
+ );
+ }
+ if configured_model.is_empty() {
+ return Some(Err(anyhow::anyhow!(
+ "[chat-factory] provider string '{}' for role '{}' has an empty model — \
+ use 'claude-code:<model-id>'",
+ provider,
+ role
+ )));
+ }
+ if let Err(error) = enforce_local_only_inference(role, provider) {
+ return Some(Err(error));
+ }
+ #[cfg(not(test))]
+ if let Err(error) = verify_session_active(config) {
+ return Some(Err(error));
+ }
+ let workspace =
+ crate::inference::provider::claude_code::workspace_dir_from_config(config);
+ let effective_model = model_override.unwrap_or(&configured_model).to_string();
+ emit_inference_egress(
+ role,
+ &format!(
+ "{}{effective_model}",
+ crate::inference::provider::claude_code::PROVIDER_PREFIX
+ ),
+ );
+ let chat =
+ match crate::inference::provider::claude_code::ClaudeCodeProvider::from_env(
+ effective_model,
+ workspace,
+ config.action_dir.clone(),
+ ) {
+ Ok(model) => Arc::new(model) as Arc<dyn ChatModel<()>>,
+ Err(error) => return Some(Err(error)),
+ };
+ Some(Ok((chat, configured_model)))
+}
diff --git a/crates/openhuman-core/src/inference/provider/factory/tiers.rs b/crates/openhuman-core/src/inference/provider/factory/tiers.rs
new file mode 100644
index 0000000000..5767646339
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/factory/tiers.rs
@@ -0,0 +1,224 @@
+use super::*;
+
+pub(super) fn is_abstract_tier_model(model: &str) -> bool {
+ use crate::config::{
+ MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1, MODEL_CODING_V1, MODEL_REASONING_QUICK_V1,
+ MODEL_REASONING_V1, MODEL_SUMMARIZATION_V1, MODEL_VISION_V1,
+ };
+ let trimmed = model.trim();
+ trimmed == MODEL_REASONING_V1
+ || trimmed == MODEL_REASONING_QUICK_V1
+ || trimmed == MODEL_CHAT_V1
+ || trimmed == MODEL_AGENTIC_V1
+ || trimmed == MODEL_BURST_V1
+ || trimmed == MODEL_CODING_V1
+ || trimmed == MODEL_VISION_V1
+ || trimmed == MODEL_SUMMARIZATION_V1
+}
+
+/// Resolve a model hint (e.g. `"hint:reasoning"`) or tier name to the
+/// concrete model string that the provider router would use — without
+/// constructing the actual provider. Returns the provider-string prefix
+/// (e.g. `"openai"`) concatenated with the model when a BYOK provider is
+/// active, or the bare tier name for the managed OpenHuman backend.
+pub fn resolve_model_for_hint(hint_or_tier: &str, config: &Config) -> String {
+ let hint_to_tier: &[(&str, &str)] = &[
+ ("reasoning", crate::config::MODEL_REASONING_V1),
+ ("chat", crate::config::MODEL_CHAT_V1),
+ ("agentic", crate::config::MODEL_AGENTIC_V1),
+ ("burst", crate::config::MODEL_BURST_V1),
+ ("coding", crate::config::MODEL_CODING_V1),
+ ("vision", crate::config::MODEL_VISION_V1),
+ (
+ "summarization",
+ crate::config::MODEL_SUMMARIZATION_V1,
+ ),
+ // Background subconscious workload rides the lightweight chat tier on the
+ // managed backend; its `subconscious` *role* (handled below) still selects
+ // the provider via `subconscious_provider`.
+ ("subconscious", crate::config::MODEL_CHAT_V1),
+ ];
+ let tier_to_role: &[(&str, &str)] = &[
+ (crate::config::MODEL_REASONING_V1, "reasoning"),
+ (crate::config::MODEL_CHAT_V1, "chat"),
+ (crate::config::MODEL_REASONING_QUICK_V1, "chat"),
+ (crate::config::MODEL_AGENTIC_V1, "agentic"),
+ (crate::config::MODEL_BURST_V1, "burst"),
+ (crate::config::MODEL_CODING_V1, "coding"),
+ (crate::config::MODEL_VISION_V1, "vision"),
+ (
+ crate::config::MODEL_SUMMARIZATION_V1,
+ "summarization",
+ ),
+ ];
+
+ let (tier, role) = if let Some(hint_key) = hint_or_tier.strip_prefix("hint:") {
+ let tier = hint_to_tier
+ .iter()
+ .find(|(k, _)| *k == hint_key)
+ .map(|(_, v)| *v)
+ .unwrap_or(hint_or_tier);
+ // Background workloads map to a tier *model* but must keep their own
+ // role so `provider_for_role` reads their dedicated `*_provider` field
+ // rather than the chat-tier provider their model happens to share.
+ let role = match hint_key {
+ "subconscious" => "subconscious",
+ _ => tier_to_role
+ .iter()
+ .find(|(k, _)| *k == tier)
+ .map(|(_, v)| *v)
+ .unwrap_or(hint_key),
+ };
+ (tier, role)
+ } else {
+ let role = tier_to_role
+ .iter()
+ .find(|(k, _)| *k == hint_or_tier)
+ .map(|(_, v)| *v)
+ .unwrap_or("chat");
+ (hint_or_tier, role)
+ };
+
+ let provider_string = provider_for_role(role, config);
+ let ps = provider_string.trim();
+ if ps.is_empty() || ps == "cloud" || ps == PROVIDER_OPENHUMAN || ps == BYOK_INCOMPLETE_SENTINEL
+ {
+ tier.to_string()
+ } else if let Some(idx) = ps.find(':') {
+ let model_with_temp = &ps[idx + 1..];
+ let (model, _) = split_model_and_temperature(model_with_temp);
+ model
+ } else {
+ ps.to_string()
+ }
+}
+
+/// Map a managed tier name (or `hint:*` string) to the workload **role** whose
+/// configured provider serves it.
+///
+/// This is the inverse of the role→tier routing `create_chat_model` does:
+/// callers that select a model *per unit of work by tier* (e.g. a tinyflows
+/// `agent` node pinning `config.model = "reasoning-v1"`) use this to turn that
+/// tier back into the role, then call [`create_chat_model`] with it — so the
+/// completion routes to that tier on the managed backend (or the role's BYOK
+/// model) instead of some caller default. Unknown strings fall back to `"chat"`.
+///
+/// Kept deliberately small and standalone (no `Config`) — it is a pure lookup
+/// over the tier constants, mirroring the `tier_to_role` table inside
+/// [`resolve_model_for_hint`].
+pub fn role_for_model_tier(hint_or_tier: &str) -> &'static str {
+ use crate::config::{
+ MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1, MODEL_CODING_V1, MODEL_REASONING_QUICK_V1,
+ MODEL_REASONING_V1, MODEL_SUMMARIZATION_V1, MODEL_VISION_V1,
+ };
+
+ // Normalise a `hint:*` alias to its concrete tier first.
+ let tier = match hint_or_tier.strip_prefix("hint:") {
+ Some("reasoning") => MODEL_REASONING_V1,
+ Some("chat") => MODEL_CHAT_V1,
+ Some("agentic") => MODEL_AGENTIC_V1,
+ Some("burst") => MODEL_BURST_V1,
+ Some("coding") => MODEL_CODING_V1,
+ Some("vision") => MODEL_VISION_V1,
+ Some("summarization") => MODEL_SUMMARIZATION_V1,
+ // Background subconscious rides the chat tier for its model.
+ Some("subconscious") => MODEL_CHAT_V1,
+ Some(_) => hint_or_tier,
+ None => hint_or_tier,
+ };
+
+ match tier {
+ MODEL_REASONING_V1 => "reasoning",
+ MODEL_CHAT_V1 | MODEL_REASONING_QUICK_V1 => "chat",
+ MODEL_AGENTIC_V1 => "agentic",
+ MODEL_BURST_V1 => "burst",
+ MODEL_CODING_V1 => "coding",
+ MODEL_VISION_V1 => "vision",
+ MODEL_SUMMARIZATION_V1 => "summarization",
+ _ => "chat",
+ }
+}
+
+/// Return whether `model` is a recognized OpenHuman backend tier name.
+///
+/// Used to guard against stale `default_model` values (e.g. set by older UI
+/// versions) that the backend would reject with HTTP 400. The known tiers are
+/// the constants in `crate::config`; the four `hint:*` strings that
+/// `make_openhuman_backend` actually translates are also accepted. An
+/// unrecognized `hint:*` value is intentionally rejected so the factory falls
+/// back to the platform default instead of forwarding an untranslated string
+/// to the backend.
+pub(crate) fn is_known_openhuman_tier(model: &str) -> bool {
+ use crate::config::{
+ MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1, MODEL_CODING_V1, MODEL_REASONING_QUICK_V1,
+ MODEL_REASONING_V1, MODEL_SUMMARIZATION_V1, MODEL_VISION_V1,
+ };
+ matches!(
+ model,
+ MODEL_REASONING_V1
+ | MODEL_CHAT_V1
+ | MODEL_AGENTIC_V1
+ | MODEL_BURST_V1
+ | MODEL_CODING_V1
+ | MODEL_REASONING_QUICK_V1
+ | MODEL_SUMMARIZATION_V1
+ | MODEL_VISION_V1
+ | "hint:reasoning"
+ | "hint:chat"
+ | "hint:agentic"
+ | "hint:burst"
+ | "hint:coding"
+ | "hint:summarization"
+ | "hint:vision"
+ )
+}
+
+/// Return whether `model` is a raw BYOK/custom model id that must be forwarded
+/// **verbatim** to provider construction rather than mapped onto a managed tier.
+///
+/// A raw passthrough id is any **non-empty** string that is neither a `hint:*`
+/// alias nor a known managed tier ([`is_known_openhuman_tier`]) — i.e. the model
+/// ids a user pins directly on an agent/node (e.g. `"claude-opus-4"`). The
+/// OpenHuman backend preserves such ids verbatim
+/// (the managed model's blank-id normalization) and is authoritative over
+/// their validity, so the core must **not** silently collapse them onto
+/// `reasoning-v1` (issue #4598). Managed tiers and every `hint:*` string return
+/// `false` so their existing resolution is untouched.
+pub(crate) fn is_raw_passthrough_model(model: &str) -> bool {
+ let trimmed = model.trim();
+ !trimmed.is_empty() && !trimmed.starts_with("hint:") && !is_known_openhuman_tier(trimmed)
+}
+
+/// Per-tier vision (image-input) capability for the managed OpenHuman backend.
+///
+/// The remote managed backend (`api.tinyhumans.ai`) does not advertise per-tier
+/// capabilities, so the core maintains this map itself. Accepts both the tier
+/// constants and their `hint:*` forms (callers may pass either pre- or
+/// post-resolution).
+///
+/// `reasoning-v1` and the dedicated `vision-v1` tier are multimodal; every
+/// other tier returns `false` — flip an individual arm to `true` once that tier
+/// is confirmed multimodal on the backend. This is the **only** place to change
+/// managed-model vision; BYOK/custom models are handled separately by the
+/// user-set `model_registry.vision` flag
+/// ([`crate::inference::model_context::model_vision_enabled`]).
+pub(crate) fn oh_tier_supports_vision(model: &str) -> bool {
+ use crate::config::{
+ MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1, MODEL_CODING_V1, MODEL_REASONING_QUICK_V1,
+ MODEL_REASONING_V1, MODEL_SUMMARIZATION_V1, MODEL_VISION_V1,
+ };
+ match model {
+ MODEL_REASONING_V1 | "hint:reasoning" => true,
+ // Dedicated multimodal tier — the managed backend serves this with the
+ // vision flag enabled. This is what the vision sub-agent rides on.
+ MODEL_VISION_V1 | "hint:vision" => true,
+ MODEL_CHAT_V1 | "hint:chat" => false,
+ MODEL_REASONING_QUICK_V1 => false,
+ MODEL_AGENTIC_V1 | "hint:agentic" => false,
+ // Burst is a text-only tier.
+ MODEL_BURST_V1 | "hint:burst" => false,
+ MODEL_CODING_V1 | "hint:coding" => false,
+ MODEL_SUMMARIZATION_V1 | "hint:summarization" => false,
+ _ => false,
+ }
+}
diff --git a/crates/openhuman-core/src/inference/provider/factory/turn_model.rs b/crates/openhuman-core/src/inference/provider/factory/turn_model.rs
new file mode 100644
index 0000000000..1de0aed996
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/factory/turn_model.rs
@@ -0,0 +1,263 @@
+use super::*;
+
+/// Build a crate-native [`ChatModel`] for the **turn path**, pinned to an explicit
+/// `model` string — the turn's effective/dispatched model after any config-level
+/// agent pin (issue #4249, Phase 3 P3-B). The per-`(role, model)` analogue of
+/// [`create_chat_model_with_model_id`] used by the crate-native
+/// [`TurnModelSource`](crate::agent::tinyagents::TurnModelSource) to construct
+/// the primary + each workload-tier route directly.
+///
+/// - **Managed** → [`OpenHumanBackendModel`](super::openhuman_backend_model::OpenHumanBackendModel)
+/// pinned to `model`; the backend resolves the tier from `request.model`, so a
+/// tier alias / agent-model pin dispatches directly.
+/// - **Local / cloud** → the crate builders; the model rides the role's resolved
+/// provider string. A config-level *primary-model pin* on a local/cloud provider
+/// is not re-pinned here (pins are tier selection on the managed backend); the
+/// role's resolved model has the same behaviour.
+/// - **Claude Agent SDK** → its direct prompt-guided [`ChatModel`] subprocess
+/// adapter, pinned to `model`.
+/// - **Claude Code** → its direct native-tool streaming [`ChatModel`] subprocess
+/// adapter, pinned to `model`.
+///
+/// Respects the native test-model override, exactly as
+/// [`create_chat_model_with_model_id`].
+pub(crate) fn create_turn_chat_model(
+ role: &str,
+ config: &Config,
+ model: &str,
+ temperature: f64,
+) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
+ create_turn_chat_model_with_native_tools(role, config, model, temperature, true)
+}
+
+pub(crate) fn create_turn_chat_model_with_native_tools(
+ role: &str,
+ config: &Config,
+ model: &str,
+ temperature: f64,
+ native_tool_calling: bool,
+) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
+ create_turn_chat_model_with_native_tools_and_route(
+ role,
+ config,
+ model,
+ temperature,
+ native_tool_calling,
+ )
+ .map(|(chat, _, _)| chat)
+}
+
+/// Build a turn model together with the concrete provider and post-remap model
+/// id that the constructed client will put on the wire. The route metadata is
+/// consumed by channel audit recording; returning it from the construction
+/// branches avoids re-parsing a provider string before cloud default-model and
+/// abstract-tier remapping has run.
+pub(crate) fn create_turn_chat_model_with_native_tools_and_route(
+ role: &str,
+ config: &Config,
+ model: &str,
+ temperature: f64,
+ native_tool_calling: bool,
+) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String, String)> {
+ create_turn_chat_model_with_native_tools_and_route_inner(
+ role,
+ config,
+ model,
+ native_tool_calling,
+ )
+ .map(|(chat, provider, model)| (with_default_temperature(chat, temperature), provider, model))
+}
+
+pub(super) fn create_turn_chat_model_with_native_tools_and_route_inner(
+ role: &str,
+ config: &Config,
+ model: &str,
+ native_tool_calling: bool,
+) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String, String)> {
+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
+ if let Some(chat) = test_provider_override::current() {
+ let provider = chat
+ .profile()
+ .and_then(|profile| profile.provider.clone())
+ .unwrap_or_else(|| "injected".to_string());
+ return Ok((chat, provider, model.to_string()));
+ }
+ let test_override_active = {
+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
+ {
+ test_provider_override::current().is_some()
+ }
+ #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]
+ {
+ false
+ }
+ };
+ if !test_override_active {
+ if resolves_to_managed_backend(role, config) {
+ let (backend, _resolved_model) = resolve_managed_backend(role, config)?;
+ return Ok((
+ Arc::new(
+ backend
+ .with_default_model(model)
+ .with_native_tool_calling(native_tool_calling),
+ ),
+ PROVIDER_OPENHUMAN.to_string(),
+ model.to_string(),
+ ));
+ }
+ let resolved_provider = provider_for_role(role, config);
+ let provider_name = resolved_provider
+ .trim()
+ .split(':')
+ .next()
+ .unwrap_or(resolved_provider.trim())
+ .to_string();
+ if let Some(result) = prepare_claude_agent_sdk_chat_model(role, &resolved_provider, config)
+ {
+ let _resolved_model = result?;
+ emit_inference_egress(role, &format!("{CLAUDE_AGENT_SDK_PREFIX}{model}"));
+ return Ok((
+ Arc::new(ClaudeAgentSdkProvider::for_model(
+ config.claude_agent_sdk.clone(),
+ model,
+ )),
+ provider_name,
+ model.to_string(),
+ ));
+ }
+ if let Some(result) = try_create_claude_code_chat_model_from_string(
+ role,
+ &resolved_provider,
+ config,
+ Some(model),
+ ) {
+ return result
+ .map(|(chat, _configured_model)| (chat, provider_name.clone(), model.to_string()));
+ }
+ if let Some(result) = try_create_local_runtime_chat_model(role, config) {
+ return result
+ .map(|(chat, resolved_model)| (chat, provider_name.clone(), resolved_model));
+ }
+ if let Some(result) =
+ try_create_cloud_slug_chat_model_with_native_tools(role, config, native_tool_calling)
+ {
+ return result
+ .map(|(chat, resolved_model)| (chat, provider_name.clone(), resolved_model));
+ }
+ }
+ Err(unresolved_chat_model_error(
+ role,
+ &provider_for_role(role, config),
+ config,
+ ))
+}
+
+/// Like [`create_turn_chat_model`] but for an **explicit** `provider_string` — the
+/// explicit-string counterpart of [`create_turn_chat_model`], for producers
+/// whose effective provider differs from the role's default resolution.
+///
+/// The triage path needs this: [`build_remote_provider`](crate::agent::triage::routing)
+/// forces the managed backend (`provider_string == `[`PROVIDER_OPENHUMAN`]) when the
+/// subconscious route is local / BYOK-incomplete — the #1257 *"triage never goes
+/// local"* invariant — which a plain [`create_turn_chat_model`] (role → `provider_for_role`)
+/// would violate by building the local model.
+///
+/// - `provider_string` empty / `"cloud"` / [`PROVIDER_OPENHUMAN`] → managed
+/// [`OpenHumanBackendModel`] pinned to `model` (the force-managed case).
+/// - Otherwise the string equals what the role resolves to (a BYOK cloud slug), so
+/// this delegates to [`create_turn_chat_model`] for `role`.
+///
+/// Respects the test-provider override (bespoke/`Provider` path), like its siblings.
+pub(crate) fn create_turn_chat_model_from_string(
+ role: &str,
+ provider_string: &str,
+ config: &Config,
+ model: &str,
+ temperature: f64,
+) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
+ create_turn_chat_model_from_string_with_native_tools(
+ role,
+ provider_string,
+ config,
+ model,
+ temperature,
+ true,
+ )
+}
+
+pub(crate) fn create_turn_chat_model_from_string_with_native_tools(
+ role: &str,
+ provider_string: &str,
+ config: &Config,
+ model: &str,
+ temperature: f64,
+ native_tool_calling: bool,
+) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
+ create_turn_chat_model_from_string_with_native_tools_and_route(
+ role,
+ provider_string,
+ config,
+ model,
+ temperature,
+ native_tool_calling,
+ )
+ .map(|(chat, _, _)| chat)
+}
+
+pub(crate) fn create_turn_chat_model_from_string_with_native_tools_and_route(
+ role: &str,
+ provider_string: &str,
+ config: &Config,
+ model: &str,
+ temperature: f64,
+ native_tool_calling: bool,
+) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String, String)> {
+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
+ if let Some(chat) = test_provider_override::current() {
+ let provider = chat
+ .profile()
+ .and_then(|profile| profile.provider.clone())
+ .unwrap_or_else(|| "injected".to_string());
+ return Ok((
+ with_default_temperature(chat, temperature),
+ provider,
+ model.to_string(),
+ ));
+ }
+ let test_override_active = {
+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
+ {
+ test_provider_override::current().is_some()
+ }
+ #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]
+ {
+ false
+ }
+ };
+ let p = provider_string.trim();
+ let is_managed = p.is_empty() || p == "cloud" || p == PROVIDER_OPENHUMAN;
+ if is_managed && !test_override_active {
+ let (backend, _resolved_model) = resolve_managed_backend(role, config)?;
+ return Ok((
+ with_default_temperature(
+ Arc::new(
+ backend
+ .with_default_model(model)
+ .with_native_tool_calling(native_tool_calling),
+ ),
+ temperature,
+ ),
+ PROVIDER_OPENHUMAN.to_string(),
+ model.to_string(),
+ ));
+ }
+ // A concrete non-managed string equals the role's resolution (triage only
+ // honours a BYOK **cloud** route as-is), so the role-based builder matches.
+ create_turn_chat_model_with_native_tools_and_route(
+ role,
+ config,
+ model,
+ temperature,
+ native_tool_calling,
+ )
+}
diff --git a/crates/openhuman-core/src/inference/provider/factory_tests_part_02_tests.rs b/crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/inference/provider/factory_tests_part_02_tests.rs
rename to crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs
diff --git a/crates/openhuman-core/src/inference/provider/factory_tests_part_03_tests.rs b/crates/openhuman-core/src/inference/provider/factory_egress_fallback_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/inference/provider/factory_tests_part_03_tests.rs
rename to crates/openhuman-core/src/inference/provider/factory_egress_fallback_tests.rs
diff --git a/crates/openhuman-core/src/inference/provider/factory_part_01.rs b/crates/openhuman-core/src/inference/provider/factory_part_01.rs
deleted file mode 100644
index 3467475362..0000000000
--- a/crates/openhuman-core/src/inference/provider/factory_part_01.rs
+++ /dev/null
@@ -1,609 +0,0 @@
-use crate::config::schema::cloud_providers::AuthStyle;
-use crate::config::Config;
-use crate::inference::provider::auth::AuthStyle as CompatAuthStyle;
-use crate::inference::provider::claude_agent_sdk::subprocess::ClaudeAgentSdkProvider;
-use crate::inference::provider::openai_codex::{
- openai_codex_client_version, openai_codex_user_agent, resolve_openai_codex_routing,
- OPENAI_CODEX_ACCOUNT_HEADER, OPENAI_CODEX_ORIGINATOR, OPENAI_CODEX_ORIGINATOR_HEADER,
-};
-use crate::inference::provider::openhuman_backend_model::OpenHumanBackendModel;
-use crate::inference::provider::ProviderRuntimeOptions;
-use crate::security::credentials::AuthService;
-use std::sync::Arc;
-use tinyinference::model::{ChatModel, ModelRequest, ModelResponse, ModelStream};
-
-/// Sentinel meaning "use the OpenHuman backend session JWT".
-pub const PROVIDER_OPENHUMAN: &str = "openhuman";
-/// Prefix for Ollama-local providers: `"ollama:<model>"`.
-pub const OLLAMA_PROVIDER_PREFIX: &str = "ollama:";
-/// Prefix for LM Studio-local providers: `"lmstudio:<model>"`.
-pub const LM_STUDIO_PROVIDER_PREFIX: &str = "lmstudio:";
-/// Prefix for MLX-compatible local providers: `"mlx:<model>"`.
-pub const MLX_PROVIDER_PREFIX: &str = "mlx:";
-/// Prefix for OMLX local providers: `"omlx:<model>"`.
-pub const OMLX_PROVIDER_PREFIX: &str = "omlx:";
-/// Prefix for generic local OpenAI-compatible providers: `"local-openai:<model>"`.
-pub const LOCAL_OPENAI_PROVIDER_PREFIX: &str = "local-openai:";
-/// Prefix for the Claude Agent SDK subprocess provider: `"claude_agent_sdk:<model>"`.
-pub const CLAUDE_AGENT_SDK_PREFIX: &str = "claude_agent_sdk:";
-/// Sentinel for the Claude Agent SDK provider without a model suffix.
-pub const CLAUDE_AGENT_SDK_PROVIDER: &str = "claude_agent_sdk";
-/// Sentinel returned when a user has expressed custom/BYOK inference intent
-/// (via a non-openhuman `inference_url`) but no matching `cloud_providers`
-/// entry was found. Passed through `provider_for_role` and caught early in
-/// `create_chat_model_from_string` to produce a clear configuration error
-/// instead of silently routing through the managed OpenHuman backend.
-pub const BYOK_INCOMPLETE_SENTINEL: &str = "__byok_incomplete__";
-
-/// Interpolation-free substring of the empty-model bail emitted by
-/// cloud-slug resolution when a `<slug>` provider string carries
-/// no model and the `cloud_providers` entry has no `default_model` (the
-/// #2784 guard). The Sentry-demotion + user-copy classifier
-/// [`super::is_provider_config_rejection_message`] keys on this exact literal,
-/// and a round-trip test in `factory_tests.rs` asserts the bail body still
-/// contains it — so a wording drift fails CI instead of silently re-flooding
-/// Sentry (TAURI-RUST-GKV).
-pub(crate) const NO_MODEL_CONFIGURED_ANCHOR: &str = "resolved to an empty model id";
-
-fn is_abstract_tier_model(model: &str) -> bool {
- use crate::config::{
- MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1, MODEL_CODING_V1, MODEL_REASONING_QUICK_V1,
- MODEL_REASONING_V1, MODEL_SUMMARIZATION_V1, MODEL_VISION_V1,
- };
- let trimmed = model.trim();
- trimmed == MODEL_REASONING_V1
- || trimmed == MODEL_REASONING_QUICK_V1
- || trimmed == MODEL_CHAT_V1
- || trimmed == MODEL_AGENTIC_V1
- || trimmed == MODEL_BURST_V1
- || trimmed == MODEL_CODING_V1
- || trimmed == MODEL_VISION_V1
- || trimmed == MODEL_SUMMARIZATION_V1
-}
-
-/// Auth-profile storage key for a slug-keyed provider.
-///
-/// New writes use `"provider:<slug>"`. Lookups also try the bare `<slug>`
-/// as a legacy fallback (old configs stored keys as e.g. `"openai:default"`).
-pub fn auth_key_for_slug(slug: &str) -> String {
- format!("provider:{slug}")
-}
-
-/// Resolve a model hint (e.g. `"hint:reasoning"`) or tier name to the
-/// concrete model string that the provider router would use — without
-/// constructing the actual provider. Returns the provider-string prefix
-/// (e.g. `"openai"`) concatenated with the model when a BYOK provider is
-/// active, or the bare tier name for the managed OpenHuman backend.
-pub fn resolve_model_for_hint(hint_or_tier: &str, config: &Config) -> String {
- let hint_to_tier: &[(&str, &str)] = &[
- ("reasoning", crate::config::MODEL_REASONING_V1),
- ("chat", crate::config::MODEL_CHAT_V1),
- ("agentic", crate::config::MODEL_AGENTIC_V1),
- ("burst", crate::config::MODEL_BURST_V1),
- ("coding", crate::config::MODEL_CODING_V1),
- ("vision", crate::config::MODEL_VISION_V1),
- (
- "summarization",
- crate::config::MODEL_SUMMARIZATION_V1,
- ),
- // Background subconscious workload rides the lightweight chat tier on the
- // managed backend; its `subconscious` *role* (handled below) still selects
- // the provider via `subconscious_provider`.
- ("subconscious", crate::config::MODEL_CHAT_V1),
- ];
- let tier_to_role: &[(&str, &str)] = &[
- (crate::config::MODEL_REASONING_V1, "reasoning"),
- (crate::config::MODEL_CHAT_V1, "chat"),
- (crate::config::MODEL_REASONING_QUICK_V1, "chat"),
- (crate::config::MODEL_AGENTIC_V1, "agentic"),
- (crate::config::MODEL_BURST_V1, "burst"),
- (crate::config::MODEL_CODING_V1, "coding"),
- (crate::config::MODEL_VISION_V1, "vision"),
- (
- crate::config::MODEL_SUMMARIZATION_V1,
- "summarization",
- ),
- ];
-
- let (tier, role) = if let Some(hint_key) = hint_or_tier.strip_prefix("hint:") {
- let tier = hint_to_tier
- .iter()
- .find(|(k, _)| *k == hint_key)
- .map(|(_, v)| *v)
- .unwrap_or(hint_or_tier);
- // Background workloads map to a tier *model* but must keep their own
- // role so `provider_for_role` reads their dedicated `*_provider` field
- // rather than the chat-tier provider their model happens to share.
- let role = match hint_key {
- "subconscious" => "subconscious",
- _ => tier_to_role
- .iter()
- .find(|(k, _)| *k == tier)
- .map(|(_, v)| *v)
- .unwrap_or(hint_key),
- };
- (tier, role)
- } else {
- let role = tier_to_role
- .iter()
- .find(|(k, _)| *k == hint_or_tier)
- .map(|(_, v)| *v)
- .unwrap_or("chat");
- (hint_or_tier, role)
- };
-
- let provider_string = provider_for_role(role, config);
- let ps = provider_string.trim();
- if ps.is_empty() || ps == "cloud" || ps == PROVIDER_OPENHUMAN || ps == BYOK_INCOMPLETE_SENTINEL
- {
- tier.to_string()
- } else if let Some(idx) = ps.find(':') {
- let model_with_temp = &ps[idx + 1..];
- let (model, _) = split_model_and_temperature(model_with_temp);
- model
- } else {
- ps.to_string()
- }
-}
-
-/// Map a managed tier name (or `hint:*` string) to the workload **role** whose
-/// configured provider serves it.
-///
-/// This is the inverse of the role→tier routing `create_chat_model` does:
-/// callers that select a model *per unit of work by tier* (e.g. a tinyflows
-/// `agent` node pinning `config.model = "reasoning-v1"`) use this to turn that
-/// tier back into the role, then call [`create_chat_model`] with it — so the
-/// completion routes to that tier on the managed backend (or the role's BYOK
-/// model) instead of some caller default. Unknown strings fall back to `"chat"`.
-///
-/// Kept deliberately small and standalone (no `Config`) — it is a pure lookup
-/// over the tier constants, mirroring the `tier_to_role` table inside
-/// [`resolve_model_for_hint`].
-pub fn role_for_model_tier(hint_or_tier: &str) -> &'static str {
- use crate::config::{
- MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1, MODEL_CODING_V1, MODEL_REASONING_QUICK_V1,
- MODEL_REASONING_V1, MODEL_SUMMARIZATION_V1, MODEL_VISION_V1,
- };
-
- // Normalise a `hint:*` alias to its concrete tier first.
- let tier = match hint_or_tier.strip_prefix("hint:") {
- Some("reasoning") => MODEL_REASONING_V1,
- Some("chat") => MODEL_CHAT_V1,
- Some("agentic") => MODEL_AGENTIC_V1,
- Some("burst") => MODEL_BURST_V1,
- Some("coding") => MODEL_CODING_V1,
- Some("vision") => MODEL_VISION_V1,
- Some("summarization") => MODEL_SUMMARIZATION_V1,
- // Background subconscious rides the chat tier for its model.
- Some("subconscious") => MODEL_CHAT_V1,
- Some(_) => hint_or_tier,
- None => hint_or_tier,
- };
-
- match tier {
- MODEL_REASONING_V1 => "reasoning",
- MODEL_CHAT_V1 | MODEL_REASONING_QUICK_V1 => "chat",
- MODEL_AGENTIC_V1 => "agentic",
- MODEL_BURST_V1 => "burst",
- MODEL_CODING_V1 => "coding",
- MODEL_VISION_V1 => "vision",
- MODEL_SUMMARIZATION_V1 => "summarization",
- _ => "chat",
- }
-}
-
-/// Return whether `model` is a recognized OpenHuman backend tier name.
-///
-/// Used to guard against stale `default_model` values (e.g. set by older UI
-/// versions) that the backend would reject with HTTP 400. The known tiers are
-/// the constants in `crate::config`; the four `hint:*` strings that
-/// `make_openhuman_backend` actually translates are also accepted. An
-/// unrecognized `hint:*` value is intentionally rejected so the factory falls
-/// back to the platform default instead of forwarding an untranslated string
-/// to the backend.
-pub(crate) fn is_known_openhuman_tier(model: &str) -> bool {
- use crate::config::{
- MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1, MODEL_CODING_V1, MODEL_REASONING_QUICK_V1,
- MODEL_REASONING_V1, MODEL_SUMMARIZATION_V1, MODEL_VISION_V1,
- };
- matches!(
- model,
- MODEL_REASONING_V1
- | MODEL_CHAT_V1
- | MODEL_AGENTIC_V1
- | MODEL_BURST_V1
- | MODEL_CODING_V1
- | MODEL_REASONING_QUICK_V1
- | MODEL_SUMMARIZATION_V1
- | MODEL_VISION_V1
- | "hint:reasoning"
- | "hint:chat"
- | "hint:agentic"
- | "hint:burst"
- | "hint:coding"
- | "hint:summarization"
- | "hint:vision"
- )
-}
-
-/// Return whether `model` is a raw BYOK/custom model id that must be forwarded
-/// **verbatim** to provider construction rather than mapped onto a managed tier.
-///
-/// A raw passthrough id is any **non-empty** string that is neither a `hint:*`
-/// alias nor a known managed tier ([`is_known_openhuman_tier`]) — i.e. the model
-/// ids a user pins directly on an agent/node (e.g. `"claude-opus-4"`). The
-/// OpenHuman backend preserves such ids verbatim
-/// (the managed model's blank-id normalization) and is authoritative over
-/// their validity, so the core must **not** silently collapse them onto
-/// `reasoning-v1` (issue #4598). Managed tiers and every `hint:*` string return
-/// `false` so their existing resolution is untouched.
-pub(crate) fn is_raw_passthrough_model(model: &str) -> bool {
- let trimmed = model.trim();
- !trimmed.is_empty() && !trimmed.starts_with("hint:") && !is_known_openhuman_tier(trimmed)
-}
-
-/// Per-tier vision (image-input) capability for the managed OpenHuman backend.
-///
-/// The remote managed backend (`api.tinyhumans.ai`) does not advertise per-tier
-/// capabilities, so the core maintains this map itself. Accepts both the tier
-/// constants and their `hint:*` forms (callers may pass either pre- or
-/// post-resolution).
-///
-/// `reasoning-v1` and the dedicated `vision-v1` tier are multimodal; every
-/// other tier returns `false` — flip an individual arm to `true` once that tier
-/// is confirmed multimodal on the backend. This is the **only** place to change
-/// managed-model vision; BYOK/custom models are handled separately by the
-/// user-set `model_registry.vision` flag
-/// ([`crate::inference::model_context::model_vision_enabled`]).
-pub(crate) fn oh_tier_supports_vision(model: &str) -> bool {
- use crate::config::{
- MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1, MODEL_CODING_V1, MODEL_REASONING_QUICK_V1,
- MODEL_REASONING_V1, MODEL_SUMMARIZATION_V1, MODEL_VISION_V1,
- };
- match model {
- MODEL_REASONING_V1 | "hint:reasoning" => true,
- // Dedicated multimodal tier — the managed backend serves this with the
- // vision flag enabled. This is what the vision sub-agent rides on.
- MODEL_VISION_V1 | "hint:vision" => true,
- MODEL_CHAT_V1 | "hint:chat" => false,
- MODEL_REASONING_QUICK_V1 => false,
- MODEL_AGENTIC_V1 | "hint:agentic" => false,
- // Burst is a text-only tier.
- MODEL_BURST_V1 | "hint:burst" => false,
- MODEL_CODING_V1 | "hint:coding" => false,
- MODEL_SUMMARIZATION_V1 | "hint:summarization" => false,
- _ => false,
- }
-}
-
-/// The provider route a role has **explicitly** configured, before any
-/// fallback.
-///
-/// Split out of [`provider_for_role`] so the fallback machinery can ask the
-/// same question the router asks — "did the user route this role anywhere?" —
-/// without re-deriving the role→config-field mapping and drifting from it.
-fn configured_route_for_role<'a>(role: &str, config: &'a Config) -> Option<&'a str> {
- match role {
- "chat" => config.chat_provider.as_deref(),
- "reasoning" => config.reasoning_provider.as_deref(),
- "agentic" => config.agentic_provider.as_deref(),
- "coding" => config.coding_provider.as_deref(),
- // Burst uses the existing Agentic workload route for BYOK/local parity.
- // If unset, it falls through to the managed backend and is pinned to
- // `burst-v1` by `managed_tier_for_role`.
- "burst" => config.agentic_provider.as_deref(),
- // Tier-specific multimodal model; when unset it falls through to
- // `primary_cloud` (→ managed `vision-v1`), as every unset route now does.
- "vision" => config.vision_provider.as_deref(),
- // `memory_provider` covers both the memory-tree extract path and
- // the summarizer sub-agent (whose definition declares
- // `hint = "summarization"`). Both are "produce a condensed
- // representation of input text" — same model class, no reason
- // for a separate config knob.
- "memory" | "summarization" => config.memory_provider.as_deref(),
- "embeddings" => config.embeddings_provider.as_deref(),
- "heartbeat" => config.heartbeat_provider.as_deref(),
- "learning" => config.learning_provider.as_deref(),
- "subconscious" => config.subconscious_provider.as_deref(),
- _ => None,
- }
-}
-
-/// Whether `role` reached a cloud slug by *implicit fallback* rather than by an
-/// explicit route.
-///
-/// True only when the role is one of the cloud-fallback background roles **and**
-/// its own route is unset (or the literal `"cloud"`). An explicitly configured
-/// cloud route — say `vision_provider = "anthropic:claude-…"` — is not a
-/// fallback, so a credential failure there must not be explained as "your local
-/// chat model cannot do this".
-pub(crate) fn role_uses_implicit_cloud_fallback(role: &str, config: &Config) -> bool {
- if !super::fallback_diagnostics::role_falls_back_to_cloud(role) {
- return false;
- }
- let route = configured_route_for_role(role, config).unwrap_or("").trim();
- route.is_empty() || route == "cloud"
-}
-
-/// Return the configured provider string for a named workload role.
-///
-/// Empty / `"cloud"` resolves through `primary_cloud`. **Every** role behaves
-/// this way, and no role uses a sibling's BYOK provider as a fallback.
-///
-/// "Resolves through `primary_cloud`" is not the same as "goes to the managed
-/// backend": [`resolve_primary_cloud_provider_string`] may yield a legacy
-/// external `inference_url` (see below), or the fail-closed sentinel for a
-/// half-migrated BYOK config. The guarantee here is narrower and exact — an
-/// unset route does not borrow a *sibling's* configured provider.
-///
-/// The deliberate *aliases* in [`configured_route_for_role`] are unaffected and
-/// remain: `burst` reads `agentic_provider` and `summarization` reads
-/// `memory_provider`. Those are two names for one configured route, which is a
-/// different thing from an unset route borrowing a set one.
-///
-/// Until #6109 the three chat-tier roles (`chat`, `reasoning`, `coding`) took a
-/// configured BYOK provider from *any* sibling first, so setting one route moved
-/// the other two onto that key — a user who pointed only `coding_provider` at
-/// their own OpenRouter account found ordinary chat billed there too, with no
-/// setting saying so. Each route now stands alone.
-///
-/// For backwards compatibility, a legacy external `inference_url` takes
-/// precedence when `primary_cloud` still points at OpenHuman because
-/// migration 1→2 preserved the URL as a custom provider entry but older
-/// configs did not explicitly set per-workload routes.
-pub fn provider_for_role(role: &str, config: &Config) -> String {
- let opt = configured_route_for_role(role, config);
- let s = opt.unwrap_or("").trim();
- if s.is_empty() || s == "cloud" {
- // #6109: an unset chat-tier route no longer inherits a sibling's BYOK
- // provider. Setting only `coding_provider` used to move `chat` and
- // `reasoning` onto that key too — ordinary conversations silently billed
- // to the user's own account, with no settings field saying so. Each
- // route now stands alone and an unset one falls through to the managed
- // backend, the same as every other workload.
-
- let resolved = resolve_primary_cloud_provider_string(config);
-
- // #5146 §2.1: the fallback itself is correct and stays — background
- // workloads run tier-specific models that local runtimes don't serve,
- // and a local-chat + managed-subscription user genuinely wants them on
- // the cloud. What was missing is the *explanation*: when this route
- // later fails for want of a key, the user saw a bare slug-level auth
- // error naming a provider they never configured. Emit the same
- // user-facing sentence the error path uses, so the routing decision is
- // visible in logs and support transcripts before anything goes wrong.
- if super::fallback_diagnostics::role_falls_back_to_cloud(role) {
- if let Some(chat) = config.chat_provider.as_deref() {
- if crate::inference::local::profile::is_local_provider_string(chat) {
- log::info!(
- "[providers][local-fallback] role={} {}",
- role,
- super::fallback_diagnostics::cloud_fallback_notice(role, chat, &resolved)
- );
- }
- }
- }
-
- resolved
- } else {
- s.to_string()
- }
-}
-
-/// #3767: Whether the OpenHuman managed-credits gate should be bypassed for a
-/// single workload role.
-///
-/// Returns true when `role` resolves (via [`provider_for_role`]) to a non-managed
-/// provider the user funds themselves — a BYO cloud key (incl. OpenAI OAuth), a
-/// local runtime, or claude-code — with usable credentials. When the role is on
-/// the OpenHuman managed backend, or a BYO route has no usable key, it returns
-/// false (the gate stays on; #3767: "BYO key present but invalid/unverified →
-/// still gated").
-///
-/// The gate is evaluated per-tier so the UI can check the tier the user actually
-/// selected: the chat header's "Quick" mode runs on the `chat` tier and
-/// "Reasoning" mode on the `reasoning` tier, so each is checked respectively.
-/// These per-role results are surfaced under `credits_bypass` in the
-/// client-config snapshot. Tiers that stay managed and run anyway surface the
-/// per-call `USER_INSUFFICIENT_CREDITS` (402) error reactively.
-pub fn role_bypasses_managed_credits(role: &str, config: &Config) -> bool {
- let resolved = provider_for_role(role, config);
- let r = resolved.trim();
- let is_managed =
- r.is_empty() || r == "cloud" || r == PROVIDER_OPENHUMAN || r == BYOK_INCOMPLETE_SENTINEL;
- let usable_byo = !is_managed && route_has_usable_credentials(r, config);
- log::debug!(
- "[billing] role_bypasses_managed_credits role={role} resolved={resolved} \
- is_managed={is_managed} usable_byo={usable_byo}"
- );
- usable_byo
-}
-
-/// True when a resolved chat-tier provider string can actually run on the
-/// user's own funding: local runtimes / claude-code carry their own creds; a
-/// concrete cloud slug requires a non-empty stored key. Managed/sentinel
-/// strings are filtered by the caller and never reach here as "usable".
-fn route_has_usable_credentials(resolved: &str, config: &Config) -> bool {
- let r = resolved.trim();
- // Local runtimes (ollama/lmstudio/mlx/local-openai) and the local CLI
- // delegates carry their own credentials / run on-device.
- if crate::inference::local::profile::is_local_provider_string(r)
- || r.starts_with(crate::inference::provider::claude_code::PROVIDER_PREFIX)
- || r == CLAUDE_AGENT_SDK_PROVIDER
- || r.starts_with(CLAUDE_AGENT_SDK_PREFIX)
- {
- return true;
- }
- // Concrete cloud slug "<slug>:<model>" — require a usable stored key.
- if let Some((slug, _)) = r.split_once(':') {
- let slug = slug.trim();
- if !slug.is_empty() {
- // Don't silently swallow auth-store / OAuth lookup failures — a
- // transient Err would otherwise keep the credits gate on for a
- // valid BYO setup with no diagnostics. Log and treat as not-usable.
- match lookup_key_for_slug(slug, config) {
- Ok(key) => {
- let usable = !key.trim().is_empty();
- log::debug!(
- "[billing] route_has_usable_credentials slug={slug} usable={usable}"
- );
- return usable;
- }
- Err(e) => {
- log::debug!(
- "[billing] route_has_usable_credentials slug={slug} lookup_error={e}"
- );
- return false;
- }
- }
- }
- }
- false
-}
-
-
-/// Human-readable label for an *external* provider string, used in the
-/// LocalOnly privacy-mode block message so the user knows what was refused.
-fn external_provider_label(provider: &str) -> String {
- let p = provider.trim();
- if p == PROVIDER_OPENHUMAN {
- return "OpenHuman (managed cloud)".to_string();
- }
- if p == BYOK_INCOMPLETE_SENTINEL {
- return "cloud (incomplete BYOK config)".to_string();
- }
- if p == CLAUDE_AGENT_SDK_PROVIDER || p.starts_with(CLAUDE_AGENT_SDK_PREFIX) {
- return "Claude Agent SDK".to_string();
- }
- if p.starts_with(crate::inference::provider::claude_code::PROVIDER_PREFIX) {
- return "Claude Code CLI".to_string();
- }
- // Concrete cloud slug "<slug>:<model>" → surface just the slug.
- match p.split_once(':') {
- Some((slug, _)) if !slug.trim().is_empty() => slug.trim().to_string(),
- _ => p.to_string(),
- }
-}
-
-/// Privacy Mode (#4435) pure decision: under `mode`, is constructing chat
-/// provider `provider` a local-only violation? Returns `Some(label)` naming the
-/// blocked external provider when refused, else `None`.
-///
-/// Only `LocalOnly` restricts anything. Local runtimes (Ollama / LM Studio / MLX
-/// / local-openai) are always permitted. Re-resolving sentinels (`""` / `"cloud"`)
-/// return `None` here — they are resolved before model construction and
-/// re-checked with the concrete
-/// resolved string. Extracted as a pure fn so it is unit-testable without the
-/// process-global live policy.
-fn local_only_violation(
- mode: crate::config::PrivacyMode,
- provider: &str,
-) -> Option<String> {
- use crate::config::PrivacyMode;
- if mode != PrivacyMode::LocalOnly {
- return None;
- }
- let p = provider.trim();
- if p.is_empty() || p == "cloud" {
- // Deferred: re-resolves to a concrete string on the recursive call.
- return None;
- }
- if crate::inference::local::profile::is_local_provider_string(p) {
- return None;
- }
- Some(external_provider_label(p))
-}
-
-/// Enforce Privacy Mode `LocalOnly` at the inference chokepoint: refuse to build
-/// an external chat provider when the live policy is local-only. Reads the live
-/// privacy mode (defaults to `Standard`/allow when no session policy is
-/// installed). See [`local_only_violation`] for the pure decision.
-fn enforce_local_only_inference(role: &str, provider: &str) -> anyhow::Result<()> {
- let mode = crate::security::live_policy::current_privacy_mode();
- match local_only_violation(mode, provider) {
- None => {
- log::debug!(
- "[privacy][chat-factory] privacy_mode={:?} role={} provider='{}' — inference permitted",
- mode,
- role,
- provider.trim()
- );
- Ok(())
- }
- Some(label) => {
- log::warn!(
- "[privacy][chat-factory] LocalOnly BLOCK: role={} external provider='{}' ({}) refused",
- role,
- provider.trim(),
- label
- );
- anyhow::bail!(
- "Local-only privacy mode is active: this action needs external provider {label}. \
- Switch to a local model (Ollama/LM Studio/etc.) or change privacy mode in Settings."
- )
- }
- }
-}
-
-/// Egress spine (privacy epic S2, #4436): emit an [`EgressDescriptor`] for a
-/// concrete inference provider string. `provider` is expected to be already
-/// resolved (no `""` / `"cloud"` / BYOK sentinels — those are handled before
-/// this is called). Local runtimes are marked non-external, so
-/// [`emit_external_transfer`](crate::security::egress::emit_external_transfer)
-/// discloses them without firing the external-transfer event.
-fn emit_inference_egress(role: &str, provider: &str) {
- let p = provider.trim();
- if p.is_empty() || p == "cloud" {
- // Defensive: a sentinel would re-resolve on recursion; don't emit here.
- return;
- }
- if p == PROVIDER_OPENHUMAN {
- // Managed backend is emitted centrally in `resolve_managed_backend`,
- // the universal managed ChatModel funnel. Skipping here avoids a
- // duplicate descriptor.
- return;
- }
- let is_local = crate::inference::local::profile::is_local_provider_string(p);
- let (slug, model) = match p.split_once(':') {
- Some((s, m)) if !s.trim().is_empty() => (s.trim().to_string(), m.trim().to_string()),
- _ => (p.to_string(), String::new()),
- };
- // Fall back to the workload role when the provider string carries no model
- // component (e.g. a bare `"openhuman"` / `"ollama"` slug).
- let service = if model.is_empty() {
- role.to_string()
- } else {
- model
- };
- crate::security::egress::emit_external_transfer(
- crate::security::egress::EgressDescriptor::inference(slug, service, !is_local),
- );
-}
-
-/// Build an `Arc<dyn ChatModel>` for the given workload role.
-///
-/// The crate [`ChatModel`] is the model interface for the harness and one-shot
-/// inference callers. Production and tests both inject this native interface;
-/// `temperature` is applied as the request default while an explicit per-call
-/// value still wins.
-pub fn create_chat_model(
- role: &str,
- config: &Config,
- temperature: f64,
-) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
- Ok(create_chat_model_with_model_id(role, config, temperature)?.0)
-}
-
-/// Like [`create_chat_model`], but also returns the resolved model id.
-///
-/// One-shot callers that persist or log the concrete model (e.g. the memory
-/// summarise audit) need the id the role resolved to; the plain
-/// [`create_chat_model`] drops it.
-pub fn create_chat_model_with_model_id(
- role: &str,
- config: &Config,
- temperature: f64,
-) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {
- let (model, model_id) = create_chat_model_with_model_id_inner(role, config)?;
- Ok((with_default_temperature(model, temperature), model_id))
-}
diff --git a/crates/openhuman-core/src/inference/provider/factory_part_02.rs b/crates/openhuman-core/src/inference/provider/factory_part_02.rs
deleted file mode 100644
index 177d262e11..0000000000
--- a/crates/openhuman-core/src/inference/provider/factory_part_02.rs
+++ /dev/null
@@ -1,645 +0,0 @@
-
-fn create_chat_model_with_model_id_inner(
- role: &str,
- config: &Config,
-) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {
- #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
- if let Some(model) = test_provider_override::current() {
- return Ok((model, "mock-model".to_string()));
- }
- // Managed OpenHuman backend → crate-native host `ChatModel`
- // ([`OpenHumanBackendModel`], issue #4727 Motion B) instead of a
- // adapted provider. A native test-model override must still win, so only
- // take this path when no
- // override is installed. The public wrapper supplies the construction-time
- // default while preserving an explicit per-call `ModelRequest` temperature.
- let test_override_active = {
- #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
- {
- test_provider_override::current().is_some()
- }
- #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]
- {
- false
- }
- };
- if !test_override_active {
- if resolves_to_managed_backend(role, config) {
- return make_openhuman_backend_model(role, config);
- }
- if let Some(result) = try_create_claude_agent_sdk_chat_model(role, config) {
- return result;
- }
- if let Some(result) = try_create_claude_code_chat_model(role, config, None) {
- return result;
- }
- // Local OpenAI-compatible runtimes (Ollama / LM Studio / MLX / OMLX /
- // local-openai) → crate-native `ChatModel` (issue #4727 Motion B) instead
- // of a crate-adapted host provider. Cloud/BYOK/bespoke providers
- // return `None` here and fall through to the `Provider` path below.
- if let Some(result) = try_create_local_runtime_chat_model(role, config) {
- return result;
- }
- // Wire-equivalent BYOK cloud slugs (Anthropic / None / plain-Bearer, no
- // codex-oauth or `/v1/responses` fallback) → crate-native `ChatModel`
- // (issue #4727 Phase 3, conservative subset). `openai`/codex, custom
- // proxy slugs, and the managed entry return `None` and fall through.
- if let Some(result) = try_create_cloud_slug_chat_model(role, config) {
- return result;
- }
- }
- Err(unresolved_chat_model_error(
- role,
- &provider_for_role(role, config),
- config,
- ))
-}
-
-/// Whether `role` resolves to the managed OpenHuman backend (vs BYOK / local /
-/// claude-code). Uses the same empty/`cloud`/`openhuman` normalization as
-/// [`create_chat_model_from_string`] so every managed role shares one path.
-pub(crate) fn resolves_to_managed_backend(role: &str, config: &Config) -> bool {
- let mut resolved = provider_for_role(role, config);
- let trimmed = resolved.trim();
- if trimmed.is_empty() || trimmed == "cloud" {
- resolved = resolve_primary_cloud_provider_string(config);
- }
- resolved.trim() == PROVIDER_OPENHUMAN
-}
-
-/// Probe whether `role` can actually complete an inference call right now
-/// (issue B45 — the flows provider-connectivity author gate).
-///
-/// Two-stage check, mirroring the two ways a `role` can be un-runnable:
-///
-/// 1. **Construction** — [`create_chat_model_with_model_id_inner`] must
-/// succeed. This is the existing Layer 1 check (BYOK-incomplete config,
-/// unknown provider slug, local-only privacy-mode block, …) reused
-/// verbatim so this probe never re-implements it.
-/// 2. **Managed-backend readiness** — when `role` resolves to the managed
-/// OpenHuman backend, [`OpenHumanBackendModel::probe_readiness`] makes one
-/// cheap real completion attempt to catch the "account has no provider API
-/// key configured" class of failure that construction alone cannot see
-/// (construction only builds the client; it never calls the backend).
-/// BYOK/local models have no such hidden failure mode — their construction
-/// step already validates what it can, so they return `Ok(())` here
-/// unconditionally.
-///
-/// Respects the [`test_provider_override`] test seam: when a mock model is
-/// installed, construction returns it immediately and this function returns
-/// `Ok(())` without ever touching the network or resolving `role` again —
-/// `resolves_to_managed_backend` is a pure config read that would otherwise
-/// still call this "managed" in a test with a bare default `Config`.
-pub async fn probe_inference_readiness(role: &str, config: &Config) -> Result<(), String> {
- #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
- if test_provider_override::current().is_some() {
- log::debug!(
- "[flows][inference-probe] role={role} test model override active — skipping probe"
- );
- return Ok(());
- }
-
- log::debug!("[flows][inference-probe] role={role} verifying model construction");
- if let Err(e) = create_chat_model_with_model_id_inner(role, config) {
- log::debug!("[flows][inference-probe] role={role} construction failed: {e}");
- return Err(e.to_string());
- }
-
- if !resolves_to_managed_backend(role, config) {
- log::debug!(
- "[flows][inference-probe] role={role} resolves to a non-managed provider — \
- construction succeeded, nothing further to probe"
- );
- return Ok(());
- }
-
- log::debug!(
- "[flows][inference-probe] role={role} resolves to the managed OpenHuman backend — \
- probing readiness"
- );
- let (managed_model, model_id) =
- resolve_managed_backend(role, config).map_err(|e| e.to_string())?;
- let result = managed_model.probe_readiness().await;
- log::debug!(
- "[flows][inference-probe] role={role} model={model_id} probe result: {}",
- if result.is_ok() { "ready" } else { "not ready" }
- );
- result
-}
-
-/// Build an `Arc<dyn ChatModel>` from an explicit provider string and config.
-///
-/// The explicit-string counterpart of [`create_chat_model`].
-pub fn create_chat_model_from_string(
- role: &str,
- provider: &str,
- config: &Config,
- temperature: f64,
-) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
- create_chat_model_from_string_with_model_id(role, provider, config, temperature)
- .map(|(model, _)| model)
-}
-
-/// Build a crate [`ChatModel`] from an explicit provider string and return the
-/// concrete model id selected by that provider.
-///
-/// Managed, local-runtime, configured cloud-slug, Claude SDK/Code, and Codex
-/// strings all construct native `ChatModel` implementations directly.
-pub fn create_chat_model_from_string_with_model_id(
- role: &str,
- provider: &str,
- config: &Config,
- temperature: f64,
-) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {
- let (model, model_id) =
- create_chat_model_from_string_with_model_id_inner(role, provider, config)?;
- Ok((with_default_temperature(model, temperature), model_id))
-}
-
-fn create_chat_model_from_string_with_model_id_inner(
- role: &str,
- provider: &str,
- config: &Config,
-) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {
- #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
- if let Some(model) = test_provider_override::current() {
- return Ok((model, "mock-model".to_string()));
- }
- let test_override_active = {
- #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
- {
- test_provider_override::current().is_some()
- }
- #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]
- {
- false
- }
- };
- if !test_override_active {
- let mut resolved = provider.trim().to_string();
- if resolved.is_empty() || resolved == "cloud" {
- resolved = resolve_primary_cloud_provider_string(config);
- }
- if resolved == PROVIDER_OPENHUMAN {
- return make_openhuman_backend_model(role, config);
- }
- if let Some(result) =
- try_create_claude_agent_sdk_chat_model_from_string(role, &resolved, config)
- {
- return result;
- }
- if let Some(result) =
- try_create_claude_code_chat_model_from_string(role, &resolved, config, None)
- {
- return result;
- }
- if let Some(result) =
- try_create_local_runtime_chat_model_from_string(role, &resolved, config, true)
- {
- return result;
- }
- if let Some(result) = try_create_cloud_slug_chat_model_from_string(role, &resolved, config)
- {
- return result;
- }
- }
- Err(unresolved_chat_model_error(role, provider, config))
-}
-
-struct DefaultTemperatureChatModel {
- inner: Arc<dyn ChatModel<()>>,
- temperature: f64,
-}
-
-#[async_trait::async_trait]
-impl ChatModel<()> for DefaultTemperatureChatModel {
- fn profile(&self) -> Option<&tinyinference::model::ModelProfile> {
- self.inner.profile()
- }
-
- fn cache_identity(&self) -> Option<String> {
- self.inner.cache_identity()
- }
-
- async fn invoke(
- &self,
- state: &(),
- mut request: ModelRequest,
- ) -> tinyinference::Result<ModelResponse> {
- if request.temperature.is_none() {
- request.temperature = Some(self.temperature);
- }
- self.inner.invoke(state, request).await
- }
-
- async fn stream(
- &self,
- state: &(),
- mut request: ModelRequest,
- ) -> tinyinference::Result<ModelStream> {
- if request.temperature.is_none() {
- request.temperature = Some(self.temperature);
- }
- self.inner.stream(state, request).await
- }
-}
-
-fn with_default_temperature(
- model: Arc<dyn ChatModel<()>>,
- temperature: f64,
-) -> Arc<dyn ChatModel<()>> {
- Arc::new(DefaultTemperatureChatModel {
- inner: model,
- temperature,
- })
-}
-
-/// Reproduce the legacy provider factory's access gates and diagnostics for a
-/// provider string that none of the crate-native model constructors accepted.
-///
-/// Successful production routes never reach this function. Keeping error
-/// resolution separate means `create_chat_model*` no longer constructs a
-/// legacy `Provider` merely to discover that a route is invalid.
-fn unresolved_chat_model_error(role: &str, provider: &str, config: &Config) -> anyhow::Error {
- let p = provider.trim();
-
- if let Err(error) = enforce_local_only_inference(role, p) {
- return error;
- }
-
- if p == BYOK_INCOMPLETE_SENTINEL {
- let inference_url = config
- .inference_url
- .as_deref()
- .filter(|value| !value.trim().is_empty())
- .unwrap_or("<unset>");
- return anyhow::anyhow!(
- "[chat-factory] BYOK_INCOMPLETE: inference_url is set to a custom/direct endpoint \
- ({inference_url}) but no matching cloud_providers entry was found for role '{role}'. \
- To complete BYOK setup add a cloud_providers entry whose endpoint matches \
- {inference_url} (or use a workload-specific route). \
- To use the OpenHuman managed backend instead, clear inference_url from config."
- );
- }
-
- if p.is_empty() || p == "cloud" {
- return unresolved_chat_model_error(
- role,
- &resolve_primary_cloud_provider_string(config),
- config,
- );
- }
-
- #[cfg(not(test))]
- if let Err(error) = verify_session_active(config) {
- return error;
- }
-
- // Preserve the legacy chokepoint's disclosure ordering for invalid custom
- // routes: after both gates pass, the attempted external destination is
- // visible even when configuration validation then fails.
- emit_inference_egress(role, p);
-
- if let Some((slug, model_with_temperature)) = p.split_once(':') {
- if slug.trim().is_empty() {
- return anyhow::anyhow!(
- "[chat-factory] provider string '{}' for role '{}' has an empty slug",
- p,
- role
- );
- }
- let (model, _) = split_model_and_temperature(model_with_temperature);
- return match resolve_cloud_slug(role, slug.trim(), &model, config) {
- Err(error) => error,
- Ok(_) => anyhow::anyhow!(
- "[chat-factory] configured provider '{}' for role '{}' did not produce a crate-native chat model",
- p,
- role
- ),
- };
- }
-
- anyhow::anyhow!(
- "[chat-factory] unrecognised provider string '{}' for role '{}'. \
- Valid forms: openhuman, ollama:<model>, lmstudio:<model>, mlx:<model>, omlx:<model>, \
- local-openai:<model>, claude_agent_sdk, claude_agent_sdk:<model>, <slug>:<model>. \
- Configured slugs: [{}]",
- p,
- role,
- config
- .cloud_providers
- .iter()
- .map(|entry| entry.slug.as_str())
- .collect::<Vec<_>>()
- .join(", ")
- )
-}
-
-// ── Internal helpers ──────────────────────────────────────────────────────────
-
-/// Canonical managed-backend tier for a specialised workload role.
-///
-/// The managed backend otherwise derives its model from `config.default_model`
-/// (which defaults to the `chat-v1` tier), so a tier-specific workload whose
-/// per-workload provider is unset would silently inherit the global default —
-/// e.g. the `code_executor` sub-agent (`hint = "coding"`) would run on `chat-v1`
-/// instead of the dedicated `coding-v1` tier, defeating the whole point of the
-/// hint. The `hint:<tier>` translation in [`make_openhuman_backend`] only fires
-/// when the *model string itself* is `hint:coding`; here the model originates
-/// from `default_model`, so the workload role is the only signal left and must
-/// be mapped explicitly.
-///
-/// Returns `Some(tier)` for the specialised roles that map 1:1 to a managed
-/// tier (`reasoning`, `agentic`, `coding`, `vision`, `subconscious`). Returns
-/// `None` for:
-///
-/// - the generic `chat` role (and any other background/unknown role), which
-/// keeps inheriting `default_model`: the front-line chat turn and legacy
-/// `default_model = "reasoning-v1"` installs deliberately fall through to the
-/// `chat` role (see the session builder) and rely on `default_model` driving
-/// the model — pinning `chat` here would regress them.
-/// - `summarization` / `memory`, which are pinned in a dedicated branch of
-/// [`make_openhuman_backend`] via [`summarization_tier_model`] (fixed at
-/// `summarization-v1`) rather than here, only so the `memory` alias and the
-/// role string share one resolution site. They do **not** fall through to
-/// `default_model`.
-///
-/// `subconscious` IS pinned (to the lightweight `chat-v1` tier) even though it
-/// is a background workload: the cloud subconscious tick builds via the session
-/// builder with `default_model = "hint:subconscious"` (a role-routing marker, not
-/// a real tier), so "inherit `default_model`" would forward that marker to the
-/// backend. Pinning here resolves the managed model declaratively to `chat-v1` —
-/// the cheap monitoring tier the workload wants — independent of `default_model`,
-/// while [`provider_for_role`] still lets `subconscious_provider` choose the
-/// provider (managed / BYOK / local).
-///
-/// For `vision` the default-inheritance mismatch is not just suboptimal but
-/// fatal: an unset `vision_provider` would resolve to `chat-v1`,
-/// `model_supports_vision` would report `false`, and the turn engine would strip
-/// every attached image — leaving the managed vision sub-agent blind.
-fn managed_tier_for_role(role: &str) -> Option<&'static str> {
- use crate::config::{
- MODEL_AGENTIC_V1, MODEL_BURST_V1, MODEL_CHAT_V1, MODEL_CODING_V1, MODEL_REASONING_V1,
- MODEL_VISION_V1,
- };
- match role {
- "reasoning" => Some(MODEL_REASONING_V1),
- "agentic" => Some(MODEL_AGENTIC_V1),
- "coding" => Some(MODEL_CODING_V1),
- // Burst rides the managed backend's high-throughput tier. Pinned here
- // (rather than collapsing to `default_model`) so `hint = "burst"`
- // workers actually reach `burst-v1`.
- // There is no `burst_provider` knob: burst is managed-only.
- "burst" => Some(MODEL_BURST_V1),
- "vision" => Some(MODEL_VISION_V1),
- // Background subconscious tick/triage: pinned to the lightweight chat
- // tier (see the doc above for why it is pinned despite being background).
- "subconscious" => Some(MODEL_CHAT_V1),
- _ => None,
- }
-}
-
-/// The **managed-backend** summarization tier model — fixed at
-/// [`MODEL_SUMMARIZATION_V1`] (`summarization-v1`).
-///
-/// Read **only** on the managed OpenHuman path (inside [`make_openhuman_backend`]),
-/// so it is consumed iff the `summarization`/`memory` role actually resolves to
-/// the managed backend — BYOK and local routes carry their own model in the
-/// provider string and never reach here.
-///
-/// The managed summarization tier is intentionally **not** user-overridable: the
-/// hosted backend serves exactly one tier (`summarization-v1`) for this workload,
-/// so there is nothing else valid to point it at. Users who want a different
-/// model run summarization on a BYOK/local `memory_provider`, where the model
-/// rides in the provider string. (`memory_tree.cloud_llm_model` is no longer
-/// consumed — see its config doc.)
-pub(crate) fn summarization_tier_model() -> &'static str {
- crate::config::MODEL_SUMMARIZATION_V1
-}
-
-/// Build the OpenHuman backend provider (session-JWT auth).
-///
-/// `role` is the workload name (e.g. `"chat"`, `"coding"`, `"vision"`). A
-/// specialised workload role is pinned to its canonical managed tier via
-/// [`managed_tier_for_role`] so the `hint = "..."` a sub-agent declares actually
-/// reaches the matching backend tier instead of collapsing to `default_model`.
-/// The `summarization`/`memory` roles resolve their tier from
-/// [`summarization_tier_model`] (fixed at `summarization-v1`) so they never
-/// collapse to `default_model`. The generic `chat` role (and background roles)
-/// keep inheriting `config.default_model`.
-/// Resolve the managed OpenHuman backend for `role` — the model id (tier /
-/// summarization / default, with `hint:<tier>` translation) plus a configured
-/// [`OpenHumanBackendModel`]. Shared by both the `Provider` path
-/// ([`make_openhuman_backend`]) and the crate `ChatModel` path
-/// ([`make_openhuman_backend_model`], issue #4727 Motion B).
-fn resolve_managed_backend(
- role: &str,
- config: &Config,
-) -> anyhow::Result<(OpenHumanBackendModel, String)> {
- resolve_managed_backend_with_model_override(role, config, None)
-}
-
-fn resolve_managed_backend_with_model_override(
- role: &str,
- config: &Config,
- model_override: Option<&str>,
-) -> anyhow::Result<(OpenHumanBackendModel, String)> {
- let model = if let Some(tier) = managed_tier_for_role(role) {
- log::debug!(
- "[providers][chat-factory] role={} pinned to managed tier model={}",
- role,
- tier
- );
- tier.to_string()
- } else if matches!(role, "summarization" | "memory") {
- // Managed summarization/memory tier — fixed at `summarization-v1` rather
- // than inherited from `config.default_model`, so every managed
- // summarization caller — the memory tree, the chat-turn payload
- // summarizer, meeting summaries, and any `hint = "summarization"`
- // sub-agent — reaches the dedicated tier instead of silently collapsing
- // to `chat-v1`. BYOK/local routes never reach here — they build from the
- // provider string.
- let tier = summarization_tier_model().to_string();
- log::debug!(
- "[providers][chat-factory] role={} resolved managed summarization tier model={}",
- role,
- tier
- );
- tier
- } else {
- config
- .default_model
- .clone()
- .filter(|m| !m.trim().is_empty())
- .unwrap_or_else(|| "reasoning-v1".to_string())
- };
- // Critical: pass the *config's* workspace directory through so the
- // provider's `AuthService` reads `auth-profiles.json` from the
- // same dir login wrote to. Without this, `ProviderRuntimeOptions::default()`
- // leaves `openhuman_dir = None`, the provider falls back to
- // `~/.openhuman`, and reads an unrelated (or empty)
- // profile store — surfacing as "No backend session: store a JWT
- // via auth (app-session)" even though login just succeeded in the
- // user's actual workspace (e.g. test workspaces under OPENHUMAN_WORKSPACE).
- let options = ProviderRuntimeOptions {
- openhuman_dir: config.config_path.parent().map(std::path::PathBuf::from),
- secrets_encrypt: config.secrets.encrypt,
- ..ProviderRuntimeOptions::default()
- };
- log::debug!(
- "[providers][chat-factory] building openhuman backend provider model={} state_dir={:?} secrets_encrypt={}",
- model,
- options.openhuman_dir,
- options.secrets_encrypt
- );
- // Translate `hint:<tier>` model strings into the OpenHuman backend's
- // canonical tier names. Unrecognised `hint:*` strings (e.g. `hint:reaction`
- // for lightweight models) are forwarded as-is — the backend is authoritative
- // over which hint values it accepts, and the web-chat model_override path
- // uses these verbatim. Only non-hint strings that are not a known canonical
- // tier (stale `default_model` values written by older UI versions, e.g.
- // "deepseek-v4-pro", "claude-opus-4-7") fall back to the platform default.
- let model = match model.strip_prefix("hint:") {
- Some("reasoning") => crate::config::MODEL_REASONING_V1.to_string(),
- Some("chat") => crate::config::MODEL_CHAT_V1.to_string(),
- Some("agentic") => crate::config::MODEL_AGENTIC_V1.to_string(),
- Some("burst") => crate::config::MODEL_BURST_V1.to_string(),
- Some("coding") => crate::config::MODEL_CODING_V1.to_string(),
- Some("summarization") => crate::config::MODEL_SUMMARIZATION_V1.to_string(),
- Some("vision") => crate::config::MODEL_VISION_V1.to_string(),
- Some(_) => {
- // Unrecognised hint — forward verbatim; the backend decides validity.
- model
- }
- None => {
- // `model` is guaranteed non-empty here: an empty/whitespace
- // `default_model` was already normalised to `reasoning-v1` above, and
- // the managed-tier / summarization branches yield non-empty tier
- // constants. So a non-`hint:` id is either a known canonical tier or a
- // raw/BYOK id the user pinned — both forward verbatim; only the log
- // line differs.
- if is_known_openhuman_tier(&model) {
- model
- } else {
- // Unrecognised NON-empty model id — a raw/BYOK model the user
- // pinned (e.g. `claude-opus-4`, written into `default_model` or
- // a per-agent model pin). Forward it verbatim so the selected
- // model actually reaches provider construction instead of the
- // core silently collapsing it onto `reasoning-v1`. The managed
- // backend is authoritative over validity and returns a clear
- // error for a genuinely bad id (issue #4598).
- log::debug!(
- "[providers][chat-factory] forwarding raw/BYOK model '{}' verbatim to the \
- OpenHuman backend (not a managed tier); the backend validates it",
- model
- );
- model
- }
- }
- };
- let model = model_override
- .map(str::trim)
- .filter(|model| !model.is_empty())
- .map(ToOwned::to_owned)
- .unwrap_or(model);
-
- // Egress spine (privacy epic S2, #4436): managed backend resolution is the
- // universal chokepoint for EVERY managed-backend inference construction —
- // the direct ChatModel path and both turn paths
- // (`create_turn_chat_model[_from_string]_with_native_tools`) resolve here.
- // Emitting once here guarantees the default managed chat turn discloses
- // egress exactly once (see `emit_inference_egress`).
- crate::security::egress::emit_external_transfer(
- crate::security::egress::EgressDescriptor::inference("openhuman", &model, true),
- );
- Ok((
- OpenHumanBackendModel::new(config.api_url.as_deref(), &options, model.clone()),
- model,
- ))
-}
-
-/// The managed OpenHuman backend as a crate-native host `ChatModel`
-/// ([`OpenHumanBackendModel`], issue #4727 Motion B) — the cutover replacement
-/// for the `Provider` path. Same resolution; wraps the backend so the harness
-/// holds a crate `ChatModel` and the dynamic JWT + `thread_id` + billing envelope
-/// are bridged onto the crate wire client per call.
-pub(crate) fn make_openhuman_backend_model(
- role: &str,
- config: &Config,
-) -> anyhow::Result<(
- std::sync::Arc<dyn tinyinference::model::ChatModel<()>>,
- String,
-)> {
- let (model_client, model) = resolve_managed_backend(role, config)?;
- let chat: std::sync::Arc<dyn tinyinference::model::ChatModel<()>> =
- std::sync::Arc::new(model_client);
- Ok((chat, model))
-}
-
-/// Build a crate-native [`ChatModel`] for the **turn path**, pinned to an explicit
-/// `model` string — the turn's effective/dispatched model after any config-level
-/// agent pin (issue #4249, Phase 3 P3-B). The per-`(role, model)` analogue of
-/// [`create_chat_model_with_model_id`] used by the crate-native
-/// [`TurnModelSource`](crate::agent::tinyagents::TurnModelSource) to construct
-/// the primary + each workload-tier route directly.
-///
-/// - **Managed** → [`OpenHumanBackendModel`](super::openhuman_backend_model::OpenHumanBackendModel)
-/// pinned to `model`; the backend resolves the tier from `request.model`, so a
-/// tier alias / agent-model pin dispatches directly.
-/// - **Local / cloud** → the crate builders; the model rides the role's resolved
-/// provider string. A config-level *primary-model pin* on a local/cloud provider
-/// is not re-pinned here (pins are tier selection on the managed backend); the
-/// role's resolved model has the same behaviour.
-/// - **Claude Agent SDK** → its direct prompt-guided [`ChatModel`] subprocess
-/// adapter, pinned to `model`.
-/// - **Claude Code** → its direct native-tool streaming [`ChatModel`] subprocess
-/// adapter, pinned to `model`.
-///
-/// Respects the native test-model override, exactly as
-/// [`create_chat_model_with_model_id`].
-pub(crate) fn create_turn_chat_model(
- role: &str,
- config: &Config,
- model: &str,
- temperature: f64,
-) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
- create_turn_chat_model_with_native_tools(role, config, model, temperature, true)
-}
-
-pub(crate) fn create_turn_chat_model_with_native_tools(
- role: &str,
- config: &Config,
- model: &str,
- temperature: f64,
- native_tool_calling: bool,
-) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
- create_turn_chat_model_with_native_tools_and_route(
- role,
- config,
- model,
- temperature,
- native_tool_calling,
- )
- .map(|(chat, _, _)| chat)
-}
-
-/// Build a turn model together with the concrete provider and post-remap model
-/// id that the constructed client will put on the wire. The route metadata is
-/// consumed by channel audit recording; returning it from the construction
-/// branches avoids re-parsing a provider string before cloud default-model and
-/// abstract-tier remapping has run.
-pub(crate) fn create_turn_chat_model_with_native_tools_and_route(
- role: &str,
- config: &Config,
- model: &str,
- temperature: f64,
- native_tool_calling: bool,
-) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String, String)> {
- create_turn_chat_model_with_native_tools_and_route_inner(
- role,
- config,
- model,
- native_tool_calling,
- )
- .map(|(chat, provider, model)| (with_default_temperature(chat, temperature), provider, model))
-}
diff --git a/crates/openhuman-core/src/inference/provider/factory_part_03.rs b/crates/openhuman-core/src/inference/provider/factory_part_03.rs
deleted file mode 100644
index 61ec89d63e..0000000000
--- a/crates/openhuman-core/src/inference/provider/factory_part_03.rs
+++ /dev/null
@@ -1,688 +0,0 @@
-
-fn create_turn_chat_model_with_native_tools_and_route_inner(
- role: &str,
- config: &Config,
- model: &str,
- native_tool_calling: bool,
-) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String, String)> {
- #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
- if let Some(chat) = test_provider_override::current() {
- let provider = chat
- .profile()
- .and_then(|profile| profile.provider.clone())
- .unwrap_or_else(|| "injected".to_string());
- return Ok((chat, provider, model.to_string()));
- }
- let test_override_active = {
- #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
- {
- test_provider_override::current().is_some()
- }
- #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]
- {
- false
- }
- };
- if !test_override_active {
- if resolves_to_managed_backend(role, config) {
- let (backend, _resolved_model) = resolve_managed_backend(role, config)?;
- return Ok((
- Arc::new(
- backend
- .with_default_model(model)
- .with_native_tool_calling(native_tool_calling),
- ),
- PROVIDER_OPENHUMAN.to_string(),
- model.to_string(),
- ));
- }
- let resolved_provider = provider_for_role(role, config);
- let provider_name = resolved_provider
- .trim()
- .split(':')
- .next()
- .unwrap_or(resolved_provider.trim())
- .to_string();
- if let Some(result) = prepare_claude_agent_sdk_chat_model(role, &resolved_provider, config)
- {
- let _resolved_model = result?;
- emit_inference_egress(role, &format!("{CLAUDE_AGENT_SDK_PREFIX}{model}"));
- return Ok((
- Arc::new(ClaudeAgentSdkProvider::for_model(
- config.claude_agent_sdk.clone(),
- model,
- )),
- provider_name,
- model.to_string(),
- ));
- }
- if let Some(result) = try_create_claude_code_chat_model_from_string(
- role,
- &resolved_provider,
- config,
- Some(model),
- ) {
- return result
- .map(|(chat, _configured_model)| (chat, provider_name.clone(), model.to_string()));
- }
- if let Some(result) = try_create_local_runtime_chat_model(role, config) {
- return result
- .map(|(chat, resolved_model)| (chat, provider_name.clone(), resolved_model));
- }
- if let Some(result) =
- try_create_cloud_slug_chat_model_with_native_tools(role, config, native_tool_calling)
- {
- return result
- .map(|(chat, resolved_model)| (chat, provider_name.clone(), resolved_model));
- }
- }
- Err(unresolved_chat_model_error(
- role,
- &provider_for_role(role, config),
- config,
- ))
-}
-
-/// Build the Claude Agent SDK subprocess directly as a crate model. This is a
-/// prompt-guided model: TinyAgents owns its text-tool protocol, while the
-/// provider owns only subprocess transport and NDJSON decoding.
-fn try_create_claude_agent_sdk_chat_model(role: &str, config: &Config) -> OptionalChatModelResult {
- let resolved = provider_for_role(role, config);
- try_create_claude_agent_sdk_chat_model_from_string(role, &resolved, config)
-}
-
-fn try_create_claude_agent_sdk_chat_model_from_string(
- role: &str,
- provider: &str,
- config: &Config,
-) -> OptionalChatModelResult {
- let model = match prepare_claude_agent_sdk_chat_model(role, provider, config)? {
- Ok(model) => model,
- Err(error) => return Some(Err(error)),
- };
- emit_inference_egress(role, &format!("{CLAUDE_AGENT_SDK_PREFIX}{model}"));
- let chat: Arc<dyn ChatModel<()>> = Arc::new(ClaudeAgentSdkProvider::for_model(
- config.claude_agent_sdk.clone(),
- model.clone(),
- ));
- Some(Ok((chat, model)))
-}
-
-fn prepare_claude_agent_sdk_chat_model(
- role: &str,
- provider: &str,
- config: &Config,
-) -> Option<anyhow::Result<String>> {
- let model = claude_agent_sdk_model_from_string(provider, config)?;
- if let Err(error) = enforce_local_only_inference(role, provider) {
- return Some(Err(error));
- }
- #[cfg(not(test))]
- if let Err(error) = verify_session_active(config) {
- return Some(Err(error));
- }
- Some(Ok(model))
-}
-
-fn claude_agent_sdk_model_from_string(provider: &str, config: &Config) -> Option<String> {
- let provider = provider.trim();
- let model = if provider == CLAUDE_AGENT_SDK_PROVIDER {
- config.claude_agent_sdk.default_model.clone()
- } else if let Some(model) = provider.strip_prefix(CLAUDE_AGENT_SDK_PREFIX) {
- model.trim().to_string()
- } else {
- return None;
- };
- Some(model)
-}
-
-fn try_create_claude_code_chat_model(
- role: &str,
- config: &Config,
- model_override: Option<&str>,
-) -> OptionalChatModelResult {
- let resolved = provider_for_role(role, config);
- try_create_claude_code_chat_model_from_string(role, &resolved, config, model_override)
-}
-
-fn try_create_claude_code_chat_model_from_string(
- role: &str,
- provider: &str,
- config: &Config,
- model_override: Option<&str>,
-) -> OptionalChatModelResult {
- let provider = provider.trim();
- let model_with_temp = provider
- .strip_prefix(crate::inference::provider::claude_code::PROVIDER_PREFIX)?;
- let (configured_model, temperature_override) = split_model_and_temperature(model_with_temp);
- if temperature_override.is_some() {
- log::warn!(
- "[providers][chat-factory] claude-code provider: per-model temperature override \
- is accepted but not wired through to the CLI — the @<temp> suffix is ignored"
- );
- }
- if configured_model.is_empty() {
- return Some(Err(anyhow::anyhow!(
- "[chat-factory] provider string '{}' for role '{}' has an empty model — \
- use 'claude-code:<model-id>'",
- provider,
- role
- )));
- }
- if let Err(error) = enforce_local_only_inference(role, provider) {
- return Some(Err(error));
- }
- #[cfg(not(test))]
- if let Err(error) = verify_session_active(config) {
- return Some(Err(error));
- }
- let workspace =
- crate::inference::provider::claude_code::workspace_dir_from_config(config);
- let effective_model = model_override.unwrap_or(&configured_model).to_string();
- emit_inference_egress(
- role,
- &format!(
- "{}{effective_model}",
- crate::inference::provider::claude_code::PROVIDER_PREFIX
- ),
- );
- let chat =
- match crate::inference::provider::claude_code::ClaudeCodeProvider::from_env(
- effective_model,
- workspace,
- config.action_dir.clone(),
- ) {
- Ok(model) => Arc::new(model) as Arc<dyn ChatModel<()>>,
- Err(error) => return Some(Err(error)),
- };
- Some(Ok((chat, configured_model)))
-}
-
-/// Like [`create_turn_chat_model`] but for an **explicit** `provider_string` — the
-/// explicit-string counterpart of [`create_turn_chat_model`], for producers
-/// whose effective provider differs from the role's default resolution.
-///
-/// The triage path needs this: [`build_remote_provider`](crate::agent::triage::routing)
-/// forces the managed backend (`provider_string == `[`PROVIDER_OPENHUMAN`]) when the
-/// subconscious route is local / BYOK-incomplete — the #1257 *"triage never goes
-/// local"* invariant — which a plain [`create_turn_chat_model`] (role → `provider_for_role`)
-/// would violate by building the local model.
-///
-/// - `provider_string` empty / `"cloud"` / [`PROVIDER_OPENHUMAN`] → managed
-/// [`OpenHumanBackendModel`] pinned to `model` (the force-managed case).
-/// - Otherwise the string equals what the role resolves to (a BYOK cloud slug), so
-/// this delegates to [`create_turn_chat_model`] for `role`.
-///
-/// Respects the test-provider override (bespoke/`Provider` path), like its siblings.
-pub(crate) fn create_turn_chat_model_from_string(
- role: &str,
- provider_string: &str,
- config: &Config,
- model: &str,
- temperature: f64,
-) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
- create_turn_chat_model_from_string_with_native_tools(
- role,
- provider_string,
- config,
- model,
- temperature,
- true,
- )
-}
-
-pub(crate) fn create_turn_chat_model_from_string_with_native_tools(
- role: &str,
- provider_string: &str,
- config: &Config,
- model: &str,
- temperature: f64,
- native_tool_calling: bool,
-) -> anyhow::Result<Arc<dyn ChatModel<()>>> {
- create_turn_chat_model_from_string_with_native_tools_and_route(
- role,
- provider_string,
- config,
- model,
- temperature,
- native_tool_calling,
- )
- .map(|(chat, _, _)| chat)
-}
-
-pub(crate) fn create_turn_chat_model_from_string_with_native_tools_and_route(
- role: &str,
- provider_string: &str,
- config: &Config,
- model: &str,
- temperature: f64,
- native_tool_calling: bool,
-) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String, String)> {
- #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
- if let Some(chat) = test_provider_override::current() {
- let provider = chat
- .profile()
- .and_then(|profile| profile.provider.clone())
- .unwrap_or_else(|| "injected".to_string());
- return Ok((
- with_default_temperature(chat, temperature),
- provider,
- model.to_string(),
- ));
- }
- let test_override_active = {
- #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
- {
- test_provider_override::current().is_some()
- }
- #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]
- {
- false
- }
- };
- let p = provider_string.trim();
- let is_managed = p.is_empty() || p == "cloud" || p == PROVIDER_OPENHUMAN;
- if is_managed && !test_override_active {
- let (backend, _resolved_model) = resolve_managed_backend(role, config)?;
- return Ok((
- with_default_temperature(
- Arc::new(
- backend
- .with_default_model(model)
- .with_native_tool_calling(native_tool_calling),
- ),
- temperature,
- ),
- PROVIDER_OPENHUMAN.to_string(),
- model.to_string(),
- ));
- }
- // A concrete non-managed string equals the role's resolution (triage only
- // honours a BYOK **cloud** route as-is), so the role-based builder matches.
- create_turn_chat_model_with_native_tools_and_route(
- role,
- config,
- model,
- temperature,
- native_tool_calling,
- )
-}
-
-/// Local OpenAI-compatible runtimes (Ollama / LM Studio / MLX / OMLX /
-/// local-openai) as a crate-native [`ChatModel`] (issue #4727).
-///
-/// Returns `None` when `role` does not resolve to a local runtime, allowing
-/// [`create_chat_model_with_model_id`] to try cloud/BYOK/CLI constructors.
-///
-/// Endpoint/auth/`num_ctx` resolution uses the shared
-/// `ollama_base_url_from_config` / `lm_studio_base_url` / profile helpers. It
-/// runs the host access gates for custom/local providers —
-/// [`enforce_local_only_inference`] (privacy mode) +
-/// [`verify_session_active`] (session requirement) — so routing a local runtime
-/// here cannot bypass either. Temperature rides the per-call `ModelRequest` on
-/// the crate path (parity with the managed-backend cutover; the `@<temp>` suffix
-/// still bakes a fixed override).
-///
-type ResolvedChatModel = (Arc<dyn ChatModel<()>>, String);
-type OptionalChatModelResult = Option<anyhow::Result<ResolvedChatModel>>;
-
-fn try_create_local_runtime_chat_model(role: &str, config: &Config) -> OptionalChatModelResult {
- let resolved = provider_for_role(role, config);
- try_create_local_runtime_chat_model_from_string(role, &resolved, config, true)
-}
-
-fn try_create_local_runtime_chat_model_from_string(
- role: &str,
- provider: &str,
- config: &Config,
- require_session: bool,
-) -> OptionalChatModelResult {
- use crate::inference::local::profile::{
- LOCAL_OPENAI_PROFILE, MLX_PROFILE, OMLX_PROFILE,
- };
-
- let p = provider.trim().to_string();
- let is_local = p.starts_with(OLLAMA_PROVIDER_PREFIX)
- || p.starts_with(LM_STUDIO_PROVIDER_PREFIX)
- || p.starts_with(MLX_PROVIDER_PREFIX)
- || p.starts_with(OMLX_PROVIDER_PREFIX)
- || p.starts_with(LOCAL_OPENAI_PROVIDER_PREFIX);
- if !is_local {
- return None;
- }
-
- // Preserve host privacy-mode refusal + the session requirement for
- // custom/local providers.
- if let Err(e) = enforce_local_only_inference(role, &p) {
- return Some(Err(e));
- }
- if require_session {
- #[cfg(not(test))]
- if let Err(e) = verify_session_active(config) {
- return Some(Err(e));
- }
- }
-
- // Egress spine (privacy epic S2, #4436): committed to a local runtime here
- // (past the non-local `None` return + access gates). Disclose it as
- // NON-external — local inference never leaves the device, so
- // `emit_external_transfer` records it without firing a pending event. This
- // is the single local chokepoint for every ChatModel/turn entry.
- emit_inference_egress(role, &p);
-
- let unsupported = config.temperature_unsupported_models.clone();
- let empty_model_err = |p: &str, form: &str| {
- anyhow::anyhow!("[chat-factory] provider string '{p}' has an empty model — use '{form}'")
- };
-
- // Resolve the local `api_key` + auth style shared by lmstudio/omlx/local-openai
- // (Bearer when a key is configured, else no auth — same as the host builders).
- let keyed_auth = || {
- let api_key = config.local_ai.api_key.as_deref().unwrap_or("").to_string();
- let auth = if api_key.trim().is_empty() {
- CompatAuthStyle::None
- } else {
- CompatAuthStyle::Bearer
- };
- (api_key, auth)
- };
- // First env override, else `local_ai.base_url`, else the profile default.
- let env_or_config_url = |env: &str, default: &str| {
- std::env::var("OPENHUMAN_LOCAL_INFERENCE_URL")
- .ok()
- .filter(|s| !s.trim().is_empty())
- .or_else(|| std::env::var(env).ok().filter(|s| !s.trim().is_empty()))
- .or_else(|| config.local_ai.base_url.clone())
- .unwrap_or_else(|| default.to_string())
- };
-
- if let Some(rest) = p.strip_prefix(OLLAMA_PROVIDER_PREFIX) {
- let (model, temp) = split_model_and_temperature(rest);
- if model.is_empty() {
- return Some(Err(empty_model_err(&p, "ollama:<model-id>")));
- }
- // Ollama exposes the OpenAI-compatible endpoint at `/v1`.
- let base_url = crate::inference::local::ollama_base_url_from_config(config);
- let normalized = base_url.trim_end_matches('/').trim_end_matches("/v1");
- let endpoint = format!("{normalized}/v1");
- let chat = super::crate_openai::make_crate_local_runtime_chat_model(
- "ollama",
- &endpoint,
- "",
- CompatAuthStyle::None,
- &model,
- &unsupported,
- temp,
- config.local_ai.num_ctx,
- );
- return Some(Ok((chat, model)));
- }
- if let Some(rest) = p.strip_prefix(LM_STUDIO_PROVIDER_PREFIX) {
- let (model, temp) = split_model_and_temperature(rest);
- if model.is_empty() {
- return Some(Err(empty_model_err(&p, "lmstudio:<model-id>")));
- }
- let endpoint = crate::inference::local::lm_studio::lm_studio_base_url(config);
- let (api_key, auth) = keyed_auth();
- let chat = super::crate_openai::make_crate_local_runtime_chat_model(
- "lmstudio",
- &endpoint,
- &api_key,
- auth,
- &model,
- &unsupported,
- temp,
- None,
- );
- return Some(Ok((chat, model)));
- }
- if let Some(rest) = p.strip_prefix(MLX_PROVIDER_PREFIX) {
- let (model, temp) = split_model_and_temperature(rest);
- if model.is_empty() {
- return Some(Err(empty_model_err(&p, "mlx:<model-id>")));
- }
- let endpoint = env_or_config_url("MLX_SERVER_URL", MLX_PROFILE.default_base_url);
- let chat = super::crate_openai::make_crate_local_runtime_chat_model(
- "mlx",
- &endpoint,
- "",
- CompatAuthStyle::None,
- &model,
- &unsupported,
- temp,
- None,
- );
- return Some(Ok((chat, model)));
- }
- if let Some(rest) = p.strip_prefix(OMLX_PROVIDER_PREFIX) {
- let (model, temp) = split_model_and_temperature(rest);
- if model.is_empty() {
- return Some(Err(empty_model_err(&p, "omlx:<model-id>")));
- }
- let endpoint = env_or_config_url("OMLX_SERVER_URL", OMLX_PROFILE.default_base_url);
- let (api_key, auth) = keyed_auth();
- let chat = super::crate_openai::make_crate_local_runtime_chat_model(
- "omlx",
- &endpoint,
- &api_key,
- auth,
- &model,
- &unsupported,
- temp,
- None,
- );
- return Some(Ok((chat, model)));
- }
- if let Some(rest) = p.strip_prefix(LOCAL_OPENAI_PROVIDER_PREFIX) {
- let (model, temp) = split_model_and_temperature(rest);
- if model.is_empty() {
- return Some(Err(empty_model_err(&p, "local-openai:<model-id>")));
- }
- let endpoint = env_or_config_url("LOCAL_OPENAI_URL", LOCAL_OPENAI_PROFILE.default_base_url);
- let (api_key, auth) = keyed_auth();
- let chat = super::crate_openai::make_crate_local_runtime_chat_model(
- "local-openai",
- &endpoint,
- &api_key,
- auth,
- &model,
- &unsupported,
- temp,
- None,
- );
- return Some(Ok((chat, model)));
- }
- None
-}
-
-/// Build a crate-native local-runtime model for setup/probe calls that run
-/// before the desktop session gate is established.
-pub(crate) fn create_local_chat_model_from_string(
- provider: &str,
- config: &Config,
-) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {
- try_create_local_runtime_chat_model_from_string("chat", provider, config, false)
- .ok_or_else(|| anyhow::anyhow!("unsupported local provider string '{provider}'"))?
-}
-
-/// Verify the user has an active OpenHuman backend session.
-///
-/// Without this check, an unregistered user can configure every workload
-/// to use a custom cloud provider and bypass the session requirement
-/// entirely. This function ensures that custom providers (Ollama,
-/// `<slug>:<model>`) are only reachable when the workspace holds a valid
-/// `app-session` JWT.
-///
-/// `pub(crate)`: also reused directly by the flows provider-connectivity
-/// author gate (issue B45, `openhuman::flows::ops::evaluate_inference_readiness`)
-/// as its Layer 1 sync session check, so the author-time gate and this
-/// construction-time chokepoint can never diverge on what "session active"
-/// means.
-pub(crate) fn verify_session_active(config: &Config) -> anyhow::Result<()> {
- // An in-process library host is given its provider URL and credential by
- // its caller. It does not participate in the OpenHuman app's registration
- // or auth-profile lifecycle, so requiring a fabricated local session here
- // would mix desktop product policy into the library contract. The ambient
- // context is installed by the dispatch chokepoint; all other host kinds
- // retain the registration gate below.
- if !current_host_requires_session() {
- return Ok(());
- }
-
- verify_backend_session_active(config)
-}
-
-/// Managed `OpenhumanJwt` inference always needs the backend bearer, including
-/// in a Library host. Library mode exempts caller-owned provider credentials;
-/// it cannot manufacture a TinyHumans account credential.
-pub(crate) fn verify_backend_session_active(config: &Config) -> anyhow::Result<()> {
- // Fast path: the scheduler gate already knows the session is dead.
- if crate::cron::scheduler_gate::is_signed_out() {
- anyhow::bail!(
- "SESSION_EXPIRED: backend session not active — sign in to use custom providers"
- );
- }
- // Verify the app-session JWT actually exists in auth-profiles.
- let state_dir = config
- .config_path
- .parent()
- .map(std::path::PathBuf::from)
- .unwrap_or_else(|| {
- directories::UserDirs::new()
- .map(|d| d.home_dir().join(".openhuman"))
- .unwrap_or_else(|| std::path::PathBuf::from(".openhuman"))
- });
- let auth = AuthService::new(&state_dir, config.secrets.encrypt);
- let has_session = auth
- .get_provider_bearer_token(
- crate::security::credentials::APP_SESSION_PROVIDER,
- None,
- )?
- .filter(|s| !s.trim().is_empty())
- .is_some();
- if !has_session {
- anyhow::bail!("SESSION_EXPIRED: no backend session — sign in to use OpenHuman")
- }
- Ok(())
-}
-
-/// Whether inference in the ambient host participates in OpenHuman app login.
-/// Library hosts receive their provider configuration from the embedding
-/// process; every other host retains the product session policy.
-pub(crate) fn current_host_requires_session() -> bool {
- crate::core::runtime::context::CoreContext::current()
- .map(|ctx| host_requires_session(ctx.host_kind()))
- .unwrap_or(true)
-}
-
-fn host_requires_session(host_kind: crate::core::types::HostKind) -> bool {
- host_kind != crate::core::types::HostKind::Library
-}
-
-fn resolve_primary_cloud_provider_string(config: &Config) -> String {
- let primary = config
- .primary_cloud
- .as_deref()
- .and_then(|id| config.cloud_providers.iter().find(|entry| entry.id == id));
-
- if primary.is_some_and(is_openhuman_cloud_entry) {
- if let Some(legacy) = legacy_custom_inference_provider_string(config) {
- return legacy;
- }
- // Primary is explicitly OpenHuman but inference_url points at a custom
- // endpoint with no matching provider entry — this is a half-migrated BYOK
- // config. Fail closed so the user sees an actionable error rather than
- // silently routing through the managed backend.
- if has_custom_inference_intent(config) {
- log::debug!(
- "[providers][chat-factory] BYOK intent detected (host={}) \
- but no matching cloud_providers entry found; returning fail-closed sentinel",
- redact_inference_url(config.inference_url.as_deref())
- );
- return BYOK_INCOMPLETE_SENTINEL.to_string();
- }
- }
-
- if let Some(entry) = primary {
- return cloud_entry_provider_string(entry, config);
- }
-
- // No explicit primary configured. If inference_url signals custom intent but
- // no matching provider entry exists, fail closed instead of falling back to
- // the managed backend.
- legacy_custom_inference_provider_string(config).unwrap_or_else(|| {
- if has_custom_inference_intent(config) {
- log::debug!(
- "[providers][chat-factory] BYOK intent detected (host={}) \
- with no primary_cloud and no matching provider entry; returning fail-closed sentinel",
- redact_inference_url(config.inference_url.as_deref())
- );
- BYOK_INCOMPLETE_SENTINEL.to_string()
- } else {
- PROVIDER_OPENHUMAN.to_string()
- }
- })
-}
-
-/// Extract the host portion of an inference URL for safe logging.
-///
-/// Returns the host (e.g. `"api.example.com"`) so log lines are grep-friendly
-/// without exposing tokens or credentials that may appear in query-string or
-/// path components of a bearer-auth URL (e.g. `"https://host/v1?key=…"`).
-/// Falls back to `"<redacted>"` when the URL cannot be parsed or is absent.
-fn redact_inference_url(url: Option<&str>) -> &str {
- url.and_then(|u| {
- // Minimal host extraction: find the authority after "://".
- let after_scheme = u.find("://").map(|i| &u[i + 3..])?;
- // Authority ends at '/', '?', '#', or end-of-string.
- let host_end = after_scheme
- .find(['/', '?', '#'])
- .unwrap_or(after_scheme.len());
- let authority = &after_scheme[..host_end];
- // Strip optional "user:pass@" and port.
- let host = authority
- .rfind('@')
- .map_or(authority, |i| &authority[i + 1..]);
- let host = host.rfind(':').map_or(host, |i| &host[..i]);
- if host.is_empty() {
- None
- } else {
- Some(host)
- }
- })
- .unwrap_or("<redacted>")
-}
-
-/// Return `true` when the config contains a non-openhuman `inference_url`,
-/// indicating the user intends custom/BYOK routing rather than the managed
-/// backend.
-fn has_custom_inference_intent(config: &Config) -> bool {
- config
- .inference_url
- .as_deref()
- .map(str::trim)
- .filter(|url| !url.is_empty())
- .is_some_and(|url| !looks_like_openhuman_backend(url))
-}
-
-fn legacy_custom_inference_provider_string(config: &Config) -> Option<String> {
- let inference_url = config
- .inference_url
- .as_deref()
- .map(str::trim)
- .filter(|url| !url.is_empty())?;
-
- if looks_like_openhuman_backend(inference_url) {
- return None;
- }
-
- let normalized_inference = normalize_endpoint_for_compare(inference_url);
- config
- .cloud_providers
- .iter()
- .find(|entry| {
- !is_openhuman_cloud_entry(entry)
- && normalize_endpoint_for_compare(&entry.endpoint) == normalized_inference
- })
- .map(|entry| cloud_entry_provider_string(entry, config))
-}
diff --git a/crates/openhuman-core/src/inference/provider/factory_tests_part_01_tests.rs b/crates/openhuman-core/src/inference/provider/factory_route_resolution_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/inference/provider/factory_tests_part_01_tests.rs
rename to crates/openhuman-core/src/inference/provider/factory_route_resolution_tests.rs
diff --git a/crates/openhuman-core/src/inference/provider/factory_tests.rs b/crates/openhuman-core/src/inference/provider/factory_tests.rs
index 42b6c70d7f..ba1c1a8793 100644
--- a/crates/openhuman-core/src/inference/provider/factory_tests.rs
+++ b/crates/openhuman-core/src/inference/provider/factory_tests.rs
@@ -181,9 +181,9 @@ fn only_library_hosts_are_exempt_from_app_login() {
}
}
-#[path = "factory_tests_part_01_tests.rs"]
-mod part_01_tests;
-#[path = "factory_tests_part_02_tests.rs"]
-mod part_02_tests;
-#[path = "factory_tests_part_03_tests.rs"]
-mod part_03_tests;
+#[path = "factory_route_resolution_tests.rs"]
+mod route_resolution_tests;
+#[path = "factory_crate_native_tests.rs"]
+mod crate_native_tests;
+#[path = "factory_egress_fallback_tests.rs"]
+mod egress_fallback_tests;