use crate::progress::Notify;
use crate::source::{CATALOG, Origin, Stop, split};
use crate::task::{ENTRIES, Entry, describe};
use serde_json::{Map, Value, json};
use std::collections::BTreeMap;
use std::io::{BufRead, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::Arc;
use std::time::Duration;
use tessera_engine::progress::Progress;
use tessera_frontend::tasks::Error;
use tessera_frontend::tasks::task::{Chat, Collect, Run, Sink, Task};
const VERSIONS: [&str; 3] = ["2025-11-25", "2025-06-18", "2025-03-26"];
const PARSE: i64 = -32700;
const METHOD: i64 = -32601;
const PARAMS: i64 = -32602;
const ORIGIN: [(&str, &str); 2] = [("recipe", "--recipe"), ("model", "--model")];
#[derive(Task)]
#[task(name = "stop")]
pub(crate) struct Halt {
#[arg(positional)]
pub handle: String,
}
#[derive(Default)]
pub struct Servers {
running: BTreeMap<String, Child>,
started: u32,
}
impl Run<&mut Servers> for Halt {
fn run(self, servers: &mut Servers, sink: &mut dyn Sink) -> Result<(), Error> {
let unknown = || format!("{}: unknown handle", self.handle);
let mut child = servers.running.remove(&self.handle).ok_or_else(unknown)?;
let _ = child.kill();
let status = child.wait()?;
sink.record(json!({"handle": self.handle, "status": status.to_string()}));
Ok(())
}
}
impl Servers {
fn start(&mut self, flags: &[String], sink: &mut dyn Sink) -> Result<(), Error> {
self.started += 1;
let name = format!("tesserax-{}-{}.port", std::process::id(), self.started);
let temp = tessera_frontend::frontend_settings::read().temp;
let port_file = temp.ok_or("no directory for the port file")?.join(name);
let _ = std::fs::remove_file(&port_file);
let local = ["serve", "--host", "127.0.0.1", "--port", "0", "--port-file"];
let mut child = Command::new(std::env::current_exe()?)
.args(flags)
.args(local)
.arg(&port_file)
.stdin(Stdio::null())
.stdout(Stdio::null())
.spawn()?;
let port = match bound_port(&mut child, &port_file) {
Ok(port) => port,
Err(e) => {
let _ = child.kill();
let _ = child.wait();
return Err(e);
}
};
let handle = format!("serve-{}", child.id());
let url = format!("http://127.0.0.1:{port}");
self.running.insert(handle.clone(), child);
sink.record(json!({"handle": handle, "url": format!("{url}/v1")}));
let ready = format!("the model is ready when {url}/health answers 200");
sink.note(&format!(
"{ready}. Until then its body lists the load steps"
));
Ok(())
}
}
fn bound_port(child: &mut Child, port_file: &Path) -> Result<u16, Error> {
loop {
if let Ok(text) = std::fs::read_to_string(port_file) {
let _ = std::fs::remove_file(port_file);
let bad = || format!("{}: not a port: {text}", port_file.display());
return Ok(text.trim().parse().map_err(|_| bad())?);
}
if let Some(status) = child.try_wait()? {
return Err(format!("serve exited before it listened: {status}").into());
}
std::thread::sleep(Duration::from_millis(10));
}
}
impl Drop for Servers {
fn drop(&mut self) {
for child in self.running.values_mut() {
let _ = child.kill();
let _ = child.wait();
}
}
}
pub fn run(origin: Option<Origin>, rest: &[String]) -> Result<(), Stop> {
if origin.is_some() || !rest.is_empty() {
return Err(Stop::Usage);
}
let mut servers = Servers::default();
let mut out = std::io::stdout();
for line in std::io::stdin().lock().lines() {
let line = line.map_err(|e| Stop::Failed(e.to_string()))?;
if line.trim().is_empty() {
continue;
}
if let Some(reply) = answer(&mut servers, &line) {
let wrote = writeln!(out, "{reply}").and_then(|()| out.flush());
wrote.map_err(|e| Stop::Failed(e.to_string()))?;
}
}
Ok(())
}
pub fn answer(servers: &mut Servers, line: &str) -> Option<Value> {
let message: Value = match serde_json::from_str(line) {
Ok(message) => message,
Err(e) => return Some(failure(Value::Null, PARSE, &e.to_string())),
};
let id = message.get("id")?.clone();
let params = message.get("params").cloned().unwrap_or_else(|| json!({}));
let result = match message["method"].as_str().unwrap_or_default() {
"initialize" => Ok(initialize(¶ms)),
"ping" => Ok(json!({})),
"tools/list" => Ok(json!({"tools": tools()})),
"tools/call" => call(servers, ¶ms),
method => Err((METHOD, format!("unknown method {method}"))),
};
Some(match result {
Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
Err((code, text)) => failure(id, code, &text),
})
}
fn failure(id: Value, code: i64, text: &str) -> Value {
json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": text}})
}
fn initialize(params: &Value) -> Value {
let asked = params["protocolVersion"].as_str().unwrap_or_default();
let version = VERSIONS.into_iter().find(|v| *v == asked);
json!({
"protocolVersion": version.unwrap_or(VERSIONS[0]),
"capabilities": {"tools": {}},
"serverInfo": {"name": "tesserax", "version": env!("CARGO_PKG_VERSION")},
})
}
fn entries() -> impl Iterator<Item = &'static Entry> {
ENTRIES.iter().filter(|e| e.name != Chat::NAME)
}
pub fn tools() -> Vec<Value> {
let names: Vec<&str> = CATALOG.iter().map(|(name, _)| *name).collect();
let recipe = format!(
"A recipe: a catalog name ({}), a directory or git+<url>#<commit>",
names.join(", ")
);
let about = [
recipe,
"A model directory or hf:<owner>/<name>[@<revision>]".into(),
];
let mut out = Vec::new();
for e in entries() {
let mut schema = (e.schema)();
for ((key, _), about) in ORIGIN.iter().zip(&about) {
if e.source {
schema["properties"][key] = json!({"type": "string", "description": about});
}
}
out.push(json!({"name": e.name, "description": e.about, "inputSchema": schema}));
}
out.push(
json!({"name": Halt::NAME, "description": Halt::ABOUT, "inputSchema": Halt::schema()}),
);
out
}
struct Tool {
out: Collect,
token: Option<Value>,
}
impl Sink for Tool {
fn text(&mut self, piece: &str) {
self.out.text(piece);
}
fn record(&mut self, record: Value) {
self.out.record(record);
}
fn file(&mut self, path: &Path) {
self.out.file(path);
}
fn note(&mut self, text: &str) {
self.out.note(text);
}
fn progress(&self) -> Progress {
match &self.token {
Some(token) => Progress::new(Arc::new(Notify::new(token.clone()))),
None => Progress::default(),
}
}
}
fn call(servers: &mut Servers, params: &Value) -> Result<Value, (i64, String)> {
let name = params["name"].as_str().unwrap_or_default();
let mut args = match params.get("arguments") {
Some(Value::Object(args)) => args.clone(),
_ => Map::new(),
};
let mut flags = Vec::new();
for (key, flag) in ORIGIN {
if let Some(value) = args.remove(key) {
flags.extend([flag.to_string(), value.as_str().unwrap_or_default().into()]);
}
}
let args = Value::Object(args);
let token = params["_meta"].get("progressToken").cloned();
let mut out = Tool {
out: Collect::default(),
token,
};
let ran = if name == Halt::NAME {
Halt::from_json(&args)
.map_err(|e| Stop::Failed(e.0))
.and_then(|halt| {
halt.run(servers, &mut out)
.map_err(|e| Stop::Failed(e.to_string()))
})
} else {
let unknown = || (PARAMS, format!("unknown tool {name}"));
let entry = entries().find(|e| e.name == name).ok_or_else(unknown)?;
run_entry(entry, servers, &flags, &args, &mut out)
};
Ok(match ran {
Ok(()) => result(&out.out),
Err(stop) => json!({"content": [text(&describe(&stop))], "isError": true}),
})
}
fn run_entry(
entry: &Entry,
servers: &mut Servers,
flags: &[String],
args: &Value,
out: &mut Tool,
) -> Result<(), Stop> {
let words = (entry.tool_args)(args).map_err(|e| Stop::Failed(e.0))?;
let (origin, _) = split(flags)?;
if entry.stays {
return servers
.start(flags, out)
.map_err(|e| Stop::Failed(e.to_string()));
}
(entry.call)(origin, &words, out)
}
fn text(text: &str) -> Value {
json!({"type": "text", "text": text})
}
fn result(out: &Collect) -> Value {
let value = out.value();
let mut content = vec![text(&value.to_string())];
for file in out
.files
.iter()
.filter(|f| f.extension().is_some_and(|e| e == "png"))
{
if let Ok(bytes) = std::fs::read(file) {
let data = tessera_frontend::serve::base64(&bytes);
content.push(json!({"type": "image", "data": data, "mimeType": "image/png"}));
}
}
json!({"content": content, "structuredContent": value})
}