tessera-command 0.6.0

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Commands and tasks: one list for CLI and router.

mod route;
#[cfg(test)]
mod route_test;

pub use route::run as route;

use crate::source::{Origin, Source, Stop};
pub(crate) use scattered_collect::declarative::{gather, scatter};
use std::io::{BufRead, IsTerminal, Write};
use std::path::Path;
use tessera_engine::progress::Progress;
use tessera_frontend::serve::start::{self, Options};
use tessera_frontend::serve::{Model, Slot};
use tessera_frontend::tasks::task::{Ask, Chat, Embed, Field, Image, Run, Sink, Tag, Task, Usage, Value};
use tessera_frontend::tasks::{Error, Tagger};

/// The word before a task's name.
const TASK: &str = "task";

/// Runs an entry on an origin and words.
pub type Call = fn(Option<Origin>, &[String], &mut dyn Sink) -> Result<(), Stop>;

/// One command or task, for the CLI and the router.
pub struct Entry {
    /// [`TASK`] for a task, empty for a command.
    pub group: &'static str,
    pub name: &'static str,
    /// The catalog kind it runs on. `None` is any.
    pub kind: Option<&'static str>,
    pub about: &'static str,
    /// A request it answers. Only these go to the router.
    pub example: Option<&'static str>,
    pub schema: fn() -> Value,
    pub fields: &'static [Field],
    /// The arguments for `example`.
    pub example_args: fn() -> Value,
    /// A tool call's arguments as command-line words.
    pub tool_args: fn(&Value) -> Result<Vec<String>, Usage>,
    pub usage: fn() -> String,
    /// Whether the arguments parse. Commands read no stdin.
    pub accepts: fn(&[String]) -> bool,
    /// Runs with output to the sink.
    pub call: Call,
    /// Whether it keeps running, as a server does.
    pub stays: bool,
    /// Whether it opens a model, so takes `model` or `hub`.
    pub source: bool,
}

impl Entry {
    /// The command words, after the model flags.
    pub fn words(&self) -> Vec<String> {
        let words = [self.group, self.name]
            .into_iter()
            .filter(|w| !w.is_empty());
        words.map(String::from).collect()
    }
}

pub(crate) const fn entry<T: Task, O: Target<T>>(group: &'static str, stays: bool) -> Entry {
    Entry {
        group,
        name: T::NAME,
        kind: T::KIND,
        about: T::ABOUT,
        example: T::EXAMPLE,
        schema: T::schema,
        fields: T::FIELDS,
        example_args: T::example,
        tool_args: T::tool_args,
        usage: usage::<T, O>,
        accepts: accepts::<T, O>,
        call: call_entry::<T, O>,
        stays,
        source: O::SOURCE,
    }
}

gather! {
    /// Every command and task entry registered in this CLI.
    #[gather]
    pub static ENTRIES: scattered_collect::ScatteredSlice<Entry>;
}

/// Registers a command or task entry.
macro_rules! register {
    ($task:ty, $target:ty, $group:expr, $stays:expr) => {
        const _: () = {
            $crate::task::scatter! {
                #[scatter($crate::task::ENTRIES)]
                static ENTRY: $crate::task::Entry =
                    $crate::task::entry::<$task, $target>($group, $stays);
            }
        };
    };
}
pub(crate) use register;

register!(Ask, OnModel<false>, TASK, false);
register!(Chat, OnModel<true>, TASK, false);
register!(Embed, OnModel<false>, TASK, false);
register!(Image, OnModel<false>, TASK, false);
register!(Tag, OnTagger, TASK, false);

/// Commands first, then tasks, in deterministic order.
pub fn entries() -> Vec<&'static Entry> {
    let mut out: Vec<&'static Entry> = ENTRIES.iter().collect();
    out.sort_by_key(|e| (e.group, !e.stays, e.name));
    out
}

/// The entry that `group` and `name` name.
pub fn find(group: &str, name: &str) -> Option<&'static Entry> {
    ENTRIES.iter().find(|e| e.group == group && e.name == name)
}

