Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

18.4 KB
Raw Blame
use std::env;

use colored::{ColoredString, Colorize};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Rgb(pub(crate) u8, pub(crate) u8, pub(crate) u8);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ThemeColor {
    TrueColor(Rgb),
    /// Terminal default foreground (SGR 39). Follows the current light/dark theme.
    DefaultFg,
    /// Dim/faint (SGR 2). Secondary text relative to the default foreground.
    Dim,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ColorLevel {
    NoColor,
    Ansi16,
    Ansi256,
    TrueColor,
}

impl ThemeColor {
    pub(crate) fn rgb_fallback(&self) -> Rgb {
        match self {
            ThemeColor::TrueColor(rgb) => *rgb,
            ThemeColor::DefaultFg | ThemeColor::Dim => {
                unreachable!("semantic text colors follow the terminal palette")
            }
        }
    }
}

#[cfg(test)]
const BRAND_SIGNAL: Rgb = Rgb(79, 214, 240);

/// OpenViking brand deep teal (#0A7C93). Readable on both light and dark
/// terminals, so it is the accent for borders, commands and headings.
pub(crate) const BRAND_DEEP_TEAL: Rgb = Rgb(10, 124, 147);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CliTheme {
    /// Solid ink for the braille mark, readable on both terminal backgrounds.
    pub(crate) mark: Rgb,
    /// Block-letter wordmark. The brand wordmark is Paper on dark and Ink on
    /// light, which is what the terminal default foreground already gives.
    pub(crate) wordmark: ThemeColor,
    pub(crate) border: ThemeColor,
    pub(crate) version: ThemeColor,
    pub(crate) brand_title: ThemeColor,
    pub(crate) body: ThemeColor,
    pub(crate) muted: ThemeColor,
    pub(crate) command: ThemeColor,
    pub(crate) heading: ThemeColor,
    pub(crate) value: ThemeColor,
    pub(crate) sky_value: ThemeColor,
    pub(crate) success: ThemeColor,
    pub(crate) warning: ThemeColor,
    pub(crate) error: ThemeColor,
    pub(crate) config_name: ThemeColor,
    pub(crate) section_marker: ThemeColor,
    pub(crate) prompt: ThemeColor,
    pub(crate) selection: ThemeColor,
}

pub(crate) fn active_theme() -> CliTheme {
    palette()
}

pub(crate) fn palette() -> CliTheme {
    CliTheme {
        mark: BRAND_DEEP_TEAL,
        wordmark: ThemeColor::DefaultFg,
        border: ThemeColor::TrueColor(BRAND_DEEP_TEAL),
        version: ThemeColor::TrueColor(BRAND_DEEP_TEAL),
        brand_title: ThemeColor::TrueColor(BRAND_DEEP_TEAL),
        body: ThemeColor::DefaultFg,
        muted: ThemeColor::Dim,
        command: ThemeColor::TrueColor(BRAND_DEEP_TEAL),
        heading: ThemeColor::TrueColor(BRAND_DEEP_TEAL),
        value: ThemeColor::TrueColor(Rgb(0, 112, 190)),
        sky_value: ThemeColor::TrueColor(Rgb(0, 112, 190)),
        success: ThemeColor::TrueColor(Rgb(0, 133, 90)),
        warning: ThemeColor::TrueColor(Rgb(185, 90, 0)),
        error: ThemeColor::TrueColor(Rgb(212, 60, 55)),
        config_name: ThemeColor::TrueColor(Rgb(199, 80, 0)),
        section_marker: ThemeColor::TrueColor(Rgb(139, 92, 246)),
        prompt: ThemeColor::TrueColor(Rgb(150, 109, 27)),
        selection: ThemeColor::TrueColor(Rgb(0, 133, 90)),
    }
}

pub(crate) fn colorize(text: impl Into<String>, color: ThemeColor) -> ColoredString {
    let text = text.into();
    match color {
        ThemeColor::TrueColor(Rgb(red, green, blue)) => text.truecolor(red, green, blue),
        ThemeColor::DefaultFg => default_foreground(text),
        ThemeColor::Dim => text.dimmed(),
    }
}

fn default_foreground(text: String) -> ColoredString {
    paint_default_foreground(text, false)
}

fn paint_default_foreground(text: String, bold: bool) -> ColoredString {
    if !colored::control::SHOULD_COLORIZE.should_colorize() {
        return ColoredString::from(text);
    }

    // colored 2.x has no Default color. Emit SGR 39 so body text uses the
    // terminal default foreground instead of a hardcoded gray, black, or white.
    let code = if bold { "1;39" } else { "39" };
    ColoredString::from(format!("\u{1b}[{code}m{text}\u{1b}[0m"))
}

pub(crate) fn terminal_color_level() -> ColorLevel {
    if !colored::control::SHOULD_COLORIZE.should_colorize() {
        return ColorLevel::NoColor;
    }

    terminal_color_level_from_env(
        env::var("COLORTERM").ok().as_deref(),
        env::var("TERM").ok().as_deref(),
        env::var("TERM_PROGRAM").ok().as_deref(),
    )
}

pub(crate) fn terminal_color_level_from_env(
    colorterm: Option<&str>,
    term: Option<&str>,
    term_program: Option<&str>,
) -> ColorLevel {
    if colorterm
        .map(|value| value.eq_ignore_ascii_case("truecolor") || value.eq_ignore_ascii_case("24bit"))
        .unwrap_or(false)
        || term
            .map(|value| {
                let value = value.to_ascii_lowercase();
                value.contains("truecolor") || value.contains("24bit") || value.contains("direct")
            })
            .unwrap_or(false)
        || term_program
            .map(|value| {
                matches!(
                    value.to_ascii_lowercase().as_str(),
                    "iterm.app" | "wezterm" | "vscode" | "windows_terminal"
                )
            })
            .unwrap_or(false)
    {
        return ColorLevel::TrueColor;
    }

    if term
        .map(|value| value.to_ascii_lowercase().contains("256color"))
        .unwrap_or(false)
        || term_program
            .map(|value| value.eq_ignore_ascii_case("Apple_Terminal"))
            .unwrap_or(false)
    {
        return ColorLevel::Ansi256;
    }

    ColorLevel::Ansi16
}

pub(crate) fn style_rgb(text: impl AsRef<str>, rgb: Rgb, bold: bool) -> String {
    style_rgb_for_level(text, rgb, bold, terminal_color_level())
}

pub(crate) fn style_rgb_for_level(
    text: impl AsRef<str>,
    rgb: Rgb,
    bold: bool,
    level: ColorLevel,
) -> String {
    let text = text.as_ref();
    match level {
        ColorLevel::NoColor => text.to_string(),
        ColorLevel::TrueColor => {
            let Rgb(red, green, blue) = rgb;
            ansi_style(text, &format!("38;2;{red};{green};{blue}"), bold)
        }
        ColorLevel::Ansi256 => {
            ansi_style(text, &format!("38;5;{}", ansi256_index_for_rgb(rgb)), bold)
        }
        ColorLevel::Ansi16 => ansi_style(text, &ansi16_fg_code_for_rgb(rgb).to_string(), bold),
    }
}

/// Styles `text` with a semantic theme color at an explicit color level, so
/// callers that already resolved the level (banner art) stay deterministic.
pub(crate) fn style_theme_color_for_level(
    text: impl AsRef<str>,
    color: ThemeColor,
    bold: bool,
    level: ColorLevel,
) -> String {
    let text = text.as_ref();
    match (color, level) {
        (_, ColorLevel::NoColor) => text.to_string(),
        (ThemeColor::TrueColor(rgb), _) => style_rgb_for_level(text, rgb, bold, level),
        (ThemeColor::DefaultFg, _) => ansi_style(text, "39", bold),
        (ThemeColor::Dim, _) => ansi_style(text, "2", bold),
    }
}

fn ansi_style(text: &str, fg_code: &str, bold: bool) -> String {
    if bold {
        format!("\u{1b}[1;{fg_code}m{text}\u{1b}[0m")
    } else {
        format!("\u{1b}[{fg_code}m{text}\u{1b}[0m")
    }
}

pub(crate) fn ansi256_index_for_rgb(rgb: Rgb) -> u8 {
    let Rgb(red, green, blue) = rgb;

    if red.abs_diff(green) <= 10 && green.abs_diff(blue) <= 10 {
        let average = (u16::from(red) + u16::from(green) + u16::from(blue)) / 3;
        if average < 8 {
            return 16;
        }
        if average > 238 {
            return 231;
        }
        return 232 + ((average - 8) / 10) as u8;
    }

    let red = ansi256_cube_component(red);
    let green = ansi256_cube_component(green);
    let blue = ansi256_cube_component(blue);

    16 + 36 * red + 6 * green + blue
}

fn ansi256_cube_component(value: u8) -> u8 {
    if value < 48 {
        0
    } else if value < 115 {
        1
    } else {
        ((value - 35) / 40).min(5)
    }
}

fn ansi16_fg_code_for_rgb(rgb: Rgb) -> u8 {
    const ANSI16: [(u8, Rgb); 16] = [
        (30, Rgb(0, 0, 0)),
        (31, Rgb(128, 0, 0)),
        (32, Rgb(0, 128, 0)),
        (33, Rgb(128, 128, 0)),
        (34, Rgb(0, 0, 128)),
        (35, Rgb(128, 0, 128)),
        (36, Rgb(0, 128, 128)),
        (37, Rgb(192, 192, 192)),
        (90, Rgb(128, 128, 128)),
        (91, Rgb(255, 0, 0)),
        (92, Rgb(0, 255, 0)),
        (93, Rgb(255, 255, 0)),
        (94, Rgb(0, 0, 255)),
        (95, Rgb(255, 0, 255)),
        (96, Rgb(0, 255, 255)),
        (97, Rgb(255, 255, 255)),
    ];

    ANSI16
        .iter()
        .min_by_key(|(_, candidate)| rgb_distance_squared(rgb, *candidate))
        .map(|(code, _)| *code)
        .unwrap_or(37)
}

fn rgb_distance_squared(left: Rgb, right: Rgb) -> u32 {
    let red = i32::from(left.0) - i32::from(right.0);
    let green = i32::from(left.1) - i32::from(right.1);
    let blue = i32::from(left.2) - i32::from(right.2);

    (red * red + green * green + blue * blue) as u32
}

pub(crate) fn brand_title(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.brand_title)
}

