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};
const GUIDED: bool = cfg!(feature = "guided");
pub(crate) const BUILTIN: &str = include_str!("route.js");
#[derive(Task)]
struct Route {
yes: bool,
#[arg(value = "<n>")]
max_tokens: Option<usize>,
#[arg(value = "<file.js>")]
script: Option<PathBuf>,
#[arg(value = "<file.wasm>")]
guest: Option<PathBuf>,
#[arg(positional)]
request: String,
}
#[derive(Task)]
#[task(name = "chat")]
struct Driver {
#[arg(value = "<n>")]
max_tokens: Option<usize>,
#[arg(value = "<file.js>")]
script: Option<PathBuf>,
#[arg(value = "<file.wasm>")]
guest: Option<PathBuf>,
yes: bool,
}
fn failed(e: impl std::fmt::Display) -> Stop {
Stop::Failed(e.to_string())
}
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
}
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
}
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 })
}
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 })
}
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
}
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);
}
}
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))
}
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),
})
}
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
}
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()],
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))
}
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
}
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)?))
}
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)
}
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(())
}
struct Session {
slot: Slot,
progress: Progress,
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(),
})
}
fn host(self) -> Host {
Rc::new(RefCell::new(move |name: &str, args: Value| {
self.call(name, args).map_err(|e| describe(&e))
}))
}
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}"))),
}
}
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_chat(&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
}
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))
}
}
fn text_arg(args: &Value) -> &str {
args.as_str()
.or_else(|| args.get("text").and_then(Value::as_str))
.unwrap_or_default()
}
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);
}
}
const ITEMS: usize = 8;
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(),
}
}
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}")])
}
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"))
}
#[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()))
}
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}"))),
}
}