tessera-command 0.5.8

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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! A prompt or chat turn driven by JavaScript.

use super::{ENTRIES, Entry, describe, entries, load, model};
use crate::source::{self, Source, Stop, kind};
use serde_json::{Map, Value, json};
use std::cell::RefCell;
use std::io::{BufRead, IsTerminal};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use tessera_frontend::chat::Message;
use tessera_engine::progress::{Progress, Scope, Unit};
use tessera_frontend::frontend_settings::{KNOBS, knob_var};
use tessera_frontend::recipe::{Catalog, Recipe};
use tessera_frontend::script::{Guest, Host, Limits, Script};
use tessera_frontend::serve::Slot;
use tessera_frontend::tasks::api::Format;
use tessera_frontend::tasks::task::{Collect, Sink, Task};

/// Whether this build can hold answers to a JSON schema.
const GUIDED: bool = cfg!(feature = "guided");

/// The built-in routing and chat loop driver.
pub(crate) const BUILTIN: &str = include_str!("route.js");

/// Answer a prompt, or run the command the model picks.
#[derive(Task)]
struct Route {
    /// Run the picked command without asking.
    yes: bool,
    /// The most tokens in a reply.
    #[arg(value = "<n>")]
    max_tokens: Option<usize>,
    /// A JavaScript driver in place of the built-in one.
    #[arg(value = "<file.js>")]
    script: Option<PathBuf>,
    /// A QuickJS wasm guest in place of the bundled one.
    #[arg(value = "<file.wasm>")]
    guest: Option<PathBuf>,
    /// The request, from stdin if none.
    #[arg(positional)]
    request: String,
}

/// Interactive chat driven by the built-in or given JavaScript script.
#[derive(Task)]
#[task(name = "chat")]
struct Driver {
    /// The most tokens in each answer.
    #[arg(value = "<n>")]
    max_tokens: Option<usize>,
    /// A JavaScript driver in place of the built-in one.
    #[arg(value = "<file.js>")]
    script: Option<PathBuf>,
    /// A QuickJS wasm guest in place of the bundled one.
    #[arg(value = "<file.wasm>")]
    guest: Option<PathBuf>,
    /// Run the tasks the script picks without asking.
    yes: bool,
}

fn failed(e: impl std::fmt::Display) -> Stop {
    Stop::Failed(e.to_string())
}

/// Catalog names of `kind`, or every name.
fn names(catalog: &[Recipe], of: Option<&str>) -> Vec<String> {
    let mut out = Vec::new();
    for r in catalog {
        if of.is_none_or(|k| k == kind(r)) {
            out.push(r.name.clone());
        }
    }
    out
}

/// Entries with an example and a catalog model to run.
pub fn tools(catalog: &[Recipe]) -> Vec<&'static Entry> {
    let mut out = Vec::new();
    for e in entries() {
        if e.example.is_some() && (!e.source || !names(catalog, e.kind).is_empty()) {
            out.push(e);
        }
    }
    out
}

/// JSON for a reply, or a tool and its arguments.
pub fn schema(catalog: &[Recipe], tools: &[&Entry]) -> Value {
    let only = |word: &str| json!({ "enum": [word] });
    let mut branches = vec![json!({
        "type": "object",
        "properties": { "tool": only("reply") },
        "required": ["tool"],
        "additionalProperties": false,
    })];
    for t in tools {
        if !t.source {
            branches.push(branch(t, None));
            continue;
        }
        let words = json!({ "type": "string", "minLength": 2, "maxLength": 60 });
        let models = json!({ "enum": names(catalog, t.kind) });
        for (key, value) in [("model", models), ("hub", words)] {
            branches.push(branch(t, Some((key, value))));
        }
    }
    json!({ "anyOf": branches })
}