pub(crate) fn border(text: impl Into<String>) -> ColoredString {
    colorize(text, active_theme().border)
}

pub(crate) fn version(text: impl Into<String>) -> ColoredString {
    colorize(text, active_theme().version)
}

pub(crate) fn command(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.command)
}

pub(crate) fn body(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.body)
}

pub(crate) fn muted(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.muted)
}

pub(crate) fn heading(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.heading)
}

pub(crate) fn value(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.value)
}

pub(crate) fn sky_value(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.sky_value)
}

pub(crate) fn success(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.success)
}

pub(crate) fn warning(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.warning)
}

pub(crate) fn error(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.error)
}

pub(crate) fn config_name(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.config_name)
}

pub(crate) fn section_marker(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.section_marker)
}

pub(crate) fn prompt(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.prompt)
}

pub(crate) fn selection(text: impl Into<String>) -> ColoredString {
    let theme = active_theme();
    colorize(text, theme.selection)
}

pub(crate) fn strong(text: impl Into<String>) -> ColoredString {
    paint_default_foreground(text.into(), true)
}

#[cfg(test)]
fn relative_luminance(color: Rgb) -> f32 {
    fn channel(value: u8) -> f32 {
        let value = value as f32 / 255.0;
        if value <= 0.03928 {
            value / 12.92
        } else {
            ((value + 0.055) / 1.055).powf(2.4)
        }
    }
    0.2126 * channel(color.0) + 0.7152 * channel(color.1) + 0.0722 * channel(color.2)
}

