tessera-command 0.6.0

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
use super::route::{BUILTIN, argv, brief, knobs, schema, tasks_payload, tools};
use crate::source::{Origin, builtins, catalog, split};
use serde_json::{Value, json};
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
use tessera_frontend::recipe::Catalog;
use tessera_frontend::script::{Guest, Host, Limits, Script};

/// Tools come from the entry list, and picks become commands.
#[test]
fn picks_become_commands() {
    let catalog = catalog();
    assert_eq!(catalog.len(), builtins().len());
    let tools = tools(&catalog);
    let names: Vec<&str> = tools.iter().map(|t| t.name).collect();
    assert_eq!(names, ["serve", "fetch", "machine", "embed", "image"]);
    let branches = schema(&catalog, &tools)["anyOf"].as_array().map(Vec::len);
    assert_eq!(branches, Some(2 * tools.len()));
    let image = json!({ "tool": "image", "model": "flux2-klein", "prompt": "a fox", "n": 2 });
    let found = |words: &str| {
        let id = format!("hf:found/{}", words.replace(' ', "-"));
        Ok(vec!["--model".to_string(), id])
    };
    let args = argv(&image, &catalog, found)
        .ok()
        .flatten()
        .unwrap_or_default();
    assert_eq!(
        args,
        [
            "--recipe",
            "flux2-klein",
            "task",
            "image",
            "--n",
            "2",
            "a fox"
        ]
    );
    let origin = split(&args).ok().and_then(|(origin, _)| origin);
    assert!(matches!(origin, Some(Origin::Builtin("flux2-klein"))));
    let hub = json!({ "tool": "serve", "hub": "qwen 27b", "knobs": { "profile": "1" } });
    assert_eq!(knobs(&hub), [("profile".to_string(), "1".to_string())]);
    let args = argv(&hub, &catalog, found)
        .ok()
        .flatten()
        .unwrap_or_default();
    assert_eq!(args, ["--model", "hf:found/qwen-27b", "serve"]);
    let kind = json!({ "tool": "fetch", "hub": "the image model" });
    assert_eq!(
        argv(&kind, &catalog, found)
            .ok()
            .flatten()
            .unwrap_or_default(),
        ["--recipe", "flux2-klein", "fetch"]
    );
    let machine = argv(&json!({ "tool": "machine" }), &catalog, found);
    assert_eq!(machine.ok().flatten().unwrap_or_default(), ["machine"]);
    assert!(matches!(
        argv(&json!({ "tool": "reply" }), &catalog, found),
        Ok(None)
    ));
    let vector = json!({ "records": [{ "embedding": vec![0.5; 768] }] });
    let cut = brief(&vector)["records"][0]["embedding"].clone();
    assert_eq!(cut.as_array().map(Vec::len), Some(9));
    assert_eq!(cut[8], json!("760 more, 768 in all"));
}

/// Built-in recipes match the embedded catalog.
#[test]
fn builtins_match_the_catalog() {
    let known = Catalog::embedded().unwrap();
    for recipe in catalog() {
        let family = known.find(&recipe.name).unwrap();
        let pick = &family.picks[0].recipe().unwrap();
        assert_eq!(pick.weights, recipe.weights, "{}", recipe.name);
        assert_eq!(pick.serve, recipe.serve, "{}", recipe.name);
        assert_eq!(pick.config, recipe.config, "{}", recipe.name);
    }
}

/// Runs the embedded `route.js` against scripted host replies.
#[test]
fn driver_runs_tasks() {
    let tasks = tasks_payload(&catalog(), &Catalog::embedded().unwrap(), true);
    let replies = Rc::new(RefCell::new(VecDeque::from([
        json!(r#"{"tool":"machine"}"#),
        json!(r#"{"tool":"reply"}"#),
        json!("This box has an M4."),
        json!(r#"{"tool":"serve","hub":"qwen 27b"}"#),
    ])));
    let calls = Rc::new(RefCell::new(Vec::<(String, Value)>::new()));
    let (r, c) = (replies.clone(), calls.clone());
    let host: Host = Rc::new(RefCell::new(move |name: &str, args: Value| {
        c.borrow_mut().push((name.into(), args.clone()));
        match name {
            "tasks" => Ok(tasks.clone()),
            "generate" => Ok(r.borrow_mut().pop_front().unwrap()),
            "run" => Ok(json!({ "chip": "M4" })),
            "replace" => Ok(Value::Bool(true)),
            _ => Err(format!("unexpected {name}")),
        }
    }));
    let guest = Guest::shared().unwrap();
    let mut script =
        Script::with_host(guest, "route.js", BUILTIN, Limits::default(), Some(host)).unwrap();
    script
        .call("turn", &json!({ "request": "what hardware?" }), &mut [])
        .unwrap();
    script
        .call("oneshot", &json!({ "request": "serve qwen 27b" }), &mut [])
        .unwrap();
    let log = calls.borrow();
    let names: Vec<&str> = log.iter().map(|(n, _)| n.as_str()).collect();
    assert_eq!(
        names,
        [
            "tasks", "generate", "run", "generate", "generate", "tasks", "generate", "replace"
        ]
    );
    let prompt = log[1].1["messages"][0]["content"].as_str().unwrap();
    assert!(prompt.ends_with("Request: what hardware?\n"));
    assert_eq!(log[4].1["show"], json!(true));
    assert_eq!(log[7].1["tool"], json!("serve"));
}