Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
AK1b: raea-io-clef: one clef client, routed to the person's plan first; raea judge moved onto it
shinyobjectz70cb98d3e827
diff --git a/Cargo.lock b/Cargo.lockindex 6ed82e90..d57f661a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -13902,14 +13902,13 @@ dependencies = [name = "raea-app-judge"version = "0.1.0"dependencies = [- "base64 0.22.1","dunce",- "image",+ "raea-core-ask","raea-core-facts",+ "raea-io-clef","raea-io-home","raea-runtime-bundle","serde_json",- "ureq 2.12.1",][[package]]@@ -14566,6 +14565,20 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-io-clef"+version = "0.1.0"+dependencies = [+ "base64 0.22.1",+ "raea-core-ask",+ "raea-io-assets",+ "raea-io-ffmpeg",+ "raea-io-home",+ "serde_json",+ "sha2 0.10.9",+ "ureq 2.12.1",+]+[[package]]name = "raea-io-codec"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 729bcb9c..1e01a25c 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -62,6 +62,7 @@ members = ["io/codec","io/media","io/assets",+ "io/clef","io/gen","io/gen-comfy","io/gen-core",diff --git a/apps/judge/Cargo.toml b/apps/judge/Cargo.tomlindex 223e3602..e130bb7d 100644--- a/apps/judge/Cargo.toml+++ b/apps/judge/Cargo.toml@@ -13,6 +13,6 @@ raea-io-home = { path = "../../io/home" }raea-core-facts = { path = "../../core/facts" }serde_json = "1"raea-runtime-bundle = { path = "../../runtime/bundle" }-ureq = { version = "2", features = ["json"] }-base64 = "0.22"-image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }+# the one clef client: the question format and the call, routed to the person's plan first (docs/ask.feature AK1b)+raea-core-ask = { path = "../../core/ask" }+raea-io-clef = { path = "../../io/clef" }diff --git a/apps/judge/src/clef.rs b/apps/judge/src/clef.rsdeleted file mode 100644index 0af66436..00000000--- a/apps/judge/src/clef.rs+++ /dev/null@@ -1,37 +0,0 @@-//! One clef-omni call on Workers AI (as apps/app/host/critique.ts makes it): the state paragraph, the questions by id,-//! the images as data URLs (each made a JPEG at most 1600 px wide first). Keys: CLOUDFLARE_ACCOUNT_ID and-//! CLOUDFLARE_API_TOKEN from raea's settings (the environment, then ~/.raea/env).--use std::path::PathBuf;--use base64::Engine as _;-use serde_json::{Value, json};--fn jpeg(p: &PathBuf) -> Result<String, String> {- let img = image::open(p).map_err(|e| format!("{}: {e}", p.display()))?;- let img = if img.width() > 1600 { img.resize(1600, u32::MAX, image::imageops::FilterType::Triangle) } else { img };- let mut buf = std::io::Cursor::new(Vec::new());- img.to_rgb8().write_to(&mut buf, image::ImageFormat::Jpeg).map_err(|e| e.to_string())?;- Ok(format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(buf.into_inner())))-}--/// The answers by question id, and the call's cost in dollars ($0.15 a million input tokens).-pub fn ask(state: &str, questions: &Value, images: &[PathBuf]) -> Result<(Value, f64), String> {- let (Some(acct), Some(token)) = (raea_io_home::setting("CLOUDFLARE_ACCOUNT_ID"), raea_io_home::setting("CLOUDFLARE_API_TOKEN")) else {- return Err("judge: clef-omni on Workers AI needs CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN (the environment or ~/.raea/env)".into());- };- let imgs: Vec<String> = images.iter().map(jpeg).collect::<Result<_, _>>()?;- let body = json!({"state": state, "questions": questions, "images": imgs});- let url = format!("https://api.cloudflare.com/client/v4/accounts/{acct}/ai/run/@cf/cloudflare/clef-omni");- let res = ureq::post(&url).set("authorization", &format!("Bearer {token}")).timeout(std::time::Duration::from_secs(180)).send_json(body);- let j: Value = match res {- Ok(r) => r.into_json().map_err(|e| format!("clef: {e}"))?,- Err(ureq::Error::Status(code, r)) => return Err(format!("clef: HTTP {code}: {}", r.into_string().unwrap_or_default().chars().take(300).collect::<String>())),- Err(e) => return Err(format!("clef: {e}")),- };- if j["success"] != true {- return Err(format!("clef: {}", j["errors"].to_string().chars().take(300).collect::<String>()));- }- let cost = j["result"]["usage"]["input_tokens"].as_f64().unwrap_or(0.0) * 0.15 / 1e6;- Ok((j["result"]["answers"].clone(), cost))-}diff --git a/apps/judge/src/lib.rs b/apps/judge/src/lib.rsindex 93739a5b..63d988cc 100644--- a/apps/judge/src/lib.rs+++ b/apps/judge/src/lib.rs@@ -10,7 +10,6 @@//! each a fresh call) and the stall (the mean up by less than a point over two rounds) are read from it.mod agent;-mod clef;mod eye;pub mod rubric;@@ -24,6 +23,17 @@ use serde_json::{Value, json};pub const USAGE: &str = "raea judge DIR [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; the pass decided in code; clef advises until calibrated against your eye or an agent's)";+/// One call through raea's one clef client (raea-io-clef: the person's plan first, then their own Cloudflare keys),+/// with the rubric's questions as written and each sheet as a JPEG still.+fn ask(state: &str, questions: &Value, images: &[PathBuf]) -> Result<(Value, f64), String> {+ let qs = questions.as_object().ok_or("judge: the questions aren't a map")?;+ let questions = qs.iter().map(|(id, w)| raea_core_ask::Question::from_wire(id, w).ok_or(format!("judge: {id} isn't one of clef's question types"))).collect::<Result<_, _>>()?;+ let stills = images.iter().map(|p| raea_io_clef::media::still(p, None)).collect::<Result<_, _>>()?;+ let call = raea_io_clef::Call { state: state.into(), questions, media: raea_io_clef::Media { stills, ..Default::default() } };+ let a = raea_io_clef::ask(&call)?;+ Ok((Value::Object(a.answers), a.cost))+}+/// The brief's words, from `raea spec brief.ts --as brief` (look, logline, notDoing), or nothing.fn brief_of(path: Option<&str>) -> Result<Value, String> {let Some(p) = path else { return Ok(json!({})) };@@ -104,7 +114,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {let mut photo = Value::Null;let mut cost = 0.0;for (sheet, st, q, images) in &calls {- let (answers, c) = clef::ask(st, q, images)?;+ let (answers, c) = ask(st, q, images)?;cost += c;if *sheet == "blind" {photo = json!(answers["photo"]["noul"].as_f64().map(|p| (p * 1000.0).round() / 1000.0));diff --git a/core/ask/src/question.rs b/core/ask/src/question.rsindex 21ffe6ee..22c25f9d 100644--- a/core/ask/src/question.rs+++ b/core/ask/src/question.rs@@ -184,6 +184,34 @@ impl Question {serde_json::from_value(json!({"id": id, "ask": ask})).expect("a plain question")}+ /// A question written in clef's own wire format (`{type: noul | choice | score, instructions, criteria}`), as raea+ /// judge's rubric and the playtest packs write them; None when it isn't one.+ pub fn from_wire(id: &str, w: &Value) -> Option<Question> {+ let mut q = Question::plain(id, w["instructions"].as_str()?);+ match w["type"].as_str()? {+ "noul" => {+ if let (Some(y), Some(n)) = (w["criteria"]["true"].as_str(), w["criteria"]["false"].as_str()) {+ q.means = BTreeMap::from([("yes".into(), y.into()), ("no".into(), n.into())]);+ }+ }+ "choice" => {+ q.kind = Kind::Choose;+ for (k, v) in w["criteria"].as_object()? {+ q.options.push(k.clone());+ if let Some(m) = v.as_str() {+ q.means.insert(k.clone(), m.into());+ }+ }+ }+ "score" => {+ q.kind = Kind::Rate;+ q.options = w["criteria"].as_array()?.iter().map(|l| l.as_str().map(str::to_string)).collect::<Option<_>>()?;+ }+ _ => return None,+ }+ Some(q)+ }+/// Its levels or options as clef is sent them.pub fn levels(&self) -> Vec<String> {match (self.kind, self.options.is_empty()) {diff --git a/core/ask/src/tests.rs b/core/ask/src/tests.rsindex 91299324..0c05affc 100644--- a/core/ask/src/tests.rs+++ b/core/ask/src/tests.rs@@ -85,6 +85,19 @@ fn each_type_goes_out_as_clefs_own_and_reads_back_as_a_problem_score() {assert_eq!((r.choice.as_deref(), r.problem), (Some("second"), None), "a pick has no problem score");}+#[test]+fn a_question_in_clefs_own_format_comes_back_as_it_went() {+ for w in [+ json!({"type": "noul", "instructions": "Is it a photograph?"}),+ json!({"type": "noul", "instructions": "Is it a photograph?", "criteria": {"true": "a real place", "false": "a render"}}),+ json!({"type": "score", "instructions": "How is the light?", "criteria": ["none", "flat", "good"]}),+ json!({"type": "choice", "instructions": "Which?", "criteria": {"a": null, "b": "the second"}}),+ ] {+ assert_eq!(Question::from_wire("q", &w).unwrap().wire(), w);+ }+ assert!(Question::from_wire("q", &json!({"type": "essay", "instructions": "Say"})).is_none());+}+#[test]fn a_calibrated_question_flags_at_its_own_threshold() {let q = library::find("face.text_over", None).unwrap();diff --git a/docs/settings.md b/docs/settings.mdindex 868c95e8..3674bd0a 100644--- a/docs/settings.md+++ b/docs/settings.md@@ -41,7 +41,11 @@ libraries (pianos, General MIDI instruments, orchestral and percussion samples,| Setting | What ||---|---|-| `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN` | The checks' judge model (clef-omni on Workers AI) |+| `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN` | The decision model (clef-omni on Workers AI) on your own Cloudflare account, for `raea ask`, `raea judge` and the checks that ask. Signed in to raea on Pro or Studio, the app pays from your plan's monthly pool first (docs/ask.feature) |+| `RAEA_AGENT_KEY`, `RAEA_API` | An agent key with the `ask` scope, and the API address it came with: asks from your plan's pool with no app running (a pipeline, CI, a server) |+| `RAEA_ASK_ROUTE` | `app`, `agent` or `own`: ask only that way, rather than the first that answers |+| `RAEA_ASK_DIR` | Where `raea ask` keeps its answers, the clips it cut and its cache (`~/.raea/ask`) |+| `RAEA_CLEF_REPLAY` | A JSON file of answers by question id, given back for every call: for tests, which then never spend || `RAEA_GUIDES` | A folder of craft references for the agent's `guide` tool (`captions.md`, `motion-rules.md`, ...) |## Renderingdiff --git a/io/clef/Cargo.toml b/io/clef/Cargo.tomlnew file mode 100644index 00000000..8a9d78bc--- /dev/null+++ b/io/clef/Cargo.toml@@ -0,0 +1,18 @@+[package]+name = "raea-io-clef"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "The decision model (clef-omni) called one way: the call, the media cut to its limits, the route (the person's raea plan first) and the cache"++[dependencies]+raea-core-ask = { path = "../../core/ask" }+raea-io-home = { path = "../home" }+# raea's own FFmpeg (fetched on Windows) and the H.264 encoder this machine has+raea-io-assets = { path = "../assets" }+raea-io-ffmpeg = { path = "../ffmpeg" }+serde_json = "1"+ureq = { version = "2", features = ["json"] }+base64 = "0.22"+sha2 = "0.10"diff --git a/io/clef/src/cache.rs b/io/clef/src/cache.rsnew file mode 100644index 00000000..497d5737--- /dev/null+++ b/io/clef/src/cache.rs@@ -0,0 +1,36 @@+//! Answers kept by what was asked (docs/ask.feature AK1b): the hash of everything the model reads (the state, the+//! questions as sent, the media), so the same questions on the same media cost nothing the second time. clef gives the+//! same answer to the same request, so a kept answer is the answer. Under RAEA_ASK_DIR, else ~/.raea/ask, in cache/.++use serde_json::{Map, Value};+use sha2::{Digest, Sha256};++use crate::client::Call;++/// raea ask's own folder: answers, kept media and this cache.+pub fn dir() -> std::path::PathBuf {+ raea_io_home::env_path("RAEA_ASK_DIR", ".raea/ask")+}++/// The request's hash.+pub fn key(call: &Call) -> String {+ let mut h = Sha256::new();+ h.update(call.clef_body().to_string().as_bytes());+ h.finalize().iter().map(|b| format!("{b:02x}")).collect()+}++pub fn get(key: &str) -> Option<Map<String, Value>> {+ let text = std::fs::read_to_string(dir().join("cache").join(format!("{key}.json"))).ok()?;+ serde_json::from_str(&text).ok()+}++/// Kept, unless nothing came back (an empty answer is never cached, so a fixed problem is asked again).+pub fn put(key: &str, answers: &Map<String, Value>) {+ if answers.is_empty() {+ return;+ }+ let d = dir().join("cache");+ if std::fs::create_dir_all(&d).is_ok() {+ let _ = std::fs::write(d.join(format!("{key}.json")), Value::Object(answers.clone()).to_string());+ }+}diff --git a/io/clef/src/client.rs b/io/clef/src/client.rsnew file mode 100644index 00000000..6a95af51--- /dev/null+++ b/io/clef/src/client.rs@@ -0,0 +1,160 @@+//! One call to the decision model (docs/ask.feature AK1b): the state, the questions by id and the media, sent to Workers+//! AI with the person's keys, or to raea-api (directly with an agent key, or through the app, which adds its sign-in).+//! The answers come back by question id with the call's cost. A transport is handed in, so tests replay recorded+//! answers and never spend.++use base64::Engine as _;+use raea_core_ask::{Question, limits};+use serde_json::{Map, Value, json};++/// The media one call reads: stills as JPEG, videos as MP4, sounds as MP3, each already cut to clef's limits.+#[derive(Debug, Clone, Default)]+pub struct Media {+ pub stills: Vec<Vec<u8>>,+ pub videos: Vec<Vec<u8>>,+ pub sounds: Vec<Vec<u8>>,+}++/// One call: what the piece is (the state), every question about this media, and the media.+#[derive(Debug, Clone, Default)]+pub struct Call {+ pub state: String,+ pub questions: Vec<Question>,+ pub media: Media,+}++/// What came back: the answers by question id (clef's own shape: `noul`, or `choice` and `probabilities`, or `score`),+/// what it cost, whether it came from a cache, the route it took and the pool left after it (raea's routes only).+#[derive(Debug, Clone, Default)]+pub struct Answered {+ pub answers: Map<String, Value>,+ pub cost: f64,+ pub cached: bool,+ pub route: String,+ pub pool_left: Option<f64>,+}++/// Why a route didn't answer: `Next` means try the next one (no plan, signed out, not running, no ask scope); `Stop`+/// means asking again elsewhere won't help (the call itself is wrong, or the pool is spent and nothing else is set).+#[derive(Debug, Clone, PartialEq)]+pub enum Fail {+ Next(String),+ Stop(String),+}++/// An HTTP POST of JSON: its status and body. `Http` is the real one; a test hands in its own.+pub trait Transport {+ fn post(&self, url: &str, bearer: Option<&str>, body: &Value) -> Result<(u16, Value), String>;+}++pub struct Http;++impl Transport for Http {+ fn post(&self, url: &str, bearer: Option<&str>, body: &Value) -> Result<(u16, Value), String> {+ let mut r = ureq::post(url).timeout(std::time::Duration::from_secs(180));+ if let Some(b) = bearer {+ r = r.set("authorization", &format!("Bearer {b}"));+ }+ match r.send_json(body.clone()) {+ Ok(res) => Ok((res.status(), res.into_json().map_err(|e| format!("{url}: {e}"))?)),+ Err(ureq::Error::Status(code, res)) => Ok((code, res.into_json().unwrap_or_else(|_| json!({})))),+ Err(e) => Err(format!("{url}: {e}")),+ }+ }+}++fn b64(v: &[u8]) -> String {+ base64::engine::general_purpose::STANDARD.encode(v)+}++impl Call {+ /// Why it can't be sent as it stands, or None: clef's counts and sizes, every question's own limits.+ pub fn problem(&self) -> Option<String> {+ let m = &self.media;+ if self.questions.is_empty() || self.questions.len() > limits::QUESTIONS {+ return Some(format!("a call asks 1 to {} questions, not {}", limits::QUESTIONS, self.questions.len()));+ }+ if let Some(p) = self.questions.iter().find_map(limits::check) {+ return Some(p);+ }+ if m.stills.is_empty() && m.videos.is_empty() && m.sounds.is_empty() {+ return Some("a call needs something to look at or listen to".into());+ }+ let over = |v: &[Vec<u8>], most: usize, each: usize| v.len() > most || v.iter().any(|b| b.len() > each);+ if over(&m.stills, limits::STILLS, limits::STILL_BYTES) || m.stills.iter().map(Vec::len).sum::<usize>() > limits::STILLS_BYTES {+ return Some(format!("at most {} stills of 4 MiB, 8 MiB in all", limits::STILLS));+ }+ if over(&m.videos, limits::VIDEOS, limits::VIDEO_BYTES) || over(&m.sounds, limits::SOUNDS, limits::SOUND_BYTES) {+ return Some(format!("at most {} videos of 16 MiB and {} sounds of 8 MiB", limits::VIDEOS, limits::SOUNDS));+ }+ (m.videos.iter().chain(&m.sounds).map(Vec::len).sum::<usize>() > limits::AV_BYTES).then(|| "the videos and sounds together are over 16 MiB".into())+ }++ fn questions(&self) -> Value {+ Value::Object(self.questions.iter().map(|q| (q.id.clone(), q.wire())).collect())+ }++ fn state(&self) -> String {+ self.state.chars().take(limits::STATE_CHARS).collect()+ }++ /// The body Workers AI takes: the media as data URLs.+ pub fn clef_body(&self) -> Value {+ let urls = |v: &[Vec<u8>], mime: &str| v.iter().map(|b| format!("data:{mime};base64,{}", b64(b))).collect::<Vec<_>>();+ let mut body = json!({"state": self.state(), "questions": self.questions()});+ for (k, v, mime) in [("images", &self.media.stills, "image/jpeg"), ("videos", &self.media.videos, "video/mp4"), ("audio", &self.media.sounds, "audio/mpeg")] {+ if !v.is_empty() {+ body[k] = json!(urls(v, mime));+ }+ }+ body+ }++ /// raea-api's body: the media as bare base64 (it adds the data URL's type).+ pub fn api_body(&self) -> Value {+ let mut body = json!({"state": self.state(), "questions": self.questions()});+ for (k, v) in [("images", &self.media.stills), ("videos", &self.media.videos), ("audio", &self.media.sounds)] {+ if !v.is_empty() {+ body[k] = json!(v.iter().map(|b| b64(b)).collect::<Vec<_>>());+ }+ }+ body+ }+}++fn said(body: &Value, code: u16) -> String {+ body["message"].as_str().or(body["error"].as_str()).map(str::to_string).unwrap_or_else(|| format!("HTTP {code}"))+}++/// Workers AI, on the person's own Cloudflare account.+pub fn workers_ai(t: &dyn Transport, call: &Call, account: &str, token: &str) -> Result<Answered, Fail> {+ let url = format!("https://api.cloudflare.com/client/v4/accounts/{account}/ai/run/@cf/cloudflare/clef-omni");+ let (code, j) = t.post(&url, Some(token), &call.clef_body()).map_err(Fail::Stop)?;+ if code == 401 || code == 403 {+ return Err(Fail::Next(format!("your Cloudflare keys were refused ({code}): check CLOUDFLARE_API_TOKEN")));+ }+ if j["success"] != true {+ return Err(Fail::Stop(format!("clef: {}", j["errors"].to_string().chars().take(300).collect::<String>())));+ }+ let r = &j["result"];+ let cost = r["usage"]["input_tokens"].as_f64().unwrap_or(0.0) * limits::USD_PER_M / 1e6;+ Ok(Answered { answers: r["answers"].as_object().cloned().unwrap_or_default(), cost, cached: false, route: "your Cloudflare account".into(), pool_left: None })+}++/// raea-api's /v1/clef/ask at `url` (the API itself with an agent key, or the app's /host/ask, which signs it), charged+/// to the account's pool. `own_keys` says whether a spent pool may fall through to the person's own account.+pub fn raea_api(t: &dyn Transport, call: &Call, url: &str, bearer: Option<&str>, route: &str, own_keys: bool) -> Result<Answered, Fail> {+ let (code, j) = t.post(url, bearer, &call.api_body()).map_err(|e| Fail::Next(format!("{route} didn't answer: {e}")))?;+ match (code, j["error"].as_str()) {+ (200..=299, _) => Ok(Answered {+ answers: j["answers"].as_object().cloned().unwrap_or_default(),+ cost: j["cost_usd"].as_f64().unwrap_or(0.0),+ cached: j["cached"] == true,+ route: route.into(),+ pool_left: j["pool_left_usd"].as_f64(),+ }),+ (402, Some("pool_spent")) if !own_keys => Err(Fail::Stop(said(&j, code))),+ (400 | 413, _) => Err(Fail::Stop(said(&j, code))),+ _ => Err(Fail::Next(format!("{route}: {}", said(&j, code)))),+ }+}diff --git a/io/clef/src/lib.rs b/io/clef/src/lib.rsnew file mode 100644index 00000000..c3fd5ac4--- /dev/null+++ b/io/clef/src/lib.rs@@ -0,0 +1,19 @@+//! The decision model, called one way for every caller (docs/ask.feature AK1b): a call's body and its answers+//! (`client`), the media cut to what it reads (`media`), the route it takes, the person's plan first (`route`), and the+//! answers kept by request (`cache`). `raea ask` (apps/ask) and `raea judge` call it.++pub mod cache;+pub mod client;+pub mod media;+pub mod route;++pub use client::{Answered, Call, Fail, Http, Media, Transport};+pub use route::Route;++/// One call, by the routes open on this computer.+pub fn ask(call: &Call) -> Result<Answered, String> {+ route::ask(&Http, call, &route::open())+}++#[cfg(test)]+mod tests;diff --git a/io/clef/src/media.rs b/io/clef/src/media.rsnew file mode 100644index 00000000..bcbaa8b4--- /dev/null+++ b/io/clef/src/media.rs@@ -0,0 +1,135 @@+//! The media cut to what the decision model reads (docs/ask.feature AK1b), with raea's own FFmpeg: a window of a video as+//! 480 px H.264 of at most 60 s, its sound as mono 16 kHz MP3 of at most 300 s, a still as JPEG of at most 1,600 px.+//! What a file has (its length, a picture, a sound) comes from ffprobe first, so a question that can't be answered+//! isn't asked.++use std::path::{Path, PathBuf};+use std::process::Command;++use raea_core_ask::limits;++/// What a file holds.+#[derive(Debug, Clone, Copy, Default, PartialEq)]+pub struct Probe {+ pub seconds: f64,+ /// a moving picture (a video stream with more than one frame)+ pub video: bool,+ /// a picture that doesn't move (an image, or a video of one frame)+ pub still: bool,+ pub sound: bool,+}++fn tool(name: &str, file: &Path) -> Result<Command, String> {+ let video = file.extension().is_some_and(|e| !matches!(e.to_string_lossy().to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "webp" | "mp3" | "wav" | "m4a"));+ raea_io_assets::ffmpeg_tool(name, video).map(Command::new)+}++fn run(mut c: Command, what: &str) -> Result<Vec<u8>, String> {+ let out = c.output().map_err(|e| format!("{what}: {e}"))?;+ if !out.status.success() {+ let err = String::from_utf8_lossy(&out.stderr);+ return Err(format!("{what}: {}", err.lines().last().unwrap_or("FFmpeg failed").trim()));+ }+ Ok(out.stdout)+}++/// What `file` holds, from ffprobe.+pub fn probe(file: &Path) -> Result<Probe, String> {+ if !file.is_file() {+ return Err(format!("{}: no such file", file.display()));+ }+ let mut c = tool("ffprobe", file)?;+ c.args(["-v", "error", "-show_entries", "stream=codec_type,nb_frames,disposition:format=duration", "-of", "json"]).arg(file);+ let j: serde_json::Value = serde_json::from_slice(&run(c, "ffprobe")?).map_err(|e| format!("ffprobe: {e}"))?;+ let streams = j["streams"].as_array().cloned().unwrap_or_default();+ let seconds = j["format"]["duration"].as_str().and_then(|s| s.parse().ok()).unwrap_or(0.0);+ let pictures: Vec<&serde_json::Value> = streams.iter().filter(|s| s["codec_type"] == "video" && s["disposition"]["attached_pic"] != 1).collect();+ let one_frame = |s: &&serde_json::Value| s["nb_frames"].as_str().is_some_and(|n| n == "1") || seconds == 0.0;+ Ok(Probe {+ seconds,+ video: pictures.iter().any(|s| !one_frame(s)),+ still: !pictures.is_empty() && pictures.iter().all(one_frame),+ sound: streams.iter().any(|s| s["codec_type"] == "audio"),+ })+}++/// A file in the temp folder, removed when dropped.+struct Temp(PathBuf);++impl Temp {+ fn new(ext: &str) -> Temp {+ static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+ let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ Temp(std::env::temp_dir().join(format!("raea-ask-{}-{n}.{ext}", std::process::id())))+ }+ fn read(&self) -> Result<Vec<u8>, String> {+ std::fs::read(&self.0).map_err(|e| format!("{}: {e}", self.0.display()))+ }+}++impl Drop for Temp {+ fn drop(&mut self) {+ let _ = std::fs::remove_file(&self.0);+ }+}++fn window(from: f64, to: Option<f64>, most: f64) -> Vec<String> {+ let len = to.map(|t| (t - from).max(0.1)).unwrap_or(most).min(most);+ vec!["-ss".into(), format!("{from:.3}"), "-t".into(), format!("{len:.3}")]+}++/// The H.264 this FFmpeg has, small: libx264 at CRF 30, else the system's own at 600 kb/s (raea_io_ffmpeg's choice, which+/// for a clip a person plays is 8 Mb/s, too big for a minute under 16 MiB).+fn small_h264() -> Result<Vec<String>, String> {+ let mut args: Vec<String> = raea_io_ffmpeg::h264().ok_or("this FFmpeg has no H.264 encoder (libx264, VideoToolbox or Media Foundation)")?.into_iter().map(str::to_string).collect();+ match args.iter().position(|a| a == "8M") {+ Some(i) => args[i] = "600k".into(),+ None => args.extend(["-crf", "30", "-preset", "veryfast"].map(String::from)),+ }+ Ok(args)+}++/// The picture from `from` to `to` (at most 60 s), 480 px wide, no sound.+pub fn video(file: &Path, from: f64, to: Option<f64>) -> Result<Vec<u8>, String> {+ let out = Temp::new("mp4");+ let mut c = tool("ffmpeg", file)?;+ c.args(["-nostdin", "-v", "error", "-y"]).args(window(from, to, limits::VIDEO_SECONDS)).arg("-i").arg(file);+ c.args(["-an", "-vf", "scale=480:-2", "-r", "10"]).args(small_h264()?).args(["-movflags", "+faststart"]).arg(&out.0);+ run(c, "cutting the picture")?;+ out.read()+}++/// The sound from `from` to `to` (at most 300 s), mono 16 kHz MP3.+pub fn sound(file: &Path, from: f64, to: Option<f64>) -> Result<Vec<u8>, String> {+ let out = Temp::new("mp3");+ let mut c = tool("ffmpeg", file)?;+ c.args(["-nostdin", "-v", "error", "-y"]).args(window(from, to, limits::SOUND_SECONDS)).arg("-i").arg(file);+ c.args(["-vn", "-ac", "1", "-ar", "16000", "-c:a", "libmp3lame", "-b:a", "64k"]).arg(&out.0);+ run(c, "cutting the sound").map_err(|e| if e.contains("libmp3lame") { "this FFmpeg can't write MP3 (libmp3lame)".into() } else { e })?;+ out.read()+}++/// A still: an image file as it is, or a video's frame at `at` seconds, as JPEG at most 1,600 px wide.+pub fn still(file: &Path, at: Option<f64>) -> Result<Vec<u8>, String> {+ let out = Temp::new("jpg");+ let mut c = tool("ffmpeg", file)?;+ c.args(["-nostdin", "-v", "error", "-y"]);+ if let Some(t) = at {+ c.args(["-ss", &format!("{t:.3}")]);+ }+ c.arg("-i").arg(file).args(["-frames:v", "1", "-vf", "scale='min(1600,iw)':-2", "-q:v", "4"]).arg(&out.0);+ run(c, "taking the still")?;+ out.read()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_window_is_held_to_the_limit() {+ assert_eq!(window(5.0, Some(20.0), 60.0), ["-ss", "5.000", "-t", "15.000"]);+ assert_eq!(window(0.0, None, 60.0), ["-ss", "0.000", "-t", "60.000"]);+ assert_eq!(window(0.0, Some(400.0), 300.0)[3], "300.000");+ }+}diff --git a/io/clef/src/route.rs b/io/clef/src/route.rsnew file mode 100644index 00000000..10e36e08--- /dev/null+++ b/io/clef/src/route.rs@@ -0,0 +1,112 @@+//! Which way a call goes (docs/ask.feature AK1b), the first that answers: the raea app on this computer when it's signed+//! in with a pool (it adds its sign-in, which stays the app's alone); an agent key (`RAEA_AGENT_KEY` with `RAEA_API`, the+//! address the key came with, for a pipeline, CI or raea cloud); the person's own Cloudflare account. Unchanged questions on unchanged media come from the cache+//! first. `RAEA_CLEF_REPLAY` names a file of recorded answers, for tests that must never spend.++use std::path::PathBuf;++use raea_io_home::setting;+use serde_json::{Map, Value};++use crate::cache;+use crate::client::{Answered, Call, Fail, Transport, raea_api, workers_ai};++#[derive(Debug, Clone, PartialEq)]+pub enum Route {+ /// the raea app's host, at the address ~/.raea/app-host.json gives+ App(String),+ /// raea-api with an agent key that has the `ask` scope+ Agent { api: String, key: String },+ /// the person's own Workers AI+ Own { account: String, token: String },+ /// recorded answers by question id, for tests+ Replay(PathBuf),+}++impl Route {+ pub fn name(&self) -> &'static str {+ match self {+ Route::App(_) => "your raea plan, through the app",+ Route::Agent { .. } => "your raea plan, with an agent key",+ Route::Own { .. } => "your Cloudflare account",+ Route::Replay(_) => "recorded answers",+ }+ }+}++/// The address the running raea app listens at, if it left one (RAEA_HOST_FILE, else ~/.raea/app-host.json).+fn app() -> Option<String> {+ let file = raea_io_home::env_path("RAEA_HOST_FILE", ".raea/app-host.json");+ let j: Value = serde_json::from_str(&std::fs::read_to_string(file).ok()?).ok()?;+ j["url"].as_str().map(|u| u.trim_end_matches('/').to_string())+}++/// The routes open here, in the order they're tried. `RAEA_ASK_ROUTE` (app, agent or own) keeps one.+pub fn open() -> Vec<Route> {+ if let Some(p) = setting("RAEA_CLEF_REPLAY") {+ return vec![Route::Replay(p.into())];+ }+ let mut out = Vec::new();+ if let Some(url) = app() {+ out.push(Route::App(url));+ }+ if let (Some(key), Some(api)) = (setting("RAEA_AGENT_KEY"), setting("RAEA_API")) {+ out.push(Route::Agent { api: api.trim_end_matches('/').to_string(), key });+ }+ if let (Some(account), Some(token)) = (setting("CLOUDFLARE_ACCOUNT_ID"), setting("CLOUDFLARE_API_TOKEN")) {+ out.push(Route::Own { account, token });+ }+ match setting("RAEA_ASK_ROUTE").as_deref() {+ Some("app") => out.retain(|r| matches!(r, Route::App(_))),+ Some("agent") => out.retain(|r| matches!(r, Route::Agent { .. })),+ Some("own") => out.retain(|r| matches!(r, Route::Own { .. })),+ _ => {}+ }+ out+}++pub const NONE: &str = "sign in to raea on Pro or Studio (the app), set RAEA_AGENT_KEY and RAEA_API, or add CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN to ~/.raea/env (docs/settings.md)";++fn replay(call: &Call, file: &PathBuf) -> Result<Answered, String> {+ let all: Map<String, Value> = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?)+ .map_err(|e| format!("{}: {e}", file.display()))?;+ let answers = call.questions.iter().filter_map(|q| all.get(&q.id).map(|a| (q.id.clone(), a.clone()))).collect();+ Ok(Answered { answers, cost: 0.0, cached: false, route: Route::Replay(file.clone()).name().into(), pool_left: None })+}++/// One call answered: from the cache, else by the first route that answers. Every route's reason is kept for the+/// refusal when none does.+pub fn ask(t: &dyn Transport, call: &Call, routes: &[Route]) -> Result<Answered, String> {+ if let Some(p) = call.problem() {+ return Err(p);+ }+ if let Some(Route::Replay(f)) = routes.first() {+ return replay(call, f);+ }+ let key = cache::key(call);+ if let Some(answers) = cache::get(&key) {+ return Ok(Answered { answers, cost: 0.0, cached: true, route: "asked before (cache)".into(), pool_left: None });+ }+ if routes.is_empty() {+ return Err(format!("nothing to ask with: {NONE}"));+ }+ let own = routes.iter().any(|r| matches!(r, Route::Own { .. }));+ let mut why = Vec::new();+ for r in routes {+ let got = match r {+ Route::App(url) => raea_api(t, call, &format!("{url}/host/ask"), None, r.name(), own),+ Route::Agent { api, key } => raea_api(t, call, &format!("{api}/v1/clef/ask"), Some(key), r.name(), own),+ Route::Own { account, token } => workers_ai(t, call, account, token),+ Route::Replay(f) => replay(call, f).map_err(Fail::Stop),+ };+ match got {+ Ok(a) => {+ cache::put(&key, &a.answers);+ return Ok(a);+ }+ Err(Fail::Stop(e)) => return Err(e),+ Err(Fail::Next(e)) => why.push(e),+ }+ }+ Err(format!("nothing answered ({}): {NONE}", why.join("; ")))+}diff --git a/io/clef/src/tests.rs b/io/clef/src/tests.rsnew file mode 100644index 00000000..40d5e867--- /dev/null+++ b/io/clef/src/tests.rs@@ -0,0 +1,108 @@+use std::cell::RefCell;++use raea_core_ask::Question;+use serde_json::{Value, json};++use crate::client::{Call, Media, Transport};+use crate::route::{self, Route};++/// Canned replies by URL ending, and every URL asked.+struct Fake {+ replies: Vec<(&'static str, u16, Value)>,+ seen: RefCell<Vec<String>>,+}++impl Transport for Fake {+ fn post(&self, url: &str, _bearer: Option<&str>, _body: &Value) -> Result<(u16, Value), String> {+ self.seen.borrow_mut().push(url.to_string());+ self.replies.iter().find(|(end, ..)| url.ends_with(end)).map(|(_, c, j)| (*c, j.clone())).ok_or_else(|| format!("{url}: connection refused"))+ }+}++fn setup() {+ static ONCE: std::sync::Once = std::sync::Once::new();+ // SAFETY: set once, before any test reads it, to the same value for every test+ ONCE.call_once(|| unsafe { std::env::set_var("RAEA_ASK_DIR", std::env::temp_dir().join(format!("raea-clef-test-{}", std::process::id()))) });+}++/// A call unique to its test (the cache is shared), with one question and a little media.+fn call(test: &str) -> Call {+ setup();+ Call { state: format!("a test piece: {test}"), questions: vec![Question::plain("q", "Is it loud?")], media: Media { sounds: vec![vec![1, 2, 3]], ..Default::default() } }+}++fn routes() -> Vec<Route> {+ vec![Route::App("http://127.0.0.1:9".into()), Route::Agent { api: "https://api.test".into(), key: "k".into() }, Route::Own { account: "a".into(), token: "t".into() }]+}++const ANSWER: &str = r#"{"success": true, "result": {"answers": {"q": {"noul": 0.7}}, "usage": {"input_tokens": 10000}}}"#;++#[test]+fn each_route_that_cant_answer_hands_on_to_the_next() {+ let f = Fake {+ replies: vec![+ ("/host/ask", 402, json!({"error": "plan_required", "message": "checks come with Pro and Studio"})),+ ("/v1/clef/ask", 403, json!({"error": "agent_scope", "message": "this key can't ask"})),+ ("/clef-omni", 200, serde_json::from_str(ANSWER).unwrap()),+ ],+ seen: RefCell::default(),+ };+ let a = route::ask(&f, &call("hand-on"), &routes()).unwrap();+ assert_eq!((a.route.as_str(), a.answers["q"]["noul"].as_f64()), ("your Cloudflare account", Some(0.7)));+ assert!((a.cost - 0.0015).abs() < 1e-9, "{}", a.cost);+ assert_eq!(f.seen.borrow().len(), 3);+}++#[test]+fn a_spent_pool_stops_unless_the_person_has_their_own_keys() {+ let spent = || Fake { replies: vec![("/host/ask", 402, json!({"error": "pool_spent", "message": "this month's checks are used up"}))], seen: RefCell::default() };+ let e = route::ask(&spent(), &call("spent"), &routes()[..1]).unwrap_err();+ assert!(e.contains("used up"), "{e}");+ let mut f = spent();+ f.replies.push(("/clef-omni", 200, serde_json::from_str(ANSWER).unwrap()));+ let a = route::ask(&f, &call("spent-own"), &[routes()[0].clone(), routes()[2].clone()]).unwrap();+ assert_eq!(a.route, "your Cloudflare account");+}++#[test]+fn the_plan_answers_with_whats_left_and_a_second_ask_costs_nothing() {+ let f = Fake { replies: vec![("/host/ask", 200, json!({"answers": {"q": {"noul": 0.2}}, "cost_usd": 0.004, "cached": false, "pool_left_usd": 1.62}))], seen: RefCell::default() };+ let c = call("plan");+ let a = route::ask(&f, &c, &routes()).unwrap();+ assert_eq!((a.route.as_str(), a.cost, a.pool_left), ("your raea plan, through the app", 0.004, Some(1.62)));+ let again = route::ask(&f, &c, &routes()).unwrap();+ assert!(again.cached && again.cost == 0.0);+ assert_eq!(f.seen.borrow().len(), 1, "the second came from the cache");+}++#[test]+fn with_nothing_open_it_says_how_to_get_one() {+ let f = Fake { replies: vec![], seen: RefCell::default() };+ let e = route::ask(&f, &call("none"), &[]).unwrap_err();+ assert!(e.contains("RAEA_AGENT_KEY") && e.contains("CLOUDFLARE_API_TOKEN"), "{e}");+ let e = route::ask(&f, &call("refused"), &routes()[..1]).unwrap_err();+ assert!(e.contains("connection refused") && e.contains("Pro or Studio"), "{e}");+}++#[test]+fn a_call_that_breaks_the_limits_is_refused_before_anything_is_sent() {+ let f = Fake { replies: vec![], seen: RefCell::default() };+ let mut c = call("limits");+ c.media = Media::default();+ assert!(route::ask(&f, &c, &routes()).unwrap_err().contains("look at or listen to"));+ let mut c = call("too-many");+ c.questions = (0..65).map(|i| Question::plain(&format!("q{i}"), "Is it loud?")).collect();+ assert!(route::ask(&f, &c, &routes()).unwrap_err().contains("1 to 64"));+ assert!(f.seen.borrow().is_empty());+}++#[test]+fn workers_ai_gets_data_urls_and_raea_api_bare_base64() {+ let c = Call { state: "s".into(), questions: vec![Question::plain("q", "Is it loud?")], media: Media { stills: vec![vec![0xff]], videos: vec![], sounds: vec![vec![1]] } };+ let clef = c.clef_body();+ assert_eq!(clef["images"][0], "data:image/jpeg;base64,/w==");+ assert_eq!(clef["audio"][0], "data:audio/mpeg;base64,AQ==");+ assert!(clef.get("videos").is_none());+ assert_eq!(c.api_body()["audio"][0], "AQ==");+ assert_eq!(clef["questions"]["q"]["type"], "noul");+}diff --git a/tools/layers.toml b/tools/layers.tomlindex 810a3262..c175ff27 100644--- a/tools/layers.toml+++ b/tools/layers.toml@@ -26,6 +26,7 @@ raea-io-os = "io"raea-io-trace = "io"raea-io-media = "io"raea-io-assets = "io"+raea-io-clef = "io"raea-io-gen = "io"raea-io-gen-comfy = "io"raea-io-gen-core = "io"