Skip to content

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

8.8 KB
Raw Blame
//! Config snapshots serialized for the desktop UI.

use crate::core::runtime::DispatchCtx;
use serde_json::json;

use crate::config::Config;
use crate::core::Outcome;

/// Serializes the current configuration into a JSON snapshot for the UI.
pub fn snapshot_config_json(config: &Config) -> Result<serde_json::Value, String> {
    let mut value = serde_json::to_value(config).map_err(|e| e.to_string())?;
    // The full snapshot is sent over RPC. Keep search settings visible while
    // removing credentials, including the legacy Seltz key.
    for provider in ["brave", "querit", "exa", "tavily", "gemini", "parallel"] {
        value["search"][provider]["api_key"] = serde_json::Value::Null;
    }
    value["seltz"]["api_key"] = serde_json::Value::Null;
    // A broker URL may carry credentials too; show it redacted.
    if let Some(url) = config.inbound.queue_url.as_deref() {
        value["inbound"]["queue_url"] =
            serde_json::Value::String(crate::config::schema::storage::redact_url(url));
    }
    // A storage URL may carry database credentials; show it redacted.
    if let Some(url) = config.storage.url.as_deref() {
        value["storage"]["url"] =
            serde_json::Value::String(crate::config::schema::storage::redact_url(url));
    }
    #[cfg(feature = "modules")]
    let browser_billing_route = crate::modules::desktop::billing_route(config);
    #[cfg(not(feature = "modules"))]
    let browser_billing_route = "unavailable";
    Ok(json!({
        "config": value,
        "browser_billing_route": browser_billing_route,
        "workspace_dir": config.workspace_dir.display().to_string(),
        "config_path": config.config_path.display().to_string(),
    }))
}

/// Serializes the client-facing AI config slice consumed by the settings UI.
pub fn client_config_json(config: &Config) -> serde_json::Value {
    let app_version =
        std::env::var("OPENHUMAN_APP_VERSION").unwrap_or_else(|_| "unknown".to_string());
    let api_key_set = config
        .api_key
        .as_deref()
        .map(|k| !k.trim().is_empty())
        .unwrap_or(false);
    let model_routes: Vec<serde_json::Value> = config
        .model_routes
        .iter()
        .map(|r| serde_json::json!({ "hint": r.hint, "model": r.model }))
        .collect();
    let cloud_providers: Vec<serde_json::Value> = config
        .cloud_providers
        .iter()
        .map(|c| {
            serde_json::json!({
                "id": c.id,
                "slug": c.slug,
                "label": c.label,
                "endpoint": c.endpoint,
                "auth_style": c.auth_style.as_str(),
                "ca_cert_pem": config.cloud_provider_ca_certs.get(&c.slug),
            })
        })
        .collect();
    let model_registry: Vec<serde_json::Value> = config
        .model_registry
        .iter()
        .map(|m| {
            serde_json::json!({
                "id": m.id,
                "provider": m.provider,
                "cost_per_1m_input": m.cost_per_1m_input,
                "cost_per_1m_cached_input": m.cost_per_1m_cached_input,
                "cost_per_1m_output": m.cost_per_1m_output,
                "context_window": m.context_window,
                "vision": m.vision,
            })
        })
        .collect();

    serde_json::json!({
        "api_url": config.api_url,
        "inference_url": config.inference_url,
        "default_model": config.default_model,
        // The composer's thinking-level default (`runtime.reasoning_effort`);
        // `null` means the provider decides.
        "reasoning_effort": config.runtime.reasoning_effort,
        // Per-model thinking levels (`runtime.reasoning_effort_by_model`).
        "reasoning_effort_by_model": config.runtime.reasoning_effort_by_model,
        "app_version": app_version,
        "api_key_set": api_key_set,
        "model_routes": model_routes,
        "cloud_providers": cloud_providers,
        "model_registry": model_registry,
        "primary_cloud": config.primary_cloud,
        // #3767: authoritative, core-side decision telling the UI whether the
        // managed-credits gate should be bypassed, per chat-mode tier. The chat
        // header's "Quick" mode runs on the `chat` tier and "Reasoning" mode on
        // the `reasoning` tier, so each is reported separately and the UI checks
        // the tier the user actually selected. True for a tier when it runs on a
        // non-managed provider the user funds themselves (BYO key / local /
        // claude-code) with usable creds. Managed tiers that run anyway surface
        // credit errors per-call.
        "credits_bypass": {
            "chat": crate::inference::provider::factory::role_bypasses_managed_credits(
                "chat", config,
            ),
            "reasoning":
                crate::inference::provider::factory::role_bypasses_managed_credits(
                    "reasoning", config,
                ),
        },
        "chat_provider": config.chat_provider,
        "reasoning_provider": config.reasoning_provider,
        "agentic_provider": config.agentic_provider,
        "coding_provider": config.coding_provider,
        "vision_provider": config.vision_provider,
        "memory_provider": config.memory_provider,
        "embeddings_provider": config.embeddings_provider,
        "voice_providers": config.voice_providers.iter().map(|v| {
            serde_json::json!({
                "id": v.id,
                "slug": v.slug,
                "label": v.label,
                "endpoint": v.endpoint,
                "auth_style": v.auth_style.as_str(),
                "capability": v.capability.as_str(),
                "stt_api_style": v.stt_api_style,
                "tts_api_style": v.tts_api_style,
                "default_stt_model": v.default_stt_model,
                "default_tts_voice": v.default_tts_voice,
            })
        }).collect::<Vec<_>>(),
        "stt_provider": config.stt_provider,
        "tts_provider": config.tts_provider,
    })
}