/// The optional `knobs` object, with a value pattern per knob.
fn knobs_schema() -> Value {
    let mut props = Map::new();
    for k in &KNOBS {
        props.insert(
            k.name.into(),
            json!({ "type": "string", "pattern": k.pattern }),
        );
    }
    json!({ "type": "object", "properties": props, "additionalProperties": false })
}

/// Tool `t` with its model, knobs and arguments.
fn branch(t: &Entry, model: Option<(&str, Value)>) -> Value {
    let mut schema = (t.schema)();
    let mut props = Map::new();
    props.insert("tool".into(), json!({ "enum": [t.name] }));
    let mut required = vec![json!("tool")];
    if let Some((key, model)) = model {
        props.insert(key.into(), model);
        required.push(json!(key));
    }
    props.insert("knobs".into(), knobs_schema());
    if let Value::Object(args) = schema["properties"].take() {
        props.extend(args);
    }
    if let Value::Array(args) = schema["required"].take() {
        required.extend(args);
    }
    schema["properties"] = Value::Object(props);
    schema["required"] = Value::Array(required);
    schema
}

/// `t`'s example request, and the pick it makes.
fn example(catalog: &[Recipe], t: &Entry) -> (String, Value) {
    let asked = t.example.unwrap_or_default();
    if !t.source {
        let mut pick = json!({ "tool": t.name });
        if let (Value::Object(fields), Value::Object(args)) = (&mut pick, (t.example_args)()) {
            fields.extend(args);
        }
        return (asked.into(), pick);
    }
    let mut models: Vec<&Recipe> = Vec::new();
    for r in catalog {
        if t.kind.is_none_or(|k| k == kind(r)) {
            models.push(r);
        }
    }
    // A request by kind names the last model.
    let by_kind = asked.contains("{kind}");
    let recipe = if by_kind {
        models.last()
    } else {
        models.first()
    };
    let Some(recipe) = recipe else {
        return (asked.into(), json!({ "tool": "reply" }));
    };
    let model = recipe.name.clone();
    let mut pick = Map::new();
    pick.insert("tool".into(), t.name.into());
    pick.insert("model".into(), model.clone().into());
    if let Value::Object(args) = (t.example_args)() {
        pick.extend(args);
    }
    let asked = asked.replace("{kind}", kind(recipe));
    (asked.replace("{model}", &model), Value::Object(pick))
}

/// The `tasks` payload exposed to the driver script.
pub(crate) fn tasks_payload(catalog: &[Recipe], known: &Catalog, guided: bool) -> Value {
    let tools = tools(catalog);
    let mut listed = Vec::new();
    for t in &tools {
        let (request, pick) = example(catalog, t);
        listed.push(json!({
            "name": t.name,
            "about": t.about,
            "kind": t.kind,
            "source": t.source,
            "stays": t.stays,
            "args": (t.schema)(),
            "example": { "request": request, "pick": pick },
        }));
    }
    let mut models = Vec::new();
    for r in catalog {
        models.push(json!({ "name": r.name, "kind": kind(r), "about": r.about }));
    }
    let mut families = Vec::new();
    for family in &known.families {
        if catalog.iter().all(|r| r.name != family.family) {
            families.push(json!({ "family": family.family, "aliases": family.aliases }));
        }
    }
    let mut knobs = Vec::new();
    for k in &KNOBS {
        knobs.push(json!({ "name": k.name, "about": k.about, "pattern": k.pattern }));
    }
    json!({
        "guided": guided,
        "tools": listed,
        "models": models,
        "families": families,
        "knobs": knobs,
        "pick": schema(catalog, &tools),
    })
}

/// The catalog model that words such as "image model" name.
fn by_kind<'a>(catalog: &'a [Recipe], words: &str) -> Option<&'a str> {
    if let Some(r) = catalog.iter().find(|r| r.name == words.trim()) {
        return Some(&r.name);
    }
    let mut named = Vec::new();
    for word in words.split_whitespace() {
        let word = word.to_lowercase();
        if !["a", "an", "the", "model", "models"].contains(&word.as_str()) {
            named.push(word);
        }
    }
    let [word] = named.as_slice() else {
        return None;
    };
    for r in catalog {
        let k = kind(r);
        if word.starts_with(k) || k.starts_with(word.as_str()) {
            return Some(&r.name);
        }
    }
    None
}