/// A task's run target, and how the CLI opens one.
pub(crate) trait Target<T: Task> {
    /// Whether it opens a recipe or model.
    const SOURCE: bool = true;
    /// Whether extra `flag` takes a value. `None` refuses the flag.
    fn takes(flag: &str) -> Option<bool>;
    /// The extra flags' usage.
    fn extra() -> String;
    fn run(task: T, source: Source, sink: &mut dyn Sink) -> Result<(), Error>;
    /// Opens the source for `origin`, then runs.
    fn call(task: T, origin: Option<Origin>, sink: &mut dyn Sink) -> Result<(), Stop> {
        let source = Source::open_or_kind(origin, T::KIND, sink.progress())?;
        Self::run(task, source, sink).map_err(stop)
    }
}

/// A model the loader fills. `WARM` warms plans.
struct OnModel<const WARM: bool>;

impl<const WARM: bool, T: Task + for<'a> Run<&'a Model>> Target<T> for OnModel<WARM> {
    fn takes(flag: &str) -> Option<bool> {
        let owned = tessera_frontend::serve::task::flags_of(T::KIND?);
        owned
            .iter()
            .find(|f| f.name == flag)
            .map(|f| !f.value.is_empty())
    }

    fn extra() -> String {
        let mut out = Vec::new();
        for flag in tessera_frontend::serve::task::flags_of(T::KIND.unwrap_or_default()) {
            if !T::FIELDS.iter().any(|f| f.flag == flag.name) {
                out.push(flag.usage());
            }
        }
        out.join(" ")
    }

    fn run(task: T, source: Source, sink: &mut dyn Sink) -> Result<(), Error> {
        let mut options = source.options(&task.load_flags())?;
        if let Some(kind) = T::KIND {
            options.flag("--task", kind.into()).ok_or(Stop::Usage)?;
        }
        options.slots = 1;
        options.warm = WARM;
        let slot = load(options)?;
        task.run(model(&slot), sink)
    }
}

/// A tagger opened from the model's files.
struct OnTagger;

impl<T: Task + for<'a> Run<&'a mut Tagger>> Target<T> for OnTagger {
    fn takes(_: &str) -> Option<bool> {
        None
    }

    fn extra() -> String {
        String::new()
    }

    fn run(task: T, source: Source, sink: &mut dyn Sink) -> Result<(), Error> {
        let options = source.options(&[])?;
        let settings = tessera_frontend::frontend_settings::read();
        let mut tagger = Tagger::open(&options.model, &settings)?;
        task.run(&mut tagger, sink)
    }
}

/// No model, for commands about this machine.
pub(crate) struct OnMachine;

impl<T: Task + Run<()>> Target<T> for OnMachine {
    const SOURCE: bool = false;

    fn takes(_: &str) -> Option<bool> {
        None
    }

    fn extra() -> String {
        String::new()
    }

    fn run(task: T, _: Source, sink: &mut dyn Sink) -> Result<(), Error> {
        task.run((), sink)
    }

    fn call(task: T, _: Option<Origin>, sink: &mut dyn Sink) -> Result<(), Stop> {
        task.run((), sink).map_err(stop)
    }
}

fn serve_takes(flag: &str) -> Option<bool> {
    // `--also` starts the next model's flags.
    Some(flag != "--also" && !Options::default().switch(flag))
}

/// The opened recipe or model, for commands.
pub(crate) struct OnSource;

impl<T: Task + Run<Source>> Target<T> for OnSource {
    fn takes(flag: &str) -> Option<bool> {
        serve_takes(flag)
    }

    fn extra() -> String {
        "[flags]".into()
    }

    fn run(task: T, source: Source, sink: &mut dyn Sink) -> Result<(), Error> {
        task.run(source, sink)
    }
}

/// The optional recipe or model origin, without opening weights.
pub(crate) struct OnOrigin<const EXTRA: bool = false>;

impl<const EXTRA: bool, T: Task + Run<Option<Origin>>> Target<T> for OnOrigin<EXTRA> {
    fn takes(flag: &str) -> Option<bool> {
        if EXTRA { serve_takes(flag) } else { None }
    }

    fn extra() -> String {
        if EXTRA {
            "[flags]".into()
        } else {
            String::new()
        }
    }

    fn run(_: T, _: Source, _: &mut dyn Sink) -> Result<(), Error> {
        unreachable!("OnOrigin invokes run directly")
    }

    fn call(task: T, origin: Option<Origin>, sink: &mut dyn Sink) -> Result<(), Stop> {
        task.run(origin, sink).map_err(stop)
    }
}

fn usage<T: Task, O: Target<T>>() -> String {
    T::usage(&O::extra())
}

