tessera-command 0.5.5

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
//! `task chat --script`: a chat loop in JavaScript.

use super::model;
use super::route::{Session, brief, example, find, schema, tools};
use crate::source::{Stop, kind};
use serde_json::{Value, json};
use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;
use tessera_frontend::chat::Message;
use tessera_frontend::script::{Guest, Host, Limits, Script};
use tessera_frontend::tasks::api::Format;
use tessera_frontend::tasks::task::Task;

/// Chat, with each turn run by a script.
#[derive(Task)]
#[task(name = "chat")]
struct Agent {
    /// The most tokens in each answer.
    #[arg(value = "<n>")]
    max_tokens: Option<usize>,
    /// The script that runs each turn.
    #[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())
}

pub fn chat(args: &[String]) -> Result<(), Stop> {
    let agent = Agent::parse(args, &|_| None).map_err(|_| Stop::Usage)?;
    let Some(path) = agent.script else {
        return Err(Stop::Usage);
    };
    let source = std::fs::read_to_string(&path).map_err(|e| failed(format!("{path:?}: {e}")))?;
    let guest = match agent.guest {
        Some(guest) => {
            let bytes = std::fs::read(&guest).map_err(|e| failed(format!("{guest:?}: {e}")))?;
            Guest::new(&bytes)
        }
        None => Guest::bundled(),
    };
    let guest = guest.map_err(failed)?;
    let session = Session::open(agent.max_tokens, agent.yes)?;
    let host: Host = Rc::new(RefCell::new(move |name: &str, args: Value| {
        call(&session, name, args).map_err(|e| match e {
            Stop::Failed(text) => text,
            other => format!("{other:?}"),
        })
    }));
    let name = path.display().to_string();
    let script = Script::with_host(&guest, &name, &source, Limits::default(), Some(host));
    let mut script = script.map_err(failed)?;
    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 script's `host(name, args)` calls.
fn call(session: &Session, name: &str, args: Value) -> Result<Value, Stop> {
    match name {
        "tasks" => Ok(catalog(session)),
        "generate" => generate(session, &args).map(Value::String),
        "run" => run(session, &args),
        "say" => {
            let text = args.get("text").and_then(Value::as_str).unwrap_or_default();
            println!("{text}");
            Ok(Value::Null)
        }
        _ => Err(failed(format!("no host function {name}"))),
    }
}

/// `tasks`: tools with examples, models, and the pick schema.
fn catalog(session: &Session) -> Value {
    let tools = tools(&session.catalog);
    let mut listed = Vec::new();
    for t in &tools {
        let (request, pick) = example(&session.catalog, t);
        listed.push(json!({
            "name": t.name,
            "about": t.about,
            "kind": t.kind,
            "args": (t.schema)(),
            "example": { "request": request, "pick": pick },
        }));
    }
    let mut models = Vec::new();
    for r in &session.catalog {
        models.push(json!({ "name": r.name, "kind": kind(r), "about": r.about }));
    }
    json!({ "tools": listed, "models": models, "pick": schema(&session.catalog, &tools) })
}

/// `generate`: messages, with an optional format, to answer text.
fn generate(session: &Session, 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") {
        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(session.max_tokens);
    let show = args.get("show").and_then(Value::as_bool).unwrap_or(false);
    let model = model(&session.slot);
    let text = model.render(&messages).map_err(failed)?;
    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)
}

/// `run`: a confirmed pick to its result. Servers are refused.
fn run(session: &Session, pick: &Value) -> Result<Value, Stop> {
    if Session::entry(pick)?.stays {
        return Err(failed("a script cannot start a task that keeps running"));
    }
    let token = session.token.as_deref();
    let args = super::route::argv(pick, &session.catalog, |w| find(w, token))?;
    let args = args.ok_or_else(|| failed("`reply` is no task"))?;
    Ok(session
        .execute(pick, &args)?
        .map_or(Value::Null, |r| brief(&r)))
}