#[cfg(test)]
mod tune_test;
use crate::source::{Origin, Source, Stop};
use serde_json::{Map, Value, json};
use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::thread::sleep;
use std::time::Duration;
use tessera_frontend::script::{Guest, Host, Limits, Script};
use tessera_frontend::serve::Slot;
use tessera_frontend::tasks::task::Sink;
pub(crate) const BUILTIN: &str = include_str!("tune.js");
const POLL: Duration = Duration::from_millis(20);
pub(crate) struct Args {
pub script: Option<PathBuf>,
pub guest: Option<PathBuf>,
pub url: Option<String>,
pub profile_only: bool,
pub prompt_tokens: usize,
pub tokens: usize,
pub streams: usize,
pub knobs: Vec<String>,
pub max_trials: Option<usize>,
pub abba: bool,
pub output: Option<PathBuf>,
pub json: bool,
pub extra: Map<String, Value>,
pub serve: Vec<String>,
}
impl Default for Args {
fn default() -> Self {
Self {
script: None,
guest: None,
url: None,
profile_only: false,
prompt_tokens: 128,
tokens: 32,
streams: 1,
knobs: Vec::new(),
max_trials: None,
abba: true,
output: None,
json: false,
extra: Map::new(),
serve: Vec::new(),
}
}
}
pub(crate) trait Backend {
fn schema(&self) -> Result<Value, String>;
fn recipe(&self) -> Result<Value, String>;
fn explain(&self, ask: &Value) -> Result<Value, String>;
fn apply(&self, ask: &Value) -> Result<Value, String>;
fn measure(&self, ask: &Value) -> Result<Value, String>;
}
pub(crate) fn parse(rest: &[String]) -> Result<Args, Stop> {
let mut out = Args::default();
let mut it = rest.iter();
while let Some(arg) = it.next() {
match arg.as_str() {
"--script" => out.script = Some(PathBuf::from(next_val(&mut it, arg)?)),
"--guest" => out.guest = Some(PathBuf::from(next_val(&mut it, arg)?)),
"--url" => out.url = Some(next_val(&mut it, arg)?.clone()),
"--profile-only" => out.profile_only = true,
"--prompt-tokens" => out.prompt_tokens = parse_usize(next_val(&mut it, arg)?, arg)?,
"--tokens" => out.tokens = parse_usize(next_val(&mut it, arg)?, arg)?,
"--streams" => out.streams = parse_usize(next_val(&mut it, arg)?, arg)?,
"--max-trials" => out.max_trials = Some(parse_usize(next_val(&mut it, arg)?, arg)?),
"--no-abba" => out.abba = false,
"--abba" => out.abba = true,
"--output" => out.output = Some(PathBuf::from(next_val(&mut it, arg)?)),
"--json" => out.json = true,
"--knobs" => {
for item in next_val(&mut it, arg)?.split(',') {
let trimmed = item.trim();
if !trimmed.is_empty() {
out.knobs.push(trimmed.into());
}
}
}
"--arg" => {
let raw = next_val(&mut it, arg)?;
let Some((k, v)) = raw.split_once('=') else {
return Err(Stop::Failed(format!("invalid --arg {raw:?}: want key=val")));
};
let parsed = serde_json::from_str(v).unwrap_or_else(|_| Value::String(v.into()));
out.extra.insert(k.into(), parsed);
}
"-h" | "--help" => return Err(Stop::Usage),
_ => out.serve.push(arg.clone()),
}
}
if out.prompt_tokens == 0 || out.tokens == 0 || out.streams == 0 {
return Err(Stop::Failed(
"--prompt-tokens, --tokens, and --streams must be at least 1".into(),
));
}
Ok(out)
}
fn next_val<'a>(it: &mut std::slice::Iter<'a, String>, flag: &str) -> Result<&'a String, Stop> {
it.next()
.ok_or_else(|| Stop::Failed(format!("{flag} requires a value")))
}
fn parse_usize(raw: &str, flag: &str) -> Result<usize, Stop> {
raw.parse::<usize>()
.map_err(|_| Stop::Failed(format!("invalid {flag} {raw:?}")))
}
pub fn run(origin: Option<Origin>, rest: &[String]) -> Result<(), Stop> {
let args = parse(rest)?;
let (name, source) = load_source(args.script.as_deref())?;
let guest = load_guest(args.guest.as_deref())?;
let config = script_config(&args);
let sink = Rc::new(RefCell::new(crate::task::terminal()));
let result = match &args.url {
Some(url) => {
if !args.serve.is_empty() {
return Err(Stop::Failed(format!(
"unexpected flags with --url: {}",
args.serve.join(" ")
)));
}
let backend: Rc<dyn Backend> = Rc::new(RemoteBackend::new(url));
drive(
&guest,
&name,
&source,
&config,
backend,
args.output.as_deref(),
sink,
)?
}
None => {
let progress = sink.borrow().progress();
let src = Source::open_or_kind(origin, Some("generate"), progress)?;
let mut options = src.options(&args.serve)?;
options.flag("--tune", String::new());
options.slots = options.slots.max(args.streams);
let slot = crate::task::load(options)?;
let backend: Rc<dyn Backend> = Rc::new(LocalBackend(slot));
drive(
&guest,
&name,
&source,
&config,
backend,
args.output.as_deref(),
sink,
)?
}
};
if args.json {
println!(
"{}",
serde_json::to_string_pretty(&result).unwrap_or_default()
);
}
Ok(())
}
pub(crate) fn script_config(args: &Args) -> Value {
json!({
"profile_only": args.profile_only,
"prompt_tokens": args.prompt_tokens,
"tokens": args.tokens,
"streams": args.streams,
"knobs": args.knobs,
"max_trials": args.max_trials,
"abba": args.abba,
"json": args.json,
"args": args.extra,
})
}
fn load_source(path: Option<&Path>) -> Result<(String, String), Stop> {
match path {
Some(path) => {
let text = std::fs::read_to_string(path)
.map_err(|e| Stop::Failed(format!("{}: {e}", path.display())))?;
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "tune.js".into());
Ok((name, text))
}
None => Ok(("tune.js".into(), BUILTIN.into())),
}
}
fn load_guest(path: Option<&Path>) -> Result<Guest, Stop> {
match path {
Some(path) => {
let bytes = std::fs::read(path)
.map_err(|e| Stop::Failed(format!("{}: {e}", path.display())))?;
Guest::new(&bytes).map_err(|e| Stop::Failed(e.to_string()))
}
None => Guest::shared()
.cloned()
.map_err(|e| Stop::Failed(e.to_string())),
}
}
pub(crate) fn drive(
guest: &Guest,
name: &str,
source: &str,
config: &Value,
backend: Rc<dyn Backend>,
output: Option<&Path>,
sink: Rc<RefCell<Box<dyn Sink>>>,
) -> Result<Value, Stop> {
let output = output.map(PathBuf::from);
let host: Host = Rc::new(RefCell::new(move |call: &str, args: Value| {
let mut sink = sink.borrow_mut();
dispatch(call, args, backend.as_ref(), output.as_deref(), &mut **sink)
}));
let mut script = Script::with_host(guest, name, source, Limits::default(), Some(host))
.map_err(|e| Stop::Failed(e.to_string()))?;
script
.call("run", config, &mut [])
.map_err(|e| Stop::Failed(e.to_string()))
}
fn dispatch(
name: &str,
args: Value,
backend: &dyn Backend,
output: Option<&Path>,
sink: &mut dyn Sink,
) -> Result<Value, String> {
match name {
"schema" => backend.schema(),
"recipe" => backend.recipe(),
"explain" => backend.explain(&args),
"apply" => apply_and_wait(backend, &args),
"measure" => backend.measure(&args),
"save" => save_overlay(&args, output),
"say" => {
sink.text(&text_arg(&args)?);
Ok(Value::Null)
}
"note" => {
sink.note(&text_arg(&args)?);
Ok(Value::Null)
}
"record" => {
sink.record(args);
Ok(Value::Null)
}
other => Err(format!("unknown tune host call `{other}`")),
}
}
fn text_arg(args: &Value) -> Result<String, String> {
match args {
Value::String(s) => Ok(s.clone()),
Value::Object(m) => m
.get("text")
.and_then(Value::as_str)
.map(String::from)
.ok_or_else(|| "expected string or {\"text\": \"...\"}".into()),
_ => Err("expected string or {\"text\": \"...\"}".into()),
}
}
fn apply_and_wait(backend: &dyn Backend, args: &Value) -> Result<Value, String> {
let wait = args.get("wait").and_then(Value::as_bool).unwrap_or(true);
let mut ask = args.clone();
if let Some(map) = ask.as_object_mut() {
map.remove("wait");
}
let started = backend.apply(&ask)?;
if !wait {
return Ok(started);
}
let mut state = backend.recipe()?;
while state.get("applying").and_then(Value::as_bool) == Some(true) {
sleep(POLL);
state = backend.recipe()?;
}
Ok(json!({
"lowered": started.get("lowered").cloned().unwrap_or(Value::Null),
"recipe": state.get("recipe").cloned().unwrap_or(Value::Null),
"loads": state.get("loads").cloned().unwrap_or(Value::Null),
"seconds": state.get("seconds").cloned().unwrap_or(Value::Null),
"error": state.get("error").cloned().unwrap_or(Value::Null),
}))
}
pub(crate) fn save_overlay(args: &Value, output: Option<&Path>) -> Result<Value, String> {
let shape = args
.get("shape")
.and_then(Value::as_array)
.ok_or("save expects {\"shape\": [[spot, value], ...]}")?;
let want_json = args
.get("format")
.and_then(Value::as_str)
.is_some_and(|f| f.eq_ignore_ascii_case("json"))
|| output
.and_then(|p| p.extension())
.and_then(|e| e.to_str())
.is_some_and(|e| e.eq_ignore_ascii_case("json"));
let text = if want_json {
format!(
"{}\n",
serde_json::to_string_pretty(&json!({ "shape": shape })).map_err(|e| e.to_string())?
)
} else {
format_toml(shape)?
};
let saved_path = match output {
Some(path) => {
std::fs::write(path, &text).map_err(|e| format!("{}: {e}", path.display()))?;
Value::String(path.display().to_string())
}
None => Value::Null,
};
Ok(json!({ "path": saved_path, "text": text }))
}
pub(crate) fn format_toml(shape: &[Value]) -> Result<String, String> {
let mut lines = Vec::with_capacity(shape.len());
for pair in shape {
let Some(items) = pair.as_array() else {
return Err("each shape entry must be [spot, value]".into());
};
let (Some(spot), Some(val)) = (
items.first().and_then(Value::as_str),
items.get(1).and_then(Value::as_u64),
) else {
return Err("each shape entry must be [string, u64]".into());
};
let flag = match spot.split_once(',') {
Some((head, tests)) => format!("{head}={val},{tests}"),
None => format!("{spot}={val}"),
};
lines.push(format!(" {flag:?},"));
}
if lines.is_empty() {
return Ok("[lower]\nknobs = []\n".into());
}
Ok(format!("[lower]\nknobs = [\n{}\n]\n", lines.join("\n")))
}
struct LocalBackend(Slot);
impl LocalBackend {
fn tuner(&self) -> Result<&dyn tessera_frontend::tasks::api::Tune, String> {
crate::task::model(&self.0)
.tune
.as_deref()
.ok_or_else(|| "model was not loaded with --tune".into())
}
}
impl Backend for LocalBackend {
fn schema(&self) -> Result<Value, String> {
Ok(self.tuner()?.schema())
}
fn recipe(&self) -> Result<Value, String> {
Ok(self.tuner()?.recipe())
}
fn explain(&self, ask: &Value) -> Result<Value, String> {
let bytes = serde_json::to_vec(ask).map_err(|e| e.to_string())?;
self.tuner()?.explain(&bytes)
}
fn apply(&self, ask: &Value) -> Result<Value, String> {
let bytes = serde_json::to_vec(ask).map_err(|e| e.to_string())?;
self.tuner()?.apply(&bytes)
}
fn measure(&self, ask: &Value) -> Result<Value, String> {
let m = crate::task::model(&self.0);
let generator = m
.generator
.as_deref()
.ok_or("loaded model does not generate")?;
let bytes = serde_json::to_vec(ask).map_err(|e| e.to_string())?;
self.tuner()?.measure(&bytes, m.tokens.as_ref(), generator)
}
}
struct RemoteBackend {
base: String,
agent: ureq::Agent,
}
impl RemoteBackend {
fn new(url: &str) -> Self {
let base = url.trim_end_matches('/').to_string();
let agent = ureq::AgentBuilder::new()
.timeout_connect(Duration::from_secs(15))
.build();
Self { base, agent }
}
fn get(&self, path: &str) -> Result<Value, String> {
let url = format!("{}{path}", self.base);
read_http(self.agent.get(&url).call())
}
fn post(&self, path: &str, body: &Value) -> Result<Value, String> {
let url = format!("{}{path}", self.base);
read_http(self.agent.post(&url).send_json(body.clone()))
}
}
fn read_http(resp: Result<ureq::Response, ureq::Error>) -> Result<Value, String> {
match resp {
Ok(ok) => ok.into_json::<Value>().map_err(|e| e.to_string()),
Err(ureq::Error::Status(code, resp)) => {
let text = resp.into_string().unwrap_or_default();
if let Ok(val) = serde_json::from_str::<Value>(&text)
&& let Some(msg) = val.pointer("/error/message").and_then(Value::as_str)
{
return Err(format!("HTTP {code}: {msg}"));
}
Err(format!("HTTP {code}: {text}"))
}
Err(ureq::Error::Transport(e)) => Err(e.to_string()),
}
}
impl Backend for RemoteBackend {
fn schema(&self) -> Result<Value, String> {
self.get("/tune/schema")
}
fn recipe(&self) -> Result<Value, String> {
self.get("/tune/recipe")
}
fn explain(&self, ask: &Value) -> Result<Value, String> {
self.post("/tune/explain", ask)
}
fn apply(&self, ask: &Value) -> Result<Value, String> {
self.post("/tune/apply", ask)
}
fn measure(&self, ask: &Value) -> Result<Value, String> {
self.post("/tune/measure", ask)
}
}