Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

22.7 KB
Raw Blame
use super::*;

pub(crate) fn provider_from_row(
    row: &rusqlite::Row<'_>,
    secrets: &SecretStore,
) -> rusqlite::Result<ProviderPublic> {
    let secret_ref: Option<String> = row.get(8)?;
    let id: String = row.get(0)?;
    let legacy_model_id: Option<String> = row.get(9)?;
    let config_raw: String = row.get(11).unwrap_or_else(|_| "{}".to_string());
    let models = config_model_bindings(&config_raw, legacy_model_id.clone(), &id);
    let has_api_key = secret_ref.as_ref().map(|r| secrets.has(r)).unwrap_or(false);
    let has_oauth = secrets.has(&secret_ref_for_provider_oauth(&id));
    Ok(ProviderPublic {
        id,
        name: row.get(1)?,
        vendor_key: row.get(2)?,
        provider_type: row.get(3)?,
        protocol: row.get(4)?,
        enabled: row.get::<_, i64>(5)? != 0,
        base_url: row.get(6)?,
        auth_kind: row.get(7)?,
        has_secret: has_api_key || has_oauth,
        has_oauth,
        oauth_account_label: row
            .get::<_, String>(11)
            .ok()
            .and_then(|raw| config_oauth_account_label(&raw)),
        headers: row
            .get::<_, String>(11)
            .ok()
            .and_then(|raw| config_headers(&raw)),
        default_model_id: models
            .first()
            .map(|binding| binding.id.clone())
            .or(legacy_model_id),
        models,
        api_style: row.get(10)?,
        supports_reasoning: row
            .get::<_, String>(11)
            .ok()
            .and_then(|raw| config_reasoning_override(&raw)),
        supported_thinking_levels: row
            .get::<_, String>(11)
            .ok()
            .and_then(|raw| config_thinking_levels_override(&raw)),
        context_window: row
            .get::<_, String>(11)
            .ok()
            .and_then(|raw| config_limit_u32(&raw, "contextWindow")),
        max_output_tokens: row
            .get::<_, String>(11)
            .ok()
            .and_then(|raw| config_limit_u32(&raw, "maxOutputTokens")),
        temperature: row
            .get::<_, String>(11)
            .ok()
            .and_then(|raw| config_limit_f64(&raw, "temperature")),
        owner_plugin_id: row.get(14)?,
        created_at: ms_to_ts(row.get(12)?),
        updated_at: ms_to_ts(row.get(13)?),
    })
}

pub fn list_providers(
    db: &Database,
    secrets: &SecretStore,
    include_disabled: bool,
) -> Result<Vec<ProviderPublic>> {
    let sql = if include_disabled {
        format!("{PROVIDER_SELECT} ORDER BY created_at ASC")
    } else {
        format!("{PROVIDER_SELECT} WHERE enabled = 1 ORDER BY created_at ASC")
    };
    let mut stmt = db.conn().prepare_cached(&sql)?;
    let rows = stmt.query_map([], |row| provider_from_row(row, secrets))?;
    let mut providers = rows.collect::<rusqlite::Result<Vec<_>>>()?;
    for provider in &mut providers {
        hydrate_dynamic_plugin_models(db, provider)?;
    }
    super::order::apply_saved_order(db, &mut providers)?;
    Ok(providers)
}

/// An empty model declaration opts an API-key plugin provider into using the
/// endpoint's cached discovery results. Static manifest models stay authoritative
/// whenever the plugin declares at least one.
fn hydrate_dynamic_plugin_models(db: &Database, provider: &mut ProviderPublic) -> Result<()> {
    if provider.owner_plugin_id.is_none() || !provider.models.is_empty() {
        return Ok(());
    }
    provider.models = list_models(db, Some(&provider.id))?
        .into_iter()
        .map(|model| {
            let alias = (model.display_name != model.model_id).then_some(model.display_name);
            ModelBinding {
                id: model.model_id,
                alias,
                context_window_source: None,
                max_tokens_source: None,
                context_window: model.context_window.unwrap_or(DEFAULT_CONTEXT_WINDOW),
                max_tokens: DEFAULT_MAX_TOKENS,
                thinking_levels: Vec::new(),
                default_thinking_level: None,
                thinking_protocol: None,
                supports_reasoning_effort: None,
                supports_images: model
                    .capabilities
                    .iter()
                    .any(|value| value == "vision")
                    .then_some(true),
                supports_documents: None,
                available_for_subagents: None,
                native_web_search: None,
                fast_mode_allowed: None,
                allow_empty_thinking_signature: None,
            }
        })
        .collect();
    if provider
        .default_model_id
        .as_deref()
        .map(|value| value.is_empty())
        .unwrap_or(true)
    {
        provider.default_model_id = provider.models.first().map(|model| model.id.clone());
    }
    Ok(())
}