fn accepts<T: Task, O: Target<T>>(args: &[String]) -> bool {
    T::parse(args, &O::takes).is_ok()
}

fn call_entry<T: Task, O: Target<T>>(
    origin: Option<Origin>,
    args: &[String],
    sink: &mut dyn Sink,
) -> Result<(), Stop> {
    let task = T::parse(args, &O::takes);
    let task = task.map_err(|e| Stop::Tasks(Some(format!("{}: {e}", T::NAME))))?;
    O::call(task, origin, sink)
}

/// A task's error as a `Stop`.
fn stop(e: Error) -> Stop {
    let e = match e.downcast::<Stop>() {
        Ok(stop) => return *stop,
        Err(e) => e,
    };
    match e.downcast::<Usage>() {
        Ok(usage) => Stop::Tasks(Some(usage.0)),
        Err(e) => Stop::Failed(e.to_string()),
    }
}

/// A stop as words for the person or the model.
pub fn describe(stop: &Stop) -> String {
    match stop {
        Stop::Failed(why) | Stop::Tasks(Some(why)) => why.clone(),
        _ => "the task refused its arguments".into(),
    }
}

/// Every command and task: its usage and what it does.
pub fn list() -> String {
    let mut out = String::from("commands and tasks:");
    for e in entries() {
        let mut words = e.words();
        words.pop();
        words.push((e.usage)());
        let usage = words.join(" ");
        match usage.len() < 36 {
            true => out += &format!("\n  {usage:<36}{}", e.about),
            false => out += &format!("\n  {usage}\n  {:<36}{}", "", e.about),
        }
    }
    out
}

pub fn run(origin: Option<Origin>, rest: &[String]) -> Result<(), Stop> {
    let Some((name, args)) = rest.split_first() else {
        return Err(Stop::Tasks(None));
    };
    let unknown = || Stop::Tasks(Some(format!("unknown task {name}")));
    let entry = find(TASK, name).ok_or_else(unknown)?;
    // Chat without a model flag may run tasks each turn.
    if origin.is_none() && name == Chat::NAME {
        return route::chat(args);
    }
    (entry.call)(origin, args, &mut *terminal())
}

/// The sink for this process's terminal.
pub(crate) fn terminal() -> Box<dyn Sink> {
    #[cfg(feature = "tern")]
    if let Some(tern) = tessera_tern::sink() {
        return Box::new(tern);
    }
    Box::new(Print::default())
}

/// Closes the terminal's views before the process is replaced.
pub(crate) fn leave() {
    #[cfg(feature = "tern")]
    tessera_tern::leave();
}

/// Starts the load and waits for the model.
pub(crate) fn load(options: Options) -> Result<Slot, Stop> {
    start::open(options).map_err(Stop::Failed)
}

pub(crate) fn model(slot: &Slot) -> &Model {
    slot.get().expect("the model loaded")
}

/// Prints text as it comes, and results a line each.
#[derive(Default)]
pub(crate) struct Print {
    /// Text ended without a newline.
    open: bool,
}

impl Print {
    fn end_line(&mut self) {
        if std::mem::take(&mut self.open) {
            println!();
        }
    }
}

impl Sink for Print {
    fn text(&mut self, piece: &str) {
        let mut out = std::io::stdout();
        let _ = write!(out, "{piece}");
        let _ = out.flush();
        if !piece.is_empty() {
            self.open = !piece.ends_with('\n');
        }
    }

    fn record(&mut self, record: Value) {
        self.end_line();
        println!("{record}");
    }

    fn file(&mut self, path: &Path) {
        self.end_line();
        println!("{}", path.display());
    }

    fn note(&mut self, text: &str) {
        self.end_line();
        eprintln!("tesserax: {text}");
    }

    fn turn(&mut self) -> Option<String> {
        self.end_line();
        let stdin = std::io::stdin();
        if stdin.is_terminal() {
            eprint!("> ");
            let _ = std::io::stderr().flush();
        }
        let mut line = String::new();
        match stdin.lock().read_line(&mut line) {
            Ok(n) if n > 0 => Some(line),
            _ => None,
        }
    }

    fn progress(&self) -> Progress {
        crate::progress::stderr()
    }

    fn passthrough(&self) -> bool {
        true
    }
}

impl Drop for Print {
    fn drop(&mut self) {
        self.end_line();
    }
}