#[cfg(test)]
mod tests {
    use super::{
        BRAND_DEEP_TEAL, BRAND_SIGNAL, CliTheme, ColorLevel, Rgb, ThemeColor, active_theme,
        ansi256_index_for_rgb, palette, relative_luminance, style_rgb_for_level,
        style_theme_color_for_level, terminal_color_level_from_env,
    };

    const PALE_PEARL: Rgb = Rgb(234, 253, 247);
    const WHITE: Rgb = Rgb(255, 255, 255);
    const BLACK: Rgb = Rgb(0, 0, 0);

    #[test]
    fn active_theme_uses_the_single_palette() {
        assert_eq!(active_theme(), palette());
    }

    #[test]
    fn apple_terminal_uses_ansi256_instead_of_truecolor() {
        assert_eq!(
            terminal_color_level_from_env(None, Some("xterm-256color"), Some("Apple_Terminal")),
            ColorLevel::Ansi256
        );
        assert_eq!(
            terminal_color_level_from_env(
                Some("truecolor"),
                Some("xterm-256color"),
                Some("Apple_Terminal")
            ),
            ColorLevel::TrueColor
        );
    }

    #[test]
    fn ansi256_mapping_keeps_dark_teal_out_of_black_and_gray() {
        let index = ansi256_index_for_rgb(Rgb(5, 86, 80));

        assert_eq!(index, 23);
        assert!(!matches!(index, 0 | 8 | 232..=255));
    }