/// Arguments for `pick`, or `None` for a reply.
pub fn argv(
    pick: &Value,
    catalog: &[Recipe],
    find: impl Fn(&str) -> Result<Vec<String>, Stop>,
) -> Result<Option<Vec<String>>, Stop> {
    let field = |k: &str| pick.get(k).and_then(Value::as_str);
    let bad = || Stop::Failed(format!("the model picked {pick}"));
    let name = field("tool").ok_or_else(bad)?;
    if name == "reply" {
        return Ok(None);
    }
    let tool = ENTRIES
        .iter()
        .find(|t| t.name == name && t.example.is_some());
    let tool = tool.ok_or_else(bad)?;
    let mut out = match (field("model"), field("hub")) {
        _ if !tool.source => Vec::new(),
        (Some(model), _) if catalog.iter().any(|r| r.name == model) => {
            vec!["--recipe".to_string(), model.to_string()]
        }
        (_, Some(hub)) => match by_kind(catalog, hub) {
            Some(name) => vec!["--recipe".to_string(), name.to_string()],
            // `find` turns outside words into a Hub id.
            None => find(hub)?,
        },
        (Some(model), None) => find(model)?,
        _ => return Err(bad()),
    };
    out.extend(tool.words());
    let mut args = pick.as_object().cloned().unwrap_or_default();
    for key in ["tool", "model", "hub", "knobs"] {
        args.remove(key);
    }
    let args = (tool.tool_args)(&Value::Object(args));
    out.extend(args.map_err(|e| Stop::Failed(format!("the model picked {pick}: {e}")))?);
    Ok(Some(out))
}

/// The knobs in `pick`, as names and values.
pub fn knobs(pick: &Value) -> Vec<(String, String)> {
    let mut out = Vec::new();
    if let Some(Value::Object(set)) = pick.get("knobs") {
        for (name, value) in set {
            if let Some(value) = value.as_str() {
                out.push((name.clone(), value.to_string()));
            }
        }
    }
    out
}

/// Loads the built-in or user driver script with `host`.
fn open_script(
    script: Option<&Path>,
    guest: Option<&Path>,
    host: Host,
) -> Result<(String, Script), Stop> {
    let (name, source) = match script {
        Some(path) => {
            let text =
                std::fs::read_to_string(path).map_err(|e| failed(format!("{path:?}: {e}")))?;
            (path.display().to_string(), text)
        }
        None => ("route.js".into(), BUILTIN.into()),
    };
    let loaded = match guest {
        Some(path) => {
            let bytes = std::fs::read(path).map_err(|e| failed(format!("{path:?}: {e}")))?;
            Guest::new(&bytes).map_err(failed)?
        }
        None => Guest::shared().map_err(failed)?.clone(),
    };
    let script = Script::with_host(&loaded, &name, &source, Limits::default(), Some(host));
    Ok((name, script.map_err(failed)?))
}

/// Answers `words`, or runs the task the default model picks.
pub fn run(words: &[String]) -> Result<(), Stop> {
    let route = Route::parse(words, &|_| None).map_err(|_| Stop::Usage)?;
    let session = Session::open(route.max_tokens, route.yes)?;
    let (name, mut script) = open_script(
        route.script.as_deref(),
        route.guest.as_deref(),
        session.host(),
    )?;
    let entry = if script.has("oneshot") {
        "oneshot"
    } else if script.has("turn") {
        "turn"
    } else {
        return Err(failed(format!("{name} exports no `oneshot` or `turn`")));
    };
    let request = route.request.trim();
    script
        .call(entry, &json!({ "request": request }), &mut [])
        .map(|_| ())
        .map_err(failed)
}

