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
raea a58fe84a985bdeb8b965446abd7757c352811012
shinyobjectz46e4b5295b1d
diff --git a/.gitignore b/.gitignoreindex 6e24ab4c..deca5b81 100644--- a/.gitignore+++ b/.gitignore@@ -98,3 +98,6 @@ docs/craft/phase9/!.env.example# a session's throwaway scripts beside the SDK (sdk/raea/.scratch-N/), never committedsdk/raea/.scratch-*/++# the Tripo CLI writes its last task id into the directory it runs in+.tripo/diff --git a/io/gen-core/src/lib.rs b/io/gen-core/src/lib.rsindex 97963965..8f81f763 100644--- a/io/gen-core/src/lib.rs+++ b/io/gen-core/src/lib.rs@@ -1,7 +1,7 @@//! Generation flows' ground. A flow (flow.rs) names generation steps by what they make (image.generate,//! video.generate, audio.sfx, mesh.generate, …), its ops in one table (types.rs writes it as raea/gen's TypeScript);//! the hosted backends a step runs on are here too: made.app (one key for 118 image, video and audio models at the-//! provider's price), fal, Replicate, OpenRouter, Modal endpoints and Fish Audio's speech. ComfyUI is raea-io-gen-comfy; routing and running+//! provider's price), fal, Replicate, OpenRouter, Modal endpoints, Fish Audio's speech and Tripo 3D (its own CLI, the founder's key). ComfyUI is raea-io-gen-comfy; routing and running//! are raea-io-gen.pub mod direct;@@ -13,6 +13,7 @@ pub mod made;pub mod modal;pub mod openrouter;pub mod replicate;+pub mod tripo;pub mod types;/// A setting: the environment, then raea's settings file (raea_io_home::setting).diff --git a/io/gen-core/src/tripo.rs b/io/gen-core/src/tripo.rsnew file mode 100644index 00000000..ac93452b--- /dev/null+++ b/io/gen-core/src/tripo.rs@@ -0,0 +1,207 @@+//! Tripo 3D through Tripo's own CLI (`npm install -g tripo-cli`, the `tripo` binary), on the founder's own key: a step+//! whose model is `tripo:<model>` (`tripo:` alone is Tripo's default, P2; `tripo:H3.1` the denser, cheaper H series).+//! The CLI does the upload, the polling and the download, and prints one JSON line (`model_file`, `preview`,+//! `credits_consumed`), so raea reads that and nothing else.+//!+//! The key: TRIPO_API_KEY (the environment, then ~/.raea/env), else whatever `tripo login` saved in ~/.tripo. Each user+//! brings their own; raea never ships one.+//!+//! **Credits live in the API wallet, not the app's.** A key draws on https://developers.tripo3d.ai/en/billing (the+//! API platform). Credits bought on the main tripo3d.ai dashboard (the Studio web app) are a separate wallet the API+//! never sees: on 2026-11-05 a freshly topped-up Studio account still answered `balance 0` and exit 4 until credits+//! were added on the developers billing page. Every insufficient-credits error below says so.+//!+//! Price: Tripo bills credits; one credit is 1¢ (RAEA_TRIPO_CENTS_PER_CREDIT overrides), the same as fal's resale of+//! the same models (`fal:tripo3d/...`, priced in credits at $0.01). A plan quotes with `tripo make --dry-run`, which+//! sends nothing.++use std::path::{Path, PathBuf};+use std::process::Command;++use serde_json::{Map, Value as J};++use crate::setting;++/// Where a key's credits come from (not the tripo3d.ai dashboard's wallet).+pub const BILLING: &str = "https://developers.tripo3d.ai/en/billing";++/// Why a Tripo step failed, so routing can tell "no credits" (nothing was submitted) from everything else.+#[derive(Debug)]+pub enum Fail {+ /// exit 4: the key's API wallet is empty; nothing was submitted or charged+ Credits(String),+ /// exit 3: no key, a bad key, or a key for the other region+ Auth(String),+ Other(String),+}++impl std::fmt::Display for Fail {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ match self {+ Fail::Credits(m) | Fail::Auth(m) | Fail::Other(m) => f.write_str(m),+ }+ }+}++/// The CLI's binary: RAEA_TRIPO_BIN, else `tripo` on PATH.+pub fn bin() -> String {+ setting("RAEA_TRIPO_BIN").unwrap_or_else(|| "tripo".into())+}++pub fn cents_per_credit() -> f64 {+ setting("RAEA_TRIPO_CENTS_PER_CREDIT").and_then(|c| c.parse().ok()).unwrap_or(1.0)+}++/// Whether this host can run Tripo itself: the CLI answers, and a key is set or `tripo login` saved one.+pub fn available() -> bool {+ let has_key = setting("TRIPO_API_KEY").is_some() || home_dir().join(".tripo/config.json").exists();+ has_key && Command::new(bin()).arg("--version").output().is_ok_and(|o| o.status.success())+}++fn home_dir() -> PathBuf {+ std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default()+}++fn command() -> Command {+ let mut c = Command::new(bin());+ // the CLI asks its host to name itself on every call (its agent docs); a user's own value wins+ if std::env::var_os("TRIPO_CLIENT_APP").is_none() {+ c.env("TRIPO_CLIENT_APP", "raea");+ }+ if let Some(k) = setting("TRIPO_API_KEY") {+ c.env("TRIPO_API_KEY", k);+ }+ if let Some(r) = setting("TRIPO_REGION") {+ c.env("TRIPO_REGION", r);+ }+ c+}++/// `tripo make`'s arguments for a step: its inputs (a prompt, or 1 image, or 2-4 views as `image` + `refs`, as local+/// paths or URLs), the model, seed, and every x_<name> as `-p name=value` (Tripo's own parameter names:+/// x_texture_quality=detailed, x_face_limit=8000, x_pbr=true). `texture: false` asks for bare geometry.+pub fn args(model: &str, inputs: &Map<String, J>, media: &[String], out: &Path, dry: bool) -> Vec<String> {+ let mut a: Vec<String> = vec!["make".into()];+ if media.is_empty() {+ a.push(inputs.get("prompt").and_then(|p| p.as_str()).unwrap_or("").to_string());+ } else {+ a.extend(media.iter().take(4).cloned());+ }+ if !model.is_empty() {+ a.extend(["--model".into(), model.to_string()]);+ }+ if let Some(s) = inputs.get("seed").and_then(|s| s.as_u64()) {+ a.extend(["--seed".into(), s.to_string()]);+ }+ if inputs.get("texture") == Some(&J::Bool(false)) {+ a.extend(["-p".into(), "texture=false".into()]);+ }+ for (k, v) in inputs {+ if let Some(name) = k.strip_prefix("x_") {+ let v = match v { J::String(s) => s.clone(), other => other.to_string() };+ a.extend(["-p".into(), format!("{name}={v}")]);+ }+ }+ a.extend(["--json".into(), "--yes".into(), "--no-open".into(), "--quiet".into()]);+ if dry {+ a.push("--dry-run".into());+ } else {+ a.extend(["-o".into(), out.display().to_string()]);+ }+ a+}++fn last_json(stdout: &[u8]) -> Option<J> {+ String::from_utf8_lossy(stdout).lines().rev().find_map(|l| serde_json::from_str::<J>(l.trim()).ok())+}++fn fail(code: Option<i32>, stdout: &[u8], stderr: &[u8]) -> Fail {+ let said = last_json(stdout).map(|v| v["error"]["message"].as_str().or(v["message"].as_str()).or(v["error"].as_str()).map(str::to_string).unwrap_or(v.to_string()))+ .unwrap_or_else(|| String::from_utf8_lossy(stderr).lines().filter(|l| !l.trim().is_empty()).take(3).collect::<Vec<_>>().join(" | "));+ match code {+ Some(4) => Fail::Credits(format!("tripo: insufficient credits ({said}). A key's credits are the API wallet's: add them at {BILLING} (not the tripo3d.ai dashboard, a separate wallet), or `tripo topup`")),+ Some(3) => Fail::Auth(format!("tripo: no usable key ({said}). Set TRIPO_API_KEY=tsk_… in ~/.raea/env (from {}), or run `tripo login`; `tripo doctor` explains a region mismatch", BILLING.replace("/billing", "/api-keys"))),+ Some(5) => Fail::Other(format!("tripo: refused by content policy ({said})")),+ Some(6) => Fail::Other(format!("tripo: the task failed, credits refunded ({said})")),+ Some(c) => Fail::Other(format!("tripo make exited {c}: {said}")),+ None => Fail::Other(format!("tripo make was killed: {said}")),+ }+}++/// The credits a step would cost, from `tripo make --dry-run` (no upload, no submit, nothing billed). None when Tripo+/// publishes no estimate (P1, legacy models, chained steps): never read as zero.+pub fn quote(model: &str, inputs: &Map<String, J>, media: &[String]) -> Result<Option<u64>, String> {+ let o = command().args(args(model, inputs, media, Path::new("."), true)).output().map_err(|e| format!("tripo didn't start ({e}): npm install -g tripo-cli"))?;+ if !o.status.success() {+ return Err(fail(o.status.code(), &o.stdout, &o.stderr).to_string());+ }+ let v = last_json(&o.stdout).ok_or("tripo --dry-run printed no JSON")?;+ if v["valid"] == false {+ return Err(format!("tripo: {}", v["errors"]));+ }+ Ok(v["generation_credits_estimate"].as_u64())+}++/// What a step made: the model file first, then its preview render, and what it cost in credits.+pub struct Made {+ pub files: Vec<PathBuf>,+ pub credits: u64,+ pub task: Option<String>,+}++/// One step through `tripo make`, its files kept in `out`. Blocks until the CLI is done (it polls Tripo itself).+pub fn run(model: &str, inputs: &Map<String, J>, media: &[String], out: &Path) -> Result<Made, Fail> {+ // absolute: the CLI runs inside `out`, so a relative one would nest a second copy of itself there+ let out = &std::path::absolute(out).unwrap_or(out.to_path_buf());+ std::fs::create_dir_all(out).map_err(|e| Fail::Other(format!("{}: {e}", out.display())))?;+ let o = command().current_dir(out).args(args(model, inputs, media, out, false)).output().map_err(|e| Fail::Other(format!("tripo didn't start ({e}): npm install -g tripo-cli")))?;+ if !o.status.success() {+ return Err(fail(o.status.code(), &o.stdout, &o.stderr));+ }+ let v = last_json(&o.stdout).ok_or(Fail::Other("tripo make printed no JSON".into()))?;+ let at = |k: &str| v[k].as_str().map(|p| under(out, p));+ let dir = at("output_dir").unwrap_or(out.to_path_buf());+ let mut files: Vec<PathBuf> = [at("model_file"), at("preview")].into_iter().flatten().collect();+ if files.is_empty() {+ files = v["files"].as_array().into_iter().flatten().filter_map(|f| f.as_str()).map(|f| dir.join(f)).filter(|f| !is_json(f)).collect();+ }+ files.retain(|f| f.exists());+ if files.is_empty() {+ return Err(Fail::Other(format!("tripo make answered with no files: {}", v.to_string().chars().take(300).collect::<String>())));+ }+ Ok(Made { files, credits: v["credits_consumed"].as_u64().unwrap_or(0), task: v["task_id"].as_str().map(str::to_string) })+}++/// The CLI's own task record, not a made file.+fn is_json(f: &Path) -> bool {+ f.extension().is_none_or(|e| e == "json")+}++/// A path the CLI printed: as it is when absolute, else under the directory it ran in.+fn under(out: &Path, p: &str) -> PathBuf {+ let p = Path::new(p);+ if p.is_absolute() { p.to_path_buf() } else { out.join(p) }+}++/// The fal endpoint serving the same Tripo model, for a host without the CLI or a key with no credits: H3.1 by+/// default (fal names Tripo's models h3.1, p1, p2), by what the step is given.+pub fn fal_twin(model: &str, views: usize) -> String {+ let m = match model.to_ascii_lowercase().trim_start_matches("tripo-") {+ "" | "p2" | "p2.0" => "p2",+ "p1" | "p1.0" => "p1",+ _ => "h3.1",+ }+ .to_string();+ let kind = match views { 0 => "text-to-3d", 1 => "image-to-3d", _ => "multiview-to-3d" };+ format!("tripo3d/{m}/{kind}")+}++/// The key's balance in credits (`tripo balance`), for `raea gen balance`.+pub fn balance() -> Result<(u64, u64), String> {+ let o = command().args(["balance", "--json"]).output().map_err(|e| format!("tripo didn't start ({e})"))?;+ if !o.status.success() {+ return Err(fail(o.status.code(), &o.stdout, &o.stderr).to_string());+ }+ let v = last_json(&o.stdout).ok_or("tripo balance printed no JSON")?;+ Ok((v["balance"].as_u64().unwrap_or(0), v["frozen"].as_u64().unwrap_or(0)))+}diff --git a/io/gen/src/cli.rs b/io/gen/src/cli.rsindex 9027280e..4ce947c2 100644--- a/io/gen/src/cli.rs+++ b/io/gen/src/cli.rs@@ -10,8 +10,8 @@ use crate::made::Made;use crate::run::{Local, Run};pub const USAGE: &str = "raea gen models [--kind image|video|audio] [--query WORDS] | balance | types [-o FILE] | flow FLOW.ts [-o FLOW.json]- raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" [--model M] [--image FILE]... [--seconds S] [--aspect W:H] [-o DIR] [--max-cents N] [--plan]- raea gen plan FLOW.json|FLOW.ts [--exact] | raea gen run FLOW.json|FLOW.ts [-o DIR] [--max-cents N] [--exact] [--comfy-on-replicate] [--no-local]+ raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" [--model M] [--image FILE]... [--seconds S] [--aspect W:H] [-o DIR] [--max-cents N] [--plan] (mesh: --model tripo:H3.1|tripo:P2|fal:<endpoint>)+ raea gen plan FLOW.json|FLOW.ts [--exact] | raea gen run FLOW.json|FLOW.ts [-o DIR] [--max-cents N] [--exact] [--comfy-on-replicate] [--no-local] [--no-tripo]raea gen comfy import WORKFLOW.json [-o FLOW.json] | comfy export FLOW.json|FLOW.ts [-o WORKFLOW.json] | comfy needs WORKFLOW.json [-o NEEDS.json]raea gen comfy run WORKFLOW.json [-o DIR] (any workflow as it is, on the ComfyUI server: its input files uploaded, every output fetched)raea gen comfy view WORKFLOW.json [-o FILE] | comfy set WORKFLOW.json CHANGES.json (nodes, settings by name, links, groups; edits written back)@@ -72,6 +72,7 @@ fn runner<'a>(args: &[String], base: &Path, local: Option<&'a dyn Local>) -> Run}r.policy.exact = args.iter().any(|a| a == "--exact");r.policy.comfy_on_replicate = args.iter().any(|a| a == "--comfy-on-replicate") || crate::setting("RAEA_COMFY_ON") .as_deref() == Some("replicate");+ r.policy.tripo = !args.iter().any(|a| a == "--no-tripo") && crate::tripo::available();if let Some(l) = local.filter(|_| !args.iter().any(|a| a == "--no-local")) {r.policy.local = l.names();r.local = Some(l);@@ -94,7 +95,12 @@ pub fn command(args: &[String], local: Option<&dyn Local>) -> Result<String, Str}Ok(out.trim_end().to_string())}- "balance" => Ok(format!("{:.1} credits (${:.2}) on made.app", Made::from_settings()?.balance_cents()? as f64 / 10.0, Made::from_settings()?.balance_cents()? as f64 / 100.0)),+ "balance" => {+ let made = Made::from_settings().and_then(|m| m.balance_cents()).map(|c| format!("{:.1} credits (${:.2}) on made.app", c as f64 / 10.0, c as f64 / 100.0)).unwrap_or_else(|e| format!("made.app: {e}"));+ // a Tripo key's credits are its API wallet (developers.tripo3d.ai/en/billing), not the tripo3d.ai dashboard's+ let tripo = crate::tripo::balance().map(|(b, f)| format!("{b} credits ({f} frozen) on Tripo's API wallet, {}", crate::tripo::BILLING)).unwrap_or_else(|e| format!("tripo: {e}"));+ Ok(format!("{made}\n{tripo}"))+ }"plan" | "run" => {let path = args.get(1).ok_or(USAGE)?;let flow = read_flow(path)?;diff --git a/io/gen/src/hosted.rs b/io/gen/src/hosted.rsindex 4b22d93f..189fc2f4 100644--- a/io/gen/src/hosted.rs+++ b/io/gen/src/hosted.rs@@ -137,3 +137,35 @@ impl Run<'_> {Ok((Made1 { files: vec![file], ..Default::default() }, cents))}}++impl Run<'_> {+ /// A mesh step through the tripo CLI: a prompt, or its pictures as local files (the CLI uploads them; a step that+ /// made only a URL hands the URL on). Returns the model file and its preview, and the cost in cents.+ pub(crate) fn tripo(&self, model: &str, s: &Step, key: &str, done: &BTreeMap<String, Made1>) -> Result<(Made1, u64), crate::tripo::Fail> {+ let media = self.tripo_media(s, done).map_err(crate::tripo::Fail::Other)?;+ let lit: Map<String, J> = s.inputs.iter().filter(|(_, v)| reference(v).is_none() && !matches!(v, J::Array(a) if a.iter().any(|x| reference(x).is_some()))).map(|(k, v)| (k.clone(), v.clone())).collect();+ let m = crate::tripo::run(model, &lit, &media, &stems(self, key, 0))?;+ let cents = (m.credits as f64 * crate::tripo::cents_per_credit()).ceil() as u64;+ Ok((Made1 { files: m.files, job: m.task.map(|t| format!("tripo:{t}")), url: None }, cents))+ }++ /// The step's pictures for Tripo, `image` first then `refs` (2-4 views make a multiview model).+ pub(crate) fn tripo_media(&self, s: &Step, done: &BTreeMap<String, Made1>) -> Result<Vec<String>, String> {+ let mut out = Vec::new();+ for k in ["image", "refs"] {+ let vals: Vec<&J> = match s.inputs.get(k) { Some(J::Array(a)) => a.iter().collect(), Some(v) => vec![v], None => vec![] };+ for v in vals {+ let Some(r) = reference(v) else { continue };+ let up = done.get(r).ok_or(format!("@{r} isn't made yet"))?;+ let file = if crate::flow::index(v).is_some() { crate::run::file_of(done, v).cloned() } else { up.files.first().cloned() };+ match (file, &up.url) {+ // absolute: the CLI runs in the step's own folder, so a path relative to the run's -o would miss+ (Some(f), _) => out.push(std::path::absolute(&f).unwrap_or(f).display().to_string()),+ (None, Some(u)) => out.push(u.clone()),+ _ => return Err(format!("@{r} made nothing")),+ }+ }+ }+ Ok(out)+ }+}diff --git a/io/gen/src/lib.rs b/io/gen/src/lib.rsindex 9b489d6c..b5fc599f 100644--- a/io/gen/src/lib.rs+++ b/io/gen/src/lib.rs@@ -10,6 +10,8 @@ pub mod route;pub mod run;#[cfg(test)]mod tests;+#[cfg(test)]+mod tests_tripo;pub use raea_io_gen_comfy as comfy;-pub use raea_io_gen_core::{direct, fal, fish, flow, http, made, modal, openrouter, replicate, setting, types};+pub use raea_io_gen_core::{direct, fal, fish, flow, http, made, modal, openrouter, replicate, setting, tripo, types};diff --git a/io/gen/src/route.rs b/io/gen/src/route.rsindex 6594b892..497fdcfc 100644--- a/io/gen/src/route.rs+++ b/io/gen/src/route.rs@@ -1,5 +1,6 @@//! Where each step runs. A step that names its model goes there (`made:<id>`, `fal:<endpoint>`,-//! `replicate:<owner/name>`, `openrouter:<model>`, `modal:<endpoint>`, `fish:<model>`, `comfy`, `local:<name>`). text.generate goes to+//! `replicate:<owner/name>`, `openrouter:<model>`, `modal:<endpoint>`, `fish:<model>`, `tripo:<model>`, `comfy`, `local:<name>`). mesh.generate goes to+//! Tripo 3D: through the tripo CLI on the founder's own key when this host has both (tripo.rs), else the same Tripo model on fal. text.generate goes to//! OpenRouter (RAEA_GEN_TEXT_MODEL, else Kimi). Otherwise: a `comfy` step on the ComfyUI server; a step with ComfyUI weights on the server too when//! the flow asks for the exact weights (`--exact`), else made's model for that op, which is noted as standing in for//! them; a local model when the host has one for the op (sao for effects); made for the rest.@@ -17,6 +18,8 @@ pub enum Backend {Modal(String),/// Fish Audio's text-to-speech, with the founder's FISH_API_KEY (raea-io-gen-core's fish.rs)Fish(String),+ /// Tripo 3D through its own CLI and the founder's key (raea-io-gen-core's tripo.rs); the name is Tripo's model id or alias+ Tripo(String),Comfy,Local(String),Load,@@ -33,6 +36,7 @@ impl std::fmt::Display for Backend {Backend::OpenRouter(m) => write!(f, "openrouter:{m}"),Backend::Modal(m) => write!(f, "modal:{m}"),Backend::Fish(m) => write!(f, "fish:{}", if m.is_empty() { crate::fish::DEFAULT_MODEL } else { m }),+ Backend::Tripo(m) => write!(f, "tripo:{m}"),Backend::Comfy => write!(f, "comfy"),Backend::Local(m) => write!(f, "local:{m}"),Backend::Load => write!(f, "load"),@@ -80,6 +84,8 @@ pub struct Policy {pub local: Vec<String>,/// comfy steps go to Replicate's any-comfyui-workflow rather than a ComfyUI server (RAEA_COMFY_URL)pub comfy_on_replicate: bool,+ /// the tripo CLI and a key are on this host (tripo::available), so mesh steps run on Tripo itself+ pub tripo: bool,}/// Where a step runs, and a note when it stands in for something it was asked for.@@ -93,9 +99,10 @@ pub fn route(s: &Step, p: &Policy) -> Result<(Backend, Option<String>), String>"openrouter" => Backend::OpenRouter(name.into()),"modal" => Backend::Modal(name.into()),"fish" => Backend::Fish(name.into()),+ "tripo" => Backend::Tripo(name.into()),"comfy" => Backend::Comfy,"local" => Backend::Local(name.into()),- _ => return Err(format!("model `{m}`: say made:<id>, fal:<endpoint>, replicate:<owner/name>, openrouter:<model>, modal:<endpoint>, fish:<model>, comfy or local:<name>")),+ _ => return Err(format!("model `{m}`: say made:<id>, fal:<endpoint>, replicate:<owner/name>, openrouter:<model>, modal:<endpoint>, fish:<model>, tripo:<model>, comfy or local:<name>")),}, None));}match s.op.as_str() {@@ -105,8 +112,13 @@ pub fn route(s: &Step, p: &Policy) -> Result<(Backend, Option<String>), String>"comfy" => return Ok((Backend::Comfy, None)),"text.generate" => return Ok((Backend::OpenRouter(crate::setting("RAEA_GEN_TEXT_MODEL").unwrap_or_else(|| "moonshotai/kimi-k3.1-pro".into())), None)),"mesh.generate" => {- let e = if s.inputs.contains_key("image") { "fal-ai/hunyuan-3d/v3.1/rapid/image-to-3d" } else { "fal-ai/hunyuan-3d/v3.1/rapid/text-to-3d" };- return Ok((Backend::Fal(e.into()), None));+ // Tripo by default (hunyuan-3d rapid on fal errored three times running, 10-29): its CLI on the founder's key when+ // the host has both, else fal's resale of the same model+ if p.tripo {+ return Ok((Backend::Tripo(String::new()), None));+ }+ let views = usize::from(s.inputs.contains_key("image")) + s.inputs.get("refs").and_then(|r| r.as_array()).map_or(0, Vec::len);+ return Ok((Backend::Fal(crate::tripo::fal_twin("", views)), Some("no tripo CLI with a key here (npm install -g tripo-cli; TRIPO_API_KEY): the same Tripo model on fal".into())));}_ => {}}diff --git a/io/gen/src/run.rs b/io/gen/src/run.rsindex a2cafcea..84df4ea2 100644--- a/io/gen/src/run.rs+++ b/io/gen/src/run.rs@@ -115,6 +115,15 @@ impl<'a> Run<'a> {let c = crate::fish::quote(s.inputs.get("text").and_then(|t| t.as_str()).unwrap_or(""));total += c;row["cents"] = json!(c);+ } else if let Backend::Tripo(m) = &b {+ // a plan uploads nothing: each picture input counts as one view+ let views = ["image", "refs"].iter().map(|k| match s.inputs.get(*k) { Some(J::Array(a)) => a.len(), Some(_) => 1, None => 0 }).sum::<usize>();+ let media: Vec<String> = (0..views).map(|k| format!("https://example.invalid/view{k}.png")).collect();+ match crate::tripo::quote(m, &s.inputs, &media) {+ Ok(Some(c)) => { let cents = (c as f64 * crate::tripo::cents_per_credit()).ceil() as u64; total += cents; row["cents"] = json!(cents); row["credits"] = json!(c); }+ Ok(None) => row["quote"] = json!("Tripo publishes no estimate for this model (never zero)"),+ Err(e) => row["quote"] = json!(e),+ }} else if let Backend::Fal(e) = &b {if let Ok((c, unit)) = Fal::from_settings().and_then(|f| f.price(e)) {row["cents_per"] = json!(format!("{c:.1} per {unit}"));@@ -170,6 +179,30 @@ impl<'a> Run<'a> {self.made(made.as_ref().unwrap(), m, s, key, &done, &mut spent)?}Backend::Fal(e) => (self.fal(e, &s, key, &done)?, 0),+ Backend::Tripo(m) => {+ // the credits are known before sending (tripo make --dry-run): held to the run's cap like a made step+ let media = self.tripo_media(s, &done)?;+ if let Some(c) = crate::tripo::quote(m, &s.inputs, &media).ok().flatten() {+ let charge = (c as f64 * crate::tripo::cents_per_credit()).ceil() as u64;+ if spent + charge > self.max_cents {+ return Err(format!("{b} would cost {charge}¢ ({c} credits), past this run's cap of {}¢ ({spent}¢ spent): raise --max-cents or RAEA_GEN_MAX_CENTS", self.max_cents));+ }+ }+ match self.tripo(m, s, key, &done) {+ Ok((m1, c)) => { spent += c; (m1, c) }+ // no credits or no key: nothing was submitted, so the same model on fal (FAL_KEY) runs instead,+ // unless RAEA_TRIPO_FALLBACK=0+ Err(crate::tripo::Fail::Credits(e) | crate::tripo::Fail::Auth(e)) if crate::setting("FAL_KEY").is_some() && crate::setting("RAEA_TRIPO_FALLBACK").as_deref() != Some("0") => {+ let views = media.len();+ let twin = crate::tripo::fal_twin(m, views);+ eprintln!("raea gen: {id}: {e}\nraea gen: {id} runs on fal:{twin} instead (RAEA_TRIPO_FALLBACK=0 stops this)");+ let mut m1 = self.fal(&twin, s, key, &done)?;+ m1.job = Some(format!("fal:{twin}"));+ (m1, 0)+ }+ Err(e) => return Err(e.to_string()),+ }+ }Backend::Replicate(m) => (self.replicate(m, &s, key, &done)?, 0),Backend::OpenRouter(m) => self.openrouter(m, &s, key, &done)?,Backend::Modal(m) => self.modal(m, &s, key, &done)?,@@ -356,8 +389,25 @@ fn inline_text(s: &Step, done: &BTreeMap<String, Made1>) -> Step {/// An output's files under the output's name: one file as `<name>.<ext>`, several (a mesh and its textures) as/// `<name>/` holding them, and a GLB among them also as `<name>.glb`. Replaced on every run, so the name always holds the latest result.+#[cfg(test)]+pub(crate) fn name_output_for_test(dir: &Path, name: &str, files: &[PathBuf]) -> Result<Vec<PathBuf>, String> {+ name_output(dir, name, files)+}+fn name_output(dir: &Path, name: &str, files: &[PathBuf]) -> Result<Vec<PathBuf>, String> {- let copy = |from: &Path, to: &Path| std::fs::copy(from, to).map(|_| to.to_path_buf()).map_err(|e| format!("{}: {e}", to.display()));+ let copy = |from: &Path, to: &Path| {+ // a name that already is the file (a link to it, or the file itself) is left alone: copying a file onto itself+ // truncates it to nothing (11-05: four Tripo models lost their step files so). A link elsewhere is replaced.+ if let (Ok(a), Ok(b)) = (std::fs::canonicalize(from), std::fs::canonicalize(to)) {+ if a == b {+ return Ok(to.to_path_buf());+ }+ }+ if to.is_symlink() {+ let _ = std::fs::remove_file(to);+ }+ std::fs::copy(from, to).map(|_| to.to_path_buf()).map_err(|e| format!("{}: {e}", to.display()))+ };match files {[] => Ok(vec![]),[one] if one.parent() == Some(dir) => {diff --git a/io/gen/src/tests_tripo.rs b/io/gen/src/tests_tripo.rsnew file mode 100644index 00000000..5d0d9bdd--- /dev/null+++ b/io/gen/src/tests_tripo.rs@@ -0,0 +1,42 @@+//! raea gen's Tripo tests: routing, the CLI's arguments, and naming outputs (kept apart from tests.rs for its size).+use serde_json::json;++use crate::flow::Step;+use crate::route::{Backend, Policy, route};++#[test]+fn tripo_routes_and_args() {+ let mut s = Step::new("mesh.generate", json!({"prompt": "a CRT television", "x_texture_quality": "detailed", "x_face_limit": 8000, "seed": 7}));+ // a host with the CLI and a key: Tripo itself; without: the same model on fal+ assert_eq!(route(&s, &Policy { tripo: true, ..Default::default() }).unwrap().0, Backend::Tripo(String::new()));+ assert_eq!(route(&s, &Policy::default()).unwrap().0, Backend::Fal("tripo3d/p2/text-to-3d".into()));+ s.model = Some("tripo:H3.1".into());+ assert_eq!(route(&s, &Policy::default()).unwrap().0, Backend::Tripo("H3.1".into()));+ let a = crate::tripo::args("H3.1", &s.inputs, &[], std::path::Path::new("/tmp/o"), false);+ let line = a.join(" ");+ assert!(line.starts_with("make a CRT television --model H3.1 --seed 7"), "{line}");+ assert!(line.contains("-p texture_quality=detailed") && line.contains("-p face_limit=8000") && line.ends_with("-o /tmp/o"), "{line}");+ // pictures replace the prompt; a dry run writes nothing+ let a = crate::tripo::args("", &s.inputs, &["/x/front.png".into(), "/x/back.png".into()], std::path::Path::new("."), true);+ assert_eq!((a[1].as_str(), a[2].as_str(), a.last().unwrap().as_str()), ("/x/front.png", "/x/back.png", "--dry-run"));+ assert_eq!(crate::tripo::fal_twin("H3.1", 1), "tripo3d/h3.1/image-to-3d");+ assert_eq!(crate::tripo::fal_twin("tripo-p1", 3), "tripo3d/p1/multiview-to-3d");+}++#[test]+fn naming_an_output_never_truncates_it() {+ let dir = std::env::temp_dir().join(format!("raea-gen-name-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(dir.join("k")).unwrap();+ let glb = dir.join("k/model.glb");+ std::fs::write(&glb, b"glTF-bytes").unwrap();+ let png = dir.join("k/preview.png");+ std::fs::write(&png, b"png").unwrap();+ // someone linked the name to the step's file already+ #[cfg(unix)]+ std::os::unix::fs::symlink(&glb, dir.join("prop.glb")).unwrap();+ crate::run::name_output_for_test(&dir, "prop", &[glb.clone(), png]).unwrap();+ assert_eq!(std::fs::read(&glb).unwrap(), b"glTF-bytes");+ assert_eq!(std::fs::read(dir.join("prop.glb")).unwrap(), b"glTF-bytes");+ let _ = std::fs::remove_dir_all(&dir);+}diff --git a/sdk/guides/craft/motion/gen.md b/sdk/guides/craft/motion/gen.mdindex ec86cf59..e2696415 100644--- a/sdk/guides/craft/motion/gen.md+++ b/sdk/guides/craft/motion/gen.md@@ -38,10 +38,20 @@`gen.jsonl` index. A step that is already there isn't run again, and a changed prompt reruns only what comes afterit, so edit and rerun freely.- Pick a model only when the piece needs one. Without one, each op goes to its default: made.app for pictures, video- and audio, OpenRouter (Kimi) for words, fal for meshes, this Mac's sao for effects, and made.app for speech. To name a+ and audio, OpenRouter (Kimi) for words, Tripo for meshes (its own `tripo` CLI on your key when this Mac has both, else the same Tripo model on fal), this Mac's sao for effects, and made.app for speech. To name amodel, use `{ model: "made:kling_3_pro" }`, `"fal:<endpoint>"`, `"replicate:owner/name"`, `"openrouter:<model>"`,- `"modal:<name>"`, `"fish:<model>"` (Fish Audio, with your FISH_API_KEY), `"comfy"` or `"local:sao"`. `raea gen models` lists made's ids. A made model's own setting goes in+ `"modal:<name>"`, `"fish:<model>"` (Fish Audio, with your FISH_API_KEY), `"tripo:H3.1"` or `"tripo:P2"` (Tripo 3D through its CLI), `"comfy"` or `"local:sao"`. `raea gen models` lists made's ids. A made model's own setting goes inas `x_<name>`.+- Meshes on Tripo (`npm install -g tripo-cli`, then `TRIPO_API_KEY=tsk_…` in ~/.raea/env or `tripo login`; every user+ brings their own key). Feed it a picture rather than words: an image step making a clean product shot (one object,+ plain light background, three-quarter view) gives far better geometry than a prompt. Tripo's own settings go in as+ x_<name>: `x_face_limit: 15000` (a raw H3.1 model can be 1.5 million triangles and 40 MB, too heavy for a live+ scene), `x_texture_quality: "detailed"`, `x_pbr: true`, `x_auto_size: true` (real metres). `tripo:H3.1` costs+ 20-50 credits a model, `tripo:P2` (Tripo's default, clean low topology) 100-130; a credit is 1¢, and `raea gen plan`+ quotes it with `tripo make --dry-run`. **Credits are the API wallet's:** buy them at+ https://developers.tripo3d.ai/en/billing, not on the tripo3d.ai dashboard, whose credits the key never sees (it+ answers "insufficient credits", exit 4). With no credits or no key, the step goes to fal's Tripo instead+ (RAEA_TRIPO_FALLBACK=0 stops that); `raea gen balance` shows both wallets.- Crops, resizes and side-by-sides between steps are free and run here: `image.crop`, `image.scale` (width, height,factor or megapixels; fit stretch, cover or contain) and `image.stitch` (a list of images, right or down).- ComfyUI: `raea gen comfy import workflow.json -o flow.json` turns a workflow into a flow. Sampler chains and