pub fn create_provider(
    db: &Database,
    secrets: &SecretStore,
    input: ProviderCreateInput,
) -> Result<ProviderPublic> {
    let id = Uuid::new_v4().to_string();
    let now = now_ms();
    // Validate before any side effect: a rejected alias must not leave a
    // stored secret behind.
    if let Some(models) = input.models.as_deref() {
        validate_model_aliases(models)?;
    }
    let secret_ref = secret_ref_for_provider(&id);
    let mut backend = None;
    if let Some(secret) = input.secret_value.as_ref().filter(|s| !s.is_empty()) {
        let b = secrets.set(&secret_ref, secret)?;
        upsert_secret_meta(db, &secret_ref, &id, &b)?;
        backend = Some(b);
    }

    let vendor_key = input.vendor_key.unwrap_or_else(|| "custom".into());
    let provider_type = input
        .provider_type
        .unwrap_or_else(|| "openai_compatible".into());
    let protocol = input.protocol.unwrap_or_else(|| "openai_compatible".into());
    let auth_kind = input
        .auth_kind
        .unwrap_or_else(|| "api_key_and_base_url".into());
    let config_json = build_provider_config_json(
        input.supports_reasoning,
        input.supported_thinking_levels.as_deref(),
        input.models.as_deref(),
        &LimitOverrides {
            context_window: input.context_window,
            max_output_tokens: input.max_output_tokens,
            temperature: input.temperature,
        },
    )?;
    let config_json = match input.oauth_account_label.as_deref() {
        Some(label) => config_with_oauth_account_label(&config_json, label)?,
        None => config_json,
    };
    let config_json = match input.headers.as_ref() {
        Some(headers) => config_with_headers(&config_json, headers)?,
        None => config_json,
    };

    db.conn()
        .prepare_cached(
            "INSERT INTO providers (
                id, name, vendor_key, type, protocol, enabled, base_url, auth_kind, secret_ref,
                api_style, default_model_id, config_json, created_at, updated_at
             ) VALUES (?1, ?2, ?3, ?4, ?5, 1, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?12)",
        )?
        .execute(params![
            id,
            input.name,
            vendor_key,
            provider_type,
            protocol,
            input.base_url,
            auth_kind,
            if backend.is_some() {
                Some(secret_ref.clone())
            } else {
                None
            },
            input.api_style,
            input.default_model_id.or_else(|| {
                input
                    .models
                    .as_ref()
                    .and_then(|models| models.first().map(|model| model.id.clone()))
            }),
            config_json.to_string(),
            now,
        ])?;

    get_provider(db, secrets, &id)?.ok_or_else(|| anyhow::anyhow!("provider missing after create"))
}