/// `task chat` without a model flag. Turns may run tasks.
pub fn chat(args: &[String]) -> Result<(), Stop> {
    let driver = Driver::parse(args, &|_| None).map_err(|_| Stop::Usage)?;
    let session = Session::open(driver.max_tokens, driver.yes)?;
    let (name, mut script) = open_script(
        driver.script.as_deref(),
        driver.guest.as_deref(),
        session.host(),
    )?;
    if !script.has("turn") {
        return Err(failed(format!("{name} exports no function `turn`")));
    }
    let mut print = super::terminal();
    while let Some(line) = print.turn() {
        let line = line.trim();
        if line.is_empty() {
            break;
        }
        if let Err(e) = script.call("turn", &json!({ "request": line }), &mut []) {
            print.note(&e.to_string());
        }
    }
    Ok(())
}

/// The default model, progress sinks, and settings.
struct Session {
    slot: Slot,
    /// One sink for load, picks and kernel builds.
    progress: Progress,
    /// Where kernel builds nest while a command is picked.
    scope: Arc<Scope>,
    max_tokens: Option<usize>,
    yes: bool,
    token: Option<String>,
    catalog: Vec<Recipe>,
}

impl Session {
    fn open(max_tokens: Option<usize>, yes: bool) -> Result<Self, Stop> {
        let scope = Arc::new(Scope::default());
        let progress = super::terminal().progress().within(scope.clone());
        let source = Source::open_or_kind(None, None, progress.clone())?;
        let switches: &[String] = if GUIDED { &["--guided".into()] } else { &[] };
        let mut options = source.options(switches)?;
        options.slots = 1;
        options.warm = false;
        Ok(Session {
            slot: load(options)?,
            progress,
            scope,
            max_tokens,
            yes,
            token: source.token.clone(),
            catalog: source::catalog(),
        })
    }

    /// Host callback exposing `tasks`, `generate`, `run`, `replace`, `say`, `note`, `record`.
    fn host(self) -> Host {
        Rc::new(RefCell::new(move |name: &str, args: Value| {
            self.call(name, args).map_err(|e| describe(&e))
        }))
    }

    /// Dispatches one `host(name, args)` call from the script.
    fn call(&self, name: &str, args: Value) -> Result<Value, Stop> {
        match name {
            "tasks" => Ok(tasks_payload(&self.catalog, Catalog::current(), GUIDED)),
            "generate" => self.generate(&args).map(Value::String),
            "run" => self.run_task(&args, false),
            "replace" => self.run_task(&args, true),
            "say" => {
                super::terminal().text(text_arg(&args));
                Ok(Value::Null)
            }
            "note" => {
                super::terminal().note(text_arg(&args));
                Ok(Value::Null)
            }
            "record" => {
                super::terminal().record(args);
                Ok(Value::Null)
            }
            _ => Err(failed(format!("no host function {name}"))),
        }
    }

    /// `generate`: renders messages and streams or collects an answer.
    fn generate(&self, args: &Value) -> Result<String, Stop> {
        let messages = args.get("messages").cloned().unwrap_or_default();
        let messages: Vec<Message> = serde_json::from_value(messages).map_err(failed)?;
        let format = match args.get("format") {
            _ if !GUIDED => None,
            None | Some(Value::Null) => None,
            Some(Value::String(s)) if s == "object" => Some(Format::Object),
            Some(schema) => Some(Format::Schema(schema.clone())),
        };
        let max = args.get("max_tokens").and_then(Value::as_u64);
        let max = max.map(|m| m as usize).or(self.max_tokens);
        let show = args.get("show").and_then(Value::as_bool).unwrap_or(false);
        let step = args
            .get("step")
            .and_then(Value::as_str)
            .map(|label| self.progress.step(label, Unit::Items, None));
        if let Some(step) = &step {
            self.scope.enter(step);
        }
        let model = model(&self.slot);
        let rendered = model.render(&messages).map_err(failed);
        let out = rendered.and_then(|text| {
            let mut print = super::terminal();
            let mut each = |t: &str| {
                if show {
                    print.text(t);
                }
            };
            model.answer(&text, max, format, &mut each).map_err(failed)
        });
        if let Some(step) = step {
            self.scope.clear();
            if let Some(done) = args.get("done").and_then(Value::as_str) {
                step.rename(done);
            }
            step.finish();
        }
        out
    }

