tessera-command 0.5.5

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
//! `tesserax [--recipe <src>] [--model <dir | hf:<owner>/<name>[@<revision>]>] <verb>`.

mod check;
#[cfg(test)]
mod check_test;
mod fetch;
#[cfg(all(test, feature = "tern"))]
mod lib_test;
mod machine;
mod mcp;
#[cfg(test)]
mod mcp_test;
mod models;
#[cfg(test)]
mod models_test;
mod progress;
mod serve;
#[cfg(test)]
mod serve_test;
mod size;
mod source;
#[cfg(test)]
mod source_test;
mod surface;
#[cfg(test)]
mod surface_test;
mod task;
mod teleport;
#[cfg(test)]
mod teleport_test;
mod version;

use source::{Stop, split};
use std::process::ExitCode;
use tessera_frontend::serve::ranks::FLAGS as RANKS;
use tessera_frontend::serve::start::flags;
use tessera_frontend::tasks::task::Shown;

const USAGE: &str = "usage: tesserax [--recipe <dir | git+<url>#<commit> | kindling:<model>[:<backend>][:<N>x][@<ref>]>] [--model <dir | hf:<owner>/<name>[@<revision>]>] <verb>
  [--yes] [--max-tokens <n>] <prompt>...
                 answer one prompt. With no model flag, the default model may
                 pick a command for it instead, and asks first on a terminal.
                 Without a terminal it refuses unless --yes is given
  <command>      run one of the commands below
  task <task>    run one of the tasks below on the model
  models [--readme <path>]
                 print the model architectures and the tested weights. --readme
                 rewrites the Supported Models section of that file
  mcp            serve the commands and tasks as MCP tools on stdin and stdout
  size [--ctx <tokens>] [--slots <n>] [--boot]
                 print the memory the model needs and this machine has, as
                 JSON. --boot loads it and runs one step to measure
  check-kernels [--arch <sm_XX>] [--max-spills <bytes>] [--file <path>] [--json]
                 compile planned or standalone CUDA kernels offline with NVRTC and ptxas
  teleport [--from <dir>] [--root <dir>] <user@host | local>...
                 copy this build to other machines over ssh
  --version      print version, commit, target and GPU features
  --cli-json     print the commands, flags and words as JSON";

const HELP: &str = include_str!("../HELP.md");

/// Whether the command may draw Tern views.
#[cfg(feature = "tern")]
fn views(given: &[String]) -> bool {
    if given == ["--version"] || given == ["--cli-json"] {
        return false;
    }
    let Ok((_, args)) = split(given) else {
        return false;
    };
    let Some(verb) = args.first() else {
        return true;
    };
    !matches!(verb.as_str(), "mcp" | "-h" | "--help" | "help")
}

fn run(given: &[String]) -> Result<(), Stop> {
    if given.is_empty() {
        if !task::terminal().show(Shown::Markdown(HELP)) {
            print!("{HELP}");
        }
        return Ok(());
    }
    if given == ["--version"] {
        println!("{}", version::line());
        return Ok(());
    }
    if given == ["--cli-json"] {
        println!("{:#}", surface::json());
        return Ok(());
    }
    let (origin, args) = split(given)?;
    let Some((verb, rest)) = args.split_first() else {
        return Err(Stop::Usage);
    };
    match (verb.as_str(), task::find("", verb)) {
        // Words a command refuses may still be a prompt.
        (_, Some(command)) if origin.is_some() || (command.accepts)(rest) => {
            (command.call)(origin, rest, &mut *task::terminal())
        }
        ("task", _) => task::run(origin, rest),
        ("mcp", _) => mcp::run(origin, rest),
        ("models", _) => models::run(rest),
        ("teleport", _) => teleport::run(rest),
        ("size", _) => size::run(origin, rest),
        ("check-kernels", _) => check::run(origin, rest),
        ("-h" | "--help" | "help", _) => Err(Stop::Usage),
        // Other words are a prompt for the default model.
        _ if origin.is_none() => task::route(&args),
        _ => task::run(origin, &[&["ask".to_string()], args.as_slice()].concat()),
    }
}

/// Prints why a run stopped and gives its exit code.
fn finish(result: Result<(), Stop>) -> u8 {
    match result {
        Ok(()) => 0,
        Err(Stop::Usage) => {
            let default = source::default_model();
            eprintln!("{USAGE}\nwith neither flag, the model is {default}");
            eprintln!("{}", task::list());
            eprintln!("serve flags: {} {RANKS}", flags());
            2
        }
        Err(Stop::Tasks(message)) => {
            if let Some(message) = message {
                eprintln!("tesserax: {message}");
            }
            eprintln!("{}", task::list());
            2
        }
        Err(Stop::Failed(e)) => {
            let no_gpu = tessera_frontend::frontend_settings::no_gpu();
            if !task::terminal().show(Shown::Failed(&e, no_gpu.as_deref())) {
                eprintln!("tesserax: {e}");
                if let Some(no_gpu) = no_gpu {
                    eprintln!("tesserax: {no_gpu}");
                }
            }
            1
        }
    }
}

/// Runs the command line with the process arguments.
pub fn main() -> ExitCode {
    let given: Vec<String> = std::env::args().skip(1).collect();
    #[cfg(feature = "tern")]
    if views(&given)
        && let Some(ui) = tessera_tern::connect()
    {
        let work = given.clone();
        return match ui.run(move || finish(run(&work))) {
            tessera_tern::Ended::Done(code) => ExitCode::from(code),
            tessera_tern::Ended::Stopped => ExitCode::from(130),
        };
    }
    ExitCode::from(finish(run(&given)))
}