/// Import a user-owned provider while preserving its stable id. Ordinary
/// settings flows continue to use `create_provider` and receive a fresh UUID;
/// configuration sync is the only caller allowed to restore an existing id so
/// repeated imports do not create duplicate provider identities.
pub(crate) fn create_provider_with_id(
    db: &Database,
    secrets: &SecretStore,
    id: &str,
    input: ProviderCreateInput,
) -> Result<ProviderPublic> {
    if id.trim().is_empty() || id.len() > 128 {
        bail!("PROVIDER_INVALID: provider id is invalid");
    }
    if db
        .conn()
        .query_row("SELECT 1 FROM providers WHERE id = ?1", params![id], |_| {
            Ok(())
        })
        .optional()?
        .is_some()
    {
        bail!("PROVIDER_INVALID: provider already exists");
    }
    if let Some(models) = input.models.as_deref() {
        validate_model_aliases(models)?;
    }
    let now = now_ms();
    let secret_ref = secret_ref_for_provider(id);
    let mut backend = None;
    if let Some(secret) = input.secret_value.as_ref().filter(|s| !s.is_empty()) {
        let value = secrets.set(&secret_ref, secret)?;
        upsert_secret_meta(db, &secret_ref, id, &value)?;
        backend = Some(value);
    }
    let vendor_key = input.vendor_key.unwrap_or_else(|| "custom".into());
    let provider_type = input
        .provider_type
        .unwrap_or_else(|| "openai_compatible".into());
    let protocol = input.protocol.unwrap_or_else(|| "openai_compatible".into());
    let auth_kind = input
        .auth_kind
        .unwrap_or_else(|| "api_key_and_base_url".into());
    let config_json = build_provider_config_json(
        input.supports_reasoning,
        input.supported_thinking_levels.as_deref(),
        input.models.as_deref(),
        &LimitOverrides {
            context_window: input.context_window,
            max_output_tokens: input.max_output_tokens,
            temperature: input.temperature,
        },
    )?;
    let config_json = match input.oauth_account_label.as_deref() {
        Some(label) => config_with_oauth_account_label(&config_json, label)?,
        None => config_json,
    };
    let config_json = match input.headers.as_ref() {
        Some(headers) => config_with_headers(&config_json, headers)?,
        None => config_json,
    };
    db.conn()
        .prepare_cached(
            "INSERT INTO providers (
                id, name, vendor_key, type, protocol, enabled, base_url, auth_kind, secret_ref,
                api_style, default_model_id, config_json, created_at, updated_at
             ) VALUES (?1, ?2, ?3, ?4, ?5, 1, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?12)",
        )?
        .execute(params![
            id,
            input.name,
            vendor_key,
            provider_type,
            protocol,
            input.base_url,
            auth_kind,
            if backend.is_some() {
                Some(secret_ref)
            } else {
                None
            },
            input.api_style,
            input.default_model_id.or_else(|| {
                input
                    .models
                    .as_ref()
                    .and_then(|models| models.first().map(|model| model.id.clone()))
            }),
            config_json,
            now,
        ])?;
    get_provider(db, secrets, id)?.ok_or_else(|| anyhow::anyhow!("provider missing after import"))
}

