Skip to main content

tessera_command/
lib.rs

1//! `tesserax [--recipe <src>] [--model <dir | hf:<owner>/<name>[@<revision>]>] <verb>`.
2
3mod check;
4#[cfg(test)]
5mod check_test;
6mod fetch;
7#[cfg(all(test, feature = "tern"))]
8mod lib_test;
9mod machine;
10mod mcp;
11#[cfg(test)]
12mod mcp_test;
13mod models;
14#[cfg(test)]
15mod models_test;
16mod progress;
17mod serve;
18#[cfg(test)]
19mod serve_test;
20mod size;
21mod source;
22#[cfg(test)]
23mod source_test;
24mod surface;
25#[cfg(test)]
26mod surface_test;
27mod task;
28mod teleport;
29#[cfg(test)]
30mod teleport_test;
31mod version;
32
33use source::{Stop, split};
34use std::process::ExitCode;
35use tessera_frontend::serve::ranks::FLAGS as RANKS;
36use tessera_frontend::serve::start::flags;
37use tessera_frontend::tasks::task::Shown;
38
39const USAGE: &str = "usage: tesserax [--recipe <dir | git+<url>#<commit> | kindling:<model>[:<backend>][:<N>x][@<ref>]>] [--model <dir | hf:<owner>/<name>[@<revision>]>] <verb>
40  [--yes] [--max-tokens <n>] <prompt>...
41                 answer one prompt. With no model flag, the default model may
42                 pick a command for it instead, and asks first on a terminal.
43                 Without a terminal it refuses unless --yes is given
44  <command>      run one of the commands below
45  task <task>    run one of the tasks below on the model
46  models [--readme <path>]
47                 print the model architectures and the tested weights. --readme
48                 rewrites the Supported Models section of that file
49  mcp            serve the commands and tasks as MCP tools on stdin and stdout
50  size [--ctx <tokens>] [--slots <n>] [--boot]
51                 print the memory the model needs and this machine has, as
52                 JSON. --boot loads it and runs one step to measure
53  check-kernels [--arch <sm_XX>] [--max-spills <bytes>] [--file <path>] [--json]
54                 compile planned or standalone CUDA kernels offline with NVRTC and ptxas
55  teleport [--from <dir>] [--root <dir>] <user@host | local>...
56                 copy this build to other machines over ssh
57  --version      print version, commit, target and GPU features
58  --cli-json     print the commands, flags and words as JSON";
59
60const HELP: &str = include_str!("../HELP.md");
61
62/// Whether the command may draw Tern views.
63#[cfg(feature = "tern")]
64fn views(given: &[String]) -> bool {
65    if given == ["--version"] || given == ["--cli-json"] {
66        return false;
67    }
68    let Ok((_, args)) = split(given) else {
69        return false;
70    };
71    let Some(verb) = args.first() else {
72        return true;
73    };
74    !matches!(verb.as_str(), "mcp" | "-h" | "--help" | "help")
75}
76
77fn run(given: &[String]) -> Result<(), Stop> {
78    if given.is_empty() {
79        if !task::terminal().show(Shown::Markdown(HELP)) {
80            print!("{HELP}");
81        }
82        return Ok(());
83    }
84    if given == ["--version"] {
85        println!("{}", version::line());
86        return Ok(());
87    }
88    if given == ["--cli-json"] {
89        println!("{:#}", surface::json());
90        return Ok(());
91    }
92    let (origin, args) = split(given)?;
93    let Some((verb, rest)) = args.split_first() else {
94        return Err(Stop::Usage);
95    };
96    match (verb.as_str(), task::find("", verb)) {
97        // Words a command refuses may still be a prompt.
98        (_, Some(command)) if origin.is_some() || (command.accepts)(rest) => {
99            (command.call)(origin, rest, &mut *task::terminal())
100        }
101        ("task", _) => task::run(origin, rest),
102        ("mcp", _) => mcp::run(origin, rest),
103        ("models", _) => models::run(rest),
104        ("teleport", _) => teleport::run(rest),
105        ("size", _) => size::run(origin, rest),
106        ("check-kernels", _) => check::run(origin, rest),
107        ("-h" | "--help" | "help", _) => Err(Stop::Usage),
108        // Other words are a prompt for the default model.
109        _ if origin.is_none() => task::route(&args),
110        _ => task::run(origin, &[&["ask".to_string()], args.as_slice()].concat()),
111    }
112}
113
114/// Prints why a run stopped and gives its exit code.
115fn finish(result: Result<(), Stop>) -> u8 {
116    match result {
117        Ok(()) => 0,
118        Err(Stop::Usage) => {
119            let default = source::default_model();
120            eprintln!("{USAGE}\nwith neither flag, the model is {default}");
121            eprintln!("{}", task::list());
122            eprintln!("serve flags: {} {RANKS}", flags());
123            2
124        }
125        Err(Stop::Tasks(message)) => {
126            if let Some(message) = message {
127                eprintln!("tesserax: {message}");
128            }
129            eprintln!("{}", task::list());
130            2
131        }
132        Err(Stop::Failed(e)) => {
133            let no_gpu = tessera_frontend::frontend_settings::no_gpu();
134            if !task::terminal().show(Shown::Failed(&e, no_gpu.as_deref())) {
135                eprintln!("tesserax: {e}");
136                if let Some(no_gpu) = no_gpu {
137                    eprintln!("tesserax: {no_gpu}");
138                }
139            }
140            1
141        }
142    }
143}
144
145/// Runs the command line with the process arguments.
146pub fn main() -> ExitCode {
147    let given: Vec<String> = std::env::args().skip(1).collect();
148    #[cfg(feature = "tern")]
149    if views(&given)
150        && let Some(ui) = tessera_tern::connect()
151    {
152        let work = given.clone();
153        return match ui.run(move || finish(run(&work))) {
154            tessera_tern::Ended::Done(code) => ExitCode::from(code),
155            tessera_tern::Ended::Stopped => ExitCode::from(130),
156        };
157    }
158    ExitCode::from(finish(run(&given)))
159}