Skip to content

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

refactor: delegate reusable inference to upstream crates

Steven Enamakel2448f7d5594a
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 9207cfed88..3c72cbb10a 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -174,10 +174,6 @@ path = "../../tests/calendar_grounding_e2e.rs"
name = "channels_host_boundary_e2e"
path = "../../tests/channels_host_boundary_e2e.rs"
-[[test]]
-name = "claude_code_stream_e2e"
-path = "../../tests/claude_code_stream_e2e.rs"
-
[[test]]
name = "cli_model_overrides_e2e"
path = "../../tests/cli_model_overrides_e2e.rs"
diff --git a/crates/openhuman-core/src/agent/message_convert_tests.rs b/crates/openhuman-core/src/agent/message_convert_tests.rs
index 49d9fd0233..304e922d27 100644
--- a/crates/openhuman-core/src/agent/message_convert_tests.rs
+++ b/crates/openhuman-core/src/agent/message_convert_tests.rs
@@ -39,9 +39,10 @@ fn native_image_round_trip_preserves_adjacent_text_for_claude_code() {
ContentBlock::Text(" after".to_string()),
],
});
- let native = message_to_native_chat_message(&source);
- let stdin =
- crate::inference::provider::claude_code::input_builder::build_stdin(&[native], true);
+ let stdin = tinyagents_harness::providers::claude_code::render_request_stdin(
+ &ModelRequest::new(vec![source]),
+ true,
+ );
let line: serde_json::Value = serde_json::from_slice(&stdin).unwrap();
let content = line["message"]["content"].as_array().unwrap();
assert_eq!(content[0]["text"], "before ");
@@ -60,9 +61,10 @@ fn native_image_round_trip_preserves_literal_private_marker_text() {
}),
],
});
- let native = message_to_native_chat_message(&source);
- let stdin =
- crate::inference::provider::claude_code::input_builder::build_stdin(&[native], true);
+ let stdin = tinyagents_harness::providers::claude_code::render_request_stdin(
+ &ModelRequest::new(vec![source]),
+ true,
+ );
let line: serde_json::Value = serde_json::from_slice(&stdin).unwrap();
let content = line["message"]["content"].as_array().unwrap();
assert_eq!(content[0]["text"], "literal ");
diff --git a/crates/openhuman-core/src/agent/tinyagents/model.rs b/crates/openhuman-core/src/agent/tinyagents/model.rs
index 9caf470760..d399a4580b 100644
--- a/crates/openhuman-core/src/agent/tinyagents/model.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/model.rs
@@ -297,12 +297,20 @@ pub(crate) fn merge_openhuman_usage_meta(
/// counts *and* backend-charged USD — survives the crossing.
pub(crate) fn usage_info_from_response(response: &ModelResponse) -> Option<UsageInfo> {
let usage = response.usage.as_ref()?;
- let meta = response
+ let mut meta = response
.raw
.as_ref()
.and_then(|v| v.get(OPENHUMAN_USAGE_META_KEY))
.and_then(|v| serde_json::from_value::<OpenhumanUsageMeta>(v.clone()).ok())
.unwrap_or_default();
+ if meta.charged_amount_usd <= 0.0 {
+ meta.charged_amount_usd = response
+ .raw
+ .as_ref()
+ .and_then(|value| value.get("total_cost_usd"))
+ .and_then(serde_json::Value::as_f64)
+ .unwrap_or_default();
+ }
Some(UsageInfo {
input_tokens: usage.input_tokens,
output_tokens: usage.output_tokens,
diff --git a/crates/openhuman-core/src/agent/tinyagents/model_g1_usage_tests_tests.rs b/crates/openhuman-core/src/agent/tinyagents/model_g1_usage_tests_tests.rs
index ae3a0190e1..5996f2a582 100644
--- a/crates/openhuman-core/src/agent/tinyagents/model_g1_usage_tests_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/model_g1_usage_tests_tests.rs
@@ -68,6 +68,18 @@ fn no_billing_metadata_leaves_raw_clean() {
assert_eq!(recovered.input_tokens, 5);
}
+#[test]
+fn provider_neutral_total_cost_metadata_is_recovered() {
+ let model_response = ModelResponse {
+ usage: Some(Usage::new(8, 3)),
+ raw: Some(serde_json::json!({"total_cost_usd": 0.0042})),
+ ..ModelResponse::assistant("done")
+ };
+
+ let recovered = usage_info_from_response(&model_response).expect("usage info");
+ assert!((recovered.charged_amount_usd - 0.0042).abs() < 1e-9);
+}
+
#[test]
fn no_usage_reconstructs_to_none() {
let chat = ChatResponse {
diff --git a/crates/openhuman-core/src/agent/triage/routing.rs b/crates/openhuman-core/src/agent/triage/routing.rs
index 063ecf3a7b..3d82013a8d 100644
--- a/crates/openhuman-core/src/agent/triage/routing.rs
+++ b/crates/openhuman-core/src/agent/triage/routing.rs
@@ -117,8 +117,8 @@ pub fn build_local_provider_with_config(config: &Config) -> Option<ResolvedProvi
/// the provider for a triage turn (#1257). Kept separate from
/// `is_local_provider_string`, which only classifies the local HTTP runtimes.
fn is_local_cli_route(provider_string: &str) -> bool {
- use crate::inference::provider::claude_code;
use crate::inference::provider::factory::{CLAUDE_AGENT_SDK_PREFIX, CLAUDE_AGENT_SDK_PROVIDER};
+ use tinyagents_harness::providers::claude_code;
let s = provider_string.trim();
s == CLAUDE_AGENT_SDK_PROVIDER
|| s.starts_with(CLAUDE_AGENT_SDK_PREFIX)
diff --git a/crates/openhuman-core/src/config/ops/local_ai_presets.rs b/crates/openhuman-core/src/config/ops/local_ai_presets.rs
new file mode 100644
index 0000000000..b237e39296
--- /dev/null
+++ b/crates/openhuman-core/src/config/ops/local_ai_presets.rs
@@ -0,0 +1,79 @@
+//! OpenHuman configuration mapping for TinyInference local-model presets.
+
+use crate::config::schema::LocalAiConfig;
+use tinyinference::local::presets::{all_presets, preset_for_tier, ModelTier, VisionMode};
+
+pub fn vision_mode_for_config(config: &LocalAiConfig) -> VisionMode {
+ match current_tier_from_config(config) {
+ ModelTier::Custom => {
+ if config.vision_model_id.trim().is_empty() {
+ VisionMode::Disabled
+ } else if config.preload_vision_model {
+ VisionMode::Bundled
+ } else {
+ VisionMode::Ondemand
+ }
+ }
+ tier => tinyinference::local::presets::vision_mode_for_tier(tier),
+ }
+}
+
+pub fn supports_screen_summary(config: &LocalAiConfig) -> bool {
+ !matches!(vision_mode_for_config(config), VisionMode::Disabled)
+}
+
+pub fn apply_preset_to_config(config: &mut LocalAiConfig, tier: ModelTier) {
+ if let Some(preset) = preset_for_tier(tier) {
+ tracing::debug!(
+ ?tier,
+ chat = preset.chat_model_id,
+ vision_mode = ?preset.vision_mode,
+ "[local_ai] applying preset to config"
+ );
+ config.model_id = preset.chat_model_id.to_string();
+ config.chat_model_id = preset.chat_model_id.to_string();
+ config.vision_model_id = preset.vision_model_id.to_string();
+ config.embedding_model_id = preset.embedding_model_id.to_string();
+ config.quantization = preset.quantization.to_string();
+ config.preload_vision_model = matches!(preset.vision_mode, VisionMode::Bundled);
+ config.preload_embedding_model = true;
+ config.selected_tier = Some(tier.as_str().to_string());
+ config.runtime_enabled = true;
+ } else {
+ tracing::debug!("[local_ai] apply_preset_to_config called for custom tier; no-op");
+ }
+}
+
+pub fn current_tier_from_config(config: &LocalAiConfig) -> ModelTier {
+ if let Some(ref stored) = config.selected_tier {
+ if let Some(tier) = ModelTier::from_str_opt(stored) {
+ if tier == ModelTier::Custom {
+ return ModelTier::Custom;
+ }
+ if let Some(preset) = preset_for_tier(tier) {
+ if preset_matches_config(&preset, config) {
+ return tier;
+ }
+ }
+ }
+ }
+
+ all_presets()
+ .into_iter()
+ .find(|preset| preset_matches_config(preset, config))
+ .map_or(ModelTier::Custom, |preset| preset.tier)
+}
+
+fn preset_matches_config(
+ preset: &tinyinference::local::presets::ModelPreset,
+ config: &LocalAiConfig,
+) -> bool {
+ let vision_matches = if matches!(preset.vision_mode, VisionMode::Disabled) {
+ config.vision_model_id.trim().is_empty()
+ } else {
+ config.vision_model_id == preset.vision_model_id
+ };
+ config.chat_model_id == preset.chat_model_id
+ && vision_matches
+ && config.embedding_model_id == preset.embedding_model_id
+}
diff --git a/crates/openhuman-core/src/config/ops/mod.rs b/crates/openhuman-core/src/config/ops/mod.rs
index e43fd57678..b9f177f76f 100644
--- a/crates/openhuman-core/src/config/ops/mod.rs
+++ b/crates/openhuman-core/src/config/ops/mod.rs
@@ -2,6 +2,7 @@
mod agent;
mod loader;
+pub mod local_ai_presets;
mod model;
mod privacy;
mod sandbox;
diff --git a/crates/openhuman-core/src/config/ops/model.rs b/crates/openhuman-core/src/config/ops/model.rs
index 445cfa26b7..b886c2127b 100644
--- a/crates/openhuman-core/src/config/ops/model.rs
+++ b/crates/openhuman-core/src/config/ops/model.rs
@@ -317,8 +317,10 @@ pub async fn apply_memory_settings(
// `embeddings::rpc::update_settings`), so a chat model id pasted here
// would otherwise be stored unchecked and 400 "does not exist" on every
// memory re-embed (2205 events from one user). Conservative check — see
- // `embeddings::non_embedding_model_reason`.
- if let Some(reason) = crate::inference::embeddings::non_embedding_model_reason(&model) {
+ // `tinyinference::embeddings::catalog::non_embedding_model_reason`.
+ if let Some(reason) =
+ tinyinference::embeddings::catalog::non_embedding_model_reason(&model)
+ {
return Err(format!("invalid embeddings model `{model}`: {reason}"));
}
config.memory.embedding_model = model;
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
index 2276c6815a..450dc1140c 100644
--- a/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rs
+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rs
@@ -9,8 +9,10 @@ impl Config {
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 {
+ if let Some(tier) =
+ tinyinference::local::presets::ModelTier::from_str_opt(&tier_str)
+ {
+ if tier == tinyinference::local::presets::ModelTier::Custom {
tracing::warn!(
tier = %tier_str,
"ignoring custom OPENHUMAN_LOCAL_AI_TIER; only built-in presets are supported"
@@ -21,7 +23,10 @@ impl Config {
"ignoring OPENHUMAN_LOCAL_AI_TIER outside the 1B local-model allowlist"
);
} else {
- crate::inference::presets::apply_preset_to_config(&mut self.local_ai, tier);
+ crate::config::ops::local_ai_presets::apply_preset_to_config(
+ &mut self.local_ai,
+ tier,
+ );
tracing::debug!(
tier = %tier_str,
"applied local AI tier from OPENHUMAN_LOCAL_AI_TIER"
diff --git a/crates/openhuman-core/src/inference/README.md b/crates/openhuman-core/src/inference/README.md
index b82a024c09..cc7b2bc8df 100644
--- a/crates/openhuman-core/src/inference/README.md
+++ b/crates/openhuman-core/src/inference/README.md
@@ -3,7 +3,7 @@
OpenHuman's inference integration domain. Reusable model, provider transport,
embedding, capability, temperature, and failure behavior belongs to
`tinyinference`; this domain owns product configuration, credentials, access
-policy, local process lifecycle (Ollama / LM Studio / Piper), RPC/controller
+policy, local process lifecycle (Ollama / LM Studio), RPC/controller
surfaces, OpenAI/Codex subscription OAuth, and the OpenAI-compatible HTTP
endpoint. The RPC surface is `inference.*`; older `local_ai_*` method names are
compatibility aliases in `crates/openhuman-core/src/core/legacy_aliases.rs`.
@@ -11,7 +11,7 @@ compatibility aliases in `crates/openhuman-core/src/core/legacy_aliases.rs`.
## Responsibilities
- Resolve workload names (`chat`, `reasoning`, `agentic`, `coding`, `memory`, `embeddings`, `heartbeat`, `learning`, etc.) and provider strings (`openhuman`, `cloud`, `ollama:<model>`, `lmstudio:<model>`, `claude_agent_sdk:<model>`, `claude-code:<model>`, `<slug>:<model>[@<temp>]`) to a concrete `Arc<dyn tinyinference::ChatModel<()>>` + model id.
-- Manage the local AI runtime: detect/spawn/adopt `ollama serve`, probe LM Studio over HTTP (never spawned), install/run Piper (TTS), track download progress, and enforce a minimum-context-window floor. Local STT (whisper.cpp) was retired; STT is now cloud/engine-configurable via `voice_server.stt_engine` (see `config/migrations/retire_local_whisper_stt.rs`).
+- Manage the local AI runtime: detect/spawn/adopt `ollama serve`, probe LM Studio over HTTP (never spawned), select OpenHuman-owned artifact paths, invoke TinyInference's Ollama/Piper installers, and enforce a minimum-context-window floor. Local STT (whisper.cpp) was retired; STT is now cloud/engine-configurable via `voice_server.stt_engine` (see `config/migrations/retire_local_whisper_stt.rs`).
- Provide chat, vision (multimodal), summarization, embeddings, sentiment, and "should react" inference operations.
- Preserve product-specific config-rejection, billing, and authentication policy while TinyInference owns provider-failure classification and TinyAgents owns model-call retry execution.
- Resolve abstract tier names (`reasoning-v1`, `agentic-v1`, `coding-v1`, etc.) through the TinyAgents `ModelRouter` in `crates/openhuman-core/src/agent/tinyagents/routes.rs` and the provider factory here.
@@ -34,14 +34,13 @@ compatibility aliases in `crates/openhuman-core/src/core/legacy_aliases.rs`.
| `tinyinference::model::effective_temperature` | Applies unsupported-model glob patterns and overrides before provider serialization. |
| `types.rs` | Serde DTOs: `LocalAiStatus`, `LocalAiAssetsStatus`, `LocalAiDownloadsProgress`, `LocalAiEmbeddingResult`, `LocalAiSpeechResult`, `LocalAiTtsResult`, etc. |
| `model_context.rs` | Known model context-window sizes (`context_window_for_model`) for pre-dispatch budgeting. |
-| `presets.rs` | `ModelPreset`, `ModelTier`, `VisionMode`; tier recommendation + apply-to-config; MVP preset gating. |
+| `config/ops/local_ai_presets.rs` | OpenHuman `LocalAiConfig` mapping for `tinyinference::local::presets`; reusable tiers, recommendations, and preset data live upstream. |
| `paths.rs` | Host-owned on-disk model artifact paths. Completion and sentiment parsing live in `tinyinference`. |
| `local/` | Local runtime manager (was `local_ai/`). See `local/README.md`. |
| `local/core.rs` | `LocalAiService` singleton (`global`/`try_global`), `model_artifact_path`. |
| `local/ops.rs` + `local/ops/` (`runtime_ops.rs`, `chat.rs`, `agent_chat.rs`, `reactions.rs`, `turn_guards.rs`) | Local RPC entrypoints (`local_ai_status/prompt/summarize/vision_prompt/embed/should_react`, `ReactionDecision`); re-exported as `local::rpc`. |
| `local/schemas.rs` | Local-runtime `inference.*` controller schemas + handlers. |
-| `local/install*.rs`, `local/voice_install_common.rs` | Ollama/Piper install + shared download logic. No Whisper install any more. |
-| `tinyinference::local` | Ollama/LM Studio wire types, URL handling, model requirements, runtime profiles, provider selection, process flags, and spawn-marker persistence. |
+| `tinyinference::local` | Ollama/LM Studio wire types, URL handling, model requirements, runtime profiles, provider selection, process flags, spawn-marker persistence, Ollama installation, and Piper binary/voice installation. |
| `local/service/` | `LocalAiService` impl split: `bootstrap`, `assets`, `lm_studio`, `model_rpc`, `public_infer`, `speech`, `transcription`, `vision_embed`, `spawn_marker`, `ollama_admin/`. |
| `local/service/ollama_admin/` | Ollama daemon lifecycle split by concern: `binary`, `diagnostics`, `health`, `model_pull`, `server`, `util` (`test_ollama_connection`). |
| `provider/` | Native TinyAgents model construction plus host provider configuration, auth, error taxonomy, DTOs, and RPC helpers (was `providers/`). See `provider/README.md`. |
@@ -51,7 +50,7 @@ compatibility aliases in `crates/openhuman-core/src/core/legacy_aliases.rs`.
| `provider/openhuman_backend_model.rs` | Managed OpenHuman backend `ChatModel` with session JWT, billing metadata, and thread context. |
| `provider/openai_codex.rs` | `pub(crate)` Codex routing metadata (`OpenAiCodexRouting`, `resolve_openai_codex_routing`): re-targets the `openai` slug at the ChatGPT Codex backend with account/originator headers when Codex OAuth tokens exist. Not a `ChatModel` itself. |
| `tinyagents_harness::providers::claude_agent_sdk` | Claude Agent SDK subprocess provider and prompt-guided tool adapter. |
-| `provider/claude_code/` | Claude Code CLI provider (`claude-code:<model>`). Drives the `claude` CLI over stream-json; see `provider/claude_code/README.md`. |
+| `tinyagents_harness::providers::claude_code` | Claude Code CLI provider (`claude-code:<model>`), stream-json parser/driver, auth probes, settings, and subprocess lifecycle. OpenHuman supplies only its MCP endpoint and product routing. |
| `provider/error_classify.rs` | OpenHuman policy layered on the reusable classifiers in `tinyinference::classification`. |
| `tinyinference::providers::openai::AuthStyle` | Wire auth style consumed directly by crate-native builders. |
| `provider/ops/` | Host HTTP policy, model catalog RPC, and provider configuration; reusable sanitization lives in `tinyinference::sanitize`. |
@@ -69,7 +68,6 @@ compatibility aliases in `crates/openhuman-core/src/core/legacy_aliases.rs`.
From `mod.rs` re-exports:
- `model_context::context_window_for_model`
-- `presets::{ModelPreset, ModelTier, VisionMode}`
- `types::{LocalAiStatus, LocalAiAssetStatus, LocalAiAssetsStatus, LocalAiDownloadProgressItem, LocalAiDownloadsProgress, LocalAiEmbeddingResult, LocalAiSpeechResult, LocalAiTtsResult}`
- `local::all_local_inference_controller_schemas` / `local::all_local_inference_registered_controllers` (legacy export names; registered schemas are in the `inference` namespace)
- `rpc` (alias for `ops`) and `all_inference_controller_schemas` / `all_inference_registered_controllers`
@@ -96,7 +94,7 @@ Also exposes a non-RPC HTTP router (`http::router()`) nested at `/v1` by `crates
- `openai_oauth/store.rs` persists OAuth tokens via the credentials auth-profile store (`AuthProfilesStore`, `auth-profiles.json`, encrypted at rest) under profile key `provider:openai` / profile `oauth`.
- `LocalAiService` holds in-process runtime state (status, owned `ollama serve` child) via the `local::global` `OnceCell` singleton — process-lifetime, not durably persisted.
-- Model artifacts live under `<root>/models/local-ai/` (`local/core.rs::model_artifact_path`); installed Piper assets via `local/install*`.
+- Model artifacts live under `<root>/models/local-ai/` (`local/core.rs::model_artifact_path`); OpenHuman selects the Piper root and passes it to `tinyinference::local::piper::PiperInstall`.
- Routing/provider/local settings persisted through `config` (no dedicated `store.rs`).
## Dependencies
diff --git a/crates/openhuman-core/src/inference/embeddings/catalog.rs b/crates/openhuman-core/src/inference/embeddings/catalog.rs
deleted file mode 100644
index 6043c7adba..0000000000
--- a/crates/openhuman-core/src/inference/embeddings/catalog.rs
+++ /dev/null
@@ -1,203 +0,0 @@
-//! Static catalog of supported embedding providers.
-//!
-//! Each entry declares its slug, display label, whether it requires an API key,
-//! and the models + dimension presets it supports. The frontend reads this via
-//! `openhuman.embeddings_get_settings` to populate the provider picker.
-
-use serde::Serialize;
-
-#[derive(Debug, Clone, Serialize)]
-pub struct EmbeddingModelPreset {
- pub id: &'static str,
- pub label: &'static str,
- pub default_dimensions: usize,
- pub allowed_dimensions: &'static [usize],
-}
-
-#[derive(Debug, Clone, Serialize)]
-pub struct EmbeddingProviderEntry {
- pub slug: &'static str,
- pub label: &'static str,
- pub description: &'static str,
- pub requires_api_key: bool,
- pub requires_endpoint: bool,
- pub models: &'static [EmbeddingModelPreset],
-}
-
-pub const PROVIDER_MANAGED: &str = "managed";
-pub const PROVIDER_VOYAGE: &str = "voyage";
-pub const PROVIDER_OPENAI: &str = "openai";
-pub const PROVIDER_COHERE: &str = "cohere";
-pub const PROVIDER_OLLAMA: &str = "ollama";
-pub const PROVIDER_CUSTOM: &str = "custom";
-pub const PROVIDER_NONE: &str = "none";
-
-static MANAGED_MODELS: &[EmbeddingModelPreset] = &[EmbeddingModelPreset {
- id: "embedding-v1",
- label: "Embedding v1 (Voyage-backed)",
- default_dimensions: 1024,
- allowed_dimensions: &[1024],
-}];
-
-static VOYAGE_MODELS: &[EmbeddingModelPreset] = &[
- EmbeddingModelPreset {
- id: "voyage-3-large",
- label: "Voyage 3 Large",
- default_dimensions: 1024,
- allowed_dimensions: &[256, 512, 1024, 2048],
- },
- EmbeddingModelPreset {
- id: "voyage-3",
- label: "Voyage 3",
- default_dimensions: 1024,
- allowed_dimensions: &[1024],
- },
- EmbeddingModelPreset {
- id: "voyage-code-3",
- label: "Voyage Code 3",
- default_dimensions: 1024,
- allowed_dimensions: &[1024],
- },
-];
-
-static OPENAI_MODELS: &[EmbeddingModelPreset] = &[
- EmbeddingModelPreset {
- id: "text-embedding-3-small",
- label: "Embedding 3 Small",
- default_dimensions: 1536,
- allowed_dimensions: &[512, 1536],
- },
- EmbeddingModelPreset {
- id: "text-embedding-3-large",
- label: "Embedding 3 Large",
- default_dimensions: 3072,
- allowed_dimensions: &[256, 1024, 3072],
- },
-];
-
-static COHERE_MODELS: &[EmbeddingModelPreset] = &[
- EmbeddingModelPreset {
- id: "embed-english-v3.0",
- label: "Embed English v3",
- default_dimensions: 1024,
- allowed_dimensions: &[1024],
- },
- EmbeddingModelPreset {
- id: "embed-multilingual-v3.0",
- label: "Embed Multilingual v3",
- default_dimensions: 1024,
- allowed_dimensions: &[1024],
- },
-];
-
-static OLLAMA_MODELS: &[EmbeddingModelPreset] = &[EmbeddingModelPreset {
- id: "bge-m3",
- label: "BGE-M3",
- default_dimensions: 1024,
- allowed_dimensions: &[1024],
-}];
-
-static CATALOG: &[EmbeddingProviderEntry] = &[
- EmbeddingProviderEntry {
- slug: PROVIDER_MANAGED,
- label: "Managed (OpenHuman)",
- description: "Routes through the OpenHuman backend. No API key needed.",
- requires_api_key: false,
- requires_endpoint: false,
- models: MANAGED_MODELS,
- },
- EmbeddingProviderEntry {
- slug: PROVIDER_VOYAGE,
- label: "Voyage AI",
- description: "Direct Voyage AI API with your own key.",
- requires_api_key: true,
- requires_endpoint: false,
- models: VOYAGE_MODELS,
- },
- EmbeddingProviderEntry {
- slug: PROVIDER_OPENAI,
- label: "OpenAI",
- description: "OpenAI embeddings API with your own key.",
- requires_api_key: true,
- requires_endpoint: false,
- models: OPENAI_MODELS,
- },
- EmbeddingProviderEntry {
- slug: PROVIDER_COHERE,
- label: "Cohere",
- description: "Cohere embed API with your own key.",
- requires_api_key: true,
- requires_endpoint: false,
- models: COHERE_MODELS,
- },
- EmbeddingProviderEntry {
- slug: PROVIDER_OLLAMA,
- label: "Ollama (Local)",
- description: "Local Ollama server. No API key needed.",
- requires_api_key: false,
- requires_endpoint: false,
- models: OLLAMA_MODELS,
- },
- EmbeddingProviderEntry {
- slug: PROVIDER_CUSTOM,
- label: "Custom (OpenAI-compatible)",
- description: "Any OpenAI-compatible embedding endpoint.",
- requires_api_key: true,
- requires_endpoint: true,
- models: &[],
- },
- EmbeddingProviderEntry {
- slug: PROVIDER_NONE,
- label: "Disabled",
- description: "Disable semantic search. Keyword search only.",
- requires_api_key: false,
- requires_endpoint: false,
- models: &[],
- },
-];
-
-pub fn all_providers() -> &'static [EmbeddingProviderEntry] {
- CATALOG
-}
-
-pub fn find_provider(slug: &str) -> Option<&'static EmbeddingProviderEntry> {
- CATALOG.iter().find(|e| e.slug == slug)
-}
-
-pub fn find_model(provider_slug: &str, model_id: &str) -> Option<&'static EmbeddingModelPreset> {
- find_provider(provider_slug).and_then(|p| p.models.iter().find(|m| m.id == model_id))
-}
-
-pub fn default_model_for(provider_slug: &str) -> Option<&'static EmbeddingModelPreset> {
- find_provider(provider_slug).and_then(|p| p.models.first())
-}
-
-/// Returns `Some(reason)` when `model` is unmistakably **not** an embeddings
-/// model and must be rejected before it is persisted as the embeddings model.
-///
-/// Conservative by design (zero false positives on real embedding ids): the
-/// only hard signal is the OpenRouter `:free` chat/reasoning tier suffix — no
-/// embeddings model is served under it, and a chat model id pasted into the
-/// free-text custom-model field is exactly how TAURI-RUST-9SK happened
-/// (`nvidia/nemotron-3-super-120b-a12b:free` saved as the embeddings model,
-/// then 400 "does not exist" on every memory re-embed — 2205 events).
-///
-/// This is a source-gate for the persist paths that have **no** live verify
-/// probe (`config::ops::model::apply_memory_settings`); the Custom-provider
-/// setup flow already runs a save-time test embed (`embeddings::rpc::
-/// update_settings`), and the broad long tail of chat ids is caught at runtime
-/// by the 400 "does not exist" classifier in `core::observability`. Kept
-/// deliberately tight: a false positive blocks a user's valid embeddings model.
-pub fn non_embedding_model_reason(model: &str) -> Option<&'static str> {
- if model.trim().to_ascii_lowercase().ends_with(":free") {
- return Some(
- "`:free` denotes an OpenRouter chat/reasoning tier, not an embeddings model — \
- pick an embeddings-capable model in Settings → Memory",
- );
- }
- None
-}
-
-#[cfg(test)]
-#[path = "catalog_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/embeddings/catalog_tests.rs b/crates/openhuman-core/src/inference/embeddings/catalog_tests.rs
deleted file mode 100644
index 8030aa4b30..0000000000
--- a/crates/openhuman-core/src/inference/embeddings/catalog_tests.rs
+++ /dev/null
@@ -1,112 +0,0 @@
-use super::*;
-
-#[test]
-fn catalog_is_non_empty() {
- assert!(!all_providers().is_empty());
-}
-
-#[test]
-fn managed_is_first() {
- assert_eq!(all_providers()[0].slug, PROVIDER_MANAGED);
-}
-
-#[test]
-fn find_voyage_model() {
- let m = find_model(PROVIDER_VOYAGE, "voyage-3-large").unwrap();
- assert!(m.allowed_dimensions.contains(&1024));
-}
-
-#[test]
-fn default_model_for_openai() {
- let m = default_model_for(PROVIDER_OPENAI).unwrap();
- assert_eq!(m.id, "text-embedding-3-small");
-}
-
-#[test]
-fn none_has_no_models() {
- let p = find_provider(PROVIDER_NONE).unwrap();
- assert!(p.models.is_empty());
-}
-
-#[test]
-fn unknown_provider_returns_none() {
- assert!(find_provider("unknown").is_none());
-}
-
-#[test]
-fn all_providers_have_unique_slugs() {
- let providers = all_providers();
- let mut seen = std::collections::HashSet::new();
- for entry in providers {
- assert!(
- seen.insert(entry.slug),
- "duplicate slug in CATALOG: \"{}\"",
- entry.slug
- );
- }
-}
-
-#[test]
-fn all_models_have_valid_dimensions() {
- for entry in all_providers() {
- for model in entry.models {
- assert!(
- model.allowed_dimensions.contains(&model.default_dimensions),
- "provider \"{}\" model \"{}\" has default_dimensions {} not in allowed_dimensions {:?}",
- entry.slug,
- model.id,
- model.default_dimensions,
- model.allowed_dimensions
- );
- }
- }
-}
-
-#[test]
-fn non_embedding_model_reason_rejects_openrouter_free_tier() {
- // TAURI-RUST-9SK — the exact incident id and case/whitespace variants.
- for id in [
- "nvidia/nemotron-3-super-120b-a12b:free",
- "meta-llama/llama-3-70b-instruct:FREE",
- " some-chat-model:free ",
- ] {
- assert!(
- non_embedding_model_reason(id).is_some(),
- "{id:?} (`:free` chat tier) must be rejected as an embeddings model"
- );
- }
-}
-
-#[test]
-fn non_embedding_model_reason_accepts_real_embedding_ids() {
- // Must NOT false-positive on genuine embedding model ids across providers.
- for id in [
- "text-embedding-3-small",
- "text-embedding-3-large",
- "voyage-3-large",
- "embed-english-v3.0",
- "nomic-embed-text:latest",
- "bge-m3",
- "mxbai-embed-large",
- "",
- ] {
- assert!(
- non_embedding_model_reason(id).is_none(),
- "{id:?} is a valid embeddings model and must not be rejected"
- );
- }
-}
-
-#[test]
-fn default_model_for_all_providers_with_models() {
- for entry in all_providers() {
- if !entry.models.is_empty() {
- assert!(
- default_model_for(entry.slug).is_some(),
- "default_model_for({:?}) returned None but provider has {} models",
- entry.slug,
- entry.models.len()
- );
- }
- }
-}
diff --git a/crates/openhuman-core/src/inference/embeddings/mod.rs b/crates/openhuman-core/src/inference/embeddings/mod.rs
index bba3403c33..dc38afb4f7 100644
--- a/crates/openhuman-core/src/inference/embeddings/mod.rs
+++ b/crates/openhuman-core/src/inference/embeddings/mod.rs
@@ -12,7 +12,6 @@
//! - **Custom**: Any OpenAI-compatible endpoint.
//! - **Noop**: A fallback provider for keyword-only search.
-pub mod catalog;
#[path = "cloud_adapter.rs"]
pub mod cloud;
mod factory;
@@ -21,7 +20,6 @@ mod provider_trait;
mod rpc;
mod schemas;
-pub use catalog::non_embedding_model_reason;
pub use cloud::{
OpenHumanCloudEmbedding, DEFAULT_CLOUD_EMBEDDING_DIMENSIONS, DEFAULT_CLOUD_EMBEDDING_MODEL,
};
diff --git a/crates/openhuman-core/src/inference/embeddings/rpc/settings.rs b/crates/openhuman-core/src/inference/embeddings/rpc/settings.rs
index 6f06e9d27b..7af8809e6b 100644
--- a/crates/openhuman-core/src/inference/embeddings/rpc/settings.rs
+++ b/crates/openhuman-core/src/inference/embeddings/rpc/settings.rs
@@ -8,7 +8,7 @@ use crate::security::credentials::AuthService;
use super::probe::{classify_embed_probe, final_probe_dims, probe_custom_embeddings, EmbedProbe};
use super::served_models::{check_requested_model_served, fetch_served_model_ids};
use super::{resolve_api_key, LOG_PREFIX};
-use crate::inference::embeddings::catalog;
+use tinyinference::embeddings::catalog;
/// Slug naming the embedder ingestion will actually use, resolved host-side
/// from the `Config` fields the resolution ladder reads.
diff --git a/crates/openhuman-core/src/inference/local/install.rs b/crates/openhuman-core/src/inference/local/install.rs
deleted file mode 100644
index 79c7f5c08e..0000000000
--- a/crates/openhuman-core/src/inference/local/install.rs
+++ /dev/null
@@ -1,335 +0,0 @@
-//! Automatic Ollama installer and system binary discovery.
-
-use std::path::{Path, PathBuf};
-
-/// Name of the Inno Setup installer process. On Windows the installer is
-/// spawned via PowerShell's `Start-Process`, which creates a top-level
-/// process — it survives the parent OpenHuman process dying. If OpenHuman
-/// is killed mid-install (or the user closes the app and reopens it before
-/// install completes) we need to detect the in-flight installer instead
-/// of launching a second one that would race on the same install dir.
-#[cfg(windows)]
-const OLLAMA_INSTALLER_PROCESS_NAME: &str = "OllamaSetup.exe";
-
-/// Returns `true` when a Windows OllamaSetup.exe process is currently
-/// running anywhere on the machine. macOS / Linux installs are spawned
-/// as `sh` children of the Rust core and cannot orphan past it; the
-/// non-Windows branch is therefore a constant `false`.
-#[cfg(windows)]
-pub(crate) fn is_ollama_installer_running() -> bool {
- use sysinfo::{ProcessesToUpdate, System};
- let mut sys = System::new();
- // refresh_processes is sufficient — we only need the process list, not
- // CPU/memory/disk/network. refresh_all() adds dozens of milliseconds of
- // blocking I/O on a loaded Windows machine and this function runs on the
- // async executor inside download_and_install_ollama.
- // sysinfo 0.33 added a second `remove_dead_processes` parameter.
- sys.refresh_processes(ProcessesToUpdate::All, true);
- sys.processes().values().any(|p| {
- p.name()
- .to_string_lossy()
- .eq_ignore_ascii_case(OLLAMA_INSTALLER_PROCESS_NAME)
- })
-}
-
-#[cfg(not(windows))]
-pub(crate) fn is_ollama_installer_running() -> bool {
- false
-}
-
-/// Captured output from the Ollama install script.
-pub(crate) struct InstallResult {
- pub exit_status: std::process::ExitStatus,
- pub stdout: String,
- pub stderr: String,
-}
-
-/// Run the platform-specific Ollama install into the workspace and capture stdout/stderr.
-pub(crate) async fn run_ollama_install_script(install_dir: &Path) -> Result<InstallResult, String> {
- let mut cmd = build_install_command(install_dir)?;
-
- let output = cmd
- .output()
- .await
- .map_err(|e| format!("failed to execute Ollama installer: {e}"))?;
-
- log::debug!(
- "[local_ai] Ollama install script finished (dir={} exit={}) stdout={} stderr={}",
- install_dir.display(),
- output.status,
- String::from_utf8_lossy(&output.stdout),
- String::from_utf8_lossy(&output.stderr),
- );
-
- Ok(InstallResult {
- exit_status: output.status,
- stdout: String::from_utf8_lossy(&output.stdout).to_string(),
- stderr: String::from_utf8_lossy(&output.stderr).to_string(),
- })
-}
-
-#[cfg(target_os = "windows")]
-pub(crate) fn resolve_powershell_executable() -> std::ffi::OsString {
- // `Command::new("powershell")` relies on PATH. When OpenHuman.exe is
- // spawned by `cargo tauri dev` (or similar dev harnesses) the inherited
- // PATH can be sanitized down to a subset that excludes the
- // `WindowsPowerShell\v1.0` dir, and the spawn fails with `program not
- // found`. Probe known absolute locations first and fall back to the
- // bare name if none are present.
- //
- // %SystemRoot% defaults to `C:\Windows` and is always set on Windows
- // sessions.
- let system_root =
- std::env::var_os("SystemRoot").unwrap_or_else(|| std::ffi::OsString::from("C:\\Windows"));
- for relative in [
- "System32\\WindowsPowerShell\\v1.0\\powershell.exe",
- "SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe",
- ] {
- let mut candidate = std::path::PathBuf::from(&system_root);
- candidate.push(relative);
- if candidate.is_file() {
- return candidate.into_os_string();
- }
- }
- // PowerShell 7 (`pwsh.exe`) is another viable substitute when present.
- if let Ok(pf) = std::env::var("ProgramFiles") {
- let p7 = std::path::PathBuf::from(pf)
- .join("PowerShell")
- .join("7")
- .join("pwsh.exe");
- if p7.is_file() {
- return p7.into_os_string();
- }
- }
- std::ffi::OsString::from("powershell")
-}
-
-fn build_install_command(install_dir: &Path) -> Result<tokio::process::Command, String> {
- #[cfg(target_os = "windows")]
- {
- let powershell_exe = resolve_powershell_executable();
- log::debug!(
- "[local_ai] resolved powershell for installer: {}",
- powershell_exe.to_string_lossy()
- );
- let mut cmd = tokio::process::Command::new(&powershell_exe);
- // Kill the PowerShell child if the spawning future is dropped — e.g.
- // the in-process tokio runtime shuts down because the user closed
- // OpenHuman mid-install. Without this, `cmd.output().await` keeps
- // OpenHuman.exe alive (and port 7788 bound) for the full 60–120s of
- // the install download, producing zombie processes and
- // "port in use" errors on the next launch. Note: OllamaSetup.exe is
- // spawned by PowerShell as a TOP-LEVEL process (via `Start-Process`),
- // so it survives PowerShell's death. That's intentional — the
- // crash-resume detection in `is_ollama_installer_running` picks it
- // up on the next OpenHuman launch and waits.
- cmd.kill_on_drop(true);
- tinyinference::local::process::apply_no_window(&mut cmd);
- cmd.env("OPENHUMAN_OLLAMA_INSTALL_DIR", install_dir);
- cmd.args([
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-Command",
- r#"
- $ErrorActionPreference = "Stop"
- $ProgressPreference = "SilentlyContinue"
- $installDir = $env:OPENHUMAN_OLLAMA_INSTALL_DIR
- New-Item -ItemType Directory -Path $installDir -Force | Out-Null
- $installerUrl = "https://ollama.com/download/OllamaSetup.exe"
- $tempInstaller = Join-Path $env:TEMP "OllamaSetup.exe"
- Invoke-WebRequest -UseBasicParsing -Uri $installerUrl -OutFile $tempInstaller
- # /SILENT (not /VERYSILENT) so Inno Setup's small progress dialog
- # appears. The dialog is owned by the OS, not OpenHuman, so it
- # survives the parent process crashing — giving the user a visible
- # signal that an install is in flight even if OpenHuman dies.
- $args = "/SILENT /NORESTART /SUPPRESSMSGBOXES /CURRENTUSER /DIR=""$installDir"""
- $proc = Start-Process -FilePath $tempInstaller -ArgumentList $args -PassThru
- $proc.WaitForExit()
- if ($proc.ExitCode -ne 0) {
- throw "Installation failed with exit code $($proc.ExitCode)"
- }
- Remove-Item $tempInstaller -Force -ErrorAction SilentlyContinue
- "#,
- ]);
- return Ok(cmd);
- }
-
- #[cfg(target_os = "macos")]
- {
- let mut cmd = tokio::process::Command::new("sh");
- // Same rationale as the Windows branch: kill the child if the
- // spawning task is dropped (e.g. app shutdown mid-install) so the
- // tokio runtime can exit cleanly instead of waiting for curl to
- // finish downloading the full Ollama.app bundle.
- cmd.kill_on_drop(true);
- cmd.env("OPENHUMAN_OLLAMA_INSTALL_DIR", install_dir);
- cmd.arg("-lc")
- .arg(
- r#"
- set -eu
- for tool in curl unzip mktemp rm cp chmod mkdir; do
- command -v "$tool" >/dev/null 2>&1 || { echo "missing required tool: $tool" >&2; exit 1; }
- done
- dest="$OPENHUMAN_OLLAMA_INSTALL_DIR"
- tmp_dir="$(mktemp -d)"
- cleanup() { rm -rf "$tmp_dir"; }
- trap cleanup EXIT
- archive="$tmp_dir/Ollama-darwin.zip"
- echo ">>> Downloading Ollama for macOS into $dest" >&2
- curl --fail --show-error --location --progress-bar -o "$archive" "https://ollama.com/download/Ollama-darwin.zip"
- unzip -q "$archive" -d "$tmp_dir"
- rm -rf "$dest"
- mkdir -p "$dest"
- cp -R "$tmp_dir/Ollama.app/Contents/Resources/." "$dest/"
- chmod 755 "$dest/ollama"
- "#,
- );
- return Ok(cmd);
- }
-
- #[cfg(target_os = "linux")]
- {
- let mut cmd = tokio::process::Command::new("sh");
- cmd.kill_on_drop(true); // see Windows-branch comment above
- cmd.env("OPENHUMAN_OLLAMA_INSTALL_DIR", install_dir);
- cmd.arg("-lc")
- .arg(
- r#"
- set -eu
- for tool in curl tar uname rm mkdir; do
- command -v "$tool" >/dev/null 2>&1 || { echo "missing required tool: $tool" >&2; exit 1; }
- done
- arch="$(uname -m)"
- case "$arch" in
- x86_64) arch="amd64" ;;
- aarch64|arm64) arch="arm64" ;;
- *) echo "Unsupported architecture: $arch" >&2; exit 1 ;;
- esac
- dest="$OPENHUMAN_OLLAMA_INSTALL_DIR"
- archive_url="https://ollama.com/download/ollama-linux-${arch}.tar.zst"
- if ! command -v unzstd >/dev/null 2>&1; then
- echo "missing required tool: unzstd (zstd package)" >&2
- exit 1
- fi
- rm -rf "$dest"
- mkdir -p "$dest"
- echo ">>> Downloading Ollama for Linux into $dest" >&2
- curl --fail --show-error --location --progress-bar "$archive_url" | tar --use-compress-program=unzstd -xf - -C "$dest"
- chmod 755 "$dest/bin/ollama"
- "#,
- );
- return Ok(cmd);
- }
-
- #[allow(unreachable_code)]
- Err(format!(
- "Unsupported platform for automatic Ollama install: {}-{}",
- std::env::consts::OS,
- std::env::consts::ARCH
- ))
-}
-
-pub(crate) fn find_system_ollama_binary() -> Option<PathBuf> {
- if let Some(from_env) = std::env::var("OLLAMA_BIN")
- .ok()
- .filter(|v| !v.trim().is_empty())
- {
- let path = PathBuf::from(from_env);
- if path.is_file() {
- return Some(path);
- }
- }
-
- let binary_name = if cfg!(windows) {
- "ollama.exe"
- } else {
- "ollama"
- };
- if let Some(path_var) = std::env::var_os("PATH") {
- for entry in std::env::split_paths(&path_var) {
- let candidate = entry.join(binary_name);
- if candidate.is_file() {
- return Some(candidate);
- }
- }
- }
-
- if cfg!(windows) {
- let mut candidates: Vec<PathBuf> = Vec::new();
- if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {
- candidates.push(
- PathBuf::from(&local_app_data)
- .join("Programs")
- .join("Ollama")
- .join("ollama.exe"),
- );
- candidates.push(
- PathBuf::from(&local_app_data)
- .join("Ollama")
- .join("ollama.exe"),
- );
- }
- if let Ok(program_files) = std::env::var("PROGRAMFILES") {
- candidates.push(
- PathBuf::from(&program_files)
- .join("Ollama")
- .join("ollama.exe"),
- );
- }
- for candidate in candidates {
- if candidate.is_file() {
- log::debug!(
- "[local_ai] found system Ollama at common Windows path: {}",
- candidate.display()
- );
- return Some(candidate);
- }
- }
- }
-
- if cfg!(target_os = "macos") {
- let mut candidates = vec![
- PathBuf::from("/usr/local/bin/ollama"),
- PathBuf::from("/opt/homebrew/bin/ollama"),
- ];
- // Ollama.app installed in /Applications or ~/Applications ships its
- // CLI binary inside the app bundle resources directory.
- let bundle_rel = std::path::Path::new("Applications")
- .join("Ollama.app")
- .join("Contents")
- .join("Resources")
- .join("ollama");
- candidates.push(PathBuf::from("/").join(&bundle_rel));
- if let Some(home) = std::env::var_os("HOME") {
- candidates.push(PathBuf::from(home).join(&bundle_rel));
- }
- for candidate in candidates {
- if candidate.is_file() {
- log::debug!(
- "[local_ai] found system Ollama at macOS path: {}",
- candidate.display()
- );
- return Some(candidate);
- }
- }
- }
-
- if cfg!(target_os = "linux") {
- let common = [
- PathBuf::from("/usr/local/bin/ollama"),
- PathBuf::from("/usr/bin/ollama"),
- ];
- for candidate in common {
- if candidate.is_file() {
- return Some(candidate);
- }
- }
- }
-
- None
-}
-
-#[cfg(test)]
-#[path = "install_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/local/install_piper.rs b/crates/openhuman-core/src/inference/local/install_piper.rs
deleted file mode 100644
index 6e0df70ea7..0000000000
--- a/crates/openhuman-core/src/inference/local/install_piper.rs
+++ /dev/null
@@ -1,619 +0,0 @@
-//! Piper installer — downloads the platform-specific Piper binary
-//! archive and the bundled `en_US-lessac-medium` voice (`.onnx` +
-//! `.onnx.json` sidecar) into the workspace.
-//!
-//! Voice IDs other than the bundled default are intentionally out of
-//! scope; the VoicePanel exposes a free-text `tts_voice_id` input so
-//! advanced users can manually drop in additional `.onnx` files alongside
-//! the bundled one (see Voice TTS factory docs).
-
-use std::io::Read;
-use std::path::PathBuf;
-
-use crate::config::Config;
-
-use super::paths;
-use super::voice_install_common::{
- download_to_file, read_status, write_status, VoiceInstallState, VoiceInstallStatus,
- ENGINE_PIPER,
-};
-
-const LOG_PREFIX: &str = "[voice-install:piper]";
-
-/// Default voice id shipped with the installer. Matches
-/// [`crate::voice::factory::DEFAULT_PIPER_VOICE`].
-pub const DEFAULT_PIPER_VOICE: &str = "en_US-lessac-medium";
-
-/// Minimum bytes for the Piper release archive. The smallest historical
-/// build is ~7 MB; below 1 MB is almost certainly an error response.
-const MIN_BINARY_ARCHIVE_BYTES: u64 = 1024 * 1024;
-
-/// Minimum bytes for the voice `.onnx` model. `en_US-lessac-medium.onnx`
-/// is ~60 MB; allow some slack for CDN compression differences.
-const MIN_VOICE_BYTES: u64 = 30 * 1024 * 1024;
-
-/// Minimum bytes for the `.onnx.json` sidecar. The file is human-readable
-/// JSON, typically a few KB; anything below 256 bytes is almost certainly
-/// a 404 HTML response masquerading as JSON.
-const MIN_VOICE_JSON_BYTES: u64 = 256;
-
-/// Binaries shipped inside the Piper release archive that must carry the
-/// executable bit for the engine to start.
-///
-/// The upstream macOS tarballs ship `espeak-ng` with mode `0644` (#5045).
-/// `tar::Archive::unpack` faithfully reproduces the archived mode, so a
-/// plain extraction leaves the file non-executable and Piper fails when it
-/// shells out to phonemize. Extraction must therefore repair the bit
-/// rather than trust the archive.
-///
-/// Unix-only: Windows has no executable bit, so the const would be dead
-/// code there.
-#[cfg(unix)]
-const PIPER_EXECUTABLES: [&str; 3] = ["piper", "piper_phonemize", "espeak-ng"];
-
-/// Result of resolving the Piper binary archive URL for the host OS.
-struct BinaryAsset {
- url: String,
- /// Archive shape — drives the extraction strategy.
- kind: ArchiveKind,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum ArchiveKind {
- Zip,
- TarGz,
-}
-
-/// Per-OS Piper release asset URL. The Piper project publishes one
-/// archive per OS/architecture under the `latest` release alias. Names
-/// have been stable across recent releases.
-/// Read a Piper base-URL override, treating empty / whitespace-only values as
-/// unset and stripping surrounding whitespace + trailing slashes so the asset
-/// paths concatenated onto it never produce a doubled slash.
-fn piper_base_override(key: &str) -> Option<String> {
- std::env::var(key)
- .ok()
- .map(|v| v.trim().trim_end_matches('/').to_string())
- .filter(|v| !v.is_empty())
-}
-
-fn binary_download_asset() -> Option<BinaryAsset> {
- let base = piper_base_override("OPENHUMAN_PIPER_RELEASE_BASE_URL")
- .unwrap_or_else(|| "https://github.com/rhasspy/piper/releases/latest/download".to_string());
- if cfg!(target_os = "windows") {
- return Some(BinaryAsset {
- url: format!("{base}/piper_windows_amd64.zip"),
- kind: ArchiveKind::Zip,
- });
- }
- if cfg!(target_os = "macos") {
- // Two assets exist (`piper_macos_x64.tar.gz` and
- // `piper_macos_aarch64.tar.gz`). Pick based on the host arch.
- //
- // NOTE (#5045): as of the pinned upstream release `2023.11.14-2`
- // the two macOS assets are byte-identical x86_64 builds — the
- // `aarch64` name is a mislabel — and neither ships the
- // `@rpath` dylibs `piper` links against. Selecting the arm64
- // asset here is still correct, but it cannot make Piper run on
- // Apple Silicon until upstream republishes the bundle. The arch
- // is logged below so a bad asset is diagnosable from user logs.
- let arch = std::env::consts::ARCH;
- let suffix = match arch {
- "aarch64" | "arm64" => "macos_aarch64",
- _ => "macos_x64",
- };
- log::info!("{LOG_PREFIX} host arch={arch} selecting asset=piper_{suffix}.tar.gz");
- return Some(BinaryAsset {
- url: format!("{base}/piper_{suffix}.tar.gz"),
- kind: ArchiveKind::TarGz,
- });
- }
- if cfg!(target_os = "linux") {
- let arch = std::env::consts::ARCH;
- let suffix = match arch {
- "aarch64" | "arm64" => "linux_aarch64",
- "armv7" | "arm" => "linux_armv7",
- _ => "linux_x86_64",
- };
- return Some(BinaryAsset {
- url: format!("{base}/piper_{suffix}.tar.gz"),
- kind: ArchiveKind::TarGz,
- });
- }
- None
-}
-
-/// Voice file URLs on HuggingFace. Returns `(onnx_url, onnx_json_url)`.
-fn voice_download_urls(voice_id: &str) -> (String, String) {
- // The Piper voices repo uses the structure:
- // en/en_US/lessac/medium/en_US-lessac-medium.onnx
- // en/en_US/lessac/medium/en_US-lessac-medium.onnx.json
- // We only support the bundled default — multi-voice support is
- // tracked separately. The path components mirror the voice id.
- let (lang_short, locale, name, quality) = decode_voice_id(voice_id);
- let base = match piper_base_override("OPENHUMAN_PIPER_VOICES_BASE_URL") {
- Some(root) => format!("{root}/{lang_short}/{locale}/{name}/{quality}"),
- None => format!(
- "https://huggingface.co/rhasspy/piper-voices/resolve/main/{lang_short}/{locale}/{name}/{quality}"
- ),
- };
- let stem = format!("{locale}-{name}-{quality}");
- (
- format!("{base}/{stem}.onnx"),
- format!("{base}/{stem}.onnx.json"),
- )
-}
-
-/// Decompose `en_US-lessac-medium` into its repo-path pieces.
-///
-/// Returns `(short_lang, locale, voice_name, quality)`.
-fn decode_voice_id(voice_id: &str) -> (String, String, String, String) {
- // Fall back to the bundled default if the id is malformed — the
- // installer should never panic on user-typed input.
- let trimmed = voice_id.trim();
- let id = if trimmed.is_empty() {
- DEFAULT_PIPER_VOICE
- } else {
- trimmed
- };
- let parts: Vec<&str> = id.split('-').collect();
- if parts.len() < 3 {
- // Reuse the default decomposition on any malformed input so the
- // download URL is still well-formed (the install will fail at
- // size validation if the file doesn't exist upstream).
- return (
- "en".to_string(),
- "en_US".to_string(),
- "lessac".to_string(),
- "medium".to_string(),
- );
- }
- let locale = parts[0].to_string();
- let name = parts[1].to_string();
- let quality = parts[2..].join("-");
- let short_lang = locale.split('_').next().unwrap_or("en").to_string();
- (short_lang, locale, name, quality)
-}
-
-/// Convenience: read the current installer status snapshot, falling back
-/// to "installed" when on-disk artifacts pass validation.
-pub fn status(config: &Config) -> VoiceInstallStatus {
- let mut snapshot = read_status(ENGINE_PIPER);
- let configured_voice = tinyinference::local::models::effective_tts_voice_id(config);
- let configured_voice = configured_voice.trim_end_matches(".onnx").to_string();
- if matches!(snapshot.state, VoiceInstallState::Missing)
- && installed_artifacts_ok(config, &configured_voice)
- {
- snapshot.state = VoiceInstallState::Installed;
- snapshot.stage = Some("binary and voice present".to_string());
- }
- snapshot
-}
-
-fn installed_artifacts_ok(config: &Config, voice_id: &str) -> bool {
- // Check the SPECIFIC requested voice, not the hard-coded default.
- // Without this, switching voice via the dropdown would short-circuit
- // with "already installed" and never fetch the new `.onnx`.
- let voice_ok = paths::workspace_piper_voice_paths(config, voice_id)
- .map(|(onnx, json)| {
- let onnx_ok = std::fs::metadata(&onnx)
- .map(|m| m.is_file() && m.len() >= MIN_VOICE_BYTES)
- .unwrap_or(false);
- let json_ok = std::fs::metadata(&json)
- .map(|m| m.is_file() && m.len() >= MIN_VOICE_JSON_BYTES)
- .unwrap_or(false);
- log::debug!(
- "{LOG_PREFIX} install check onnx={} onnx_ok={} json={} json_ok={}",
- onnx.display(),
- onnx_ok,
- json.display(),
- json_ok
- );
- onnx_ok && json_ok
- })
- .unwrap_or(false);
- let binary_ok = paths::workspace_piper_binary_candidates(config)
- .iter()
- .any(|p| p.is_file());
- log::debug!(
- "{LOG_PREFIX} install check binary_ok={} voice_ok={}",
- binary_ok,
- voice_ok
- );
- binary_ok && voice_ok
-}
-
-/// Kick off (or re-kick) a Piper install. `force_reinstall = true`
-/// removes any existing voice file first; otherwise an already-installed
-/// engine returns immediately with a no-op success.
-pub async fn install_piper(
- config: &Config,
- voice_id: Option<String>,
- force_reinstall: bool,
-) -> Result<VoiceInstallStatus, String> {
- let voice = voice_id
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .unwrap_or(DEFAULT_PIPER_VOICE)
- .to_string();
- log::debug!("{LOG_PREFIX} install requested voice={voice} force_reinstall={force_reinstall}");
-
- if !force_reinstall && installed_artifacts_ok(config, &voice) {
- log::debug!("{LOG_PREFIX} short-circuit: artifacts already present");
- // Repair permissions on the EXISTING install before reporting success.
- // Users hit by #5045 already extracted the affected archive, so they
- // reach this branch on every launch and would never run the repair that
- // only lived on the fresh-install path — they would keep seeing TTS
- // failures until they manually forced a reinstall. `ensure_executable_bits`
- // is a no-op when the bits are already set, so this costs a stat per
- // executable on the happy path.
- ensure_executable_bits(&paths::workspace_piper_dir(config));
- let snapshot = VoiceInstallStatus {
- engine: ENGINE_PIPER.to_string(),
- state: VoiceInstallState::Installed,
- progress: Some(100),
- downloaded_bytes: None,
- total_bytes: None,
- stage: Some("already installed".to_string()),
- error_detail: None,
- };
- write_status(snapshot.clone());
- return Ok(snapshot);
- }
-
- write_status(VoiceInstallStatus {
- engine: ENGINE_PIPER.to_string(),
- state: VoiceInstallState::Installing,
- progress: Some(0),
- downloaded_bytes: Some(0),
- total_bytes: None,
- stage: Some(format!("starting piper install ({voice})")),
- error_detail: None,
- });
-
- let result = run_install(config, &voice).await;
- match &result {
- Ok(()) => {
- let snapshot = VoiceInstallStatus {
- engine: ENGINE_PIPER.to_string(),
- state: VoiceInstallState::Installed,
- progress: Some(100),
- downloaded_bytes: None,
- total_bytes: None,
- stage: Some("install complete".to_string()),
- error_detail: None,
- };
- write_status(snapshot.clone());
- Ok(snapshot)
- }
- Err(msg) => {
- let snapshot = VoiceInstallStatus {
- engine: ENGINE_PIPER.to_string(),
- state: VoiceInstallState::Error,
- progress: None,
- downloaded_bytes: None,
- total_bytes: None,
- stage: None,
- error_detail: Some(msg.clone()),
- };
- write_status(snapshot.clone());
- Err(msg.clone())
- }
- }
-}
-
-async fn run_install(config: &Config, voice: &str) -> Result<(), String> {
- // 1) Voice files: `.onnx` (heavy) + `.onnx.json` (small sidecar).
- let (onnx_url, json_url) = voice_download_urls(voice);
- let (onnx_path, json_path) = paths::workspace_piper_voice_paths(config, voice)
- .ok_or_else(|| format!("{LOG_PREFIX} could not resolve voice paths for '{voice}'"))?;
-
- log::debug!("{LOG_PREFIX} downloading voice url={onnx_url}");
- update_stage(format!("downloading {voice}.onnx"));
- download_to_file(
- &onnx_url,
- &onnx_path,
- None,
- MIN_VOICE_BYTES,
- LOG_PREFIX,
- |downloaded, total| {
- let progress = total
- .filter(|t| *t > 0)
- .map(|t| ((downloaded * 100) / t).min(100) as u8);
- write_status(VoiceInstallStatus {
- engine: ENGINE_PIPER.to_string(),
- state: VoiceInstallState::Installing,
- progress,
- downloaded_bytes: Some(downloaded),
- total_bytes: total,
- stage: Some("downloading voice (.onnx)".to_string()),
- error_detail: None,
- });
- },
- )
- .await?;
- log::debug!("{LOG_PREFIX} voice .onnx staged at {}", onnx_path.display());
-
- log::debug!("{LOG_PREFIX} downloading voice json url={json_url}");
- update_stage(format!("downloading {voice}.onnx.json"));
- download_to_file(
- &json_url,
- &json_path,
- None,
- MIN_VOICE_JSON_BYTES,
- LOG_PREFIX,
- |downloaded, total| {
- let progress = total
- .filter(|t| *t > 0)
- .map(|t| ((downloaded * 100) / t).min(100) as u8);
- write_status(VoiceInstallStatus {
- engine: ENGINE_PIPER.to_string(),
- state: VoiceInstallState::Installing,
- progress,
- downloaded_bytes: Some(downloaded),
- total_bytes: total,
- stage: Some("downloading voice (.onnx.json)".to_string()),
- error_detail: None,
- });
- },
- )
- .await?;
-
- // 2) Binary archive.
- let asset = binary_download_asset()
- .ok_or_else(|| format!("{LOG_PREFIX} no piper binary release for this OS/arch"))?;
- let archive_name = asset
- .url
- .rsplit('/')
- .next()
- .unwrap_or("piper_archive")
- .to_string();
- let archive_path = paths::workspace_piper_dir(config).join(&archive_name);
- log::debug!("{LOG_PREFIX} downloading binary url={}", asset.url);
- update_stage("downloading piper binary".to_string());
- download_to_file(
- &asset.url,
- &archive_path,
- None,
- MIN_BINARY_ARCHIVE_BYTES,
- LOG_PREFIX,
- |downloaded, total| {
- let progress = total
- .filter(|t| *t > 0)
- .map(|t| ((downloaded * 100) / t).min(100) as u8);
- write_status(VoiceInstallStatus {
- engine: ENGINE_PIPER.to_string(),
- state: VoiceInstallState::Installing,
- progress,
- downloaded_bytes: Some(downloaded),
- total_bytes: total,
- stage: Some("downloading binary".to_string()),
- error_detail: None,
- });
- },
- )
- .await?;
- update_stage("extracting piper binary".to_string());
- let dest = paths::workspace_piper_dir(config);
- match asset.kind {
- ArchiveKind::Zip => extract_zip(&archive_path, &dest)?,
- ArchiveKind::TarGz => extract_tar_gz(&archive_path, &dest)?,
- }
- ensure_executable_bits(&dest);
- if let Err(e) = std::fs::remove_file(&archive_path) {
- log::warn!(
- "{LOG_PREFIX} could not remove archive {}: {e}",
- archive_path.display()
- );
- }
-
- Ok(())
-}
-
-/// Directories under the install root where an extracted Piper binary can
-/// land. Mirrors the layouts probed by
-/// [`paths::workspace_piper_binary_candidates`]: the macOS/Linux tarballs
-/// nest under `piper/`, some builds flatten to the root, and a few use
-/// `bin/`. Bounded on purpose — a recursive walk would descend into
-/// `espeak-ng-data/` and `voices/` (which holds a ~60 MB `.onnx`) for no
-/// benefit.
-#[cfg(unix)]
-fn executable_search_dirs(dest_dir: &std::path::Path) -> [PathBuf; 3] {
- [
- dest_dir.to_path_buf(),
- dest_dir.join("piper"),
- dest_dir.join("bin"),
- ]
-}
-
-/// Repair the executable bit on the binaries extracted from the Piper
-/// archive.
-///
-/// Upstream ships `espeak-ng` as mode `0644` inside both macOS tarballs
-/// (#5045) and `tar::Archive::unpack` reproduces the archived mode
-/// verbatim, so the extracted tree is left with a non-executable
-/// `espeak-ng`. Rather than trust archive metadata, set `0o755` on every
-/// binary we know Piper needs.
-///
-/// Best-effort by design: a `chmod` failure is logged but does not fail
-/// the install, since the caller may still have a working engine on
-/// `PATH` (`PIPER_BIN`) and a hard error here would regress that path.
-#[cfg(unix)]
-fn ensure_executable_bits(dest_dir: &std::path::Path) {
- use std::os::unix::fs::PermissionsExt;
-
- for dir in executable_search_dirs(dest_dir) {
- for name in PIPER_EXECUTABLES {
- let path = dir.join(name);
- let Ok(meta) = std::fs::metadata(&path) else {
- continue;
- };
- if !meta.is_file() {
- continue;
- }
- let mode = meta.permissions().mode();
- // Any of user/group/other execute already set → leave it be.
- if mode & 0o111 != 0 {
- log::debug!(
- "{LOG_PREFIX} {} already executable (mode {:o})",
- path.display(),
- mode & 0o777
- );
- continue;
- }
- match std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)) {
- Ok(()) => log::info!(
- "{LOG_PREFIX} repaired execute bit on {} (was mode {:o})",
- path.display(),
- mode & 0o777
- ),
- Err(e) => log::warn!("{LOG_PREFIX} could not chmod +x {}: {e}", path.display()),
- }
- }
- }
-}
-
-/// Windows has no executable bit — extraction is sufficient there.
-#[cfg(not(unix))]
-fn ensure_executable_bits(_dest_dir: &std::path::Path) {}
-
-fn update_stage(stage: String) {
- let mut current = read_status(ENGINE_PIPER);
- current.stage = Some(stage);
- write_status(current);
-}
-
-fn extract_zip(zip_path: &std::path::Path, dest_dir: &std::path::Path) -> Result<(), String> {
- log::debug!(
- "{LOG_PREFIX} extract_zip {} -> {}",
- zip_path.display(),
- dest_dir.display()
- );
- let file = std::fs::File::open(zip_path).map_err(|e| format!("{LOG_PREFIX} open zip: {e}"))?;
- let mut archive =
- zip::ZipArchive::new(file).map_err(|e| format!("{LOG_PREFIX} parse zip: {e}"))?;
- std::fs::create_dir_all(dest_dir).map_err(|e| format!("{LOG_PREFIX} mkdir dest: {e}"))?;
- for i in 0..archive.len() {
- let mut entry = archive
- .by_index(i)
- .map_err(|e| format!("{LOG_PREFIX} zip entry {i}: {e}"))?;
- let Some(rel) = entry.enclosed_name() else {
- continue;
- };
- let rel = rel.to_path_buf();
- let out_path = dest_dir.join(&rel);
- if entry.is_dir() {
- std::fs::create_dir_all(&out_path)
- .map_err(|e| format!("{LOG_PREFIX} mkdir {}: {e}", out_path.display()))?;
- } else {
- if let Some(parent) = out_path.parent() {
- std::fs::create_dir_all(parent)
- .map_err(|e| format!("{LOG_PREFIX} mkdir {}: {e}", parent.display()))?;
- }
- let mut out = std::fs::File::create(&out_path)
- .map_err(|e| format!("{LOG_PREFIX} create {}: {e}", out_path.display()))?;
- std::io::copy(&mut entry, &mut out)
- .map_err(|e| format!("{LOG_PREFIX} copy {}: {e}", out_path.display()))?;
- }
- }
- Ok(())
-}
-
-fn extract_tar_gz(archive: &std::path::Path, dest_dir: &std::path::Path) -> Result<(), String> {
- log::debug!(
- "{LOG_PREFIX} extract_tar_gz {} -> {}",
- archive.display(),
- dest_dir.display()
- );
- std::fs::create_dir_all(dest_dir).map_err(|e| format!("{LOG_PREFIX} mkdir dest: {e}"))?;
- let file =
- std::fs::File::open(archive).map_err(|e| format!("{LOG_PREFIX} open tar.gz: {e}"))?;
- // The Piper tarball is gzipped. The `flate2` crate is already a
- // transitive dep through `tar`; if it's not directly available we
- // would need to add it here. As of this writing the workspace uses
- // gzip-aware tar via the `flate2` dep that ships with `zip`'s
- // companion utilities — but the standard pattern in this codebase
- // is to shell out to `tar` so we don't grow the dep tree.
- //
- // To keep the installer self-contained without adding a new
- // workspace dep, decompress in-memory then hand the plain tar to
- // the `tar` crate. The Piper archive is only ~7 MB so a single
- // in-memory inflate is acceptable.
- let mut gz = std::io::BufReader::new(file);
- let mut compressed = Vec::new();
- gz.read_to_end(&mut compressed)
- .map_err(|e| format!("{LOG_PREFIX} read tar.gz: {e}"))?;
- let decompressed =
- inflate_gzip(&compressed).map_err(|e| format!("{LOG_PREFIX} inflate tar.gz: {e}"))?;
- let mut tar = tar::Archive::new(std::io::Cursor::new(decompressed));
- tar.unpack(dest_dir)
- .map_err(|e| format!("{LOG_PREFIX} unpack tar: {e}"))?;
- Ok(())
-}
-
-/// Inflate a gzip stream using the `flate2` crate that ships with `zip`'s
-/// deflate feature. We re-export through the `zip` crate's surface to
-/// avoid a direct flate2 dep declaration.
-fn inflate_gzip(compressed: &[u8]) -> Result<Vec<u8>, String> {
- // `flate2` is pulled in transitively by `zip` with the `deflate`
- // feature. Use its public reader API directly.
- use flate2::read::GzDecoder;
- let mut decoder = GzDecoder::new(compressed);
- let mut out = Vec::new();
- decoder
- .read_to_end(&mut out)
- .map_err(|e| format!("gz decode: {e}"))?;
- Ok(out)
-}
-
-/// Return the workspace-installed Piper binary path if one exists. Used
-/// by `paths::resolve_piper_binary` to prefer the workspace install over
-/// `PIPER_BIN` / PATH.
-pub(crate) fn find_workspace_piper_binary(config: &Config) -> Option<PathBuf> {
- let candidates = paths::workspace_piper_binary_candidates(config);
- for candidate in candidates {
- if !candidate.is_file() {
- continue;
- }
- // A file we cannot execute is not a usable candidate. Returning it
- // anyway would pin resolution to the broken workspace copy and make the
- // `PIPER_BIN` / PATH fallback unreachable, which is exactly what
- // happens when the `chmod` repair fails (denied, or a filesystem with
- // no execute bit). Skipping lets resolution continue to a working
- // engine instead of failing at launch.
- if !is_executable_file(&candidate) {
- log::warn!(
- "{LOG_PREFIX} skipping non-executable workspace piper binary {} — falling back to PIPER_BIN/PATH",
- candidate.display()
- );
- continue;
- }
- log::debug!(
- "{LOG_PREFIX} found workspace piper binary at {}",
- candidate.display()
- );
- return Some(candidate);
- }
- None
-}
-
-/// Whether `path` carries an execute bit for anybody.
-///
-/// Windows has no execute bit, so every regular file qualifies there.
-#[cfg(unix)]
-fn is_executable_file(path: &std::path::Path) -> bool {
- use std::os::unix::fs::PermissionsExt;
- std::fs::metadata(path)
- .map(|m| m.permissions().mode() & 0o111 != 0)
- .unwrap_or(false)
-}
-
-#[cfg(not(unix))]
-fn is_executable_file(_path: &std::path::Path) -> bool {
- true
-}
-
-#[cfg(test)]
-#[path = "install_piper_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/local/install_piper_tests.rs b/crates/openhuman-core/src/inference/local/install_piper_tests.rs
deleted file mode 100644
index 949caee6e7..0000000000
--- a/crates/openhuman-core/src/inference/local/install_piper_tests.rs
+++ /dev/null
@@ -1,377 +0,0 @@
-use super::*;
-use crate::inference::local::voice_install_common::reset_status;
-
-/// Point [`paths::shared_root_dir`] at a test's own `TempDir`.
-///
-/// `shared_root_dir` only honours `config.workspace_dir` when
-/// `OPENHUMAN_WORKSPACE` is set; without it every write below lands in the
-/// developer's real `~/.openhuman/bin/piper` and the cleanup deletes their
-/// installed Piper (CodeRabbit, #5253). Setting the variable for the
-/// duration keeps writes *and* cleanup inside the `TempDir`, so the
-/// `TempDir`'s own `Drop` is the cleanup and it runs on unwind too: a
-/// failing assertion can no longer leave a stub binary behind for the next
-/// test to trip over.
-///
-/// Callers must already hold [`shared_install_lock`] — this mutates
-/// process-wide environment state.
-///
-/// `#[cfg(unix)]` because its only consumer is the unix-only permissions
-/// test; unconditional would be dead code on Windows, where clippy runs
-/// with `-D warnings`.
-#[cfg(unix)]
-struct SharedRootOverride {
- previous: Option<std::ffi::OsString>,
-}
-
-#[cfg(unix)]
-impl SharedRootOverride {
- fn set(root: &std::path::Path) -> Self {
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- std::env::set_var("OPENHUMAN_WORKSPACE", root);
- Self { previous }
- }
-}
-
-#[cfg(unix)]
-impl Drop for SharedRootOverride {
- fn drop(&mut self) {
- match self.previous.as_ref() {
- Some(previous) => std::env::set_var("OPENHUMAN_WORKSPACE", previous),
- None => std::env::remove_var("OPENHUMAN_WORKSPACE"),
- }
- }
-}
-
-#[cfg(unix)]
-#[test]
-fn non_executable_workspace_binary_is_skipped_so_path_can_win() {
- // #5045 review (Codex P2): when the chmod repair fails, returning the
- // 0644 workspace copy anyway pins resolution to a binary that cannot
- // launch and makes the PIPER_BIN/PATH fallback unreachable.
- //
- // This test must hold the module lock: it mutates OPENHUMAN_WORKSPACE,
- // which is process-wide, and `reset_status`/install state is shared
- // with every sibling install_piper / paths test.
- //
- // `workspace_piper_binary_candidates` resolves through
- // `paths::shared_root_dir`, which ignores `config.workspace_dir` unless
- // OPENHUMAN_WORKSPACE is set and otherwise returns the real
- // `~/.openhuman/bin/piper`. `SharedRootOverride` sets it to this test's
- // TempDir so the stub written below, and its cleanup, stay inside the
- // TempDir instead of touching a developer's installed Piper.
- use std::os::unix::fs::PermissionsExt;
- let _g = shared_install_lock();
- let (_dir, config) = temp_config();
- let _root = SharedRootOverride::set(&config.workspace_dir);
- wipe_shared_install_dir(&config);
- let candidates = paths::workspace_piper_binary_candidates(&config);
- let candidate = candidates.first().expect("at least one candidate").clone();
- std::fs::create_dir_all(candidate.parent().unwrap()).unwrap();
- std::fs::write(&candidate, b"#!/bin/sh\n").unwrap();
-
- std::fs::set_permissions(&candidate, std::fs::Permissions::from_mode(0o644)).unwrap();
- assert!(
- find_workspace_piper_binary(&config).is_none(),
- "a non-executable workspace binary must not be resolved"
- );
-
- std::fs::set_permissions(&candidate, std::fs::Permissions::from_mode(0o755)).unwrap();
- assert_eq!(
- find_workspace_piper_binary(&config).as_deref(),
- Some(candidate.as_path()),
- "an executable workspace binary is still preferred"
- );
-
- // No tail cleanup: it would only run when every assertion above passed.
- // `_dir` (TempDir) and `_root` (SharedRootOverride) clean up on drop,
- // which happens on the panic path too.
-}
-
-fn temp_config() -> (tempfile::TempDir, Config) {
- let dir = tempfile::tempdir().expect("tempdir");
- let config = Config {
- workspace_dir: dir.path().join("workspace"),
- config_path: dir.path().join("config.toml"),
- ..Config::default()
- };
- (dir, config)
-}
-
-#[test]
-fn decode_voice_id_splits_correctly() {
- assert_eq!(
- decode_voice_id("en_US-lessac-medium"),
- (
- "en".to_string(),
- "en_US".to_string(),
- "lessac".to_string(),
- "medium".to_string()
- )
- );
- assert_eq!(
- decode_voice_id("de_DE-thorsten-high"),
- (
- "de".to_string(),
- "de_DE".to_string(),
- "thorsten".to_string(),
- "high".to_string()
- )
- );
-}
-
-#[test]
-fn decode_voice_id_falls_back_for_garbage() {
- // Single-piece input is malformed → bundled default decomposition.
- let (lang, locale, name, quality) = decode_voice_id("garbage");
- assert_eq!(lang, "en");
- assert_eq!(locale, "en_US");
- assert_eq!(name, "lessac");
- assert_eq!(quality, "medium");
-
- let (_lang, _locale, _name, _quality) = decode_voice_id("");
- // Empty string also produces the bundled default — guarded above.
-}
-
-#[test]
-fn voice_download_urls_anchor_on_hf_bucket() {
- let (onnx, json) = voice_download_urls("en_US-lessac-medium");
- assert!(onnx.starts_with("https://huggingface.co/rhasspy/piper-voices/resolve/main/"));
- assert!(onnx.ends_with("en_US-lessac-medium.onnx"));
- assert!(json.ends_with("en_US-lessac-medium.onnx.json"));
-}
-
-#[test]
-fn binary_download_asset_picks_an_os_specific_url() {
- let asset = binary_download_asset();
- // On supported platforms we expect an asset; the test only runs
- // on the host so this is informative.
- if cfg!(any(
- target_os = "windows",
- target_os = "macos",
- target_os = "linux"
- )) {
- let asset = asset.expect("supported platform should return an asset");
- assert!(asset.url.contains("piper"));
- assert!(asset
- .url
- .starts_with("https://github.com/rhasspy/piper/releases"));
- if cfg!(windows) {
- assert_eq!(asset.kind, ArchiveKind::Zip);
- } else {
- assert_eq!(asset.kind, ArchiveKind::TarGz);
- }
- } else {
- assert!(asset.is_none());
- }
-}
-
-/// Serialise tests that write into the shared `~/.openhuman/bin/piper/`
-/// directory; reuses the module-wide `local_ai_test_guard` so paths +
-/// sibling installer tests are serialised through the same lock.
-fn shared_install_lock() -> std::sync::MutexGuard<'static, ()> {
- crate::inference::inference_test_guard()
-}
-
-fn wipe_shared_install_dir(config: &Config) {
- let dir = paths::workspace_piper_dir(config);
- let _ = std::fs::remove_dir_all(&dir);
-}
-
-#[test]
-fn status_reports_missing_for_fresh_workspace() {
- let _g = shared_install_lock();
- reset_status(ENGINE_PIPER);
- let (_tmp, config) = temp_config();
- wipe_shared_install_dir(&config);
- let snapshot = status(&config);
- assert_eq!(snapshot.state, VoiceInstallState::Missing);
-}
-
-/// Build a `.onnx.json` payload big enough to pass the size floor.
-/// Real Piper sidecars are a few KB; the floor exists to reject 404
-/// HTML pages, so as long as we write past 256 bytes we mirror the
-/// production validator's accept set.
-fn synthetic_voice_json() -> Vec<u8> {
- let mut body = br#"{"audio":{"sample_rate":22050},"phoneme_id_map":{},"#.to_vec();
- // Pad to comfortably exceed the size floor without altering shape.
- body.extend_from_slice(br#""filler":""#);
- body.extend(std::iter::repeat_n(b'x', 512));
- body.extend_from_slice(br#""}"#);
- body
-}
-
-#[test]
-fn status_promotes_to_installed_when_voice_and_binary_present() {
- let _g = shared_install_lock();
- reset_status(ENGINE_PIPER);
- let (_tmp, config) = temp_config();
- wipe_shared_install_dir(&config);
- // Voice files.
- let (onnx, json) =
- paths::workspace_piper_voice_paths(&config, DEFAULT_PIPER_VOICE).expect("voice paths");
- std::fs::create_dir_all(onnx.parent().unwrap()).unwrap();
- std::fs::write(&onnx, vec![0u8; (MIN_VOICE_BYTES + 1024) as usize]).unwrap();
- std::fs::write(&json, synthetic_voice_json()).unwrap();
- // Binary.
- let bin_candidate = paths::workspace_piper_binary_candidates(&config)[0].clone();
- std::fs::create_dir_all(bin_candidate.parent().unwrap()).unwrap();
- std::fs::write(&bin_candidate, b"stub").unwrap();
-
- let snapshot = status(&config);
- assert_eq!(snapshot.state, VoiceInstallState::Installed);
- wipe_shared_install_dir(&config);
-}
-
-// Holding the sync mutex over
-// the install await is safe because the install path doesn't acquire
-// any other locks, and the guard's job is to keep filesystem writes
-// from racing with sibling tests.
-#[allow(clippy::await_holding_lock)]
-#[tokio::test]
-async fn install_short_circuits_when_already_installed() {
- let _g = shared_install_lock();
- reset_status(ENGINE_PIPER);
- let (_tmp, config) = temp_config();
- wipe_shared_install_dir(&config);
- let (onnx, json) =
- paths::workspace_piper_voice_paths(&config, DEFAULT_PIPER_VOICE).expect("voice paths");
- std::fs::create_dir_all(onnx.parent().unwrap()).unwrap();
- std::fs::write(&onnx, vec![0u8; (MIN_VOICE_BYTES + 1024) as usize]).unwrap();
- std::fs::write(&json, synthetic_voice_json()).unwrap();
- let bin_candidate = paths::workspace_piper_binary_candidates(&config)[0].clone();
- std::fs::create_dir_all(bin_candidate.parent().unwrap()).unwrap();
- std::fs::write(&bin_candidate, b"stub").unwrap();
-
- let result = install_piper(&config, None, false).await;
- assert!(result.is_ok(), "short-circuit must succeed: {result:?}");
- let snap = result.unwrap();
- assert_eq!(snap.state, VoiceInstallState::Installed);
- wipe_shared_install_dir(&config);
-}
-
-#[test]
-fn find_workspace_piper_binary_returns_path_when_present() {
- let _g = shared_install_lock();
- let (_tmp, config) = temp_config();
- wipe_shared_install_dir(&config);
- let target = paths::workspace_piper_binary_candidates(&config)[0].clone();
- std::fs::create_dir_all(target.parent().unwrap()).unwrap();
- std::fs::write(&target, b"stub").unwrap();
- // "Present" now means present AND executable: a 0644 file is not a
- // usable binary, and resolving it would pin us to a copy that cannot
- // launch (see `non_executable_workspace_binary_is_skipped_so_path_can_win`).
- // `std::fs::write` creates 0644, so grant the bit explicitly.
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755)).unwrap();
- }
- let found = find_workspace_piper_binary(&config).expect("should find binary");
- assert_eq!(found, target);
- wipe_shared_install_dir(&config);
-}
-
-#[test]
-fn find_workspace_piper_binary_returns_none_without_install() {
- let _g = shared_install_lock();
- let (_tmp, config) = temp_config();
- wipe_shared_install_dir(&config);
- assert!(find_workspace_piper_binary(&config).is_none());
-}
-
-/// Regression tests for #5045: the upstream macOS tarballs ship
-/// `espeak-ng` as mode 0644 and `tar::Archive::unpack` reproduces the
-/// archived mode verbatim, leaving Piper unable to phonemize.
-#[cfg(unix)]
-mod executable_bits {
- use super::*;
- use std::os::unix::fs::PermissionsExt;
-
- fn mode_of(path: &std::path::Path) -> u32 {
- std::fs::metadata(path)
- .expect("metadata")
- .permissions()
- .mode()
- & 0o777
- }
-
- fn write_with_mode(path: &std::path::Path, mode: u32) {
- std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
- std::fs::write(path, b"stub").expect("write");
- std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).expect("chmod");
- }
-
- /// The headline bug: a 0644 `espeak-ng` in the nested `piper/`
- /// layout the macOS tarball actually produces.
- #[test]
- fn repairs_non_executable_espeak_ng_in_nested_layout() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let espeak = tmp.path().join("piper").join("espeak-ng");
- write_with_mode(&espeak, 0o644);
- assert_eq!(mode_of(&espeak), 0o644, "precondition: not executable");
-
- ensure_executable_bits(tmp.path());
-
- assert_eq!(
- mode_of(&espeak),
- 0o755,
- "espeak-ng must be executable after extraction"
- );
- }
-
- /// Some builds flatten the archive to the install root rather than
- /// nesting under `piper/`; both layouts must be repaired.
- #[test]
- fn repairs_binaries_in_flat_layout() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let espeak = tmp.path().join("espeak-ng");
- write_with_mode(&espeak, 0o644);
-
- ensure_executable_bits(tmp.path());
-
- assert_eq!(mode_of(&espeak), 0o755);
- }
-
- /// `piper` and `piper_phonemize` already ship 0755 upstream — the
- /// repair must not widen or otherwise rewrite a good mode.
- #[test]
- fn leaves_already_executable_binaries_untouched() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let piper = tmp.path().join("piper").join("piper");
- // Deliberately narrower than 0755 to prove we don't rewrite.
- write_with_mode(&piper, 0o700);
-
- ensure_executable_bits(tmp.path());
-
- assert_eq!(
- mode_of(&piper),
- 0o700,
- "an already-executable binary must keep its mode"
- );
- }
-
- /// Data files shipped alongside the binaries (`libtashkeel_model.ort`,
- /// the `.onnx` voices) must not become executable.
- #[test]
- fn does_not_touch_non_binary_payloads() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let data = tmp.path().join("piper").join("libtashkeel_model.ort");
- write_with_mode(&data, 0o644);
-
- ensure_executable_bits(tmp.path());
-
- assert_eq!(
- mode_of(&data),
- 0o644,
- "data payloads must not gain the execute bit"
- );
- }
-
- /// A missing install directory is the common case on a fresh
- /// workspace — the repair must be a silent no-op, not a panic.
- #[test]
- fn is_a_no_op_when_nothing_was_extracted() {
- let tmp = tempfile::tempdir().expect("tempdir");
- ensure_executable_bits(&tmp.path().join("does-not-exist"));
- }
-}
diff --git a/crates/openhuman-core/src/inference/local/install_tests.rs b/crates/openhuman-core/src/inference/local/install_tests.rs
deleted file mode 100644
index 59ebdf08c8..0000000000
--- a/crates/openhuman-core/src/inference/local/install_tests.rs
+++ /dev/null
@@ -1,204 +0,0 @@
-use super::*;
-use std::ffi::OsString;
-
-/// Serialises tests that mutate process-global environment variables
-/// (OLLAMA_BIN, PATH) with other local-AI tests that also read these
-/// variables. Without this, cargo's test runner can interleave set/remove
-/// calls and cause flakes.
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- crate::inference::inference_test_guard()
-}
-
-/// RAII guard: records the prior value of `var` on construction and
-/// restores it on drop (or removes the var if it was previously unset).
-struct EnvGuard {
- var: &'static str,
- prior: Option<OsString>,
-}
-
-impl EnvGuard {
- fn set(var: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {
- let prior = std::env::var_os(var);
- unsafe { std::env::set_var(var, value) };
- Self { var, prior }
- }
-
- fn unset(var: &'static str) -> Self {
- let prior = std::env::var_os(var);
- unsafe { std::env::remove_var(var) };
- Self { var, prior }
- }
-}
-
-impl Drop for EnvGuard {
- fn drop(&mut self) {
- unsafe {
- match self.prior.take() {
- Some(v) => std::env::set_var(self.var, v),
- None => std::env::remove_var(self.var),
- }
- }
- }
-}
-
-#[test]
-fn build_install_command_on_supported_platform_returns_ok() {
- let tmp = tempfile::tempdir().unwrap();
- let result = build_install_command(tmp.path());
- if cfg!(any(
- target_os = "linux",
- target_os = "macos",
- target_os = "windows"
- )) {
- assert!(
- result.is_ok(),
- "build_install_command must return Ok on supported platforms, got {result:?}"
- );
- } else {
- assert!(
- result.is_err(),
- "build_install_command must return Err on unsupported platforms"
- );
- }
-}
-
-#[test]
-fn find_system_ollama_binary_respects_env_override_when_file_exists() {
- let _lock = env_lock();
- let tmp = tempfile::tempdir().unwrap();
- let fake = tmp.path().join("ollama-stub");
- std::fs::write(&fake, "").unwrap();
- let _g = EnvGuard::set("OLLAMA_BIN", &fake);
- let found = find_system_ollama_binary();
- assert_eq!(found.as_deref(), Some(fake.as_path()));
-}
-
-#[test]
-fn find_system_ollama_binary_ignores_env_override_when_file_missing() {
- let _lock = env_lock();
- let _g = EnvGuard::set("OLLAMA_BIN", "/nonexistent/ollama-stub-missing");
- // Result depends on whether /usr/bin/ollama etc. exist on this
- // machine. The important thing is the env-override didn't succeed.
- let found = find_system_ollama_binary();
- if let Some(p) = found {
- assert!(!p.to_string_lossy().contains("ollama-stub-missing"));
- }
-}
-
-#[test]
-fn find_system_ollama_binary_ignores_empty_env_override() {
- let _lock = env_lock();
- {
- let _g = EnvGuard::set("OLLAMA_BIN", "");
- let _ = find_system_ollama_binary();
- }
- {
- let _g = EnvGuard::set("OLLAMA_BIN", " ");
- let _ = find_system_ollama_binary();
- }
-}
-
-#[test]
-fn find_system_ollama_binary_finds_binary_via_path() {
- let _lock = env_lock();
- let tmp = tempfile::tempdir().unwrap();
- let binary_name = if cfg!(windows) {
- "ollama.exe"
- } else {
- "ollama"
- };
- let fake = tmp.path().join(binary_name);
- std::fs::write(&fake, "").unwrap();
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
- }
- let prev_path = std::env::var_os("PATH").unwrap_or_default();
- let mut new_entries = vec![tmp.path().to_path_buf()];
- new_entries.extend(std::env::split_paths(&prev_path));
- let new_path = std::env::join_paths(new_entries).unwrap();
- let _ollama_guard = EnvGuard::unset("OLLAMA_BIN");
- let _path_guard = EnvGuard::set("PATH", &new_path);
- let found = find_system_ollama_binary();
- assert!(
- found.is_some(),
- "PATH-based lookup should succeed with a valid stub"
- );
-}
-
-#[cfg(target_os = "macos")]
-#[test]
-fn find_system_ollama_binary_detects_macos_app_bundle_in_applications() {
- let _lock = env_lock();
- // `find_system_ollama_binary` probes a fixed priority list on macOS:
- // 1. /usr/local/bin/ollama (intel homebrew, hand-installed)
- // 2. /opt/homebrew/bin/ollama (apple-silicon homebrew)
- // 3. /Applications/Ollama.app/Contents/Resources/ollama
- // 4. $HOME/Applications/Ollama.app/Contents/Resources/ollama
- // The test exercises (4) by pointing $HOME at a tempdir and clearing
- // PATH/OLLAMA_BIN. Paths (1)–(3) are absolute and cannot be redirected
- // — if a dev machine already has Ollama installed at either homebrew
- // location or in the system /Applications dir, the function returns
- // that real binary first and the assertion below fails. Skip when any
- // earlier candidate already resolves so this test stays a regression
- // gate on the ~/Applications branch and not a "is Ollama installed on
- // this CI runner" probe.
- let unmaskable_real_install = [
- "/usr/local/bin/ollama",
- "/opt/homebrew/bin/ollama",
- "/Applications/Ollama.app/Contents/Resources/ollama",
- ]
- .iter()
- .any(|p| std::path::Path::new(p).is_file());
- if unmaskable_real_install {
- eprintln!(
- "skipping: host has a real Ollama install at a higher-priority absolute path \
- the test cannot mock"
- );
- return;
- }
- let tmp = tempfile::tempdir().unwrap();
- // Build a fake /Applications/Ollama.app/Contents/Resources/ollama tree.
- let bundle_bin = tmp
- .path()
- .join("Applications")
- .join("Ollama.app")
- .join("Contents")
- .join("Resources")
- .join("ollama");
- std::fs::create_dir_all(bundle_bin.parent().unwrap()).unwrap();
- std::fs::write(&bundle_bin, b"stub").unwrap();
-
- // Clear OLLAMA_BIN, clear PATH so the normal PATH lookup won't find it,
- // and point HOME to tmp so the ~/Applications branch is exercised via a
- // separate sub-test below. Here we exercise /Applications by building
- // the file at root and verifying the function returns it when the static
- // /Applications path exists — we skip direct-path injection since the
- // function hard-codes "/" as root and we cannot mock the filesystem.
- // Instead verify the ~/Applications path via the HOME trick.
- let _home_guard = EnvGuard::set("HOME", tmp.path());
- let _bin_guard = EnvGuard::unset("OLLAMA_BIN");
- let prev_path = std::env::var_os("PATH").unwrap_or_default();
- let _path_guard = EnvGuard::set("PATH", "");
-
- // ~/Applications bundle path is under HOME.
- let home_bundle = tmp
- .path()
- .join("Applications")
- .join("Ollama.app")
- .join("Contents")
- .join("Resources")
- .join("ollama");
- std::fs::create_dir_all(home_bundle.parent().unwrap()).unwrap();
- std::fs::write(&home_bundle, b"stub").unwrap();
-
- let found = find_system_ollama_binary();
- assert_eq!(
- found.as_deref(),
- Some(home_bundle.as_path()),
- "should find Ollama in ~/Applications bundle"
- );
- drop(_path_guard);
- let _ = prev_path;
-}
diff --git a/crates/openhuman-core/src/inference/local/mod.rs b/crates/openhuman-core/src/inference/local/mod.rs
index 0343df28c1..20f52db5c9 100644
--- a/crates/openhuman-core/src/inference/local/mod.rs
+++ b/crates/openhuman-core/src/inference/local/mod.rs
@@ -21,16 +21,12 @@ mod schemas;
// Re-expose host integration modules used across the local runtime.
pub use super::paths;
-pub use super::presets;
pub use super::types;
-pub mod install;
-pub(crate) mod install_piper;
// `pub(crate)` so the shared `apply_no_window` helper can be reused from the
// agent shell runtime (`agent::host_runtime`) — single source of truth for the
// Windows `CREATE_NO_WINDOW` flag (#3727/#3728).
pub mod service;
-pub(crate) mod voice_install_common;
pub use core::*;
pub use ops as rpc;
diff --git a/crates/openhuman-core/src/inference/local/schemas.rs b/crates/openhuman-core/src/inference/local/schemas.rs
index d9b2e68e1a..ae3d82fa21 100644
--- a/crates/openhuman-core/src/inference/local/schemas.rs
+++ b/crates/openhuman-core/src/inference/local/schemas.rs
@@ -406,26 +406,26 @@ fn handle_local_ai_install_piper(params: Map<String, Value>) -> ControllerFuture
// already in flight must be a no-op, not a second concurrent download
// racing on the same `.part` file. `try_acquire_install_slot` does the
// check-and-claim under a single mutex acquisition.
- let slot = match crate::inference::local::voice_install_common::try_acquire_install_slot(
- crate::inference::local::voice_install_common::ENGINE_PIPER,
+ let slot = match tinyinference::local::download::try_acquire_install_slot(
+ tinyinference::local::download::ENGINE_PIPER,
) {
Some(slot) => slot,
None => {
tracing::debug!(
"[voice-install:piper] slot already held — returning current status"
);
- let current = crate::inference::local::voice_install_common::read_status(
- crate::inference::local::voice_install_common::ENGINE_PIPER,
+ let current = tinyinference::local::download::read_status(
+ tinyinference::local::download::ENGINE_PIPER,
);
return serde_json::to_value(current)
.map_err(|e| format!("serialize piper status: {e}"));
}
};
- crate::inference::local::voice_install_common::write_status(
- crate::inference::local::voice_install_common::VoiceInstallStatus {
- engine: crate::inference::local::voice_install_common::ENGINE_PIPER.to_string(),
- state: crate::inference::local::voice_install_common::VoiceInstallState::Installing,
+ tinyinference::local::download::write_status(
+ tinyinference::local::download::VoiceInstallStatus {
+ engine: tinyinference::local::download::ENGINE_PIPER.to_string(),
+ state: tinyinference::local::download::VoiceInstallState::Installing,
progress: Some(0),
downloaded_bytes: None,
total_bytes: None,
@@ -446,16 +446,18 @@ fn handle_local_ai_install_piper(params: Map<String, Value>) -> ControllerFuture
// on task exit, including via panic.
tokio::spawn(async move {
let _slot = slot;
+ let install = tinyinference::local::piper::PiperInstall::new(
+ crate::inference::paths::workspace_piper_dir(&config),
+ );
if let Err(e) =
- crate::inference::local::install_piper::install_piper(&config, voice_id, force)
- .await
+ tinyinference::local::piper::install_piper(&install, voice_id, force).await
{
log::warn!("[voice-install:piper] background install failed: {e}");
}
});
- let status = crate::inference::local::voice_install_common::read_status(
- crate::inference::local::voice_install_common::ENGINE_PIPER,
+ let status = tinyinference::local::download::read_status(
+ tinyinference::local::download::ENGINE_PIPER,
);
serde_json::to_value(status).map_err(|e| format!("serialize piper status: {e}"))
})
@@ -473,7 +475,11 @@ fn handle_local_ai_test_connection(params: Map<String, Value>) -> ControllerFutu
fn handle_local_ai_piper_install_status(_params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
- let status = crate::inference::local::install_piper::status(&config);
+ let install = tinyinference::local::piper::PiperInstall::new(
+ crate::inference::paths::workspace_piper_dir(&config),
+ );
+ let voice_id = tinyinference::local::models::effective_tts_voice_id(&config);
+ let status = tinyinference::local::piper::status(&install, &voice_id);
serde_json::to_value(status).map_err(|e| format!("serialize piper status: {e}"))
})
}
diff --git a/crates/openhuman-core/src/inference/local/schemas_tests.rs b/crates/openhuman-core/src/inference/local/schemas_tests.rs
index d21d7d1969..fa1a1e4c50 100644
--- a/crates/openhuman-core/src/inference/local/schemas_tests.rs
+++ b/crates/openhuman-core/src/inference/local/schemas_tests.rs
@@ -119,15 +119,15 @@ async fn install_piper_handler_serializes_concurrent_calls() {
std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());
}
- let slot = crate::inference::local::voice_install_common::try_acquire_install_slot(
- crate::inference::local::voice_install_common::ENGINE_PIPER,
+ let slot = tinyinference::local::download::try_acquire_install_slot(
+ tinyinference::local::download::ENGINE_PIPER,
)
.expect("test should be able to claim the slot first");
- crate::inference::local::voice_install_common::write_status(
- crate::inference::local::voice_install_common::VoiceInstallStatus {
- engine: crate::inference::local::voice_install_common::ENGINE_PIPER.to_string(),
- state: crate::inference::local::voice_install_common::VoiceInstallState::Installing,
+ tinyinference::local::download::write_status(
+ tinyinference::local::download::VoiceInstallStatus {
+ engine: tinyinference::local::download::ENGINE_PIPER.to_string(),
+ state: tinyinference::local::download::VoiceInstallState::Installing,
progress: Some(0),
downloaded_bytes: None,
total_bytes: None,
@@ -145,9 +145,7 @@ async fn install_piper_handler_serializes_concurrent_calls() {
std::env::remove_var("OPENHUMAN_WORKSPACE");
}
drop(slot);
- crate::inference::local::voice_install_common::reset_status(
- crate::inference::local::voice_install_common::ENGINE_PIPER,
- );
+ tinyinference::local::download::reset_status(tinyinference::local::download::ENGINE_PIPER);
let v1 = r1.expect("first call ok");
let v2 = r2.expect("second call ok");
diff --git a/crates/openhuman-core/src/inference/local/service/assets/download.rs b/crates/openhuman-core/src/inference/local/service/assets/download.rs
index 7909544d07..ddb5afc61b 100644
--- a/crates/openhuman-core/src/inference/local/service/assets/download.rs
+++ b/crates/openhuman-core/src/inference/local/service/assets/download.rs
@@ -1,10 +1,11 @@
//! Triggering model downloads: everything the profile needs, or one asset.
+use crate::config::ops::local_ai_presets;
use crate::config::Config;
use crate::inference::local::service::LocalAiService;
-use crate::inference::presets::{self, VisionMode};
use crate::inference::types::LocalAiAssetsStatus;
use tinyinference::local::models as model_ids;
+use tinyinference::local::presets::VisionMode;
use tinyinference::local::provider::{provider_from_name, LocalAiProvider};
impl LocalAiService {
@@ -67,7 +68,7 @@ impl LocalAiService {
("embedding", model_ids::effective_embedding_model_id(config)),
];
if matches!(
- presets::vision_mode_for_config(&config.local_ai),
+ local_ai_presets::vision_mode_for_config(&config.local_ai),
VisionMode::Bundled
) {
steps.insert(1, ("vision", model_ids::effective_vision_model_id(config)));
@@ -104,7 +105,7 @@ impl LocalAiService {
{
let mut status = self.status.lock();
status.state = "ready".to_string();
- status.vision_state = match presets::vision_mode_for_config(&config.local_ai) {
+ status.vision_state = match local_ai_presets::vision_mode_for_config(&config.local_ai) {
VisionMode::Disabled => "disabled".to_string(),
VisionMode::Ondemand => "idle".to_string(),
VisionMode::Bundled => "ready".to_string(),
@@ -148,7 +149,7 @@ impl LocalAiService {
}
"vision" => {
if matches!(
- presets::vision_mode_for_config(&config.local_ai),
+ local_ai_presets::vision_mode_for_config(&config.local_ai),
VisionMode::Disabled
) {
return Err(
diff --git a/crates/openhuman-core/src/inference/local/service/assets/status.rs b/crates/openhuman-core/src/inference/local/service/assets/status.rs
index d6cdd11a53..b256cb9829 100644
--- a/crates/openhuman-core/src/inference/local/service/assets/status.rs
+++ b/crates/openhuman-core/src/inference/local/service/assets/status.rs
@@ -2,12 +2,13 @@
use tracing::{debug, trace};
+use crate::config::ops::local_ai_presets;
use crate::config::Config;
use crate::inference::local::service::LocalAiService;
use crate::inference::paths::resolve_tts_voice_path;
-use crate::inference::presets::{self, VisionMode};
use crate::inference::types::{LocalAiAssetStatus, LocalAiAssetsStatus};
use tinyinference::local::models as model_ids;
+use tinyinference::local::presets::VisionMode;
use tinyinference::local::provider::{provider_from_name, LocalAiProvider};
impl LocalAiService {
@@ -254,7 +255,7 @@ impl LocalAiService {
_ => None,
};
- let vision_mode = presets::vision_mode_for_config(&config.local_ai);
+ let vision_mode = local_ai_presets::vision_mode_for_config(&config.local_ai);
let embedding_path = Some(format!("ollama://{embedding_model}"));
Ok(LocalAiAssetsStatus {
chat: LocalAiAssetStatus {
diff --git a/crates/openhuman-core/src/inference/local/service/bootstrap.rs b/crates/openhuman-core/src/inference/local/service/bootstrap.rs
index d7a44e8e6a..0332ed9804 100644
--- a/crates/openhuman-core/src/inference/local/service/bootstrap.rs
+++ b/crates/openhuman-core/src/inference/local/service/bootstrap.rs
@@ -1,8 +1,9 @@
+use crate::config::ops::local_ai_presets;
use crate::config::Config;
-use crate::inference::presets::{self, VisionMode};
use crate::inference::types::LocalAiStatus;
use tinyinference::device::DeviceProfile;
use tinyinference::local::models as model_ids;
+use tinyinference::local::presets::VisionMode;
use tinyinference::local::provider::{provider_from_name, LocalAiProvider};
use super::LocalAiService;
@@ -302,11 +303,12 @@ impl LocalAiService {
let mut status = self.status.lock();
status.state = "ready".to_string();
- status.vision_state = match presets::vision_mode_for_config(&effective_config.local_ai) {
- VisionMode::Disabled => "disabled".to_string(),
- VisionMode::Bundled => "ready".to_string(),
- VisionMode::Ondemand => "idle".to_string(),
- };
+ status.vision_state =
+ match local_ai_presets::vision_mode_for_config(&effective_config.local_ai) {
+ VisionMode::Disabled => "disabled".to_string(),
+ VisionMode::Bundled => "ready".to_string(),
+ VisionMode::Ondemand => "idle".to_string(),
+ };
status.embedding_state = if effective_config.local_ai.preload_embedding_model {
"ready".to_string()
} else {
@@ -345,7 +347,8 @@ impl LocalAiService {
}
fn config_with_recommended_tier_if_unselected(config: &Config, device: &DeviceProfile) -> Config {
- let current_tier = crate::inference::presets::current_tier_from_config(&config.local_ai);
+ let current_tier =
+ crate::config::ops::local_ai_presets::current_tier_from_config(&config.local_ai);
// Local AI is opt-in on every device. The only way to keep it enabled
// across a restart is an explicit opt-in (`apply_preset` on a real tier),
@@ -355,7 +358,7 @@ fn config_with_recommended_tier_if_unselected(config: &Config, device: &DevicePr
if !config.local_ai.opt_in_confirmed {
tracing::debug!(
total_ram_gb = device.total_ram_gb(),
- min_required_gb = crate::inference::presets::MIN_RAM_GB_FOR_LOCAL_AI,
+ min_required_gb = tinyinference::local::presets::MIN_RAM_GB_FOR_LOCAL_AI,
?current_tier,
selected_tier = ?config.local_ai.selected_tier,
"[local_ai] bootstrap: opt_in_confirmed=false, hard-overriding to disabled (cloud fallback)"
@@ -375,21 +378,21 @@ fn config_with_recommended_tier_if_unselected(config: &Config, device: &DevicePr
}
fn format_degraded_warning(err: &str, config: &Config) -> String {
- let current = crate::inference::presets::current_tier_from_config(&config.local_ai);
+ let current = crate::config::ops::local_ai_presets::current_tier_from_config(&config.local_ai);
match current {
- crate::inference::presets::ModelTier::Ram16PlusGb => {
+ tinyinference::local::presets::ModelTier::Ram16PlusGb => {
format!(
"{err}. Hint: your device may not support the 16 GB+ tier model. \
Try switching to the 8-16 GB or 4-8 GB tier in Settings > Local AI Model."
)
}
- crate::inference::presets::ModelTier::Ram8To16Gb => {
+ tinyinference::local::presets::ModelTier::Ram8To16Gb => {
format!(
"{err}. Hint: your device may not support the 8-16 GB tier model. \
Try switching to the 4-8 GB or 2-4 GB tier in Settings > Local AI Model."
)
}
- crate::inference::presets::ModelTier::Ram4To8Gb => format!(
+ tinyinference::local::presets::ModelTier::Ram4To8Gb => format!(
"{err}. Hint: your device may not support the 4-8 GB tier vision sidecar. \
Try switching to the 2-4 GB tier for text-only local AI."
),
@@ -398,14 +401,18 @@ fn format_degraded_warning(err: &str, config: &Config) -> String {
}
fn initial_vision_state(config: &Config) -> String {
- match presets::vision_mode_for_config(&config.local_ai) {
+ match local_ai_presets::vision_mode_for_config(&config.local_ai) {
VisionMode::Disabled => "disabled".to_string(),
VisionMode::Ondemand | VisionMode::Bundled => "idle".to_string(),
}
}
fn vision_mode_str(config: &Config) -> String {
- format!("{:?}", presets::vision_mode_for_config(&config.local_ai)).to_ascii_lowercase()
+ format!(
+ "{:?}",
+ local_ai_presets::vision_mode_for_config(&config.local_ai)
+ )
+ .to_ascii_lowercase()
}
fn model_path_for_config(config: &Config) -> String {
diff --git a/crates/openhuman-core/src/inference/local/service/bootstrap_tests.rs b/crates/openhuman-core/src/inference/local/service/bootstrap_tests.rs
index 88451a5a1d..a28b509d7a 100644
--- a/crates/openhuman-core/src/inference/local/service/bootstrap_tests.rs
+++ b/crates/openhuman-core/src/inference/local/service/bootstrap_tests.rs
@@ -55,9 +55,9 @@ fn bootstrap_honors_opt_in_on_low_ram_device() {
let mut config = Config::default();
config.local_ai.selected_tier = Some("ram_2_4gb".to_string());
config.local_ai.opt_in_confirmed = true;
- crate::inference::presets::apply_preset_to_config(
+ crate::config::ops::local_ai_presets::apply_preset_to_config(
&mut config.local_ai,
- crate::inference::presets::ModelTier::Ram2To4Gb,
+ tinyinference::local::presets::ModelTier::Ram2To4Gb,
);
let device = test_device(4);
@@ -74,9 +74,9 @@ fn bootstrap_honors_opt_in_on_sufficient_ram_device() {
let mut config = Config::default();
config.local_ai.selected_tier = Some("ram_2_4gb".to_string());
config.local_ai.opt_in_confirmed = true;
- crate::inference::presets::apply_preset_to_config(
+ crate::config::ops::local_ai_presets::apply_preset_to_config(
&mut config.local_ai,
- crate::inference::presets::ModelTier::Ram2To4Gb,
+ tinyinference::local::presets::ModelTier::Ram2To4Gb,
);
let device = test_device(16);
diff --git a/crates/openhuman-core/src/inference/local/service/ollama_admin/binary.rs b/crates/openhuman-core/src/inference/local/service/ollama_admin/binary.rs
index 99ea10f217..2cde3eda0e 100644
--- a/crates/openhuman-core/src/inference/local/service/ollama_admin/binary.rs
+++ b/crates/openhuman-core/src/inference/local/service/ollama_admin/binary.rs
@@ -1,8 +1,8 @@
use std::path::{Path, PathBuf};
use crate::config::Config;
-use crate::inference::local::install::{find_system_ollama_binary, run_ollama_install_script};
use crate::inference::paths::find_workspace_ollama_binary;
+use tinyinference::local::install::{find_system_ollama_binary, run_ollama_install_script};
use tinyinference::local::process::apply_no_window;
use super::super::LocalAiService;
@@ -99,7 +99,7 @@ impl LocalAiService {
// OllamaSetup.exe running, wait for it instead of starting a
// second one — two concurrent installers race on the same dir
// and corrupt the install.
- if crate::inference::local::install::is_ollama_installer_running() {
+ if tinyinference::local::install::is_ollama_installer_running() {
log::info!(
"[local_ai] detected in-flight OllamaSetup.exe — \
waiting for it to finish before deciding whether to install"
@@ -119,7 +119,7 @@ impl LocalAiService {
const INSTALLER_WAIT_TIMEOUT: std::time::Duration =
std::time::Duration::from_secs(5 * 60);
let mut timed_out = false;
- while crate::inference::local::install::is_ollama_installer_running() {
+ while tinyinference::local::install::is_ollama_installer_running() {
if wait_start.elapsed() >= INSTALLER_WAIT_TIMEOUT {
timed_out = true;
break;
diff --git a/crates/openhuman-core/src/inference/local/service/ollama_admin/diagnostics.rs b/crates/openhuman-core/src/inference/local/service/ollama_admin/diagnostics.rs
index 0e70b6825b..e3da0e988b 100644
--- a/crates/openhuman-core/src/inference/local/service/ollama_admin/diagnostics.rs
+++ b/crates/openhuman-core/src/inference/local/service/ollama_admin/diagnostics.rs
@@ -1,5 +1,5 @@
+use crate::config::ops::local_ai_presets;
use crate::config::Config;
-use crate::inference::presets::{self, VisionMode};
use tinyinference::local::lm_studio::lm_studio_base_url;
use tinyinference::local::model_requirements::{
evaluate_context, ContextEligibility, MIN_CONTEXT_TOKENS,
@@ -9,6 +9,7 @@ use tinyinference::local::ollama::{
ollama_base_url_from_override, OllamaModelShow, OllamaModelTag, OllamaShowRequest,
OllamaShowResponse, OllamaTagsResponse,
};
+use tinyinference::local::presets::VisionMode;
use tinyinference::local::provider::{
model_discovery_api, provider_from_name, LocalAiProvider, ModelDiscoveryApi,
};
@@ -186,7 +187,7 @@ impl LocalAiService {
}
if healthy
&& matches!(
- presets::vision_mode_for_config(&config.local_ai),
+ local_ai_presets::vision_mode_for_config(&config.local_ai),
VisionMode::Bundled
)
&& !vision_found
@@ -250,7 +251,7 @@ impl LocalAiService {
"context_requirement": {
"min_context_tokens": MIN_CONTEXT_TOKENS,
},
- "vision_mode": presets::vision_mode_for_config(&config.local_ai),
+ "vision_mode": local_ai_presets::vision_mode_for_config(&config.local_ai),
"expected": {
"chat_model": expected_chat,
"chat_found": chat_found,
diff --git a/crates/openhuman-core/src/inference/local/service/ollama_admin/health.rs b/crates/openhuman-core/src/inference/local/service/ollama_admin/health.rs
index 420b9d5cd5..2709332705 100644
--- a/crates/openhuman-core/src/inference/local/service/ollama_admin/health.rs
+++ b/crates/openhuman-core/src/inference/local/service/ollama_admin/health.rs
@@ -1,8 +1,8 @@
use std::path::PathBuf;
use crate::config::Config;
-use crate::inference::local::install::find_system_ollama_binary;
use crate::inference::paths::{find_workspace_ollama_binary, workspace_ollama_binary};
+use tinyinference::local::install::find_system_ollama_binary;
use tinyinference::local::ollama::{ollama_base_url, ollama_base_url_from_override};
use super::super::LocalAiService;
@@ -280,8 +280,7 @@ impl LocalAiService {
}
// 5. Platform-specific well-known locations (macOS bundles, Windows, Linux).
- crate::inference::local::install::find_system_ollama_binary()
- .map(|p| p.display().to_string())
+ tinyinference::local::install::find_system_ollama_binary().map(|p| p.display().to_string())
}
pub(in crate::inference::local::service) async fn has_model(
diff --git a/crates/openhuman-core/src/inference/local/service/ollama_admin/model_pull.rs b/crates/openhuman-core/src/inference/local/service/ollama_admin/model_pull.rs
index 0bbb14ff42..c54308d8df 100644
--- a/crates/openhuman-core/src/inference/local/service/ollama_admin/model_pull.rs
+++ b/crates/openhuman-core/src/inference/local/service/ollama_admin/model_pull.rs
@@ -1,11 +1,12 @@
use futures_util::StreamExt;
+use crate::config::ops::local_ai_presets;
use crate::config::Config;
-use crate::inference::presets::{self, VisionMode};
use tinyinference::local::models as model_ids;
use tinyinference::local::ollama::{
ollama_base_url_from_override, OllamaPullEvent, OllamaPullProgress, OllamaPullRequest,
};
+use tinyinference::local::presets::VisionMode;
use super::super::LocalAiService;
use super::util::interrupted_pull_settle_window_secs;
@@ -25,7 +26,7 @@ impl LocalAiService {
// pull bury it and leave `vision_state = "missing"` with no explanation.
let mut vision_warning: Option<String> = None;
- match presets::vision_mode_for_config(&config.local_ai) {
+ match local_ai_presets::vision_mode_for_config(&config.local_ai) {
VisionMode::Disabled => {
self.status.lock().vision_state = "disabled".to_string();
}
diff --git a/crates/openhuman-core/src/inference/local/service/vision_embed.rs b/crates/openhuman-core/src/inference/local/service/vision_embed.rs
index fbe8e25cfc..ca21562cb1 100644
--- a/crates/openhuman-core/src/inference/local/service/vision_embed.rs
+++ b/crates/openhuman-core/src/inference/local/service/vision_embed.rs
@@ -1,6 +1,6 @@
use crate::agent::multimodal;
+use crate::config::ops::local_ai_presets;
use crate::config::Config;
-use crate::inference::presets::{self, VisionMode};
use crate::inference::types::LocalAiEmbeddingResult;
use tinyinference::embeddings::{
EmbeddingModel, OllamaEmbeddingModel, DEFAULT_OLLAMA_DIMENSIONS,
@@ -11,6 +11,7 @@ use tinyinference::local::ollama::{
ollama_base_url_from_override, redact_ollama_base_url, OllamaGenerateOptions,
OllamaGenerateRequest,
};
+use tinyinference::local::presets::VisionMode;
use super::LocalAiService;
@@ -42,7 +43,7 @@ impl LocalAiService {
return Err("vision prompt requires at least one image reference".to_string());
}
if matches!(
- presets::vision_mode_for_config(&config.local_ai),
+ local_ai_presets::vision_mode_for_config(&config.local_ai),
VisionMode::Disabled
) {
self.status.lock().vision_state = "disabled".to_string();
diff --git a/crates/openhuman-core/src/inference/local/voice_install_common.rs b/crates/openhuman-core/src/inference/local/voice_install_common.rs
deleted file mode 100644
index 0ccd797eee..0000000000
--- a/crates/openhuman-core/src/inference/local/voice_install_common.rs
+++ /dev/null
@@ -1,415 +0,0 @@
-//! Shared installer plumbing for the local voice stack (Piper TTS).
-//!
-//! Both installers need the same primitives:
-//!
-//! - Stream a URL to disk via `.part` suffix + atomic rename so a crash
-//! never leaves a corrupt artifact that downstream code (the STT/TTS
-//! factory) tries to load.
-//! - Validate either a known SHA256 (when upstream publishes one) or a
-//! minimum size threshold so a truncated download doesn't masquerade as
-//! a finished install.
-//! - Surface per-engine progress (downloading, extracting, idle, ready,
-//! error) on a polled status RPC — matches the existing
-//! `local_ai_downloads_progress` UX so the VoicePanel can reuse the
-//! same progress UI primitives without inventing a new event-bus channel.
-//!
-//! The Ollama installer fires-and-forgets a single PowerShell / sh block
-//! and lets the OS owner that process. For Piper we need
-//! finer-grained progress reporting (the GGML model file alone is up to
-//! 1.6 GB and users absolutely will need a percentage indicator) so the
-//! shared harness here streams the body chunks itself and updates a
-//! singleton state map keyed by engine id.
-
-use std::collections::{HashMap, HashSet};
-use std::path::{Path, PathBuf};
-use std::sync::{Mutex, OnceLock};
-use std::time::{Duration, Instant};
-
-use futures_util::StreamExt;
-use serde::{Deserialize, Serialize};
-use sha2::{Digest, Sha256};
-
-/// Overall request timeout for a single install download. 30 minutes covers
-/// the 1.6 GB `ggml-large-v3-turbo` model on a 1 Mbps link with headroom;
-/// anything slower probably isn't realistically going to finish anyway.
-const REQUEST_TIMEOUT: Duration = Duration::from_secs(1800);
-
-/// Per-chunk idle timeout. If the body stream produces no bytes for this
-/// long, treat the connection as dead and abort so the caller can retry
-/// from a clean state. Without this guard, a half-open TCP connection (the
-/// failure mode behind the "progress stuck at 18%" symptom) holds the
-/// install task forever, defeating the polled-status UX.
-const CHUNK_IDLE_TIMEOUT: Duration = Duration::from_secs(45);
-use tokio::io::AsyncWriteExt;
-
-/// Stable engine id for status tracking. The installer registers its progress
-/// under this key; the status RPC reads it back.
-pub const ENGINE_PIPER: &str = "piper";
-
-/// Lifecycle state for a voice-engine install. Mirrors the state machine
-/// the Ollama installer exposes via `LocalAiStatus.state`.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum VoiceInstallState {
- /// Nothing has happened — no binaries, no models. The default state
- /// when the workspace has never been touched.
- Missing,
- /// An install is in flight. `progress` and `downloaded_bytes` will be
- /// updated as chunks land.
- Installing,
- /// All required artifacts (binary + at least one default model) are
- /// present and pass validation.
- Installed,
- /// The expected install dir contains artifacts but they fail
- /// validation (e.g. size below threshold, hash mismatch, missing
- /// `.onnx.json` sidecar). The user should re-run install.
- Broken,
- /// The last install attempt errored. `error_detail` carries the
- /// human-readable reason.
- Error,
-}
-
-impl VoiceInstallState {
- pub fn as_str(&self) -> &'static str {
- match self {
- VoiceInstallState::Missing => "missing",
- VoiceInstallState::Installing => "installing",
- VoiceInstallState::Installed => "installed",
- VoiceInstallState::Broken => "broken",
- VoiceInstallState::Error => "error",
- }
- }
-}
-
-/// Snapshot returned over JSON-RPC for one engine's installer.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct VoiceInstallStatus {
- /// Stable engine id (today only `"piper"`).
- pub engine: String,
- /// Current state — see [`VoiceInstallState`].
- pub state: VoiceInstallState,
- /// 0-100 percent for the in-flight download (`None` when state is not
- /// `Installing`).
- pub progress: Option<u8>,
- /// Bytes received so far.
- pub downloaded_bytes: Option<u64>,
- /// Total bytes expected (from `Content-Length` — may be `None` for
- /// chunked transfer encoding).
- pub total_bytes: Option<u64>,
- /// Free-text status line — what file we're downloading, what stage
- /// we're at. Useful for the UI to show "Downloading piper…" vs
- /// "Downloading ggml-large-v3-turbo.bin…".
- pub stage: Option<String>,
- /// Populated when `state == Error` — the user-facing failure reason.
- pub error_detail: Option<String>,
-}
-
-impl VoiceInstallStatus {
- fn missing(engine: &str) -> Self {
- Self {
- engine: engine.to_string(),
- state: VoiceInstallState::Missing,
- progress: None,
- downloaded_bytes: None,
- total_bytes: None,
- stage: None,
- error_detail: None,
- }
- }
-}
-
-/// In-memory status table — keyed by engine id. Both installers share
-/// this so the status RPC can answer for either engine without a separate
-/// store.
-static STATUS_TABLE: once_cell::sync::Lazy<Mutex<HashMap<String, VoiceInstallStatus>>> =
- once_cell::sync::Lazy::new(|| Mutex::new(HashMap::new()));
-
-/// Fetch the current status snapshot for `engine`. Returns `Missing`
-/// when the engine has never been touched.
-pub fn read_status(engine: &str) -> VoiceInstallStatus {
- STATUS_TABLE
- .lock()
- .expect("voice install status lock poisoned")
- .get(engine)
- .cloned()
- .unwrap_or_else(|| VoiceInstallStatus::missing(engine))
-}
-
-/// Replace the snapshot for `engine`. Internal helper for the installer
-/// flow — exposed at module scope so install_piper can
-/// update progress without going through a public setter API.
-pub(crate) fn write_status(status: VoiceInstallStatus) {
- log::debug!(
- "[voice-install] status update engine={} state={} progress={:?} stage={:?}",
- status.engine,
- status.state.as_str(),
- status.progress,
- status.stage,
- );
- let mut table = STATUS_TABLE
- .lock()
- .expect("voice install status lock poisoned");
- table.insert(status.engine.clone(), status);
-}
-
-/// Force a fresh missing state for `engine`. Used by tests and by the
-/// "Reinstall" path before kicking off a new download.
-#[cfg(test)]
-pub(crate) fn reset_status(engine: &str) {
- let mut table = STATUS_TABLE
- .lock()
- .expect("voice install status lock poisoned");
- table.remove(engine);
-}
-
-/// Set of engines that currently have an install task in flight. Acts as a
-/// true single-writer guard around the install-start critical section so
-/// two concurrent RPC calls (a double-click, or the auto-install-on-change
-/// firing in parallel with a manual button click) can't both pass an
-/// `is-Installing?` snapshot check and then both spawn duplicate install
-/// tasks that race on the same `.part` file inside `download_to_file`.
-///
-/// `STATUS_TABLE` advertises lifecycle state to the polling RPC; this set
-/// owns the *start* decision. They are deliberately separate locks: the
-/// status table is read on every status poll (cheap, frequent), while
-/// this set is only touched on install start / end (rare).
-static IN_FLIGHT: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
-
-fn in_flight() -> &'static Mutex<HashSet<&'static str>> {
- IN_FLIGHT.get_or_init(|| Mutex::new(HashSet::new()))
-}
-
-/// RAII guard returned by [`try_acquire_install_slot`]. Holding one of
-/// these proves the caller has exclusive ownership of the install-start
-/// slot for `engine`. Dropping it (including via panic unwind) releases
-/// the slot so a subsequent install attempt can proceed.
-///
-/// The handler is expected to **move** the slot into the spawned tokio
-/// task so the slot lives for the install's actual duration, not just
-/// the RPC handler's lifetime. Releasing the slot when the handler
-/// returns (instead of when the install finishes) would re-open the
-/// race the slot was added to close.
-pub(crate) struct InstallSlot {
- engine: &'static str,
-}
-
-impl Drop for InstallSlot {
- fn drop(&mut self) {
- match in_flight().lock() {
- Ok(mut guard) => {
- let removed = guard.remove(self.engine);
- log::debug!(
- "[voice-install] install slot released engine={} was_present={}",
- self.engine,
- removed
- );
- }
- Err(_) => {
- // Lock poisoned — another thread panicked while holding
- // it. The set is in an unknown state; the best we can do
- // is log and let the process continue. Subsequent
- // acquire attempts will also hit the poisoned lock and
- // surface the failure to the user.
- log::error!(
- "[voice-install] install slot lock poisoned on drop for engine={}",
- self.engine
- );
- }
- }
- }
-}
-
-/// Atomically try to claim the install-start slot for `engine`. Returns
-/// `Some(InstallSlot)` if no install is currently in flight for this
-/// engine, or `None` if one is already running.
-///
-/// This replaces the previous non-atomic `read_status` -> check ->
-/// `write_status` sequence in the install RPC handlers. The
-/// check-and-insert happens under a single mutex acquisition, so two
-/// concurrent callers cannot both observe "not installing" and both
-/// spawn tasks.
-pub(crate) fn try_acquire_install_slot(engine: &'static str) -> Option<InstallSlot> {
- let mut guard = in_flight()
- .lock()
- .expect("voice install in-flight lock poisoned");
- if guard.contains(engine) {
- log::debug!(
- "[voice-install] install slot denied engine={} (already in flight)",
- engine
- );
- return None;
- }
- guard.insert(engine);
- log::debug!("[voice-install] install slot acquired engine={}", engine);
- Some(InstallSlot { engine })
-}
-
-/// Download `url` to `dest` with atomic rename. Streams bytes through
-/// SHA256 if `expected_sha256` is provided, otherwise validates that the
-/// final size is at least `min_bytes`.
-///
-/// The on-disk write goes to `<dest>.part` first and is `rename`d into
-/// place only after all checks pass. If the function is interrupted
-/// mid-stream (process killed, network drop) the `.part` file is the
-/// only thing left behind; the next call detects and overwrites it so
-/// we never read a half-written model.
-///
-/// Progress callbacks fire every chunk with `(downloaded_bytes,
-/// total_bytes)`. Total may be `None` for chunked responses.
-pub async fn download_to_file(
- url: &str,
- dest: &Path,
- expected_sha256: Option<&str>,
- min_bytes: u64,
- log_prefix: &str,
- mut on_progress: impl FnMut(u64, Option<u64>),
-) -> Result<(), String> {
- if let Some(parent) = dest.parent() {
- tokio::fs::create_dir_all(parent)
- .await
- .map_err(|e| format!("{log_prefix} mkdir {}: {e}", parent.display()))?;
- }
-
- let part_path = part_path(dest);
- // Always start from scratch — resumable HTTP Range support is
- // useful but not free (servers must return 206, hash state has to
- // restart on hash mismatch). For the MVP we restart cleanly and
- // ensure `.part` is removed first so we never accidentally append
- // to leftover bytes from an earlier failed attempt.
- if part_path.exists() {
- let _ = tokio::fs::remove_file(&part_path).await;
- }
-
- log::debug!("{log_prefix} GET {url} -> {}", part_path.display());
- let client = reqwest::Client::builder()
- // 15s connect handshake; 30min overall request budget (covers 1.6 GB
- // GGML model on a 1 Mbps link). Per-chunk idle timeout is enforced
- // separately on each stream read below so half-open connections
- // fail fast instead of hanging the install task forever.
- .connect_timeout(Duration::from_secs(15))
- .timeout(REQUEST_TIMEOUT)
- .build()
- .map_err(|e| format!("{log_prefix} build http client: {e}"))?;
- let started = Instant::now();
- let resp = client
- .get(url)
- .send()
- .await
- .map_err(|e| format!("{log_prefix} request {url}: {e}"))?;
- if !resp.status().is_success() {
- return Err(format!(
- "{log_prefix} non-2xx response from {url}: {}",
- resp.status()
- ));
- }
- let total = resp.content_length();
- log::debug!(
- "{log_prefix} response status={} content_length={:?}",
- resp.status(),
- total
- );
-
- let mut file = tokio::fs::File::create(&part_path)
- .await
- .map_err(|e| format!("{log_prefix} create {}: {e}", part_path.display()))?;
- let mut hasher = expected_sha256.is_some().then(Sha256::new);
- let mut downloaded: u64 = 0;
- let mut stream = resp.bytes_stream();
- loop {
- // Per-chunk idle timeout — if no bytes arrive within CHUNK_IDLE_TIMEOUT,
- // bail out so a stalled half-open TCP connection doesn't hold the install
- // task forever. Clean up the .part on the way out so a retry starts fresh.
- let next = tokio::time::timeout(CHUNK_IDLE_TIMEOUT, stream.next()).await;
- let chunk = match next {
- Ok(Some(chunk)) => chunk,
- Ok(None) => break,
- Err(_) => {
- drop(file);
- let _ = tokio::fs::remove_file(&part_path).await;
- return Err(format!(
- "{log_prefix} body stream idle for >{}s after {downloaded} bytes; aborting",
- CHUNK_IDLE_TIMEOUT.as_secs()
- ));
- }
- };
- let bytes = match chunk {
- Ok(bytes) => bytes,
- Err(e) => {
- drop(file);
- let _ = tokio::fs::remove_file(&part_path).await;
- return Err(format!("{log_prefix} body stream: {e}"));
- }
- };
- if let Some(h) = hasher.as_mut() {
- h.update(&bytes);
- }
- if let Err(e) = file.write_all(&bytes).await {
- drop(file);
- let _ = tokio::fs::remove_file(&part_path).await;
- return Err(format!("{log_prefix} write {}: {e}", part_path.display()));
- }
- downloaded = downloaded.saturating_add(bytes.len() as u64);
- on_progress(downloaded, total);
- }
- file.flush()
- .await
- .map_err(|e| format!("{log_prefix} flush {}: {e}", part_path.display()))?;
- drop(file);
-
- if downloaded < min_bytes {
- let _ = tokio::fs::remove_file(&part_path).await;
- return Err(format!(
- "{log_prefix} downloaded payload too small: {downloaded} bytes < min {min_bytes}"
- ));
- }
- if let (Some(expected), Some(hasher)) = (expected_sha256, hasher) {
- let got = hex::encode(hasher.finalize());
- let expected_norm = expected.trim().to_ascii_lowercase();
- if got != expected_norm {
- // Never log the full file contents on mismatch — just the hashes.
- log::warn!(
- "{log_prefix} sha256 mismatch expected={} got={}",
- expected_norm,
- got
- );
- let _ = tokio::fs::remove_file(&part_path).await;
- return Err(format!(
- "{log_prefix} sha256 mismatch (expected {expected_norm}, got {got})"
- ));
- }
- }
-
- // Atomic rename — only after all checks pass. On Windows
- // `tokio::fs::rename` maps to `MoveFileExW` which fails if the dest
- // already exists, so remove it first.
- if dest.exists() {
- tokio::fs::remove_file(dest)
- .await
- .map_err(|e| format!("{log_prefix} remove existing {}: {e}", dest.display()))?;
- }
- tokio::fs::rename(&part_path, dest).await.map_err(|e| {
- format!(
- "{log_prefix} rename {} -> {}: {e}",
- part_path.display(),
- dest.display()
- )
- })?;
- log::debug!(
- "{log_prefix} downloaded {} bytes -> {} elapsed_ms={}",
- downloaded,
- dest.display(),
- started.elapsed().as_millis()
- );
- Ok(())
-}
-
-/// Produce the `.part` sibling of `dest`. Helper kept testable.
-pub fn part_path(dest: &Path) -> PathBuf {
- let mut s = dest.as_os_str().to_os_string();
- s.push(".part");
- PathBuf::from(s)
-}
-
-#[cfg(test)]
-#[path = "voice_install_common_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/local/voice_install_common_tests.rs b/crates/openhuman-core/src/inference/local/voice_install_common_tests.rs
deleted file mode 100644
index 1ce7a5b31f..0000000000
--- a/crates/openhuman-core/src/inference/local/voice_install_common_tests.rs
+++ /dev/null
@@ -1,278 +0,0 @@
-use super::*;
-
-#[test]
-fn part_path_appends_part_suffix() {
- let p = part_path(Path::new("/tmp/foo.bin"));
- assert_eq!(
- p.file_name().unwrap().to_string_lossy(),
- "foo.bin.part",
- "should append .part"
- );
-}
-
-#[test]
-fn part_path_handles_no_extension() {
- let p = part_path(Path::new("/tmp/binaryname"));
- assert_eq!(p.file_name().unwrap().to_string_lossy(), "binaryname.part");
-}
-
-#[test]
-fn voice_install_state_as_str_is_stable() {
- // The UI relies on the lowercase string form — guard against an
- // accidental rename breaking the wire contract.
- assert_eq!(VoiceInstallState::Missing.as_str(), "missing");
- assert_eq!(VoiceInstallState::Installing.as_str(), "installing");
- assert_eq!(VoiceInstallState::Installed.as_str(), "installed");
- assert_eq!(VoiceInstallState::Broken.as_str(), "broken");
- assert_eq!(VoiceInstallState::Error.as_str(), "error");
-}
-
-#[test]
-fn read_status_defaults_to_missing_for_unseen_engine() {
- let unique = format!("test-engine-{}", uuid::Uuid::new_v4());
- let snapshot = read_status(&unique);
- assert_eq!(snapshot.state, VoiceInstallState::Missing);
- assert_eq!(snapshot.engine, unique);
- assert!(snapshot.progress.is_none());
-}
-
-#[test]
-fn write_and_read_status_roundtrip() {
- let engine = format!("rt-{}", uuid::Uuid::new_v4());
- let status = VoiceInstallStatus {
- engine: engine.clone(),
- state: VoiceInstallState::Installing,
- progress: Some(42),
- downloaded_bytes: Some(1024),
- total_bytes: Some(2048),
- stage: Some("downloading model".to_string()),
- error_detail: None,
- };
- write_status(status);
- let got = read_status(&engine);
- assert_eq!(got.state, VoiceInstallState::Installing);
- assert_eq!(got.progress, Some(42));
- assert_eq!(got.stage.as_deref(), Some("downloading model"));
- // Clean up so the suite stays deterministic for parallel runs.
- reset_status(&engine);
-}
-
-#[test]
-fn reset_status_returns_engine_to_missing() {
- let engine = format!("rs-{}", uuid::Uuid::new_v4());
- write_status(VoiceInstallStatus {
- engine: engine.clone(),
- state: VoiceInstallState::Installed,
- progress: None,
- downloaded_bytes: None,
- total_bytes: None,
- stage: None,
- error_detail: None,
- });
- reset_status(&engine);
- assert_eq!(read_status(&engine).state, VoiceInstallState::Missing);
-}
-
-// Engine ids used by the slot tests below. The slot map is keyed by
-// `&'static str`, so we can't use uuid-suffixed names like the
-// status-table tests; we use these dedicated keys instead. Production
-// engine ids (ENGINE_PIPER) are deliberately avoided so tests can't
-// deadlock against a real install in another test.
-const TEST_SLOT_ENGINE_A: &str = "__test_slot_engine_a__";
-const TEST_SLOT_ENGINE_B: &str = "__test_slot_engine_b__";
-
-fn slot_test_lock() -> std::sync::MutexGuard<'static, ()> {
- static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
- LOCK.get_or_init(|| std::sync::Mutex::new(()))
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
-}
-
-/// Best-effort drain of a test slot so the global set is clean across
-/// runs. Tests that leave a slot held (e.g. by forgetting it) would
-/// pollute subsequent runs in the same `cargo test` invocation.
-fn drain_test_slot(engine: &'static str) {
- if let Ok(mut g) = in_flight().lock() {
- g.remove(engine);
- }
-}
-
-#[test]
-fn try_acquire_install_slot_grants_then_blocks_then_releases() {
- let _test_guard = slot_test_lock();
- drain_test_slot(TEST_SLOT_ENGINE_A);
-
- // First caller gets the slot.
- let slot = try_acquire_install_slot(TEST_SLOT_ENGINE_A);
- assert!(slot.is_some(), "first acquire should succeed");
-
- // Concurrent caller is rejected while the first slot lives.
- let second = try_acquire_install_slot(TEST_SLOT_ENGINE_A);
- assert!(
- second.is_none(),
- "second acquire must be rejected while slot is held"
- );
-
- // Releasing the first slot reopens the door for a fresh caller.
- drop(slot);
- let third = try_acquire_install_slot(TEST_SLOT_ENGINE_A);
- assert!(
- third.is_some(),
- "acquire after drop should succeed (Drop must release)"
- );
-
- drop(third);
- drain_test_slot(TEST_SLOT_ENGINE_A);
-}
-
-#[test]
-fn install_slot_keys_are_independent_per_engine() {
- let _test_guard = slot_test_lock();
- drain_test_slot(TEST_SLOT_ENGINE_A);
- drain_test_slot(TEST_SLOT_ENGINE_B);
-
- let slot_a = try_acquire_install_slot(TEST_SLOT_ENGINE_A).expect("A acquire");
- // Holding the A slot must not block the B slot — installs for
- // different engines run independently.
- let slot_b =
- try_acquire_install_slot(TEST_SLOT_ENGINE_B).expect("B acquire must succeed independently");
- // Acquiring A again must still fail though.
- assert!(
- try_acquire_install_slot(TEST_SLOT_ENGINE_A).is_none(),
- "A slot is still held"
- );
-
- drop(slot_a);
- drop(slot_b);
- drain_test_slot(TEST_SLOT_ENGINE_A);
- drain_test_slot(TEST_SLOT_ENGINE_B);
-}
-
-/// Race-path test — the whole reason the slot exists. Spawn many
-/// concurrent tasks that all try to acquire the slot for the same
-/// engine; exactly one must succeed, all others must be rejected.
-/// This is the unit-level analogue of "two RPC handlers fire at the
-/// same time and both spawn install tasks" — the bug CodeRabbit
-/// flagged on PR #1755.
-#[tokio::test]
-async fn concurrent_install_slot_acquire_grants_exactly_one() {
- let _test_guard = slot_test_lock();
- drain_test_slot(TEST_SLOT_ENGINE_A);
-
- // 32 concurrent acquirers — high enough to make a non-atomic
- // implementation almost certainly fail, low enough to stay
- // hermetic and fast.
- const N: usize = 32;
- let mut handles = Vec::with_capacity(N);
- for _ in 0..N {
- handles.push(tokio::spawn(async move {
- try_acquire_install_slot(TEST_SLOT_ENGINE_A)
- }));
- }
- let mut winners = 0usize;
- let mut losers = 0usize;
- // Collect outcomes *before* any slot is dropped — winners must
- // hold their slot alive past every other acquirer's attempt.
- let mut held = Vec::new();
- for h in handles {
- match h.await.expect("task panicked") {
- Some(slot) => {
- winners += 1;
- held.push(slot);
- }
- None => losers += 1,
- }
- }
- assert_eq!(
- winners, 1,
- "exactly one concurrent acquirer must win (got {winners})"
- );
- assert_eq!(losers, N - 1, "all other acquirers must lose");
-
- // Now drop the winner — the slot becomes available again.
- held.clear();
- let after = try_acquire_install_slot(TEST_SLOT_ENGINE_A);
- assert!(
- after.is_some(),
- "slot must be reacquirable once the winner drops"
- );
- drop(after);
- drain_test_slot(TEST_SLOT_ENGINE_A);
-}
-
-#[tokio::test]
-async fn download_to_file_rejects_oversize_min_bytes() {
- // 4xx-like guard: a non-existent host fails before we can write
- // anything. Use a localhost port that nothing is listening on so
- // the test is hermetic.
- let dir = tempfile::tempdir().unwrap();
- let dest = dir.path().join("never.bin");
- let result = download_to_file(
- "http://127.0.0.1:1/never",
- &dest,
- None,
- 10,
- "[voice-install:test]",
- |_, _| {},
- )
- .await;
- assert!(result.is_err(), "expected network error on unused port");
- // No `.part` should be left behind on a connection failure.
- let part = part_path(&dest);
- assert!(
- !part.exists(),
- "no part file should remain after pre-stream failure"
- );
-}
-
-#[tokio::test]
-async fn download_to_file_streams_and_renames_atomically() {
- // Spin up a one-shot in-process server with hyper via reqwest's
- // test infrastructure isn't available here, so we stand up a tiny
- // TCP listener that serves a fixed body. Keep the body small so
- // the test stays fast.
- use std::io::Write as _;
- use std::net::TcpListener;
- let listener = TcpListener::bind("127.0.0.1:0").unwrap();
- let addr = listener.local_addr().unwrap();
- let body = b"hello voice-install body";
- let server = tokio::task::spawn_blocking(move || {
- let (mut sock, _) = listener.accept().unwrap();
- // Drain request bytes — we only need headers.
- let mut buf = [0u8; 1024];
- use std::io::Read as _;
- let _ = sock.read(&mut buf);
- let response = format!(
- "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: application/octet-stream\r\nConnection: close\r\n\r\n",
- body.len()
- );
- sock.write_all(response.as_bytes()).unwrap();
- sock.write_all(body).unwrap();
- sock.flush().unwrap();
- });
-
- let dir = tempfile::tempdir().unwrap();
- let dest = dir.path().join("hello.bin");
- let url = format!("http://{addr}/hello");
- let mut last_progress = (0u64, None);
- let result = download_to_file(
- &url,
- &dest,
- None,
- 5,
- "[voice-install:test]",
- |downloaded, total| {
- last_progress = (downloaded, total);
- },
- )
- .await;
- server.await.unwrap();
- assert!(result.is_ok(), "download failed: {result:?}");
- let on_disk = tokio::fs::read(&dest).await.unwrap();
- assert_eq!(on_disk.as_slice(), body, "wrong bytes landed on disk");
- assert!(last_progress.0 > 0, "progress callback should fire");
- assert!(
- !part_path(&dest).exists(),
- "part file should be renamed away"
- );
-}
diff --git a/crates/openhuman-core/src/inference/mod.rs b/crates/openhuman-core/src/inference/mod.rs
index 0742b1562d..84fc4745e4 100644
--- a/crates/openhuman-core/src/inference/mod.rs
+++ b/crates/openhuman-core/src/inference/mod.rs
@@ -31,7 +31,6 @@ pub mod model_context;
pub mod openai_oauth;
pub mod ops;
pub mod paths;
-pub mod presets;
pub mod provider;
mod schemas;
pub mod tokenjuice;
@@ -48,7 +47,6 @@ pub use schemas::{
pub use local::all_local_inference_controller_schemas;
pub use local::all_local_inference_registered_controllers;
pub use model_context::context_window_for_model;
-pub use presets::{ModelPreset, ModelTier, VisionMode};
pub use types::{
LocalAiAssetStatus, LocalAiAssetsStatus, LocalAiDownloadProgressItem, LocalAiDownloadsProgress,
LocalAiEmbeddingResult, LocalAiSpeechResult, LocalAiStatus, LocalAiTtsResult,
diff --git a/crates/openhuman-core/src/inference/ops.rs b/crates/openhuman-core/src/inference/ops.rs
index 03e3ce2af1..fadc462765 100644
--- a/crates/openhuman-core/src/inference/ops.rs
+++ b/crates/openhuman-core/src/inference/ops.rs
@@ -1,15 +1,16 @@
//! JSON-RPC controller surface for inference operations.
+use crate::config::ops::local_ai_presets;
use crate::config::rpc as config_rpc;
use crate::config::Config;
use crate::inference::local as local_runtime;
use crate::inference::local::ops::ReactionDecision;
-use crate::inference::presets;
use crate::inference::provider as providers;
use crate::inference::{LocalAiEmbeddingResult, LocalAiStatus};
use crate::rpc::RpcOutcome;
use serde_json::{json, Value};
use tinyinference::device::detect_device_profile;
+use tinyinference::local::presets;
use tinyinference::message::Message;
use tinyinference::model::ModelRequest;
use tinyinference::sentiment::{parse_sentiment_response, SentimentResult};
@@ -409,7 +410,7 @@ pub async fn inference_presets() -> Result<RpcOutcome<Value>, String> {
let config = config_rpc::load_config_with_timeout().await?;
let device = detect_device_profile();
let recommended = presets::recommend_tier(&device);
- let current = presets::current_tier_from_config(&config.local_ai);
+ let current = local_ai_presets::current_tier_from_config(&config.local_ai);
let selected_tier = config.local_ai.selected_tier.as_ref().and_then(|value| {
let normalized = value.trim().to_ascii_lowercase();
presets::ModelTier::from_str_opt(&normalized)
@@ -477,7 +478,7 @@ pub async fn inference_apply_preset(tier: &str) -> Result<RpcOutcome<Value>, Str
let mut config = config_rpc::load_config_with_timeout().await?;
config.local_ai.runtime_enabled = true;
config.local_ai.opt_in_confirmed = true;
- presets::apply_preset_to_config(&mut config.local_ai, tier);
+ local_ai_presets::apply_preset_to_config(&mut config.local_ai, tier);
config
.save()
.await
@@ -491,7 +492,7 @@ pub async fn inference_apply_preset(tier: &str) -> Result<RpcOutcome<Value>, Str
"vision_model_id": config.local_ai.vision_model_id,
"embedding_model_id": config.local_ai.embedding_model_id,
"quantization": config.local_ai.quantization,
- "vision_mode": presets::vision_mode_for_config(&config.local_ai),
+ "vision_mode": local_ai_presets::vision_mode_for_config(&config.local_ai),
"local_ai_enabled": true,
}),
"inference preset applied",
diff --git a/crates/openhuman-core/src/inference/paths.rs b/crates/openhuman-core/src/inference/paths.rs
index bf05c37ea1..80f3a51ff2 100644
--- a/crates/openhuman-core/src/inference/paths.rs
+++ b/crates/openhuman-core/src/inference/paths.rs
@@ -186,9 +186,8 @@ pub(crate) fn resolve_piper_binary() -> Option<PathBuf> {
/// Config-aware piper resolution: workspace install first, env second,
/// PATH third.
pub(crate) fn resolve_piper_binary_with_config(config: &Config) -> Option<PathBuf> {
- if let Some(workspace) =
- crate::inference::local::install_piper::find_workspace_piper_binary(config)
- {
+ let install = tinyinference::local::piper::PiperInstall::new(workspace_piper_dir(config));
+ if let Some(workspace) = tinyinference::local::piper::find_workspace_piper_binary(&install) {
return Some(workspace);
}
resolve_piper_binary()
diff --git a/crates/openhuman-core/src/inference/presets.rs b/crates/openhuman-core/src/inference/presets.rs
deleted file mode 100644
index d21371915d..0000000000
--- a/crates/openhuman-core/src/inference/presets.rs
+++ /dev/null
@@ -1,345 +0,0 @@
-//! Tiered model presets and recommendation logic for local AI.
-//!
-//! Text generation is always the primary summarizer. Vision is a secondary
-//! scene-description sidecar whose output can be merged with OCR by the text
-//! model when a tier supports it.
-
-use serde::{Deserialize, Serialize};
-
-use crate::config::schema::LocalAiConfig;
-
-use tinyinference::device::DeviceProfile;
-
-/// Performance tier for local AI model selection.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
-pub enum ModelTier {
- #[serde(rename = "ram_1gb")]
- Ram1Gb,
- #[serde(rename = "ram_2_4gb")]
- Ram2To4Gb,
- #[serde(rename = "ram_4_8gb")]
- Ram4To8Gb,
- #[serde(rename = "ram_8_16gb")]
- Ram8To16Gb,
- #[serde(rename = "ram_16_plus_gb")]
- Ram16PlusGb,
- #[serde(rename = "custom")]
- Custom,
-}
-
-/// Single local model tier exposed in the current build. Larger local models
-/// stay blocked to keep summarization lightweight and battery-friendly.
-pub const MVP_MAX_TIER: ModelTier = ModelTier::Ram2To4Gb;
-
-/// Minimum host RAM (in whole GB) below which the **default** is to skip
-/// local inference and use the cloud summarizer instead. The user can still
-/// override this and opt into local AI via settings.
-pub const MIN_RAM_GB_FOR_LOCAL_AI: u64 = 8;
-
-/// Returns `true` when the device has enough RAM that local AI should be
-/// enabled by default. Below the floor we recommend cloud fallback instead.
-pub fn device_supports_local_ai(device: &DeviceProfile) -> bool {
- device.total_ram_gb() >= MIN_RAM_GB_FOR_LOCAL_AI
-}
-
-/// Returns `true` when the device is below the RAM floor and local AI should
-/// default to disabled (cloud fallback). This is a **recommendation**, not a
-/// hard gate — the user can still opt in.
-pub fn should_default_to_cloud_fallback(device: &DeviceProfile) -> bool {
- !device_supports_local_ai(device)
-}
-
-impl ModelTier {
- pub fn as_str(&self) -> &'static str {
- match self {
- Self::Ram1Gb => "ram_1gb",
- Self::Ram2To4Gb => "ram_2_4gb",
- Self::Ram4To8Gb => "ram_4_8gb",
- Self::Ram8To16Gb => "ram_8_16gb",
- Self::Ram16PlusGb => "ram_16_plus_gb",
- Self::Custom => "custom",
- }
- }
-
- /// Whether this tier is allowed in the current MVP build.
- pub fn is_mvp_allowed(self) -> bool {
- matches!(self, Self::Ram2To4Gb)
- }
-
- pub fn from_str_opt(s: &str) -> Option<Self> {
- match s.to_ascii_lowercase().as_str() {
- "ram_1gb" | "tier_1gb" | "1gb" => Some(Self::Ram1Gb),
- "ram_2_4gb" | "tier_2_4gb" | "2_4gb" | "low" => Some(Self::Ram2To4Gb),
- "ram_4_8gb" | "tier_4_8gb" | "4_8gb" => Some(Self::Ram4To8Gb),
- "ram_8_16gb" | "tier_8_16gb" | "8_16gb" | "medium" => Some(Self::Ram8To16Gb),
- "ram_16_plus_gb" | "tier_16_plus_gb" | "16_plus_gb" | "high" => Some(Self::Ram16PlusGb),
- "custom" => Some(Self::Custom),
- _ => None,
- }
- }
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum VisionMode {
- Disabled,
- Ondemand,
- Bundled,
-}
-
-/// A concrete model preset tied to a performance tier.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ModelPreset {
- pub tier: ModelTier,
- pub label: &'static str,
- pub description: &'static str,
- pub chat_model_id: &'static str,
- pub vision_model_id: &'static str,
- pub embedding_model_id: &'static str,
- pub quantization: &'static str,
- pub vision_mode: VisionMode,
- pub supports_screen_summary: bool,
- pub target_ram_gb: u64,
- pub min_ram_gb: u64,
- pub approx_download_gb: f32,
-}
-
-/// Return all built-in presets.
-pub fn all_presets() -> Vec<ModelPreset> {
- vec![
- ModelPreset {
- tier: ModelTier::Ram1Gb,
- label: "1 GB",
- description: "Fastest chat-only tier for ultra-low-memory devices. OCR + text only.",
- chat_model_id: "gemma3:270m-it-qat",
- vision_model_id: "",
- embedding_model_id: "all-minilm:latest",
- quantization: "qat",
- vision_mode: VisionMode::Disabled,
- supports_screen_summary: false,
- target_ram_gb: 1,
- min_ram_gb: 1,
- approx_download_gb: 0.3,
- },
- ModelPreset {
- tier: ModelTier::Ram2To4Gb,
- label: "Gemma 3 1B",
- description:
- "Battery-friendly local summarization preset. Uses the 1B Gemma model with vision disabled.",
- chat_model_id: "gemma3:1b-it-qat",
- vision_model_id: "",
- // bge-m3 — 1024 dims required by memory tree's on-disk format
- // and 8192-token context for long-chunk embeds.
- embedding_model_id: "bge-m3",
- quantization: "qat",
- vision_mode: VisionMode::Disabled,
- supports_screen_summary: false,
- target_ram_gb: 2,
- min_ram_gb: 2,
- approx_download_gb: 2.3,
- },
- ModelPreset {
- tier: ModelTier::Ram4To8Gb,
- label: "4-8 GB",
- description: "Light Gemma chat with on-demand vision summaries via Moondream.",
- chat_model_id: "gemma3:1b-it-qat",
- vision_model_id: "moondream:1.8b-v2-q4_K_S",
- embedding_model_id: "all-minilm:latest",
- quantization: "qat",
- vision_mode: VisionMode::Ondemand,
- supports_screen_summary: true,
- target_ram_gb: 4,
- min_ram_gb: 4,
- approx_download_gb: 2.8,
- },
- ModelPreset {
- tier: ModelTier::Ram8To16Gb,
- label: "8-16 GB",
- description: "Balanced Gemma multimodal preset with bundled vision support.",
- chat_model_id: "gemma3:4b-it-qat",
- // Gemma 3 is multimodal from 4B upward, so one model covers chat
- // and vision here. (The 270M and 1B builds are text-only.)
- vision_model_id: "gemma3:4b-it-qat",
- // bge-m3 (1024 dims). nomic-embed-text is 768 dims and fails the
- // memory tree's post-call dimension validator; the embedding
- // allowlist already rewrote it to bge-m3 at resolution time, so
- // naming bge-m3 here only makes the preset honest about what is
- // actually pulled.
- embedding_model_id: "bge-m3",
- quantization: "qat",
- vision_mode: VisionMode::Bundled,
- supports_screen_summary: true,
- target_ram_gb: 8,
- min_ram_gb: 8,
- // gemma3:4b-it-qat (4.0 GB) + bge-m3 (1.2 GB)
- approx_download_gb: 5.2,
- },
- ModelPreset {
- tier: ModelTier::Ram16PlusGb,
- label: "16 GB+",
- description: "Best local quality with Gemma 4 on higher-end devices.",
- // GH #5055 moved this tier off `gemma4:e4b` because no `gemma4`
- // namespace existed on the Ollama library at the time, and landed
- // on `gemma3n:e4b-it-q8_0`. Two things have changed (#5146 §1.3):
- //
- // 1. Gemma 4 has since been published, and `gemma4:e4b-it-q8_0`
- // resolves (11.6 GB, 128K context).
- // 2. Gemma 3n is **text-only** on Ollama, so using it as the
- // `vision_model_id` of a `Bundled` vision tier pointed every
- // vision request at a model with no vision encoder. Ollama
- // accepts the `images` array against such a model, discards
- // it, and answers from the prompt text — a hallucinated
- // description rather than an error.
- //
- // Gemma 4 is multimodal at every published size, so this tier is
- // back to one model serving both chat and vision, matching how the
- // 8-16 GB tier uses `gemma3:4b-it-qat`.
- chat_model_id: "gemma4:e4b-it-q8_0",
- vision_model_id: "gemma4:e4b-it-q8_0",
- // bge-m3 (1024 dims) — see the 8-16 GB tier note above.
- embedding_model_id: "bge-m3",
- // The other tiers ship QAT builds; this one is q8_0. The field is a
- // display label (`effective_quantization`) and does not take part in
- // resolving the model tag, but it should still match what is pulled.
- quantization: "q8_0",
- vision_mode: VisionMode::Bundled,
- supports_screen_summary: true,
- target_ram_gb: 16,
- min_ram_gb: 16,
- // gemma4:e4b-it-q8_0 (11.6 GB) + bge-m3 (1.2 GB)
- approx_download_gb: 12.8,
- },
- ]
-}
-
-/// Return only the presets allowed under the current MVP ceiling.
-pub fn mvp_presets() -> Vec<ModelPreset> {
- all_presets()
- .into_iter()
- .filter(|preset| preset.tier.is_mvp_allowed())
- .collect()
-}
-
-/// Return the preset for a specific tier, or `None` for `Custom`.
-pub fn preset_for_tier(tier: ModelTier) -> Option<ModelPreset> {
- all_presets().into_iter().find(|preset| preset.tier == tier)
-}
-
-/// Recommend a tier based on device capabilities.
-pub fn recommend_tier(device: &DeviceProfile) -> ModelTier {
- // NOTE: the MVP intentionally caps every device at `MVP_MAX_TIER`
- // regardless of installed RAM (the `recommend_tier_scales_with_ram` test
- // pins this non-scaling contract). `ram_gb` is read only for the
- // diagnostic log below; RAM->tier scaling is deferred until the higher
- // tiers are productised.
- let ram_gb = device.total_ram_gb();
- let tier = MVP_MAX_TIER;
- tracing::debug!(ram_gb, ?tier, "[local_ai] recommended model tier");
- tier
-}
-
-pub fn vision_mode_for_tier(tier: ModelTier) -> VisionMode {
- match tier {
- ModelTier::Ram1Gb | ModelTier::Ram2To4Gb => VisionMode::Disabled,
- ModelTier::Ram4To8Gb => VisionMode::Ondemand,
- ModelTier::Ram8To16Gb | ModelTier::Ram16PlusGb => VisionMode::Bundled,
- ModelTier::Custom => VisionMode::Bundled,
- }
-}
-
-pub fn vision_mode_for_config(config: &LocalAiConfig) -> VisionMode {
- match current_tier_from_config(config) {
- ModelTier::Custom => {
- if config.vision_model_id.trim().is_empty() {
- VisionMode::Disabled
- } else if config.preload_vision_model {
- VisionMode::Bundled
- } else {
- VisionMode::Ondemand
- }
- }
- tier => vision_mode_for_tier(tier),
- }
-}
-
-pub fn supports_screen_summary(config: &LocalAiConfig) -> bool {
- !matches!(vision_mode_for_config(config), VisionMode::Disabled)
-}
-
-/// Apply a preset to a [`LocalAiConfig`], overwriting model IDs, quantization,
-/// and the `selected_tier` marker.
-pub fn apply_preset_to_config(config: &mut LocalAiConfig, tier: ModelTier) {
- if let Some(preset) = preset_for_tier(tier) {
- tracing::debug!(
- ?tier,
- chat = preset.chat_model_id,
- vision_mode = ?preset.vision_mode,
- "[local_ai] applying preset to config"
- );
- config.model_id = preset.chat_model_id.to_string();
- config.chat_model_id = preset.chat_model_id.to_string();
- config.vision_model_id = preset.vision_model_id.to_string();
- config.embedding_model_id = preset.embedding_model_id.to_string();
- config.quantization = preset.quantization.to_string();
- config.preload_vision_model = matches!(preset.vision_mode, VisionMode::Bundled);
- config.preload_embedding_model = true;
- config.selected_tier = Some(tier.as_str().to_string());
- // Applying a real preset enables the runtime — this is the authoritative
- // activation path. bootstrap's config_with_recommended_tier_if_unselected
- // also sets runtime_enabled = true when opt_in_confirmed is true, but
- // setting it here ensures in-process callers (tests, RPC handlers) see
- // the correct state without relying on bootstrap's post-processing.
- config.runtime_enabled = true;
- } else {
- tracing::debug!("[local_ai] apply_preset_to_config called for custom tier; no-op");
- }
-}
-
-/// Reverse-lookup the current tier from config. Returns `Custom` if none of the
-/// built-in presets match the current model IDs.
-pub fn current_tier_from_config(config: &LocalAiConfig) -> ModelTier {
- if let Some(ref stored) = config.selected_tier {
- if let Some(tier) = ModelTier::from_str_opt(stored) {
- if tier == ModelTier::Custom {
- return ModelTier::Custom;
- }
- if let Some(preset) = preset_for_tier(tier) {
- let vision_matches = if matches!(preset.vision_mode, VisionMode::Disabled) {
- config.vision_model_id.trim().is_empty()
- } else {
- config.vision_model_id == preset.vision_model_id
- };
- if config.chat_model_id == preset.chat_model_id
- && vision_matches
- && config.embedding_model_id == preset.embedding_model_id
- {
- return tier;
- }
- }
- }
- }
-
- for preset in all_presets() {
- let vision_matches = if matches!(preset.vision_mode, VisionMode::Disabled) {
- config.vision_model_id.trim().is_empty()
- } else {
- config.vision_model_id == preset.vision_model_id
- };
- if config.chat_model_id == preset.chat_model_id
- && vision_matches
- && config.embedding_model_id == preset.embedding_model_id
- {
- return preset.tier;
- }
- }
-
- ModelTier::Custom
-}
-
-#[cfg(test)]
-#[path = "presets_tests.rs"]
-mod presets_tests;
-
-#[cfg(test)]
-#[path = "presets_tests_2_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/presets_tests.rs b/crates/openhuman-core/src/inference/presets_tests.rs
deleted file mode 100644
index 99aee38ee1..0000000000
--- a/crates/openhuman-core/src/inference/presets_tests.rs
+++ /dev/null
@@ -1,307 +0,0 @@
-//! Additional unit tests for `local_ai::presets` — colocated test module.
-//!
-//! These tests complement the inline `#[cfg(test)] mod tests` block in `presets.rs`
-//! and focus on coverage gaps: `from_str_opt`, `as_str`, `preset_for_tier`,
-//! `vision_mode_for_tier` for every tier, and `apply_preset_to_config` runtime-enable
-//! semantics.
-
-use super::*;
-use crate::config::schema::LocalAiConfig;
-
-// ── ModelTier helpers ─────────────────────────────────────────────────────
-
-#[test]
-fn from_str_opt_recognizes_all_canonical_names() {
- assert_eq!(ModelTier::from_str_opt("ram_1gb"), Some(ModelTier::Ram1Gb));
- assert_eq!(
- ModelTier::from_str_opt("ram_2_4gb"),
- Some(ModelTier::Ram2To4Gb)
- );
- assert_eq!(
- ModelTier::from_str_opt("ram_4_8gb"),
- Some(ModelTier::Ram4To8Gb)
- );
- assert_eq!(
- ModelTier::from_str_opt("ram_8_16gb"),
- Some(ModelTier::Ram8To16Gb)
- );
- assert_eq!(
- ModelTier::from_str_opt("ram_16_plus_gb"),
- Some(ModelTier::Ram16PlusGb)
- );
- assert_eq!(ModelTier::from_str_opt("custom"), Some(ModelTier::Custom));
-}
-
-#[test]
-fn from_str_opt_recognizes_aliases() {
- assert_eq!(ModelTier::from_str_opt("1gb"), Some(ModelTier::Ram1Gb));
- assert_eq!(ModelTier::from_str_opt("low"), Some(ModelTier::Ram2To4Gb));
- assert_eq!(
- ModelTier::from_str_opt("medium"),
- Some(ModelTier::Ram8To16Gb)
- );
- assert_eq!(
- ModelTier::from_str_opt("high"),
- Some(ModelTier::Ram16PlusGb)
- );
-}
-
-#[test]
-fn from_str_opt_is_case_insensitive() {
- assert_eq!(
- ModelTier::from_str_opt("RAM_2_4GB"),
- Some(ModelTier::Ram2To4Gb)
- );
- assert_eq!(ModelTier::from_str_opt("CUSTOM"), Some(ModelTier::Custom));
-}
-
-#[test]
-fn from_str_opt_returns_none_for_unknown() {
- assert!(ModelTier::from_str_opt("").is_none());
- assert!(ModelTier::from_str_opt("bogus").is_none());
- assert!(ModelTier::from_str_opt("ram_999gb").is_none());
-}
-
-#[test]
-fn as_str_round_trips_through_from_str_opt() {
- let tiers = [
- ModelTier::Ram1Gb,
- ModelTier::Ram2To4Gb,
- ModelTier::Ram4To8Gb,
- ModelTier::Ram8To16Gb,
- ModelTier::Ram16PlusGb,
- ModelTier::Custom,
- ];
- for tier in tiers {
- let s = tier.as_str();
- assert_eq!(
- ModelTier::from_str_opt(s),
- Some(tier),
- "as_str/from_str_opt round-trip failed for {s}"
- );
- }
-}
-
-// ── preset_for_tier ───────────────────────────────────────────────────────
-
-#[test]
-fn preset_for_tier_returns_some_for_all_non_custom_tiers() {
- let expected_tiers = [
- ModelTier::Ram1Gb,
- ModelTier::Ram2To4Gb,
- ModelTier::Ram4To8Gb,
- ModelTier::Ram8To16Gb,
- ModelTier::Ram16PlusGb,
- ];
- for tier in expected_tiers {
- let preset = preset_for_tier(tier);
- assert!(
- preset.is_some(),
- "preset_for_tier({tier:?}) should return Some"
- );
- assert_eq!(preset.unwrap().tier, tier);
- }
-}
-
-#[test]
-fn preset_for_custom_returns_none() {
- assert!(preset_for_tier(ModelTier::Custom).is_none());
-}
-
-// ── vision_mode_for_tier — all 5 tiers ───────────────────────────────────
-
-#[test]
-fn vision_mode_for_tier_ram1gb_is_disabled() {
- assert_eq!(
- vision_mode_for_tier(ModelTier::Ram1Gb),
- VisionMode::Disabled
- );
-}
-
-#[test]
-fn vision_mode_for_tier_ram2_4gb_is_disabled() {
- assert_eq!(
- vision_mode_for_tier(ModelTier::Ram2To4Gb),
- VisionMode::Disabled
- );
-}
-
-#[test]
-fn vision_mode_for_tier_ram4_8gb_is_ondemand() {
- assert_eq!(
- vision_mode_for_tier(ModelTier::Ram4To8Gb),
- VisionMode::Ondemand
- );
-}
-
-#[test]
-fn vision_mode_for_tier_ram8_16gb_is_bundled() {
- assert_eq!(
- vision_mode_for_tier(ModelTier::Ram8To16Gb),
- VisionMode::Bundled
- );
-}
-
-#[test]
-fn vision_mode_for_tier_ram16plus_is_bundled() {
- assert_eq!(
- vision_mode_for_tier(ModelTier::Ram16PlusGb),
- VisionMode::Bundled
- );
-}
-
-// ── preset vision_mode metadata ───────────────────────────────────────────
-
-#[test]
-fn preset_vision_mode_matches_vision_mode_for_tier() {
- for preset in all_presets() {
- let expected = vision_mode_for_tier(preset.tier);
- assert_eq!(
- preset.vision_mode, expected,
- "preset {:?} vision_mode mismatch",
- preset.tier
- );
- }
-}
-
-#[test]
-fn presets_below_4gb_have_no_vision_model_id() {
- let sub_4gb = all_presets()
- .into_iter()
- .filter(|p| matches!(p.tier, ModelTier::Ram1Gb | ModelTier::Ram2To4Gb));
- for preset in sub_4gb {
- assert!(
- preset.vision_model_id.is_empty(),
- "tier {:?} should have empty vision_model_id",
- preset.tier
- );
- }
-}
-
-#[test]
-fn presets_4gb_and_above_have_vision_model_id() {
- let high_tiers = all_presets().into_iter().filter(|p| {
- matches!(
- p.tier,
- ModelTier::Ram4To8Gb | ModelTier::Ram8To16Gb | ModelTier::Ram16PlusGb
- )
- });
- for preset in high_tiers {
- assert!(
- !preset.vision_model_id.is_empty(),
- "tier {:?} should have a non-empty vision_model_id",
- preset.tier
- );
- }
-}
-
-// ── apply_preset_to_config: runtime_enabled semantics ────────────────────
-
-#[test]
-fn apply_preset_enables_runtime() {
- let mut config = LocalAiConfig {
- runtime_enabled: false,
- ..Default::default()
- };
- apply_preset_to_config(&mut config, ModelTier::Ram2To4Gb);
- assert!(
- config.runtime_enabled,
- "apply_preset_to_config should set runtime_enabled = true"
- );
-}
-
-#[test]
-fn apply_preset_custom_is_noop() {
- let mut config = LocalAiConfig {
- chat_model_id: "original-model".to_string(),
- runtime_enabled: false,
- ..Default::default()
- };
- apply_preset_to_config(&mut config, ModelTier::Custom);
- // Custom tier → no-op, so none of the fields change
- assert_eq!(
- config.chat_model_id, "original-model",
- "custom tier should not change chat_model_id"
- );
- assert!(
- !config.runtime_enabled,
- "custom tier should not change runtime_enabled"
- );
-}
-
-#[test]
-fn apply_preset_sets_selected_tier_marker() {
- let mut config = LocalAiConfig::default();
- apply_preset_to_config(&mut config, ModelTier::Ram4To8Gb);
- assert_eq!(
- config.selected_tier.as_deref(),
- Some("ram_4_8gb"),
- "selected_tier should be set to the tier's canonical string"
- );
-}
-
-#[test]
-fn apply_preset_ram8_16gb_sets_preload_vision_model() {
- let mut config = LocalAiConfig::default();
- apply_preset_to_config(&mut config, ModelTier::Ram8To16Gb);
- assert!(
- config.preload_vision_model,
- "bundled vision tiers should set preload_vision_model"
- );
-}
-
-#[test]
-fn apply_preset_ram2_4gb_does_not_set_preload_vision_model() {
- let mut config = LocalAiConfig::default();
- apply_preset_to_config(&mut config, ModelTier::Ram2To4Gb);
- assert!(
- !config.preload_vision_model,
- "disabled vision tier should not set preload_vision_model"
- );
-}
-
-// ── current_tier_from_config — selected_tier marker vs model IDs ──────────
-
-#[test]
-fn current_tier_prefers_selected_tier_when_models_match() {
- let mut config = LocalAiConfig::default();
- apply_preset_to_config(&mut config, ModelTier::Ram4To8Gb);
- // After apply the selected_tier is "ram_4_8gb" and models match the preset
- assert_eq!(current_tier_from_config(&config), ModelTier::Ram4To8Gb);
-}
-
-#[test]
-fn current_tier_falls_back_to_model_scan_when_no_selected_tier() {
- let mut config = LocalAiConfig::default();
- apply_preset_to_config(&mut config, ModelTier::Ram8To16Gb);
- config.selected_tier = None; // clear the marker
- // The model IDs still match Ram8To16Gb so the scan should find it
- assert_eq!(current_tier_from_config(&config), ModelTier::Ram8To16Gb);
-}
-
-// ── supports_screen_summary ────────────────────────────────────────────────
-
-#[test]
-fn supports_screen_summary_false_below_4gb() {
- let mut config = LocalAiConfig::default();
- apply_preset_to_config(&mut config, ModelTier::Ram1Gb);
- assert!(!supports_screen_summary(&config));
- apply_preset_to_config(&mut config, ModelTier::Ram2To4Gb);
- assert!(!supports_screen_summary(&config));
-}
-
-#[test]
-fn supports_screen_summary_true_at_4gb_and_above() {
- let mut config = LocalAiConfig::default();
- for tier in [
- ModelTier::Ram4To8Gb,
- ModelTier::Ram8To16Gb,
- ModelTier::Ram16PlusGb,
- ] {
- apply_preset_to_config(&mut config, tier);
- assert!(
- supports_screen_summary(&config),
- "tier {tier:?} should support screen summary"
- );
- }
-}
diff --git a/crates/openhuman-core/src/inference/presets_tests_2_tests.rs b/crates/openhuman-core/src/inference/presets_tests_2_tests.rs
deleted file mode 100644
index b9880c7084..0000000000
--- a/crates/openhuman-core/src/inference/presets_tests_2_tests.rs
+++ /dev/null
@@ -1,202 +0,0 @@
-use super::*;
-
-fn test_device(total_ram_gb: u64) -> DeviceProfile {
- DeviceProfile {
- total_ram_bytes: total_ram_gb * 1024 * 1024 * 1024,
- cpu_count: 4,
- cpu_brand: String::new(),
- os_name: String::new(),
- os_version: String::new(),
- has_gpu: false,
- gpu_description: None,
- }
-}
-
-#[test]
-fn recommend_tier_scales_with_ram() {
- assert_eq!(recommend_tier(&test_device(1)), ModelTier::Ram2To4Gb);
- assert_eq!(recommend_tier(&test_device(3)), ModelTier::Ram2To4Gb);
- assert_eq!(recommend_tier(&test_device(4)), ModelTier::Ram2To4Gb);
- assert_eq!(recommend_tier(&test_device(8)), ModelTier::Ram2To4Gb);
- assert_eq!(recommend_tier(&test_device(32)), ModelTier::Ram2To4Gb);
-}
-
-#[test]
-fn mvp_allowed_tiers() {
- assert!(!ModelTier::Ram1Gb.is_mvp_allowed());
- assert!(ModelTier::Ram2To4Gb.is_mvp_allowed());
- assert!(!ModelTier::Ram4To8Gb.is_mvp_allowed());
- assert!(!ModelTier::Ram8To16Gb.is_mvp_allowed());
- assert!(!ModelTier::Ram16PlusGb.is_mvp_allowed());
- assert!(!ModelTier::Custom.is_mvp_allowed());
-}
-
-#[test]
-fn mvp_presets_only_returns_allowed_tiers() {
- let presets = mvp_presets();
- assert_eq!(presets.len(), 1);
- assert_eq!(presets[0].tier, ModelTier::Ram2To4Gb);
-}
-
-#[test]
-fn preset_application_and_round_trip() {
- let mut config = LocalAiConfig::default();
- apply_preset_to_config(&mut config, ModelTier::Ram2To4Gb);
- assert_eq!(config.chat_model_id, "gemma3:1b-it-qat");
- assert_eq!(config.selected_tier, Some("ram_2_4gb".to_string()));
- assert_eq!(current_tier_from_config(&config), ModelTier::Ram2To4Gb);
- assert!(!config.preload_vision_model);
- assert_eq!(vision_mode_for_config(&config), VisionMode::Disabled);
-}
-
-#[test]
-fn custom_detection_when_models_dont_match() {
- let mut config = LocalAiConfig::default();
- config.chat_model_id = "some-other-model:latest".to_string();
- config.selected_tier = None;
- assert_eq!(current_tier_from_config(&config), ModelTier::Custom);
-}
-
-#[test]
-fn all_presets_returns_five_tiers() {
- let presets = all_presets();
- assert_eq!(presets.len(), 5);
- assert_eq!(presets[0].tier, ModelTier::Ram1Gb);
- assert_eq!(presets[1].tier, ModelTier::Ram2To4Gb);
- assert_eq!(presets[2].tier, ModelTier::Ram4To8Gb);
- assert_eq!(presets[3].tier, ModelTier::Ram8To16Gb);
- assert_eq!(presets[4].tier, ModelTier::Ram16PlusGb);
-}
-
-#[test]
-fn default_config_maps_to_balanced_tier() {
- let config = LocalAiConfig::default();
- assert_eq!(current_tier_from_config(&config), ModelTier::Ram2To4Gb);
- assert_eq!(vision_mode_for_config(&config), VisionMode::Disabled);
-}
-
-#[test]
-fn device_supports_local_ai_honors_min_ram_floor() {
- assert!(!device_supports_local_ai(&test_device(1)));
- assert!(!device_supports_local_ai(&test_device(4)));
- assert!(!device_supports_local_ai(&test_device(7)));
- assert!(device_supports_local_ai(&test_device(8)));
- assert!(device_supports_local_ai(&test_device(16)));
- assert!(device_supports_local_ai(&test_device(64)));
-}
-
-#[test]
-fn should_default_to_cloud_fallback_below_floor() {
- assert!(should_default_to_cloud_fallback(&test_device(1)));
- assert!(should_default_to_cloud_fallback(&test_device(4)));
- assert!(should_default_to_cloud_fallback(&test_device(7)));
- assert!(!should_default_to_cloud_fallback(&test_device(8)));
- assert!(!should_default_to_cloud_fallback(&test_device(16)));
-}
-
-#[test]
-fn built_in_vision_modes_match_expectations() {
- let mut config = LocalAiConfig::default();
- apply_preset_to_config(&mut config, ModelTier::Ram2To4Gb);
- assert_eq!(vision_mode_for_config(&config), VisionMode::Disabled);
- assert!(!supports_screen_summary(&config));
-
- apply_preset_to_config(&mut config, ModelTier::Ram4To8Gb);
- assert_eq!(vision_mode_for_config(&config), VisionMode::Ondemand);
- assert!(supports_screen_summary(&config));
-
- apply_preset_to_config(&mut config, ModelTier::Ram16PlusGb);
- assert_eq!(vision_mode_for_config(&config), VisionMode::Bundled);
-}
-
-/// GH #5055 / #5146 §1.3: every preset must name a model that actually
-/// exists on the Ollama library and is fully qualified, so `ollama pull`
-/// can fetch it and the allowlist does not silently redirect the user.
-///
-/// The original #5055 form of this test asserted the narrower fact "no id
-/// may start with `gemma4:`", because no `gemma4` namespace existed then.
-/// Gemma 4 has since been published (`gemma4:e4b-it-q8_0` resolves against
-/// `registry.ollama.ai`), so that assertion encoded a fact that expired.
-/// The durable invariant is the shape check below plus the
-/// `preset_chat_models_are_allowlisted_and_resolve_unchanged` cross-check
-/// in `model_ids`.
-#[test]
-fn preset_model_ids_are_fully_qualified() {
- for preset in all_presets() {
- for (field, id) in [
- ("chat", preset.chat_model_id),
- ("vision", preset.vision_model_id),
- ("embedding", preset.embedding_model_id),
- ] {
- if id.is_empty() {
- // Only `vision` is legitimately empty (vision disabled).
- assert_eq!(
- field, "vision",
- "preset {:?} {field} model must not be empty",
- preset.tier
- );
- continue;
- }
- // `bge-m3` is deliberately exempt rather than retagged to
- // `bge-m3:latest` (greptile, #5253). The bare id is the
- // canonical spelling across the embedding stack: it is the
- // entry in `model_ids::MVP_ALLOWED_EMBEDDING_MODELS`, the
- // `embeddings::catalog` id, and what `normalize_embed_model_id`
- // collapses `bge-m3:latest` *to*. Retagging the preset alone
- // would be silently rewritten back by
- // `enforce_mvp_embedding_allowlist`; retagging all of them is a
- // cross-cutting rename that must also migrate configs already
- // persisting `bge-m3` - disproportionate to a cosmetic tag.
- assert!(
- id.contains(':') || id == "bge-m3",
- "preset {:?} {field} model `{id}` must be a fully-qualified \
- `<model>:<tag>` id",
- preset.tier
- );
- }
- }
-}
-
-/// #5146 §Part 1: a preset that declares a vision mode must name a model
-/// that can actually accept images.
-///
-/// The 16 GB+ tier previously used `gemma3n:e4b-it-q8_0` as its
-/// `vision_model_id`. Gemma 3n is text-only on Ollama, and Ollama does not
-/// reject an `images` array sent to a text-only model — it drops the
-/// images and answers from the prompt alone, so the user got a fluent,
-/// fabricated description of an image the model never saw.
-#[test]
-fn preset_vision_models_are_vision_capable() {
- use tinyinference::model::model_id_supports_vision;
-
- for preset in all_presets() {
- match preset.vision_mode {
- VisionMode::Disabled => assert!(
- preset.vision_model_id.is_empty(),
- "preset {:?} disables vision but names `{}`",
- preset.tier,
- preset.vision_model_id
- ),
- VisionMode::Ondemand | VisionMode::Bundled => assert!(
- model_id_supports_vision(preset.vision_model_id),
- "preset {:?} routes vision at `{}`, which is not vision-capable",
- preset.tier,
- preset.vision_model_id
- ),
- }
- }
-}
-
-/// The 16 GB+ tier must name an allowlisted chat model, so selecting the
-/// preset is not immediately redirected back to the default by
-/// `enforce_mvp_chat_allowlist`, and that model must be multimodal so the
-/// tier's `Bundled` vision mode is real rather than nominal.
-#[test]
-fn high_tier_preset_uses_one_multimodal_build_for_chat_and_vision() {
- use tinyinference::model::model_id_supports_vision;
-
- let preset = preset_for_tier(ModelTier::Ram16PlusGb).expect("16 GB+ preset");
- assert_eq!(preset.chat_model_id, "gemma4:e4b-it-q8_0");
- assert_eq!(preset.vision_model_id, preset.chat_model_id);
- assert!(model_id_supports_vision(preset.vision_model_id));
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/README.md b/crates/openhuman-core/src/inference/provider/claude_code/README.md
deleted file mode 100644
index 2f83bb6c8f..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/README.md
+++ /dev/null
@@ -1,121 +0,0 @@
-# claude_code
-
-`ChatModel<()>` implementation that drives Anthropic's `claude` CLI as a
-subprocess instead of calling the Messages API directly. Selected by the
-`claude-code:<model>` provider string (`PROVIDER_PREFIX`) — see
-[Selection](#selection).
-
-`mod.rs`'s module doc still describes the original Phase 2 cut ("native CC
-built-ins disabled at the caller; v2 will expose OpenHuman's tools back over
-MCP"). `driver.rs` has since moved past that: the loopback MCP bridge is in
-place, and CC's built-in tools do run — under a user-chosen permission
-posture (below).
-
-## CLI invocation
-
-`ClaudeCodeProvider::run_chat` acquires one of `MAX_CONCURRENT_TURNS` (4)
-`Semaphore` permits, then `driver::run_turn` spawns
-`claude -p --input-format stream-json --output-format stream-json --verbose
---include-partial-messages --add-dir <action_dir> --permission-mode
-<acceptEdits|bypassPermissions> --session-id <uuid>|--resume <uuid> --model
-<model>`, plus `--append-system-prompt` (written to a per-turn scratch file),
-`--mcp-config <scratch>/openhuman-mcp-config.json --strict-mcp-config` when the
-loopback MCP server started, and `--disallowedTools Bash,BashOutput,KillShell,
-WebFetch,WebSearch,Task` (`DISALLOWED_CC_BUILTINS`) unless full access is on.
-`--session-id` is used on a new CC session and `--resume` afterwards; the UUID
-comes from `session_store.rs`, keyed by a SHA-256 hash of the conversation's
-first user message (`thread_key_from_messages`) because the real OpenHuman
-thread id is not yet plumbed through `ChatRequest`. `cwd` is
-`config.action_dir` (the project root the CLI's file tools operate in).
-
-## File map
-
-| File | Role |
-| --- | --- |
-| `mod.rs` | `ClaudeCodeProvider` (`ChatModel<()>` impl), `PROVIDER_PREFIX`, `MAX_CONCURRENT_TURNS`, `workspace_dir_from_config` (= parent of `config.config_path`, i.e. `~/.openhuman` — deliberately *not* `Config::workspace_dir` or `action_dir`), `from_env` (CLI discovery + version gate + key resolution), `run_chat`, `thread_key_from_messages`. |
-| `auth.rs` | `resolve()` → `(AuthSource, Option<key>)`: which credential the spawned CLI will use. |
-| `auth_status.rs` | `probe()` — the CLI's own auth state (API key env / subscription login / signed out / unknown) for the settings UI, via `claude auth status --json`. |
-| `driver.rs` | `run_turn`: per-turn scratch dir, permission posture, macOS Seatbelt jail, MCP config, argv, stdin/stdout piping, `DEFAULT_TURN_TIMEOUT_SECS` (900, override `OPENHUMAN_CLAUDE_CODE_TURN_TIMEOUT_SECS`), stderr diagnostics cap. |
-| `event_mapper.rs` | `ClaudeCodeEvent` → `ProviderDelta` / aggregated `ChatResponse`. `tool_use` blocks are tracked only to keep their `input_json_delta`s out of the visible text and are **not** surfaced as `ToolCall`s: the CLI is self-executing, so a tool block in the stream has already run; surfacing it would make the tinyagents harness try to dispatch `Read`/`Bash`/… and loop on "unknown tool". |
-| `input_builder.rs` | `build_stdin`: JSONL user turns for `--input-format stream-json` — full history on a new session, only the last user turn on `--resume`; inline images re-hydrated from `agent::multimodal` markers (5 MiB cap). |
-| `session_store.rs` | `SessionStore`: thread key → CC session UUID v4, persisted in `<workspace>/claude-code-sessions.json`. |
-| `settings.rs` | `ClaudeCodeSettings { full_access }` persisted in `<workspace>/claude_code_settings.json` next to `config.toml`; written by the `inference.claude_code_set_full_access` RPC. |
-| `stream_parser.rs` | Line-buffered JSONL parser for `--output-format stream-json`; permissive `serde_json::Value` payloads so a minor CLI schema bump does not break parsing. |
-| `types.rs` | `MIN_CLI_VERSION` (`2.0.0`), `CliStatus`, `BRAND_LABEL`. |
-| `version_check.rs` | `resolve_binary` (`OPENHUMAN_CLAUDE_CLI` env → `PATH` → well-known install dirs, because GUI launches inherit a stripped launchd `PATH`) and `probe()` against `MIN_CLI_VERSION`. |
-
-## Auth resolution order
-
-1. Process env `ANTHROPIC_API_KEY` (highest precedence) — `auth.rs::resolve`
- returns `AuthSource::EnvApiKey` and the key is set on the child at spawn.
-2. Otherwise `AuthSource::CliCredentials`: the env var is *not* set and the
- CLI uses its own login (`~/.claude/.credentials.json`, or the Keychain on
- macOS).
-3. `auth_status.rs` reports the richer state for the UI by spawning
- `claude auth status --json` (bounded by `AUTH_STATUS_TIMEOUT` = 10 s)
- rather than reading the credentials file, because on macOS the CLI stores
- credentials in the Keychain (service `Claude Code-credentials`) — a
- logged-in macOS user would otherwise be misreported as signed out. Older
- CLIs without `auth status` map to `AuthSource::Unknown`, never to
- "signed out".
-4. Picking up an Anthropic key from OpenHuman's auth-profile store and
- Claude Pro/Max OAuth are both future work (v1.1 / v2 per `auth.rs`).
-
-Tests that touch `ANTHROPIC_API_KEY` / `OPENHUMAN_CLAUDE_CODE_*` serialize
-through `mod.rs::ENV_TEST_LOCK`.
-
-## Permission posture, sandbox, and loopback MCP
-
-The user opts into Claude Code explicitly, so its toolset is not restricted
-beyond a permission posture that is the user's choice
-(`driver.rs::claude_code_full_access`):
-
-- default: `--permission-mode acceptEdits` plus `--disallowedTools` for
- shell, network, and `Task` fan-out — file reads/edits in `action_dir` only;
-- full access (`settings.rs` toggle, or `OPENHUMAN_CLAUDE_CODE_PERMISSION_MODE=
- bypass|bypassPermissions|full`): `--permission-mode bypassPermissions` and
- the entire CC toolset including Bash.
-
-On macOS the spawn is additionally wrapped in a Seatbelt jail
-(`sandbox-exec -p <profile>`, on by default when `/usr/bin/sandbox-exec`
-exists; opt out with `OPENHUMAN_CLAUDE_CODE_SANDBOX=0`). The profile allows
-everything the user can do *except* reads and writes under the entire
-`~/.openhuman[-staging]` tree — the whole root, not just the per-user
-workspace subdir, because `workspace_dir` is a subdirectory of it and a
-narrower deny would leave siblings readable. This is the OS-level counterpart
-of `is_workspace_internal_path`. Linux and Windows have no OS wall yet; CC
-runs unconfined there.
-
-That deny would also cut the coding agent off from OpenHuman's memory and
-tools, so `driver.rs` calls `crate::mcp::server::ensure_local_http()` and
-writes a per-turn `--mcp-config` pointing at the in-process HTTP MCP server
-(`crate::mcp::server::local`). The MCP server runs in the **unjailed core
-process**, not as a child of the sandboxed `claude`, and is reached over
-loopback with a per-process bearer token carried in the config's
-`Authorization` header, so it keeps full access to `~/.openhuman` while CC's
-raw tools stay denied that path. If `ensure_local_http` fails (for example a
-build without the `http-server` feature), CC runs without OpenHuman MCP tools
-and the turn still proceeds.
-
-## Selection
-
-`../factory/chat_model.rs` (`create_chat_model*`) calls
-`try_create_claude_code_chat_model`, defined in `../factory/subprocess_providers.rs`: it
-strips `PROVIDER_PREFIX` from the resolved provider string, rejects an empty
-model id, runs `enforce_local_only_inference` and `verify_session_active`,
-emits the inference egress descriptor, and builds
-`ClaudeCodeProvider::from_env(model, workspace_dir_from_config(config),
-config.action_dir)`. An `@<temp>` suffix is accepted but ignored (logged).
-`from_env` fails fast with an actionable error when the CLI is missing,
-outdated (`MIN_CLI_VERSION`), or unusable. `../factory/routing.rs` and
-`../factory/access_gates.rs` also special-case the prefix in
-`route_has_usable_credentials` (a CC route carries its own credentials) and
-`external_provider_label` ("Claude Code CLI" in Privacy-Mode messages).
-
-## Tests
-
-Per-file `*_tests.rs` alongside each module (`auth_tests.rs`,
-`auth_status_tests.rs`, `driver_tests.rs`, `event_mapper_tests.rs`,
-`input_builder_tests.rs`, `session_store_tests.rs`, `settings_tests.rs`,
-`stream_parser_tests.rs`, `version_check_tests.rs`) plus `mod_tests.rs` for
-the `ModelProfile` and session-key hashing.
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/auth.rs b/crates/openhuman-core/src/inference/provider/claude_code/auth.rs
deleted file mode 100644
index ab9da11c17..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/auth.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-//! Resolve an `ANTHROPIC_API_KEY` for the spawned `claude` CLI.
-//!
-//! v1 resolution order:
-//! 1. Process env `ANTHROPIC_API_KEY` (highest precedence).
-//! 2. `~/.claude/.credentials.json` — only used if the CLI is already
-//! logged in via `claude login`. We pass it through transparently by
-//! *not* setting `ANTHROPIC_API_KEY`; the CLI then reads its own
-//! credentials file.
-//!
-//! v1.1 will wire OpenHuman `AuthService` (auth-profiles.json) so an
-//! Anthropic key stored in settings is picked up automatically.
-//! Subscription / OAuth auth (Claude Pro/Max) deferred to v2.
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum AuthSource {
- /// Explicit API key — pass via `ANTHROPIC_API_KEY` env var.
- EnvApiKey,
- /// No explicit key resolved. Defer to whatever the CLI finds in
- /// `~/.claude/.credentials.json`.
- CliCredentials,
-}
-
-/// Probe sources in priority order. Returns the resolved API key plus the
-/// origin label (for logging) when found. The returned key is only the
-/// key value — call-sites set env on spawn, never log it.
-pub fn resolve() -> (AuthSource, Option<String>) {
- if let Ok(k) = std::env::var("ANTHROPIC_API_KEY") {
- let k = k.trim();
- if !k.is_empty() {
- return (AuthSource::EnvApiKey, Some(k.to_string()));
- }
- }
- (AuthSource::CliCredentials, None)
-}
-
-#[cfg(test)]
-#[path = "auth_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/auth_status.rs b/crates/openhuman-core/src/inference/provider/claude_code/auth_status.rs
deleted file mode 100644
index 59ddc6f4aa..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/auth_status.rs
+++ /dev/null
@@ -1,271 +0,0 @@
-//! Detect Claude Code CLI auth state via the CLI's own structured probe.
-//!
-//! Resolution order:
-//! 1. `ANTHROPIC_API_KEY` env var present → `ApiKeyEnv` (the spawned CLI
-//! inherits it, so it wins regardless of any logged-in session).
-//! 2. `claude auth status --json` → parse the structured result.
-//!
-//! Why spawn the CLI instead of reading `~/.claude/.credentials.json`:
-//! on **macOS** the `claude` CLI stores credentials in the Keychain
-//! (service `Claude Code-credentials`), *not* in that file. A logged-in
-//! macOS user therefore had no credentials file and was misreported as
-//! signed out — on the primary shipping platform. `claude auth status`
-//! abstracts file-vs-Keychain for us and works on macOS, Linux, and
-//! Windows. It returns only non-secret metadata (login flag, auth method,
-//! account email, subscription type) — never the access/refresh token —
-//! so we keep the "never read the token" principle.
-//!
-//! Older CLIs (below the `auth status` cut) yield a non-zero exit or
-//! non-JSON output; we map those to [`AuthSource::Unknown`] and never to
-//! `None`, so we never tell a signed-in user they're signed out just
-//! because their binary predates the subcommand.
-
-use std::io::Read as _;
-use std::process::{Command, Stdio};
-use std::time::{Duration, SystemTime};
-
-use serde::{Deserialize, Serialize};
-use wait_timeout::ChildExt as _;
-
-use super::version_check;
-
-/// Hard ceiling on the `claude auth status --json` subprocess. The CLI is an
-/// external binary that can wedge (stuck keychain prompt, hung network); a
-/// bounded wait keeps the auth-status RPC — and the settings modal that awaits
-/// it — from hanging forever. On timeout we kill the child and report
-/// `Unknown` (never "signed out").
-const AUTH_STATUS_TIMEOUT: Duration = Duration::from_secs(10);
-
-/// Discriminator for who actually authenticates the spawned CLI.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case", tag = "source")]
-pub enum AuthSource {
- /// Claude Pro / Max subscription — `claude auth status` reports
- /// `loggedIn: true` with `authMethod: "claude.ai"`. Account email +
- /// subscription type returned best-effort; absent when the schema
- /// drifts.
- Subscription {
- account_email: Option<String>,
- /// `"max"` / `"pro"` etc., for display. Absent when not reported.
- subscription_type: Option<String>,
- /// Reserved for a future expiry field; `claude auth status` does
- /// not currently expose one, so this is always `None` today. Kept
- /// for wire stability with the prior schema.
- expires_at: Option<String>,
- },
- /// `ANTHROPIC_API_KEY` is set in the core process env, or the CLI is
- /// logged in via an API key rather than a claude.ai subscription. The
- /// spawned CLI authenticates with that key.
- ApiKeyEnv,
- /// `claude auth status` reported `loggedIn: false`. The CLI will fail
- /// any chat with an auth error until the user signs in.
- None,
- /// Could not determine the sign-in state — binary missing, spawn
- /// failed, non-zero exit (e.g. a CLI older than `auth status`), or
- /// unparseable output. We surface this as "couldn't determine" and a
- /// Reconnect affordance, **never** as signed-out.
- Unknown { reason: Option<String> },
-}
-
-/// Returned by the `claude_code_auth_status` RPC. Snake-case Serde so the
-/// TS side discriminates on `source`.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct AuthStatus {
- #[serde(flatten)]
- pub source: AuthSource,
- /// Unix seconds when this probe ran — UI shows "last checked" so users
- /// can tell a stale subscription badge from a fresh one.
- pub last_checked: u64,
-}
-
-/// Parse the stdout of `claude auth status --json` into an [`AuthSource`].
-///
-/// Pure function — no spawn, no env — so it is unit-testable. Observed
-/// shape (claude 2.1.175):
-/// ```json
-/// {
-/// "loggedIn": true,
-/// "authMethod": "claude.ai",
-/// "apiProvider": "firstParty",
-/// "email": "[email protected]",
-/// "subscriptionType": "max"
-/// }
-/// ```
-pub fn parse_auth_status_json(raw: &str) -> AuthSource {
- let val: serde_json::Value = match serde_json::from_str(raw) {
- Ok(v) => v,
- Err(e) => {
- return AuthSource::Unknown {
- reason: Some(format!("unparseable `claude auth status` JSON: {e}")),
- };
- }
- };
-
- // The single field we treat as load-bearing. If it's absent the shape
- // is foreign to us — refuse to guess, return Unknown.
- let logged_in = match val.get("loggedIn").and_then(serde_json::Value::as_bool) {
- Some(b) => b,
- None => {
- return AuthSource::Unknown {
- reason: Some("`claude auth status` JSON missing `loggedIn`".to_string()),
- };
- }
- };
-
- if !logged_in {
- return AuthSource::None;
- }
-
- let auth_method = val
- .get("authMethod")
- .and_then(serde_json::Value::as_str)
- .unwrap_or("");
-
- // `authMethod: "claude.ai"` is the Pro/Max OAuth subscription. Any other
- // *named* logged-in method (console API key, etc.) authenticates via a key,
- // so we surface it like an API-key source. A MISSING/empty `authMethod`
- // (schema drift) must NOT be reported as a definite signed-in state —
- // the settings UI renders `api_key_env` as "signed in", so fall through to
- // `unknown` ("couldn't determine") instead.
- match auth_method {
- "claude.ai" => {
- let account_email = val
- .get("email")
- .and_then(serde_json::Value::as_str)
- .map(str::to_string);
- let subscription_type = val
- .get("subscriptionType")
- .and_then(serde_json::Value::as_str)
- .map(str::to_string);
- AuthSource::Subscription {
- account_email,
- subscription_type,
- expires_at: None,
- }
- }
- "" => AuthSource::Unknown {
- reason: Some("`claude auth status` reported loggedIn without authMethod".to_string()),
- },
- _ => AuthSource::ApiKeyEnv,
- }
-}
-
-/// Spawn `claude auth status --json` and classify the result. Honors the
-/// `OPENHUMAN_CLAUDE_CLI` override via [`version_check::resolve_binary`].
-fn probe_via_cli() -> AuthSource {
- let Some(bin) = version_check::resolve_binary() else {
- log::debug!("[claude-code][auth] no `claude` binary on PATH; auth state unknown");
- return AuthSource::Unknown {
- reason: Some("`claude` CLI not found on PATH".to_string()),
- };
- };
-
- let bin_str = bin.display().to_string();
- let mut child = match Command::new(&bin)
- .args(["auth", "status", "--json"])
- .env("PATH", super::driver::child_path_with_user_bins(&bin))
- .stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
- {
- Ok(c) => c,
- Err(e) => {
- log::warn!("[claude-code][auth] spawn failed bin={bin_str} err={e}");
- return AuthSource::Unknown {
- reason: Some(format!("spawn failed: {e}")),
- };
- }
- };
-
- // Bounded wait — the CLI is external and can hang. On timeout, kill it and
- // report `Unknown` rather than letting the RPC (and the settings modal)
- // wait forever.
- let status = match child.wait_timeout(AUTH_STATUS_TIMEOUT) {
- Ok(Some(s)) => s,
- Ok(None) => {
- log::warn!(
- "[claude-code][auth] `claude auth status` timed out after {}s; killing bin={bin_str}",
- AUTH_STATUS_TIMEOUT.as_secs()
- );
- let _ = child.kill();
- let _ = child.wait();
- return AuthSource::Unknown {
- reason: Some(format!(
- "`claude auth status` timed out after {}s",
- AUTH_STATUS_TIMEOUT.as_secs()
- )),
- };
- }
- Err(e) => {
- log::warn!("[claude-code][auth] wait failed bin={bin_str} err={e}");
- let _ = child.kill();
- let _ = child.wait();
- return AuthSource::Unknown {
- reason: Some(format!("wait failed: {e}")),
- };
- }
- };
-
- if !status.success() {
- // Most likely an older CLI without the `auth status` subcommand.
- // Never downgrade to signed-out on this path.
- let mut stderr = String::new();
- if let Some(mut s) = child.stderr.take() {
- let _ = s.read_to_string(&mut stderr);
- }
- log::debug!(
- "[claude-code][auth] `claude auth status` exit={} stderr={}",
- status,
- stderr.trim()
- );
- return AuthSource::Unknown {
- reason: Some(format!("`claude auth status` exited {status}")),
- };
- }
-
- let mut stdout = String::new();
- if let Some(mut s) = child.stdout.take() {
- let _ = s.read_to_string(&mut stdout);
- }
- let source = parse_auth_status_json(stdout.trim());
- log::debug!(
- "[claude-code][auth] probe classified source={}",
- match &source {
- AuthSource::Subscription { .. } => "subscription",
- AuthSource::ApiKeyEnv => "api_key_env",
- AuthSource::None => "none",
- AuthSource::Unknown { .. } => "unknown",
- }
- );
- source
-}
-
-/// Probe auth state. Spawns the `claude` CLI (same cost class as the
-/// `claude --version` probe) — keep call-sites on-demand, never on a hot
-/// path.
-pub fn probe() -> AuthStatus {
- let last_checked = SystemTime::now()
- .duration_since(SystemTime::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0);
-
- if let Ok(k) = std::env::var("ANTHROPIC_API_KEY") {
- if !k.trim().is_empty() {
- log::debug!("[claude-code][auth] ANTHROPIC_API_KEY present → api_key_env");
- return AuthStatus {
- source: AuthSource::ApiKeyEnv,
- last_checked,
- };
- }
- }
-
- AuthStatus {
- source: probe_via_cli(),
- last_checked,
- }
-}
-
-#[cfg(test)]
-#[path = "auth_status_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/auth_status_tests.rs b/crates/openhuman-core/src/inference/provider/claude_code/auth_status_tests.rs
deleted file mode 100644
index 5a6067f25d..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/auth_status_tests.rs
+++ /dev/null
@@ -1,98 +0,0 @@
-use super::*;
-
-#[test]
-fn parses_claude_ai_subscription() {
- let raw = r#"{
- "loggedIn": true,
- "authMethod": "claude.ai",
- "apiProvider": "firstParty",
- "email": "[email protected]",
- "subscriptionType": "max"
- }"#;
- match parse_auth_status_json(raw) {
- AuthSource::Subscription {
- account_email,
- subscription_type,
- expires_at,
- } => {
- assert_eq!(account_email.as_deref(), Some("[email protected]"));
- assert_eq!(subscription_type.as_deref(), Some("max"));
- assert!(expires_at.is_none());
- }
- other => panic!("expected Subscription, got {other:?}"),
- }
-}
-
-#[test]
-fn subscription_tolerates_missing_email_and_type() {
- let raw = r#"{ "loggedIn": true, "authMethod": "claude.ai" }"#;
- match parse_auth_status_json(raw) {
- AuthSource::Subscription {
- account_email,
- subscription_type,
- ..
- } => {
- assert!(account_email.is_none());
- assert!(subscription_type.is_none());
- }
- other => panic!("expected Subscription, got {other:?}"),
- }
-}
-
-#[test]
-fn logged_in_via_api_key_method_maps_to_api_key_env() {
- let raw = r#"{ "loggedIn": true, "authMethod": "console", "apiProvider": "console" }"#;
- assert_eq!(parse_auth_status_json(raw), AuthSource::ApiKeyEnv);
-}
-
-#[test]
-fn logged_in_without_auth_method_is_unknown_not_api_key() {
- // Schema drift: `loggedIn: true` but no `authMethod`. Must NOT be
- // reported as the definite `api_key_env` signed-in state — fall to
- // `unknown` so the UI shows "couldn't determine" instead.
- let raw = r#"{ "loggedIn": true }"#;
- match parse_auth_status_json(raw) {
- AuthSource::Unknown { reason } => assert!(reason.is_some()),
- other => panic!("expected Unknown, got {other:?}"),
- }
-}
-
-#[test]
-fn logged_out_maps_to_none() {
- let raw = r#"{ "loggedIn": false }"#;
- assert_eq!(parse_auth_status_json(raw), AuthSource::None);
-}
-
-#[test]
-fn missing_logged_in_field_is_unknown() {
- let raw = r#"{ "authMethod": "claude.ai", "email": "[email protected]" }"#;
- match parse_auth_status_json(raw) {
- AuthSource::Unknown { reason } => assert!(reason.is_some()),
- other => panic!("expected Unknown, got {other:?}"),
- }
-}
-
-#[test]
-fn malformed_json_is_unknown_not_signed_out() {
- match parse_auth_status_json("not json at all") {
- AuthSource::Unknown { reason } => assert!(reason.is_some()),
- other => panic!("expected Unknown, got {other:?}"),
- }
-}
-
-#[test]
-fn api_key_env_short_circuits_probe() {
- let _env = super::super::ENV_TEST_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let prev = std::env::var("ANTHROPIC_API_KEY").ok();
- std::env::set_var("ANTHROPIC_API_KEY", "sk-ant-test");
-
- let s = probe();
- assert_eq!(s.source, AuthSource::ApiKeyEnv);
-
- match prev {
- Some(v) => std::env::set_var("ANTHROPIC_API_KEY", v),
- None => std::env::remove_var("ANTHROPIC_API_KEY"),
- }
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/auth_tests.rs b/crates/openhuman-core/src/inference/provider/claude_code/auth_tests.rs
deleted file mode 100644
index 968a386993..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/auth_tests.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-use super::*;
-
-#[test]
-fn defaults_to_cli_credentials_without_env() {
- let _env = super::super::ENV_TEST_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let prev = std::env::var("ANTHROPIC_API_KEY").ok();
- std::env::remove_var("ANTHROPIC_API_KEY");
-
- let (src, key) = resolve();
- assert_eq!(src, AuthSource::CliCredentials);
- assert!(key.is_none());
-
- if let Some(v) = prev {
- std::env::set_var("ANTHROPIC_API_KEY", v);
- }
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/driver.rs b/crates/openhuman-core/src/inference/provider/claude_code/driver.rs
deleted file mode 100644
index 4bd7de9e3c..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/driver.rs
+++ /dev/null
@@ -1,591 +0,0 @@
-//! Spawn the `claude` CLI for one chat turn, stream its stdout into the
-//! event mapper, and return an aggregated `ChatResponse`.
-//!
-//! The driver does *not* own concurrency limits; the `ClaudeCodeProvider`
-//! holds a `Semaphore` and acquires a permit before calling this.
-
-use std::path::PathBuf;
-use std::process::Stdio;
-use std::sync::Arc;
-use std::time::Duration;
-
-use serde_json::json;
-use tokio::io::{AsyncReadExt, AsyncWriteExt};
-use tokio::process::Command;
-use tokio::sync::mpsc;
-
-/// Hard timeout per turn (PLAN §8). If the CLI hangs (network stall,
-/// infinite loop, MCP deadlock) we kill the child and surface a timeout.
-const DEFAULT_TURN_TIMEOUT_SECS: u64 = 900;
-
-fn turn_timeout() -> Duration {
- let secs = std::env::var("OPENHUMAN_CLAUDE_CODE_TURN_TIMEOUT_SECS")
- .ok()
- .and_then(|raw| raw.trim().parse::<u64>().ok())
- .filter(|secs| *secs > 0)
- .unwrap_or(DEFAULT_TURN_TIMEOUT_SECS);
- Duration::from_secs(secs)
-}
-
-fn parse_error_line_shape(line: &str) -> &'static str {
- match line.trim_start().chars().next() {
- Some('{') => "json object",
- Some('[') => "json array",
- Some('"') => "json string",
- Some(_) => "non-json",
- None => "blank",
- }
-}
-
-fn parse_error_log_line(ev: &ClaudeCodeEvent) -> Option<String> {
- let ClaudeCodeEvent::ParseError { line, reason } = ev else {
- return None;
- };
- Some(format!(
- "[claude-code][driver] dropping unparsable stream line ({reason}): {} of {} bytes",
- parse_error_line_shape(line),
- line.len()
- ))
-}
-
-/// How much of the child's stderr we keep for diagnostics.
-const STDERR_DIAGNOSTIC_CAP: usize = 16_384;
-
-/// Append `chunk` to `acc`, keeping at most `max_bytes` and never splitting a
-/// character.
-///
-/// `String::truncate` takes a *byte* index and panics when it is not a character
-/// boundary, so bounding this accumulator with `acc.truncate(16_384)` aborted the
-/// task the moment a multi-byte character straddled the cap. The panic happened
-/// inside `tokio::spawn`, and the join is `unwrap_or_default()`, so it surfaced as
-/// an empty stderr string: the operator lost the whole error output for that turn
-/// and saw `exit Some(1) stderr=`.
-fn push_bounded(acc: &mut String, chunk: &str, max_bytes: usize) {
- acc.push_str(chunk);
- if acc.len() > max_bytes {
- let keep = utf8_safe_prefix_at_byte_boundary(acc, max_bytes).len();
- acc.truncate(keep);
- }
-}
-
-use crate::util::text::utf8_safe_prefix_at_byte_boundary;
-
-use super::event_mapper::EventMapper;
-use super::input_builder::build_stdin;
-use super::session_store::{generate_uuid_v4, is_uuid_v4, SessionStore};
-use super::stream_parser::{ClaudeCodeEvent, StreamJsonParser};
-use crate::agent::messages::ChatMessage;
-use crate::inference::provider::types::{ChatResponse, ProviderDelta};
-
-/// Tools withheld in the DEFAULT (`acceptEdits`) posture: Claude Code can
-/// read/edit files in the project, but not run shell, hit the network, or
-/// fan out CC subagents. The user opts into the full toolset separately by
-/// enabling full access (see [`claude_code_full_access`]), which switches to
-/// `bypassPermissions` and drops this list.
-const DISALLOWED_CC_BUILTINS: &[&str] = &[
- "Bash",
- "BashOutput",
- "KillShell",
- "WebFetch",
- "WebSearch",
- "Task",
-];
-
-/// Whether the user opted into FULL access for Claude Code (`bypassPermissions`
-/// + full native toolset incl. Bash/network). Default is **off** → the safer
-///
-/// `acceptEdits` posture (file edits only). This is a deliberate user choice,
-/// not the default — enabling Claude Code alone does not grant shell/network
-/// power.
-///
-/// Resolution order:
-/// 1. `OPENHUMAN_CLAUDE_CODE_PERMISSION_MODE` env var, when set to a recognised
-/// value, wins (debugging / power users). `bypass`/`bypassPermissions`/`full`
-/// force ON; `acceptEdits`/`edits`/`default`/`off`/`false`/`0` force OFF.
-/// 2. Otherwise the persisted UI toggle in
-/// [`super::settings`] (the Claude Code modal "Full access" switch).
-fn claude_code_full_access(workspace_dir: &std::path::Path) -> bool {
- if let Ok(raw) = std::env::var("OPENHUMAN_CLAUDE_CODE_PERMISSION_MODE") {
- match raw.trim() {
- "bypass" | "bypassPermissions" | "full" => return true,
- "acceptEdits" | "edits" | "default" | "off" | "false" | "0" => return false,
- _ => {}
- }
- }
- super::settings::load(workspace_dir).full_access
-}
-
-/// Whether to wrap the `claude` spawn in the macOS Seatbelt jail. On by
-/// default on macOS where `sandbox-exec` exists; opt out with
-/// `OPENHUMAN_CLAUDE_CODE_SANDBOX=0`.
-fn seatbelt_available() -> bool {
- #[cfg(target_os = "macos")]
- {
- let opted_out = std::env::var("OPENHUMAN_CLAUDE_CODE_SANDBOX")
- .map(|v| v == "0")
- .unwrap_or(false);
- !opted_out && std::path::Path::new("/usr/bin/sandbox-exec").exists()
- }
- #[cfg(not(target_os = "macos"))]
- {
- false
- }
-}
-
-/// Render a Seatbelt profile that lets Claude Code do **everything** the user
-/// can — read/write anywhere, run subprocesses, use the network — EXCEPT touch
-/// OpenHuman's internal workspace (`~/.openhuman*`: memory DB, sessions, auth
-/// tokens, config). That is the one hard wall: CC's raw tools must not be able
-/// to corrupt OpenHuman's own state. This mirrors OpenHuman's existing
-/// `is_workspace_internal_path` invariant (its native tools already can't write
-/// there) and now enforces the same boundary for the CC subprocess at the OS
-/// level. Everything else is the user's call.
-///
-/// Denies BOTH reads and writes of the OpenHuman workspace: CC's raw tools
-/// can neither corrupt nor exfiltrate OpenHuman's internal state (memory DB,
-/// sessions, auth tokens, config). CC still reaches OpenHuman memory — but only
-/// through the MCP HTTP server, which runs in the unjailed core (not as CC's
-/// child), so this full deny is safe.
-#[cfg(target_os = "macos")]
-fn seatbelt_profile(workspace_dir: &std::path::Path) -> String {
- let esc = |p: String| p.replace('\\', "\\\\").replace('"', "\\\"");
- // Deny the ENTIRE `~/.openhuman[-staging]` tree, not just the per-user
- // workspace subdir. `workspace_dir` is `…/.openhuman-staging/users/<id>/…`,
- // but sensitive files (core.token, credentials) also live at the root — so
- // denying only the subdir leaves them readable. Walk up to the `.openhuman*`
- // ancestor and deny that whole tree.
- let root = openhuman_internal_root(workspace_dir);
- let root = esc(std::fs::canonicalize(&root)
- .unwrap_or(root)
- .to_string_lossy()
- .to_string());
- format!(
- "(version 1)\n(allow default)\n\
- (deny file-write*\n (subpath \"{root}\")\n)\n\
- (deny file-read*\n (subpath \"{root}\")\n)\n"
- )
-}
-
-/// Resolve the OpenHuman internal root (`~/.openhuman` / `~/.openhuman-staging`)
-/// from a path inside it by walking up to the first `.openhuman*` ancestor.
-/// Falls back to the input path when no such ancestor exists.
-#[cfg(target_os = "macos")]
-fn openhuman_internal_root(workspace_dir: &std::path::Path) -> std::path::PathBuf {
- let mut cur = workspace_dir;
- loop {
- if cur
- .file_name()
- .and_then(|n| n.to_str())
- .map(|n| n.starts_with(".openhuman"))
- .unwrap_or(false)
- {
- return cur.to_path_buf();
- }
- match cur.parent() {
- Some(p) => cur = p,
- None => return workspace_dir.to_path_buf(),
- }
- }
-}
-
-/// One CC chat turn.
-pub struct TurnContext<'a> {
- pub bin_path: PathBuf,
- pub workspace_dir: PathBuf,
- /// The user's project root (`config.action_dir`). Claude Code runs here
- /// (cwd + `--add-dir`) so its file tools act on the user's code, not the
- /// internal OpenHuman workspace.
- pub project_dir: PathBuf,
- pub thread_id: String,
- pub model: String,
- pub append_system_prompt: Option<String>,
- pub messages: &'a [ChatMessage],
- pub session_store: Arc<SessionStore>,
- pub stream: Option<&'a mpsc::Sender<ProviderDelta>>,
- /// Optional explicit `ANTHROPIC_API_KEY` to set on the child. When
- /// `None`, the CLI falls back to its own `~/.claude/.credentials.json`.
- pub anthropic_api_key: Option<String>,
-}
-
-/// Write a CC `--mcp-config` JSON pointing at OpenHuman's in-process HTTP MCP
-/// server (running in the unjailed core). CC connects over loopback, so the
-/// MCP server is NOT a child of the sandboxed `claude` and keeps full access
-/// to `~/.openhuman` for memory — while CC's own raw tools are denied that dir
-/// by the jail. Returns the on-disk path; caller cleans up.
-fn write_mcp_http_config(
- dir: &std::path::Path,
- addr: std::net::SocketAddr,
- token: &str,
-) -> std::io::Result<PathBuf> {
- let path = dir.join("openhuman-mcp-config.json");
- // The loopback MCP server is authenticated — carry the per-process bearer
- // token so only this `claude` launch (not other local processes) can reach
- // OpenHuman's tools/memory.
- let cfg = json!({
- "mcpServers": {
- "openhuman": {
- "type": "http",
- "url": format!("http://{addr}/"),
- "headers": {
- "Authorization": format!("Bearer {token}"),
- }
- }
- }
- });
- std::fs::write(
- &path,
- serde_json::to_string_pretty(&cfg).unwrap_or_default(),
- )?;
- Ok(path)
-}
-
-/// Build the child's `PATH` so `claude` — and any tool it shells out to (git,
-/// ripgrep, node, …) — resolves even when OpenHuman was launched from
-/// Finder/Dock and inherited only the stripped launchd `PATH`
-/// (`/usr/bin:/bin:/usr/sbin:/sbin`, no `~/.local/bin`). Prepends the resolved
-/// CLI's own directory plus the common user/Homebrew bin dirs to whatever
-/// `PATH` we inherited; the inherited system entries are kept after them.
-/// Prepend-only — duplicate `PATH` entries are harmless, so this stays safe if
-/// a dir is already present (e.g. a terminal launch).
-pub(crate) fn child_path_with_user_bins(claude_bin: &std::path::Path) -> std::ffi::OsString {
- let mut prefix: Vec<PathBuf> = Vec::new();
- if let Some(parent) = claude_bin.parent() {
- if !parent.as_os_str().is_empty() {
- prefix.push(parent.to_path_buf());
- }
- }
- if let Some(home) = dirs::home_dir() {
- prefix.push(home.join(".local/bin"));
- prefix.push(home.join("bin"));
- }
- #[cfg(target_os = "macos")]
- prefix.push(PathBuf::from("/opt/homebrew/bin"));
- prefix.push(PathBuf::from("/usr/local/bin"));
-
- let existing = std::env::var_os("PATH").unwrap_or_default();
- std::env::join_paths(
- prefix
- .into_iter()
- .chain(std::env::split_paths(&existing).filter(|path| !path.as_os_str().is_empty())),
- )
- .unwrap_or(existing)
-}
-
-/// Keep the potentially large harness prompt out of argv. Windows flattens
-/// argv into a command line capped at 32,767 UTF-16 code units, while Claude's
-/// file flag has no such limit. The per-turn scratch directory owns cleanup.
-fn append_system_prompt_args(
- dir: &std::path::Path,
- prompt: Option<&str>,
-) -> std::io::Result<Vec<String>> {
- let Some(prompt) = prompt.filter(|value| !value.trim().is_empty()) else {
- return Ok(Vec::new());
- };
-
- let path = dir.join("append-system-prompt.txt");
- log::debug!(
- "[claude-code][driver] append-system-prompt file write start path={} bytes={}",
- path.display(),
- prompt.len()
- );
- if let Err(error) = std::fs::write(&path, prompt) {
- log::warn!(
- "[claude-code][driver] append-system-prompt file write failed path={} error={}",
- path.display(),
- error
- );
- return Err(error);
- }
- log::debug!(
- "[claude-code][driver] append-system-prompt file write complete path={} bytes={}",
- path.display(),
- prompt.len()
- );
- Ok(vec![
- "--append-system-prompt-file".to_string(),
- path.display().to_string(),
- ])
-}
-
-/// Run one turn against the `claude` CLI. Awaits process exit. Forwards
-/// `ProviderDelta`s through `ctx.stream` as they arrive and returns the
-/// aggregated `ChatResponse` when done.
-pub async fn run_turn(ctx: TurnContext<'_>) -> anyhow::Result<ChatResponse> {
- let stored = ctx.session_store.get(&ctx.thread_id);
- let is_new = !stored.as_deref().map(is_uuid_v4).unwrap_or(false);
- let cc_session_id = if is_new {
- let id = generate_uuid_v4();
- if let Err(e) = ctx.session_store.set(&ctx.thread_id, &id) {
- log::warn!(
- "[claude-code][driver] failed to persist session uuid for thread {}: {}",
- ctx.thread_id,
- e
- );
- }
- id
- } else {
- stored.expect("checked Some above")
- };
-
- // Set up a per-turn scratch dir for --mcp-config and any other transient
- // state. Best-effort cleanup at end of turn.
- let scratch = tempfile::Builder::new()
- .prefix("openhuman-cc-")
- .tempdir()
- .map_err(|e| anyhow::anyhow!("create scratch dir: {e}"))?;
- // Point CC at OpenHuman's in-process HTTP MCP server (unjailed core), so
- // the memory bridge survives CC's `.openhuman` jail deny.
- let mut mcp_config_path: Option<PathBuf> = None;
- match crate::mcp::server::ensure_local_http().await {
- Ok(endpoint) => match write_mcp_http_config(scratch.path(), endpoint.addr, &endpoint.token) {
- Ok(p) => {
- log::debug!(
- "[claude-code][driver] wrote http mcp-config path={} url=http://{}/ (authenticated)",
- p.display(),
- endpoint.addr
- );
- mcp_config_path = Some(p);
- }
- Err(e) => log::warn!(
- "[claude-code][driver] failed to write mcp-config: {e}; CC will run without OpenHuman MCP tools"
- ),
- },
- Err(e) => log::warn!(
- "[claude-code][driver] in-process MCP HTTP server unavailable: {e}; CC running without OpenHuman MCP tools"
- ),
- }
-
- // The user explicitly opts into Claude Code, so we do NOT limit its toolset
- // on any platform — CC always gets its full tools + `bypassPermissions`.
- // The jail (macOS Seatbelt, below) is purely the `.openhuman` wall: it
- // doesn't restrict CC, it just protects OpenHuman's internal data where the
- // OS supports it. On Linux/Windows there's no OS wall yet, so CC runs
- // unconfined there (user's machine, user's call).
- let jailed = seatbelt_available();
- // `jailed` is only consumed by the macOS Seatbelt spawn-wrap below.
- #[cfg(not(target_os = "macos"))]
- let _ = jailed;
-
- // Permission posture is a USER choice. Default `acceptEdits` (file edits
- // only); the user opts into `bypassPermissions` (full toolset incl. bash)
- // explicitly. On macOS the Seatbelt jail walls off `~/.openhuman` in either
- // mode; on Linux/Windows full access is unconfined.
- let full_access = claude_code_full_access(&ctx.workspace_dir);
- let permission_mode = if full_access {
- "bypassPermissions"
- } else {
- "acceptEdits"
- };
-
- let mut args: Vec<String> = vec![
- "-p".into(),
- "--input-format".into(),
- "stream-json".into(),
- "--output-format".into(),
- "stream-json".into(),
- "--verbose".into(),
- "--include-partial-messages".into(),
- // Grant file-tool access to the user's project root (cwd is set to the
- // same dir below). This is where the coding agent reads/edits code.
- "--add-dir".into(),
- ctx.project_dir.display().to_string(),
- // Default `acceptEdits` (auto-apply edits, gate the rest); the user can
- // opt into `bypassPermissions` for the full toolset (see above).
- "--permission-mode".into(),
- permission_mode.to_string(),
- if is_new {
- "--session-id".into()
- } else {
- "--resume".into()
- },
- cc_session_id.clone(),
- "--model".into(),
- ctx.model.clone(),
- ];
- args.extend(
- append_system_prompt_args(scratch.path(), ctx.append_system_prompt.as_deref())
- .map_err(|e| anyhow::anyhow!("write Claude Code system prompt file: {e}"))?,
- );
- if let Some(p) = mcp_config_path.as_ref() {
- args.push("--mcp-config".into());
- args.push(p.display().to_string());
- args.push("--strict-mcp-config".into());
- }
- // Tool surface follows the permission posture: full access → no
- // `--disallowedTools` (CC keeps its entire toolset incl. Bash/network);
- // default `acceptEdits` → withhold the dangerous builtins (edits only).
- if !full_access {
- args.push("--disallowedTools".into());
- args.push(DISALLOWED_CC_BUILTINS.join(","));
- }
-
- // Validate input *before* spawning so we don't launch a process we
- // can't feed (CodeRabbit: validate before spawn).
- let stdin_bytes = build_stdin(ctx.messages, is_new);
- if stdin_bytes.is_empty() {
- anyhow::bail!("[claude-code][driver] no input messages to deliver");
- }
-
- log::debug!(
- "[claude-code][driver] spawn bin={} model={} is_new={} cc_session_id={}",
- ctx.bin_path.display(),
- ctx.model,
- is_new,
- cc_session_id
- );
-
- // Best-effort: ensure the project dir exists so spawn (cwd) doesn't fail.
- std::fs::create_dir_all(&ctx.project_dir).ok();
-
- // Wrap the spawn in the macOS Seatbelt jail when available so CC's file
- // writes are OS-confined: `sandbox-exec -p <profile> <claude> <args…>`.
- #[cfg(target_os = "macos")]
- let (program, final_args): (PathBuf, Vec<String>) = if jailed {
- let profile = seatbelt_profile(&ctx.workspace_dir);
- let mut wrapped = vec![
- "-p".to_string(),
- profile,
- ctx.bin_path.display().to_string(),
- ];
- wrapped.extend(args.iter().cloned());
- log::debug!(
- "[claude-code][driver] seatbelt jail active root={}",
- ctx.project_dir.display()
- );
- (PathBuf::from("/usr/bin/sandbox-exec"), wrapped)
- } else {
- (ctx.bin_path.clone(), args.clone())
- };
- #[cfg(not(target_os = "macos"))]
- let (program, final_args): (PathBuf, Vec<String>) = (ctx.bin_path.clone(), args.clone());
-
- let mut cmd = Command::new(&program);
- cmd.args(&final_args)
- .current_dir(&ctx.project_dir)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .kill_on_drop(true);
- if let Some(key) = &ctx.anthropic_api_key {
- cmd.env("ANTHROPIC_API_KEY", key);
- }
- // A Finder/Dock launch inherits a stripped launchd PATH; make sure the CLI
- // and anything it invokes resolve by prepending the user's bin dirs.
- cmd.env("PATH", child_path_with_user_bins(&ctx.bin_path));
-
- let mut child = cmd
- .spawn()
- .map_err(|e| anyhow::anyhow!("failed to spawn `claude`: {e}"))?;
- if let Some(mut stdin) = child.stdin.take() {
- stdin
- .write_all(&stdin_bytes)
- .await
- .map_err(|e| anyhow::anyhow!("write stdin: {e}"))?;
- stdin
- .shutdown()
- .await
- .map_err(|e| anyhow::anyhow!("close stdin: {e}"))?;
- }
-
- let mut stdout = child
- .stdout
- .take()
- .ok_or_else(|| anyhow::anyhow!("claude child stdout missing"))?;
- let mut stderr = child
- .stderr
- .take()
- .ok_or_else(|| anyhow::anyhow!("claude child stderr missing"))?;
-
- let mut parser = StreamJsonParser::new();
- let mut mapper = EventMapper::new();
- let mut buf = [0u8; 8192];
-
- // Drain stderr in parallel into a buffer for diagnostics.
- let stderr_task = tokio::spawn(async move {
- let mut acc = String::new();
- let mut tmp = [0u8; 4096];
- while let Ok(n) = stderr.read(&mut tmp).await {
- if n == 0 {
- break;
- }
- push_bounded(
- &mut acc,
- &String::from_utf8_lossy(&tmp[..n]),
- STDERR_DIAGNOSTIC_CAP,
- );
- }
- acc
- });
-
- // Wrap the streaming + wait in a timeout so a stuck CLI doesn't
- // block this task forever (PLAN §8).
- let timeout = turn_timeout();
- let timed = tokio::time::timeout(timeout, async {
- loop {
- let n = stdout
- .read(&mut buf)
- .await
- .map_err(|e| anyhow::anyhow!("read stdout: {e}"))?;
- if n == 0 {
- break;
- }
- for ev in parser.feed_bytes(&buf[..n]) {
- if let Some(msg) = parse_error_log_line(&ev) {
- log::warn!("{msg}");
- }
- for delta in mapper.handle(ev) {
- if let Some(tx) = ctx.stream {
- let _ = tx.send(delta).await;
- }
- }
- }
- }
- for ev in parser.end() {
- if let Some(msg) = parse_error_log_line(&ev) {
- log::warn!("{msg}");
- }
- for delta in mapper.handle(ev) {
- if let Some(tx) = ctx.stream {
- let _ = tx.send(delta).await;
- }
- }
- }
-
- let status = child
- .wait()
- .await
- .map_err(|e| anyhow::anyhow!("wait child: {e}"))?;
- Ok::<_, anyhow::Error>(status)
- })
- .await;
-
- let status = match timed {
- Ok(inner) => inner?,
- Err(_elapsed) => {
- log::error!("[claude-code][driver] turn timeout ({timeout:?}) exceeded; killing child");
- // kill_on_drop handles cleanup, but explicit kill gives us
- // a chance to collect stderr.
- let _ = child.kill().await;
- anyhow::bail!("[claude-code][driver] turn timed out after {:?}", timeout);
- }
- };
-
- let stderr_text = stderr_task.await.unwrap_or_default();
-
- if !status.success() {
- anyhow::bail!(
- "[claude-code][driver] exit {:?} stderr={}",
- status.code(),
- stderr_text.trim()
- );
- }
- if let Some(err) = mapper.error.clone() {
- anyhow::bail!("[claude-code][driver] {}", err);
- }
-
- Ok(mapper.into_response())
-}
-
-#[cfg(test)]
-#[path = "driver_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/driver_tests.rs b/crates/openhuman-core/src/inference/provider/claude_code/driver_tests.rs
deleted file mode 100644
index f32472ae19..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/driver_tests.rs
+++ /dev/null
@@ -1,329 +0,0 @@
-use super::*;
-
-#[test]
-fn write_mcp_http_config_emits_http_url_with_bearer_header() {
- let dir = tempfile::tempdir().expect("tempdir");
- let addr: std::net::SocketAddr = "127.0.0.1:54321".parse().unwrap();
- let path = write_mcp_http_config(dir.path(), addr, "tok-abc123").expect("write config");
- let raw = std::fs::read_to_string(&path).expect("read config");
- let v: serde_json::Value = serde_json::from_str(&raw).expect("valid json");
- let server = &v["mcpServers"]["openhuman"];
- assert_eq!(
- server["type"], "http",
- "MCP transport must be http (out-of-jail)"
- );
- assert_eq!(server["url"], "http://127.0.0.1:54321/");
- // The loopback server is authenticated — the config must carry the bearer.
- assert_eq!(server["headers"]["Authorization"], "Bearer tok-abc123");
- // It must NOT spawn a stdio child (the old jailed path).
- assert!(server.get("command").is_none());
-}
-
-#[test]
-fn child_path_prepends_cli_dir_and_keeps_inherited_entries() {
- let _env = super::super::ENV_TEST_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- struct PathRestore(Option<std::ffi::OsString>);
- impl Drop for PathRestore {
- fn drop(&mut self) {
- match self.0.take() {
- Some(path) => std::env::set_var("PATH", path),
- None => std::env::remove_var("PATH"),
- }
- }
- }
-
- let _restore = PathRestore(std::env::var_os("PATH"));
- let inherited = std::env::join_paths([
- std::path::Path::new("/usr/bin"),
- std::path::Path::new("/bin"),
- ])
- .expect("valid test paths");
- std::env::set_var("PATH", inherited);
-
- let combined = child_path_with_user_bins(std::path::Path::new("/Users/test/.local/bin/claude"));
- let dirs: Vec<PathBuf> = std::env::split_paths(&combined).collect();
-
- assert_eq!(
- dirs.first().map(|p| p.as_path()),
- Some(std::path::Path::new("/Users/test/.local/bin"))
- );
- assert!(dirs.iter().any(|p| p == std::path::Path::new("/usr/bin")));
- assert!(dirs.iter().any(|p| p == std::path::Path::new("/bin")));
- let cli_idx = dirs
- .iter()
- .position(|p| p == std::path::Path::new("/Users/test/.local/bin"))
- .expect("CLI directory");
- let usr_idx = dirs
- .iter()
- .position(|p| p == std::path::Path::new("/usr/bin"))
- .expect("inherited directory");
- assert!(
- cli_idx < usr_idx,
- "CLI dir must come before inherited /usr/bin"
- );
- assert!(!dirs.iter().any(|p| p.as_os_str().is_empty()));
-}
-
-#[test]
-fn large_system_prompt_is_written_to_file_instead_of_argv() {
- let dir = tempfile::tempdir().expect("tempdir");
- let prompt = "system instruction\n".repeat(2_500);
- assert!(prompt.len() > 32_767);
-
- let args = append_system_prompt_args(dir.path(), Some(&prompt)).expect("prompt args");
-
- assert_eq!(args[0], "--append-system-prompt-file");
- assert_eq!(args.len(), 2);
- assert!(!args.iter().any(|arg| arg.contains(&prompt)));
- assert_eq!(
- std::fs::read_to_string(&args[1]).expect("read prompt file"),
- prompt
- );
-}
-
-#[test]
-fn empty_system_prompt_does_not_add_an_argument() {
- let dir = tempfile::tempdir().expect("tempdir");
- let args = append_system_prompt_args(dir.path(), Some(" \n ")).expect("prompt args");
-
- assert!(args.is_empty());
- assert!(!dir.path().join("append-system-prompt.txt").exists());
-}
-
-#[test]
-fn system_prompt_write_error_is_propagated() {
- let dir = tempfile::tempdir().expect("tempdir");
- let not_a_directory = dir.path().join("file");
- std::fs::write(&not_a_directory, "occupied").expect("write blocking file");
-
- let error = append_system_prompt_args(&not_a_directory, Some("system prompt"))
- .expect_err("non-directory parent must fail");
-
- assert!(!error.to_string().is_empty());
-}
-
-#[cfg(target_os = "macos")]
-#[test]
-fn seatbelt_profile_denies_whole_openhuman_root_not_just_subdir() {
- // Driver passes the per-user subdir; the jail must deny the WHOLE
- // `.openhuman-staging` tree (so root-level core.token/credentials are
- // protected), not just the subdir.
- let ws = std::path::Path::new("/Users/test/.openhuman-staging/users/abc/workspace");
- let p = seatbelt_profile(ws);
- assert!(
- p.contains("(allow default)"),
- "CC does everything by default"
- );
- assert!(p.contains("(deny file-write*"), "must deny writes");
- assert!(
- p.contains("(deny file-read*"),
- "must deny reads (no token exfil)"
- );
- // Denied path is the ROOT, not the per-user subdir.
- assert!(
- p.contains("/Users/test/.openhuman-staging\""),
- "deny subpath must be the .openhuman root: {p}"
- );
- assert!(
- !p.contains("users/abc"),
- "deny must NOT be scoped to the narrow subdir: {p}"
- );
-}
-
-#[cfg(target_os = "macos")]
-#[test]
-fn openhuman_internal_root_walks_up_to_dotopenhuman() {
- let r = openhuman_internal_root(std::path::Path::new(
- "/Users/x/.openhuman/users/id/workspace/memory",
- ));
- assert_eq!(r, std::path::Path::new("/Users/x/.openhuman"));
- // Fallback: no `.openhuman*` ancestor → returns the input.
- let r2 = openhuman_internal_root(std::path::Path::new("/tmp/custom/ws"));
- assert_eq!(r2, std::path::Path::new("/tmp/custom/ws"));
-}
-
-#[cfg(target_os = "macos")]
-#[test]
-fn seatbelt_available_honors_opt_out() {
- let _env = super::super::ENV_TEST_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let prev = std::env::var("OPENHUMAN_CLAUDE_CODE_SANDBOX").ok();
- std::env::set_var("OPENHUMAN_CLAUDE_CODE_SANDBOX", "0");
- assert!(
- !seatbelt_available(),
- "explicit opt-out must disable the jail"
- );
- match prev {
- Some(v) => std::env::set_var("OPENHUMAN_CLAUDE_CODE_SANDBOX", v),
- None => std::env::remove_var("OPENHUMAN_CLAUDE_CODE_SANDBOX"),
- }
-}
-
-#[test]
-fn full_access_defaults_off_and_opts_in_via_env() {
- let _env = super::super::ENV_TEST_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- // Empty workspace (no persisted toggle) → file layer resolves to OFF.
- let ws = std::env::temp_dir().join("oh_cc_fullaccess_env_test");
- let _ = std::fs::remove_dir_all(&ws);
- let key = "OPENHUMAN_CLAUDE_CODE_PERMISSION_MODE";
- let prev = std::env::var(key).ok();
- std::env::remove_var(key);
- assert!(
- !claude_code_full_access(&ws),
- "default posture must be acceptEdits (full access OFF)"
- );
- std::env::set_var(key, "bypass");
- assert!(
- claude_code_full_access(&ws),
- "explicit opt-in (`bypass`) enables full access"
- );
- std::env::set_var(key, "acceptEdits");
- assert!(
- !claude_code_full_access(&ws),
- "acceptEdits env override keeps the default (limited) posture"
- );
- match prev {
- Some(v) => std::env::set_var(key, v),
- None => std::env::remove_var(key),
- }
-}
-
-#[test]
-fn full_access_reads_persisted_toggle_when_env_unset() {
- use super::super::settings::{self, ClaudeCodeSettings};
- let _env = super::super::ENV_TEST_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let ws = std::env::temp_dir().join("oh_cc_fullaccess_file_test");
- let _ = std::fs::remove_dir_all(&ws);
- std::fs::create_dir_all(&ws).unwrap();
- let key = "OPENHUMAN_CLAUDE_CODE_PERMISSION_MODE";
- let prev = std::env::var(key).ok();
- std::env::remove_var(key);
-
- settings::save(&ws, &ClaudeCodeSettings { full_access: true }).unwrap();
- assert!(
- claude_code_full_access(&ws),
- "persisted toggle ON must enable full access when env is unset"
- );
-
- // Env override beats the persisted toggle.
- std::env::set_var(key, "acceptEdits");
- assert!(
- !claude_code_full_access(&ws),
- "env override OFF must beat a persisted ON toggle"
- );
-
- match prev {
- Some(v) => std::env::set_var(key, v),
- None => std::env::remove_var(key),
- }
- let _ = std::fs::remove_dir_all(&ws);
-}
-
-/// `String::truncate` takes a byte index and panics when it is not a character
-/// boundary, so bounding the stderr accumulator with `acc.truncate(16_384)`
-/// aborted the drain task whenever a multi-byte character straddled the cap.
-/// The join is `unwrap_or_default()`, so the operator saw `stderr=` and lost
-/// the whole error output for that turn.
-#[test]
-fn push_bounded_never_splits_a_character() {
- // "aéb" is 4 bytes: a=0, é=1..2, b=3. A cap of 2 lands *inside* 'é', so the
- // helper must back up to byte 1 -- `String::truncate(2)` would panic here.
- let mut acc = String::new();
- super::push_bounded(&mut acc, "aéb", 2);
- assert_eq!(acc, "a", "must back up to the boundary, not split it");
-
- // A cap of 3 lands exactly on a boundary, so nothing is given up needlessly.
- let mut acc = String::new();
- super::push_bounded(&mut acc, "aéb", 3);
- assert_eq!(acc, "aé");
- assert!(acc.len() <= 3);
-
- // The same, driven the way the reader does it: many small chunks over the cap.
- let mut acc = String::new();
- for _ in 0..600 {
- super::push_bounded(&mut acc, "日本語テキスト", 1024);
- }
- assert!(acc.len() <= 1024);
- // The real assertion: it is still valid UTF-8 and did not panic getting here.
- assert!(std::str::from_utf8(acc.as_bytes()).is_ok());
-}
-
-#[test]
-fn push_bounded_keeps_everything_below_the_cap() {
- let mut acc = String::new();
- super::push_bounded(&mut acc, "hello ", 64);
- super::push_bounded(&mut acc, "world", 64);
- assert_eq!(acc, "hello world");
-}
-
-#[test]
-fn push_bounded_handles_an_ascii_cap_exactly() {
- let mut acc = String::new();
- super::push_bounded(&mut acc, "abcdef", 3);
- assert_eq!(acc, "abc");
-}
-
-#[test]
-fn parse_error_events_produce_a_log_line() {
- let ev = ClaudeCodeEvent::ParseError {
- line: "{not json".to_string(),
- reason: "expected value at line 1 column 2".to_string(),
- };
- let msg = parse_error_log_line(&ev).expect("a ParseError must be reported");
- assert!(msg.contains("expected value at line 1 column 2"), "{msg}");
- assert!(msg.contains("9 bytes"), "{msg}");
-}
-
-#[test]
-fn other_events_produce_nothing() {
- let ev = ClaudeCodeEvent::Error {
- message: "boom".to_string(),
- };
- assert!(parse_error_log_line(&ev).is_none());
-}
-
-/// An unparsable line can be a well-formed event of an unknown type, so it
-/// can hold the prompt, the reply, or a credential. None of it is quoted.
-#[test]
-fn the_line_itself_is_never_quoted() {
- let ev = ClaudeCodeEvent::ParseError {
- line: r#"{"type":"secret_leak","api_key":"sk-ant-not-in-the-log"}"#.to_string(),
- reason: "unknown event type `secret_leak`".to_string(),
- };
- let msg = parse_error_log_line(&ev).unwrap();
- assert!(!msg.contains("sk-ant-not-in-the-log"), "{msg}");
- assert!(!msg.contains("api_key"), "{msg}");
-}
-
-/// Size is reported instead of content, so a truncated stream still reads
-/// differently from a chatty one.
-#[test]
-fn the_size_of_the_line_is_reported() {
- let ev = ClaudeCodeEvent::ParseError {
- line: "x".repeat(5_000),
- reason: "trailing characters".to_string(),
- };
- assert!(parse_error_log_line(&ev).unwrap().contains("5000 bytes"));
-}
-
-#[test]
-fn the_shape_of_the_line_is_reported() {
- let shape = |line: &str| {
- parse_error_log_line(&ClaudeCodeEvent::ParseError {
- line: line.to_string(),
- reason: "r".to_string(),
- })
- .unwrap()
- };
- assert!(shape(r#" {"type":"x"}"#).contains("json object"));
- assert!(shape("[1,2]").contains("json array"));
- assert!(shape("panic: claude-code crashed").contains("non-json"));
- assert!(shape(" ").contains("blank"));
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/event_mapper.rs b/crates/openhuman-core/src/inference/provider/claude_code/event_mapper.rs
deleted file mode 100644
index 66ee4bbb52..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/event_mapper.rs
+++ /dev/null
@@ -1,302 +0,0 @@
-//! Translate `ClaudeCodeEvent`s into OpenHuman `ProviderDelta`s plus a
-//! final aggregated `ChatResponse`.
-//!
-//! The CLI emits content as anthropic-style content blocks. We map:
-//! - `content_block_start` text → start a text accumulator
-//! - `content_block_delta` text → `ProviderDelta::TextDelta`
-//! - `content_block_*` tool → tracked but **NOT surfaced** (see below)
-//! - `result` → finalize usage + cost
-//!
-//! Thinking blocks (`thinking_delta`) are forwarded as
-//! `ProviderDelta::ThinkingDelta`.
-//!
-//! ## Tool blocks are deliberately not surfaced
-//!
-//! The `claude` CLI is a **self-executing** agent: it runs its own built-in
-//! tools (`Read`/`Write`/`Edit`/`Bash`/`Glob`/…) and OpenHuman's MCP tools
-//! internally, in its own agent loop, and returns their results itself. So a
-//! `tool_use` block in the stream is a call the CLI has **already executed** —
-//! not a request for OpenHuman to run something.
-//!
-//! If we surfaced these as OpenHuman [`ToolCall`]s, the tinyagents harness would
-//! try to dispatch them, hold none of them by those names, and reject each one
-//! (`unknown tool \`Read\`; valid tools: [...]`) — injecting that corrective
-//! back into the transcript and looping until it aborts (`N tool calls in a row
-//! failed with no progress`). That is the intermittent "something went wrong"
-//! wall users hit (it only bit when a `tool_use` block arrived as a streamed
-//! partial rather than solely in the skipped final `assistant` message).
-//!
-//! So we track a `tool_use` block only enough to keep its `input_json_delta`s
-//! out of the visible text, and surface nothing. The CLI's final assistant text
-//! is the turn's result; its live narration/thinking still streams to the UI.
-
-use std::collections::HashMap;
-
-use serde_json::Value;
-
-use super::stream_parser::ClaudeCodeEvent;
-use crate::inference::provider::types::{ChatResponse, ProviderDelta, ToolCall, UsageInfo};
-
-#[derive(Debug, Clone)]
-struct BlockState {
- kind: BlockKind,
- tool_name: Option<String>,
- text_accum: String,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-enum BlockKind {
- Text,
- Thinking,
- Tool,
-}
-
-#[derive(Debug, Default)]
-pub struct EventMapper {
- blocks: HashMap<u64, BlockState>,
- pub final_text: String,
- /// Always empty for the self-executing `claude` CLI: its `tool_use` blocks
- /// are calls it already ran itself, so they are never surfaced as OpenHuman
- /// tool calls (see the module docs). Kept as the response's `tool_calls`
- /// slot so the harness always sees a terminal, tool-less response.
- pub tool_calls: Vec<ToolCall>,
- pub usage: Option<UsageInfo>,
- pub error: Option<String>,
- pub session_id: Option<String>,
- pub finished: bool,
-}
-
-impl EventMapper {
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Process one event and return the deltas to forward to the stream
- /// sink (if any).
- pub fn handle(&mut self, event: ClaudeCodeEvent) -> Vec<ProviderDelta> {
- match event {
- ClaudeCodeEvent::System { session_id, .. } => {
- if let Some(id) = session_id {
- self.session_id = Some(id);
- }
- Vec::new()
- }
- ClaudeCodeEvent::Error { message } => {
- self.error = Some(message);
- Vec::new()
- }
- ClaudeCodeEvent::Result {
- subtype,
- usage,
- total_cost_usd,
- ..
- } => {
- let mut parsed = usage.as_ref().map(parse_usage);
- // CC stream emits `total_cost_usd` on the terminal `result`
- // event — surface it as `UsageInfo.charged_amount_usd` so
- // downstream cost.rs can record it without re-pricing
- // tokens × model rates.
- if let Some(cost) = total_cost_usd {
- let usage = parsed.get_or_insert_with(UsageInfo::default);
- usage.charged_amount_usd = cost;
- }
- self.usage = parsed;
- if subtype.as_deref() == Some("error") && self.error.is_none() {
- self.error = Some("claude reported `result.subtype=error`".into());
- }
- self.finished = true;
- Vec::new()
- }
- ClaudeCodeEvent::Assistant { message } => {
- // CC 2.x emits a final assembled `assistant` event with
- // `message.type == "message"` after streaming completes via
- // `stream_event`. Skip to avoid double-emission.
- if message.get("type").and_then(Value::as_str) == Some("message") {
- return Vec::new();
- }
- self.handle_assistant_block(&message)
- }
- ClaudeCodeEvent::StreamEvent { event } => self.handle_assistant_block(&event),
- ClaudeCodeEvent::User { message } => {
- // tool_result blocks from the CLI's own tool runs aren't
- // surfaced to OpenHuman's harness (the harness owns tools
- // via MCP, not via CC internals). Track for completeness.
- let _ = message;
- Vec::new()
- }
- ClaudeCodeEvent::RateLimit { .. } | ClaudeCodeEvent::ParseError { .. } => Vec::new(),
- }
- }
-
- fn handle_assistant_block(&mut self, msg: &Value) -> Vec<ProviderDelta> {
- let ty = msg.get("type").and_then(Value::as_str).unwrap_or("");
- let index = msg.get("index").and_then(Value::as_u64).unwrap_or(0);
- match ty {
- "content_block_start" => self.on_block_start(index, msg),
- "content_block_delta" => self.on_block_delta(index, msg),
- "content_block_stop" => self.on_block_stop(index),
- _ => Vec::new(),
- }
- }
-
- fn on_block_start(&mut self, index: u64, msg: &Value) -> Vec<ProviderDelta> {
- let block = match msg.get("content_block") {
- Some(b) => b,
- None => return Vec::new(),
- };
- let kind = block.get("type").and_then(Value::as_str).unwrap_or("");
- match kind {
- "text" => {
- self.blocks.insert(
- index,
- BlockState {
- kind: BlockKind::Text,
- tool_name: None,
- text_accum: String::new(),
- },
- );
- Vec::new()
- }
- "thinking" => {
- self.blocks.insert(
- index,
- BlockState {
- kind: BlockKind::Thinking,
- tool_name: None,
- text_accum: String::new(),
- },
- );
- Vec::new()
- }
- "tool_use" => {
- // The CLI has ALREADY executed this tool itself (see the module
- // docs). Track the block so its argument deltas don't leak into
- // the visible text, but surface no `ToolCallStart` — OpenHuman's
- // harness must never try to re-dispatch a call the CLI ran.
- let tool_name = block
- .get("name")
- .and_then(Value::as_str)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
- if let Some(name) = tool_name.as_deref() {
- log::debug!(
- "[claude-code][event-mapper] CLI self-executed tool `{name}` (not surfaced to the harness)"
- );
- }
- // The block is tracked so its `input_json_delta`s and its stop
- // event are swallowed rather than leaking, but it is NOT
- // surfaced to OpenHuman's harness — see the note on
- // `on_block_stop`.
- self.blocks.insert(
- index,
- BlockState {
- kind: BlockKind::Tool,
- tool_name,
- text_accum: String::new(),
- },
- );
- Vec::new()
- }
- _ => Vec::new(),
- }
- }
-
- fn on_block_delta(&mut self, index: u64, msg: &Value) -> Vec<ProviderDelta> {
- let delta = match msg.get("delta") {
- Some(d) => d,
- None => return Vec::new(),
- };
- let dtype = delta.get("type").and_then(Value::as_str).unwrap_or("");
- let Some(state) = self.blocks.get_mut(&index) else {
- return Vec::new();
- };
- match (state.kind.clone(), dtype) {
- (BlockKind::Text, "text_delta") => {
- let text = delta
- .get("text")
- .and_then(Value::as_str)
- .unwrap_or("")
- .to_string();
- state.text_accum.push_str(&text);
- self.final_text.push_str(&text);
- vec![ProviderDelta::TextDelta { delta: text }]
- }
- (BlockKind::Thinking, "thinking_delta") => {
- let text = delta
- .get("thinking")
- .and_then(Value::as_str)
- .or_else(|| delta.get("text").and_then(Value::as_str))
- .unwrap_or("")
- .to_string();
- state.text_accum.push_str(&text);
- vec![ProviderDelta::ThinkingDelta { delta: text }]
- }
- (BlockKind::Tool, "input_json_delta") => {
- // Self-executed by the CLI (see the module docs). Discard the
- // argument fragments: they are not surfaced to the harness and
- // retaining them until block stop only wastes memory.
- Vec::new()
- }
- _ => Vec::new(),
- }
- }
-
- fn on_block_stop(&mut self, index: u64) -> Vec<ProviderDelta> {
- let Some(state) = self.blocks.remove(&index) else {
- return Vec::new();
- };
- if state.kind == BlockKind::Tool {
- // A native `tool_use` block from this CLI is the CLI's OWN call —
- // its builtins (Bash / Read / Write / Edit …) or a server from the
- // `--mcp-config` we hand it. The CLI executes them itself inside
- // its own agentic loop, which is why the matching `tool_result`
- // blocks are deliberately dropped in `map_event`.
- //
- // Surfacing the *call* while dropping its *result* handed
- // OpenHuman's harness a tool it does not own and cannot run: with
- // `full_access` on (no `--disallowedTools`), a turn that reached
- // for `Bash` produced repeated tool failures until the circuit
- // breaker halted the run, and the turn then burned its 900s
- // wall-clock backstop. So neither half is surfaced, and this
- // provider behaves as what it is — a chat model whose tool use is
- // internal. OpenHuman's own tools reach it through the prompt
- // catalogue, not through native tool calls.
- log::debug!(
- "[claude-code][event-mapper] dropping cli-internal tool call name={}",
- state.tool_name.unwrap_or_default(),
- );
- }
- Vec::new()
- }
-
- /// Build the final aggregated `ChatResponse` once the stream is done.
- pub fn into_response(self) -> ChatResponse {
- ChatResponse {
- text: if self.final_text.is_empty() {
- None
- } else {
- Some(self.final_text)
- },
- tool_calls: self.tool_calls,
- usage: self.usage,
- reasoning_content: None,
- }
- }
-}
-
-fn parse_usage(v: &Value) -> UsageInfo {
- let n = |k: &str| v.get(k).and_then(Value::as_u64).unwrap_or(0);
- UsageInfo {
- input_tokens: n("input_tokens"),
- output_tokens: n("output_tokens"),
- context_window: 0,
- cached_input_tokens: n("cache_read_input_tokens"),
- cache_creation_tokens: n("cache_creation_input_tokens"),
- reasoning_tokens: 0,
- charged_amount_usd: 0.0,
- }
-}
-
-#[cfg(test)]
-#[path = "event_mapper_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/event_mapper_tests.rs b/crates/openhuman-core/src/inference/provider/claude_code/event_mapper_tests.rs
deleted file mode 100644
index c463a5a90c..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/event_mapper_tests.rs
+++ /dev/null
@@ -1,155 +0,0 @@
-use super::*;
-use serde_json::json;
-
-fn text_block_start(idx: u64) -> Value {
- json!({"type":"content_block_start","index":idx,"content_block":{"type":"text"}})
-}
-fn text_delta(idx: u64, t: &str) -> Value {
- json!({"type":"content_block_delta","index":idx,"delta":{"type":"text_delta","text":t}})
-}
-
-#[test]
-fn text_streams_through() {
- let mut m = EventMapper::new();
- m.handle(ClaudeCodeEvent::StreamEvent {
- event: text_block_start(0),
- });
- let d1 = m.handle(ClaudeCodeEvent::StreamEvent {
- event: text_delta(0, "hel"),
- });
- let d2 = m.handle(ClaudeCodeEvent::StreamEvent {
- event: text_delta(0, "lo"),
- });
- assert!(matches!(&d1[0], ProviderDelta::TextDelta { delta } if delta == "hel"));
- assert!(matches!(&d2[0], ProviderDelta::TextDelta { delta } if delta == "lo"));
- assert_eq!(m.final_text, "hello");
-}
-
-/// A native `tool_use` block is the CLI's own call — a builtin, or a server
-/// from the `--mcp-config` it was handed — and the CLI runs it inside its own
-/// loop. The matching `tool_result` was always dropped; surfacing the call
-/// while dropping its result handed OpenHuman's harness a tool it cannot run,
-/// which failed repeatedly until the circuit breaker halted the whole turn.
-/// Neither half is surfaced now.
-#[test]
-fn cli_internal_tool_calls_are_not_surfaced_to_the_harness() {
- let mut m = EventMapper::new();
- let start = json!({"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"call_1","name":"Bash"}});
- let d_args = json!({"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"command\":\"ls\"}"}});
- let stop = json!({"type":"content_block_stop","index":1});
-
- assert!(
- m.handle(ClaudeCodeEvent::StreamEvent { event: start })
- .is_empty(),
- "no ToolCallStart reaches the harness"
- );
- assert!(
- m.handle(ClaudeCodeEvent::StreamEvent { event: d_args })
- .is_empty(),
- "no ToolCallArgsDelta reaches the harness"
- );
- m.handle(ClaudeCodeEvent::StreamEvent { event: stop });
-
- assert!(
- m.tool_calls.is_empty(),
- "the aggregated response carries no tool calls for the harness to execute"
- );
-}
-
-#[test]
-fn cli_internal_tool_blocks_without_metadata_are_still_suppressed() {
- let mut m = EventMapper::new();
- let start = json!({
- "type": "content_block_start",
- "index": 1,
- "content_block": {"type": "tool_use"}
- });
- let args = json!({
- "type": "content_block_delta",
- "index": 1,
- "delta": {"type": "input_json_delta", "partial_json": "{\"x\":1}"}
- });
- let stop = json!({"type": "content_block_stop", "index": 1});
-
- assert!(m
- .handle(ClaudeCodeEvent::StreamEvent { event: start })
- .is_empty());
- assert!(m
- .handle(ClaudeCodeEvent::StreamEvent { event: args })
- .is_empty());
- assert!(m
- .handle(ClaudeCodeEvent::StreamEvent { event: stop })
- .is_empty());
- assert!(m.tool_calls.is_empty());
-}
-
-/// Text in the same turn still streams normally — dropping the tool block must
-/// not swallow the CLI's actual answer.
-#[test]
-fn text_in_a_turn_with_a_cli_tool_call_still_streams() {
- let mut m = EventMapper::new();
- m.handle(ClaudeCodeEvent::StreamEvent {
- event: json!({"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"call_1","name":"Write"}}),
- });
- m.handle(ClaudeCodeEvent::StreamEvent {
- event: json!({"type":"content_block_stop","index":0}),
- });
- m.handle(ClaudeCodeEvent::StreamEvent {
- event: text_block_start(1),
- });
- let deltas = m.handle(ClaudeCodeEvent::StreamEvent {
- event: text_delta(1, "done"),
- });
-
- assert!(matches!(&deltas[0], ProviderDelta::TextDelta { delta } if delta == "done"));
- assert_eq!(m.final_text, "done");
- assert!(m.tool_calls.is_empty());
-}
-
-#[test]
-fn result_event_captures_usage() {
- let mut m = EventMapper::new();
- m.handle(ClaudeCodeEvent::Result {
- subtype: Some("success".into()),
- usage: Some(json!({
- "input_tokens": 100,
- "output_tokens": 50,
- "cache_read_input_tokens": 25
- })),
- total_cost_usd: Some(0.001),
- raw: Value::Null,
- });
- assert!(m.finished);
- let u = m.usage.as_ref().unwrap();
- assert_eq!(u.input_tokens, 100);
- assert_eq!(u.output_tokens, 50);
- assert_eq!(u.cached_input_tokens, 25);
- // cost wired through from total_cost_usd
- assert!((u.charged_amount_usd - 0.001).abs() < f64::EPSILON);
-}
-
-#[test]
-fn cost_surfaced_even_without_usage_object() {
- let mut m = EventMapper::new();
- m.handle(ClaudeCodeEvent::Result {
- subtype: Some("success".into()),
- usage: None,
- total_cost_usd: Some(0.05),
- raw: Value::Null,
- });
- let u = m
- .usage
- .as_ref()
- .expect("usage synthesized for cost-only result");
- assert_eq!(u.input_tokens, 0);
- assert!((u.charged_amount_usd - 0.05).abs() < f64::EPSILON);
-}
-
-#[test]
-fn final_assistant_message_is_skipped() {
- let mut m = EventMapper::new();
- let deltas = m.handle(ClaudeCodeEvent::Assistant {
- message: json!({"type":"message","role":"assistant","content":[]}),
- });
- assert!(deltas.is_empty());
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/input_builder.rs b/crates/openhuman-core/src/inference/provider/claude_code/input_builder.rs
deleted file mode 100644
index b1e8c2d265..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/input_builder.rs
+++ /dev/null
@@ -1,305 +0,0 @@
-//! Build the stream-json stdin payload fed to `claude --input-format stream-json`.
-//!
-//! The CLI consumes one JSON object per line on stdin. Each line looks
-//! like:
-//! { "type":"user", "message":{"role":"user","content":[{"type":"text","text":"..."}]} }
-//!
-//! v1 piping policy:
-//! - On a *new* CC session: send every history `ChatMessage` so claude
-//! has full context (system message is conveyed via
-//! `--append-system-prompt`, not stdin).
-//! - On a `--resume` of an existing CC session: claude already has prior
-//! turns server-side; we only send the last user turn.
-
-use base64::Engine as _;
-use serde_json::{json, Value};
-use std::io::Read;
-
-use crate::agent::messages::ChatMessage;
-use crate::agent::multimodal::{
- managed_attachment_path, parse_image_markers, rehydrate_image_placeholders,
-};
-
-const MAX_IMAGE_BYTES: usize = 5 * 1024 * 1024;
-
-/// Build the bytes to write to claude's stdin. Returns an empty `Vec`
-/// when there is nothing to send (caller should abort).
-pub fn build_stdin(messages: &[ChatMessage], is_new_session: bool) -> Vec<u8> {
- // Resolve any `[Image: … #att:<id>]` placeholders to on-disk `[IMAGE:<path>]`
- // markers so pasted images can be inlined below. No-op for messages that
- // carry no image placeholder, so plain-text turns are unaffected.
- let rehydrated = rehydrate_image_placeholders(messages);
- let messages: &[ChatMessage] = &rehydrated;
-
- // `--input-format stream-json` accepts ONLY user-role turns — replaying an
- // assistant turn fails with `Expected message role 'user', got 'assistant'`.
- // So we always emit exactly one user message: the trailing user turn. On a
- // *new* session (including a recreated one — see the session_store recovery
- // path) any prior turns are folded into a text preamble so the session keeps
- // its context instead of erroring; on resume the CLI already holds them.
- let non_system: Vec<&ChatMessage> = messages.iter().filter(|m| m.role != "system").collect();
- // A prompt is active only when the final non-system turn is from the
- // user. If history ends on an assistant/tool turn, replay all of it as
- // context on a new session; never resubmit an earlier answered prompt.
- let last_user_pos = non_system.iter().rposition(|m| m.role == "user");
- let active_user_pos = last_user_pos.filter(|&pos| pos == non_system.len() - 1);
-
- let mut content: Vec<Value> = Vec::new();
- if is_new_session {
- let context_end = active_user_pos.unwrap_or(non_system.len());
- if let Some(preamble) = prior_conversation_preamble(&non_system, context_end) {
- let preamble_blocks = content_blocks(&preamble);
- if preamble_blocks.iter().any(|block| block["type"] == "image") {
- content.extend(preamble_blocks);
- } else {
- // Preserve the historical single-block preamble shape when
- // there are no images to rehydrate.
- content.push(json!({"type": "text", "text": preamble}));
- }
- }
- }
- let Some(last_user_pos) = active_user_pos else {
- return if is_new_session && !content.is_empty() {
- let line = json!({
- "type": "user",
- "message": { "role": "user", "content": content },
- });
- let mut out = String::new();
- push_json_line(&mut out, &line);
- out.into_bytes()
- } else {
- Vec::new()
- };
- };
- // Pasted images arrive as inline `[IMAGE:data:…]` markers in the user turn's
- // content (the multimodal pipeline rehydrates them, and the native-provider
- // message bridge re-emits them from its typed image blocks — see
- // `message_convert::message_to_native_chat_message`). `content_blocks` splits
- // each marker into a real Anthropic `image` block below.
- content.extend(content_blocks(&non_system[last_user_pos].content));
- if content.is_empty() {
- return Vec::new();
- }
-
- let line = json!({
- "type": "user",
- "message": { "role": "user", "content": content },
- });
- let mut out = String::new();
- push_json_line(&mut out, &line);
- out.into_bytes()
-}
-
-/// Render the turns before `end` (the latest user turn) as a plain-text preamble
-/// so a newly-created CC session inherits the thread's context — the CLI can't
-/// accept assistant-role input, so this is the only way to seed prior turns.
-///
-/// A user turn with no assistant reply after it is skipped: that is a failed or
-/// pending attempt (e.g. a message that errored and was then re-asked), not part
-/// of the conversation. Replaying it would duplicate the re-asked current turn
-/// and make the message look like it "came through twice". Image markers are
-/// preserved so a recreated session retains the same multimodal context. Returns `None` when
-/// there is nothing to carry over (a genuinely fresh conversation).
-fn prior_conversation_preamble(non_system: &[&ChatMessage], end: usize) -> Option<String> {
- let mut turns = Vec::new();
- for (i, m) in non_system.iter().take(end).enumerate() {
- match m.role.as_str() {
- "assistant" => {
- let (text, _images) = parse_image_markers(&m.content);
- if !text.is_empty() {
- turns.push(format!("Assistant: {text}"));
- }
- }
- "user" => {
- // A consecutive group of user turns is answered when the
- // assistant follows the group. This preserves queued
- // steering messages while omitting a trailing attempt.
- let mut next = i + 1;
- while non_system
- .get(next)
- .is_some_and(|message| message.role == "user")
- {
- next += 1;
- }
- let answered = non_system
- .get(next)
- .is_some_and(|message| message.role == "assistant");
- if answered && !m.content.is_empty() {
- // Keep native image markers in the labelled transcript.
- // `content_blocks` below will convert real markers into
- // image blocks while leaving literal marker text alone.
- turns.push(format!("User: {}", m.content));
- }
- }
- _ => {}
- }
- }
- if turns.is_empty() {
- return None;
- }
- Some(format!(
- "[Earlier in this conversation]\n{}\n[End of earlier conversation]\n",
- turns.join("\n")
- ))
-}
-
-/// Split a message's text into stream-json content blocks: the prose as a
-/// `text` block, plus one native `image` block per `[IMAGE:<ref>]` marker (the
-/// `claude` CLI + Opus are vision-capable). An image that cannot be read
-/// degrades to a short text note rather than being silently dropped.
-fn content_blocks(raw: &str) -> Vec<Value> {
- const IMAGE_PREFIX: &str = "[IMAGE:";
- const NATIVE_IMAGE_PREFIX: &str = "[OH_IMAGE:";
- const LITERAL_NATIVE_IMAGE_PREFIX: &str = "[OH_IMAGE_LITERAL:";
- let mut blocks: Vec<Value> = Vec::new();
- let mut cursor = 0;
- while let Some((relative, prefix)) = [
- IMAGE_PREFIX,
- NATIVE_IMAGE_PREFIX,
- LITERAL_NATIVE_IMAGE_PREFIX,
- ]
- .iter()
- .filter_map(|prefix| raw[cursor..].find(prefix).map(|offset| (offset, *prefix)))
- .min_by_key(|(offset, _)| *offset)
- {
- let start = cursor + relative;
- let Some(end_relative) = raw[start..].find(']') else {
- blocks.push(json!({"type": "text", "text": &raw[cursor..]}));
- cursor = raw.len();
- break;
- };
- let end = start + end_relative + 1;
- if start > cursor {
- blocks.push(json!({"type": "text", "text": &raw[cursor..start]}));
- }
- let reference = &raw[start + prefix.len()..end - 1];
- if prefix == LITERAL_NATIVE_IMAGE_PREFIX {
- blocks.push(json!({
- "type": "text",
- "text": format!("[OH_IMAGE:{reference}]"),
- }));
- } else {
- match image_block(reference, prefix == NATIVE_IMAGE_PREFIX) {
- Some(block) => blocks.push(block),
- None if prefix == IMAGE_PREFIX => {
- // `[IMAGE:…]` is ordinary text unless it names a managed
- // attachment. Never interpret a user-typed data URI as an
- // instruction to send an image.
- blocks.push(json!({"type": "text", "text": &raw[start..end]}));
- }
- None => blocks.push(json!({
- "type": "text",
- "text": "[an attached image could not be read]"
- })),
- }
- }
- cursor = end;
- }
- if cursor < raw.len() {
- blocks.push(json!({"type": "text", "text": &raw[cursor..]}));
- }
- if blocks.is_empty() {
- // Preserve prior behaviour for a genuinely empty message.
- blocks.push(json!({"type": "text", "text": raw}));
- }
- blocks
-}
-
-/// Build an Anthropic `image` content block from an `[IMAGE:<ref>]` reference.
-/// `<ref>` is either a `data:` URI (inline base64) or an on-disk file path (a
-/// rehydrated attachment). Returns `None` when the ref cannot be resolved.
-fn image_block(reference: &str, native_marker: bool) -> Option<Value> {
- let (media_type, data_b64) = if native_marker {
- let rest = reference.strip_prefix("data:")?;
- let (mime, data) = rest.split_once(";base64,")?;
- let media_type = mime.to_ascii_lowercase();
- if !matches!(
- media_type.as_str(),
- "image/png" | "image/jpeg" | "image/gif" | "image/webp"
- ) {
- return None;
- }
- let bytes = base64::engine::general_purpose::STANDARD
- .decode(data)
- .ok()?;
- if bytes.len() > MAX_IMAGE_BYTES {
- return None;
- }
- (media_type, data.to_string())
- } else {
- let path = managed_attachment_path(reference)?;
- let attachment_id = path
- .file_name()
- .and_then(|name| name.to_str())
- .and_then(|name| name.split('.').next())
- .filter(|id| !id.is_empty())
- .unwrap_or("unknown");
- let mut file = match std::fs::File::open(&path) {
- Ok(file) => file,
- Err(error) => {
- tracing::warn!(
- target: "claude_code",
- attachment_id,
- error_kind = ?error.kind(),
- "[claude-code][input] managed attachment read failed"
- );
- return None;
- }
- };
- let mut bytes = Vec::new();
- if let Err(error) = file
- .by_ref()
- .take((MAX_IMAGE_BYTES + 1) as u64)
- .read_to_end(&mut bytes)
- {
- tracing::warn!(
- target: "claude_code",
- attachment_id,
- error_kind = ?error.kind(),
- "[claude-code][input] managed attachment read failed"
- );
- return None;
- }
- if bytes.len() > MAX_IMAGE_BYTES {
- tracing::warn!(
- target: "claude_code",
- attachment_id,
- max_bytes = MAX_IMAGE_BYTES,
- "[claude-code][input] managed attachment exceeds size cap"
- );
- return None;
- }
- (
- media_type_from_path(&path.to_string_lossy()),
- base64::engine::general_purpose::STANDARD.encode(bytes),
- )
- };
- Some(json!({
- "type": "image",
- "source": {"type": "base64", "media_type": media_type, "data": data_b64},
- }))
-}
-
-/// Best-effort media type from a file extension. Claude accepts jpeg/png/gif/webp.
-fn media_type_from_path(path: &str) -> String {
- let lower = path.to_ascii_lowercase();
- if lower.ends_with(".png") {
- "image/png"
- } else if lower.ends_with(".gif") {
- "image/gif"
- } else if lower.ends_with(".webp") {
- "image/webp"
- } else {
- "image/jpeg"
- }
- .to_string()
-}
-
-fn push_json_line(buf: &mut String, v: &Value) {
- buf.push_str(&serde_json::to_string(v).unwrap_or_default());
- buf.push('\n');
-}
-
-#[cfg(test)]
-#[path = "input_builder_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/input_builder_tests.rs b/crates/openhuman-core/src/inference/provider/claude_code/input_builder_tests.rs
deleted file mode 100644
index 237c084337..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/input_builder_tests.rs
+++ /dev/null
@@ -1,217 +0,0 @@
-use super::*;
-
-fn msg(role: &str, content: &str) -> ChatMessage {
- match role {
- "system" => ChatMessage::system(content),
- "user" => ChatMessage::user(content),
- "assistant" => ChatMessage::assistant(content),
- _ => ChatMessage::tool(content),
- }
-}
-
-/// Every row's `message.role` must be `"user"`. The CLI validates this
-/// before invoking the model and exits 1 with
-/// `Expected message role 'user', got 'assistant'` otherwise (#5711).
-/// Verified against Claude Code CLI 2.1.221.
-fn assert_every_row_is_a_user_role(payload: &str) {
- for (i, line) in payload.lines().enumerate() {
- let row: Value = serde_json::from_str(line).unwrap_or_else(|e| {
- panic!(
- "row {i} is not valid JSON: {e}
-{line}"
- )
- });
- assert_eq!(
- row["message"]["role"], "user",
- "row {i} must carry role=user, the only role CC stdin accepts
-{line}"
- );
- assert_eq!(row["type"], "user", "row {i} envelope type");
- }
-}
-
-#[test]
-fn new_session_never_emits_an_assistant_role() {
- let history = vec![
- msg("system", "you are helpful"),
- msg("user", "first user"),
- msg("assistant", "prior assistant"),
- msg("user", "latest user"),
- ];
- let s = String::from_utf8(build_stdin(&history, true)).unwrap();
- assert_every_row_is_a_user_role(&s);
- assert!(
- !s.contains("\"role\":\"assistant\""),
- "an assistant role row is what the CLI rejects:
-{s}"
- );
-}
-
-#[test]
-fn new_session_carries_prior_turns_as_one_labelled_transcript() {
- let history = vec![
- msg("system", "you are helpful"),
- msg("user", "hi"),
- msg("assistant", "hello"),
- msg("user", "how are you?"),
- ];
- let s = String::from_utf8(build_stdin(&history, true)).unwrap();
- let lines: Vec<_> = s.lines().collect();
-
- // The transcript and latest prompt are content blocks in one user row.
- assert_eq!(
- lines.len(),
- 1,
- "got:
-{s}"
- );
- assert!(lines[0].contains("User: hi"));
- assert!(lines[0].contains("Assistant: hello"));
- assert!(
- !lines[0].contains("you are helpful"),
- "the system message must not leak into the transcript"
- );
-
- // The prompt itself is passed through untouched, not folded in.
- let latest: Value = serde_json::from_str(lines[0]).unwrap();
- assert_eq!(latest["message"]["content"][1]["text"], "how are you?");
-}
-
-#[test]
-fn a_history_ending_on_an_assistant_turn_is_all_context() {
- // Switching an existing conversation to the CC provider can leave the
- // assistant speaking last; none of it is a fresh instruction.
- let history = vec![msg("user", "hi"), msg("assistant", "hello")];
- let s = String::from_utf8(build_stdin(&history, true)).unwrap();
- let lines: Vec<_> = s.lines().collect();
- assert_eq!(
- lines.len(),
- 1,
- "got:
-{s}"
- );
- assert_every_row_is_a_user_role(&s);
- assert!(lines[0].contains("User: hi"));
- assert!(lines[0].contains("Assistant: hello"));
-}
-
-#[test]
-fn a_single_user_turn_is_sent_verbatim_with_no_transcript() {
- let history = vec![msg("user", "just this")];
- let s = String::from_utf8(build_stdin(&history, true)).unwrap();
- let lines: Vec<_> = s.lines().collect();
- assert_eq!(lines.len(), 1);
- let row: Value = serde_json::from_str(lines[0]).unwrap();
- assert_eq!(row["message"]["content"][0]["text"], "just this");
-}
-
-#[test]
-fn resume_pipes_only_last_user_turn() {
- let history = vec![
- msg("user", "earlier turn"),
- msg("assistant", "earlier reply"),
- msg("user", "follow-up"),
- ];
- let bytes = build_stdin(&history, false);
- let s = String::from_utf8(bytes).unwrap();
- let lines: Vec<_> = s.lines().collect();
- assert_eq!(lines.len(), 1);
- assert!(lines[0].contains("\"follow-up\""));
- assert_every_row_is_a_user_role(&s);
-}
-
-#[test]
-fn empty_history_yields_empty_bytes() {
- let bytes = build_stdin(&[], true);
- assert!(bytes.is_empty());
-}
-
-#[test]
-fn image_blocks_preserve_text_order() {
- let s = String::from_utf8(build_stdin(
- &[ChatMessage::user(
- "before [OH_IMAGE:data:image/png;base64,QUJD] between [OH_IMAGE:data:image/gif;base64,R0lG] after",
- )],
- true,
- ))
- .unwrap();
- let row: Value = serde_json::from_str(s.lines().next().unwrap()).unwrap();
- let content = row["message"]["content"].as_array().unwrap();
- assert_eq!(content.len(), 5);
- assert_eq!(content[0]["text"], "before ");
- assert_eq!(content[1]["type"], "image");
- assert_eq!(content[2]["text"], " between ");
- assert_eq!(content[3]["type"], "image");
- assert_eq!(content[4]["text"], " after");
-}
-
-#[test]
-fn literal_file_marker_is_not_read() {
- let s = String::from_utf8(build_stdin(
- &[ChatMessage::user("read [IMAGE:/etc/hostname]")],
- true,
- ))
- .unwrap();
- assert!(!s.contains("\"type\":\"image\""), "{s}");
- assert!(s.contains("[IMAGE:/etc/hostname]"), "{s}");
-}
-
-#[test]
-fn new_session_history_preserves_answered_user_images() {
- let history = vec![
- ChatMessage::user("earlier [OH_IMAGE:data:image/png;base64,QUJD]"),
- ChatMessage::assistant("old answer"),
- ChatMessage::user("latest"),
- ];
- let s = String::from_utf8(build_stdin(&history, true)).unwrap();
- let row: Value = serde_json::from_str(s.lines().next().unwrap()).unwrap();
- let content = row["message"]["content"].as_array().unwrap();
- assert!(content.iter().any(|block| block["type"] == "image"));
- assert!(content.iter().any(|block| {
- block["text"]
- .as_str()
- .is_some_and(|text| text.contains("User: earlier "))
- }));
- assert!(s.contains("Assistant: old answer"));
-}
-
-#[test]
-fn consecutive_answered_user_turns_are_all_in_preamble() {
- let history = vec![
- ChatMessage::user("first steering"),
- ChatMessage::user("second steering"),
- ChatMessage::assistant("answer"),
- ChatMessage::user("latest"),
- ];
- let s = String::from_utf8(build_stdin(&history, true)).unwrap();
- assert!(s.contains("User: first steering"));
- assert!(s.contains("User: second steering"));
-}
-
-#[test]
-fn unterminated_image_marker_preserves_trailing_text() {
- let s = String::from_utf8(build_stdin(
- &[ChatMessage::user(
- "before [OH_IMAGE:data:image/png;base64,QUJD after",
- )],
- true,
- ))
- .unwrap();
- assert!(
- s.contains("before [OH_IMAGE:data:image/png;base64,QUJD after"),
- "{s}"
- );
-}
-
-#[test]
-fn invalid_native_images_use_the_text_fallback() {
- let s = String::from_utf8(build_stdin(
- &[ChatMessage::user(
- "bad [OH_IMAGE:data:image/svg+xml;base64,PHN2Zz4=] and [OH_IMAGE:data:image/png;base64,not-base64]",
- )],
- true,
- ))
- .unwrap();
- assert!(!s.contains("\"type\":\"image\""), "{s}");
- assert!(s.contains("an attached image could not be read"), "{s}");
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/mod.rs b/crates/openhuman-core/src/inference/provider/claude_code/mod.rs
deleted file mode 100644
index 01b270e4cd..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/mod.rs
+++ /dev/null
@@ -1,342 +0,0 @@
-//! Claude Code CLI provider.
-//!
-//! Drives Anthropic's `claude` CLI (`-p --output-format stream-json
-//! --verbose --include-partial-messages --resume <uuid>`) instead of
-//! calling the HTTP API directly. v2 will expose OpenHuman's native
-//! Rust tools back into the CLI over MCP; this Phase 2 cut runs the
-//! driver end-to-end with native CC built-ins disabled at the caller
-//! (no `--allowedTools` set means CC's own tools simply don't fire
-//! during a non-interactive `-p` turn).
-
-pub mod auth;
-pub mod auth_status;
-pub mod driver;
-pub mod event_mapper;
-pub mod input_builder;
-pub mod session_store;
-pub mod settings;
-pub mod stream_parser;
-pub mod types;
-pub mod version_check;
-
-use std::path::PathBuf;
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use tinyinference::model::{
- ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
-};
-use tokio::sync::Semaphore;
-
-use super::types::{ChatRequest, ChatResponse};
-use crate::agent::messages::ChatMessage;
-
-/// Provider string prefix used in the factory grammar: `claude-code:<model>`.
-pub const PROVIDER_PREFIX: &str = "claude-code:";
-
-/// Serializes tests that mutate process-global env vars (`ANTHROPIC_API_KEY`,
-/// `OPENHUMAN_CLAUDE_CODE_*`). `cargo test` runs tests in parallel within a
-/// crate, so without this lock the auth-status and auth resolvers race on
-/// `ANTHROPIC_API_KEY` (one sets it while another reads/removes it),
-/// producing flaky failures. Every env-touching test in this module acquires
-/// it first. Poison-tolerant: a panicking test must not wedge the suite.
-#[cfg(test)]
-pub(crate) static ENV_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
-
-/// Resolve the workspace directory the Claude Code provider operates against
-/// (where session state and [`settings`] live). Derived from the config file's
-/// parent so the RPC layer and the chat factory agree on the exact path. Falls
-/// back to `~/.openhuman` (then `./.openhuman`) when the config path has no
-/// parent.
-///
-/// **"Workspace" here is provider-local and means the OpenHuman config
-/// directory** (`~/.openhuman` by default) — the parent of `config.config_path`.
-/// It is deliberately *not*
-/// [`crate::config::Config::workspace_dir`] (the internal state dir
-/// `~/.openhuman/workspace`) and *not* the user's project root
-/// (`config.action_dir`, where the CLI's file tools run).
-pub fn workspace_dir_from_config(config: &crate::config::Config) -> PathBuf {
- config
- .config_path
- .parent()
- .map(PathBuf::from)
- .unwrap_or_else(|| {
- directories::UserDirs::new()
- .map(|d| d.home_dir().join(".openhuman"))
- .unwrap_or_else(|| PathBuf::from(".openhuman"))
- })
-}
-
-/// Max concurrent `claude` child processes per provider instance.
-/// Picked to match the v1 design doc (PLAN §11).
-pub const MAX_CONCURRENT_TURNS: usize = 4;
-
-/// CC-CLI-backed `Provider`. Owns a `Semaphore` that caps concurrent
-/// child processes and an `Arc<SessionStore>` for per-thread UUIDs.
-#[derive(Clone)]
-pub struct ClaudeCodeProvider {
- pub model: String,
- bin_path: PathBuf,
- workspace_dir: PathBuf,
- /// User's project root (`config.action_dir`) — Claude Code runs here so its
- /// file tools act on the user's code, not the internal workspace.
- project_dir: PathBuf,
- anthropic_api_key: Option<String>,
- semaphore: Arc<Semaphore>,
- session_store: Arc<session_store::SessionStore>,
- profile: ModelProfile,
-}
-
-impl ClaudeCodeProvider {
- /// Construct with the CLI path resolved up-front (via `version_check`).
- pub fn new(
- model: impl Into<String>,
- bin_path: PathBuf,
- workspace_dir: PathBuf,
- project_dir: PathBuf,
- anthropic_api_key: Option<String>,
- ) -> Self {
- let model = model.into();
- let session_store = Arc::new(session_store::SessionStore::open(&workspace_dir));
- Self {
- profile: ModelProfile {
- provider: Some("claude-code".to_string()),
- model: Some(model.clone()),
- tool_calling: true,
- parallel_tool_calls: true,
- streaming: true,
- streaming_tool_chunks: true,
- ..Default::default()
- },
- model,
- bin_path,
- workspace_dir,
- project_dir,
- anthropic_api_key,
- semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_TURNS)),
- session_store,
- }
- }
-
- /// Build the provider from environment + workspace. `project_dir` is the
- /// user's code root (`config.action_dir`) that the coding agent operates
- /// in. Errors when the CLI is not installed or below `MIN_CLI_VERSION`.
- pub fn from_env(
- model: impl Into<String>,
- workspace_dir: PathBuf,
- project_dir: PathBuf,
- ) -> anyhow::Result<Self> {
- match version_check::probe() {
- types::CliStatus::Ok { path, .. } => {
- let (_, key) = auth::resolve();
- Ok(Self::new(
- model,
- PathBuf::from(path),
- workspace_dir,
- project_dir,
- key,
- ))
- }
- types::CliStatus::NotInstalled => {
- anyhow::bail!(
- "[claude-code] `claude` CLI not installed. Install Claude Code CLI \
- ({}) >= {} and retry.",
- "https://docs.anthropic.com/en/docs/claude-code",
- types::MIN_CLI_VERSION
- )
- }
- types::CliStatus::Outdated {
- version,
- min_required,
- path,
- } => anyhow::bail!(
- "[claude-code] `claude` CLI at {} is version {}; require >= {}",
- path,
- version,
- min_required
- ),
- types::CliStatus::Unusable { path, reason } => anyhow::bail!(
- "[claude-code] `claude` CLI at {} unusable: {}",
- path,
- reason
- ),
- }
- }
-
- async fn run_chat(
- &self,
- request: ChatRequest<'_>,
- model_override: Option<&str>,
- ) -> anyhow::Result<ChatResponse> {
- // Cap concurrent CC processes.
- let _permit = self
- .semaphore
- .clone()
- .acquire_owned()
- .await
- .map_err(|e| anyhow::anyhow!("claude-code semaphore closed: {e}"))?;
-
- // Extract system prompt + thread_id from the request.
- let append_system_prompt = request
- .messages
- .iter()
- .find(|m| m.role == "system")
- .map(|m| m.content.clone());
-
- // OpenHuman doesn't pass thread_id directly through ChatRequest yet
- // (Phase 4 will). For Phase 2 we key sessions on a stable hash of
- // the conversation so /resume kicks in across consecutive turns.
- let thread_id = thread_key_from_messages(request.messages);
-
- let model = model_override.unwrap_or(&self.model).to_string();
-
- let turn = driver::TurnContext {
- bin_path: self.bin_path.clone(),
- workspace_dir: self.workspace_dir.clone(),
- project_dir: self.project_dir.clone(),
- thread_id,
- model,
- append_system_prompt,
- messages: request.messages,
- session_store: self.session_store.clone(),
- stream: request.stream,
- anthropic_api_key: self.anthropic_api_key.clone(),
- };
- driver::run_turn(turn).await
- }
-}
-
-fn map_model_error(error: anyhow::Error) -> tinyinference::Error {
- let message = format!("claude-code model call failed: {error}");
- if crate::inference::provider::error_classify::is_non_retryable(&error) {
- tinyinference::Error::Validation(message)
- } else {
- tinyinference::Error::Model(message)
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for ClaudeCodeProvider {
- fn profile(&self) -> Option<&ModelProfile> {
- Some(&self.profile)
- }
-
- /// Identity for harness response-cache scoping. Names the binary and the
- /// model, never the API key.
- fn cache_identity(&self) -> Option<String> {
- Some(format!(
- "claude_code:{}:{}",
- self.bin_path.display(),
- self.model
- ))
- }
-
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference::Result<ModelResponse> {
- let messages = crate::agent::tinyagents::model::native_chat_messages(&request);
- let response = self
- .run_chat(
- ChatRequest {
- messages: &messages,
- tools: None,
- stream: None,
- max_tokens: request.max_tokens,
- },
- None,
- )
- .await
- .map_err(map_model_error)?;
- Ok(crate::agent::tinyagents::model::native_model_response(
- &response,
- ))
- }
-
- async fn stream(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference::Result<ModelStream> {
- let provider = self.clone();
- let label = self.model.clone();
- let (item_tx, item_rx) = tokio::sync::mpsc::unbounded_channel::<ModelStreamItem>();
- let handle = tokio::spawn(async move {
- let _ = item_tx.send(ModelStreamItem::Started);
- let messages = crate::agent::tinyagents::model::native_chat_messages(&request);
- let (delta_tx, mut delta_rx) =
- tokio::sync::mpsc::channel::<super::types::ProviderDelta>(64);
- let chat = async {
- provider
- .run_chat(
- ChatRequest {
- messages: &messages,
- tools: None,
- stream: Some(&delta_tx),
- max_tokens: request.max_tokens,
- },
- None,
- )
- .await
- };
- tokio::pin!(chat);
-
- let response = loop {
- tokio::select! {
- delta = delta_rx.recv() => {
- if let Some(delta) = delta {
- crate::agent::tinyagents::model::forward_provider_delta(
- &item_tx,
- delta,
- );
- }
- }
- response = &mut chat => break response,
- }
- };
- while let Ok(delta) = delta_rx.try_recv() {
- crate::agent::tinyagents::model::forward_provider_delta(&item_tx, delta);
- }
-
- let terminal = match response {
- Ok(response) => ModelStreamItem::Completed(
- crate::agent::tinyagents::model::native_model_response(&response),
- ),
- Err(error) => ModelStreamItem::Failed(map_model_error(error).to_string()),
- };
- let _ = item_tx.send(terminal);
- });
- let guard = crate::agent::tinyagents::abort_guard::AbortOnDrop::new(handle, label);
- let stream =
- futures_util::stream::unfold((item_rx, guard), |(mut receiver, guard)| async move {
- receiver.recv().await.map(|item| (item, (receiver, guard)))
- });
- Ok(Box::pin(stream))
- }
-}
-
-/// Stable session key derived from the conversation's first user message.
-/// Best-effort — Phase 4 will plumb the real OpenHuman thread id through
-/// `ChatRequest`.
-///
-/// Uses SHA-256 (truncated) so the key is stable across Rust compiler
-/// versions (unlike `DefaultHasher` which may change between rustc
-/// releases, breaking persisted session lookups).
-fn thread_key_from_messages(messages: &[ChatMessage]) -> String {
- use sha2::{Digest, Sha256};
- let first = messages
- .iter()
- .find(|m| m.role == "user")
- .map(|m| m.content.as_str())
- .unwrap_or("");
- let digest = Sha256::digest(first.as_bytes());
- format!(
- "hash_{:032x}",
- u128::from_be_bytes(digest[..16].try_into().unwrap())
- )
-}
-
-#[cfg(test)]
-#[path = "mod_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/mod_tests.rs b/crates/openhuman-core/src/inference/provider/claude_code/mod_tests.rs
deleted file mode 100644
index 71224c3c9f..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/mod_tests.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-use super::*;
-
-#[test]
-fn chat_model_profile_advertises_native_streaming_tools() {
- let workspace = tempfile::tempdir().expect("workspace");
- let project = tempfile::tempdir().expect("project");
- let provider = ClaudeCodeProvider::new(
- "claude-sonnet-4-6",
- PathBuf::from("claude"),
- workspace.path().to_path_buf(),
- project.path().to_path_buf(),
- None,
- );
-
- let profile = provider.profile().expect("profile");
- assert_eq!(profile.provider.as_deref(), Some("claude-code"));
- assert_eq!(profile.model.as_deref(), Some("claude-sonnet-4-6"));
- assert!(profile.tool_calling);
- assert!(profile.parallel_tool_calls);
- assert!(profile.streaming);
- assert!(profile.streaming_tool_chunks);
-}
-
-#[test]
-fn thread_key_is_stable_for_same_conversation() {
- let a = vec![ChatMessage::user("hello world")];
- let b = vec![
- ChatMessage::user("hello world"),
- ChatMessage::assistant("hi"),
- ];
- assert_eq!(thread_key_from_messages(&a), thread_key_from_messages(&b));
-}
-
-#[test]
-fn thread_key_diverges_for_different_first_user() {
- let a = vec![ChatMessage::user("alpha")];
- let b = vec![ChatMessage::user("beta")];
- assert_ne!(thread_key_from_messages(&a), thread_key_from_messages(&b));
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/session_store.rs b/crates/openhuman-core/src/inference/provider/claude_code/session_store.rs
deleted file mode 100644
index 6eaf092779..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/session_store.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-//! Per-thread CC session UUID persistence.
-//!
-//! The `claude` CLI's `--resume <uuid>` only reuses a server-side session
-//! if we pass it the same UUIDv4 we used the first time. We map an
-//! OpenHuman thread id → CC session UUID in a JSON file under the
-//! workspace.
-
-use std::collections::HashMap;
-use std::path::{Path, PathBuf};
-use std::sync::Mutex;
-
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Default, Serialize, Deserialize)]
-struct StoreFile {
- /// thread_id → CC session uuid (v4)
- sessions: HashMap<String, String>,
-}
-
-/// Disk-backed session store. Cheap to clone — it's `Arc`-shareable via
-/// the holding `ClaudeCodeProvider`.
-#[derive(Debug)]
-pub struct SessionStore {
- path: PathBuf,
- inner: Mutex<StoreFile>,
-}
-
-impl SessionStore {
- /// Open (or initialize) the session store at `workspace/claude-code-sessions.json`.
- pub fn open(workspace_dir: &Path) -> Self {
- let path = workspace_dir.join("claude-code-sessions.json");
- let inner = std::fs::read_to_string(&path)
- .ok()
- .and_then(|s| serde_json::from_str::<StoreFile>(&s).ok())
- .unwrap_or_default();
- Self {
- path,
- inner: Mutex::new(inner),
- }
- }
-
- /// Lookup an existing CC session UUID for `thread_id`.
- pub fn get(&self, thread_id: &str) -> Option<String> {
- let guard = self.inner.lock().expect("session store mutex poisoned");
- guard.sessions.get(thread_id).cloned()
- }
-
- /// Persist a thread → UUID mapping.
- pub fn set(&self, thread_id: &str, uuid: &str) -> std::io::Result<()> {
- let mut guard = self.inner.lock().expect("session store mutex poisoned");
- guard
- .sessions
- .insert(thread_id.to_string(), uuid.to_string());
- let serialized = serde_json::to_string_pretty(&*guard).map_err(std::io::Error::other)?;
- if let Some(parent) = self.path.parent() {
- std::fs::create_dir_all(parent)?;
- }
- std::fs::write(&self.path, serialized)
- }
-}
-
-/// Random RFC-4122 v4 UUID, formatted lower-case with hyphens.
-pub fn generate_uuid_v4() -> String {
- use rand::RngExt as _;
- let mut bytes = [0u8; 16];
- rand::rng().fill(&mut bytes);
- bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
- bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10
- format!(
- "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
- bytes[0], bytes[1], bytes[2], bytes[3],
- bytes[4], bytes[5],
- bytes[6], bytes[7],
- bytes[8], bytes[9],
- bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
- )
-}
-
-/// CC accepts only RFC-4122 v4. Older stores might carry pre-v4 strings;
-/// we treat those as missing and regenerate.
-pub fn is_uuid_v4(s: &str) -> bool {
- let s = s.as_bytes();
- if s.len() != 36 {
- return false;
- }
- let hyphens = [8, 13, 18, 23];
- for (i, b) in s.iter().enumerate() {
- let is_hyphen = hyphens.contains(&i);
- if is_hyphen {
- if *b != b'-' {
- return false;
- }
- } else if !b.is_ascii_hexdigit() {
- return false;
- }
- }
- // version nibble (index 14) must be '4'; variant nibble (index 19)
- // must be one of 8/9/a/b
- s[14] == b'4' && matches!(s[19], b'8' | b'9' | b'a' | b'b' | b'A' | b'B')
-}
-
-#[cfg(test)]
-#[path = "session_store_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/session_store_tests.rs b/crates/openhuman-core/src/inference/provider/claude_code/session_store_tests.rs
deleted file mode 100644
index df3f4ec97a..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/session_store_tests.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-use super::*;
-use tempfile::tempdir;
-
-#[test]
-fn uuid_v4_format() {
- let id = generate_uuid_v4();
- assert!(is_uuid_v4(&id), "generated id should be v4: {id}");
-}
-
-#[test]
-fn rejects_non_v4() {
- assert!(!is_uuid_v4("not-a-uuid"));
- assert!(!is_uuid_v4("cc_abc123"));
- // version 1 uuid (nibble at 14 is '1')
- assert!(!is_uuid_v4("00000000-0000-1000-8000-000000000000"));
-}
-
-#[test]
-fn roundtrip_set_and_get() {
- let dir = tempdir().unwrap();
- let store = SessionStore::open(dir.path());
- assert!(store.get("thread_a").is_none());
- store.set("thread_a", "abc").unwrap();
- let reopened = SessionStore::open(dir.path());
- assert_eq!(reopened.get("thread_a").as_deref(), Some("abc"));
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/settings.rs b/crates/openhuman-core/src/inference/provider/claude_code/settings.rs
deleted file mode 100644
index cf9c4a0a29..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/settings.rs
+++ /dev/null
@@ -1,107 +0,0 @@
-//! Persisted, self-contained Claude Code provider settings.
-//!
-//! The only Claude-Code-specific knob exposed to the user — full access
-//! (`bypassPermissions` + full native toolset) vs the default `acceptEdits`
-//! posture — lives in its own small JSON file rather than in the central
-//! [`crate::config::Config`]. Keeping it module-local means the
-//! toggle is easy to reason about and trivial to remove, and it avoids
-//! threading a Claude-Code-only flag through the shared config/RPC plumbing.
-//!
-//! **Where the file actually is:** the directory
-//! [`super::workspace_dir_from_config`] returns — the parent of
-//! `config.config_path`, i.e. the OpenHuman **config directory** (`~/.openhuman`
-//! by default), so the file sits next to `config.toml`. Despite the parameter
-//! name below, that is *not* [`crate::config::Config::workspace_dir`]
-//! (the internal state dir, `~/.openhuman/workspace`) and *not* the user's
-//! project root (`config.action_dir`).
-//!
-//! Read at turn time by [`super::driver`]; written by the
-//! `inference.claude_code_set_full_access` RPC. The
-//! `OPENHUMAN_CLAUDE_CODE_PERMISSION_MODE` env var overrides this at the driver
-//! layer (debugging / power users).
-
-use std::path::{Path, PathBuf};
-
-use serde::{Deserialize, Serialize};
-
-/// File name holding the persisted toggle, written into the directory the
-/// caller passes (the OpenHuman config dir — see the module docs).
-const SETTINGS_FILE: &str = "claude_code_settings.json";
-
-/// Persisted Claude Code provider settings. Defaults are the safe posture.
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct ClaudeCodeSettings {
- /// When true, Claude Code runs with `--permission-mode bypassPermissions`
- /// plus its complete native toolset (Bash/network/subagents). Default
- /// false → `acceptEdits` (auto-apply file edits, gate everything else).
- #[serde(default)]
- pub full_access: bool,
-}
-
-fn settings_path(workspace_dir: &Path) -> PathBuf {
- workspace_dir.join(SETTINGS_FILE)
-}
-
-/// Load settings from `workspace_dir` — the Claude Code provider's own notion
-/// of a workspace, which is the OpenHuman config dir (see the module docs), not
-/// [`crate::config::Config::workspace_dir`]. A missing or
-/// unreadable/corrupt file yields defaults (full access OFF) — fail safe, never
-/// fail open.
-pub fn load(workspace_dir: &Path) -> ClaudeCodeSettings {
- let path = settings_path(workspace_dir);
- match std::fs::read(&path) {
- Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
- log::warn!(
- "[claude-code][settings] corrupt {} ({e}); using safe defaults",
- path.display()
- );
- ClaudeCodeSettings::default()
- }),
- Err(e) => {
- log::debug!(
- "[claude-code][settings] no settings at {} ({e}); using defaults",
- path.display()
- );
- ClaudeCodeSettings::default()
- }
- }
-}
-
-/// Persist `settings` to `workspace_dir`, creating the directory if needed.
-pub fn save(workspace_dir: &Path, settings: &ClaudeCodeSettings) -> std::io::Result<()> {
- let path = settings_path(workspace_dir);
- if let Some(parent) = path.parent() {
- std::fs::create_dir_all(parent)?;
- }
- let json = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?;
- std::fs::write(&path, json)?;
- log::debug!(
- "[claude-code][settings] saved full_access={} → {}",
- settings.full_access,
- path.display()
- );
- Ok(())
-}
-
-/// Load settings for the directory implied by `config` — the parent of
-/// `config.config_path`, resolved via [`super::workspace_dir_from_config`].
-/// Keeps path resolution + file IO out of the RPC handler so `schemas.rs` stays
-/// a thin delegator.
-pub fn load_for_config(config: &crate::config::Config) -> ClaudeCodeSettings {
- load(&super::workspace_dir_from_config(config))
-}
-
-/// Persist the full-access toggle for the workspace implied by `config` and
-/// return the saved settings.
-pub fn save_full_access_for_config(
- config: &crate::config::Config,
- full_access: bool,
-) -> std::io::Result<ClaudeCodeSettings> {
- let settings = ClaudeCodeSettings { full_access };
- save(&super::workspace_dir_from_config(config), &settings)?;
- Ok(settings)
-}
-
-#[cfg(test)]
-#[path = "settings_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/settings_tests.rs b/crates/openhuman-core/src/inference/provider/claude_code/settings_tests.rs
deleted file mode 100644
index 56fa5e4345..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/settings_tests.rs
+++ /dev/null
@@ -1,88 +0,0 @@
-use super::*;
-
-#[test]
-fn load_missing_file_returns_safe_defaults() {
- let dir = std::env::temp_dir().join("oh_cc_settings_missing_test");
- let _ = std::fs::remove_dir_all(&dir);
- let s = load(&dir);
- assert!(!s.full_access, "missing settings must default to OFF");
-}
-
-#[test]
-fn save_then_load_roundtrips() {
- let dir = std::env::temp_dir().join("oh_cc_settings_roundtrip_test");
- let _ = std::fs::remove_dir_all(&dir);
- std::fs::create_dir_all(&dir).unwrap();
- save(&dir, &ClaudeCodeSettings { full_access: true }).unwrap();
- assert!(
- load(&dir).full_access,
- "saved full_access=true must persist"
- );
- save(&dir, &ClaudeCodeSettings { full_access: false }).unwrap();
- assert!(
- !load(&dir).full_access,
- "toggling back to false must persist"
- );
- let _ = std::fs::remove_dir_all(&dir);
-}
-
-#[test]
-fn load_corrupt_file_returns_safe_defaults() {
- let dir = std::env::temp_dir().join("oh_cc_settings_corrupt_test");
- let _ = std::fs::remove_dir_all(&dir);
- std::fs::create_dir_all(&dir).unwrap();
- std::fs::write(settings_path(&dir), b"{not json").unwrap();
- assert!(
- !load(&dir).full_access,
- "corrupt settings must fail safe to OFF"
- );
- let _ = std::fs::remove_dir_all(&dir);
-}
-
-/// Pins **where** the settings file lands (#6075 part 2): beside `config.toml`
-/// in the OpenHuman config dir.
-///
-/// The RPC schema description and this module's docs both name that location,
-/// and they previously said "under the workspace" — which reads as
-/// `Config::workspace_dir` (`~/.openhuman/workspace`) or the user's project
-/// root. Building a config whose three candidate directories are all distinct
-/// makes the assertion discriminating: it fails if the resolution ever moves to
-/// either of the other two, so the docs cannot silently go stale again.
-#[test]
-fn save_for_config_writes_beside_config_toml_not_workspace_or_action_dir() {
- let tmp = tempfile::TempDir::new().expect("tempdir");
- let config_dir = tmp.path().join("config-dir");
- let workspace_dir = config_dir.join("workspace");
- let action_dir = tmp.path().join("projects");
- std::fs::create_dir_all(&workspace_dir).expect("workspace dir");
- std::fs::create_dir_all(&action_dir).expect("action dir");
-
- let config = crate::config::Config {
- config_path: config_dir.join("config.toml"),
- workspace_dir: workspace_dir.clone(),
- action_dir: action_dir.clone(),
- ..Default::default()
- };
-
- let saved = save_full_access_for_config(&config, true).expect("save settings");
- assert!(saved.full_access);
-
- assert!(
- config_dir.join(SETTINGS_FILE).is_file(),
- "settings must land next to config.toml in {}",
- config_dir.display()
- );
- assert!(
- !workspace_dir.join(SETTINGS_FILE).exists(),
- "settings must NOT land in Config::workspace_dir"
- );
- assert!(
- !action_dir.join(SETTINGS_FILE).exists(),
- "settings must NOT land in Config::action_dir"
- );
-
- assert!(
- load_for_config(&config).full_access,
- "load_for_config must read back from the same directory it wrote to"
- );
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/stream_parser.rs b/crates/openhuman-core/src/inference/provider/claude_code/stream_parser.rs
deleted file mode 100644
index 69e6ffc96a..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/stream_parser.rs
+++ /dev/null
@@ -1,237 +0,0 @@
-//! Line-buffered JSONL parser for `claude --output-format stream-json`.
-//!
-//! The CLI writes one JSON object per line on stdout. Each object has a
-//! `type` discriminator (`system`, `user`, `assistant`, `stream_event`,
-//! `result`, `error`, `rate_limit_event`). We keep variants permissive
-//! (everything is `serde_json::Value`) so a minor CLI schema bump does
-//! not break the parser — the event mapper interprets what it knows.
-
-use serde_json::Value;
-
-/// One decoded event from the `claude` CLI stdout stream.
-#[derive(Debug, Clone)]
-pub enum ClaudeCodeEvent {
- System {
- session_id: Option<String>,
- schema_version: Option<String>,
- raw: Value,
- },
- User {
- message: Value,
- },
- Assistant {
- message: Value,
- },
- StreamEvent {
- event: Value,
- },
- RateLimit {
- raw: Value,
- },
- Result {
- subtype: Option<String>,
- usage: Option<Value>,
- total_cost_usd: Option<f64>,
- raw: Value,
- },
- Error {
- message: String,
- },
- /// JSONL line that failed to parse. Kept so the driver can log without
- /// dropping silently. Not surfaced as a `ProviderDelta`.
- ParseError {
- line: String,
- reason: String,
- },
-}
-
-/// Stateful parser that takes byte chunks from `proc.stdout` and emits
-/// fully-formed events on each newline.
-#[derive(Debug, Default)]
-pub struct StreamJsonParser {
- buffer: String,
- /// Bytes of an incomplete UTF-8 sequence carried over from the previous chunk.
- ///
- /// `feed_bytes` is handed arbitrary read boundaries, so a multi-byte character
- /// can straddle two chunks. Decoding each chunk on its own replaced both halves
- /// with U+FFFD, and the JSON still parsed -- the replacement character is legal
- /// inside a string -- so the corruption reached the transcript silently.
- pending: Vec<u8>,
- /// First-seen `schema_version` from a `system` event, if any.
- pub schema_version: Option<String>,
-}
-
-/// Decode `bytes` as UTF-8, returning the text and any incomplete trailing
-/// sequence to carry into the next chunk.
-///
-/// Invalid bytes are replaced, as `from_utf8_lossy` would — the stream must not
-/// stall on input that will never become valid. The difference is that only the
-/// invalid *sequence* is consumed, and decoding then continues, so an incomplete
-/// character at the very end is still carried.
-///
-/// Handing the whole remainder to `from_utf8_lossy` after the first bad byte
-/// looks equivalent and is not: it replaces a trailing partial character before
-/// its other half has arrived, which is the corruption this parser carries
-/// `pending` to avoid. One stray byte earlier in the chunk was enough to bring
-/// it back.
-fn decode_carrying_tail(bytes: &[u8]) -> (String, Vec<u8>) {
- let mut decoded = String::new();
- let mut rest = bytes;
-
- loop {
- match std::str::from_utf8(rest) {
- Ok(text) => {
- decoded.push_str(text);
- return (decoded, Vec::new());
- }
- Err(err) => {
- let valid = err.valid_up_to();
- // `valid_up_to` guarantees this prefix is valid UTF-8.
- decoded.push_str(&String::from_utf8_lossy(&rest[..valid]));
- match err.error_len() {
- // An incomplete tail: hold it for the next chunk.
- None => return (decoded, rest[valid..].to_vec()),
- // One replacement per invalid sequence, matching lossy
- // semantics, then carry on with what follows it.
- Some(len) => {
- decoded.push(char::REPLACEMENT_CHARACTER);
- rest = &rest[valid + len..];
- }
- }
- }
- }
- }
-}
-
-impl StreamJsonParser {
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Append a UTF-8 byte chunk and return any events whose terminating
- /// newline arrived in this chunk.
- ///
- /// See [`decode_carrying_tail`] for the decode contract.
- pub fn feed_bytes(&mut self, chunk: &[u8]) -> Vec<ClaudeCodeEvent> {
- // Decode only complete sequences and carry the trailing partial one into the
- // next chunk. `valid_up_to()` is the boundary; anything after it is either an
- // incomplete tail (keep it) or genuinely invalid input (replace it, as before).
- let bytes: &[u8] = if self.pending.is_empty() {
- chunk
- } else {
- self.pending.extend_from_slice(chunk);
- &self.pending[..]
- };
- let (decoded, carry) = decode_carrying_tail(bytes);
- self.pending = carry;
- self.buffer.push_str(&decoded);
- self.flush()
- }
-
- /// Append a string chunk.
- pub fn feed(&mut self, chunk: &str) -> Vec<ClaudeCodeEvent> {
- self.buffer.push_str(chunk);
- self.flush()
- }
-
- /// Drain any remaining buffered content. Call on EOF.
- pub fn end(&mut self) -> Vec<ClaudeCodeEvent> {
- // No further chunk is coming, so a held incomplete sequence can never be
- // completed. Release it lossily rather than dropping it: that is what the
- // per-chunk decode produced before the carry-over existed, and silently
- // discarding trailing bytes would be a different kind of data loss than the
- // one this parser is fixing.
- if !self.pending.is_empty() {
- let tail = std::mem::take(&mut self.pending);
- self.buffer.push_str(&String::from_utf8_lossy(&tail));
- }
- if !self.buffer.is_empty() && !self.buffer.ends_with('\n') {
- self.buffer.push('\n');
- }
- self.flush()
- }
-
- fn flush(&mut self) -> Vec<ClaudeCodeEvent> {
- let mut out = Vec::new();
- loop {
- let Some(nl) = self.buffer.find('\n') else {
- break;
- };
- let line = self.buffer[..nl].trim().to_string();
- self.buffer.drain(..=nl);
- if line.is_empty() {
- continue;
- }
- match serde_json::from_str::<Value>(&line) {
- Ok(v) => out.push(self.decode(v)),
- Err(e) => out.push(ClaudeCodeEvent::ParseError {
- line,
- reason: e.to_string(),
- }),
- }
- }
- out
- }
-
- fn decode(&mut self, v: Value) -> ClaudeCodeEvent {
- let ty = v.get("type").and_then(Value::as_str).unwrap_or("");
- match ty {
- "system" => {
- let session_id = v
- .get("session_id")
- .and_then(Value::as_str)
- .map(str::to_string);
- let schema_version = v
- .get("schema_version")
- .and_then(Value::as_str)
- .map(str::to_string);
- if let Some(sv) = &schema_version {
- if self.schema_version.is_none() {
- self.schema_version = Some(sv.clone());
- }
- }
- ClaudeCodeEvent::System {
- session_id,
- schema_version,
- raw: v,
- }
- }
- "user" => ClaudeCodeEvent::User {
- message: v.get("message").cloned().unwrap_or(Value::Null),
- },
- "assistant" => ClaudeCodeEvent::Assistant {
- message: v.get("message").cloned().unwrap_or(Value::Null),
- },
- "stream_event" => ClaudeCodeEvent::StreamEvent {
- event: v.get("event").cloned().unwrap_or(Value::Null),
- },
- "rate_limit_event" => ClaudeCodeEvent::RateLimit { raw: v },
- "result" => {
- let subtype = v.get("subtype").and_then(Value::as_str).map(str::to_string);
- let usage = v.get("usage").cloned();
- let total_cost_usd = v.get("total_cost_usd").and_then(Value::as_f64);
- ClaudeCodeEvent::Result {
- subtype,
- usage,
- total_cost_usd,
- raw: v,
- }
- }
- "error" => ClaudeCodeEvent::Error {
- message: v
- .get("error")
- .and_then(Value::as_str)
- .unwrap_or("claude-code error")
- .to_string(),
- },
- other => ClaudeCodeEvent::ParseError {
- line: v.to_string(),
- reason: format!("unknown event type `{other}`"),
- },
- }
- }
-}
-
-#[cfg(test)]
-#[path = "stream_parser_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/stream_parser_tests.rs b/crates/openhuman-core/src/inference/provider/claude_code/stream_parser_tests.rs
deleted file mode 100644
index 36b6cdc4ae..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/stream_parser_tests.rs
+++ /dev/null
@@ -1,241 +0,0 @@
-use super::*;
-
-#[test]
-fn parses_multiline_chunk() {
- let mut p = StreamJsonParser::new();
- let chunk = r#"{"type":"system","session_id":"s1","schema_version":"2.0"}
-{"type":"assistant","message":{"type":"content_block_start","index":0,"content_block":{"type":"text"}}}
-"#;
- let events = p.feed(chunk);
- assert_eq!(events.len(), 2);
- assert_eq!(p.schema_version.as_deref(), Some("2.0"));
- assert!(matches!(events[0], ClaudeCodeEvent::System { .. }));
- assert!(matches!(events[1], ClaudeCodeEvent::Assistant { .. }));
-}
-
-#[test]
-fn handles_split_lines_across_chunks() {
- let mut p = StreamJsonParser::new();
- assert!(p.feed("{\"type\":\"system\"").is_empty());
- assert!(p.feed(",\"session_id\":\"s1\"}").is_empty());
- let events = p.feed("\n");
- assert_eq!(events.len(), 1);
- assert!(matches!(events[0], ClaudeCodeEvent::System { .. }));
-}
-
-#[test]
-fn flushes_trailing_line_on_end() {
- let mut p = StreamJsonParser::new();
- assert!(p
- .feed(r#"{"type":"result","subtype":"success"}"#)
- .is_empty());
- let events = p.end();
- assert_eq!(events.len(), 1);
- assert!(matches!(events[0], ClaudeCodeEvent::Result { .. }));
-}
-
-#[test]
-fn unknown_type_becomes_parse_error() {
- let mut p = StreamJsonParser::new();
- let events = p.feed("{\"type\":\"weird\"}\n");
- assert!(matches!(events[0], ClaudeCodeEvent::ParseError { .. }));
-}
-
-#[test]
-fn bad_json_becomes_parse_error() {
- let mut p = StreamJsonParser::new();
- let events = p.feed("not json\n");
- assert!(matches!(events[0], ClaudeCodeEvent::ParseError { .. }));
-}
-
-/// A stream that ends mid-character must not swallow the partial bytes.
-/// Before the carry-over existed, `from_utf8_lossy` turned them into U+FFFD
-/// immediately; holding them means `end()` has to release them, or the last
-/// line of a truncated stream disappears entirely.
-#[test]
-fn end_flushes_an_incomplete_trailing_sequence() {
- let line = serde_json::json!({
- "type": "system",
- "session_id": "x",
- "schema_version": "2.0"
- })
- .to_string();
- let mut bytes = line.into_bytes();
- // A lone lead byte: a genuine incomplete tail, and no newline follows.
- bytes.push(0xE4);
-
- let mut p = StreamJsonParser::new();
- assert!(
- p.feed_bytes(&bytes).is_empty(),
- "no newline yet, nothing emitted"
- );
- let events = p.end();
- assert_eq!(
- events.len(),
- 1,
- "the buffered line must still be emitted at EOF"
- );
- // The held byte is released as a replacement character rather than vanishing,
- // which is what the per-chunk decode produced before the carry-over existed.
- //
- // Asserted on the field that carries it, not on the Debug rendering: a
- // `contains` over `{:?}` passes if U+FFFD turns up anywhere in any field, so it
- // would keep passing if the byte were released into the wrong place. The lone
- // 0xE4 lands after the closing brace, which is why this is a `ParseError` and
- // not a `System` event -- the released byte makes the line invalid JSON.
- match &events[0] {
- ClaudeCodeEvent::ParseError { line, .. } => assert!(
- line.ends_with(char::REPLACEMENT_CHARACTER),
- "the released byte should be the last character of the line, got {line:?}"
- ),
- other => panic!("expected the unparsable line to be reported, got {other:?}"),
- }
-}
-
-/// An invalid byte earlier in the chunk must not cost the incomplete
-/// character at the end of it.
-///
-/// Handing everything after the first bad byte to `from_utf8_lossy` replaces
-/// a trailing partial sequence before its other half arrives — the exact
-/// corruption `pending` exists to prevent, reachable again through one stray
-/// byte anywhere earlier in the same read.
-#[test]
-fn an_invalid_byte_does_not_consume_a_split_character_after_it() {
- let mut parser = StreamJsonParser::new();
-
- // An ASCII marker holds the spot while the fixture is built as valid
- // JSON, and is overwritten with a real invalid byte afterwards. (A NUL
- // would not survive: serde escapes it to `\u0000`, six ASCII bytes.)
- let line = serde_json::json!({
- "type": "assistant",
- "message": { "type": "text", "text": "bad@then 🌍 tail" }
- })
- .to_string()
- + "\n";
-
- let mut bytes: Vec<u8> = line.into_bytes();
- let bad = bytes
- .windows(8)
- .position(|w| w == b"bad@then")
- .expect("fixture contains the marker")
- + 3;
- // A lone lead byte of a 3-byte sequence: never valid on its own.
- bytes[bad] = 0xE4;
-
- let emoji_start = bytes
- .windows(4)
- .position(|w| w == "🌍".as_bytes())
- .expect("fixture contains the emoji");
- // Split inside the emoji, which sits after the invalid byte.
- let split = emoji_start + 2;
- assert!(
- split > bad,
- "precondition: the invalid byte has to come first for this to test anything"
- );
-
- let first = parser.feed_bytes(&bytes[..split]);
- assert!(
- first.is_empty(),
- "no newline in the first chunk, so nothing should be emitted yet"
- );
-
- let events = parser.feed_bytes(&bytes[split..]);
- assert_eq!(events.len(), 1, "the completed line must be emitted");
-
- match &events[0] {
- ClaudeCodeEvent::Assistant { message } => {
- let text = message
- .get("text")
- .and_then(Value::as_str)
- .expect("the fixture carries the text field");
- assert!(
- text.contains('🌍'),
- "the split emoji must survive an invalid byte earlier in the chunk, got {text:?}"
- );
- assert!(
- text.contains(char::REPLACEMENT_CHARACTER),
- "the invalid byte should still surface as a replacement, got {text:?}"
- );
- }
- other => panic!("expected the assistant line to parse, got {other:?}"),
- }
-}
-
-/// `feed_bytes` is handed arbitrary read boundaries (the driver reads into an
-/// 8 KiB buffer), so a multi-byte character can straddle two chunks. Decoding
-/// each chunk independently replaced both halves with U+FFFD, and because that
-/// character is legal inside a JSON string the line still parsed -- the text was
-/// corrupted with no error raised anywhere.
-#[test]
-fn feed_bytes_preserves_a_character_split_across_chunks() {
- let line = serde_json::json!({
- "type": "assistant",
- "message": { "type": "text", "text": "héllo 世界 🌍 tail" }
- })
- .to_string()
- + "\n";
-
- // Split inside the emoji: its four bytes land on both sides of the boundary.
- let bytes = line.as_bytes();
- let emoji_start = line.find('🌍').expect("fixture contains the emoji");
- let split = emoji_start + 2;
- assert!(
- !line.is_char_boundary(split),
- "the split must be mid-character"
- );
-
- let mut p = StreamJsonParser::new();
- let mut events = p.feed_bytes(&bytes[..split]);
- events.extend(p.feed_bytes(&bytes[split..]));
-
- assert_eq!(events.len(), 1);
-
- // `ParseError` carries the original line, so its Debug rendering contains
- // the emoji too — matching the variant is what separates "decoded across
- // the boundary" from "failed to parse and echoed the bytes back".
- let ClaudeCodeEvent::Assistant { message } = &events[0] else {
- panic!("expected an Assistant event, got {:?}", events[0]);
- };
- assert_eq!(
- message["text"], "héllo 世界 🌍 tail",
- "the character split across the two chunks must survive intact"
- );
-
- let rendered = format!("{:?}", events[0]);
- assert!(
- rendered.contains("héllo 世界 🌍 tail"),
- "text was corrupted across the chunk boundary: {rendered}"
- );
- assert!(
- !rendered.contains('\u{FFFD}'),
- "replacement character present: {rendered}"
- );
-}
-
-/// Bytes that can never become valid must not stall the stream: the old lossy
-/// behaviour is kept for those, so only an *incomplete tail* is carried over.
-#[test]
-fn feed_bytes_still_replaces_genuinely_invalid_bytes() {
- let mut p = StreamJsonParser::new();
- let mut chunk: Vec<u8> = b"{\"type\":\"system\",\"session_id\":\"".to_vec();
- chunk.push(0xFF); // not a valid UTF-8 lead byte in any position
- chunk.extend_from_slice(b"\",\"schema_version\":\"2.0\"}\n");
- let events = p.feed_bytes(&chunk);
- assert_eq!(
- events.len(),
- 1,
- "the line must still be emitted, not withheld"
- );
-
- // Not just "an event arrived": the invalid byte has to have been REPLACED.
- // Dropping it would also emit one event and would also parse, so the count
- // alone cannot tell the two apart.
- let ClaudeCodeEvent::System { session_id, .. } = &events[0] else {
- panic!("expected a System event, got {:?}", events[0]);
- };
- assert_eq!(
- session_id.as_deref(),
- Some("\u{FFFD}"),
- "0xFF must decode to the replacement character, not vanish"
- );
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/types.rs b/crates/openhuman-core/src/inference/provider/claude_code/types.rs
deleted file mode 100644
index b8b4d8192c..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/types.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-//! Shared types for the Claude Code CLI provider.
-
-use serde::{Deserialize, Serialize};
-
-/// Minimum supported `claude` CLI version. Below this, the provider refuses
-/// to start so we never feed an unsupported stream-json schema into the
-/// parser.
-pub const MIN_CLI_VERSION: &str = "2.0.0";
-
-/// Outcome of probing the `claude` CLI binary on disk.
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(tag = "status", rename_all = "snake_case")]
-pub enum CliStatus {
- Ok {
- version: String,
- path: String,
- },
- NotInstalled,
- Outdated {
- version: String,
- min_required: String,
- path: String,
- },
- Unusable {
- path: String,
- reason: String,
- },
-}
-
-/// Branding string used in user-facing copy. Locked decision (PLAN §13.4).
-pub const BRAND_LABEL: &str = "Claude Code CLI";
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/version_check.rs b/crates/openhuman-core/src/inference/provider/claude_code/version_check.rs
deleted file mode 100644
index dae736ed82..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/version_check.rs
+++ /dev/null
@@ -1,207 +0,0 @@
-//! Locate the `claude` CLI binary and verify it meets `MIN_CLI_VERSION`.
-//!
-//! We rely on `claude --version`, which prints a line of the form:
-//! `2.0.4 (Claude Code)`
-//! The first whitespace-delimited token is the semver string we compare
-//! against [`MIN_CLI_VERSION`].
-
-use std::path::PathBuf;
-use std::process::Command;
-
-use super::types::{CliStatus, MIN_CLI_VERSION};
-
-/// Locate the `claude` CLI binary.
-///
-/// Resolution order:
-/// 1. `OPENHUMAN_CLAUDE_CLI` env override (tests / power users / a fixed path).
-/// 2. `PATH` search.
-/// 3. Well-known absolute install locations ([`well_known_candidates`]).
-///
-/// Step 3 exists because a macOS app launched from Finder/Dock inherits only
-/// the stripped launchd `PATH` (`/usr/bin:/bin:/usr/sbin:/sbin`), which never
-/// contains the native installer's `~/.local/bin` — so a PATH-only lookup
-/// reports the CLI "not installed" even though it is present. (Terminal
-/// launches inherit the shell `PATH` and hit step 2, so this only bites GUI
-/// launches.)
-pub fn resolve_binary() -> Option<PathBuf> {
- if let Ok(explicit) = std::env::var("OPENHUMAN_CLAUDE_CLI") {
- let p = PathBuf::from(explicit);
- if p.exists() {
- return Some(p);
- }
- }
- if let Some(p) = which_on_path("claude") {
- return Some(p);
- }
- // PATH miss — fall back to well-known install locations. This is the
- // Finder/Dock-launch case where `~/.local/bin` is absent from `PATH`.
- let found = first_existing(&well_known_candidates());
- if let Some(p) = found.as_ref() {
- log::debug!(
- "[claude-code][version] `claude` not on PATH; resolved via well-known location {}",
- p.display()
- );
- }
- found
-}
-
-/// Absolute paths the `claude` CLI is commonly installed at, tried in order
-/// when it is not found on `PATH`. Ordered by how the native installer and the
-/// common package managers lay it down; the native installer's `~/.local/bin`
-/// is first because that is the default and the one a stripped launchd `PATH`
-/// omits.
-fn well_known_candidates() -> Vec<PathBuf> {
- let mut out = Vec::new();
- if let Some(home) = dirs::home_dir() {
- out.push(home.join(".local/bin/claude")); // native installer default
- out.push(home.join(".claude/local/claude")); // legacy local install
- out.push(home.join(".bun/bin/claude")); // bun global
- out.push(home.join(".npm-global/bin/claude")); // npm global (custom prefix)
- out.push(home.join("bin/claude"));
- }
- out.push(PathBuf::from("/opt/homebrew/bin/claude")); // Homebrew (Apple Silicon)
- out.push(PathBuf::from("/usr/local/bin/claude")); // Homebrew (Intel) / npm default
- out
-}
-
-/// First candidate that resolves to a file (follows symlinks — the native
-/// installer's `~/.local/bin/claude` is a symlink into a versioned dir).
-fn first_existing(candidates: &[PathBuf]) -> Option<PathBuf> {
- candidates
- .iter()
- .find(|p| p.is_file() && is_executable(p))
- .cloned()
-}
-
-#[cfg(unix)]
-fn is_executable(path: &std::path::Path) -> bool {
- use std::os::unix::fs::PermissionsExt;
-
- path.metadata()
- .map(|metadata| metadata.permissions().mode() & 0o111 != 0)
- .unwrap_or(false)
-}
-
-#[cfg(not(unix))]
-fn is_executable(path: &std::path::Path) -> bool {
- path.is_file()
-}
-
-fn which_on_path(name: &str) -> Option<PathBuf> {
- let path_var = std::env::var_os("PATH")?;
- let exts: Vec<String> = if cfg!(windows) {
- std::env::var("PATHEXT")
- .unwrap_or_else(|_| ".EXE;.CMD;.BAT;.COM".into())
- .split(';')
- .filter(|s| !s.is_empty())
- .map(|s| s.to_ascii_lowercase())
- .collect()
- } else {
- vec![String::new()]
- };
- for dir in std::env::split_paths(&path_var) {
- if cfg!(windows) {
- for ext in &exts {
- let candidate = dir.join(format!("{name}{ext}"));
- if candidate.is_file() {
- return Some(candidate);
- }
- }
- } else {
- let candidate = dir.join(name);
- if candidate.is_file() {
- return Some(candidate);
- }
- }
- }
- None
-}
-
-/// Probe the `claude` CLI and return its status.
-pub fn probe() -> CliStatus {
- let Some(path) = resolve_binary() else {
- log::debug!("[claude-code][version] no `claude` binary on PATH");
- return CliStatus::NotInstalled;
- };
- let path_str = path.display().to_string();
-
- let output = match Command::new(&path)
- .arg("--version")
- .env("PATH", super::driver::child_path_with_user_bins(&path))
- .output()
- {
- Ok(o) => o,
- Err(e) => {
- log::warn!("[claude-code][version] spawn failed path={path_str} err={e}");
- return CliStatus::Unusable {
- path: path_str,
- reason: format!("spawn failed: {e}"),
- };
- }
- };
-
- if !output.status.success() {
- return CliStatus::Unusable {
- path: path_str,
- reason: format!(
- "non-zero exit {}: {}",
- output.status,
- String::from_utf8_lossy(&output.stderr).trim()
- ),
- };
- }
-
- let stdout = String::from_utf8_lossy(&output.stdout);
- let version = match parse_version(&stdout) {
- Some(v) => v,
- None => {
- return CliStatus::Unusable {
- path: path_str,
- reason: format!("could not parse version from: {stdout:?}"),
- }
- }
- };
-
- if version_lt(&version, MIN_CLI_VERSION) {
- CliStatus::Outdated {
- version,
- min_required: MIN_CLI_VERSION.to_string(),
- path: path_str,
- }
- } else {
- CliStatus::Ok {
- version,
- path: path_str,
- }
- }
-}
-
-fn parse_version(stdout: &str) -> Option<String> {
- stdout
- .split_whitespace()
- .next()
- .filter(|tok| tok.chars().next().is_some_and(|c| c.is_ascii_digit()))
- .map(|s| s.to_string())
-}
-
-/// Numeric semver compare. Returns true when `a < b`.
-/// Pre-release suffixes (`-rc.1`) are stripped before comparison.
-fn version_lt(a: &str, b: &str) -> bool {
- let pa = parts(a);
- let pb = parts(b);
- pa < pb
-}
-
-fn parts(v: &str) -> (u32, u32, u32) {
- let core = v.split('-').next().unwrap_or(v);
- let mut it = core.split('.').map(|s| s.parse::<u32>().unwrap_or(0));
- (
- it.next().unwrap_or(0),
- it.next().unwrap_or(0),
- it.next().unwrap_or(0),
- )
-}
-
-#[cfg(test)]
-#[path = "version_check_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/claude_code/version_check_tests.rs b/crates/openhuman-core/src/inference/provider/claude_code/version_check_tests.rs
deleted file mode 100644
index 3cf7159d74..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_code/version_check_tests.rs
+++ /dev/null
@@ -1,75 +0,0 @@
-use super::*;
-
-#[test]
-fn parses_typical_output() {
- assert_eq!(
- parse_version("2.0.4 (Claude Code)\n").as_deref(),
- Some("2.0.4")
- );
-}
-
-#[test]
-fn rejects_non_numeric_prefix() {
- assert_eq!(parse_version("claude version 2.0.4"), None);
-}
-
-#[test]
-fn version_compare() {
- assert!(version_lt("1.9.9", "2.0.0"));
- assert!(version_lt("2.0.0", "2.0.1"));
- assert!(!version_lt("2.0.0", "2.0.0"));
- assert!(!version_lt("2.1.0", "2.0.9"));
-}
-
-#[test]
-fn version_compare_strips_prerelease() {
- assert!(!version_lt("2.0.0-rc.1", "2.0.0"));
-}
-
-#[test]
-fn first_existing_skips_missing_candidates_and_returns_first_file() {
- let dir = tempfile::tempdir().expect("tempdir");
- let missing = dir.path().join("missing/claude");
- let real = dir.path().join("claude");
- std::fs::write(&real, b"#!/bin/sh\n").expect("write fake binary");
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o755))
- .expect("set permissions");
- }
-
- assert_eq!(first_existing(std::slice::from_ref(&missing)), None);
- assert_eq!(first_existing(&[missing, real.clone()]), Some(real));
-}
-
-#[cfg(unix)]
-#[test]
-fn first_existing_skips_non_executable_files() {
- use std::os::unix::fs::PermissionsExt;
-
- let dir = tempfile::tempdir().expect("tempdir");
- let non_executable = dir.path().join("not-executable");
- let executable = dir.path().join("executable");
- std::fs::write(&non_executable, b"#!/bin/sh\n").expect("write file");
- std::fs::write(&executable, b"#!/bin/sh\n").expect("write file");
- std::fs::set_permissions(&non_executable, std::fs::Permissions::from_mode(0o644))
- .expect("set permissions");
- std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755))
- .expect("set permissions");
-
- assert_eq!(
- first_existing(&[non_executable, executable.clone()]),
- Some(executable)
- );
-}
-
-#[test]
-fn well_known_candidates_put_native_install_first() {
- let candidates = well_known_candidates();
- assert!(!candidates.is_empty());
- match dirs::home_dir() {
- Some(home) => assert_eq!(candidates[0], home.join(".local/bin/claude")),
- None => assert_eq!(candidates[0], std::path::Path::new("/usr/local/bin/claude")),
- }
-}
diff --git a/crates/openhuman-core/src/inference/provider/factory/access_gates.rs b/crates/openhuman-core/src/inference/provider/factory/access_gates.rs
index 1fc2a585a7..5fef1cd7bd 100644
--- a/crates/openhuman-core/src/inference/provider/factory/access_gates.rs
+++ b/crates/openhuman-core/src/inference/provider/factory/access_gates.rs
@@ -16,7 +16,7 @@ pub(super) fn external_provider_label(provider: &str) -> 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) {
+ if p.starts_with(tinyagents_harness::providers::claude_code::PROVIDER_PREFIX) {
return "Claude Code CLI".to_string();
}
// Concrete cloud slug "<slug>:<model>" → surface just the slug.
diff --git a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs
index 5d5584a207..448e3d1afd 100644
--- a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs
+++ b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs
@@ -263,7 +263,7 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(
|| p == BYOK_INCOMPLETE_SENTINEL
|| p == CLAUDE_AGENT_SDK_PROVIDER
|| p.starts_with(CLAUDE_AGENT_SDK_PREFIX)
- || p.starts_with(crate::inference::provider::claude_code::PROVIDER_PREFIX)
+ || p.starts_with(tinyagents_harness::providers::claude_code::PROVIDER_PREFIX)
{
return None;
}
diff --git a/crates/openhuman-core/src/inference/provider/factory/routing.rs b/crates/openhuman-core/src/inference/provider/factory/routing.rs
index 92a69c1095..5291a7ad9a 100644
--- a/crates/openhuman-core/src/inference/provider/factory/routing.rs
+++ b/crates/openhuman-core/src/inference/provider/factory/routing.rs
@@ -156,7 +156,7 @@ pub(super) fn route_has_usable_credentials(resolved: &str, config: &Config) -> b
// Local runtimes (ollama/lmstudio/mlx/local-openai) and the local CLI
// delegates carry their own credentials / run on-device.
if tinyinference::local::profile::is_local_provider_string(r)
- || r.starts_with(crate::inference::provider::claude_code::PROVIDER_PREFIX)
+ || r.starts_with(tinyagents_harness::providers::claude_code::PROVIDER_PREFIX)
|| r == CLAUDE_AGENT_SDK_PROVIDER
|| r.starts_with(CLAUDE_AGENT_SDK_PREFIX)
{
diff --git a/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs b/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs
index 9b6b0cce13..1cf0589e0a 100644
--- a/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs
+++ b/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs
@@ -80,7 +80,7 @@ pub(super) fn try_create_claude_code_chat_model_from_string(
) -> OptionalChatModelResult {
let provider = provider.trim();
let model_with_temp =
- provider.strip_prefix(crate::inference::provider::claude_code::PROVIDER_PREFIX)?;
+ provider.strip_prefix(tinyagents_harness::providers::claude_code::PROVIDER_PREFIX)?;
let (configured_model, temperature_override) = split_model_and_temperature(model_with_temp);
if temperature_override.is_some() {
log::warn!(
@@ -103,22 +103,49 @@ pub(super) fn try_create_claude_code_chat_model_from_string(
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 workspace = config
+ .config_path
+ .parent()
+ .map(std::path::Path::to_path_buf)
+ .unwrap_or_else(|| config.workspace_dir.clone());
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
+ tinyagents_harness::providers::claude_code::PROVIDER_PREFIX
),
);
- let chat = match crate::inference::provider::claude_code::ClaudeCodeProvider::from_env(
+ let chat = match tinyagents_harness::providers::claude_code::ClaudeCodeProvider::from_env(
effective_model,
workspace,
config.action_dir.clone(),
) {
- Ok(model) => Arc::new(model) as Arc<dyn ChatModel<()>>,
+ Ok(model) => Arc::new(model.with_mcp_provider(Arc::new(OpenHumanMcpEndpoint)))
+ as Arc<dyn ChatModel<()>>,
Err(error) => return Some(Err(error)),
};
Some(Ok((chat, configured_model)))
}
+
+#[derive(Debug)]
+struct OpenHumanMcpEndpoint;
+
+#[async_trait::async_trait]
+impl tinyagents_harness::providers::claude_code::driver::McpEndpointProvider
+ for OpenHumanMcpEndpoint
+{
+ async fn endpoint(
+ &self,
+ ) -> Result<tinyagents_harness::providers::claude_code::driver::McpEndpoint, String> {
+ let endpoint = crate::mcp::server::ensure_local_http()
+ .await
+ .map_err(|error| error.to_string())?;
+ Ok(
+ tinyagents_harness::providers::claude_code::driver::McpEndpoint {
+ addr: endpoint.addr,
+ token: endpoint.token,
+ },
+ )
+ }
+}
diff --git a/crates/openhuman-core/src/inference/provider/mod.rs b/crates/openhuman-core/src/inference/provider/mod.rs
index 366a23b6cc..4399e5c922 100644
--- a/crates/openhuman-core/src/inference/provider/mod.rs
+++ b/crates/openhuman-core/src/inference/provider/mod.rs
@@ -5,7 +5,6 @@
//! inference concerns (local runtime, cloud providers, HTTP endpoint) share
//! a single domain root.
-pub mod claude_code;
pub mod error_classify;
pub mod factory;
pub(crate) mod openai_codex;
diff --git a/crates/openhuman-core/src/inference/schemas/claude_code_handlers.rs b/crates/openhuman-core/src/inference/schemas/claude_code_handlers.rs
index ec716f22ad..384695ea67 100644
--- a/crates/openhuman-core/src/inference/schemas/claude_code_handlers.rs
+++ b/crates/openhuman-core/src/inference/schemas/claude_code_handlers.rs
@@ -19,7 +19,7 @@ pub(super) struct InferenceClaudeCodeSetFullAccessParams {
pub(super) fn handle_inference_claude_code_status(_params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let status = tokio::task::spawn_blocking(
- crate::inference::provider::claude_code::version_check::probe,
+ tinyagents_harness::providers::claude_code::version_check::probe,
)
.await
.map_err(|e| format!("claude_code_status join error: {e}"))?;
@@ -32,7 +32,7 @@ pub(super) fn handle_inference_claude_code_auth_status(
) -> ControllerFuture {
Box::pin(async move {
let auth = tokio::task::spawn_blocking(
- crate::inference::provider::claude_code::auth_status::probe,
+ tinyagents_harness::providers::claude_code::auth_status::probe,
)
.await
.map_err(|e| format!("claude_code_auth_status join error: {e}"))?;
@@ -43,10 +43,11 @@ pub(super) fn handle_inference_claude_code_auth_status(
pub(super) fn handle_inference_claude_code_settings(
_params: Map<String, Value>,
) -> ControllerFuture {
- use crate::inference::provider::claude_code::settings;
+ use tinyagents_harness::providers::claude_code::settings;
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
- let settings = settings::load_for_config(&config);
+ let workspace = config.config_path.parent().unwrap_or(&config.workspace_dir);
+ let settings = settings::load(workspace);
log::debug!(
"[rpc][inference.claude_code_settings] full_access={}",
settings.full_access
@@ -58,11 +59,15 @@ pub(super) fn handle_inference_claude_code_settings(
pub(super) fn handle_inference_claude_code_set_full_access(
params: Map<String, Value>,
) -> ControllerFuture {
- use crate::inference::provider::claude_code::settings;
+ use tinyagents_harness::providers::claude_code::settings;
Box::pin(async move {
let p = deserialize_params::<InferenceClaudeCodeSetFullAccessParams>(params)?;
let config = config_rpc::load_config_with_timeout().await?;
- let settings = settings::save_full_access_for_config(&config, p.enabled)
+ let workspace = config.config_path.parent().unwrap_or(&config.workspace_dir);
+ let settings = settings::ClaudeCodeSettings {
+ full_access: p.enabled,
+ };
+ settings::save(workspace, &settings)
.map_err(|e| format!("failed to persist claude code settings: {e}"))?;
log::info!(
"[rpc][inference.claude_code_set_full_access] persisted full_access={}",
diff --git a/crates/openhuman-core/src/inference/types.rs b/crates/openhuman-core/src/inference/types.rs
index 17749f641b..d7f947c20f 100644
--- a/crates/openhuman-core/src/inference/types.rs
+++ b/crates/openhuman-core/src/inference/types.rs
@@ -3,7 +3,7 @@
use crate::config::Config;
use serde::{Deserialize, Serialize};
-use super::presets;
+use crate::config::ops::local_ai_presets;
use tinyinference::local::models as model_ids;
use tinyinference::local::provider::provider_from_name;
@@ -43,7 +43,7 @@ pub struct LocalAiStatus {
impl LocalAiStatus {
pub(crate) fn disabled(config: &Config) -> Self {
- let vision_mode = presets::vision_mode_for_config(&config.local_ai);
+ let vision_mode = local_ai_presets::vision_mode_for_config(&config.local_ai);
let provider = provider_from_name(&config.local_ai.provider);
Self {
state: "disabled".to_string(),
diff --git a/tests/claude_code_stream_e2e.rs b/tests/claude_code_stream_e2e.rs
deleted file mode 100644
index 0e15caab4b..0000000000
--- a/tests/claude_code_stream_e2e.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-//! End-to-end test of the Claude Code stream-json pipeline.
-//!
-//! Feeds a captured representative CC 2.x stream-json transcript through
-//! `StreamJsonParser` → `EventMapper` and asserts that:
-//! - text deltas arrive in order and aggregate into the final response
-//! - a `tool_use` block is the CLI's **own, already-executed** call: its
-//! `input_json_delta`s are kept out of the visible text and nothing is
-//! surfaced to the harness — no `ToolCallStart`, no `ToolCallArgsDelta`,
-//! no aggregated `ToolCall` (see the `event_mapper` module docs; #5739)
-//! - the `result` event finalizes usage tokens (incl. cache_read)
-//! - session_id is captured from the first `system` event
-//!
-//! This is a parser-level E2E; the real driver / process spawn is mocked
-//! in `tests/claude_code_driver_smoke.rs`.
-
-use openhuman_core::inference::provider::claude_code::{
- event_mapper::EventMapper, stream_parser::StreamJsonParser,
-};
-use openhuman_core::inference::provider::types::ProviderDelta;
-
-const TRANSCRIPT: &str = r#"{"type":"system","subtype":"init","session_id":"f47ac10b-58cc-4372-a567-0e02b2c3d479","schema_version":"2.0"}
-{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text"}}}
-{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}}
-{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" world"}}}
-{"type":"stream_event","event":{"type":"content_block_stop","index":0}}
-{"type":"stream_event","event":{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"call_42","name":"memory_search"}}}
-{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"que"}}}
-{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"ry\":\"foo\"}"}}}
-{"type":"stream_event","event":{"type":"content_block_stop","index":1}}
-{"type":"assistant","message":{"type":"message","role":"assistant","content":[]}}
-{"type":"result","subtype":"success","usage":{"input_tokens":120,"output_tokens":42,"cache_read_input_tokens":80,"cache_creation_input_tokens":0},"total_cost_usd":0.0012}
-"#;
-
-#[test]
-fn captures_text_tool_call_and_usage() {
- let mut parser = StreamJsonParser::new();
- let mut mapper = EventMapper::new();
- let mut deltas: Vec<ProviderDelta> = Vec::new();
-
- // Feed in chunks to exercise the chunk-boundary buffering as well.
- let mid = TRANSCRIPT.len() / 2;
- for chunk in [&TRANSCRIPT[..mid], &TRANSCRIPT[mid..]] {
- for evt in parser.feed(chunk) {
- for d in mapper.handle(evt) {
- deltas.push(d);
- }
- }
- }
- for evt in parser.end() {
- for d in mapper.handle(evt) {
- deltas.push(d);
- }
- }
-
- // Schema version was captured by the parser.
- assert_eq!(parser.schema_version.as_deref(), Some("2.0"));
-
- // Session id was captured by the mapper from the first system event.
- assert_eq!(
- mapper.session_id.as_deref(),
- Some("f47ac10b-58cc-4372-a567-0e02b2c3d479")
- );
-
- // Text deltas arrived in order.
- let text_chunks: Vec<&str> = deltas
- .iter()
- .filter_map(|d| match d {
- ProviderDelta::TextDelta { delta } => Some(delta.as_str()),
- _ => None,
- })
- .collect();
- assert_eq!(text_chunks, vec!["Hello", " world"]);
-
- // The CLI's own tool call is suppressed end to end: nothing about
- // `call_42` reaches the harness, and its argument JSON never leaks into
- // the text stream.
- assert!(
- !deltas.iter().any(|d| matches!(
- d,
- ProviderDelta::ToolCallStart { .. } | ProviderDelta::ToolCallArgsDelta { .. }
- )),
- "a self-executed CLI tool_use block must not surface as a harness tool call: {deltas:?}"
- );
- assert!(
- !text_chunks
- .iter()
- .any(|t| t.contains("que") || t.contains("ry\"")),
- "input_json_delta text must stay out of the visible text: {text_chunks:?}"
- );
-
- // Aggregated response.
- assert_eq!(mapper.final_text, "Hello world");
- assert!(
- mapper.tool_calls.is_empty(),
- "no ToolCall is aggregated for a CLI-internal tool_use block"
- );
-
- // Usage from the `result` event.
- assert!(mapper.finished);
- let u = mapper.usage.as_ref().expect("usage should be populated");
- assert_eq!(u.input_tokens, 120);
- assert_eq!(u.output_tokens, 42);
- assert_eq!(u.cached_input_tokens, 80);
-}
diff --git a/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs b/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs
index 8ee44e0d38..eefdaa6bb2 100644
--- a/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs
@@ -120,10 +120,13 @@ use openhuman_core::inference::local::{
use openhuman_core::inference::openai_oauth::{
lookup_openai_bearer_token, OPENAI_OAUTH_PROFILE_NAME, OPENAI_PROVIDER_KEY,
};
-use openhuman_core::inference::presets::{
- all_presets, apply_preset_to_config, current_tier_from_config, device_supports_local_ai,
- mvp_presets, preset_for_tier, recommend_tier, should_default_to_cloud_fallback,
- supports_screen_summary, vision_mode_for_config, vision_mode_for_tier, ModelTier, VisionMode,
+use openhuman_core::config::ops::local_ai_presets::{
+ apply_preset_to_config, current_tier_from_config, supports_screen_summary,
+ vision_mode_for_config,
+};
+use tinyinference::local::presets::{
+ all_presets, device_supports_local_ai, mvp_presets, preset_for_tier, recommend_tier,
+ should_default_to_cloud_fallback, vision_mode_for_tier, ModelTier, VisionMode,
MIN_RAM_GB_FOR_LOCAL_AI, MVP_MAX_TIER,
};
use openhuman_core::inference::provider::factory::{
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 0017dfb155..6706ebf993 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 0017dfb15547d6dd56fdabf41e966fce41c4f99b
+Subproject commit 6706ebf99377eed59437701f0426573d6a546d9d