eclipse-cli 0.13.4

Command-line interface for eclipse
//! "Which quirk is on?" answered without reading a manifest.
//!
//! A provider profile is a manifest, and a manifest is invisible from the outside: the run behaves
//! differently because of a file the person asking never opened. This says which profile is in
//! force for the configured model and base URL, whether it came from the binary or from a file, and
//! what it decides — the reasoning control, the limits, the fields this route will not take.
//!
//! Two commands print it: `eclipse config check` (a human looking for what is on) and
//! `eclipse tools schema` (a script, in the same document as the tools).

use eclipse_core::config::Config;
use eclipse_core::provider::{ProviderProfile, Reasoning};
use eclipse_core::{plugins, reasoning};

use crate::{process_env, Style};

/// Everything the report says, built once and rendered two ways.
pub struct Report {
    pub profile: String,
    /// Where the profile came from: `built-in`, or the manifest that declared it.
    pub source: String,
    pub model: String,
    pub base_url: String,
    /// What a reasoning ask becomes here, or why this backend has no dial.
    pub reasoning: String,
    /// The effort this session would send right now, if it sends one.
    pub effort: Option<String>,
    pub vision: Option<bool>,
    pub num_ctx: Option<u32>,
    pub max_output: Option<u32>,
    pub temperature: Option<String>,
    pub rejects: Vec<String>,
    pub aux_model: Option<String>,
    /// The fields this profile will and will not put on the wire, named so the answer does not
    /// depend on reading the source of the clamp.
    pub sends: Vec<String>,
}

impl Report {
    pub fn as_json(&self) -> serde_json::Value {
        serde_json::json!({
            "profile": self.profile,
            "source": self.source,
            "model": self.model,
            "base_url": self.base_url,
            "reasoning": self.reasoning,
            "effort": self.effort,
            "vision": self.vision,
            "num_ctx": self.num_ctx,
            "max_output": self.max_output,
            "temperature": self.temperature,
            "reject_response_formats": self.rejects,
            "aux_model": self.aux_model,
            "sends": self.sends,
        })
    }

    /// The human view: one line per fact, because a table here would be a paragraph.
    pub fn lines(&self, style: &Style) -> Vec<String> {
        let mut out = Vec::new();
        let head = if self.source == "built-in" {
            format!("{} (built in)", self.profile)
        } else {
            format!("{} (from {})", self.profile, self.source)
        };
        out.push(format!(
            "{} {} for {} at {}",
            style.dim("provider profile:"),
            style.cyan(&head),
            self.model,
            self.base_url
        ));
        out.push(format!("{} {}", style.dim("reasoning:"), self.reasoning));
        if let Some(effort) = &self.effort {
            // The sentinel is a spelling, not a level: saying `omit` alone next to "reasoning:
            // not sent" reads like two settings that disagree (`#278`).
            let word = if eclipse_core::reasoning::is_omit(effort) {
                format!("{effort} (no field is sent)")
            } else {
                effort.clone()
            };
            out.push(format!("{} {word}", style.dim("effort now:")));
        }
        if let Some(vision) = self.vision {
            out.push(format!(
                "{} {}",
                style.dim("vision:"),
                if vision { "yes" } else { "no" }
            ));
        }
        if self.num_ctx.is_some() || self.max_output.is_some() {
            let mut limits = Vec::new();
            if let Some(n) = self.num_ctx {
                limits.push(format!("num_ctx {n}"));
            }
            if let Some(n) = self.max_output {
                limits.push(format!("max_output {n}"));
            }
            out.push(format!("{} {}", style.dim("limits:"), limits.join(", ")));
        }
        if let Some(t) = &self.temperature {
            out.push(format!("{} {t}", style.dim("temperature:")));
        }
        if !self.rejects.is_empty() {
            out.push(format!(
                "{} {}",
                style.dim("rejects:"),
                self.rejects.join(", ")
            ));
        }
        if let Some(aux) = &self.aux_model {
            out.push(format!("{} {aux}", style.dim("aux model:")));
        }
        if !self.sends.is_empty() {
            out.push(format!(
                "{} {}",
                style.dim("sends:"),
                self.sends.join(" · ")
            ));
        }
        out
    }
}

