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)
})
}
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
}
pub fn handle_with_mode(args: Vec<String>, mode: ReadMode) -> Result<()> {
let (effective_mode, clean_args) = extract_trailing_mode(args, mode);
if clean_args.len() == 1 && std::path::Path::new(&clean_args[0]).is_file() {
let file_mode = match effective_mode {
ReadMode::Auto => ReadMode::Signatures,
other => other,
};
return handle_file(&clean_args[0], file_mode);
}
handle_inner(clean_args, Some(effective_mode))
}
fn extract_trailing_mode(mut args: Vec<String>, existing: ReadMode) -> (ReadMode, Vec<String>) {
let mut mode = existing;
let _ = &mode; let mut i = 0;
while i < args.len() {
if args[i] == "--mode" && i + 1 < args.len() {
let val = args.remove(i + 1);
args.remove(i);
if matches!(mode, ReadMode::Auto) {
mode = ReadMode::parse(&val).unwrap_or(ReadMode::Auto);
}
} else if let Some(val) = args[i].strip_prefix("--mode=") {
let val = val.to_string();
args.remove(i);
if matches!(mode, ReadMode::Auto) {
mode = ReadMode::parse(&val).unwrap_or(ReadMode::Auto);
}
} else {
i += 1;
}
}
(mode, args)
}
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<()> {
let mode = std::env::var("BCTX_MODE")
.ok()
.and_then(|v| ReadMode::parse(&v));
let args = match args.first().map(String::as_str) {
Some("run") => args[1..].to_vec(),
_ => args,
};
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();
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 {
Some(ReadMode::Full) => raw_stdout.clone(),
Some(mode) => mode.apply(&raw_stdout, &ctx).content,
None => mesh().apply(&program, &cmd_args, &raw_stdout, &ctx).content,
};
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());
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);
}