    #[test]
    fn rgb_styling_uses_fixed_ansi256_when_truecolor_is_unavailable() {
        let styled = style_rgb_for_level("X", Rgb(5, 86, 80), true, ColorLevel::Ansi256);

        assert_eq!(styled, "\u{1b}[1;38;5;23mX\u{1b}[0m");
        assert!(!styled.contains("38;2"));
    }

    fn accent_colors(palette: CliTheme) -> [(&'static str, ThemeColor); 11] {
        [
            ("brand_title", palette.brand_title),
            ("command", palette.command),
            ("heading", palette.heading),
            ("value", palette.value),
            ("sky_value", palette.sky_value),
            ("success", palette.success),
            ("warning", palette.warning),
            ("error", palette.error),
            ("config_name", palette.config_name),
            ("section_marker", palette.section_marker),
            ("prompt", palette.prompt),
        ]
    }

    fn contrast_ratio(foreground: Rgb, background: Rgb) -> f32 {
        let foreground = relative_luminance(foreground);
        let background = relative_luminance(background);
        let (lighter, darker) = if foreground > background {
            (foreground, background)
        } else {
            (background, foreground)
        };
        (lighter + 0.05) / (darker + 0.05)
    }

    fn assert_min_contrast(name: &str, color: ThemeColor, background: Rgb, minimum: f32) {
        let ratio = contrast_ratio(color.rgb_fallback(), background);
        assert!(
            ratio >= minimum,
            "{name} contrast {ratio:.2} is below {minimum:.2} against {background:?}"
        );
    }

    #[test]
    fn single_palette_uses_explicit_balanced_functional_colors() {
        let palette = palette();
        for (name, color) in accent_colors(palette) {
            assert_ne!(
                color.rgb_fallback(),
                PALE_PEARL,
                "{name} must not use pale Pearl"
            );
            assert_min_contrast(name, color, WHITE, 4.0);
            assert_min_contrast(name, color, BLACK, 4.0);
        }
    }

    #[test]
    fn brand_colors_match_the_openviking_brand_manual() {
        assert_eq!(BRAND_SIGNAL, Rgb(0x4F, 0xD6, 0xF0));
        assert_eq!(BRAND_DEEP_TEAL, Rgb(0x0A, 0x7C, 0x93));
    }

    #[test]
    fn signal_cyan_never_carries_text() {
        // The brand forbids Signal on light backgrounds, and the CLI cannot
        // see the terminal background, so the CLI uses solid deep teal for the mark and accents.
        let palette = palette();
        for (name, color) in accent_colors(palette) {
            assert_ne!(
                color,
                ThemeColor::TrueColor(BRAND_SIGNAL),
                "{name} must not be Signal"
            );
        }
        assert!(contrast_ratio(BRAND_SIGNAL, WHITE) < 4.0);
        assert!(contrast_ratio(BRAND_DEEP_TEAL, WHITE) >= 4.5);
        assert!(contrast_ratio(BRAND_DEEP_TEAL, BLACK) >= 4.0);
    }

    #[test]
    fn theme_color_styling_respects_the_color_level() {
        assert_eq!(
            style_theme_color_for_level("OV", ThemeColor::DefaultFg, true, ColorLevel::TrueColor),
            "\u{1b}[1;39mOV\u{1b}[0m"
        );
        assert_eq!(
            style_theme_color_for_level("OV", ThemeColor::DefaultFg, true, ColorLevel::NoColor),
            "OV"
        );
        assert_eq!(
            style_theme_color_for_level(
                "OV",
                ThemeColor::TrueColor(BRAND_DEEP_TEAL),
                false,
                ColorLevel::Ansi256
            ),
            "\u{1b}[38;5;30mOV\u{1b}[0m"
        );
    }

    #[test]
    fn body_and_muted_follow_the_terminal_instead_of_fixed_gray() {
        let palette = palette();
        assert_eq!(palette.body, ThemeColor::DefaultFg);
        assert_eq!(palette.muted, ThemeColor::Dim);
    }

    #[test]
    fn body_uses_default_foreground_instead_of_black_white_or_rgb_gray() {
        colored::control::set_override(true);
        let rendered = super::body("The context database").to_string();
        colored::control::unset_override();

        assert_eq!(rendered, "\u{1b}[39mThe context database\u{1b}[0m");
        assert!(!rendered.contains("38;2"));
        assert!(!rendered.contains("\u{1b}[30m"));
        assert!(!rendered.contains("\u{1b}[37m"));
        assert!(!rendered.contains("\u{1b}[90m"));
        assert!(!rendered.contains("\u{1b}[97m"));
    }

    #[test]
    fn muted_uses_dim_instead_of_gray_rgb() {
        colored::control::set_override(true);
        let rendered = super::muted("optional hint").to_string();
        colored::control::unset_override();

        assert!(
            rendered.contains("\u{1b}[2m"),
            "muted text should use SGR 2 (dim): {rendered:?}"
        );
        assert!(rendered.contains("optional hint"));
        assert!(!rendered.contains("38;2"));
        assert!(!rendered.contains("\u{1b}[30m"));
        assert!(!rendered.contains("\u{1b}[37m"));
        assert!(!rendered.contains("\u{1b}[90m"));
        assert!(!rendered.contains("\u{1b}[97m"));
    }

    #[test]
    fn strong_bolds_the_default_foreground() {
        colored::control::set_override(true);
        let rendered = super::strong("Normal commands").to_string();
        colored::control::unset_override();

        assert_eq!(rendered, "\u{1b}[1;39mNormal commands\u{1b}[0m");
        assert!(!rendered.contains("38;2"));
    }

    #[test]
    fn single_palette_keeps_teal_structure_and_sky_values() {
        let palette = palette();

        let Rgb(command_red, command_green, _) = palette.command.rgb_fallback();
        assert!(
            command_red < 40 && command_green >= 115,
            "commands should remain green/teal structure text"
        );

        let Rgb(sky_red, sky_green, sky_blue) = palette.sky_value.rgb_fallback();
        assert!(
            sky_blue > sky_green && sky_blue > sky_red,
            "model names, paths, and URLs should use a clearer sky-blue value color"
        );
    }
}