bigtext 0.19.1

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
//! The assistant's settings as the settings file keeps them (`ai_*` lines): the provider, its
//! address and model, how the assistant works and what it may send. Read by the app's AI settings
//! and by `bigtext-cli ask`. Keys are never here (see [`super::keys`]).

use super::chat::Effort;
use super::keys::{self, KeyError, KeyStore};
use super::privacy::{self, Privacy};
use super::{preset, Preset, Provider};

/// A provider's address, model and way of working, as the user set them.
#[derive(Clone, Debug, PartialEq)]
pub struct ProviderConf {
    pub id: String,
    pub url: String,
    pub model: String,
    /// Tool calling (several steps); off: one step planned as JSON.
    pub tools: bool,
    /// The workspace of an Anthropic organization key (empty: none, or ANTHROPIC_WORKSPACE_ID).
    pub workspace: String,
}

impl ProviderConf {
    pub fn from_preset(p: &Preset) -> ProviderConf {
        ProviderConf {
            id: p.id.into(),
            url: p.url.into(),
            model: p.model.into(),
            // Small local models often plan better in JSON than with tool calls.
            tools: p.needs_key,
            workspace: String::new(),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct AiConfig {
    /// The active provider's preset id (empty: the assistant is off).
    pub provider: String,
    pub confs: Vec<ProviderConf>,
    /// Steps that only read run without asking: with a local provider, and with a cloud one.
    pub auto_local: bool,
    pub auto_cloud: bool,
    /// Send the results back for an answer.
    pub explain: bool,
    /// Tool steps one question may take.
    pub steps: u8,
    /// Offer steps that change the file (always confirmed).
    pub writes: bool,
    pub effort: Effort,
    pub privacy: Privacy,
    /// Redact for local providers too.
    pub redact_local: bool,
    /// Cloud providers whose first request the user has seen and allowed.
    pub asked: Vec<String>,
    /// Questions asked, newest first.
    pub history: Vec<String>,
}

pub const HISTORY_MAX: usize = 50;
pub const STEPS_MAX: u8 = 8;

impl Default for AiConfig {
    fn default() -> AiConfig {
        AiConfig {
            provider: String::new(),
            confs: Vec::new(),
            auto_local: true,
            auto_cloud: false,
            explain: true,
            steps: STEPS_MAX,
            writes: true,
            effort: Effort::Low,
            privacy: Privacy::default(),
            redact_local: false,
            asked: Vec::new(),
            history: Vec::new(),
        }
    }
}

impl AiConfig {
    pub fn enabled(&self) -> bool {
        preset(&self.provider).is_some()
    }

    /// The settings of provider `id` (its preset's until changed).
    pub fn conf(&self, id: &str) -> Option<ProviderConf> {
        self.confs
            .iter()
            .find(|c| c.id == id)
            .cloned()
            .or_else(|| preset(id).map(ProviderConf::from_preset))
    }

    pub fn set_conf(&mut self, c: ProviderConf) {
        match self.confs.iter_mut().find(|x| x.id == c.id) {
            Some(x) => *x = c,
            None => self.confs.push(c),
        }
    }

    /// The active provider, without its key.
    pub fn provider(&self) -> Option<Provider> {
        let p = preset(&self.provider)?;
        let c = self.conf(p.id)?;
        Some(Provider {
            id: c.id,
            protocol: p.protocol,
            url: c.url,
            model: c.model,
            key: None,
            workspace: c.workspace,
        })
    }

    pub fn remember(&mut self, question: &str) {
        let q = question.trim();
        if q.is_empty() || q.contains(['\n', '\r']) {
            return;
        }
        self.history.retain(|h| h != q);
        self.history.insert(0, q.to_string());
        self.history.truncate(HISTORY_MAX);
    }

    /// The settings file's `ai_*` lines.
    pub fn to_lines(&self) -> Vec<String> {
        let b = |x: bool| if x { "1" } else { "0" };
        let mut out = Vec::new();
        if !self.provider.is_empty() {
            out.push(format!("ai_provider={}", self.provider));
        }
        for c in &self.confs {
            if [&c.url, &c.model].iter().any(|s| s.contains(['\n', '\r'])) {
                continue;
            }
            out.push(format!(
                "ai_conf={}|{}|{}|{}",
                c.id,
                b(c.tools),
                c.model.replace('|', ""),
                c.url
            ));
            let ws = c.workspace.trim();
            if !ws.is_empty() && !ws.contains(['\n', '\r']) {
                out.push(format!("ai_workspace={}|{ws}", c.id));
            }
        }
        let p = &self.privacy;
        out.push(format!(
            "ai_opts=auto_local:{};auto_cloud:{};explain:{};steps:{};writes:{};effort:{};redact:{};ips:{};limit:{};journal:{};redact_local:{}",
            b(self.auto_local),
            b(self.auto_cloud),
            b(self.explain),
            self.steps,
            b(self.writes),
            self.effort.id(),
            b(p.redact),
            b(p.ips),
            p.limit,
            b(p.journal),
            b(self.redact_local),
        ));
        out.extend(self.asked.iter().map(|a| format!("ai_asked={a}")));
        out.extend(self.history.iter().map(|h| format!("ai_hist={h}")));
        out
    }

    pub fn from_lines(lines: &[String]) -> AiConfig {
        let mut c = AiConfig::default();
        for l in lines {
            let Some((k, v)) = l.split_once('=') else {
                continue;
            };
            match k {
                "ai_provider" => c.provider = v.to_string(),
                "ai_conf" => {
                    let mut it = v.splitn(4, '|');
                    if let (Some(id), Some(t), Some(model), Some(url)) =
                        (it.next(), it.next(), it.next(), it.next())
                    {
                        if preset(id).is_some() {
                            let workspace = c.conf(id).map(|x| x.workspace).unwrap_or_default();
                            c.set_conf(ProviderConf {
                                id: id.into(),
                                url: url.into(),
                                model: model.into(),
                                tools: t == "1",
                                workspace,
                            });
                        }
                    }
                }
                // A line of its own, so that 0.19.0 reads the ai_conf lines as before.
                "ai_workspace" => {
                    if let Some((id, ws)) = v.split_once('|') {
                        if let Some(mut pc) = c.conf(id) {
                            pc.workspace = ws.trim().into();
                            c.set_conf(pc);
                        }
                    }
                }
                "ai_opts" => {
                    for kv in v.split(';') {
                        let Some((k, v)) = kv.split_once(':') else {
                            continue;
                        };
                        let on = v == "1";
                        match k {
                            "auto_local" => c.auto_local = on,
                            "auto_cloud" => c.auto_cloud = on,
                            "explain" => c.explain = on,
                            "steps" => {
                                c.steps = v.parse::<u8>().unwrap_or(STEPS_MAX).clamp(1, STEPS_MAX)
                            }
                            "writes" => c.writes = on,
                            "effort" => c.effort = Effort::from_id(v).unwrap_or(Effort::Low),
                            "redact" => c.privacy.redact = on,
                            "ips" => c.privacy.ips = on,
                            "limit" => {
                                c.privacy.limit = v
                                    .parse::<usize>()
                                    .unwrap_or(privacy::LIMIT_DEFAULT)
                                    .clamp(privacy::LIMIT_MIN, privacy::LIMIT_MAX)
                            }
                            "journal" => c.privacy.journal = on,
                            "redact_local" => c.redact_local = on,
                            _ => {}
                        }
                    }
                }
                "ai_asked" => c.asked.push(v.to_string()),
                "ai_hist" if c.history.len() < HISTORY_MAX => c.history.push(v.to_string()),
                _ => {}
            }
        }
        c
    }
}

/// Where the active provider's key comes from.
#[derive(Clone, Debug, PartialEq)]
pub enum KeyStatus {
    /// From this environment variable.
    Env(String),
    Keychain,
    /// In the encrypted key file.
    File(String),
    Missing,
    /// The key file needs its passphrase.
    Locked,
    Failed(String),
    NotNeeded,
}

/// The key of preset `p`: from its environment variable, else from the store.
pub fn resolve_key(store: &KeyStore, p: &Preset) -> (Option<String>, KeyStatus) {
    if let Some((k, var)) = keys::from_env(p) {
        return (Some(k), KeyStatus::Env(var.into()));
    }
    match store.get(p.id) {
        Ok(Some(k)) => {
            let where_ = match &store.kind {
                keys::Kind::Keychain => KeyStatus::Keychain,
                keys::Kind::File(f) => KeyStatus::File(f.display().to_string()),
            };
            (Some(k), where_)
        }
        Ok(None) if !p.needs_key => (None, KeyStatus::NotNeeded),
        Ok(None) => (None, KeyStatus::Missing),
        Err(KeyError::NeedPassphrase) | Err(KeyError::WrongPassphrase) => (None, KeyStatus::Locked),
        Err(e) => (None, KeyStatus::Failed(e.to_string())),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn settings_lines_round_trip() {
        let mut c = AiConfig {
            provider: "ollama".into(),
            steps: 3,
            explain: false,
            auto_cloud: true,
            effort: Effort::High,
            ..AiConfig::default()
        };
        c.privacy.limit = 32 * 1024;
        c.privacy.ips = true;
        c.set_conf(ProviderConf {
            id: "ollama".into(),
            url: "http://localhost:11434/v1".into(),
            model: "qwen3:8b".into(),
            tools: false,
            workspace: String::new(),
        });
        let mut a = ProviderConf::from_preset(preset("anthropic").unwrap());
        a.workspace = "wrkspc_test".into();
        c.set_conf(a);
        c.asked.push("anthropic".into());
        c.remember("find all errors");
        c.remember("multi\nline");
        let back = AiConfig::from_lines(&c.to_lines());
        assert_eq!(back, c);
        assert_eq!(back.history, vec!["find all errors"]);
        let p = back.provider().unwrap();
        assert_eq!(p.model, "qwen3:8b");
        assert!(p.key.is_none());
        assert!(c
            .to_lines()
            .contains(&"ai_workspace=anthropic|wrkspc_test".to_string()));
        assert_eq!(back.conf("anthropic").unwrap().workspace, "wrkspc_test");
        // Unknown providers and odd values are ignored.
        let odd = AiConfig::from_lines(&[
            "ai_conf=nope|1|m|u".into(),
            "ai_opts=steps:99;limit:1".into(),
        ]);
        assert!(odd.confs.is_empty());
        assert_eq!(odd.steps, STEPS_MAX);
        assert_eq!(odd.privacy.limit, privacy::LIMIT_MIN);
        assert!(!AiConfig::default().enabled());
    }
}