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