    /// Confirms and runs or replaces the picked command.
    fn run_task(&self, pick: &Value, allow_replace: bool) -> Result<Value, Stop> {
        let name = pick.get("tool").and_then(Value::as_str).unwrap_or_default();
        let entry = ENTRIES
            .iter()
            .find(|e| e.name == name)
            .ok_or_else(|| failed(format!("the model picked {pick}")))?;
        if entry.stays && !allow_replace {
            return Err(failed(format!(
                "task `{name}` keeps running: use host('replace', pick)"
            )));
        }
        let token = self.token.as_deref();
        let args = argv(pick, &self.catalog, |words| find(words, token))?;
        let args = args.ok_or_else(|| failed("`reply` is no task"))?;
        let knobs = knobs(pick);
        if !confirm(&knobs, &args, self.yes)? {
            return Ok(Value::Null);
        }
        if entry.stays || allow_replace {
            return replace(&knobs, &args).map(|()| Value::Bool(true));
        }
        let (origin, words) = source::split(&args)?;
        let rest = words.get(entry.words().len()..).unwrap_or_default();
        let mut out = Both {
            print: super::terminal(),
            collect: Collect::default(),
        };
        tessera_frontend::frontend_settings::knobs(&knobs).map_err(Stop::Failed)?;
        let called = (entry.call)(origin, rest, &mut out);
        tessera_frontend::frontend_settings::knobs(&[]).map_err(Stop::Failed)?;
        let result = match called {
            Ok(()) => out.collect.value(),
            Err(e) => json!({ "error": describe(&e) }),
        };
        Ok(brief(&result))
    }
}

/// Extracts string text from either `"..."` or `{ "text": "..." }`.
fn text_arg(args: &Value) -> &str {
    args.as_str()
        .or_else(|| args.get("text").and_then(Value::as_str))
        .unwrap_or_default()
}

/// Output for the person, also kept for the model.
struct Both {
    print: Box<dyn Sink>,
    collect: Collect,
}

impl Sink for Both {
    fn progress(&self) -> Progress {
        self.print.progress()
    }

    fn text(&mut self, piece: &str) {
        self.print.text(piece);
        self.collect.text(piece);
    }

    fn record(&mut self, record: Value) {
        self.print.record(record.clone());
        self.collect.record(record);
    }

    fn file(&mut self, path: &Path) {
        self.print.file(path);
        self.collect.file(path);
    }

    fn note(&mut self, text: &str) {
        self.print.note(text);
        self.collect.note(text);
    }
}

/// The most items of a list the model reads.
const ITEMS: usize = 8;

/// `value` with long lists cut to [`ITEMS`] and a count.
pub(crate) fn brief(value: &Value) -> Value {
    match value {
        Value::Array(items) if items.len() > ITEMS => {
            let mut out: Vec<Value> = items[..ITEMS].iter().map(brief).collect();
            let rest = items.len() - ITEMS;
            out.push(json!(format!("{rest} more, {} in all", items.len())));
            Value::Array(out)
        }
        Value::Array(items) => Value::Array(items.iter().map(brief).collect()),
        Value::Object(fields) => {
            let fields = fields.iter().map(|(k, v)| (k.clone(), brief(v)));
            Value::Object(fields.collect())
        }
        other => other.clone(),
    }
}