pub fn update_provider(
    db: &Database,
    secrets: &SecretStore,
    input: ProviderUpdateInput,
) -> Result<Option<ProviderPublic>> {
    let Some(current) = get_provider(db, secrets, &input.id)? else {
        return Ok(None);
    };
    // A plugin-declared row is refreshed from its manifest on every load, so a
    // generic edit would be silently reverted. The plugin path owns it.
    if let Some(owner) = current.owner_plugin_id.as_deref() {
        bail!(
            "PROVIDER_OWNED_BY_PLUGIN: provider {} belongs to plugin {owner}",
            input.id
        );
    }
    // Validate before any side effect: a rejected alias must not replace the
    // stored secret.
    if let Some(models) = input.models.as_deref() {
        validate_model_aliases(models)?;
    }
    let raw_config: String = db.conn().query_row(
        "SELECT config_json FROM providers WHERE id = ?1",
        params![input.id],
        |row| row.get(0),
    )?;
    // Do not let a partial read silently replace unreadable stored bindings.
    if input.models.is_some() {
        ensure_model_bindings_update_safe(&raw_config)?;
    }
    // The discovered answer belongs to the endpoint that produced it, and the
    // cached rows carry no endpoint of their own: an edit that moves the address
    // or the wire format has to drop that answer, or the picker would paint the
    // previous service's models as this one's. Read before the update moves the
    // fields into the row.
    let endpoint_changed = input
        .base_url
        .as_deref()
        .is_some_and(|value| value.trim() != current.base_url.as_deref().unwrap_or("").trim())
        || input
            .api_style
            .as_deref()
            .is_some_and(|value| value != current.api_style.as_deref().unwrap_or(""));
    // Derive from the API key ref directly: `has_secret` now also covers an
    // OAuth credential, so reusing it here would stamp an api_key ref onto a
    // provider that only ever signed in with a vendor account.
    let api_key_ref = secret_ref_for_provider(&input.id);
    let effective_auth_kind = input
        .auth_kind
        .as_deref()
        .unwrap_or(current.auth_kind.as_str());
    let clear_api_key = effective_auth_kind == "none";
    let mut secret_ref = (!clear_api_key && secrets.has(&api_key_ref)).then(|| api_key_ref.clone());

    if !clear_api_key {
        if let Some(secret) = input.secret_value.as_ref().filter(|s| !s.is_empty()) {
            let backend = secrets.set(&api_key_ref, secret)?;
            upsert_secret_meta(db, &api_key_ref, &input.id, &backend)?;
            secret_ref = Some(api_key_ref.clone());
        }
    }
    // `Some(None)` clears an explicit levels override; plain `None` leaves it.
    let levels_update = if input.supported_thinking_levels.is_some() {
        Some(input.supported_thinking_levels.clone())
    } else {
        None
    };
    let models_update = input.models.clone().map(Some);
    let config_json = merge_provider_config_overrides(
        &raw_config,
        input.supports_reasoning,
        levels_update,
        models_update,
        &LimitOverrides {
            context_window: input.context_window,
            max_output_tokens: input.max_output_tokens,
            temperature: input.temperature,
        },
    )?;
    // An empty label clears the badge, which is what logout sends.
    let config_json = match input.oauth_account_label.as_deref() {
        Some(label) => Some(config_with_oauth_account_label(
            config_json.as_deref().unwrap_or(&raw_config),
            label,
        )?),
        None => config_json,
    };
    // An empty map clears stored headers so adapter defaults return.
    let config_json = match input.headers.as_ref() {
        Some(headers) => Some(config_with_headers(
            config_json.as_deref().unwrap_or(&raw_config),
            headers,
        )?),
        None => config_json,
    };

    if clear_api_key {
        secrets.delete(&api_key_ref)?;
        db.conn()
            .prepare_cached("DELETE FROM secrets_meta WHERE secret_ref = ?1")?
            .execute(params![api_key_ref])?;
    }

    db.conn()
        .prepare_cached(
            "UPDATE providers SET
                name = COALESCE(?1, name),
                vendor_key = COALESCE(?2, vendor_key),
                type = COALESCE(?3, type),
                protocol = COALESCE(?4, protocol),
                base_url = COALESCE(?5, base_url),
                auth_kind = COALESCE(?6, auth_kind),
                default_model_id = COALESCE(?7, default_model_id),
                api_style = COALESCE(?8, api_style),
                enabled = COALESCE(?9, enabled),
                secret_ref = CASE WHEN ?14 THEN NULL ELSE COALESCE(?10, secret_ref) END,
                config_json = COALESCE(?11, config_json),
                updated_at = ?12
             WHERE id = ?13",
        )?
        .execute(params![
            input.name,
            input.vendor_key,
            input.provider_type,
            input.protocol,
            input.base_url,
            input.auth_kind,
            input.default_model_id.or_else(|| {
                input
                    .models
                    .as_ref()
                    .and_then(|models| models.first().map(|model| model.id.clone()))
            }),
            input.api_style,
            input.enabled.map(|b| if b { 1 } else { 0 }),
            secret_ref,
            config_json,
            now_ms(),
            input.id,
            clear_api_key
        ])?;
    // A save that drops bindings also forgets their cached rows. The cache is
    // the service's answer, and a model the user removed is no longer part of
    // the configuration that answer belongs to; keeping the row would feed the
    // deleted model's recorded limits back to the next add of the same id.
    if let Some(models) = input.models.as_deref() {
        let removed: Vec<String> = current
            .models
            .iter()
            .filter(|binding| {
                let id = binding.id.trim().to_lowercase();
                !models
                    .iter()
                    .any(|model| model.id.trim().to_lowercase() == id)
            })
            .map(|binding| binding.id.clone())
            .collect();
        forget_cached_models(db, &input.id, &removed)?;
    }
    // A save that moves the endpoint drops the answer the previous one
    // produced. The models the user configured stay: they are the configuration
    // the save just wrote, not a cached answer.
    if endpoint_changed {
        let configured: Vec<String> = match input.models.as_ref() {
            Some(models) => models.iter().map(|model| model.id.clone()).collect(),
            None => current
                .models
                .iter()
                .map(|binding| binding.id.clone())
                .collect(),
        };
        forget_missing_discovered_models(db, &input.id, &configured)?;
        db.conn().execute(
            "UPDATE models SET discovery_state = NULL, reported_context_window = NULL
             WHERE provider_id = ?1",
            params![input.id],
        )?;
    }
    get_provider(db, secrets, &input.id)
}

/// Delete a user-owned provider row. A plugin-declared row is refused here:
/// only its plugin (or the user disabling/uninstalling it) may remove it.
pub fn delete_provider(db: &Database, secrets: &SecretStore, id: &str) -> Result<bool> {
    if let Some(owner) = provider_owner_plugin(db, id)? {
        bail!("PROVIDER_OWNED_BY_PLUGIN: provider {id} belongs to plugin {owner}");
    }
    delete_provider_row(db, secrets, id)
}

