Skip to content

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

7.9 KB
Raw Blame
//! Handlers for model and provider settings: resolution, status, client
//! config, model and local-runtime settings updates, model listing, device
//! auth errors, and diagnostics.

use crate::core::runtime::DispatchCtx;
use serde::de::Deserializer;
use serde::Deserialize;
use serde_json::{Map, Value};

use super::{deserialize_params, to_json};
use crate::config::rpc as config_rpc;
use crate::core::all::ControllerFuture;
use crate::core::Outcome;

#[derive(Debug, Deserialize)]
pub(super) struct InferenceResolveModelParams {
    hint: String,
}

#[derive(Debug, Deserialize)]
pub(super) struct InferenceModelRouteUpdate {
    hint: String,
    model: String,
}

#[derive(Debug, Deserialize)]
pub(super) struct InferenceUpdateModelSettingsParams {
    api_url: Option<String>,
    inference_url: Option<String>,
    api_key: Option<String>,
    default_model: Option<String>,
    default_temperature: Option<f64>,
    model_routes: Option<Vec<InferenceModelRouteUpdate>>,
    cloud_providers: Option<Vec<crate::config::ops::CloudProviderUpdate>>,
    #[serde(default)]
    model_registry: Option<Vec<crate::config::schema::ModelRegistryEntry>>,
    primary_cloud: Option<String>,
    chat_provider: Option<String>,
    reasoning_provider: Option<String>,
    agentic_provider: Option<String>,
    coding_provider: Option<String>,
    vision_provider: Option<String>,
    memory_provider: Option<String>,
    embeddings_provider: Option<String>,
}

#[derive(Debug, Deserialize)]
pub(super) struct InferenceUpdateLocalSettingsParams {
    runtime_enabled: Option<bool>,
    opt_in_confirmed: Option<bool>,
    provider: Option<String>,
    #[serde(default, deserialize_with = "deserialize_present_json")]
    base_url: Option<Value>,
    model_id: Option<String>,
    chat_model_id: Option<String>,
    usage_embeddings: Option<bool>,
    api_key: Option<String>,
}

#[derive(Debug, Deserialize)]
pub(super) struct InferenceListModelsParams {
    provider_id: String,
}

pub(super) fn handle_inference_resolve_model(
    ctx: DispatchCtx,
    params: Map<String, Value>,
) -> ControllerFuture {
    Box::pin(async move {
        let p = deserialize_params::<InferenceResolveModelParams>(params)?;
        let config = ctx.load_config().await?;
        let resolved_context = ctx.resolved();
        let extensions = resolved_context
            .as_deref()
            .map(crate::core::runtime::CoreContext::extensions);
        let resolved = crate::inference::provider_model::resolve_provider_model_hint_for(
            extensions,
            crate::inference::provider::factory::PROVIDER_OPENHUMAN,
            &p.hint,
            &config,
        );
        // Whether the resolved model accepts image input — drives the chat UI's
        // image-attachment affordance. Managed OpenHuman tiers consult the
        // core-owned per-tier map, which returns `true` for the reasoning and
        // vision tiers (and their `hint:` aliases) and `false` for every other
        // tier; custom/BYOK models are covered by the user's per-model
        // `model_registry.vision` flag.
        let vision = crate::inference::model_context::model_supports_vision_in(
            extensions, &resolved, &config,
        );
        to_json(Outcome::new(
            serde_json::json!({ "model": resolved, "vision": vision }),
            vec![],
        ))
    })
}

pub(super) fn handle_inference_status(
    ctx: DispatchCtx,
    _params: Map<String, Value>,
) -> ControllerFuture {
    Box::pin(async move {
        let config = ctx.load_config().await?;
        to_json(crate::inference::ops::inference_status(&config).await?)
    })
}

pub(super) fn handle_inference_get_client_config(
    ctx: DispatchCtx,
    _params: Map<String, Value>,
) -> ControllerFuture {
    Box::pin(
        async move { to_json(crate::inference::ops::inference_get_client_config(&ctx).await?) },
    )
}