/// Loads config and returns the client-facing AI config slice.
pub async fn load_and_get_client_config_snapshot(
    ctx: &DispatchCtx,
) -> Result<Outcome<serde_json::Value>, String> {
    let config = ctx.load_config().await?;
    let snapshot = client_config_json(&config);
    Ok(Outcome::new(
        snapshot,
        vec!["client config read".to_string()],
    ))
}

/// Returns a full configuration snapshot for the UI.
pub async fn get_config_snapshot(config: &Config) -> Result<Outcome<serde_json::Value>, String> {
    let snapshot = snapshot_config_json(config)?;
    Ok(Outcome::new(
        snapshot,
        vec![format!(
            "config loaded from {}",
            config.config_path.display()
        )],
    ))
}

/// Loads the configuration from disk and returns a snapshot.
pub async fn load_and_get_config_snapshot(
    ctx: &DispatchCtx,
) -> Result<Outcome<serde_json::Value>, String> {
    let config = ctx.load_config().await?;
    get_config_snapshot(&config).await
}

/// Reads dashboard settings exposed to the desktop UI.
pub async fn get_dashboard_settings(
    ctx: &DispatchCtx,
) -> Result<Outcome<serde_json::Value>, String> {
    let request_id = uuid::Uuid::new_v4().to_string();
    tracing::debug!(
        target: "openhuman_core::config",
        request_id = %request_id,
        method = "openhuman.config_get_dashboard_settings",
        "OPENHUMAN: get_dashboard_settings entry"
    );
    tracing::debug!(
        target: "openhuman_core::config",
        request_id = %request_id,
        method = "openhuman.config_get_dashboard_settings",
        "OPENHUMAN: get_dashboard_settings loading config"
    );

    let config = ctx.load_config().await.map_err(|error| {
        tracing::warn!(
            target: "openhuman_core::config",
            request_id = %request_id,
            method = "openhuman.config_get_dashboard_settings",
            error = %error,
            "OPENHUMAN: get_dashboard_settings config load failed"
        );
        error
    })?;

    tracing::debug!(
        target: "openhuman_core::config",
        request_id = %request_id,
        method = "openhuman.config_get_dashboard_settings",
        "OPENHUMAN: get_dashboard_settings serializing dashboard settings"
    );
    let result = serde_json::to_value(&config.dashboard).map_err(|error| {
        let message = error.to_string();
        tracing::warn!(
            target: "openhuman_core::config",
            request_id = %request_id,
            method = "openhuman.config_get_dashboard_settings",
            error = %message,
            "OPENHUMAN: get_dashboard_settings serialization failed"
        );
        message
    })?;

    tracing::debug!(
        target: "openhuman_core::config",
        request_id = %request_id,
        method = "openhuman.config_get_dashboard_settings",
        "OPENHUMAN: get_dashboard_settings exit"
    );
    Ok(Outcome::new(
        result,
        vec!["dashboard settings read".to_string()],
    ))
}