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