pub(super) fn handle_inference_update_model_settings(
    ctx: DispatchCtx,
    params: Map<String, Value>,
) -> ControllerFuture {
    Box::pin(async move {
        let update = deserialize_params::<InferenceUpdateModelSettingsParams>(params)?;
        let ca_certs = update
            .cloud_providers
            .as_ref()
            .map(|providers| {
                crate::config::ops::collect_provider_ca_certs(
                    providers
                        .iter()
                        .map(|provider| (provider.slug.as_str(), provider.ca_cert_pem.as_deref())),
                )
            })
            .transpose()?;
        let patch = config_rpc::ModelSettingsPatch {
            api_url: update.api_url,
            inference_url: update.inference_url,
            api_key: update.api_key,
            default_model: update.default_model,
            default_temperature: update.default_temperature,
            cloud_provider_ca_certs: ca_certs,
            model_routes: update.model_routes.map(|routes| {
                routes
                    .into_iter()
                    .map(|route| crate::config::ModelRouteConfig {
                        hint: route.hint,
                        model: route.model,
                    })
                    .collect()
            }),
            cloud_providers: update
                .cloud_providers
                .map(crate::config::ops::build_cloud_provider_creds)
                .transpose()?,
            model_registry: update.model_registry,
            primary_cloud: update.primary_cloud,
            chat_provider: update.chat_provider,
            reasoning_provider: update.reasoning_provider,
            agentic_provider: update.agentic_provider,
            coding_provider: update.coding_provider,
            vision_provider: update.vision_provider,
            memory_provider: update.memory_provider,
            embeddings_provider: update.embeddings_provider,
        };
        to_json(crate::inference::ops::inference_update_model_settings(&ctx, patch).await?)
    })
}

pub(super) fn handle_inference_update_local_settings(
    ctx: DispatchCtx,
    params: Map<String, Value>,
) -> ControllerFuture {
    Box::pin(async move {
        let update = deserialize_params::<InferenceUpdateLocalSettingsParams>(params)?;
        let base_url = match update.base_url {
            None => None,
            Some(Value::Null) => Some(None),
            Some(Value::String(value)) => Some(Some(value)),
            Some(_) => return Err("invalid params: base_url must be a string or null".to_string()),
        };
        let patch = config_rpc::LocalAiSettingsPatch {
            runtime_enabled: update.runtime_enabled,
            opt_in_confirmed: update.opt_in_confirmed,
            provider: update.provider,
            base_url,
            model_id: update.model_id,
            chat_model_id: update.chat_model_id,
            usage_embeddings: update.usage_embeddings,
            api_key: update.api_key,
        };
        to_json(crate::inference::ops::inference_update_local_settings(&ctx, patch).await?)
    })
}

pub(super) fn handle_inference_list_models(
    ctx: DispatchCtx,
    params: Map<String, Value>,
) -> ControllerFuture {
    Box::pin(async move {
        let request = deserialize_params::<InferenceListModelsParams>(params)?;
        to_json(crate::inference::ops::inference_list_models(&ctx, &request.provider_id).await?)
    })
}

pub(super) fn handle_inference_provider_auth_errors(
    _ctx: DispatchCtx,
    _params: Map<String, Value>,
) -> ControllerFuture {
    Box::pin(async move { to_json(crate::inference::ops::inference_provider_auth_errors().await?) })
}

pub(super) fn handle_inference_diagnostics(
    ctx: DispatchCtx,
    _params: Map<String, Value>,
) -> ControllerFuture {
    Box::pin(async move {
        let config = ctx.load_config().await?;
        to_json(crate::inference::ops::inference_diagnostics(&config).await?)
    })
}

fn deserialize_present_json<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
where
    D: Deserializer<'de>,
{
    Value::deserialize(deserializer).map(Some)
}