bigtext 0.19.0

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
//! What may leave the computer. File text that goes to a model — the profile's lines, tool
//! results, a selection — first passes through Share safely's redaction (tokens, keys,
//! passwords, cookies, e-mail addresses and, if chosen, IP addresses), and one question may send
//! at most a set number of bytes of it: past that, results lose their lines and keep their
//! counts. A local journal of what was sent is kept only when the user turns it on.

use std::io::Write;
use std::path::PathBuf;

use serde_json::Value;

use crate::redact::{Options, Redactor};

/// The default number of bytes of file text one question may send.
pub const LIMIT_DEFAULT: usize = 16 * 1024;
pub const LIMIT_MIN: usize = 4 * 1024;
pub const LIMIT_MAX: usize = 256 * 1024;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Privacy {
    /// Hide secrets in the file text sent.
    pub redact: bool,
    /// Hide IP addresses too.
    pub ips: bool,
    /// Bytes of file text one question may send.
    pub limit: usize,
    /// Keep a journal of what was sent (`ai-sent.log` next to the settings).
    pub journal: bool,
}

impl Default for Privacy {
    fn default() -> Privacy {
        Privacy {
            redact: true,
            ips: false,
            limit: LIMIT_DEFAULT,
            journal: false,
        }
    }
}

/// Hides secrets in text, counting what it hid.
pub struct Redact {
    r: Option<Redactor>,
    pub hidden: u64,
}

impl Redact {
    pub fn new(p: &Privacy) -> Redact {
        let r = p.redact.then(|| {
            Redactor::new(
                &Options {
                    ips: p.ips,
                    ..Options::default()
                },
                crate::redact::random_salt(),
            )
            .ok()
        });
        Redact {
            r: r.flatten(),
            hidden: 0,
        }
    }

    /// No redaction (a local model with redaction turned off).
    pub fn none() -> Redact {
        Redact { r: None, hidden: 0 }
    }

    pub fn text(&mut self, s: &str) -> String {
        let Some(r) = &mut self.r else {
            return s.to_string();
        };
        let mut out = Vec::with_capacity(s.len());
        let mut first = true;
        let mut result = String::with_capacity(s.len());
        for line in s.split('\n') {
            if !first {
                result.push('\n');
            }
            first = false;
            out.clear();
            self.hidden += r.line(line.as_bytes(), &mut out) as u64;
            result.push_str(&String::from_utf8_lossy(&out));
        }
        result
    }
}

/// About how many tokens `bytes` of text make (four bytes a token, rounded up).
pub fn tokens(bytes: usize) -> u64 {
    bytes.div_ceil(4) as u64
}

/// The arrays of a result that hold file text, emptied from the end first.
const LISTS: [&str; 9] = [
    "first_lines",
    "lines",
    "top",
    "bars",
    "longest",
    "preview",
    "first_lines_sample",
    "templates_list",
    "values",
];

/// `v` made to fit in `max` bytes of JSON: the last entries of its lists go first, then long
/// strings are cut. Returns whether anything was left out.
pub fn fit(v: &mut Value, max: usize) -> bool {
    let size = |v: &Value| serde_json::to_string(v).map(|s| s.len()).unwrap_or(0);
    let mut cut = false;
    while size(v) > max {
        cut = true;
        // The longest list loses its last entry.
        let longest = v.as_object().and_then(|o| {
            LISTS
                .iter()
                .filter_map(|k| Some((*k, o.get(*k)?.as_array()?.len())))
                .filter(|(_, n)| *n > 0)
                .max_by_key(|(_, n)| *n)
                .map(|(k, _)| k)
        });
        if let Some(k) = longest {
            if let Some(a) = v.get_mut(k).and_then(|a| a.as_array_mut()) {
                a.pop();
            }
            continue;
        }
        // Then the longest string is halved.
        if !halve_longest_string(v) {
            break;
        }
    }
    if cut {
        if let Some(o) = v.as_object_mut() {
            o.insert("cut_to_size_limit".into(), Value::Bool(true));
        }
    }
    cut
}

fn halve_longest_string(v: &mut Value) -> bool {
    fn find<'a>(v: &'a mut Value, best: &mut Option<&'a mut String>) {
        match v {
            Value::String(s) => {
                if s.len() > 40 && best.as_ref().is_none_or(|b| s.len() > b.len()) {
                    *best = Some(s);
                }
            }
            Value::Array(a) => a.iter_mut().for_each(|x| find(x, best)),
            Value::Object(o) => o.values_mut().for_each(|x| find(x, best)),
            _ => {}
        }
    }
    let mut best = None;
    find(v, &mut best);
    match best {
        Some(s) => {
            let keep: String = s.chars().take(s.chars().count() / 2).collect();
            *s = format!("{keep}…");
            true
        }
        None => false,
    }
}

/// The journal of what was sent, next to the settings file.
pub fn journal_path() -> Option<PathBuf> {
    Some(
        crate::settings_file::state_file()?
            .parent()?
            .join("ai-sent.log"),
    )
}

/// Appends one request (its provider, model and JSON body; never a key) to the journal.
pub fn log_sent(provider: &str, model: &str, body: &str) {
    let Some(p) = journal_path() else { return };
    if let Some(d) = p.parent() {
        let _ = std::fs::create_dir_all(d);
    }
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let line =
        serde_json::json!({"time": secs, "provider": provider, "model": model, "sent": body});
    if let Ok(mut f) = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&p)
    {
        let _ = writeln!(f, "{line}");
    }
}

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

    #[test]
    fn secrets_are_hidden_and_counted() {
        let mut r = Redact::new(&Privacy::default());
        let t = r.text("GET /x?token=abcdef123456 user=bob@example.com\nAuthorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig");
        assert!(!t.contains("abcdef123456"), "{t}");
        assert!(!t.contains("bob@example.com"), "{t}");
        assert!(!t.contains("eyJhbGciOiJIUzI1NiJ9"), "{t}");
        assert!(r.hidden >= 3);
        assert_eq!(t.lines().count(), 2);
        let mut ips = Redact::new(&Privacy {
            ips: true,
            ..Privacy::default()
        });
        assert!(!ips.text("from 10.1.2.3").contains("10.1.2.3"));
        assert_eq!(Redact::none().text("token=abc"), "token=abc");
    }

    #[test]
    fn results_are_cut_to_fit() {
        let mut v = json!({"lines": 100, "first_lines": (0..20).map(|i| json!({"line": i, "text": "x".repeat(150)})).collect::<Vec<_>>()});
        assert!(fit(&mut v, 1000));
        assert!(serde_json::to_string(&v).unwrap().len() <= 1000);
        assert_eq!(v["lines"], 100);
        assert_eq!(v["cut_to_size_limit"], true);
        let mut small = json!({"lines": 3});
        assert!(!fit(&mut small, 1000));
        let mut long = json!({"text": "y".repeat(5000)});
        assert!(fit(&mut long, 600));
        assert!(serde_json::to_string(&long).unwrap().len() <= 600);
        assert_eq!(tokens(10), 3);
    }
}