/// The plugin that owns a provider row, or `None` for a user-owned row.
pub(crate) fn provider_owner_plugin(db: &Database, id: &str) -> Result<Option<String>> {
    db.conn()
        .query_row(
            "SELECT owner_plugin_id FROM providers WHERE id = ?1",
            params![id],
            |row| row.get::<_, Option<String>>(0),
        )
        .optional()
        .map(Option::flatten)
        .map_err(Into::into)
}

/// Row deletion without the ownership guard, for callers that already checked
/// it — the plugin provider sync and the plugin-scoped RPC methods.
pub(crate) fn delete_provider_row(db: &Database, secrets: &SecretStore, id: &str) -> Result<bool> {
    // Both credential channels are provider-scoped, so deleting the row must
    // take the OAuth credential with it or a re-created provider could inherit
    // a stranger's refresh token.
    for sref in [
        secret_ref_for_provider(id),
        secret_ref_for_provider_oauth(id),
    ] {
        // A credential that outlives its row would be inherited by a row that a
        // later declaration recreates under the same id, so a failure here is
        // reported rather than swallowed.
        secrets.delete(&sref)?;
        db.conn()
            .prepare_cached("DELETE FROM secrets_meta WHERE secret_ref = ?1")?
            .execute(params![sref])?;
    }
    let n = db
        .conn()
        .prepare_cached("DELETE FROM providers WHERE id = ?1")?
        .execute(params![id])?;
    Ok(n > 0)
}

/// Store or clear the API key of one provider row, whoever owns it.
///
/// A plugin-declared row is not editable through `update_provider`, but the
/// credential it asks for is the *user's*: the plugin publishes an endpoint and
/// this method is how the user hands over the key that endpoint needs. Only the
/// `api_key` reference and the row's `secret_ref` change; no field the plugin's
/// manifest owns is touched, so the next load still refreshes the declaration.
///
/// An empty value deletes the stored key and clears `secret_ref`. A fullwidth
/// value is folded to half-width, the same rule header values follow, because
/// the key is signed into an HTTP header.
pub fn set_provider_secret(
    db: &Database,
    secrets: &SecretStore,
    id: &str,
    secret_value: Option<&str>,
) -> Result<Option<ProviderPublic>> {
    if get_provider(db, secrets, id)?.is_none() {
        return Ok(None);
    }
    let api_key_ref = secret_ref_for_provider(id);
    let secret_value = secret_value.map(str::trim).map(fold_fullwidth);
    match secret_value.filter(|value| !value.is_empty()) {
        Some(value) => {
            let backend = secrets.set(&api_key_ref, &value)?;
            upsert_secret_meta(db, &api_key_ref, id, &backend)?;
            db.conn()
                .prepare_cached(
                    "UPDATE providers SET secret_ref = ?2, updated_at = ?3 WHERE id = ?1",
                )?
                .execute(params![id, api_key_ref, now_ms()])?;
        }
        None => {
            let _ = secrets.delete(&api_key_ref);
            db.conn()
                .prepare_cached("DELETE FROM secrets_meta WHERE secret_ref = ?1")?
                .execute(params![api_key_ref])?;
            db.conn()
                .prepare_cached(
                    "UPDATE providers SET secret_ref = NULL, updated_at = ?2 WHERE id = ?1",
                )?
                .execute(params![id, now_ms()])?;
        }
    }
    get_provider(db, secrets, id)
}
pub fn get_provider(
    db: &Database,
    secrets: &SecretStore,
    id: &str,
) -> Result<Option<ProviderPublic>> {
    let sql = format!("{PROVIDER_SELECT} WHERE id = ?1");
    let mut provider = db
        .conn()
        .prepare_cached(&sql)?
        .query_row(params![id], |row| provider_from_row(row, secrets))
        .optional()?;
    if let Some(provider) = provider.as_mut() {
        hydrate_dynamic_plugin_models(db, provider)?;
    }
    Ok(provider)
}

/// Whether `id` names a row, whoever owns it.
///
/// Reference checks ask this instead of `get_provider` because they only need
/// to know whether the row still exists: an existing row that is disabled or
/// carries no credential keeps its references, since the user can repair that
/// in Settings.
pub(crate) fn provider_exists(db: &Database, id: &str) -> Result<bool> {
    Ok(db
        .conn()
        .prepare_cached("SELECT 1 FROM providers WHERE id = ?1")?
        .query_row(params![id], |_| Ok(()))
        .optional()?
        .is_some())
}