/// Model arguments for `words`: catalog family or Hub id.
fn find(words: &str, token: Option<&str>) -> Result<Vec<String>, Stop> {
    let words = words.trim();
    if !words.starts_with("hf:")
        && let Some(family) = Catalog::current().find(words)
    {
        let (pick, recipe) = source::choose(&family.family)?;
        let size = source::gb(pick.needs.bytes);
        let tested = match pick.tested.is_empty() {
            true => "no test on record".to_string(),
            false => format!("tested on {}", pick.tested.join(", ")),
        };
        super::terminal().note(&format!(
            "{words:?} is {} from the model catalog: {} ({size:.1} GB, {tested})",
            family.family,
            recipe.weights.hf.as_deref().unwrap_or_default(),
        ));
        return Ok(vec![
            "--recipe".into(),
            format!("{}{}", source::CATALOG_PREFIX, family.family),
        ]);
    }
    let words = words.trim_start_matches("hf:");
    if words.contains('/') && !words.contains(' ') {
        tessera_frontend::recipe::check_hf(words, token)?;
        return Ok(vec!["--model".into(), format!("hf:{words}")]);
    }
    let found = tessera_frontend::recipe::search_hf(words, token)?;
    let none = || {
        Stop::Failed(format!(
            "the Hugging Face search for {words:?} found nothing"
        ))
    };
    let id = found.ok_or_else(none)?;
    super::terminal().note(&format!(
        "{words:?} is {id} on Hugging Face, not in the model catalog (untested)"
    ));
    Ok(vec!["--model".into(), format!("hf:{id}")])
}

/// Shows the command. Asks on a terminal, fails without one.
fn confirm(knobs: &[(String, String)], args: &[String], yes: bool) -> Result<bool, Stop> {
    let quoted = |a: &String| match a.contains(' ') {
        true => format!("{a:?}"),
        false => a.clone(),
    };
    let mut shown: Vec<String> = knobs
        .iter()
        .map(|(k, v)| format!("{}={v}", knob_var(k)))
        .collect();
    shown.push("tesserax".into());
    shown.extend(args.iter().map(quoted));
    let command = shown.join(" ");
    if !yes && let Some(answer) = super::terminal().confirm(&command) {
        return Ok(answer);
    }
    super::terminal().note(&format!("the model picked `{command}`"));
    let stdin = std::io::stdin();
    if yes {
        return Ok(true);
    }
    if !stdin.is_terminal() {
        return Err(Stop::Failed(
            "no terminal to confirm the command, pass --yes to run it".into(),
        ));
    }
    eprint!("run it? [y/N] ");
    let mut line = String::new();
    stdin
        .lock()
        .read_line(&mut line)
        .map_err(|e| Stop::Failed(e.to_string()))?;
    Ok(matches!(line.trim(), "y" | "Y" | "yes"))
}

/// Replaces this process with tesserax `args` to free the model.
#[cfg(unix)]
fn replace(knobs: &[(String, String)], args: &[String]) -> Result<(), Stop> {
    use std::os::unix::process::CommandExt;
    super::leave();
    Err(Stop::Failed(command(knobs, args)?.exec().to_string()))
}

/// Tesserax with `args`, and `knobs` in its environment.
fn command(knobs: &[(String, String)], args: &[String]) -> Result<std::process::Command, Stop> {
    let exe = std::env::current_exe().map_err(|e| Stop::Failed(e.to_string()))?;
    let mut command = std::process::Command::new(exe);
    command.args(args);
    for (name, value) in knobs {
        command.env(knob_var(name), value);
    }
    Ok(command)
}

#[cfg(not(unix))]
fn replace(knobs: &[(String, String)], args: &[String]) -> Result<(), Stop> {
    let status = command(knobs, args)?.status();
    let status = status.map_err(|e| Stop::Failed(e.to_string()))?;
    match status.success() {
        true => Ok(()),
        false => Err(Stop::Failed(format!("the picked command failed: {status}"))),
    }
}