/// Resolve the profile the configured provider will actually run on, and describe it.
pub fn report(cfg: &Config) -> Report {
    let dirs = cfg.plugins_dirs(&process_env);
    let loaded = plugins::load(&dirs, &cfg.plugins.enabled);
    let from_plugins = loaded.provider_profiles();
    let name = cfg.provider.profile.clone().unwrap_or_default();
    let model = cfg.provider.model.clone();
    let base_url = cfg.provider.base_url.clone();

    // `resolve` is exactly what the provider does, so an unknown name is reported the same way it
    // will be reported when a request is attempted.
    let (profile, source) = match ProviderProfile::resolve(&name, &from_plugins) {
        Ok(profile) => {
            let from = from_plugins
                .iter()
                .find(|p| p.name == profile.name)
                .and_then(|p| {
                    loaded
                        .plugins
                        .iter()
                        .find(|plugin| {
                            plugin
                                .manifest
                                .provider_profiles
                                .iter()
                                .any(|d| d.name == p.name)
                        })
                        .map(|plugin| format!("{}/plugin.toml", plugin.dir.display()))
                })
                .unwrap_or_else(|| "built-in".to_string());
            (Some(profile), from)
        }
        Err(e) => (None, format!("unresolved: {e}")),
    };

    let mut report = Report {
        profile: if name.is_empty() {
            "openai".to_string()
        } else {
            name.clone()
        },
        source,
        model: model.clone(),
        base_url: base_url.clone(),
        reasoning: String::new(),
        effort: None,
        vision: None,
        num_ctx: None,
        max_output: None,
        temperature: None,
        rejects: Vec::new(),
        aux_model: None,
        sends: Vec::new(),
    };
    let Some(profile) = profile else {
        report.reasoning = "unresolved".to_string();
        return report;
    };

    report.vision = profile.vision;
    let limits = profile.request.limits_for(&model);
    report.num_ctx = limits.num_ctx;
    report.max_output = limits.max_output;
    report.temperature = match profile.request.temperature {
        Some(eclipse_core::provider::Temperature::Omit) => Some("never sent".to_string()),
        Some(eclipse_core::provider::Temperature::Fixed(v)) => Some(format!("always {v}")),
        _ => None,
    };
    report.rejects = profile.request.reject_response_formats.clone();
    report.aux_model = profile.request.aux_model.clone();

    match profile.reasoning_for(&model) {
        Reasoning::Off => {
            report.reasoning = "none: this model does not reason".to_string();
        }
        Reasoning::Undeclared => {
            report.reasoning =
                "undeclared: a configured level is sent as `reasoning_effort` verbatim".to_string();
        }
        Reasoning::Policy(policy) => {
            let configured = cfg
                .provider
                .reasoning_effort
                .clone()
                .or_else(|| std::env::var("ECLIPSE_REASONING_EFFORT").ok());
            report.effort = configured.clone();
            report.reasoning = policy.describe(configured.as_deref());
            // What it will do for the asks people actually type, so the clamp is visible rather
            // than inferred from the level list.
            // Every ask that lands somewhere, plus every ask the manifest renames: `xhigh → max`
            // has to be visible here or the mapping is only in the file.
            let mut sends = Vec::new();
            let mut asked: Vec<String> = ["low", "medium", "high", "minimal", "xhigh", "max"]
                .iter()
                .map(|s| s.to_string())
                .collect();
            for renamed in policy.map.keys() {
                if !asked.contains(renamed) {
                    asked.push(renamed.clone());
                }
            }
            for level in &asked {
                let line = policy.describe(Some(level));
                let rest = line
                    .strip_prefix("sends ")
                    .or_else(|| line.split_once("→ sends ").map(|(_, to)| to));
                if let Some(to) = rest {
                    sends.push(format!("{level} → {to}"));
                }
            }
            report.sends = sends;
            if let Some(off) = &policy.off {
                report.sends.push(format!("off → {}", describe_off(off)));
            }
            if policy.levels.is_empty() {
                report.reasoning = format!("{} (no graded levels)", report.reasoning);
            }
            let _ = reasoning::looks_like_ollama(&base_url);
        }
    }
    report
}

fn describe_off(switch: &reasoning::OffSwitch) -> String {
    match switch {
        reasoning::OffSwitch::Text(text) => text.clone(),
        reasoning::OffSwitch::Flag(flag) => flag.to_string(),
        reasoning::OffSwitch::Body(body) => {
            let keys: Vec<String> = body
                .as_object()
                .map(|o| o.keys().cloned().collect())
                .unwrap_or_default();
            keys.join(", ")
        }
    }
}