bctx 0.1.9

bctx CLI — intercept CLI commands and compress output for LLM coding agents
use anyhow::Result;
use forge::budget::estimator::TokenEstimator;
use forge::substrate::local::LocalSubstrate;
use forge::substrate::{Substrate, SubstrateCommand};
use std::sync::OnceLock;
use weave::lenses::LensContext;
use weave::mesh::registry::FilterMesh;
use weave::output::savings::SavesReport;
use weave::ReadMode;

static MESH: OnceLock<FilterMesh> = OnceLock::new();
fn mesh() -> &'static FilterMesh {
    MESH.get_or_init(|| {
        let root = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
        FilterMesh::default_mesh().with_project_recipes(&root)
    })
}

/// Returns true if BCTX_BYPASS=1 is set or a .bctx-bypass file exists in CWD or any parent.
fn bypass_active() -> bool {
    if std::env::var("BCTX_BYPASS").as_deref() == Ok("1") {
        return true;
    }
    let mut dir = std::env::current_dir().ok();
    while let Some(d) = dir {
        if d.join(".bctx-bypass").exists() {
            return true;
        }
        dir = d.parent().map(|p| p.to_path_buf());
    }
    false
}

/// Run with an explicit read mode override (used by `bctx read --mode`).
/// If the sole argument is an existing file path, reads and compresses the file directly
/// instead of executing it as a command.
pub fn handle_with_mode(args: Vec<String>, mode: ReadMode) -> Result<()> {
    if args.len() == 1 && std::path::Path::new(&args[0]).is_file() {
        // Auto on a direct file read has no FilterMesh command to match — use signatures
        // as the default since it gives the most useful compressed output for files.
        let file_mode = match mode {
            ReadMode::Auto => ReadMode::Signatures,
            other => other,
        };
        return handle_file(&args[0], file_mode);
    }
    handle_inner(args, Some(mode))
}

/// Read and compress a file, printing the compressed content to stdout.
fn handle_file(path: &str, mode: ReadMode) -> Result<()> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| anyhow::anyhow!("bctx read: cannot read '{path}': {e}"))?;
    let tokens_before = forge::budget::estimator::TokenEstimator::count_nonblocking(&content);
    let ctx = LensContext::new(4000);
    let output = mode.apply(&content, &ctx);
    print!("{}", output.content);
    if tokens_before > 0 {
        let savings_pct = if tokens_before > 0 {
            100.0 * (1.0 - output.tokens_after as f64 / tokens_before as f64)
        } else {
            0.0
        };
        eprintln!(
            "[bctx: {}{} tokens, {:.0}% saved]",
            tokens_before, output.tokens_after, savings_pct
        );
    }
    Ok(())
}

pub fn handle(args: Vec<String>) -> Result<()> {
    // Honour BCTX_MODE env var if set.
    let mode = std::env::var("BCTX_MODE")
        .ok()
        .and_then(|v| ReadMode::parse(&v));
    handle_inner(args, mode)
}

fn handle_inner(args: Vec<String>, mode_override: Option<ReadMode>) -> Result<()> {
    if args.is_empty() {
        anyhow::bail!("usage: bctx <command> [args...]");
    }

    let program = args[0].clone();
    let cmd_args: Vec<String> = args[1..].to_vec();

    let substrate = LocalSubstrate;
    let cmd = SubstrateCommand {
        program: program.clone(),
        args: cmd_args.clone(),
        working_dir: None,
        timeout_secs: 60,
        capture_stderr: true,
        env: Vec::new(),
    };

    let result = substrate.execute(cmd)?;
    let raw_stdout = String::from_utf8_lossy(&result.stdout).to_string();
    let raw_stderr = String::from_utf8_lossy(&result.stderr).to_string();

    // Bypass: passthrough raw output, no compression, no savings report, no cloud sync.
    if bypass_active() {
        print!("{raw_stdout}");
        if !raw_stderr.is_empty() {
            eprint!("{raw_stderr}");
        }
        std::process::exit(result.exit_code);
    }

    let exit_code = result.exit_code;
    let tokens_before = TokenEstimator::count_nonblocking(&raw_stdout);

    let ctx = LensContext::new(2000).with_exit_code(exit_code);

    let compressed_content = match &mode_override {
        // Full mode: bypass all lens processing.
        Some(ReadMode::Full) => raw_stdout.clone(),
        // Explicit mode override: apply its lens stack directly.
        Some(mode) => mode.apply(&raw_stdout, &ctx).content,
        // Auto (default): route through FilterMesh domain nodes.
        None => match mesh().find(&program, &cmd_args) {
            Some(node) => node.apply(&raw_stdout, &ctx).content,
            None => raw_stdout.clone(),
        },
    };

    let tokens_after = TokenEstimator::count_nonblocking(&compressed_content);
    print!("{compressed_content}");
    if !raw_stderr.is_empty() {
        eprint!("{raw_stderr}");
    }

    let mode_label = mode_override
        .as_ref()
        .map(|m| format!(" [{}]", m.name()))
        .unwrap_or_default();

    if tokens_before > 0 {
        let label = format!("{program}{mode_label}");
        let report = SavesReport::new(label.as_str(), tokens_before, tokens_after);
        eprintln!("{}", report.render_inline());

        // Send savings to cloud if logged in — join before exit so the thread completes
        if let Some(token) = cloud::client::auth::load_token() {
            let handle = cloud::client::sync::push_signals_bg(
                token.endpoint,
                token.access_token,
                tokens_after as i64,
                (tokens_before as i64 - tokens_after as i64).max(0),
                program.clone(),
            );
            let _ = handle.join();
        }
    }

    std::process::exit(result.exit_code);
}