raea e699cf684509a8bbada118cc302c56e99065a680

This commit is contained in:
shinyobjectz committed 2026-11-05 17:19:37 -08:00
1 parent fb3f70844e
commit 1dff4f0aa8
384 files changed
+25178 -1781

No files matched your search

+10
View File
@@ -88,3 +88,13 @@ engine/media/real/
# phase-9 run material (footage frames, transcripts, briefs) is client data: it lives in ~/films/parts-9e/, never in git # phase-9 run material (footage frames, transcripts, briefs) is client data: it lives in ~/films/parts-9e/, never in git
docs/craft/phase9/ docs/craft/phase9/
.projects/cache
.projects/vault
.projects/state.test.json
.projects/state.local.test.json
.env
.env.*
!.env.example
# a session's throwaway scripts beside the SDK (sdk/raea/.scratch-N/), never committed
sdk/raea/.scratch-*/
Generated
+132 -7
View File
@@ -11193,6 +11193,17 @@ dependencies = [
"objc2-foundation 0.3.2", "objc2-foundation 0.3.2",
] ]
[[package]]
name = "objc2-metal-fx"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2db6f3a9d3b07481d9e5884f592aff6fd3f99e155423d1d1af3977e77a90ea0e"
dependencies = [
"objc2 0.6.5",
"objc2-foundation 0.3.2",
"objc2-metal 0.3.2",
]
[[package]] [[package]]
name = "objc2-quartz-core" name = "objc2-quartz-core"
version = "0.2.2" version = "0.2.2"
@@ -13295,6 +13306,7 @@ checksum = "019b4b213425016d7d84a153c4c73afb0946fbb4840e4eece7ba8848b9d6da22"
name = "raea-app-check" name = "raea-app-check"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"raea-core-brief",
"serde_json", "serde_json",
] ]
@@ -13360,6 +13372,7 @@ name = "raea-app-tools"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"raea-io-assets", "raea-io-assets",
"raea-io-gen",
"raea-io-home", "raea-io-home",
"raea-io-media", "raea-io-media",
"raea-runtime-bundle", "raea-runtime-bundle",
@@ -13367,6 +13380,14 @@ dependencies = [
"serde_json", "serde_json",
] ]
[[package]]
name = "raea-app-workspace"
version = "0.1.0"
dependencies = [
"raea-core-brief",
"serde_json",
]
[[package]] [[package]]
name = "raea-bench-swatch" name = "raea-bench-swatch"
version = "0.1.0" version = "0.1.0"
@@ -13415,6 +13436,7 @@ dependencies = [
"bevy_trauma_shake", "bevy_trauma_shake",
"bevy_tweening", "bevy_tweening",
"fastnoise-lite", "fastnoise-lite",
"moonshine-save",
"noise", "noise",
"noisy_bevy", "noisy_bevy",
"serde", "serde",
@@ -13470,13 +13492,13 @@ dependencies = [
"lightyear", "lightyear",
"lightyear_core", "lightyear_core",
"mock_instant", "mock_instant",
"moonshine-save",
"noisy_bevy", "noisy_bevy",
"raea-bench-swatch", "raea-bench-swatch",
"raea-bevy-adapters", "raea-bevy-adapters",
"raea-bevy-calls", "raea-bevy-calls",
"raea-bevy-world", "raea-bevy-world",
"raea-core-calls", "raea-core-calls",
"raea-io-home",
"raea-runtime-plugins", "raea-runtime-plugins",
"raea-sys-page", "raea-sys-page",
"rand_pcg", "rand_pcg",
@@ -13567,15 +13589,18 @@ dependencies = [
"raea-app-media", "raea-app-media",
"raea-app-play", "raea-app-play",
"raea-app-tools", "raea-app-tools",
"raea-app-workspace",
"raea-bevy-plugins", "raea-bevy-plugins",
"raea-core-alloc", "raea-core-alloc",
"raea-core-animate", "raea-core-animate",
"raea-core-brief",
"raea-core-program", "raea-core-program",
"raea-io-home", "raea-io-home",
"raea-io-media", "raea-io-media",
"raea-io-npm", "raea-io-npm",
"raea-io-trace", "raea-io-trace",
"raea-native", "raea-native",
"raea-neural",
"raea-render", "raea-render",
"raea-runtime-bake", "raea-runtime-bake",
"raea-runtime-export", "raea-runtime-export",
@@ -13584,6 +13609,7 @@ dependencies = [
"raea-runtime-react", "raea-runtime-react",
"raea-runtime-sound", "raea-runtime-sound",
"regex", "regex",
"serde",
"serde_json", "serde_json",
"wsx", "wsx",
] ]
@@ -13760,6 +13786,34 @@ dependencies = [
"serde_json", "serde_json",
] ]
[[package]]
name = "raea-io-gen"
version = "0.1.0"
dependencies = [
"image",
"raea-io-gen-comfy",
"raea-io-gen-core",
"raea-io-home",
"serde_json",
]
[[package]]
name = "raea-io-gen-comfy"
version = "0.1.0"
dependencies = [
"raea-io-gen-core",
"serde_json",
]
[[package]]
name = "raea-io-gen-core"
version = "0.1.0"
dependencies = [
"raea-io-home",
"serde_json",
"sha2 0.10.9",
]
[[package]] [[package]]
name = "raea-io-home" name = "raea-io-home"
version = "0.1.0" version = "0.1.0"
@@ -13804,6 +13858,7 @@ dependencies = [
"indexmap", "indexmap",
"junction", "junction",
"libc", "libc",
"raea-io-home",
"reqwest", "reqwest",
"serde", "serde",
"serde_json", "serde_json",
@@ -13820,6 +13875,7 @@ dependencies = [
"flate2", "flate2",
"htmd", "htmd",
"raea-core-calls", "raea-core-calls",
"raea-io-home",
"raea-io-net", "raea-io-net",
"rusqlite", "rusqlite",
"serde_json", "serde_json",
@@ -13876,6 +13932,14 @@ dependencies = [
"url", "url",
] ]
[[package]]
name = "raea-neural"
version = "0.1.0"
dependencies = [
"image",
"raea-runtime-bundle",
]
[[package]] [[package]]
name = "raea-page" name = "raea-page"
version = "0.1.0" version = "0.1.0"
@@ -13888,6 +13952,7 @@ dependencies = [
"raea-gpu-device", "raea-gpu-device",
"raea-io-media", "raea-io-media",
"raea-runtime-dom", "raea-runtime-dom",
"raea-runtime-edit",
"raea-runtime-input", "raea-runtime-input",
"raea-runtime-js", "raea-runtime-js",
"raea-runtime-plugins", "raea-runtime-plugins",
@@ -13910,27 +13975,56 @@ dependencies = [
"blitz-dom", "blitz-dom",
"blitz-traits", "blitz-traits",
"image", "image",
"raea-gpu-device",
"raea-io-media", "raea-io-media",
"raea-page", "raea-page",
"raea-runtime-bake", "raea-page-stage",
"raea-page-window",
"raea-runtime-dom", "raea-runtime-dom",
"raea-runtime-input", "raea-runtime-input",
"raea-runtime-js", "raea-runtime-js",
"raea-runtime-live", "raea-runtime-plugins",
"raea-runtime-react",
"raea-runtime-sound",
"raea-runtime-view", "raea-runtime-view",
"raea-sys-a11y", "raea-sys-a11y",
"raea-sys-fonts", "raea-sys-fonts",
"raea-sys-page", "raea-sys-page",
"raea-sys-tweak",
"serde_json", "serde_json",
"stylo", "stylo",
"tiny_http", "tiny_http",
]
[[package]]
name = "raea-page-stage"
version = "0.1.0"
dependencies = [
"bevy",
"blitz-dom",
"raea-gpu-device",
"raea-runtime-bake",
"raea-runtime-dom",
"raea-runtime-js",
"raea-runtime-live",
"raea-runtime-react",
"raea-runtime-sound",
"raea-sys-page",
"raea-sys-tweak",
"serde_json",
"wgpu", "wgpu",
] ]
[[package]]
name = "raea-page-window"
version = "0.1.0"
dependencies = [
"bevy",
"block2 0.6.2",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"raea-runtime-js",
"raw-window-handle",
"serde_json",
]
[[package]] [[package]]
name = "raea-perceive" name = "raea-perceive"
version = "0.1.0" version = "0.1.0"
@@ -13957,6 +14051,7 @@ dependencies = [
"raea-gpu-device", "raea-gpu-device",
"raea-io-media", "raea-io-media",
"raea-io-trace", "raea-io-trace",
"raea-render-raytrace",
"raea-runtime-gpuframe", "raea-runtime-gpuframe",
"raea-runtime-plugins", "raea-runtime-plugins",
"raea-runtime-scene3d", "raea-runtime-scene3d",
@@ -13988,6 +14083,17 @@ dependencies = [
"wgpu", "wgpu",
] ]
[[package]]
name = "raea-render-raytrace"
version = "0.1.0"
dependencies = [
"bevy",
"objc2 0.6.5",
"objc2-metal 0.3.2",
"objc2-metal-fx",
"wgpu",
]
[[package]] [[package]]
name = "raea-runtime-bake" name = "raea-runtime-bake"
version = "0.1.0" version = "0.1.0"
@@ -14022,6 +14128,7 @@ dependencies = [
"bevy", "bevy",
"image", "image",
"manifold-rust", "manifold-rust",
"raea-core-scene",
"raea-core-shape", "raea-core-shape",
"raea-io-media", "raea-io-media",
"raea-io-net", "raea-io-net",
@@ -14054,6 +14161,19 @@ dependencies = [
"vello", "vello",
] ]
[[package]]
name = "raea-runtime-edit"
version = "0.1.0"
dependencies = [
"bevy",
"blitz-dom",
"parley",
"raea-runtime-dom",
"raea-runtime-js",
"raea-sys-page",
"serde_json",
]
[[package]] [[package]]
name = "raea-runtime-encode" name = "raea-runtime-encode"
version = "0.1.0" version = "0.1.0"
@@ -14141,8 +14261,10 @@ dependencies = [
"bevy", "bevy",
"raea-bevy-world", "raea-bevy-world",
"raea-core-wire", "raea-core-wire",
"raea-io-home",
"raea-io-media", "raea-io-media",
"raea-io-net", "raea-io-net",
"raea-runtime-bundle",
"raea-runtime-jsengine", "raea-runtime-jsengine",
"serde", "serde",
"serde_json", "serde_json",
@@ -14415,6 +14537,7 @@ dependencies = [
"resvg", "resvg",
"serde_json", "serde_json",
"tiny-skia 0.12.0", "tiny-skia 0.12.0",
"ttf-parser",
"usvg", "usvg",
] ]
@@ -14658,6 +14781,7 @@ dependencies = [
"anyhow", "anyhow",
"half", "half",
"ort", "ort",
"raea-io-home",
"ureq 2.12.1", "ureq 2.12.1",
] ]
@@ -14706,6 +14830,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"image", "image",
"ocrs", "ocrs",
"raea-io-home",
"raea-sys-layout", "raea-sys-layout",
"raea-sys-vision", "raea-sys-vision",
"rten", "rten",
+9
View File
@@ -25,15 +25,21 @@ members = [
"engine/bevy-world", "engine/bevy-world",
"engine/bundle", "engine/bundle",
"engine/cli", "engine/cli",
"engine/neural",
"engine/modules", "engine/modules",
"engine/native", "engine/native",
"io/npm", "io/npm",
"engine/page", "engine/page",
"engine/page/host", "engine/page/host",
"engine/page/stage",
"engine/page/window",
"io/trace", "io/trace",
"io/codec", "io/codec",
"io/media", "io/media",
"io/assets", "io/assets",
"io/gen",
"io/gen-comfy",
"io/gen-core",
"io/home", "io/home",
"io/soft", "io/soft",
"io/av1", "io/av1",
@@ -87,12 +93,14 @@ members = [
"systems/image", "systems/image",
"runtime/twins", "runtime/twins",
"runtime/dom", "runtime/dom",
"runtime/edit",
"runtime/view", "runtime/view",
"runtime/encode", "runtime/encode",
"runtime/plugins", "runtime/plugins",
"runtime/input", "runtime/input",
"tools/perceive", "tools/perceive",
"engine/render", "engine/render",
"engine/render/raytrace",
"engine/seedling", "engine/seedling",
"runtime/react", "runtime/react",
"bench/bridge", "bench/bridge",
@@ -109,6 +117,7 @@ members = [
"runtime/scene", "runtime/scene",
"runtime/shared", "runtime/shared",
"apps/check", "apps/check",
"apps/workspace",
"apps/ci", "apps/ci",
"apps/tools", "apps/tools",
"apps/media", "apps/media",
+5 -2
View File
@@ -111,8 +111,11 @@ cargo build --release -p raea-cli --no-default-features
target/release/raea render sdk/react/bench/games/pong/edit.tsx -o pong.mp4 target/release/raea render sdk/react/bench/games/pong/edit.tsx -o pong.mp4
``` ```
`--no-default-features` builds the public engine. The default features add raea's hosted services, which aren't `--no-default-features` builds the public engine, as the releases are. The default features add one hosted service,
part of this repository. [docs/settings.md](docs/settings.md) lists the settings raea reads. Content Credentials signed by raea's signing server, which isn't part of this repository. raea sends nothing on its
own: no telemetry, crash reports or update checks. What reaches the network is what you ask for (a remote URL in a
composition, a model downloaded on first use, a `raea gen` step on a provider you hold a key for), and `RAEA_OFFLINE=1`
refuses all of it. [docs/settings.md](docs/settings.md) lists the settings raea reads.
## What's in here ## What's in here
+2
View File
@@ -7,4 +7,6 @@ publish = false
description = "`raea check`: the floor's measurable lines on an export, ranked P0-P3" description = "`raea check`: the floor's measurable lines on an export, ranked P0-P3"
[dependencies] [dependencies]
# taste.ts rules, as the raea CLI evaluates them (docs/projects.feature PJ0)
raea-core-brief = { path = "../../core/brief" }
serde_json = "1" serde_json = "1"
+20 -66
View File
@@ -7,9 +7,9 @@
//! manifest (`raea render … --manifest render.json`): text clipped off the frame, text in the platform's UI zones, //! manifest (`raea render … --manifest render.json`): text clipped off the frame, text in the platform's UI zones,
//! text held too briefly to read, caption contrast against the pixels behind it. With the transcript too: captions //! text held too briefly to read, caption contrast against the pixels behind it. With the transcript too: captions
//! that come on away from the word they carry. With the face's place (`--perception`, the perception.json `raea cut` //! that come on away from the word they carry. With the face's place (`--perception`, the perception.json `raea cut`
//! writes): text over more than 8% of the face. With `--taste FILE|DIR`: the person's own mechanical rules, from the //! writes): text over more than 8% of the face. With `--taste taste.ts|DIR`: the person's own mechanical rules, the
//! `## Checks` section of their taste briefs (`- text-above 62%: Captions sit clear of the bottom.`), each a P1 when //! rules in their taste.ts files that carry a check (`{ text: "Captions sit clear of the bottom.", check: { form:
//! broken, since the person's rule beats the floor's default (docs/craft-system.md, J). Exits 1 when a P0 or P1 is found. //! "text-above", value: 62 } }`), each a P1 when broken, since the person's rule beats the floor's default (docs/craft-system.md, J). Exits 1 when a P0 or P1 is found.
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::process::Command; use std::process::Command;
@@ -20,6 +20,7 @@ mod picture;
use picture::*; use picture::*;
mod text; mod text;
use text::*; use text::*;
pub mod quick;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
@@ -33,8 +34,10 @@ struct Issue {
says: String, says: String,
} }
pub fn cli(args: &[String]) -> i32 { /// `raea check …` with the person's taste, none or more (taste.ts and the kinds beside it, which the raea CLI evaluates: it owns the engine):
match run(args) { /// its rules' checks hold the export to the person's own lines.
pub fn cli_with(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> i32 {
match run(args, tastes) {
Ok((report, bad)) => { Ok((report, bad)) => {
println!("{report}"); println!("{report}");
i32::from(bad) i32::from(bad)
@@ -50,7 +53,7 @@ fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str) args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
} }
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste FILE|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, cues, loudness, blotching, a placeholder brand kit; P0-P3)"; pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, cues, loudness, blotching, a placeholder brand kit; P0-P3)";
/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for. /// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
@@ -60,56 +63,9 @@ struct Taste {
line: String, line: String,
} }
/// the forms a taste check can take, and what each measures (apps/app/host/taste.ts offers the Director these) /// The checks among a person's taste rules (taste.ts and its kinds), each with the line it stands for.
pub const TASTE_FORMS: [(&str, &str); 6] = [ fn taste_rules(tastes: &[raea_core_brief::Taste]) -> Vec<Taste> {
("text-hold", "S: every text holds at least S seconds"), tastes.iter().flat_map(|t| &t.sections).flat_map(|s| &s.rules).filter_map(|r| r.check.map(|c| Taste { form: c.form().to_string(), value: c.value(), line: r.text.clone() })).collect()
("text-above", "P%: every text's bottom edge sits above P% of the frame's height"),
("text-below", "P%: every text's top edge sits below P% of the frame's height"),
("text-margin", "N: every text keeps N px (at 1080 on the short side) from each edge"),
("loudness", "L: integrated loudness within 1 LU of L LUFS (instead of -14)"),
("still-max", "S: nothing holds still longer than S seconds (instead of 3)"),
];
/// The `## Checks` lines of a taste brief, or of every `.brief` in a folder. A form raea doesn't know is skipped and
/// named, so a hand-written line never breaks a check.
fn taste_rules(path: &str) -> R<(Vec<Taste>, Vec<String>)> {
let p = std::path::Path::new(path);
let files: Vec<std::path::PathBuf> = if p.is_dir() {
let mut v: Vec<_> = std::fs::read_dir(p).map_err(|e| format!("{path}: {e}"))?.filter_map(|e| e.ok().map(|e| e.path())).filter(|f| f.extension().is_some_and(|x| x == "brief")).collect();
v.sort();
v
} else {
vec![p.to_path_buf()]
};
let (mut rules, mut skipped) = (Vec::new(), Vec::new());
for f in files {
let text = std::fs::read_to_string(&f).map_err(|e| format!("{}: {e}", f.display()))?;
let (r, s) = parse_taste(&text);
rules.extend(r);
skipped.extend(s);
}
Ok((rules, skipped))
}
fn parse_taste(text: &str) -> (Vec<Taste>, Vec<String>) {
let (mut rules, mut skipped, mut on) = (Vec::new(), Vec::new(), false);
for l in text.lines() {
let t = l.trim();
if let Some(h) = t.strip_prefix("## ") {
on = h.trim().eq_ignore_ascii_case("checks");
continue;
}
let Some(item) = t.strip_prefix("- ").filter(|_| on) else { continue };
let (rule, line) = item.split_once(':').map(|(a, b)| (a.trim(), b.trim())).unwrap_or((item, ""));
let mut words = rule.split_whitespace();
let form = words.next().unwrap_or("").to_lowercase();
let value = words.next().map(|v| v.trim_end_matches(|c: char| c.is_alphabetic() || c == '%')).and_then(|v| v.parse::<f64>().ok());
match value {
Some(value) if TASTE_FORMS.iter().any(|(f, _)| *f == form) => rules.push(Taste { form, value, line: if line.is_empty() { rule.to_string() } else { line.to_string() } }),
_ => skipped.push(rule.to_string()),
}
}
(rules, skipped)
} }
fn taste_of<'a>(rules: &'a [Taste], form: &str) -> Option<&'a Taste> { fn taste_of<'a>(rules: &'a [Taste], form: &str) -> Option<&'a Taste> {
@@ -148,7 +104,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
/// the flags `raea check` takes, each with a value /// the flags `raea check` takes, each with a value
const TAKES: [&str; 7] = ["--manifest", "--words", "--perception", "--shape", "--platform", "--taste", "-o"]; const TAKES: [&str; 7] = ["--manifest", "--words", "--perception", "--shape", "--platform", "--taste", "-o"];
fn run(args: &[String]) -> R<(String, bool)> { fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
let video = args.iter().enumerate().find(|(i, a)| !a.starts_with('-') && !(*i > 0 && TAKES.contains(&args[i - 1].as_str()))).map(|(_, a)| a.clone()).ok_or(USAGE)?; let video = args.iter().enumerate().find(|(i, a)| !a.starts_with('-') && !(*i > 0 && TAKES.contains(&args[i - 1].as_str()))).map(|(_, a)| a.clone()).ok_or(USAGE)?;
if !std::path::Path::new(&video).exists() { if !std::path::Path::new(&video).exists() {
return Err(format!("no file at {video}\n{USAGE}")); return Err(format!("no file at {video}\n{USAGE}"));
@@ -156,14 +112,7 @@ fn run(args: &[String]) -> R<(String, bool)> {
let probe = Probe::of(&video)?; let probe = Probe::of(&video)?;
let mut issues = Vec::new(); let mut issues = Vec::new();
let mut passed = Vec::new(); let mut passed = Vec::new();
let (taste, skipped) = match flag(args, "--taste") { let taste = taste_rules(&tastes);
Some(t) if std::path::Path::new(t).exists() => taste_rules(t)?,
_ => (Vec::new(), Vec::new()),
};
for s in skipped {
passed.push(format!("taste: \"{s}\" isn't a form raea measures; kept as a line, not checked"));
}
let manifest: Option<Value> = match flag(args, "--manifest") { let manifest: Option<Value> = match flag(args, "--manifest") {
Some(m) => Some(serde_json::from_str(&std::fs::read_to_string(m).map_err(|e| format!("{m}: {e}"))?).map_err(|e| format!("{m}: {e}"))?), Some(m) => Some(serde_json::from_str(&std::fs::read_to_string(m).map_err(|e| format!("{m}: {e}"))?).map_err(|e| format!("{m}: {e}"))?),
None => None, None => None,
@@ -192,9 +141,14 @@ fn run(args: &[String]) -> R<(String, bool)> {
} }
} }
report(&video, issues, passed, flag(args, "-o"))
}
/// The issues ranked, written to -o as JSON when asked, and the report's text; true when a P0 or P1 is among them.
fn report(video: &str, mut issues: Vec<Issue>, passed: Vec<String>, out: Option<&str>) -> R<(String, bool)> {
issues.sort_by(|a, b| a.p.cmp(&b.p).then(a.at.unwrap_or(0.0).total_cmp(&b.at.unwrap_or(0.0)))); issues.sort_by(|a, b| a.p.cmp(&b.p).then(a.at.unwrap_or(0.0).total_cmp(&b.at.unwrap_or(0.0))));
let bad = issues.iter().any(|i| i.p <= 1); let bad = issues.iter().any(|i| i.p <= 1);
if let Some(out) = flag(args, "-o") { if let Some(out) = out {
let j = json!({ let j = json!({
"file": video, "file": video,
"issues": issues.iter().map(|i| json!({"rule": i.rule, "p": format!("P{}", i.p), "at": i.at, "says": i.says})).collect::<Vec<_>>(), "issues": issues.iter().map(|i| json!({"rule": i.rule, "p": format!("P{}", i.p), "at": i.at, "says": i.says})).collect::<Vec<_>>(),
+87
View File
@@ -0,0 +1,87 @@
//! `raea check EDIT.tsx --quick` and `raea hook claude` (docs/skills.feature SK10). The quick check renders three stills
//! of a composition (a quarter in, the middle, the last frame) with their manifest, about a second, and runs the full
//! check's text rules and the person's text taste on it: clipped and cramped text, safe areas, sizes. The hook is
//! Claude Code's PostToolUse command (`raea skills install --agent claude` adds it): after a .tsx that registers a root
//! is written, the quick check's findings go back to the agent; a clean check says nothing.
use super::*;
use std::path::Path;
/// The composition's length in frames, read from its source (the first `durationInFrames={N}`), 90 without one.
fn frames(src: &str) -> u64 {
src.split("durationInFrames={").nth(1).and_then(|r| r.split('}').next()).and_then(|n| n.trim().parse().ok()).unwrap_or(90)
}
/// `raea check EDIT.tsx --quick [--shape S] [--platform P] [-o check.json]`: (report, P0 or P1 found). `tastes` are the
/// person's, evaluated by the raea CLI when --taste names them.
pub fn quick(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
let file = args.iter().find(|a| a.ends_with(".tsx")).ok_or("raea check --quick takes a composition: EDIT.tsx")?;
let src = std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?;
let n = frames(&src).max(1);
let at = format!("{},{},{}", n / 4, n / 2, n - 1);
let tmp = std::env::temp_dir().join(format!("raea-quick-{}", std::process::id()));
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
let manifest = tmp.join("render.json");
let me = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(me).arg("render").arg(file).args(["--at", &at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).output().map_err(|e| e.to_string())?;
let result = if out.status.success() {
on_manifest(file, &manifest, args, tastes)
} else {
// a render that fails is the finding: the agent sees why
let (err, out) = (String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout));
let mut why = Vec::new();
for line in err.lines().chain(out.lines()) {
if line.contains("REFUSED") || line.contains("rror") {
why.push(line);
}
}
let why = why.join("\n");
Ok((format!("raea check {file}: it doesn't render\nP0 render {why}"), true))
};
let _ = std::fs::remove_dir_all(&tmp);
result
}
/// `raea hook claude`: Claude Code's PostToolUse input on stdin; for a saved composition, the quick check's findings as
/// the hook's additionalContext. Anything else, or a clean check, prints nothing.
pub fn hook(args: &[String]) -> R<String> {
if args.first().map(String::as_str) != Some("claude") {
return Err("usage: raea hook claude (Claude Code's PostToolUse hook; raea skills install --agent claude adds it)".into());
}
let mut input = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).map_err(|e| e.to_string())?;
let v: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
let path = v["tool_input"]["file_path"].as_str().unwrap_or_default();
let composition = path.ends_with(".tsx") && std::fs::read_to_string(path).map(|t| t.contains("registerRoot")).unwrap_or(false);
if !composition {
return Ok(String::new());
}
let (report, _) = quick(&[path.to_string()], Vec::new())?;
if report.lines().nth(1).is_none_or(|l| l.starts_with("ok ")) {
return Ok(String::new());
}
let found: Vec<&str> = report.lines().filter(|l| !l.starts_with("ok ")).collect();
Ok(json!({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": format!("raea check --quick after this save:\n{}", found.join("\n"))}}).to_string())
}
/// `raea check --quick`'s half (docs/skills.feature SK10): the text rules and the person's text taste on the manifest
/// of a few stills (`raea render EDIT.tsx --at ... --manifest`), no video. What it can't see (contrast, freezes,
/// sound, blotching) waits for the full check on the export.
fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
let at = manifest.display();
let m: Value = serde_json::from_str(&std::fs::read_to_string(manifest).map_err(|e| format!("{at}: {e}"))?).map_err(|e| format!("{at}: {e}"))?;
let (mut issues, mut passed) = (Vec::new(), Vec::new());
let runs = text_runs(&m);
let (w, h) = (m["width"].as_f64().unwrap_or(1080.0), m["height"].as_f64().unwrap_or(1920.0));
text_rules(&runs, None, w, h, flag(args, "--shape"), flag(args, "--platform"), &mut issues, &mut passed);
taste_text(&taste_rules(&tastes), &runs, w, h, &mut issues, &mut passed);
report(file, issues, passed, flag(args, "-o"))
}
#[cfg(test)]
mod tests {
#[test]
fn frames_come_from_the_source() {
assert_eq!(super::frames("<Composition durationInFrames={240} fps={30} />"), 240);
assert_eq!(super::frames("no composition"), 90);
}
}
+21 -9
View File
@@ -23,8 +23,10 @@ pub(crate) fn pct(v: &[f64], q: f64) -> f64 {
s[lo] + (s[hi] - s[lo]) * (r - lo as f64) s[lo] + (s[hi] - s[lo]) * (r - lo as f64)
} }
/// Each 10 ms step's level in dB, for the whole mix and in three bands (low < 500 Hz, mid to 4 kHz, high to 12 kHz): /// Each 10 ms step's level in dBFS, for the whole mix and in three bands (low < 500 Hz, mid to 4 kHz, high to 12 kHz):
/// a bed that stops under a voice shows in the band the voice doesn't fill (a projector's clatter in the highs) /// a bed that stops under a voice shows in the band the voice doesn't fill (a projector's clatter in the highs). A band's
/// level is its share of the step's mean square (Parseval, undoing the Hann window's power), so a tone reads the same in
/// its band as in the mix
pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) { pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
use std::f64::consts::PI; use std::f64::consts::PI;
let n = x.len() / HOP; let n = x.len() / HOP;
@@ -38,6 +40,8 @@ pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
let bins: Vec<(usize, Vec<(f64, f64)>)> = (0..=HOP / 2) let bins: Vec<(usize, Vec<(f64, f64)>)> = (0..=HOP / 2)
.filter_map(|k| Some((band(k)?, (0..HOP).map(|i| (-2.0 * PI * ((k * i) % HOP) as f64 / HOP as f64).sin_cos()).collect()))) .filter_map(|k| Some((band(k)?, (0..HOP).map(|i| (-2.0 * PI * ((k * i) % HOP) as f64 / HOP as f64).sin_cos()).collect())))
.collect(); .collect();
// one-sided bins (no DC or Nyquist in any band) count twice; the window keeps mean(w²) of the power
let scale = 2.0 / (HOP * HOP) as f64 / (hann.iter().map(|h| h * h).sum::<f64>() / HOP as f64);
let (mut rms, mut bands) = (Vec::with_capacity(n), [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)]); let (mut rms, mut bands) = (Vec::with_capacity(n), [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)]);
for f in x.chunks_exact(HOP) { for f in x.chunks_exact(HOP) {
let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / HOP as f64; let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / HOP as f64;
@@ -49,17 +53,22 @@ pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
e[*b] += re * re + im * im; e[*b] += re * re + im * im;
} }
for b in 0..3 { for b in 0..3 {
bands[b].push(10.0 * (e[b] / HOP as f64 + 1e-12).log10()); bands[b].push(10.0 * (e[b] * scale + 1e-18).log10());
} }
} }
(rms, bands) (rms, bands)
} }
/// Dead stops: a steady sound (a bed: a projector, rain, room tone, a held chord) that goes in one 10 ms step instead of /// Dead stops: a steady sound (a bed: a projector, rain, room tone, a held chord) that goes in one 10 ms step instead of
/// fading. Steady: over the second before, its level smoothed to 50 ms varies by under 3 dB (a voice or music with /// fading. Steady: over the second before, its level smoothed to 50 ms varies by under 3 dB. The stop: down 12 dB or more
/// phrases never holds that still). The stop: down 12 dB or more in one step, and the 300 ms after it DROP dB under the /// in one step, from within AT dB of the bed one or two steps before (a fade that has already brought it down isn't a
/// bed. In the whole mix or one band, so a bed that stops under a voice shows where the voice doesn't cover it. /// stop), to DROP dB under the bed by the next step (gone, not a voice's tail that comes back up), and the 300 ms after it
/// DROP dB under the bed. In the whole mix or one band, so a bed that stops under a voice shows where the voice doesn't
/// cover it. Dense speech can pass for steady in the lows (its pitch fills them evenly), but a word ends in a tail that
/// rises again after the first drop, where a cut source is gone in one step.
pub(crate) fn dead_stops(rms: &[f64], bands: &[Vec<f64>; 3]) -> Vec<(f64, String)> { pub(crate) fn dead_stops(rms: &[f64], bands: &[Vec<f64>; 3]) -> Vec<(f64, String)> {
/// dB under the bed the sound may be just before it stops
const AT: f64 = 6.0;
let mut found: Vec<(f64, String)> = Vec::new(); let mut found: Vec<(f64, String)> = Vec::new();
let n = rms.len(); let n = rms.len();
for (name, lv) in [("the mix", rms), ("the lows", &bands[0][..]), ("the mids", &bands[1][..]), ("the highs", &bands[2][..])] { for (name, lv) in [("the mix", rms), ("the lows", &bands[0][..]), ("the mids", &bands[1][..]), ("the highs", &bands[2][..])] {
@@ -71,10 +80,13 @@ pub(crate) fn dead_stops(rms: &[f64], bands: &[Vec<f64>; 3]) -> Vec<(f64, String
let pre = &sm[i - 100..i - 2]; let pre = &sm[i - 100..i - 2];
let (bed, mean) = (pct(pre, 50.0), pre.iter().sum::<f64>() / pre.len() as f64); let (bed, mean) = (pct(pre, 50.0), pre.iter().sum::<f64>() / pre.len() as f64);
let sd = (pre.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / pre.len() as f64).sqrt(); let sd = (pre.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / pre.len() as f64).sqrt();
let floor = if name == "the mix" { -50.0 } else { -65.0 }; // under this nobody hears it stop
let floor = if name == "the mix" { -50.0 } else { -80.0 };
let at = i as f64 * HOP as f64 / SR as f64; let at = i as f64 * HOP as f64 / SR as f64;
if bed > floor && sd < 3.0 && bed - pct(&lv[i..i + 30], 10.0) >= DROP && !found.iter().any(|(t, _)| (t - at).abs() < 0.5) { let was_up = lv[i - 1].max(lv[i - 2]) >= bed - AT;
found.push((at, format!("{name}: a steady sound at {bed:.0} dB stops dead in 10 ms: its source ran out (make it as long as its Sequence), or a Sequence cut it with no fadeOut"))); let gone = lv[i + 1] <= bed - DROP && bed - pct(&lv[i..i + 30], 10.0) >= DROP;
if bed > floor && sd < 3.0 && was_up && gone && !found.iter().any(|(t, _)| (t - at).abs() < 0.5) {
found.push((at, format!("{name}: a steady sound at {bed:.0} dBFS stops dead in 10 ms: its source ran out (make it as long as its Sequence), or a Sequence cut it with no fadeOut or one too short to hear (fade a bed out over 100 ms or more)")));
} }
} }
} }
+6
View File
@@ -0,0 +1,6 @@
# its-a-race (raea 0.1.0-canary.2, Linux export), 12.00-14.00 s: each 10 ms step's level in dBFS, one line per track:
# the mix, the lows, the mids, the highs. The voice ends "thing." at 13.36 s and pauses; nothing is cut there.
-9.4 -9.8 -10.1 -9.6 -9.2 -10.6 -11.9 -11.6 -10.1 -11.4 -11.0 -12.3 -10.0 -12.4 -12.2 -11.9 -11.6 -14.0 -16.2 -19.8 -17.9 -18.8 -22.8 -23.0 -25.0 -27.5 -26.2 -27.7 -30.9 -25.5 -17.2 -12.1 -11.3 -11.6 -12.3 -12.5 -12.2 -11.0 -12.4 -12.0 -12.5 -12.5 -12.3 -11.7 -12.8 -11.9 -12.1 -12.9 -12.4 -11.4 -11.1 -10.2 -11.2 -12.2 -11.8 -11.6 -12.7 -11.6 -12.0 -13.0 -13.1 -12.1 -13.8 -13.2 -14.3 -16.3 -19.5 -17.7 -17.0 -19.2 -16.0 -12.7 -12.9 -13.2 -15.4 -15.0 -15.6 -18.1 -19.1 -16.3 -17.9 -22.2 -28.5 -27.6 -28.4 -26.2 -12.5 -13.3 -12.2 -13.1 -12.3 -13.4 -14.6 -15.2 -12.2 -13.0 -12.4 -13.1 -13.3 -11.8 -13.2 -14.1 -11.5 -14.8 -16.7 -16.5 -16.2 -17.0 -19.1 -21.8 -22.1 -22.2 -22.3 -16.9 -12.7 -11.9 -14.7 -13.1 -12.9 -13.9 -16.6 -15.8 -14.9 -15.1 -18.6 -15.9 -17.3 -18.9 -15.6 -19.4 -21.3 -16.8 -18.7 -22.6 -17.7 -19.1 -27.5 -28.1 -29.8 -41.1 -35.5 -37.2 -39.2 -40.4 -40.4 -39.4 -47.0 -39.7 -40.4 -51.7 -42.6 -44.1 -46.9 -48.2 -51.3 -48.3 -54.1 -54.6 -55.0 -50.8 -54.1 -51.6 -55.5 -53.5 -51.7 -54.7 -51.8 -55.6 -57.5 -54.8 -51.2 -54.0 -51.8 -51.8 -47.9 -50.9 -51.1 -47.9 -53.1 -50.0 -46.5 -49.4 -49.4 -48.3 -55.7 -51.1 -48.7 -58.9 -54.4 -54.6 -50.3 -51.6 -58.0 -60.7 -60.2 -56.3 -58.9 -55.1 -48.8 -48.3
-14.9 -13.6 -13.9 -11.8 -10.1 -11.9 -13.2 -13.9 -13.7 -14.6 -14.1 -15.8 -17.2 -14.8 -13.9 -15.5 -13.5 -13.1 -16.6 -21.9 -21.1 -20.4 -23.3 -22.7 -28.8 -27.3 -26.5 -29.2 -35.7 -27.5 -22.6 -22.5 -19.2 -18.5 -19.7 -20.1 -17.9 -17.9 -15.1 -15.8 -15.0 -13.3 -12.8 -13.5 -13.7 -13.6 -16.6 -18.3 -17.9 -17.1 -17.1 -18.0 -16.5 -14.8 -15.7 -15.5 -16.9 -15.5 -15.9 -16.3 -16.4 -15.2 -15.0 -13.5 -15.7 -16.3 -23.9 -18.8 -18.5 -23.4 -18.3 -14.9 -16.9 -17.7 -16.7 -14.8 -15.0 -18.9 -21.1 -15.8 -16.0 -21.6 -29.5 -28.3 -27.8 -29.9 -10.9 -13.0 -12.6 -15.2 -15.0 -15.2 -15.6 -16.4 -10.9 -11.7 -13.4 -16.4 -17.2 -16.1 -13.2 -12.7 -11.2 -14.8 -20.7 -20.7 -15.1 -16.6 -20.0 -21.9 -21.4 -21.1 -24.0 -20.7 -14.1 -12.1 -14.9 -13.9 -15.8 -17.8 -18.0 -17.5 -18.0 -17.0 -19.3 -18.6 -19.4 -17.7 -15.2 -19.0 -21.7 -16.0 -21.9 -26.4 -17.1 -18.4 -30.6 -32.5 -28.5 -40.9 -36.5 -39.9 -42.0 -41.9 -39.9 -38.6 -48.0 -39.9 -41.4 -51.5 -41.3 -44.6 -49.2 -51.7 -51.6 -46.6 -55.4 -54.4 -57.2 -51.8 -53.6 -54.4 -67.4 -54.8 -52.1 -59.4 -52.1 -60.5 -57.8 -56.5 -50.9 -55.9 -56.8 -54.8 -50.8 -52.6 -53.3 -48.0 -51.4 -50.9 -49.4 -53.1 -50.5 -48.2 -60.7 -51.3 -48.6 -57.8 -54.4 -56.1 -50.3 -53.1 -61.4 -63.3 -63.1 -55.4 -63.0 -64.0 -49.9 -47.3
-12.0 -10.4 -12.3 -11.7 -10.7 -10.7 -14.9 -14.4 -12.3 -16.6 -13.5 -14.5 -11.1 -16.7 -15.5 -18.9 -13.4 -22.6 -23.6 -21.8 -26.7 -20.9 -28.7 -30.7 -30.0 -33.2 -34.9 -34.4 -36.3 -31.4 -24.7 -16.0 -10.5 -9.2 -9.7 -10.8 -12.7 -15.1 -19.7 -17.3 -19.4 -19.3 -20.1 -19.5 -21.5 -19.3 -18.7 -18.7 -15.4 -13.5 -14.9 -12.2 -15.0 -15.6 -14.6 -13.9 -16.5 -13.7 -13.6 -15.2 -14.7 -13.5 -16.3 -19.3 -20.2 -19.0 -23.1 -24.0 -23.2 -23.2 -17.9 -13.7 -16.6 -17.8 -22.7 -24.8 -28.6 -28.2 -32.4 -34.7 -34.6 -36.6 -38.0 -40.1 -42.3 -35.2 -23.1 -16.8 -16.8 -18.0 -18.1 -23.6 -26.2 -29.0 -29.4 -35.4 -27.7 -27.3 -21.4 -26.4 -28.5 -27.2 -31.6 -32.5 -31.8 -36.6 -30.0 -35.9 -34.5 -38.9 -46.2 -36.8 -36.4 -28.6 -24.0 -19.9 -20.8 -18.7 -14.8 -20.7 -21.7 -21.0 -17.7 -24.2 -26.8 -25.9 -25.1 -35.3 -33.6 -35.9 -31.9 -33.1 -37.1 -37.0 -39.4 -41.9 -41.4 -41.3 -44.5 -52.1 -49.2 -51.5 -50.8 -55.7 -54.8 -54.7 -59.0 -53.6 -56.8 -62.2 -59.4 -59.3 -58.9 -61.8 -63.8 -64.5 -65.8 -59.9 -62.2 -60.3 -64.8 -63.2 -62.9 -61.9 -64.4 -68.0 -64.8 -63.3 -65.8 -65.6 -60.6 -59.4 -60.2 -62.9 -61.1 -65.1 -61.8 -61.2 -63.9 -60.1 -60.1 -63.2 -64.3 -62.1 -64.6 -58.1 -62.4 -63.1 -60.3 -64.0 -65.1 -66.5 -64.5 -64.1 -61.3 -63.4 -63.7 -64.4 -61.6 -61.3
-67.9 -67.4 -67.8 -66.7 -64.9 -65.1 -68.8 -66.5 -65.0 -67.2 -65.0 -68.4 -65.1 -63.2 -62.2 -64.6 -69.9 -69.5 -65.1 -59.3 -71.5 -71.7 -73.7 -70.1 -73.6 -71.9 -70.5 -68.0 -64.9 -59.0 -52.7 -48.0 -46.1 -43.3 -46.8 -49.0 -48.5 -45.5 -46.1 -48.9 -42.3 -48.5 -48.3 -53.6 -53.2 -52.8 -47.4 -44.4 -54.5 -56.1 -56.2 -54.6 -52.5 -53.6 -53.8 -57.0 -54.5 -55.2 -54.0 -53.7 -51.1 -59.0 -56.1 -55.7 -57.7 -58.6 -64.5 -65.6 -64.7 -66.6 -61.2 -51.6 -49.8 -51.2 -54.4 -58.5 -57.3 -62.0 -59.5 -58.1 -51.3 -45.8 -48.4 -47.1 -45.8 -50.3 -46.3 -42.4 -42.0 -47.7 -51.6 -52.3 -56.7 -59.0 -61.9 -65.4 -64.7 -63.4 -59.2 -58.6 -54.0 -55.7 -53.6 -47.1 -44.8 -41.1 -44.5 -41.3 -44.8 -43.8 -45.0 -46.5 -47.4 -48.1 -52.2 -52.5 -53.3 -54.0 -57.1 -58.2 -61.1 -60.7 -60.3 -59.0 -57.6 -59.4 -62.1 -66.4 -65.6 -68.2 -66.6 -66.0 -72.4 -68.6 -68.9 -72.2 -73.0 -71.9 -75.4 -73.8 -73.7 -76.3 -74.6 -77.1 -76.4 -76.4 -75.2 -76.3 -75.4 -76.6 -77.8 -77.1 -74.6 -76.5 -74.6 -77.6 -76.2 -77.3 -74.8 -78.0 -76.6 -79.6 -80.0 -77.4 -75.6 -77.0 -76.9 -75.9 -77.0 -76.4 -76.4 -76.5 -78.2 -77.6 -76.1 -77.6 -77.7 -76.8 -76.7 -77.5 -76.9 -77.7 -75.2 -76.9 -78.1 -76.3 -76.9 -78.3 -79.3 -78.9 -77.1 -76.9 -79.3 -77.4 -78.4 -77.1 -76.3 -77.9 -76.2 -76.3
+48 -6
View File
@@ -56,14 +56,17 @@ fn flat_dark_is_clean_and_stepped_dark_is_blotchy() {
} }
#[test] #[test]
fn taste_checks_read_their_section_and_hold_text_to_the_persons_line() { fn taste_checks_hold_text_to_the_persons_line() {
let brief = "# Shane's taste\n\n## Always\n- text-above 60%: not a check here\n\n## Checks\n- text-above 62%: Captions sit clear of the bottom.\n- glow-free: no glow\n- text-hold 2 s\n"; let taste: raea_core_brief::Taste = serde_json::from_value(json!({"title": "Shane's taste", "sections": [{"heading": "Always", "rules": [
let (rules, skipped) = parse_taste(brief); {"text": "Captions sit clear of the bottom.", "check": {"form": "text-above", "value": 62.0}},
{"text": "No glow"},
{"text": "Text holds two seconds", "check": {"form": "text-hold", "value": 2.0}},
]}]})).unwrap();
let rules = taste_rules(&[taste]);
assert_eq!(rules, vec![ assert_eq!(rules, vec![
Taste { form: "text-above".into(), value: 62.0, line: "Captions sit clear of the bottom.".into() }, Taste { form: "text-above".into(), value: 62.0, line: "Captions sit clear of the bottom.".into() },
Taste { form: "text-hold".into(), value: 2.0, line: "text-hold 2 s".into() }, Taste { form: "text-hold".into(), value: 2.0, line: "Text holds two seconds".into() },
]); ]);
assert_eq!(skipped, vec!["glow-free".to_string()]);
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 }; let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 }; let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
let (mut issues, mut passed) = (vec![], vec![]); let (mut issues, mut passed) = (vec![], vec![]);
@@ -79,7 +82,7 @@ fn taste_checks_read_their_section_and_hold_text_to_the_persons_line() {
#[ignore] #[ignore]
fn on_a_real_export() { fn on_a_real_export() {
let args: Vec<String> = std::env::var("RAEA_CHECK_ARGS").expect("RAEA_CHECK_ARGS").split_whitespace().map(String::from).collect(); let args: Vec<String> = std::env::var("RAEA_CHECK_ARGS").expect("RAEA_CHECK_ARGS").split_whitespace().map(String::from).collect();
let code = cli(&args); let code = cli_with(&args, Vec::new());
println!("exit {code}"); println!("exit {code}");
} }
@@ -103,6 +106,45 @@ fn a_steady_sound_that_stops_dead_is_found_and_a_faded_one_isnt() {
let faded: Vec<f32> = tone(4.0, &[(0.0, 3.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * (1.0 - ((i as f32 / SR as f32) - 2.0).clamp(0.0, 1.0))).collect(); let faded: Vec<f32> = tone(4.0, &[(0.0, 3.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * (1.0 - ((i as f32 / SR as f32) - 2.0).clamp(0.0, 1.0))).collect();
let (rms, bands) = levels(&faded); let (rms, bands) = levels(&faded);
assert!(dead_stops(&rms, &bands).is_empty()); assert!(dead_stops(&rms, &bands).is_empty());
// a source cut partway through a 10 ms step is as dead
let cut: Vec<f32> = tone(4.0, &[(0.0, 2.0 + 117.0 / SR as f64, -20.0)]);
let (rms, bands) = levels(&cut);
assert_eq!(dead_stops(&rms, &bands).len(), 1);
// a 100 ms fadeOut is a fade, though its last step falls into silence
let short: Vec<f32> = tone(4.0, &[(0.0, 2.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * ((2.0 - i as f32 / SR as f32) / 0.1).clamp(0.0, 1.0)).collect();
let (rms, bands) = levels(&short);
assert!(dead_stops(&rms, &bands).is_empty(), "{:?}", dead_stops(&rms, &bands));
}
#[test]
fn bands_read_in_dbfs() {
// a tone in the middle of its band reads there what it reads in the mix: -20 dBFS peak is -23 dBFS RMS
let sine = |hz: f64| (0..SR).map(|i| (0.1 * (2.0 * std::f64::consts::PI * hz * i as f64 / SR as f64).sin()) as f32).collect::<Vec<_>>();
for (hz, band) in [(200.0, 0), (2000.0, 1), (8000.0, 2)] {
let (rms, bands) = levels(&sine(hz));
assert!((rms[50] + 23.0).abs() < 0.1, "{}", rms[50]);
assert!((bands[band][50] - rms[50]).abs() < 0.2, "{hz} Hz: band {} vs the mix {}", bands[band][50], rms[50]);
}
}
#[test]
fn a_voice_that_ends_a_sentence_isnt_a_dead_stop() {
// its-a-race at 12-14 s: "AI became a thing." ends at 13.36 s and the speaker pauses. Its lows held within 2.6 dB over
// the second before and fell 12 dB in one step, so they read as a bed cut dead ("a steady sound at -0 dB", before the
// bands read in dBFS), but the mix follows the source there and the word's tail comes back up after the first drop
let tracks: Vec<Vec<f64>> = include_str!("testdata/its-a-race-12s.levels")
.lines()
.filter(|l| !l.starts_with('#'))
.map(|l| l.split_whitespace().map(|v| v.parse().unwrap()).collect())
.collect();
let bands = [tracks[1].clone(), tracks[2].clone(), tracks[3].clone()];
let stops = dead_stops(&tracks[0], &bands);
assert!(stops.is_empty(), "{stops:?}");
// the same voice with a bed under it that's cut at 13.6 s: that one is still found
let bed = 10f64.powf(-30.0 / 10.0);
let highs: Vec<f64> = tracks[3].iter().enumerate().map(|(i, v)| 10.0 * (10f64.powf(v / 10.0) + if i < 160 { bed } else { 0.0 }).log10()).collect();
let found = dead_stops(&tracks[0], &[tracks[1].clone(), tracks[2].clone(), highs]);
assert!(found.iter().any(|(at, says)| (at - 1.6).abs() < 0.02 && says.starts_with("the highs")), "{found:?}");
} }
#[test] #[test]
+1 -1
View File
@@ -94,7 +94,7 @@ pub(crate) fn gather(bundle: &mut String, dir: &Path, game: &Path, got: &mut Gat
let decoded = raea_io_net::percent_decode_str(s); let decoded = raea_io_net::percent_decode_str(s);
let mut cands: Vec<PathBuf> = Vec::new(); let mut cands: Vec<PathBuf> = Vec::new();
if let Some(rest) = decoded.strip_prefix("/media/") { if let Some(rest) = decoded.strip_prefix("/media/") {
cands.push(dir.join("media").join(rest)); cands.push(raea_runtime_react::scene::media_path(dir, &format!("/media/{rest}")));
} }
if decoded.starts_with('/') { if decoded.starts_with('/') {
cands.push(PathBuf::from(&decoded)); cands.push(PathBuf::from(&decoded));
+3 -1
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024" edition = "2024"
license = "FSL-1.1-ALv2" license = "FSL-1.1-ALv2"
publish = false publish = false
description = "The `raea` verbs that run raea's local model tools: sao, tokensynth, setup-audio, sounds, splat and song" description = "The `raea` verbs that run raea's model tools: sao, tokensynth, setup-audio, sounds, splat, song and gen"
[features] [features]
# a made sound signed as generated (raea's own API; the public engine goes without) # a made sound signed as generated (raea's own API; the public engine goes without)
@@ -12,6 +12,8 @@ service = []
[dependencies] [dependencies]
raea-io-assets = { path = "../../io/assets" } raea-io-assets = { path = "../../io/assets" }
# generation flows: made.app, fal, Replicate, OpenRouter, Modal, ComfyUI (`raea gen`)
raea-io-gen = { path = "../../io/gen" }
raea-io-home = { path = "../../io/home" } raea-io-home = { path = "../../io/home" }
raea-io-media = { path = "../../io/media", default-features = false } raea-io-media = { path = "../../io/media", default-features = false }
serde_json = "1" serde_json = "1"
+174
View File
@@ -0,0 +1,174 @@
//! The MCP servers `raea skills install` offers an agent (docs/skills.feature SK11): today `blender`, which drives a
//! running Blender through the MCP for Blender add-on (`raea setup blender` installs it). Each agent keeps MCP servers
//! in its own place; a server already registered under the name is left as the person set it.
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use std::process::Command;
/// The blender MCP server: uv runs it, so nothing is installed until an agent starts it.
const NAME: &str = "blender";
const CMD: &str = "uvx";
const ARGS: [&str; 1] = ["mcp-for-blender"];
type R<T> = Result<T, String>;
/// The person's home folder (HOME, or USERPROFILE on Windows).
pub fn user_home() -> R<PathBuf> {
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from).ok_or_else(|| "no home folder (HOME)".into())
}
/// The JSON file holding `mcpServers` for agents configured that way (Kimi Code, Gemini CLI, Claude Code's own file).
fn json_file(agent: &str) -> R<Option<PathBuf>> {
let h = user_home()?;
Ok(match agent {
"claude" => Some(h.join(".claude.json")),
"kimi" => Some(std::env::var_os("KIMI_CODE_HOME").filter(|v| !v.is_empty()).map(PathBuf::from).unwrap_or_else(|| h.join(".kimi-code")).join("mcp.json")),
"gemini" => Some(h.join(".gemini/settings.json")),
_ => None,
})
}
/// Adds `blender` to a JSON config's `mcpServers` unless one is there; true when it added.
pub fn add_json(path: &Path) -> R<bool> {
let mut doc: Value = match std::fs::read_to_string(path) {
Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", path.display()))?,
_ => json!({}),
};
let servers = doc.as_object_mut().ok_or_else(|| format!("{} isn't a JSON object", path.display()))?.entry("mcpServers").or_insert_with(|| json!({}));
let servers = servers.as_object_mut().ok_or_else(|| format!("{}: mcpServers isn't an object", path.display()))?;
if servers.contains_key(NAME) {
return Ok(false);
}
servers.insert(NAME.into(), json!({"command": CMD, "args": ARGS}));
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
let tmp = path.with_extension("raea-tmp");
std::fs::write(&tmp, serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n").map_err(|e| format!("{}: {e}", tmp.display()))?;
std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))?;
Ok(true)
}
/// Adds a `[mcp_servers.blender]` table to Codex's config.toml unless one is there; true when it added.
pub fn add_toml(path: &Path) -> R<bool> {
let text = std::fs::read_to_string(path).unwrap_or_default();
if text.lines().any(|l| l.trim() == format!("[mcp_servers.{NAME}]")) {
return Ok(false);
}
let args = ARGS.iter().map(|a| format!("{a:?}")).collect::<Vec<_>>().join(", ");
let sep = if text.is_empty() || text.ends_with("\n\n") { "" } else if text.ends_with('\n') { "\n" } else { "\n\n" };
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
std::fs::write(path, format!("{text}{sep}[mcp_servers.{NAME}]\ncommand = {CMD:?}\nargs = [{args}]\n")).map_err(|e| format!("{}: {e}", path.display()))?;
Ok(true)
}
/// Registers the blender MCP server for an agent; the line says what happened. Claude Code rewrites ~/.claude.json while
/// it runs, so its own `claude mcp add` is used when `claude` is on PATH.
pub fn offer(agent: &str) -> R<String> {
let line = |added: bool, at: &Path| if added { format!("{}: MCP server {NAME} added", at.display()) } else { format!("{}: MCP server {NAME} already there", at.display()) };
if agent == "codex" {
let p = user_home()?.join(".codex/config.toml");
return Ok(line(add_toml(&p)?, &p));
}
let p = json_file(agent)?.ok_or_else(|| format!("no agent {agent:?}"))?;
if agent == "claude" {
let listed = Command::new("claude").args(["mcp", "get", NAME]).output();
match listed {
Ok(o) if o.status.success() => return Ok(line(false, &p)),
Ok(_) => {
let o = Command::new("claude").args(["mcp", "add", "--scope", "user", NAME, "--", CMD]).args(ARGS).output().map_err(|e| e.to_string())?;
if !o.status.success() {
return Err(format!("claude mcp add {NAME}: {}", String::from_utf8_lossy(&o.stderr).trim()));
}
return Ok(line(true, &p));
}
Err(_) => {} // no claude on PATH: write its file
}
}
Ok(line(add_json(&p)?, &p))
}
/// A hook entry raea added (its command is `raea hook ...`).
fn ours(hook: &Value) -> bool {
hook["command"].as_str().unwrap_or("").starts_with("raea hook")
}
/// Claude Code's PostToolUse hook running `raea hook claude` after a file is written, in its settings.json, unless one
/// is there; true when it added. Its findings reach the agent as the hook's additionalContext.
pub fn claude_hook(settings: &Path) -> R<bool> {
let mut doc: Value = match std::fs::read_to_string(settings) {
Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", settings.display()))?,
_ => json!({}),
};
let post = doc.as_object_mut().ok_or("settings.json isn't an object")?.entry("hooks").or_insert_with(|| json!({})).as_object_mut().ok_or("settings.json: hooks isn't an object")?.entry("PostToolUse").or_insert_with(|| json!([]));
let list = post.as_array_mut().ok_or("settings.json: hooks.PostToolUse isn't a list")?;
if list.iter().any(|m| m["hooks"].as_array().into_iter().flatten().any(ours)) {
return Ok(false);
}
list.push(json!({"matcher": "Write|Edit|MultiEdit", "hooks": [{"type": "command", "command": "raea hook claude", "timeout": 60}]}));
let tmp = settings.with_extension("raea-tmp");
std::fs::write(&tmp, serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n").map_err(|e| format!("{}: {e}", tmp.display()))?;
std::fs::rename(&tmp, settings).map_err(|e| format!("{}: {e}", settings.display()))?;
Ok(true)
}
/// A move's guide as a skill of its own, named for the move: its description from the guide's first paragraph.
pub fn pin(to: &Path, mv: &str, v: &str) -> R<String> {
let guide = raea_io_home::home().join("sdk/guides/craft/verbs").join(format!("{mv}.md"));
let no = format!("no move {mv:?}: `raea guide` lists them");
if mv.is_empty() || !mv.chars().all(|c| c.is_ascii_lowercase()) {
return Err(no);
}
let text = std::fs::read_to_string(&guide).map_err(|_| no)?;
let first = text.split("\n\n").nth(1).unwrap_or_default().replace('\n', " ");
let md = format!("---\nname: {mv}\ndescription: raea's {mv} move, for a note on a raea piece. {}\nversion: {v}\n---\n\n# {mv}\n\nRun `raea guide {mv}` and follow it on the part or moment the note names. Answer the person in their words, never with the move's name. The raea skill has the rest.\n", first.replace(':', " -"));
let dir = to.join(mv);
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
std::fs::write(dir.join("SKILL.md"), md).map_err(|e| e.to_string())?;
Ok(format!("{}: /{mv} pinned\n", dir.display()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_once_and_keeps_what_was_there() {
let d = std::env::temp_dir().join(format!("raea-agent-mcp-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
let j = d.join("kimi/mcp.json");
assert!(add_json(&j).unwrap());
assert!(!add_json(&j).unwrap());
std::fs::write(&j, r#"{"theme":"dark","mcpServers":{"blender":{"command":"mine"}}}"#).unwrap();
assert!(!add_json(&j).unwrap());
let kept: Value = serde_json::from_str(&std::fs::read_to_string(&j).unwrap()).unwrap();
assert_eq!(kept["mcpServers"]["blender"]["command"], "mine");
let t = d.join("codex/config.toml");
std::fs::create_dir_all(t.parent().unwrap()).unwrap();
std::fs::write(&t, "model = \"x\"\n").unwrap();
assert!(add_toml(&t).unwrap());
assert!(!add_toml(&t).unwrap());
assert_eq!(std::fs::read_to_string(&t).unwrap(), "model = \"x\"\n\n[mcp_servers.blender]\ncommand = \"uvx\"\nargs = [\"mcp-for-blender\"]\n");
let h = d.join("claude/settings.json");
std::fs::create_dir_all(h.parent().unwrap()).unwrap();
std::fs::write(&h, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]}]}}"#).unwrap();
assert!(claude_hook(&h).unwrap());
assert!(!claude_hook(&h).unwrap());
let v: Value = serde_json::from_str(&std::fs::read_to_string(&h).unwrap()).unwrap();
assert_eq!(v["hooks"]["PostToolUse"].as_array().unwrap().len(), 2);
assert_eq!(v["model"], "x");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn a_pinned_move_is_a_skill_of_its_own() {
let d = std::env::temp_dir().join(format!("raea-pin-{}", std::process::id()));
assert!(pin(&d, "quieter", "9.9").unwrap().contains("/quieter pinned"));
let md = std::fs::read_to_string(d.join("quieter/SKILL.md")).unwrap();
assert!(md.starts_with("---\nname: quieter\ndescription: raea's quieter move") && md.contains("\nversion: 9.9\n---\n") && md.contains("raea guide quieter"), "{md}");
assert!(pin(&d, "../x", "1").is_err() && pin(&d, "nomove", "1").is_err());
let _ = std::fs::remove_dir_all(&d);
}
}
+225
View File
@@ -0,0 +1,225 @@
//! `raea setup blender` and `raea blender run` (docs/skills.feature SK11). Blender is GPL, so raea never bundles it: it
//! finds the person's Blender, or downloads the current LTS from blender.org into ~/.raea/tools/blender, and runs it as
//! its own program. The setup also installs the MCP for Blender add-on (github.com/ahujasid/mcp-for-blender, MIT) into
//! that Blender, so an agent's `blender` MCP server (raea skills install adds it) can drive a running Blender.
use std::path::{Path, PathBuf};
use std::process::Command;
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install its MCP add-on)\n raea blender run SCRIPT.py [ARGS...] (blender --background --python SCRIPT.py -- ARGS, headless)";
/// The LTS series raea downloads; the newest patch in blender.org/release/Blender<LTS>/ is taken. Moved when Blender
/// ships a new LTS (blender.org/download/lts).
const LTS: &str = "5.2";
/// Where raea keeps the Blender it downloads.
fn own_dir() -> R<PathBuf> {
Ok(crate::agent_mcp::user_home()?.join(".raea/tools/blender"))
}
/// The Blender binary inside raea's own download, per platform.
fn own_binary() -> R<PathBuf> {
let d = own_dir()?;
Ok(if cfg!(target_os = "macos") { d.join("Blender.app/Contents/MacOS/Blender") } else if cfg!(windows) { d.join("blender.exe") } else { d.join("blender") })
}
fn on_path(name: &str) -> Option<PathBuf> {
std::env::split_paths(&std::env::var_os("PATH")?).map(|d| d.join(name)).find(|p| p.is_file())
}
/// The Blender to use and where it came from: `git config --global raea.blender`, raea's own download, the usual app
/// folders, then PATH.
pub fn find() -> Option<(PathBuf, &'static str)> {
let configured = run(Command::new("git").args(["config", "--global", "raea.blender"]), "git config").ok().map(|out| PathBuf::from(out.trim()));
if let Some(p) = configured.filter(|p| p.is_file()) {
return Some((p, "raea.blender in git config"));
}
if let Some(p) = own_binary().ok().filter(|p| p.is_file()) {
return Some((p, "raea's download"));
}
let mut apps = vec![PathBuf::from("/Applications/Blender.app/Contents/MacOS/Blender")];
if let Ok(h) = crate::agent_mcp::user_home() {
apps.push(h.join("Applications/Blender.app/Contents/MacOS/Blender"));
}
if let Some(p) = apps.into_iter().find(|p| cfg!(target_os = "macos") && p.is_file()) {
return Some((p, "Applications"));
}
on_path(if cfg!(windows) { "blender.exe" } else { "blender" }).map(|p| (p, "PATH"))
}
/// `blender --version`'s first line ("Blender 5.2.1 LTS").
fn version(bin: &Path) -> R<String> {
let o = Command::new(bin).arg("--version").output().map_err(|e| format!("{}: {e}", bin.display()))?;
String::from_utf8_lossy(&o.stdout).lines().find(|l| l.starts_with("Blender ")).map(str::to_string).ok_or_else(|| format!("{} --version printed no version", bin.display()))
}
fn run(cmd: &mut Command, what: &str) -> R<String> {
let o = cmd.output().map_err(|e| format!("{what}: {e}"))?;
if !o.status.success() {
return Err(format!("{what} failed: {}{}", String::from_utf8_lossy(&o.stderr).trim(), String::from_utf8_lossy(&o.stdout).trim()));
}
Ok(String::from_utf8_lossy(&o.stdout).into_owned())
}
/// This platform's file name in a release folder, for a version.
fn asset(v: &str) -> R<String> {
match (std::env::consts::OS, std::env::consts::ARCH) {
("macos", "aarch64") => Ok(format!("blender-{v}-macos-arm64.dmg")),
("macos", _) => Ok(format!("blender-{v}-macos-x64.dmg")),
("linux", "x86_64") => Ok(format!("blender-{v}-linux-x64.tar.xz")),
("windows", "aarch64") => Ok(format!("blender-{v}-windows-arm64.zip")),
("windows", _) => Ok(format!("blender-{v}-windows-x64.zip")),
(os, arch) => Err(format!("blender.org has no build for {os} {arch}: install Blender yourself and `git config --global raea.blender PATH`")),
}
}
/// The newest patch of the LTS series in a release folder's listing.
fn newest(listing: &str) -> Option<String> {
let pre = format!("blender-{LTS}.");
let mut best: Option<(u32, String)> = None;
for part in listing.split(&pre).skip(1) {
let digits: String = part.chars().take_while(char::is_ascii_digit).collect();
if let Ok(n) = digits.parse::<u32>() {
if part[digits.len()..].starts_with('-') && best.as_ref().map_or(true, |(b, _)| n > *b) {
best = Some((n, format!("{LTS}.{n}")));
}
}
}
best.map(|(_, v)| v)
}
fn sha256(file: &Path) -> R<String> {
let out = if cfg!(windows) {
run(Command::new("certutil").arg("-hashfile").arg(file).arg("SHA256"), "certutil")?.lines().nth(1).unwrap_or_default().replace(' ', "")
} else {
run(Command::new("shasum").args(["-a", "256"]).arg(file), "shasum")?.split_whitespace().next().unwrap_or_default().to_string()
};
Ok(out.to_lowercase())
}
/// Downloads the LTS into ~/.raea/tools/blender, checked against blender.org's sha256 list, and returns its binary.
fn download() -> R<(PathBuf, String)> {
let base = format!("https://download.blender.org/release/Blender{LTS}/");
let listing = run(Command::new("curl").args(["-fsSL", &base]), "curl")?;
let v = newest(&listing).ok_or_else(|| format!("no Blender {LTS} release listed at {base}"))?;
let name = asset(&v)?;
let dir = own_dir()?;
let tmp = dir.with_file_name("blender.download");
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
let file = tmp.join(&name);
run(Command::new("curl").args(["-fL", "--retry", "3", "-o"]).arg(&file).arg(format!("{base}{name}")), "downloading Blender")?;
let sums = run(Command::new("curl").args(["-fsSL", &format!("{base}blender-{v}.sha256")]), "curl")?;
let want = sums.lines().find(|l| l.ends_with(&name)).and_then(|l| l.split_whitespace().next()).ok_or_else(|| format!("blender-{v}.sha256 doesn't list {name}"))?.to_lowercase();
if sha256(&file)? != want {
return Err(format!("{name} doesn't match blender.org's sha256; nothing installed (it's in {})", tmp.display()));
}
let unpacked = tmp.join("unpacked");
std::fs::create_dir_all(&unpacked).map_err(|e| e.to_string())?;
if name.ends_with(".dmg") {
let mnt = tmp.join("mnt");
run(Command::new("hdiutil").args(["attach", "-nobrowse", "-readonly", "-mountpoint"]).arg(&mnt).arg(&file), "hdiutil attach")?;
let copied = run(Command::new("ditto").arg(mnt.join("Blender.app")).arg(unpacked.join("Blender.app")), "copying Blender.app");
let _ = Command::new("hdiutil").args(["detach", "-quiet"]).arg(&mnt).status();
copied?;
} else {
// tar unpacks .tar.xz on Linux and .zip on Windows 10 and 11; both hold one top folder
run(Command::new("tar").arg("-xf").arg(&file).arg("-C").arg(&unpacked).args(if cfg!(windows) { vec![] } else { vec!["--strip-components=1"] }), "unpacking Blender")?;
if cfg!(windows) {
let top = std::fs::read_dir(&unpacked).map_err(|e| e.to_string())?.flatten().find(|e| e.path().is_dir()).ok_or("the zip held no folder")?.path();
let flat = tmp.join("flat");
std::fs::rename(&top, &flat).map_err(|e| e.to_string())?;
std::fs::remove_dir_all(&unpacked).map_err(|e| e.to_string())?;
std::fs::rename(&flat, &unpacked).map_err(|e| e.to_string())?;
}
}
let _ = std::fs::remove_dir_all(&dir);
std::fs::rename(&unpacked, &dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let _ = std::fs::remove_dir_all(&tmp);
Ok((own_binary()?, format!("downloaded Blender {v} LTS from blender.org")))
}
/// Python run inside Blender (background): prints the user add-ons folder, or whether the add-on is enabled.
const ADDONS_DIR: &str = "import bpy; print('RAEA_ADDONS=' + bpy.utils.user_resource('SCRIPTS', path='addons', create=True))";
const ENABLE: &str = "import addon_utils, bpy; addon_utils.enable('blender_mcp', default_set=True, persistent=True); bpy.ops.wm.save_userpref(); print('RAEA_ENABLED=' + str(addon_utils.check('blender_mcp')[1]))";
const CHECK: &str = "import addon_utils; print('RAEA_ENABLED=' + str(addon_utils.check('blender_mcp')[1]))";
fn py(bin: &Path, code: &str, key: &str) -> R<String> {
let out = run(Command::new(bin).args(["--background", "--factory-startup", "--python-expr", code]), "blender")?;
out.lines().find_map(|l| l.strip_prefix(key)).map(str::to_string).ok_or_else(|| format!("blender printed no {key}"))
}
/// The add-on: uvx mcp-for-blender's own installer writes it into this Blender's add-ons folder, then Blender enables it.
fn addon(bin: &Path, check: bool) -> R<String> {
// --factory-startup skips the person's add-ons for speed, so the check reads the saved preferences instead
let state = |b: &Path| run(Command::new(b).args(["--background", "--python-expr", CHECK]), "blender").map(|o| o.contains("RAEA_ENABLED=True"));
if state(bin)? {
return Ok("MCP add-on enabled".into());
}
if check {
return Ok("MCP add-on not installed: raea setup blender installs it".into());
}
let uvx = on_path(if cfg!(windows) { "uvx.exe" } else { "uvx" }).ok_or("the MCP add-on comes from uv's uvx: install uv (https://docs.astral.sh/uv/getting-started/installation/), then run raea setup blender again")?;
let dir = py(bin, ADDONS_DIR, "RAEA_ADDONS=")?;
run(Command::new(&uvx).args(["mcp-for-blender", "install-addon", "--addons-dir", &dir]), "uvx mcp-for-blender install-addon")?;
let on = run(Command::new(bin).args(["--background", "--python-expr", ENABLE]), "blender")?;
if !on.contains("RAEA_ENABLED=True") {
return Err(format!("the add-on is in {dir} but Blender didn't enable it: enable \"MCP for Blender\" in Preferences > Add-ons"));
}
Ok(format!("MCP add-on installed now ({dir})"))
}
/// `raea setup blender [--check] [--download]`.
pub fn setup(args: &[String]) -> R<String> {
let check = args.iter().any(|a| a == "--check");
let fresh = args.iter().any(|a| a == "--download");
let (bin, from) = match find().filter(|_| !fresh) {
Some((b, f)) => (b, f.to_string()),
None if check => return Ok(format!("CHECKED no Blender found (raea.blender, {}, PATH): raea setup blender downloads Blender {LTS} LTS", own_dir()?.display())),
None => {
let (b, f) = download()?;
run(Command::new("git").args(["config", "--global", "raea.blender"]).arg(&b), "git config")?;
(b, f)
}
};
let v = version(&bin)?;
let add = addon(&bin, check)?;
let head = if check { "CHECKED " } else { "APPLIED " };
Ok(format!("{head} {v} ({from})\n {}\n {add}\n headless: raea blender run SCRIPT.py; live: start Blender and the agent's `blender` MCP server connects (raea skills install adds it)", bin.display()))
}
/// `raea blender run SCRIPT.py [ARGS...]`: the script in a windowless Blender, its args after `--` (sys.argv), its
/// output passed through. Exits as Blender's Python did: --python-exit-code makes an uncaught error fail the run.
pub fn blender(args: &[String]) -> R<String> {
if args.get(1).map(String::as_str) != Some("run") {
return Err(format!("usage: {USAGE}"));
}
let script = args.get(2).ok_or_else(|| format!("which script: {USAGE}"))?;
if !Path::new(script).is_file() {
return Err(format!("no script {script}"));
}
let (bin, _) = find().ok_or("no Blender: raea setup blender finds or downloads one")?;
let st = Command::new(&bin).args(["--background", "--factory-startup", "--python-exit-code", "1", "--python", script, "--"]).args(&args[3..]).status().map_err(|e| format!("{}: {e}", bin.display()))?;
if !st.success() {
return Err(format!("{script} failed in Blender ({st})"));
}
Ok(String::new())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn newest_takes_the_highest_patch_of_the_lts() {
let listing = format!("<a href=\"blender-{LTS}.0-linux-x64.tar.xz\"> <a href=\"blender-{LTS}.12-macos-arm64.dmg\"> <a href=\"blender-{LTS}.3-windows-x64.zip\"> blender-{LTS}.9.sha256 blender-{LTS}.99beta");
assert_eq!(newest(&listing), Some(format!("{LTS}.12")));
assert_eq!(newest("nothing here"), None);
}
#[test]
fn every_supported_platform_names_one_file() {
assert!(asset("5.2.1").unwrap().starts_with("blender-5.2.1-"));
}
}
+53
View File
@@ -0,0 +1,53 @@
//! `raea gen …` (raea-io-gen's verbs), with raea's own local models as the flow's `local:` backend: sao for sound
//! effects, made through the edit's asset store as a render would.
use std::path::{Path, PathBuf};
use raea_io_gen::flow::Step;
use serde_json::json;
struct Local;
impl raea_io_gen::run::Local for Local {
fn names(&self) -> Vec<String> {
vec!["sao".to_string()]
}
fn make(&self, name: &str, step: &Step, dir: &Path, key: &str) -> Result<PathBuf, String> {
let text = |k: &str| step.inputs.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string();
let (prompt, params) = match name {
"sao" => (text("prompt"), json!({"seconds": step.inputs.get("seconds").and_then(|v| v.as_f64()).unwrap_or(2.0)})),
_ => return Err(format!("no local model `{name}` (this host runs sao)")),
};
let store = raea_io_assets::Store { dir: dir.join("assets") };
let seed = step.inputs.get("seed").and_then(|v| v.as_u64()).unwrap_or(1);
let a = store.make(name, &prompt, seed, &params)?;
let out = dir.join(format!("{key}.{}", a.ext));
std::fs::copy(store.path(&a), &out).map_err(|e| format!("{}: {e}", out.display()))?;
Ok(out)
}
}
pub fn generate(args: &[String]) -> Result<String, String> {
raea_io_gen::cli::command(&args[1..], Some(&Local))
}
#[cfg(test)]
mod tests {
// GN14: a flow's sfx step on this Mac's sao, through `raea gen run` as the CLI calls it. It runs the model (about 2
// GB, installed on first use), so it's ignored by default: cargo test -p raea-app-tools generate -- --ignored
#[test]
#[ignore]
fn sfx_step_runs_on_sao() {
let dir = std::env::temp_dir().join(format!("raea-gen-sao-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let flow = dir.join("flow.json");
std::fs::write(&flow, r#"{"flow":1,"steps":{"knock":{"op":"audio.sfx","in":{"prompt":"three firm knocks on a wooden door, close, dry room","seconds":2}}},"out":["knock"]}"#).unwrap();
// as engine/cli hands it over: the verb first
let args: Vec<String> = ["gen", "run", flow.to_str().unwrap(), "-o", dir.to_str().unwrap()].iter().map(|s| s.to_string()).collect();
let out = super::generate(&args).unwrap();
assert!(out.contains("local:sao"), "{out}");
let wav = dir.join("knock.wav");
assert!(std::fs::metadata(&wav).unwrap().len() > 10_000, "{}", wav.display());
}
}
+8 -1
View File
@@ -1,7 +1,14 @@
//! The verbs that run raea's local tools: sound (`raea sao`, `tokensynth`, `setup-audio`, `sounds`: foley and an //! The verbs that run raea's local tools: sound (`raea sao`, `tokensynth`, `setup-audio`, `sounds`: foley and an
//! instrument's notes made by local models, and the open sample libraries), `raea splat` (footage trained into a //! instrument's notes made by local models, and the open sample libraries), `raea splat` (footage trained into a
//! Gaussian splat) and `raea song` (a song's energy map, apps/tools/src/song.rs). //! Gaussian splat), `raea song` (a song's energy map, apps/tools/src/song.rs) and `raea gen` (generation flows on
//! made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, with sao as the local model: apps/tools/src/generate.rs).
pub mod generate;
pub mod song; pub mod song;
pub mod sound; pub mod sound;
pub mod splat; pub mod splat;
/// the MCP servers `raea skills install` offers an agent (blender, for a running Blender)
pub mod agent_mcp;
/// `raea setup blender` and `raea blender run`
pub mod blender;
+1
View File
@@ -86,6 +86,7 @@ pub(crate) fn fetch(url: &str, cached: &Path) -> R<()> {
if cached.exists() { if cached.exists() {
return Ok(()); return Ok(());
} }
raea_io_home::offline(&format!("the sample library file {url}"))?;
std::fs::create_dir_all(cached.parent().unwrap()).map_err(|e| e.to_string())?; std::fs::create_dir_all(cached.parent().unwrap()).map_err(|e| e.to_string())?;
let part = cached.with_extension("part"); let part = cached.with_extension("part");
let o = std::process::Command::new("curl").args(["-fsSL", "--retry", "2", "-o"]).arg(&part).arg(url).output().map_err(|e| format!("curl: {e}"))?; let o = std::process::Command::new("curl").args(["-fsSL", "--retry", "2", "-o"]).arg(&part).arg(url).output().map_err(|e| format!("curl: {e}"))?;
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "raea-app-workspace"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea workspace`, `raea project` and `raea controller`: a workspace's folders, projects and controllers, each change a commit"
[dependencies]
# the controller schema (core/brief controller.rs): a controller file is checked and normalized against it
raea-core-brief = { path = "../../core/brief" }
serde_json = "1"
+209
View File
@@ -0,0 +1,209 @@
//! A workspace's controllers on disk (docs/projects.feature PJ2): controllers/<id>.ts, each `export default
//! controller({...})` from "raea/brief", checked by core/brief's normalize. A project overrides a field's value in its
//! .raea/project (`[controller "delivery.format"] aspect-ratio = 16:9`), so the project's value wins, as git config's
//! own scopes do. Every change is a commit by who made it ("you", or the agent's name with --by).
use super::*;
use raea_core_brief::controller::{self as ctl, Controller, Field, Kind};
use std::process::Command;
const USAGE: &str = "usage: raea controller ls [--json] | get PATH [--json] | set PATH VALUE [--project] [--by NAME] | write FILE.ts [--by NAME] | rm ID [--by NAME]\n (PATH is controller.group.field; a VALUE is JSON for numbers, toggles and lists, else text)";
fn workspace_dir() -> R<PathBuf> {
let here = std::env::current_dir().map_err(|e| e.to_string())?;
workspace::up(&here, ".raea/workspace").ok_or_else(|| "not in a workspace: raea workspace init NAME makes one".to_string())
}
/// Every controller in the workspace, checked, in file order.
pub fn load(ws: &Path, eval: Eval) -> R<Vec<(PathBuf, Controller)>> {
let mut files: Vec<PathBuf> = std::fs::read_dir(ws.join("controllers")).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();
files.sort();
files.into_iter().map(|f| read(&f, eval).map(|c| (f, c))).collect()
}
fn read(f: &Path, eval: Eval) -> R<Controller> {
let raw: serde_json::Value = serde_json::from_str(&eval(f)?).map_err(|e| format!("{}: {e}", f.display()))?;
ctl::normalize(&raw).map_err(|e| format!("{}: {e}", f.display()))
}
/// The module a controller is kept as.
pub fn module(c: &Controller) -> String {
format!("import {{ controller }} from \"raea/brief\";\n\nexport default controller({});\n", ts_literal(&serde_json::to_value(c).unwrap_or_default(), 0))
}
/// A field's value as JSON (its kind's `value`).
fn value_of(f: &Field) -> serde_json::Value {
serde_json::to_value(&f.kind).ok().and_then(|v| v.get("value").cloned()).unwrap_or_default()
}
/// The git-config key for a field's override: `controller.<controller>.<group>.<field>`, which git reads as section
/// controller, subsection "<controller>.<group>", key <field>.
fn key(path: &str) -> String {
format!("controller.{path}")
}
/// A value as typed on the command line or kept in git config: JSON when it parses as JSON of the field's kind, else
/// the text itself (a choice, a text field).
fn parse(f: &Field, s: &str) -> R<serde_json::Value> {
let v = match (&f.kind, serde_json::from_str::<serde_json::Value>(s)) {
(Kind::Text { .. } | Kind::Choice { .. }, Ok(serde_json::Value::String(t))) => serde_json::Value::String(t),
(Kind::Text { .. } | Kind::Choice { .. }, _) => serde_json::Value::String(s.to_string()),
(_, Ok(v)) => v,
(_, Err(_)) => serde_json::Value::String(s.to_string()),
};
ctl::check_value(f, &v)
}
/// The overrides of the project `from` is in, by path.
fn overrides(from: &Path) -> Vec<(String, String)> {
let Some(p) = workspace::up(from, ".raea/project") else { return vec![] };
let text = workspace::config(Some(&p.join(".raea/project")), &["--get-regexp", "^controller\\."]).unwrap_or_default();
text.lines().filter_map(|l| l.split_once(' ')).map(|(k, v)| (k.trim_start_matches("controller.").to_string(), v.to_string())).collect()
}
fn commit(ws: &Path, paths: &[&Path], what: &str, by: &str) -> R<()> {
let mut add = Command::new("git");
add.arg("-C").arg(ws).args(["add", "-A", "--"]).args(paths);
add.status().map_err(|e| format!("git: {e}"))?;
let ok = Command::new("git").arg("-C").arg(ws).args(["-c", &format!("user.name={by}"), "commit", "-q", "-m", &format!("{by}: {what}"), "--"]).args(paths).status().map_err(|e| format!("git: {e}"))?;
if ok.success() { Ok(()) } else { Err(format!("couldn't commit {what}")) }
}
/// `raea controller …`, its specs evaluated by `eval`
pub fn controller(args: &[String], eval: Eval) -> R<String> {
let json_out = args.iter().any(|a| a == "--json");
let by = workspace::flag(args, "--by").unwrap_or("you").trim_start_matches('@').to_string();
let w: Vec<&str> = args.iter().enumerate().filter(|(i, a)| !a.starts_with("--") && !(*i > 0 && args[i - 1] == "--by")).map(|(_, a)| a.as_str()).collect();
let ws = workspace_dir()?;
match w.as_slice() {
["ls"] | [] => ls(&ws, json_out, eval),
["get", path] => get(&ws, path, json_out, eval),
["set", path, value] => set(&ws, path, value, args.iter().any(|a| a == "--project"), &by, eval),
["write", file] => write(&ws, Path::new(file), &by, eval),
["rm", id] => rm(&ws, id, &by),
_ => Err(USAGE.into()),
}
}
/// The controllers as `raea controller ls` prints them, with the overrides of the project `from` is in: what `raea
/// context` shows an agent. None outside a workspace or when it has no controllers.
pub fn summary(from: &Path, eval: Eval) -> Option<String> {
let ws = workspace::up(from, ".raea/workspace")?;
load(&ws, eval).ok().filter(|cs| !cs.is_empty())?;
ls_from(&ws, from, false, eval).ok()
}
fn ls(ws: &Path, json_out: bool, eval: Eval) -> R<String> {
ls_from(ws, &std::env::current_dir().map_err(|e| e.to_string())?, json_out, eval)
}
fn ls_from(ws: &Path, from: &Path, json_out: bool, eval: Eval) -> R<String> {
let cs = load(ws, eval)?;
let over = overrides(from);
let mut rows = vec![];
for (_, c) in &cs {
for g in &c.groups {
for f in &g.fields {
let path = format!("{}.{}.{}", c.id, g.id, f.id);
let mine = over.iter().find(|(k, _)| *k == path).and_then(|(_, v)| parse(f, v).ok());
rows.push((path, f, mine.clone().unwrap_or_else(|| value_of(f)), mine.is_some()));
}
}
}
if json_out {
let fields: Vec<_> = rows.iter().map(|(p, f, v, o)| json!({"path": p, "label": f.label, "type": serde_json::to_value(&f.kind).ok().and_then(|k| k.get("type").cloned()), "value": v, "project": o})).collect();
let list: Vec<_> = cs.iter().map(|(_, c)| serde_json::to_value(c).map(|v| tidy_deep(&v)).unwrap_or_default()).collect();
return Ok(json!({"controllers": list, "fields": fields}).to_string());
}
if cs.is_empty() {
return Ok("no controllers yet: raea controller write FILE.ts adds one (`export default controller({ title, groups })` from \"raea/brief\")".into());
}
let mut out = String::new();
for (_, c) in &cs {
out.push_str(&format!("{} ({})\n", c.title, c.id));
for (p, f, v, o) in rows.iter().filter(|r| r.0.starts_with(&format!("{}.", c.id))) {
out.push_str(&format!(" {p} {}: {}{}\n", f.label, tidy(v), if *o { " (this project)" } else { "" }));
}
}
Ok(out.trim_end().to_string())
}
/// Where a path's field is: its controller, group and field, by index.
fn locate(cs: &[(PathBuf, Controller)], path: &str) -> R<(usize, usize, usize)> {
let mut p = path.splitn(3, '.');
let (c, g, f) = (p.next().unwrap_or(""), p.next().unwrap_or(""), p.next().unwrap_or(""));
let ci = cs.iter().position(|x| x.1.id == c);
let gi = ci.and_then(|ci| cs[ci].1.groups.iter().position(|y| y.id == g));
let fi = ci.zip(gi).and_then(|(ci, gi)| cs[ci].1.groups[gi].fields.iter().position(|z| z.id == f));
match (ci, gi, fi) {
(Some(c), Some(g), Some(f)) => Ok((c, g, f)),
_ => Err(format!("no field at {path}: raea controller ls lists the paths (controller.group.field)")),
}
}
fn find<'a>(cs: &'a [(PathBuf, Controller)], path: &str) -> R<&'a Field> {
let (c, g, f) = locate(cs, path)?;
Ok(&cs[c].1.groups[g].fields[f])
}
fn get(ws: &Path, path: &str, json_out: bool, eval: Eval) -> R<String> {
let cs = load(ws, eval)?;
let f = find(&cs, path)?;
let here = std::env::current_dir().map_err(|e| e.to_string())?;
let mine = overrides(&here).into_iter().find(|(k, _)| k == path).map(|(_, v)| parse(f, &v)).transpose()?;
let v = mine.clone().unwrap_or_else(|| value_of(f));
let v = tidy(&v);
Ok(if json_out { json!({"path": path, "value": v, "project": mine.is_some()}).to_string() } else { v.to_string() })
}
fn set(ws: &Path, path: &str, value: &str, project: bool, by: &str, eval: Eval) -> R<String> {
let mut cs = load(ws, eval)?;
let v = parse(find(&cs, path)?, value)?;
if project {
let here = std::env::current_dir().map_err(|e| e.to_string())?;
let p = workspace::up(&here, ".raea/project").ok_or("--project: not in a project")?;
let text = match &v {
serde_json::Value::String(s) => s.clone(),
v => v.to_string(),
};
let file = p.join(".raea/project");
workspace::set(&file, &key(path), &text)?;
// a submodule project is its own repo; an inline one commits in the workspace
let repo = if p.join(".git").exists() { p.clone() } else { ws.to_path_buf() };
commit(&repo, &[&file], &format!("{path} = {text} for this project"), by)?;
return Ok(format!("{path} = {text} (this project)"));
}
let (c, g, f) = locate(&cs, path)?;
let (file, ctrl) = &mut cs[c];
let field = &mut ctrl.groups[g].fields[f];
let mut kind = serde_json::to_value(&field.kind).map_err(|e| e.to_string())?;
kind["value"] = v.clone();
field.kind = serde_json::from_value(kind).map_err(|e| e.to_string())?;
std::fs::write(&*file, module(ctrl)).map_err(|e| format!("{}: {e}", file.display()))?;
let file = file.clone();
let v = tidy(&v);
let said = v.as_str().map(String::from).unwrap_or_else(|| v.to_string());
commit(ws, &[&file], &format!("{path} = {said}"), by)?;
Ok(format!("{path} = {v}"))
}
fn write(ws: &Path, file: &Path, by: &str, eval: Eval) -> R<String> {
let c = read(file, eval)?;
let to = ws.join("controllers").join(format!("{}.ts", c.id));
let new = !to.exists();
std::fs::create_dir_all(ws.join("controllers")).map_err(|e| e.to_string())?;
std::fs::write(&to, module(&c)).map_err(|e| format!("{}: {e}", to.display()))?;
commit(ws, &[&to], &format!("{} controller {}", if new { "add" } else { "rewrite" }, c.id), by)?;
let n = |k: usize, what: &str| format!("{k} {what}{}", if k == 1 { "" } else { "s" });
Ok(format!("{}: {} ({}, {})", to.display(), c.title, n(c.groups.len(), "group"), n(c.groups.iter().map(|g| g.fields.len()).sum(), "field")))
}
fn rm(ws: &Path, id: &str, by: &str) -> R<String> {
let file = ws.join("controllers").join(format!("{id}.ts"));
if !file.is_file() {
return Err(format!("no controller {id}: raea controller ls lists them"));
}
std::fs::remove_file(&file).map_err(|e| format!("{}: {e}", file.display()))?;
commit(ws, &[&file], &format!("remove controller {id}"), by)?;
Ok(format!("removed {id} (git revert brings it back)"))
}
+138
View File
@@ -0,0 +1,138 @@
//! `raea doctor [--fix]` (docs/skills.feature SK10): drift between a project's files and what this raea reads. Old brief
//! files raea no longer reads, a workspace or project file missing what this version writes (or not included from the
//! repo's git config), and an agent's copy of the raea skill from another version. `raea context` runs the same checks
//! and prints CONTEXT_STALE when any finds something, so they stay cheap: file reads and git config, no engine.
use super::*;
use crate::workspace::{get, git, include, new_id, set};
/// One thing doctor found, and whether `--fix` can fix it.
pub struct Finding {
pub says: String,
fix: Fix,
}
enum Fix {
No,
/// a key missing from a git-config file: (file, key, value)
Set(PathBuf, String, String),
/// the include in a repo's config that makes `git config` read its committed file: (repo, file)
Include(PathBuf, PathBuf),
/// an agent's skills reinstalled from this raea
Skills(String),
}
impl Finding {
pub fn fixable(&self) -> bool {
!matches!(self.fix, Fix::No)
}
}
/// Old brief files under a folder (raea reads only brief.ts, script.ts and taste.ts since 11-05), a few levels down.
fn old_briefs(dir: &Path, depth: usize, out: &mut Vec<Finding>) {
let Ok(rd) = std::fs::read_dir(dir) else { return };
for e in rd.flatten() {
let p = e.path();
let name = e.file_name().to_string_lossy().into_owned();
if p.is_dir() {
if depth > 0 && !name.starts_with('.') && name != "node_modules" && name != "media" && name != "out" {
old_briefs(&p, depth - 1, out);
}
} else if [".brief", ".board"].iter().any(|x| name.ends_with(x)) {
out.push(Finding { says: format!("{}: an old brief file, which raea no longer reads; rewrite it as brief.ts (export default brief({{...}}) from \"raea/brief\") and delete it", p.display()), fix: Fix::No });
}
}
}
/// A committed git-config file's keys this version writes, and its include from the repo's config.
fn format(repo: &Path, file: &Path, keys: &[(&str, String)], out: &mut Vec<Finding>) {
for (k, v) in keys {
if get(file, k).is_none() {
out.push(Finding { says: format!("{}: no {k} (an older format); --fix sets it to {v}", file.display()), fix: Fix::Set(file.to_path_buf(), k.to_string(), v.clone()) });
}
}
// only a folder that is its own repo includes its file (a workspace, a split project); an inline project shares
// the workspace's repo, whose config must not take one project's keys
let own = git(repo, &["rev-parse", "--show-toplevel"]).ok().and_then(|t| Path::new(&t).canonicalize().ok()) == repo.canonicalize().ok();
let first = keys.first().map(|(k, _)| *k).unwrap_or_default();
let read = git(repo, &["config", first]).ok().filter(|v| !v.is_empty());
if own && read.is_none() && get(file, first).is_some() {
out.push(Finding { says: format!("{}: git config doesn't read it (no include in the repo's config); --fix adds it", file.display()), fix: Fix::Include(repo.to_path_buf(), file.to_path_buf()) });
}
}
/// The `version:` in a SKILL.md's front matter.
fn skill_version(md: &Path) -> Option<String> {
let text = std::fs::read_to_string(md).ok()?;
let front = text.strip_prefix("---\n")?.split("\n---\n").next()?;
front.lines().find_map(|l| l.strip_prefix("version:")).map(|v| v.trim().to_string())
}
/// What doctor finds from a folder: `skills` are (agent, its skills folder), `version` this raea's.
pub fn findings(from: &Path, skills: &[(&str, PathBuf)], version: &str) -> Vec<Finding> {
let mut out = Vec::new();
let ws = up(from, ".raea/workspace");
let project = up(from, ".raea/project");
let base = project.clone().or_else(|| ws.clone()).unwrap_or_else(|| from.to_path_buf());
old_briefs(&base, if project.is_some() { 2 } else { 1 }, &mut out);
if let Some(ws) = &ws {
let name = ws.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let keys = [("workspace.id", new_id("ws")), ("workspace.name", name), ("workspace.layout", "monorepo".to_string())];
format(ws, &ws.join(".raea/workspace"), &keys, &mut out);
}
if let Some(p) = &project {
let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let keys = [("project.id", new_id("pj")), ("project.name", name)];
format(p, &p.join(".raea/project"), &keys, &mut out);
}
for (agent, dir) in skills {
let md = dir.join("raea/SKILL.md");
if !md.is_file() {
continue;
}
let have = skill_version(&md).unwrap_or_else(|| "unversioned".into());
if have != version {
out.push(Finding { says: format!("{}: the raea skill {agent} reads is {have}, this raea is {version}; --fix reinstalls it", md.display()), fix: Fix::Skills(agent.to_string()) });
}
}
out
}
/// `raea doctor [--fix] [DIR]`: what it found and, with --fix, what it fixed. `reinstall` puts an agent's skills back
/// (the raea CLI's `skills install`).
pub fn doctor(args: &[String], skills: &[(&str, PathBuf)], version: &str, reinstall: &dyn Fn(&str) -> R<String>) -> R<String> {
let fix = args.iter().any(|a| a == "--fix");
let from = PathBuf::from(args.iter().find(|a| !a.starts_with("--")).map(String::as_str).unwrap_or("."));
let found = findings(&from, skills, version);
if found.is_empty() {
return Ok("CHECKED nothing to fix: this folder's files and the agents' raea skill match this raea".into());
}
let mut lines = Vec::new();
let mut fixed = 0;
for f in &found {
let done = match (&f.fix, fix) {
(Fix::Set(file, k, v), true) => set(file, k, v).map(|_| true),
(Fix::Include(repo, file), true) => include(repo, file).map(|_| true),
(Fix::Skills(agent), true) => reinstall(agent).map(|_| true),
_ => Ok(false),
};
match done {
Ok(true) => {
fixed += 1;
lines.push(format!(" fixed {}", f.says));
}
Ok(false) => lines.push(format!(" {} {}", if f.fixable() { "fix " } else { "by hand" }, f.says)),
Err(e) => lines.push(format!(" failed {}: {e}", f.says)),
}
}
// a workspace's own files changed: commit them, as every change raea makes there is
if fix && fixed > 0 {
for marker in [".raea/workspace", ".raea/project"] {
if let Some(repo) = up(&from, marker) {
let _ = crate::workspace::commit(&repo, &[marker], "doctor --fix");
}
}
}
let can = found.iter().filter(|f| f.fixable()).count();
let head = if fix { format!("APPLIED {fixed} of {} fixed", found.len()) } else { format!("CHECKED {} to fix ({can} by raea doctor --fix)", found.len()) };
Ok(format!("{head}\n{}", lines.join("\n")))
}
+25
View File
@@ -0,0 +1,25 @@
//! A workspace's folders and files (docs/projects.feature PJ1-PJ4): `raea workspace`, `raea project` (with split and
//! join) and `raea controller`. A workspace is a git repo raea changes by commits; its controllers are spec modules,
//! which the raea CLI evaluates on the engine and hands in as an `Eval`, so this crate needs no engine of its own.
use std::path::{Path, PathBuf};
use serde_json::json;
mod controllers;
pub mod doctor;
mod literal;
pub mod next;
mod storage;
mod workspace;
pub use controllers::{controller, module, summary};
pub use literal::{tidy, tidy_deep, ts_literal};
pub use workspace::{project, projects, root, slug, up, workspace};
pub type R<T> = Result<T, String>;
/// A spec module's default export as JSON: the raea CLI's spec_json, which runs it on the engine.
pub type Eval = fn(&Path) -> R<String>;
#[cfg(test)]
mod tests;
+37
View File
@@ -0,0 +1,37 @@
//! Spec modules as raea writes them: a value as a TypeScript literal, and whole numbers kept whole.
/// A value as a TypeScript literal for a spec module: unquoted keys where they can be, nulls and empty lists left out.
pub fn ts_literal(v: &serde_json::Value, indent: usize) -> String {
use serde_json::Value;
let (pad, end) = (" ".repeat(indent + 1), " ".repeat(indent));
match v {
Value::Array(a) if a.iter().all(Value::is_string) && v.to_string().len() < 70 => format!("[{}]", a.iter().map(Value::to_string).collect::<Vec<_>>().join(", ")),
Value::Array(a) => format!("[\n{}{end}]", a.iter().map(|x| format!("{pad}{},\n", ts_literal(x, indent + 1))).collect::<String>()),
Value::Object(o) => {
let ident = |k: &str| k.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
let kept = o.iter().filter(|(_, x)| !x.is_null() && !x.as_array().is_some_and(Vec::is_empty));
let body: String = kept.map(|(k, x)| format!("{pad}{}: {},\n", if ident(k) { k.clone() } else { Value::String(k.clone()).to_string() }, ts_literal(x, indent + 1))).collect();
format!("{{\n{body}{end}}}")
}
v => tidy(v).to_string(),
}
}
/// A number that's whole (as f64 values from Rust are, 45.0) written as an integer.
pub fn tidy(v: &serde_json::Value) -> serde_json::Value {
match v.as_f64() {
Some(n) if v.is_f64() && n.fract() == 0.0 && n.abs() < 1e15 => serde_json::Value::from(n as i64),
_ => match v {
serde_json::Value::Array(a) => serde_json::Value::Array(a.iter().map(tidy).collect()),
v => v.clone(),
},
}
}
/// `tidy` through a whole value: objects and arrays too.
pub fn tidy_deep(v: &serde_json::Value) -> serde_json::Value {
match v {
serde_json::Value::Object(o) => serde_json::Value::Object(o.iter().filter(|(_, x)| !x.is_null()).map(|(k, x)| (k.clone(), tidy_deep(x))).collect()),
serde_json::Value::Array(a) => serde_json::Value::Array(a.iter().map(tidy_deep).collect()),
v => tidy(v),
}
}
+86
View File
@@ -0,0 +1,86 @@
//! `raea next` (docs/skills.feature SK10): the two or three useful next steps for a project, read from its files: the
//! brief (what it still needs, from the raea CLI's brief doctor), the storyboard its modes want, its compositions, its
//! renders in out/ and their checks (`raea check ... -o out/NAME.check.json`). A menu for the agent or the person to
//! pick from; nothing runs.
use super::*;
use std::time::SystemTime;
/// What the raea CLI read from the project's brief.
pub struct Brief {
/// what the brief still needs (empty when it's shaped)
pub needs: Vec<String>,
pub modes: Vec<String>,
}
fn modified(p: &Path) -> SystemTime {
std::fs::metadata(p).and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH)
}
fn files(dir: &Path, ext: &str) -> Vec<PathBuf> {
let mut v: Vec<PathBuf> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_file() && p.to_string_lossy().ends_with(ext)).collect();
v.sort_by_key(|p| std::cmp::Reverse(modified(p)));
v
}
fn name(p: &Path) -> String {
let full = p.to_string_lossy();
full.rsplit(['/', '\\']).next().unwrap_or_default().to_string()
}
/// The P0 and P1 issues a check file holds, as its lines.
fn blocking(check: &Path) -> Vec<String> {
let Ok(j) = std::fs::read_to_string(check).map_err(drop).and_then(|t| serde_json::from_str::<serde_json::Value>(&t).map_err(drop)) else { return vec![] };
let mut out = Vec::new();
for i in j["issues"].as_array().into_iter().flatten() {
if let (Some(p @ ("P0" | "P1")), Some(says)) = (i["p"].as_str(), i["says"].as_str()) {
out.push(format!("{p} {says}"));
}
}
out
}
/// The steps, most useful first, at most three. `stale` is what `raea doctor` found here.
pub fn steps(dir: &Path, brief: &Brief, stale: usize) -> Vec<String> {
let mut out = Vec::new();
if stale > 0 {
out.push(format!("raea doctor: {stale} thing(s) in this project's files or your raea skill don't match this raea (`raea doctor --fix`)"));
}
if let Some(first) = brief.needs.first() {
out.push(format!("shape the brief: {first} (ask the person, or write your best guess and add it to `assumed`)"));
}
let boarded = brief.modes.iter().any(|m| ["pitch", "explain", "story"].contains(&m.as_str()));
let scripts = files(dir, ".script.ts");
if boarded && scripts.is_empty() {
out.push("plan it: write the storyboard as NAME.script.ts beside the brief (`raea spec NAME.script.ts` checks it) and wait for the person's approval".into());
}
let comps: Vec<PathBuf> = files(dir, ".tsx").into_iter().filter(|p| std::fs::read_to_string(p).map(|t| t.contains("registerRoot")).unwrap_or(false)).collect();
let renders = files(&dir.join("out"), ".mp4");
match (comps.first(), renders.first()) {
(None, _) => out.push("make the first item: one .tsx whose root registers a Composition (`raea guide craft` first)".into()),
(Some(c), None) => out.push(format!("render {}: stills to look at first (`raea render {} --at 0,45,89 -o frames/`), then the video into out/", name(c), name(c))),
(Some(c), Some(r)) if modified(c) > modified(r) => out.push(format!("render again: {} changed after {}", name(c), name(r))),
(_, Some(r)) => {
let check = r.with_extension("check.json");
if !check.is_file() || modified(&check) < modified(r) {
out.push(format!("check {}: `raea check out/{} -o out/{}` (add --manifest when the render wrote one)", name(r), name(r), name(&check)));
} else {
match blocking(&check).first() {
Some(issue) => out.push(format!("polish {}: {issue} (`raea guide polish`)", name(r))),
None => out.push(format!("show {}: post it to the project's feed (feed_post), or give the person its path, and read their notes", name(r))),
}
}
}
}
out.truncate(3);
out
}
/// `raea next`'s text.
pub fn text(dir: &Path, brief: &Brief, stale: usize) -> String {
let s = steps(dir, brief, stale);
let mut t = format!("raea next: {}\n", dir.display());
for (i, line) in s.iter().enumerate() {
t.push_str(&format!("{}. {line}\n", i + 1));
}
t.trim_end().to_string()
}
+95
View File
@@ -0,0 +1,95 @@
//! A project changing storage with its history (docs/projects.feature PJ4): `raea project split NAME` makes an inline
//! project its own repo, a submodule, from `git subtree split` (its commits, rewritten to the folder); `raea project
//! join NAME` brings a submodule back in as a folder, its history merged under projects/NAME (`git subtree add`).
//! .raea/workspace and .gitmodules change in the same commit.
use super::*;
use workspace::{commit, get, git, include, set};
fn workspace_and(name: &str) -> R<(PathBuf, String, PathBuf)> {
let here = std::env::current_dir().map_err(|e| e.to_string())?;
let ws = workspace::up(&here, ".raea/workspace").ok_or("not in a workspace")?;
let key = workspace::slug(name);
let rel = get(&ws.join(".raea/workspace"), &format!("project.{key}.path")).ok_or_else(|| format!("no project {name} in this workspace: raea workspace lists them"))?;
let dir = ws.join(&rel);
Ok((ws, rel, dir))
}
fn storage_of(ws: &Path, name: &str) -> String {
get(&ws.join(".raea/workspace"), &format!("project.{}.storage", workspace::slug(name))).unwrap_or_else(|| "inline".into())
}
fn clean(ws: &Path) -> R<()> {
if !git(ws, &["status", "--porcelain", "--untracked-files=no"])?.is_empty() {
return Err("the workspace has changes not yet committed: commit or drop them first, so the move is one change".into());
}
Ok(())
}
/// `raea project split NAME [--remote URL]`: an inline project made a submodule, its history kept.
pub fn split(name: &str, remote: Option<&str>) -> R<String> {
let (ws, rel, dir) = workspace_and(name)?;
if storage_of(&ws, name) == "submodule" {
return Err(format!("{name} is a submodule already"));
}
clean(&ws)?;
let branch = format!("raea-split-{}", workspace::slug(name));
let tip = git(&ws, &["subtree", "split", "-q", &format!("--prefix={rel}"), "-b", &branch])?;
let n = git(&ws, &["rev-list", "--count", &branch])?;
// the project's folder leaves the workspace's tree, then comes back as its own repo with that history
git(&ws, &["rm", "-r", "-q", "--", &rel])?;
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
git(&dir, &["init", "-q"])?;
git(&dir, &["fetch", "-q", &ws.to_string_lossy(), &branch])?;
git(&dir, &["reset", "-q", "--hard", "FETCH_HEAD"])?;
git(&ws, &["branch", "-q", "-D", &branch])?;
if Path::new(&dir.join(".gitattributes")).is_file() || ws.join(".gitattributes").is_file() {
// media stays in LFS: the workspace's attributes come along
let _ = std::fs::copy(ws.join(".gitattributes"), dir.join(".gitattributes"));
let _ = git(&dir, &["add", ".gitattributes"]).and_then(|_| git(&dir, &["commit", "-q", "-m", "raea: LFS for media/ and out/", "--", ".gitattributes"]));
}
let url = match remote {
Some(u) => {
git(&dir, &["remote", "add", "origin", u])?;
git(&dir, &["push", "-q", "-u", "origin", "HEAD"])?;
u.to_string()
}
None => format!("./{rel}"),
};
git(&ws, &["-c", "protocol.file.allow=always", "submodule", "add", "-q", &url, &rel])?;
set(&ws.join(".raea/workspace"), &format!("project.{}.storage", workspace::slug(name)), "submodule")?;
include(&dir, &dir.join(".raea/project"))?;
commit(&ws, &[".raea/workspace", ".gitmodules", &rel], &format!("project {name} split into its own repo ({n} commits kept)"))?;
Ok(format!("{}: {name} is a submodule now, its own repo with {n} commits (tip {})", dir.display(), &tip[..tip.len().min(9)]))
}
/// `raea project join NAME`: a submodule brought back in as a folder, its history merged under its path.
pub fn join(name: &str) -> R<String> {
let (ws, rel, dir) = workspace_and(name)?;
if storage_of(&ws, name) != "submodule" {
return Err(format!("{name} is a folder in the workspace already"));
}
clean(&ws)?;
if !git(&dir, &["status", "--porcelain"])?.is_empty() {
return Err(format!("{name} has changes not yet committed: commit them first, so they come along"));
}
// the submodule's repo is kept aside while its folder leaves, then its history comes in under the same path
let aside = std::env::temp_dir().join(format!("raea-join-{}-{}", workspace::slug(name), std::process::id()));
let _ = std::fs::remove_dir_all(&aside);
git(&ws, &["clone", "-q", "--no-local", &dir.to_string_lossy(), &aside.to_string_lossy()])?;
git(&ws, &["submodule", "deinit", "-q", "-f", "--", &rel])?;
git(&ws, &["rm", "-q", "-f", "--", &rel])?;
let modules = PathBuf::from(git(&ws, &["rev-parse", "--path-format=absolute", "--git-common-dir"])?).join("modules").join(&rel);
let _ = std::fs::remove_dir_all(&modules);
let _ = std::fs::remove_dir_all(&dir);
set(&ws.join(".raea/workspace"), &format!("project.{}.storage", workspace::slug(name)), "inline")?;
let gitmodules = ws.join(".gitmodules");
let mut paths = vec![".raea/workspace"];
if gitmodules.is_file() {
paths.push(".gitmodules");
}
commit(&ws, &paths, &format!("project {name} leaves its submodule"))?;
git(&ws, &["subtree", "add", "-q", &format!("--prefix={rel}"), &aside.to_string_lossy(), "HEAD", "-m", &format!("raea: project {name} joined, its history under {rel}")])?;
let _ = std::fs::remove_dir_all(&aside);
Ok(format!("{}: {name} is a folder in the workspace now, its history merged", dir.display()))
}
+73
View File
@@ -0,0 +1,73 @@
use super::*;
#[test]
fn a_name_is_its_folder() {
assert_eq!(slug("Shane's Studio"), "shane-s-studio");
assert_eq!(slug(" CJ / Reel 2 "), "cj-reel-2");
}
#[test]
fn a_spec_module_is_tidy_typescript() {
// keys unquoted where they can be, nulls and empty lists left out, whole numbers whole, short string lists inline
let v = json!({"id": "delivery", "help": null, "tags": [], "n": 45.0, "options": ["9:16", "16:9"], "odd-key": 1});
assert_eq!(ts_literal(&v, 0), "{\n id: \"delivery\",\n n: 45,\n \"odd-key\": 1,\n options: [\"9:16\", \"16:9\"],\n}");
}
#[test]
fn up_finds_the_nearest_marker() {
let root = std::env::temp_dir().canonicalize().unwrap().join(format!("raea-ws-up-{}", std::process::id()));
let deep = root.join("projects/launch/media");
std::fs::create_dir_all(&deep).unwrap();
std::fs::create_dir_all(root.join(".raea")).unwrap();
std::fs::write(root.join(".raea/workspace"), "").unwrap();
assert_eq!(up(&deep, ".raea/workspace").as_deref(), Some(root.as_path()));
assert_eq!(up(&deep, ".raea/project"), None);
let _ = std::fs::remove_dir_all(&root);
}
fn scratch(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("raea-ws-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn next_walks_a_project_from_brief_to_show() {
let d = scratch("next");
let shaped = next::Brief { needs: vec![], modes: vec!["tool".into()] };
let unshaped = next::Brief { needs: vec!["who it's for (audience)".into()], modes: vec!["pitch".into()] };
let s = next::steps(&d, &unshaped, 0);
assert!(s[0].starts_with("shape the brief: who it's for") && s[1].starts_with("plan it") && s[2].starts_with("make the first item"), "{s:?}");
assert!(next::steps(&d, &shaped, 2)[0].starts_with("raea doctor: 2"));
std::fs::write(d.join("piece.tsx"), "registerRoot(() => null)").unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("render piece.tsx"));
std::fs::create_dir_all(d.join("out")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
std::fs::write(d.join("out/piece.mp4"), "").unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("check piece.mp4"));
std::thread::sleep(std::time::Duration::from_millis(20));
std::fs::write(d.join("out/piece.check.json"), r#"{"issues":[{"p":"P1","says":"text clipped at 2 s"}]}"#).unwrap();
assert_eq!(next::steps(&d, &shaped, 0)[0], "polish piece.mp4: P1 text clipped at 2 s (`raea guide polish`)");
std::fs::write(d.join("out/piece.check.json"), r#"{"issues":[{"p":"P3","says":"minor"}]}"#).unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("show piece.mp4"));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn doctor_finds_old_briefs_and_old_skills() {
let d = scratch("doctor");
std::fs::write(d.join("acme.brief"), "title: x").unwrap();
std::fs::create_dir_all(d.join("skills/raea")).unwrap();
std::fs::write(d.join("skills/raea/SKILL.md"), "---\nname: raea\nversion: 0.0.1\n---\n").unwrap();
let skills = [("claude", d.join("skills"))];
let found = doctor::findings(&d, &skills, "0.0.2");
assert_eq!(found.len(), 2, "{:?}", found.iter().map(|f| &f.says).collect::<Vec<_>>());
assert!(found[0].says.contains("acme.brief") && !found[0].fixable());
assert!(found[1].says.contains("is 0.0.1, this raea is 0.0.2") && found[1].fixable());
assert!(doctor::findings(&d, &skills, "0.0.1").len() == 1);
let reinstalled = std::cell::Cell::new(false);
let out = doctor::doctor(&["--fix".into(), d.display().to_string()], &skills, "0.0.2", &|a| { reinstalled.set(a == "claude"); Ok(String::new()) }).unwrap();
assert!(reinstalled.get() && out.starts_with("APPLIED 1 of 2 fixed"), "{out}");
let _ = std::fs::remove_dir_all(&d);
}
+359
View File
@@ -0,0 +1,359 @@
//! Workspaces and projects on disk (docs/projects.feature PJ1). A workspace is a git repo holding .raea/workspace, a
//! git-config file that is committed, and projects/<name>/, each holding .raea/project. raea writes an include into
//! the repo's own .git/config, so `git config workspace.layout` answers from the committed file; git never loads a
//! committed config by itself. Every change raea makes here is a commit.
use super::*;
use std::process::Command;
const USAGE: &str = "usage: raea workspace [--json] | raea workspace init [NAME] [--layout monorepo|submodules] | raea workspace adopt DIR [--name NAME] [--layout monorepo|submodules]\n raea project [--json] | raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME";
pub(crate) fn git(dir: &Path, args: &[&str]) -> R<String> {
let out = Command::new("git").arg("-C").arg(dir).args(args).output().map_err(|e| format!("git: {e}"))?;
if !out.status.success() {
return Err(format!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim()));
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
/// `git config` on a file (or the global config when `file` is None), its output trimmed; Err when git says no.
pub(crate) fn config(file: Option<&Path>, args: &[&str]) -> R<String> {
let mut c = Command::new("git");
c.arg("config");
if let Some(f) = file {
c.arg("-f").arg(f);
}
let out = c.args(args).output().map_err(|e| format!("git: {e}"))?;
if !out.status.success() {
return Err(format!("git config {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim()));
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
/// A git-config file's value, None when unset.
pub(crate) fn get(file: &Path, key: &str) -> Option<String> {
config(Some(file), &[key]).ok().filter(|v| !v.is_empty())
}
pub(crate) fn set(file: &Path, key: &str, value: &str) -> R<()> {
let dir = file.parent().unwrap_or(Path::new("."));
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
config(Some(file), &[key, value]).map(drop)
}
/// Every key of a git-config file, in order, as (key, value).
fn all(file: &Path) -> Vec<(String, String)> {
let list = config(Some(file), &["--list", "-z"]).unwrap_or_default();
list.split('\0').filter_map(|e| e.split_once('\n')).map(|(k, v)| (k.to_string(), v.to_string())).collect()
}
/// The value after `name` in args.
pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
/// The words of a command that aren't flags or a flag's value.
fn words(args: &[String]) -> Vec<&str> {
let takes = ["--layout", "--storage", "--name", "--remote"];
args.iter().enumerate().filter(|(i, a)| !a.starts_with("--") && !(*i > 0 && takes.contains(&args[i - 1].as_str()))).map(|(_, a)| a.as_str()).collect()
}
/// A name as a folder: lowercase, dashes.
pub fn slug(s: &str) -> String {
let mut out = String::new();
for c in s.trim().to_lowercase().chars() {
if c.is_ascii_alphanumeric() {
out.push(c);
} else if !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
}
out.trim_end_matches('-').to_string()
}
/// A new id: the prefix and eight hex digits from the clock and the process.
pub(crate) fn new_id(prefix: &str) -> String {
let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
format!("{prefix}_{:08x}", (t as u64 ^ (std::process::id() as u64) << 20) as u32)
}
/// Where workspaces live on this machine: `git config --global raea.root`, else ~/Studio.
pub fn root() -> PathBuf {
let set = config(None, &["--global", "raea.root"]).ok().filter(|s| !s.is_empty());
let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default();
match set {
Some(s) if s.starts_with("~/") => home.join(&s[2..]),
Some(s) => PathBuf::from(s),
None => home.join("Studio"),
}
}
/// The nearest folder at or above `from` that holds `marker` (.raea/workspace, .raea/project).
pub fn up(from: &Path, marker: &str) -> Option<PathBuf> {
let from = from.canonicalize().ok()?;
from.ancestors().find(|d| d.join(marker).is_file()).map(Path::to_path_buf)
}
/// The include in a repo's own config that makes `git config` read a committed file. Idempotent; the path is relative
/// to the config file, which for a submodule lives under the workspace's .git/modules.
pub(crate) fn include(repo: &Path, file: &Path) -> R<()> {
let cfg = PathBuf::from(git(repo, &["rev-parse", "--path-format=absolute", "--git-path", "config"])?);
let file = file.canonicalize().map_err(|e| format!("{}: {e}", file.display()))?;
let rel = relative(cfg.parent().unwrap_or(Path::new("/")), &file);
let have = config(Some(&cfg), &["--get-all", "include.path"]).unwrap_or_default();
if have.lines().any(|l| l.trim() == rel) {
return Ok(());
}
config(Some(&cfg), &["--add", "include.path", &rel]).map(drop)
}
fn relative(from: &Path, to: &Path) -> String {
let (a, b): (Vec<_>, Vec<_>) = (from.components().collect(), to.components().collect());
let same = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
let mut out: Vec<String> = std::iter::repeat_n("..".to_string(), a.len() - same).collect();
out.extend(b[same..].iter().map(|c| c.as_os_str().to_string_lossy().into_owned()));
out.join("/")
}
fn write_new(path: &Path, text: &str) -> R<()> {
if path.exists() {
return Ok(());
}
if let Some(d) = path.parent() {
std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
}
std::fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))
}
/// A commit of these paths, when they changed: "raea: what".
pub(crate) fn commit(repo: &Path, paths: &[&str], what: &str) -> R<()> {
let mut add = vec!["add", "--"];
add.extend(paths);
git(repo, &add)?;
if git(repo, &["diff", "--cached", "--quiet"]).is_ok() {
return Ok(());
}
git(repo, &["commit", "-q", "-m", &format!("raea: {what}"), "--"]).map(|_| ())
}
const AGENTS_PROJECT: &str = "# Agents\n\nRun `raea context .` here before any work: the taste, this project's brief.ts and script.ts, its look and the guides\nits modes need, in the order to read them. Specs are TypeScript (`export default brief({...})` from \"raea/brief\").\n";
/// `raea workspace …`
pub fn workspace(args: &[String]) -> R<String> {
let w = words(args);
match w.first().copied() {
None => show_workspace(args.iter().any(|a| a == "--json")),
Some("init") => init(w.get(1).copied(), flag(args, "--layout")),
Some("adopt") => adopt(Path::new(w.get(1).ok_or(USAGE)?), flag(args, "--name"), flag(args, "--layout")),
Some(v) => Err(format!("raea workspace has no {v:?}\n{USAGE}")),
}
}
fn layout_of(l: Option<&str>) -> R<&str> {
match l.unwrap_or("monorepo") {
l @ ("monorepo" | "submodules") => Ok(l),
l => Err(format!("a layout is monorepo or submodules, not {l:?}")),
}
}
/// `init` in a workspace makes it work after a clone (the includes again, for it and its submodule projects); `init
/// NAME` elsewhere makes a new workspace under raea.root.
fn init(name: Option<&str>, layout: Option<&str>) -> R<String> {
let here = std::env::current_dir().map_err(|e| e.to_string())?;
if let Some(ws) = up(&here, ".raea/workspace").filter(|_| name.is_none()) {
include(&ws, &ws.join(".raea/workspace"))?;
let mut fixed = 0;
for (_, path, storage) in projects(&ws) {
let dir = ws.join(&path);
if storage == "submodule" && dir.join(".git").exists() && dir.join(".raea/project").is_file() {
include(&dir, &dir.join(".raea/project"))?;
fixed += 1;
}
}
return Ok(format!("{}: git config reads .raea/workspace{}", ws.display(), match fixed { 0 => String::new(), 1 => " and a submodule project's .raea/project".into(), n => format!(" and {n} submodule projects' .raea/project") }));
}
let name = name.ok_or(USAGE)?;
let dir = root().join(slug(name));
if dir.join(".raea/workspace").is_file() {
return Err(format!("{} is a workspace already: `cd` there and `raea workspace init` re-adds its includes", dir.display()));
}
make_workspace(&dir, name, layout_of(layout)?)?;
Ok(format!("{}: workspace {name:?} ({}); next: cd there, raea project new NAME", dir.display(), layout_of(layout)?))
}
/// An existing folder made a workspace in place: git when it isn't a repo, .raea/workspace, and each folder in it
/// holding a brief.ts registered as an inline project. Nothing is moved or deleted.
fn adopt(dir: &Path, name: Option<&str>, layout: Option<&str>) -> R<String> {
let dir = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?;
let name = name.map(String::from).unwrap_or_else(|| dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default());
make_workspace(&dir, &name, layout_of(layout)?)?;
let mut found = vec![];
for base in [dir.clone(), dir.join("projects")] {
for e in std::fs::read_dir(&base).into_iter().flatten().flatten() {
let p = e.path();
if p.join("brief.ts").is_file() && !p.join(".raea/project").is_file() {
let rel = relative(&dir, &p);
register(&dir, &p, &rel, "inline")?;
found.push(rel);
}
}
}
let mut paths = vec![".raea/workspace"];
let projs: Vec<String> = found.iter().map(|r| format!("{r}/.raea/project")).collect();
paths.extend(projs.iter().map(String::as_str));
commit(&dir, &paths, &format!("adopt {name} as a workspace ({})", count(found.len())))?;
Ok(format!("{}: workspace {name:?}, {}{}", dir.display(), count(found.len()), if found.is_empty() { String::new() } else { format!(": {}", found.join(", ")) }))
}
fn count(n: usize) -> String {
if n == 1 { "1 project".into() } else { format!("{n} projects") }
}
fn make_workspace(dir: &Path, name: &str, layout: &str) -> R<()> {
// never a workspace in another repo's own folder (on a case-insensitive disk ~/Raea is ~/raea, raea's checkout); a
// repo further up, as a home folder kept in git, is fine: the workspace is a repo of its own inside it
let parent = dir.parent().unwrap_or(Path::new("/"));
if !dir.join(".git").exists() && parent.exists() {
let top = git(parent, &["rev-parse", "--show-toplevel"]).ok().map(PathBuf::from);
if top.is_some_and(|t| t.canonicalize().ok() == parent.canonicalize().ok()) {
return Err(format!("{} would be a folder of the git repo {}: set where workspaces go, `git config --global raea.root ~/Studio`", dir.display(), parent.display()));
}
}
std::fs::create_dir_all(dir.join("projects")).map_err(|e| format!("{}: {e}", dir.display()))?;
if !dir.join(".git").exists() {
git(dir, &["init", "-q"])?;
}
let file = dir.join(".raea/workspace");
if get(&file, "workspace.id").is_none() {
set(&file, "workspace.id", &new_id("ws"))?;
}
set(&file, "workspace.name", name)?;
set(&file, "workspace.layout", layout)?;
include(dir, &file)?;
write_new(&dir.join("controllers/.gitkeep"), "")?;
write_new(&dir.join("projects/.gitkeep"), "")?;
write_new(&dir.join("taste.ts"), &format!("import {{ taste }} from \"raea/brief\";\n\n// {name}'s house rules: every project here follows them, after the person's own taste.\nexport default taste({{\n title: {:?},\n sections: [],\n}});\n", format!("{name}: house rules")))?;
write_new(&dir.join(".gitattributes"), "media/** filter=lfs diff=lfs merge=lfs -text\nout/** filter=lfs diff=lfs merge=lfs -text\n")?;
commit(dir, &[".raea/workspace", "controllers/.gitkeep", "projects/.gitkeep", "taste.ts", ".gitattributes"], &format!("workspace {name}"))
}
/// The workspace's projects: (name, path, storage), from .raea/workspace.
pub fn projects(ws: &Path) -> Vec<(String, String, String)> {
let mut out: Vec<(String, String, String)> = vec![];
for (k, v) in all(&ws.join(".raea/workspace")) {
let Some(rest) = k.strip_prefix("project.") else { continue };
let Some((name, key)) = rest.rsplit_once('.') else { continue };
let at = out.iter().position(|p| p.0 == name).unwrap_or_else(|| {
out.push((name.to_string(), format!("projects/{name}"), "inline".into()));
out.len() - 1
});
match key {
"path" => out[at].1 = v,
"storage" => out[at].2 = v,
_ => {}
}
}
out
}
/// A project's own .raea/project, and its line in the workspace's.
fn register(ws: &Path, dir: &Path, rel: &str, storage: &str) -> R<String> {
let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let file = dir.join(".raea/project");
let id = get(&file, "project.id").unwrap_or_else(|| new_id("pj"));
set(&file, "project.id", &id)?;
set(&file, "project.name", &name)?;
let wsf = ws.join(".raea/workspace");
set(&wsf, &format!("project.{name}.path"), rel)?;
set(&wsf, &format!("project.{name}.id"), &id)?;
set(&wsf, &format!("project.{name}.storage"), storage)?;
Ok(id)
}
fn show_workspace(json_out: bool) -> R<String> {
let here = std::env::current_dir().map_err(|e| e.to_string())?;
let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one (under `git config --global raea.root`, else ~/Studio)")?;
let file = ws.join(".raea/workspace");
let ps = projects(&ws);
if json_out {
let projects: Vec<_> = ps.iter().map(|(n, p, s)| json!({"name": n, "path": p, "storage": s, "id": get(&file, &format!("project.{n}.id"))})).collect();
return Ok(json!({"path": ws, "id": get(&file, "workspace.id"), "name": get(&file, "workspace.name"), "layout": get(&file, "workspace.layout"), "projects": projects}).to_string());
}
let mut out = format!("{} ({}, {})\n{}\n", get(&file, "workspace.name").unwrap_or_default(), get(&file, "workspace.id").unwrap_or_default(), get(&file, "workspace.layout").unwrap_or_default(), ws.display());
for (n, p, s) in &ps {
out.push_str(&format!(" {n} {p} {s}\n"));
}
Ok(out.trim_end().to_string())
}
/// `raea project …`
pub fn project(args: &[String]) -> R<String> {
let w = words(args);
match w.first().copied() {
None => show_project(args.iter().any(|a| a == "--json")),
Some("new") => new_project(w.get(1).ok_or(USAGE)?, flag(args, "--storage")),
Some("split") => storage::split(w.get(1).ok_or(USAGE)?, flag(args, "--remote")),
Some("join") => storage::join(w.get(1).ok_or(USAGE)?),
Some(v) => Err(format!("raea project has no {v:?}\n{USAGE}")),
}
}
fn new_project(name: &str, storage: Option<&str>) -> R<String> {
let here = std::env::current_dir().map_err(|e| e.to_string())?;
let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one")?;
let slugged = slug(name);
if slugged.is_empty() {
return Err(format!("{name:?} has no letters or digits to name a folder by"));
}
let rel = format!("projects/{slugged}");
let dir = ws.join(&rel);
if dir.join(".raea/project").is_file() {
return Err(format!("{} is a project already", dir.display()));
}
let layout = get(&ws.join(".raea/workspace"), "workspace.layout").unwrap_or_else(|| "monorepo".into());
let storage = match storage.unwrap_or(if layout == "submodules" { "submodule" } else { "inline" }) {
s @ ("inline" | "submodule") => s,
s => return Err(format!("a project's storage is inline or submodule, not {s:?}")),
};
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
write_new(&dir.join("brief.ts"), &format!("import {{ brief }} from \"raea/brief\";\n\nexport default brief({{\n title: {name:?},\n}});\n"))?;
write_new(&dir.join("AGENTS.md"), AGENTS_PROJECT)?;
for d in ["media", "brand", "out"] {
write_new(&dir.join(d).join(".gitkeep"), "")?;
}
let id = register(&ws, &dir, &rel, storage)?;
let files = [".raea/project", "brief.ts", "AGENTS.md", "media/.gitkeep", "brand/.gitkeep", "out/.gitkeep"];
if storage == "submodule" {
git(&dir, &["init", "-q"])?;
commit(&dir, &files, &format!("project {name}"))?;
// the project's own repo, added where it stands; its url is the folder until it has a remote of its own
git(&ws, &["-c", "protocol.file.allow=always", "submodule", "add", "-q", &format!("./{rel}"), &rel])?;
include(&dir, &dir.join(".raea/project"))?;
commit(&ws, &[".raea/workspace", ".gitmodules", &rel], &format!("project {name} (submodule)"))?;
} else {
let paths: Vec<String> = files.iter().map(|f| format!("{rel}/{f}")).collect();
let mut all_paths: Vec<&str> = vec![".raea/workspace"];
all_paths.extend(paths.iter().map(String::as_str));
commit(&ws, &all_paths, &format!("project {name}"))?;
}
Ok(format!("{}: project {name:?} ({id}, {storage}); next: shape brief.ts, then raea context .", dir.display()))
}
fn show_project(json_out: bool) -> R<String> {
let here = std::env::current_dir().map_err(|e| e.to_string())?;
let dir = up(&here, ".raea/project").ok_or("not in a project: raea project new NAME (in a workspace) makes one")?;
let file = dir.join(".raea/project");
let ws = up(&dir, ".raea/workspace").filter(|w| *w != dir);
let overrides: Vec<(String, String)> = all(&file).into_iter().filter(|(k, _)| k.starts_with("controller.")).collect();
if json_out {
let o: serde_json::Map<String, serde_json::Value> = overrides.iter().map(|(k, v)| (k.trim_start_matches("controller.").to_string(), json!(v))).collect();
return Ok(json!({"path": dir, "id": get(&file, "project.id"), "name": get(&file, "project.name"), "workspace": ws, "controllers": o}).to_string());
}
let mut out = format!("{} ({})\n{}\n", get(&file, "project.name").unwrap_or_default(), get(&file, "project.id").unwrap_or_default(), dir.display());
if let Some(ws) = &ws {
out.push_str(&format!("in workspace {}\n", ws.display()));
}
for (k, v) in overrides {
out.push_str(&format!(" {} = {v}\n", k.trim_start_matches("controller.")));
}
Ok(out.trim_end().to_string())
}
+201
View File
@@ -0,0 +1,201 @@
//! A workspace's controllers: settings its Director puts together with the person, out of a small set of parts. A
//! controller has groups, a group has typed fields, and every agent in the workspace works to the values (`describe`).
//! The agent writes one as `controllers/<id>.ts` (`export default controller({...})`, docs/projects.feature PJ2);
//! `normalize` checks it and fills in ids, with errors in a sentence the agent can act on. The same contract as
//! apps/app src/controllers/types.ts, whose page reads these types.
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use ts_rs::TS;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
pub struct Controller {
pub id: String,
pub title: String,
#[serde(skip_serializing_if = "Option::is_none")] pub help: Option<String>,
pub groups: Vec<Group>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
pub struct Group {
pub id: String,
pub title: String,
#[serde(skip_serializing_if = "Option::is_none")] pub help: Option<String>,
pub fields: Vec<Field>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
pub struct Field {
pub id: String,
pub label: String,
#[serde(skip_serializing_if = "Option::is_none")] pub help: Option<String>,
#[serde(flatten)]
#[ts(flatten)]
pub kind: Kind,
}
/// One step of a workflow field: who does it (an agent's name, or "you" for the person) and where a failure goes back to.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
pub struct Step {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")] pub by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] pub back: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(tag = "type", rename_all = "lowercase")]
#[ts(optional_fields)]
pub enum Kind {
Toggle { value: bool },
Choice { options: Vec<String>, value: String },
Number { value: f64, #[serde(skip_serializing_if = "Option::is_none")] unit: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] min: Option<f64>, #[serde(skip_serializing_if = "Option::is_none")] max: Option<f64>, #[serde(skip_serializing_if = "Option::is_none")] step: Option<f64> },
Text { value: String, #[serde(skip_serializing_if = "Option::is_none")] placeholder: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] multiline: Option<bool> },
List { value: Vec<String>, #[serde(skip_serializing_if = "Option::is_none")] placeholder: Option<String> },
Agents { value: Vec<String> },
Channels { value: Vec<String> },
/// steps in order; `channels` run it (all of them when unset)
Workflow { value: Vec<Step>, #[serde(skip_serializing_if = "Option::is_none")] channels: Option<Vec<String>> },
/// MCP servers: URLs, commands or GitHub repos, given to every agent's session
Servers { value: Vec<String> },
/// skills: links to SKILL.md, read into every agent's context
Skills { value: Vec<String> },
}
const TYPES: &str = "toggle, choice, number, text, list, agents, channels, workflow, servers, skills";
fn slug(s: &str) -> String {
let mut out = String::new();
for c in s.to_lowercase().chars() {
if c.is_ascii_alphanumeric() {
out.push(c);
} else if !out.ends_with('-') {
out.push('-');
}
}
let out: String = out.trim_matches('-').chars().take(48).collect();
if out.is_empty() { "x".into() } else { out.trim_end_matches('-').into() }
}
fn is_id(s: &str) -> bool {
let b = s.as_bytes();
!b.is_empty() && b.len() <= 48 && b[0].is_ascii_lowercase() && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
}
fn text(o: &Map<String, Value>, k: &str) -> Option<String> {
o.get(k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(String::from)
}
fn id_of(o: &Map<String, Value>, fallback: &str) -> String {
o.get("id").and_then(Value::as_str).filter(|s| is_id(s)).map(String::from).unwrap_or_else(|| slug(fallback))
}
fn strings(v: Option<&Value>, what: &str) -> Result<Vec<String>, String> {
match v {
None | Some(Value::Null) => Ok(vec![]),
Some(Value::Array(a)) if a.iter().all(Value::is_string) => {
Ok(a.iter().filter_map(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(String::from).collect())
}
_ => Err(format!("{what} must be a list of strings")),
}
}
fn number(o: &Map<String, Value>, k: &str) -> Option<f64> {
o.get(k).and_then(Value::as_f64).filter(|n| n.is_finite())
}
fn steps(v: Option<&Value>, at: &str) -> Result<Vec<Step>, String> {
let Some(Value::Array(a)) = v else { return Err(format!("{at}: a workflow's value is a list of steps: {{ name, by?, back? }}")) };
a.iter()
.enumerate()
.map(|(i, s)| {
let o = s.as_object().ok_or_else(|| format!("{at}: step {} needs a name", i + 1))?;
let name = text(o, "name").ok_or_else(|| format!("{at}: step {} needs a name", i + 1))?;
Ok(Step { name, by: text(o, "by").map(|b| b.trim_start_matches('@').to_string()), back: text(o, "back") })
})
.collect()
}
/// A field as the agent wrote it, checked and filled in; an error names the field and what it needs.
pub fn normalize_field(raw: &Value, at: &str) -> Result<Field, String> {
let o = raw.as_object().ok_or_else(|| format!("{at}: a field is an object"))?;
let label = text(o, "label").ok_or_else(|| format!("{at}: a field needs a label"))?;
let id = id_of(o, &label);
let w = format!("{at}.{id}");
let value = o.get("value");
let kind = match o.get("type").and_then(Value::as_str) {
Some("toggle") => Kind::Toggle { value: value == Some(&Value::Bool(true)) },
Some("choice") => {
let options = strings(o.get("options"), &format!("{w}: options"))?;
if options.len() < 2 {
return Err(format!("{w}: a choice needs at least two options"));
}
let value = value.and_then(Value::as_str).filter(|v| options.iter().any(|x| x == v)).map(String::from).unwrap_or_else(|| options[0].clone());
Kind::Choice { options, value }
}
Some("number") => Kind::Number { value: number(o, "value").unwrap_or(0.0), unit: o.get("unit").and_then(Value::as_str).map(String::from), min: number(o, "min"), max: number(o, "max"), step: number(o, "step") },
Some("text") => Kind::Text { value: value.and_then(Value::as_str).unwrap_or("").into(), placeholder: o.get("placeholder").and_then(Value::as_str).map(String::from), multiline: Some(o.get("multiline") == Some(&Value::Bool(true))) },
Some("list") => Kind::List { value: strings(value, &format!("{w}: value"))?, placeholder: o.get("placeholder").and_then(Value::as_str).map(String::from) },
Some("agents") => Kind::Agents { value: strings(value, &format!("{w}: value"))? },
Some("channels") => Kind::Channels { value: strings(value, &format!("{w}: value"))? },
Some("servers") => Kind::Servers { value: strings(value, &format!("{w}: value"))? },
Some("skills") => Kind::Skills { value: strings(value, &format!("{w}: value"))? },
Some("workflow") => Kind::Workflow { value: steps(value, &w)?, channels: o.get("channels").map(|c| strings(Some(c), &format!("{w}: channels"))).transpose()? },
_ => return Err(format!("{w}: type must be one of {TYPES}")),
};
Ok(Field { id, label, help: text(o, "help"), kind })
}
/// A controller as the agent wrote it (a module's default export, as JSON), checked: ids filled in from titles, each
/// field's value of its type.
pub fn normalize(raw: &Value) -> Result<Controller, String> {
let o = raw.as_object().filter(|o| text(o, "title").is_some()).ok_or("a controller needs a title")?;
let title = text(o, "title").unwrap_or_default();
let id = id_of(o, &title);
let gs = o.get("groups").and_then(Value::as_array).filter(|g| !g.is_empty()).ok_or_else(|| format!("{id}: a controller needs groups: [{{ title, fields: [...] }}]"))?;
let mut groups = vec![];
for (i, g) in gs.iter().enumerate() {
let g = g.as_object().filter(|g| text(g, "title").is_some()).ok_or_else(|| format!("{id}: group {} needs a title", i + 1))?;
let gtitle = text(g, "title").unwrap_or_default();
let gid = id_of(g, &gtitle);
let at = format!("{id}.{gid}");
let fs = g.get("fields").and_then(Value::as_array).ok_or_else(|| format!("{at}: a group needs fields"))?;
let fields = fs.iter().map(|f| normalize_field(f, &at)).collect::<Result<Vec<_>, _>>()?;
if let Some(d) = fields.iter().enumerate().find(|(j, f)| fields.iter().position(|x| x.id == f.id) != Some(*j)) {
return Err(format!("{at}: two fields are called {}", d.1.id));
}
groups.push(Group { id: gid, title: gtitle, help: text(g, "help"), fields });
}
Ok(Controller { id, title, help: text(o, "help"), groups })
}
/// A value checked against its field: the same type, a choice among its options, a number within its range. The
/// value as it's kept (a workflow's steps filled in, a list's strings trimmed).
pub fn check_value(f: &Field, v: &Value) -> Result<Value, String> {
let w = &f.label;
match &f.kind {
Kind::Toggle { .. } => v.as_bool().map(Value::Bool).ok_or_else(|| format!("{w} is on or off: true or false")),
Kind::Choice { options, .. } => v.as_str().filter(|s| options.iter().any(|o| o == s)).map(|s| Value::String(s.into())).ok_or_else(|| format!("{w} is one of: {}", options.join(", "))),
Kind::Number { min, max, .. } => {
let n = v.as_f64().filter(|n| n.is_finite()).ok_or_else(|| format!("{w} is a number"))?;
if min.is_some_and(|m| n < m) || max.is_some_and(|m| n > m) {
let (lo, hi) = (min.map_or("-∞".into(), |m| m.to_string()), max.map_or("∞".into(), |m| m.to_string()));
return Err(format!("{w} is between {lo} and {hi}"));
}
Ok(v.clone())
}
Kind::Text { .. } => v.as_str().map(|s| Value::String(s.into())).ok_or_else(|| format!("{w} is text")),
Kind::Workflow { .. } => Ok(serde_json::to_value(steps(Some(v), w)?).unwrap_or_default()),
_ => Ok(serde_json::to_value(strings(Some(v), w)?).unwrap_or_default()),
}
}
/// The field at a path (controller.group.field) among the controllers.
pub fn field<'a>(cs: &'a [Controller], path: &str) -> Option<&'a Field> {
let mut p = path.splitn(3, '.');
let (c, g, f) = (p.next()?, p.next()?, p.next()?);
cs.iter().find(|x| x.id == c)?.groups.iter().find(|x| x.id == g)?.fields.iter().find(|x| x.id == f)
}
+5 -1
View File
@@ -4,11 +4,13 @@
//! types (`declarations`), so what tsc checks is exactly what this crate reads. //! types (`declarations`), so what tsc checks is exactly what this crate reads.
pub mod brief; pub mod brief;
pub mod controller;
pub mod plan; pub mod plan;
pub mod script; pub mod script;
pub mod taste; pub mod taste;
pub use brief::Brief; pub use brief::Brief;
pub use controller::Controller;
pub use plan::Plan; pub use plan::Plan;
pub use script::Script; pub use script::Script;
pub use taste::Taste; pub use taste::Taste;
@@ -26,7 +28,8 @@ macro_rules! decls {
($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] }; ($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] };
} }
/// The TypeScript declarations of every schema, one file's worth (core/brief/brief.d.ts is this, checked by a test). /// The TypeScript declarations of every schema, one file's worth: sdk/raea/src/brief.gen.ts is this, checked by a test, and
/// `raea/brief` (sdk/raea/src/brief.ts) types its builders with it, so the declarations ship with the SDK.
pub fn declarations() -> String { pub fn declarations() -> String {
let cfg = Config::new(); let cfg = Config::new();
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.".to_string()]; let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.".to_string()];
@@ -35,6 +38,7 @@ pub fn declarations() -> String {
script::Script, script::Scene, script::Beat, script::Line, script::Script, script::Scene, script::Beat, script::Line,
taste::Taste, taste::TasteSection, taste::Rule, taste::Check, taste::Taste, taste::TasteSection, taste::Rule, taste::Check,
plan::Plan, plan::Concept, plan::Level, plan::Count, plan::Part, plan::Plan, plan::Concept, plan::Level, plan::Count, plan::Part,
controller::Controller, controller::Group, controller::Field, controller::Kind, controller::Step,
)); ));
out.join("\n\n") + "\n" out.join("\n\n") + "\n"
} }
+44 -2
View File
@@ -2,13 +2,13 @@ use super::*;
#[test] #[test]
fn declarations_match_the_committed_file() { fn declarations_match_the_committed_file() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/brief.d.ts"); let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/brief.gen.ts");
let now = declarations(); let now = declarations();
if std::env::var_os("RAEA_WRITE").is_some() { if std::env::var_os("RAEA_WRITE").is_some() {
std::fs::write(path, &now).unwrap(); std::fs::write(path, &now).unwrap();
} }
let committed = std::fs::read_to_string(path).unwrap_or_default(); let committed = std::fs::read_to_string(path).unwrap_or_default();
assert!(committed == now, "core/brief/brief.d.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief"); assert!(committed == now, "sdk/raea/src/brief.gen.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");
} }
#[test] #[test]
@@ -75,3 +75,45 @@ fn a_close_view_needs_tertiary_detail() {
"parts": {"body": {"role": "body", "level": "primary"}, "rocker": {"role": "rocker", "level": "secondary", "parent": "body", "count": 2}}}"#).unwrap(); "parts": {"body": {"role": "body", "level": "primary"}, "rocker": {"role": "rocker", "level": "secondary", "parent": "body", "count": 2}}}"#).unwrap();
assert!(plan::check(&p).iter().any(|m| m.contains("tertiary"))); assert!(plan::check(&p).iter().any(|m| m.contains("tertiary")));
} }
const DELIVERY: &str = r#"{"title": "Delivery", "help": "What every final keeps", "groups": [{"title": "Format", "fields": [
{"label": "Aspect ratio", "type": "choice", "options": ["9:16", "4:5", "1:1"], "value": "9:16"},
{"label": "Loudness", "type": "number", "value": -14, "unit": "LUFS", "min": -30, "max": 0},
{"label": "Burn in captions", "type": "toggle", "value": true},
{"label": "Steps", "type": "workflow", "value": [{"name": "Cut", "by": "@cutter"}, {"name": "Review", "by": "you", "back": "Cut"}]}]}]}"#;
#[test]
fn a_controller_fills_ids_from_titles_and_labels() {
let c = controller::normalize(&serde_json::from_str(DELIVERY).unwrap()).unwrap();
assert_eq!(c.id, "delivery");
assert_eq!(c.groups[0].id, "format");
let ids: Vec<_> = c.groups[0].fields.iter().map(|f| f.id.as_str()).collect();
assert_eq!(ids, ["aspect-ratio", "loudness", "burn-in-captions", "steps"]);
let controller::Kind::Workflow { value, .. } = &c.groups[0].fields[3].kind else { panic!("a workflow") };
assert_eq!(value[0].by.as_deref(), Some("cutter"));
// what it writes back reads as the same controller (the page's types are these)
let again = controller::normalize(&serde_json::to_value(&c).unwrap()).unwrap();
assert_eq!(again, c);
}
#[test]
fn a_controller_says_what_is_wrong_in_a_sentence_the_agent_can_act_on() {
let bad = |j: &str| controller::normalize(&serde_json::from_str(j).unwrap()).unwrap_err();
assert!(bad(r#"{"title": "X", "groups": [{"title": "G", "fields": [{"label": "A", "type": "slider"}]}]}"#).contains("type must be one of"));
assert!(bad(r#"{"title": "X", "groups": [{"title": "G", "fields": [{"label": "A", "type": "choice", "options": ["one"]}]}]}"#).contains("at least two options"));
assert!(bad(r#"{"title": "X"}"#).contains("needs groups"));
assert!(bad(r#"{"groups": []}"#).contains("needs a title"));
assert!(bad(r#"{"title": "X", "groups": [{"title": "G", "fields": [{"label": "A", "type": "toggle"}, {"label": "a", "type": "toggle"}]}]}"#).contains("two fields are called a"));
}
#[test]
fn a_value_is_checked_against_its_field() {
let c = controller::normalize(&serde_json::from_str(DELIVERY).unwrap()).unwrap();
let cs = [c];
let f = |p: &str| controller::field(&cs, p).unwrap();
assert!(controller::check_value(f("delivery.format.loudness"), &serde_json::json!(-16)).is_ok());
assert!(controller::check_value(f("delivery.format.loudness"), &serde_json::json!(4)).unwrap_err().contains("between -30 and 0"));
assert!(controller::check_value(f("delivery.format.aspect-ratio"), &serde_json::json!("16:9")).unwrap_err().contains("one of: 9:16, 4:5, 1:1"));
assert!(controller::check_value(f("delivery.format.burn-in-captions"), &serde_json::json!("yes")).is_err());
assert!(controller::field(&cs, "delivery.format.nope").is_none());
}
+7 -1
View File
@@ -9,6 +9,7 @@ bg:tex[T;x;y]
r:and[bg;255] r:and[bg;255]
g:and[shr[bg;8];255] g:and[shr[bg;8];255]
b:and[shr[bg;16];255] b:and[shr[bg;16];255]
a:and[shr[bg;24];255]
/ clip slot 0 / clip slot 0
on0:word[C;0] on0:word[C;0]
bx0:word[C;1] bx0:word[C;1]
@@ -62,6 +63,7 @@ bb0:clamp[shr[k0+(541*cu0)+128;8];0;255]
r:shr[(am0*rr0)+((256-am0)*r);8] r:shr[(am0*rr0)+((256-am0)*r);8]
g:shr[(am0*gg0)+((256-am0)*g);8] g:shr[(am0*gg0)+((256-am0)*g);8]
b:shr[(am0*bb0)+((256-am0)*b);8] b:shr[(am0*bb0)+((256-am0)*b);8]
a:shr[(am0*255)+((256-am0)*a);8]
end end
/ clip slot 1 / clip slot 1
on1:word[C;12] on1:word[C;12]
@@ -116,6 +118,7 @@ bb1:clamp[shr[k1+(541*cu1)+128;8];0;255]
r:shr[(am1*rr1)+((256-am1)*r);8] r:shr[(am1*rr1)+((256-am1)*r);8]
g:shr[(am1*gg1)+((256-am1)*g);8] g:shr[(am1*gg1)+((256-am1)*g);8]
b:shr[(am1*bb1)+((256-am1)*b);8] b:shr[(am1*bb1)+((256-am1)*b);8]
a:shr[(am1*255)+((256-am1)*a);8]
end end
/ clip slot 2 / clip slot 2
on2:word[C;24] on2:word[C;24]
@@ -170,6 +173,7 @@ bb2:clamp[shr[k2+(541*cu2)+128;8];0;255]
r:shr[(am2*rr2)+((256-am2)*r);8] r:shr[(am2*rr2)+((256-am2)*r);8]
g:shr[(am2*gg2)+((256-am2)*g);8] g:shr[(am2*gg2)+((256-am2)*g);8]
b:shr[(am2*bb2)+((256-am2)*b);8] b:shr[(am2*bb2)+((256-am2)*b);8]
a:shr[(am2*255)+((256-am2)*a);8]
end end
/ clip slot 3 / clip slot 3
on3:word[C;36] on3:word[C;36]
@@ -224,6 +228,7 @@ bb3:clamp[shr[k3+(541*cu3)+128;8];0;255]
r:shr[(am3*rr3)+((256-am3)*r);8] r:shr[(am3*rr3)+((256-am3)*r);8]
g:shr[(am3*gg3)+((256-am3)*g);8] g:shr[(am3*gg3)+((256-am3)*g);8]
b:shr[(am3*bb3)+((256-am3)*b);8] b:shr[(am3*bb3)+((256-am3)*b);8]
a:shr[(am3*255)+((256-am3)*a);8]
end end
/ the overlay, premultiplied: o + below * (255 - a) / 255 / the overlay, premultiplied: o + below * (255 - a) / 255
o:word[O;i] o:word[O;i]
@@ -231,4 +236,5 @@ oa:and[shr[o;24];255]
r:and[o;255]+((r*(255-oa))+127)%255 r:and[o;255]+((r*(255-oa))+127)%255
g:and[shr[o;8];255]+((g*(255-oa))+127)%255 g:and[shr[o;8];255]+((g*(255-oa))+127)%255
b:and[shr[o;16];255]+((b*(255-oa))+127)%255 b:and[shr[o;16];255]+((b*(255-oa))+127)%255
px:pack[r;g;b;255] a:oa+((a*(255-oa))+127)%255
px:pack[r;g;b;a]
+7 -1
View File
@@ -8,6 +8,7 @@ bg:tex[T;x;y]
r:and[bg;255] r:and[bg;255]
g:and[shr[bg;8];255] g:and[shr[bg;8];255]
b:and[shr[bg;16];255] b:and[shr[bg;16];255]
a:and[shr[bg;24];255]
/ clip slot 0 / clip slot 0
on0:word[C;0] on0:word[C;0]
bx0:word[C;1] bx0:word[C;1]
@@ -60,6 +61,7 @@ bb0:clamp[shr[k0+(541*cu0)+128;8];0;255]
r:shr[(am0*rr0)+((256-am0)*r);8] r:shr[(am0*rr0)+((256-am0)*r);8]
g:shr[(am0*gg0)+((256-am0)*g);8] g:shr[(am0*gg0)+((256-am0)*g);8]
b:shr[(am0*bb0)+((256-am0)*b);8] b:shr[(am0*bb0)+((256-am0)*b);8]
a:shr[(am0*255)+((256-am0)*a);8]
end end
/ clip slot 1 / clip slot 1
on1:word[C;12] on1:word[C;12]
@@ -113,6 +115,7 @@ bb1:clamp[shr[k1+(541*cu1)+128;8];0;255]
r:shr[(am1*rr1)+((256-am1)*r);8] r:shr[(am1*rr1)+((256-am1)*r);8]
g:shr[(am1*gg1)+((256-am1)*g);8] g:shr[(am1*gg1)+((256-am1)*g);8]
b:shr[(am1*bb1)+((256-am1)*b);8] b:shr[(am1*bb1)+((256-am1)*b);8]
a:shr[(am1*255)+((256-am1)*a);8]
end end
/ clip slot 2 / clip slot 2
on2:word[C;24] on2:word[C;24]
@@ -166,6 +169,7 @@ bb2:clamp[shr[k2+(541*cu2)+128;8];0;255]
r:shr[(am2*rr2)+((256-am2)*r);8] r:shr[(am2*rr2)+((256-am2)*r);8]
g:shr[(am2*gg2)+((256-am2)*g);8] g:shr[(am2*gg2)+((256-am2)*g);8]
b:shr[(am2*bb2)+((256-am2)*b);8] b:shr[(am2*bb2)+((256-am2)*b);8]
a:shr[(am2*255)+((256-am2)*a);8]
end end
/ clip slot 3 / clip slot 3
on3:word[C;36] on3:word[C;36]
@@ -219,6 +223,7 @@ bb3:clamp[shr[k3+(541*cu3)+128;8];0;255]
r:shr[(am3*rr3)+((256-am3)*r);8] r:shr[(am3*rr3)+((256-am3)*r);8]
g:shr[(am3*gg3)+((256-am3)*g);8] g:shr[(am3*gg3)+((256-am3)*g);8]
b:shr[(am3*bb3)+((256-am3)*b);8] b:shr[(am3*bb3)+((256-am3)*b);8]
a:shr[(am3*255)+((256-am3)*a);8]
end end
/ the overlay, premultiplied: o + below * (255 - a) / 255 / the overlay, premultiplied: o + below * (255 - a) / 255
o:word[O;i] o:word[O;i]
@@ -226,4 +231,5 @@ oa:and[shr[o;24];255]
r:and[o;255]+((r*(255-oa))+127)%255 r:and[o;255]+((r*(255-oa))+127)%255
g:and[shr[o;8];255]+((g*(255-oa))+127)%255 g:and[shr[o;8];255]+((g*(255-oa))+127)%255
b:and[shr[o;16];255]+((b*(255-oa))+127)%255 b:and[shr[o;16];255]+((b*(255-oa))+127)%255
px:pack[r;g;b;255] a:oa+((a*(255-oa))+127)%255
px:pack[r;g;b;a]
+7 -2
View File
@@ -9,7 +9,10 @@ L = ["/ The frame on the GPU: the camera's target T is the background (clear col
"/ Luma and chroma are bilinear; YUV is BT.709 limited range in 8.8 fixed point. One RGBA word per pixel.", "/ Luma and chroma are bilinear; YUV is BT.709 limited range in 8.8 fixed point. One RGBA word per pixel.",
"x:i!w", "y:i%w", "x:i!w", "y:i%w",
"bg:tex[T;x;y]", "bg:tex[T;x;y]",
"r:and[bg;255]", "g:and[shr[bg;8];255]", "b:and[shr[bg;16];255]"] "r:and[bg;255]", "g:and[shr[bg;8];255]", "b:and[shr[bg;16];255]",
# coverage, carried so a transparent clear (render --alpha) stays transparent where nothing is drawn; over an
# opaque background every step below keeps it 255, so those frames are the same pixels as before
"a:and[shr[bg;24];255]"]
for s in range(SLOTS): for s in range(SLOTS):
P, c = f"P{s}", lambda k: f"word[C;{s * 12 + k}]" P, c = f"P{s}", lambda k: f"word[C;{s * 12 + k}]"
L += [f"/ clip slot {s}", L += [f"/ clip slot {s}",
@@ -46,13 +49,15 @@ for s in range(SLOTS):
f"r:shr[(am{s}*rr{s})+((256-am{s})*r);8]", f"r:shr[(am{s}*rr{s})+((256-am{s})*r);8]",
f"g:shr[(am{s}*gg{s})+((256-am{s})*g);8]", f"g:shr[(am{s}*gg{s})+((256-am{s})*g);8]",
f"b:shr[(am{s}*bb{s})+((256-am{s})*b);8]", f"b:shr[(am{s}*bb{s})+((256-am{s})*b);8]",
f"a:shr[(am{s}*255)+((256-am{s})*a);8]",
"end"] "end"]
L += ["/ the overlay, premultiplied: o + below * (255 - a) / 255", L += ["/ the overlay, premultiplied: o + below * (255 - a) / 255",
"o:word[O;i]", "oa:and[shr[o;24];255]", "o:word[O;i]", "oa:and[shr[o;24];255]",
"r:and[o;255]+((r*(255-oa))+127)%255", "r:and[o;255]+((r*(255-oa))+127)%255",
"g:and[shr[o;8];255]+((g*(255-oa))+127)%255", "g:and[shr[o;8];255]+((g*(255-oa))+127)%255",
"b:and[shr[o;16];255]+((b*(255-oa))+127)%255", "b:and[shr[o;16];255]+((b*(255-oa))+127)%255",
"px:pack[r;g;b;255]"] "a:oa+((a*(255-oa))+127)%255",
"px:pack[r;g;b;a]"]
open("kernels/composite.k", "w").write("\n".join(L) + "\n") open("kernels/composite.k", "w").write("\n".join(L) + "\n")
# composite_tex.k: the same, with each slot's planes as textures, as VideoToolbox's IOSurface-backed buffers wrap # composite_tex.k: the same, with each slot's planes as textures, as VideoToolbox's IOSurface-backed buffers wrap
+57 -3
View File
@@ -44,11 +44,32 @@ pub fn decoded(src: &str) -> String {
String::from_utf8(out).unwrap_or_else(|_| s.to_string()) String::from_utf8(out).unwrap_or_else(|_| s.to_string())
} }
/// A media src as a file: a path from staticFile (/media/x under the edit's folder), absolute, or relative to it. /// The project an edit belongs to: the nearest folder at or above the edit's holding space.json (an object's folder,
/// docs/sdk.feature S5a, whose edit is src/main.tsx), else the edit's own folder. Remembered per folder, since media
/// paths are resolved every frame.
pub fn project_dir(dir: &Path) -> PathBuf {
static SEEN: std::sync::Mutex<Option<std::collections::HashMap<PathBuf, PathBuf>>> = std::sync::Mutex::new(None);
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
let seen = seen.get_or_insert_with(Default::default);
if let Some(p) = seen.get(dir) {
return p.clone();
}
let p = dir.ancestors().find(|d| d.join("space.json").is_file()).unwrap_or(dir).to_path_buf();
seen.insert(dir.to_path_buf(), p.clone());
p
}
/// A media src as a file: a path from staticFile (/media/x: the project's media/, then its assets/, as Bevy's assets
/// folder; the edit's own media/ first when the edit isn't the project's folder), absolute, or relative to the edit.
pub fn media_path(dir: &Path, src: &str) -> PathBuf { pub fn media_path(dir: &Path, src: &str) -> PathBuf {
if let Some(rest) = src.strip_prefix("/media/") { if let Some(rest) = src.strip_prefix("/media/") {
let p = dir.join("media").join(rest); let project = project_dir(dir);
if p.exists() { let mut tried = vec![dir.join("media")];
if project != dir {
tried.push(project.join("media"));
}
tried.push(project.join("assets"));
if let Some(p) = tried.iter().map(|d| d.join(rest)).find(|p| p.exists()) {
return p; return p;
} }
} }
@@ -58,3 +79,36 @@ pub fn media_path(dir: &Path, src: &str) -> PathBuf {
} }
dir.join(src.trim_start_matches('/')) dir.join(src.trim_start_matches('/'))
} }
#[cfg(test)]
mod tests {
use super::*;
// an object's folder (S5a): space.json at its root, the edit in src/, files in assets/ or media/
#[test]
fn media_from_the_project() {
let root = std::env::temp_dir().join(format!("raea-media-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let src = root.join("src");
for d in [&src, &root.join("assets"), &root.join("media"), &src.join("media")] {
std::fs::create_dir_all(d).unwrap();
}
std::fs::write(root.join("space.json"), "{}").unwrap();
for f in ["assets/a.png", "assets/b.png", "media/b.png", "src/media/c.png", "assets/c.png"] {
std::fs::write(root.join(f), "").unwrap();
}
assert_eq!(project_dir(&src), root);
assert_eq!(media_path(&src, "/media/a.png"), root.join("assets/a.png"));
assert_eq!(media_path(&src, "/media/b.png"), root.join("media/b.png"));
assert_eq!(media_path(&src, "/media/c.png"), src.join("media/c.png"));
// missing: where it was always looked for
assert_eq!(media_path(&src, "/media/d.png"), src.join("media/d.png"));
// no space.json above: the edit's folder is the project, its assets/ after its media/
let plain = root.join("plain");
std::fs::create_dir_all(plain.join("assets")).unwrap();
std::fs::write(plain.join("assets/e.png"), "").unwrap();
std::fs::remove_file(root.join("space.json")).unwrap();
assert_eq!(media_path(&plain, "/media/e.png"), plain.join("assets/e.png"));
let _ = std::fs::remove_dir_all(&root);
}
}
+3 -2
View File
@@ -15,9 +15,10 @@ pinned in rust-toolchain.toml at the root (1.97.1, what 0.20 was ported and veri
in every checkout and on the CI runner; Homebrew's rust is uninstalled so nothing on PATH comes ahead of them. A bump in every checkout and on the CI runner; Homebrew's rust is uninstalled so nothing on PATH comes ahead of them. A bump
that needs a newer rustc moves that pin in the same branch. that needs a newer rustc moves that pin in the same branch.
## The pipeline: three subagents ## The pipeline: three lanes
When a Bevy release comes out, run these three in order (they live in .claude/agents/, and each reads this file): When a Bevy release comes out, run these three in order as lanes, `tools/agents/agent start bevy-scout` and so on (their briefs
are docs/handoff/bevy-{scout,porter,verifier}.md, and each reads this file):
1. **bevy-scout** (read-only): can raea move yet? It compares crates.io against the pins, names the plugins that 1. **bevy-scout** (read-only): can raea move yet? It compares crates.io against the pins, names the plugins that
haven't caught up, picks out the migration-guide items that hit raea's code, and checks whether upstream now covers haven't caught up, picks out the migration-guide items that hit raea's code, and checks whether upstream now covers
+12
View File
@@ -8,6 +8,18 @@ which setting is missing.
mkdir -p ~/.raea && touch ~/.raea/env && chmod 600 ~/.raea/env mkdir -p ~/.raea && touch ~/.raea/env && chmod 600 ~/.raea/env
``` ```
## Network
| Setting | What |
|---|---|
| `RAEA_OFFLINE=1` | raea makes no network requests: a remote URL not already in raea's cache, a model or sample library not yet installed, a composition's own `fetch()` or WebSocket, Bevy's http asset source and every `raea gen` step are refused with what wanted out. What's on disk keeps working |
## Generation (`raea gen`, optional)
| Setting | What |
|---|---|
| `FISH_API_KEY` | Your Fish Audio key, for an `audio.speech` step on `fish:<model>` (`fish:` alone is s2.1-pro); a plan quotes Fish's price for the words first |
## Local audio models ## Local audio models
Two models make sound on your Mac, free, with no account. Each installs itself the first time a composition or a Two models make sound on your Mac, free, with no account. Each installs itself the first time a composition or a
+2
View File
@@ -25,6 +25,7 @@ fastnoise-lite = { version = "=1.1.1", optional = true, default-features = false
noisy_bevy = { version = "=0.15.0", optional = true, default-features = false, features = ["cpu", "gpu"] } noisy_bevy = { version = "=0.15.0", optional = true, default-features = false, features = ["cpu", "gpu"] }
bevy_northstar = { version = "=0.8.0", optional = true, default-features = false, features = ["parallel"] } bevy_northstar = { version = "=0.8.0", optional = true, default-features = false, features = ["parallel"] }
bevy_quinnet = { version = "=0.22.0", optional = true, default-features = false, features = ["client", "server", "shared-client-id", "recv_channels"] } bevy_quinnet = { version = "=0.22.0", optional = true, default-features = false, features = ["client", "server", "shared-client-id", "recv_channels"] }
moonshine-save = { version = "=0.8.0", optional = true, default-features = false, features = [] }
bevy_simple_tilemap = { version = "=0.21.0", optional = true, default-features = false, features = [] } bevy_simple_tilemap = { version = "=0.21.0", optional = true, default-features = false, features = [] }
bevy_sprite3d = { version = "=10.1.0", optional = true, default-features = false, features = [] } bevy_sprite3d = { version = "=10.1.0", optional = true, default-features = false, features = [] }
bevy_trauma_shake = { version = "=0.9.0", optional = true, default-features = false, features = ["events", "commands", "system_param"] } bevy_trauma_shake = { version = "=0.9.0", optional = true, default-features = false, features = ["events", "commands", "system_param"] }
@@ -44,6 +45,7 @@ noise = ["dep:noise", "dep:fastnoise-lite"]
noisy = ["dep:noisy_bevy"] noisy = ["dep:noisy_bevy"]
northstar = ["dep:bevy_northstar"] northstar = ["dep:bevy_northstar"]
quinnet = ["dep:bevy_quinnet"] quinnet = ["dep:bevy_quinnet"]
save = ["dep:moonshine-save"]
simple_tilemap = ["dep:bevy_simple_tilemap"] simple_tilemap = ["dep:bevy_simple_tilemap"]
sprite3d = ["dep:bevy_sprite3d"] sprite3d = ["dep:bevy_sprite3d"]
trauma_shake = ["dep:bevy_trauma_shake"] trauma_shake = ["dep:bevy_trauma_shake"]
+2
View File
@@ -32,6 +32,8 @@ pub mod noisy;
pub mod northstar; pub mod northstar;
#[cfg(feature = "quinnet")] #[cfg(feature = "quinnet")]
pub mod quinnet; pub mod quinnet;
#[cfg(feature = "save")]
pub mod save;
#[cfg(feature = "simple_tilemap")] #[cfg(feature = "simple_tilemap")]
pub mod simple_tilemap; pub mod simple_tilemap;
#[cfg(feature = "sprite3d")] #[cfg(feature = "sprite3d")]
+78
View File
@@ -0,0 +1,78 @@
//! moonshine-save (the declaration's `"calls": "save"`): saving marked entities to a file and loading them back
//! (docs/plugins.feature PL16). Its markers (Save, Unload) aren't reflected and saving is an event a Rust system
//! triggers, so TypeScript marks and saves through methods. moonshine-save's own observers do the work; these record
//! what each save and load did.
//!
//! save/mark {entities: [entity, ...], unload?} -> null: marks them Save (saved, and replaced on load), or with
//! unload Unload (never saved, despawned on load: a saved entity's visuals)
//! save/save {path} -> {saved: [entity, ...]}: every Save entity's reflected, serializable components, as RON
//! save/load {path} -> {loaded: [entity, ...]}: despawns the Save and Unload entities, then spawns the file's and
//! marks them Save again (Save itself isn't saved, being unreflected)
use bevy::prelude::*;
use bevy_remote::BrpResult;
use moonshine_save::prelude::{Loaded, Save, SaveWorld, Saved, TriggerLoad, TriggerSave, Unload, LoadWorld, load_on_default_event, save_on_default_event};
use serde_json::{Value, json};
use crate::{add_method, entity, fail, params};
pub fn calls(app: &mut App) {
app.add_observer(save_on_default_event).add_observer(load_on_default_event).add_observer(saved).add_observer(loaded);
add_method(app, "save/mark", mark);
add_method(app, "save/save", file(true));
add_method(app, "save/load", file(false));
}
/// What the last save or load did: None until it finishes (moonshine-save logs why one failed)
#[derive(Resource, Default)]
struct Done(Option<Vec<Entity>>);
fn saved(s: On<Saved>, mut commands: Commands) {
commands.insert_resource(Done(Some(s.entities().collect())));
}
fn loaded(l: On<Loaded>, mut commands: Commands) {
let es: Vec<Entity> = l.entities().collect();
for &e in &es {
if let Ok(mut c) = commands.get_entity(e) {
c.insert(Save);
}
}
commands.insert_resource(Done(Some(es)));
}
#[derive(serde::Deserialize)]
struct MarkParams {
entities: Vec<u64>,
#[serde(default)]
unload: bool,
}
fn mark(In(p): In<Option<Value>>, world: &mut World) -> BrpResult {
let p: MarkParams = params(p)?;
for bits in p.entities {
let e = entity(bits)?;
let mut at = world.get_entity_mut(e).map_err(|_| fail(format!("no entity {e}")))?;
if p.unload { at.insert(Unload) } else { at.insert(Save) };
}
Ok(Value::Null)
}
#[derive(serde::Deserialize)]
struct PathParams {
path: String,
}
/// save/save or save/load: one file through moonshine-save, and the entities it did, or why it didn't
fn file(save: bool) -> impl FnMut(In<Option<Value>>, &mut World) -> BrpResult {
move |In(p), world| {
let p: PathParams = params(p)?;
world.insert_resource(Done(None));
if save { world.trigger_save(SaveWorld::default_into_file(&p.path)) } else { world.trigger_load(LoadWorld::default_from_file(&p.path)) }
world.flush();
let (what, key) = if save { ("save to", "saved") } else { ("load from", "loaded") };
let done = world.remove_resource::<Done>().and_then(|d| d.0).ok_or_else(|| fail(format!("{what} {} failed (the log says why)", p.path)))?;
let bits: Vec<u64> = done.into_iter().map(Entity::to_bits).collect();
Ok(Value::Object([(key.to_string(), json!(bits))].into_iter().collect()))
}
}
+2 -2
View File
@@ -7,6 +7,7 @@ publish = false
description = "Bevy plugins compiled into raea's engine, each behind a feature (sdk/raea/docs/bevy-plugins.md): declared in a project's package.json, resolved here by tools/bevy-plugins.sh, registered with raea-render's plugin hooks, driven from TSX by generic reflect rows and from TypeScript by bevy_remote's method table, stepped by the frame index" description = "Bevy plugins compiled into raea's engine, each behind a feature (sdk/raea/docs/bevy-plugins.md): declared in a project's package.json, resolved here by tools/bevy-plugins.sh, registered with raea-render's plugin hooks, driven from TSX by generic reflect rows and from TypeScript by bevy_remote's method table, stepped by the frame index"
[dependencies] [dependencies]
raea-io-home = { path = "../../io/home" }
raea-runtime-plugins = { path = "../../runtime/plugins" } raea-runtime-plugins = { path = "../../runtime/plugins" }
# a declaration's Blitz widgets, registered for every page App (declared.rs) # a declaration's Blitz widgets, registered for every page App (declared.rs)
raea-sys-page = { path = "../../systems/page" } raea-sys-page = { path = "../../systems/page" }
@@ -51,7 +52,6 @@ iyes_progress = { version = "=0.18.0", optional = true, default-features = false
bevy_quinnet = { version = "=0.22.0", optional = true, default-features = false, features = ["client", "server", "shared-client-id", "recv_channels"] } bevy_quinnet = { version = "=0.22.0", optional = true, default-features = false, features = ["client", "server", "shared-client-id", "recv_channels"] }
bevy_rand = { version = "=0.16.0", optional = true, default-features = false, features = ["std", "wyrand", "bevy_reflect", "thread_local_entropy"] } bevy_rand = { version = "=0.16.0", optional = true, default-features = false, features = ["std", "wyrand", "bevy_reflect", "thread_local_entropy"] }
bevy_remote = { version = "=0.20.0", default-features = false } bevy_remote = { version = "=0.20.0", default-features = false }
moonshine-save = { version = "=0.8.0", optional = true, default-features = false, features = [] }
bevy_simple_tilemap = { version = "=0.21.0", optional = true, default-features = false, features = [] } bevy_simple_tilemap = { version = "=0.21.0", optional = true, default-features = false, features = [] }
bevy_skein = { version = "=0.7.0-rc.1", optional = true, default-features = false, features = [] } bevy_skein = { version = "=0.7.0-rc.1", optional = true, default-features = false, features = [] }
bevy_smud = { version = "=0.15.0", optional = true, default-features = false, features = [] } bevy_smud = { version = "=0.15.0", optional = true, default-features = false, features = [] }
@@ -108,7 +108,7 @@ rand = ["dep:bevy_rand"]
rapier2d = ["raea-bevy-adapters/rapier2d"] rapier2d = ["raea-bevy-adapters/rapier2d"]
rapier3d = ["raea-bevy-adapters/rapier3d"] rapier3d = ["raea-bevy-adapters/rapier3d"]
remote = ["bevy_remote/http"] remote = ["bevy_remote/http"]
save = ["dep:moonshine-save"] save = ["raea-bevy-calls/save"]
simple_tilemap = ["dep:bevy_simple_tilemap", "raea-bevy-calls/simple_tilemap"] simple_tilemap = ["dep:bevy_simple_tilemap", "raea-bevy-calls/simple_tilemap"]
skein = ["dep:bevy_skein"] skein = ["dep:bevy_skein"]
smud = ["dep:bevy_smud"] smud = ["dep:bevy_smud"]
+4 -2
View File
@@ -3,7 +3,7 @@
//! They need no plugin of raea's: turning a feature on puts its plugin in Bevy's DefaultPlugins, which raea-render's Engine //! They need no plugin of raea's: turning a feature on puts its plugin in Bevy's DefaultPlugins, which raea-render's Engine
//! builds. One exception is handled here: bevy_audio's AudioPlugin plays to the device, not into raea's mixer, so a //! builds. One exception is handled here: bevy_audio's AudioPlugin plays to the device, not into raea's mixer, so a
//! render wouldn't hear it and a play would hear it twice. The Engine leaves it out; a TypeScript App that wants //! render wouldn't hear it and a play would hear it twice. The Engine leaves it out; a TypeScript App that wants
//! Bevy's audio asks for it by name (`plugins: ["bevy_audio"]`). //! Bevy's audio asks for it by name (`plugins: ["bevy_audio"]`). And under RAEA_OFFLINE the http asset source is left out.
use bevy::app::PluginGroupBuilder; use bevy::app::PluginGroupBuilder;
use bevy::prelude::*; use bevy::prelude::*;
@@ -21,5 +21,7 @@ pub fn register() {
} }
fn group(b: PluginGroupBuilder) -> PluginGroupBuilder { fn group(b: PluginGroupBuilder) -> PluginGroupBuilder {
b.disable::<bevy::audio::AudioPlugin>() let b = b.disable::<bevy::audio::AudioPlugin>();
// RAEA_OFFLINE: no http(s) asset source, so a model or texture named by URL is refused rather than fetched
if raea_io_home::offline("Bevy's http asset source").is_err() { b.disable::<bevy::asset::io::web::WebAssetPlugin>() } else { b }
} }
+2 -2
View File
@@ -82,7 +82,7 @@ pub fn install() {
#[cfg(feature = "rapier3d")] #[cfg(feature = "rapier3d")]
raea_bevy_adapters::rapier3d::register(); raea_bevy_adapters::rapier3d::register();
#[cfg(feature = "save")] #[cfg(feature = "save")]
use moonshine_save as _; raea_runtime_plugins::register(raea_runtime_plugins::Registered { name: "save", install: |app| { raea_bevy_calls::save::calls(app); }, group: None, on_demand: false });
#[cfg(feature = "simple_tilemap")] #[cfg(feature = "simple_tilemap")]
raea_runtime_plugins::register(raea_runtime_plugins::Registered { name: "simple_tilemap", install: |app| { crate::AddOnce::add_once(bevy_simple_tilemap::prelude::SimpleTileMapPlugin, app); raea_bevy_calls::simple_tilemap::calls(app); }, group: None, on_demand: false }); raea_runtime_plugins::register(raea_runtime_plugins::Registered { name: "simple_tilemap", install: |app| { crate::AddOnce::add_once(bevy_simple_tilemap::prelude::SimpleTileMapPlugin, app); raea_bevy_calls::simple_tilemap::calls(app); }, group: None, on_demand: false });
#[cfg(feature = "skein")] #[cfg(feature = "skein")]
@@ -164,7 +164,7 @@ pub fn declared() -> Vec<Declared> {
#[cfg(feature = "rapier2d")] v.push(Declared { name: "rapier2d", krate: "bevy_rapier2d", source: "version = \"=0.37.0\"", prefixes: &["bevy_rapier2d::", "raea_bevy_adapters::rapier2d::"], headless: &[], on_demand: false }); #[cfg(feature = "rapier2d")] v.push(Declared { name: "rapier2d", krate: "bevy_rapier2d", source: "version = \"=0.37.0\"", prefixes: &["bevy_rapier2d::", "raea_bevy_adapters::rapier2d::"], headless: &[], on_demand: false });
#[cfg(feature = "rapier3d")] v.push(Declared { name: "rapier3d", krate: "bevy_rapier3d", source: "version = \"=0.37.0\"", prefixes: &["bevy_rapier3d::", "raea_bevy_adapters::rapier3d::"], headless: &[], on_demand: false }); #[cfg(feature = "rapier3d")] v.push(Declared { name: "rapier3d", krate: "bevy_rapier3d", source: "version = \"=0.37.0\"", prefixes: &["bevy_rapier3d::", "raea_bevy_adapters::rapier3d::"], headless: &[], on_demand: false });
v.push(Declared { name: "remote", krate: "bevy_remote", source: "version = \"=0.20.0\"", prefixes: &["bevy_remote::"], headless: &[], on_demand: false }); v.push(Declared { name: "remote", krate: "bevy_remote", source: "version = \"=0.20.0\"", prefixes: &["bevy_remote::"], headless: &[], on_demand: false });
#[cfg(feature = "save")] v.push(Declared { name: "save", krate: "moonshine-save", source: "version = \"=0.8.0\"", prefixes: &["moonshine_save::"], headless: &[], on_demand: false }); #[cfg(feature = "save")] v.push(Declared { name: "save", krate: "moonshine-save", source: "version = \"=0.8.0\"", prefixes: &["moonshine_save::"], headless: &["assets"], on_demand: false });
#[cfg(feature = "simple_tilemap")] v.push(Declared { name: "simple_tilemap", krate: "bevy_simple_tilemap", source: "version = \"=0.21.0\"", prefixes: &["bevy_simple_tilemap::"], headless: &["shader", "image"], on_demand: false }); #[cfg(feature = "simple_tilemap")] v.push(Declared { name: "simple_tilemap", krate: "bevy_simple_tilemap", source: "version = \"=0.21.0\"", prefixes: &["bevy_simple_tilemap::"], headless: &["shader", "image"], on_demand: false });
#[cfg(feature = "skein")] v.push(Declared { name: "skein", krate: "bevy_skein", source: "version = \"=0.7.0-rc.1\"", prefixes: &["bevy_skein::"], headless: &[], on_demand: false }); #[cfg(feature = "skein")] v.push(Declared { name: "skein", krate: "bevy_skein", source: "version = \"=0.7.0-rc.1\"", prefixes: &["bevy_skein::"], headless: &[], on_demand: false });
#[cfg(feature = "smud")] v.push(Declared { name: "smud", krate: "bevy_smud", source: "version = \"=0.15.0\"", prefixes: &["bevy_smud::"], headless: &["shader", "mesh"], on_demand: false }); #[cfg(feature = "smud")] v.push(Declared { name: "smud", krate: "bevy_smud", source: "version = \"=0.15.0\"", prefixes: &["bevy_smud::"], headless: &["shader", "mesh"], on_demand: false });
+7
View File
@@ -22,6 +22,10 @@ required-features = ["bevy-plugins"]
[dependencies] [dependencies]
raea-runtime-plugins = { path = "../../runtime/plugins" } raea-runtime-plugins = { path = "../../runtime/plugins" }
raea-io-home = { path = "../../io/home" } raea-io-home = { path = "../../io/home" }
# the schemas of what an agent writes (brief.ts, script.ts, taste.ts, controllers): raea context reads specs against them
raea-core-brief = { path = "../../core/brief" }
# `raea workspace`, `raea project` and `raea controller` (docs/projects.feature PJ1-PJ4)
raea-app-workspace = { path = "../../apps/workspace" }
raea-runtime-react = { path = "../../runtime/react", default-features = false, features = ["h264", "av1", "scripts", "modules", "network", "ml"] } raea-runtime-react = { path = "../../runtime/react", default-features = false, features = ["h264", "av1", "scripts", "modules", "network", "ml"] }
# the sound of its renders and plays: <Seedling> samples and speech (raea-runtime-sound's features) # the sound of its renders and plays: <Seedling> samples and speech (raea-runtime-sound's features)
raea-runtime-sound = { path = "../../runtime/sound", features = ["seedling", "ml"] } raea-runtime-sound = { path = "../../runtime/sound", features = ["seedling", "ml"] }
@@ -38,7 +42,10 @@ raea-io-media = { path = "../../io/media", default-features = false, features =
raea-io-npm = { path = "../../io/npm" } raea-io-npm = { path = "../../io/npm" }
# the agent's sandbox (WASI tools on Wasmtime/Pulley) as wsx.* native calls # the agent's sandbox (WASI tools on Wasmtime/Pulley) as wsx.* native calls
wsx = { path = "../../engine/sandbox/wsx" } wsx = { path = "../../engine/sandbox/wsx" }
serde = "1"
serde_json = "1" serde_json = "1"
# `raea neural` (docs/raytracing.feature RT2)
raea-neural = { path = "../neural" }
regex = "1" regex = "1"
# the app crates' verbs: `raea check`, `raea ci`, and the local tools' (sao, tokensynth, setup-audio, sounds, splat) # the app crates' verbs: `raea check`, `raea ci`, and the local tools' (sao, tokensynth, setup-audio, sounds, splat)
raea-app-check = { path = "../../apps/check" } raea-app-check = { path = "../../apps/check" }
+14 -1
View File
@@ -49,10 +49,11 @@ const listed = new Set([...help.matchAll(/raea ([a-z][\w-]*)/g), ...help.matchAl
const shellVerbs = JSON.parse(/const SHELL: &\[&str\] = &(\[[^\]]*\]);/.exec(readFileSync(join(raea, "engine/cli/src/verbs.rs"), "utf8"))![1]) as string[]; const shellVerbs = JSON.parse(/const SHELL: &\[&str\] = &(\[[^\]]*\]);/.exec(readFileSync(join(raea, "engine/cli/src/verbs.rs"), "utf8"))![1]) as string[];
const handled = new Set([...cli.matchAll(/case "(\w+)":/g)].map((m) => m[1]).filter((c) => c !== "--help" && c !== "help")); const handled = new Set([...cli.matchAll(/case "(\w+)":/g)].map((m) => m[1]).filter((c) => c !== "--help" && c !== "help"));
/** the hand-written text under dir: a skill's reference/ is the help itself, written by tools/skills.sh gen */
function files(dir: string, out: string[] = []): string[] { function files(dir: string, out: string[] = []): string[] {
for (const f of readdirSync(dir)) { for (const f of readdirSync(dir)) {
const p = join(dir, f); const p = join(dir, f);
if (lstatSync(p).isDirectory()) files(p, out); if (lstatSync(p).isDirectory()) f !== "reference" && files(p, out);
else if (f.endsWith(".md")) out.push(p); else if (f.endsWith(".md")) out.push(p);
} }
return out; return out;
@@ -134,6 +135,18 @@ describe("raea's surface", () => {
} finally { } finally {
rmSync(dir, { recursive: true, force: true }); rmSync(dir, { recursive: true, force: true });
} }
// by feature (S5a): space.json, package.json, assets/, src/ with main.tsx, a feature, shots/; never components/
const feat = mkdtempSync(join(tmpdir(), "raea-init-feature-"));
const go = (...a: string[]) => spawnSync("bun", [join(here, "src/native.ts"), bin, ...a], { cwd: feat, encoding: "utf8" });
try {
expect(go("init", "--layout", "feature").stdout).toContain("made space.json, package.json, src/main.tsx");
expect(["space.json", "package.json", "assets", "src/main.tsx", "src/title.tsx", "src/shots/opening.tsx", "src/screens", "src/ui", "AGENTS.md"].filter((f) => !existsSync(join(feat, f)))).toEqual([]);
expect(existsSync(join(feat, "components"))).toBe(false);
expect(go("init", "--layout", "feature").stdout).toContain("nothing to make");
expect(go("init", "--layout", "other").status).toBe(2);
} finally {
rmSync(feat, { recursive: true, force: true });
}
}); });
// a made clip (two colours: the take has a jump cut at 2 s) and a made-up transcript, never real footage // a made clip (two colours: the take has a jump cut at 2 s) and a made-up transcript, never real footage
+71 -2
View File
@@ -95,13 +95,26 @@ pub fn run_script(args: &[String]) -> R<i32> {
pub fn run(args: &[String]) -> R<String> { pub fn run(args: &[String]) -> R<String> {
// no arguments, or asking for help: the usage, plainly (the render line's refusal is for a render missing its file) // no arguments, or asking for help: the usage, plainly (the render line's refusal is for a render missing its file)
// `help --json`: the same help, each verb's usage, flags and access tag (tools/skills.sh gen reads it)
if args.len() == 2 && args[0] == "help" && args[1] == "--json" {
return Ok(usage::help_json(&run(&["help".to_string()])?).to_string());
}
if args.is_empty() || matches!(args[0].as_str(), "help" | "--help" | "-h") { if args.is_empty() || matches!(args[0].as_str(), "help" | "--help" | "-h") {
let neural_usage = neural::USAGE;
let was = IN_HELP.replace(true); let was = IN_HELP.replace(true);
let usage = run(&["render".to_string()]).err().unwrap_or_default(); let usage = run(&["render".to_string()]).err().unwrap_or_default();
IN_HELP.set(was); IN_HELP.set(was);
// `raea library` (engine/cli/src/library.ts), listed under render's usage
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
// a workspace's files and specs (docs/projects.feature), listed under render's usage like library
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Studio unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook claude (Claude Code's PostToolUse hook: the quick check after a composition is saved)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n {}\n {}", skill::USAGE, tools::blender::USAGE);
let (export_game, scene, physics, splat) = (raea_app_game::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE); let (export_game, scene, physics, splat) = (raea_app_game::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);
let apps = format!(" {}\n", raea_app_check::USAGE); let apps = format!(" {}\n", raea_app_check::USAGE);
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)")); return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));
}
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {
return Ok(skill::version());
} }
// an argument the verb doesn't take is refused with its usage, never dropped (zsh's "--frame 20", one word, rendered // an argument the verb doesn't take is refused with its usage, never dropped (zsh's "--frame 20", one word, rendered
// every frame): the verb's flags and how many arguments it takes are read from its lines in the help, the one list // every frame): the verb's flags and how many arguments it takes are read from its lines in the help, the one list
@@ -118,6 +131,55 @@ pub fn run(args: &[String]) -> R<String> {
if args[0] == "context" { if args[0] == "context" {
return context(args.get(1).map(String::as_str)); return context(args.get(1).map(String::as_str));
} }
// `workspace …` and `project …`: the folder format, configured by committed git-config (docs/projects.feature PJ1)
if args[0] == "workspace" {
return raea_app_workspace::workspace(&args[1..]);
}
if args[0] == "project" {
return raea_app_workspace::project(&args[1..]);
}
// `controller …`: the workspace's controllers/<id>.ts and a project's overrides (PJ2)
if args[0] == "controller" {
return raea_app_workspace::controller(&args[1..], spec::spec_json);
}
// `skill [NAME]` and `skills install --agent A`: the skills this raea ships, for its version (SK6)
if args[0] == "skill" {
return skill::skill(&args[1..]);
}
if args[0] == "skills" {
return skill::install(&args[1..]);
}
// `next [DIR]` and `doctor [--fix] [DIR]`: the project's next steps, and its drift from this raea (SK10)
if args[0] == "next" {
return next(&args[1..]);
}
if args[0] == "doctor" {
return skill::doctor(&args[1..]);
}
// `setup blender` and `blender run SCRIPT.py`: Blender found or downloaded, its MCP add-on, headless scripts (SK11)
if args[0] == "setup" && args.get(1).map(String::as_str) == Some("blender") {
return tools::blender::setup(&args[2..]);
}
if args[0] == "blender" {
return tools::blender::blender(args);
}
// `spec FILE.ts`: a spec's data as JSON, for a program that reads specs without evaluating TypeScript (the feed's host)
if args[0] == "spec" {
return spec::spec_cli(&args[1..]);
}
// `check VIDEO --taste taste.ts|DIR`: the taste's .ts files evaluated here, then the check (main.rs takes the rest)
if args[0] == "check" && args.iter().any(|a| a == "--quick") {
let (report, bad) = raea_app_check::quick::quick(&args[1..], spec::tastes_ts(args)?)?;
println!("{report}");
std::process::exit(i32::from(bad));
}
// `hook claude`: Claude Code's PostToolUse hook, the quick check after a composition is saved (SK10)
if args[0] == "hook" {
return raea_app_check::quick::hook(&args[1..]);
}
if args[0] == "check" {
std::process::exit(raea_app_check::cli_with(&args[1..], spec::tastes_ts(args)?));
}
if args.first().map(String::as_str) == Some("traces") { if args.first().map(String::as_str) == Some("traces") {
return traces(args); return traces(args);
} }
@@ -136,6 +198,10 @@ pub fn run(args: &[String]) -> R<String> {
} }
// `mezz [--check] PATH...`: optimized media (raea_io_media::mezz, lightspeed F4): each long-GOP source over 1080p under // `mezz [--check] PATH...`: optimized media (raea_io_media::mezz, lightspeed F4): each long-GOP source over 1080p under
// PATH (a file, or a folder's videos) gets its intra-only ProRes copy, one at a time; --check only says which would // PATH (a file, or a folder's videos) gets its intra-only ProRes copy, one at a time; --check only says which would
// `neural mlxdlss DIR -o OUT`: DLSS 5 on a `render --aov` folder, through the founder's own MLX-DLSS (RT2)
if args.first().map(String::as_str) == Some("neural") {
return neural::neural(&args[1..]);
}
if args.first().map(String::as_str) == Some("mezz") { if args.first().map(String::as_str) == Some("mezz") {
return mezz(&args[1..]); return mezz(&args[1..]);
} }
@@ -157,6 +223,9 @@ pub fn run(args: &[String]) -> R<String> {
Some("song") => return tools::song::song(args), Some("song") => return tools::song::song(args),
// `track CLIP.mp4 [--subject X,Y,W,H] [--from S]`: the clip's camera solved for <Matchmove> (motion/track.rs) // `track CLIP.mp4 [--subject X,Y,W,H] [--from S]`: the clip's camera solved for <Matchmove> (motion/track.rs)
Some("track") => return motion::track::track(args), Some("track") => return motion::track::track(args),
// `gen …`: generation flows on made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, and ComfyUI workflows read
// and written (raea-io-gen, through apps/tools generate.rs for the local models)
Some("gen") => return raea_app_tools::generate::generate(args),
// the agent shell's own verbs ported here (`init`, `cut`, `frame`): engine/cli's handler, run by its native.ts (shell()) // the agent shell's own verbs ported here (`init`, `cut`, `frame`): engine/cli's handler, run by its native.ts (shell())
Some(v) if SHELL.contains(&v) => return shell(args), Some(v) if SHELL.contains(&v) => return shell(args),
_ => {} _ => {}
@@ -255,7 +324,7 @@ pub fn run(args: &[String]) -> R<String> {
} }
if args.first().map(String::as_str) != Some("render") || args.len() < 2 { if args.first().map(String::as_str) != Some("render") || args.len() < 2 {
return Err(format!( return Err(format!(
"raea render EDIT.tsx -o OUT.mp4|OUT.png|DIR [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--stage WxH] [--10bit] [--kbps N | --quality draft|high|master|0..1] (also: --lite --comps)\n raea render PAGE.html -o OUT.mp4|DIR [--at A,B] (an HTML composition, the HTML composition format format)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it) "raea render EDIT.tsx -o OUT.mp4|OUT.png|DIR [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--stage WxH] [--10bit] [--aov] [--alpha] [--kbps N | --quality draft|high|master|0..1] (also: --lite --comps)\n raea render PAGE.html -o OUT.mp4|DIR [--at A,B] (an HTML composition, the HTML composition format format)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help) raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help)
raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)", raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)",
tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE
+64 -79
View File
@@ -43,7 +43,7 @@ pub fn guide(name: Option<&str>) -> R<String> {
Ok(if shell { format!("{GUIDE_NOTE}{text}") } else { text }) Ok(if shell { format!("{GUIDE_NOTE}{text}") } else { text })
} }
/// The taste files a mode reads beside taste.brief, which is always read /// The taste files a mode reads beside taste.ts, which is always read
pub fn taste_kinds(mode: &str) -> &'static [&'static str] { pub fn taste_kinds(mode: &str) -> &'static [&'static str] {
match mode { match mode {
"pitch" | "explain" | "story" => &["motion", "sound"], "pitch" | "explain" | "story" => &["motion", "sound"],
@@ -53,86 +53,65 @@ pub fn taste_kinds(mode: &str) -> &'static [&'static str] {
} }
} }
/// A brief's head facts (the `key: value` lines before its first `## `), "(assumed)" dropped
pub fn brief_fact(text: &str, key: &str) -> Option<String> {
text.lines()
.take_while(|l| !l.starts_with("## "))
.find_map(|l| {
let (k, v) = l.split_once(':')?;
(k.trim().eq_ignore_ascii_case(key)).then(|| v.trim().trim_end_matches("(assumed)").trim().to_string())
})
.filter(|v| !v.is_empty())
}
/// One `## Heading` section's text, without its heading
pub fn brief_section(text: &str, heading: &str) -> Option<String> {
let mut out = String::new();
let mut inside = false;
for l in text.lines() {
if let Some(h) = l.strip_prefix("## ") {
if inside {
break;
}
inside = h.trim().eq_ignore_ascii_case(heading);
continue;
}
if inside {
out.push_str(l);
out.push('\n');
}
}
let out = out.trim().to_string();
(!out.is_empty()).then_some(out)
}
/// `raea context PROJECT`: everything an agent reads before working on a project, in the order it should be read. That /// `raea context PROJECT`: everything an agent reads before working on a project, in the order it should be read. That
/// is the person's taste (~/.raea/taste/taste.brief, then the files its modes need; RAEA_TASTE moves the folder), the /// is the person's taste (~/.raea/taste/taste.ts, then the files its modes need; RAEA_TASTE moves the folder), the
/// project's brief and any deliverable briefs it links, its look (the brief's ## Look and brand/brand.css), and the /// project's brief and the briefs and script it names, its look (the brief's look and brand/brand.css), and the craft
/// craft floor and each mode's guide. PROJECT is a folder holding brief.brief, or a .brief file. /// floor and each mode's guide. PROJECT is a folder holding brief.ts, or the file.
pub fn context(project: Option<&str>) -> R<String> { pub fn context(project: Option<&str>) -> R<String> {
let project = project.ok_or("usage: raea context PROJECT (a folder with brief.brief, or a .brief file)")?; let project = project.ok_or("usage: raea context PROJECT (a folder with brief.ts, or a brief.ts file)")?;
let path = Path::new(project); let brief_path = brief_at(project)?;
let brief_path = if path.is_dir() { path.join("brief.brief") } else { path.to_path_buf() }; let spec::Loaded { path: brief_path, text: brief, title, modes, more: subs, look, .. } = spec::load_brief_ts(&brief_path)?;
let brief = std::fs::read_to_string(&brief_path).map_err(|e| format!("no brief at {} ({e}): a project starts as brief.brief", brief_path.display()))?;
let dir = brief_path.parent().unwrap_or(Path::new(".")).to_path_buf(); let dir = brief_path.parent().unwrap_or(Path::new(".")).to_path_buf();
let title = brief.lines().find_map(|l| l.strip_prefix("# ")).unwrap_or("Untitled").trim().to_string();
let modes_of = |text: &str| -> Vec<String> {
brief_fact(text, "mode").map(|m| m.split([',', '+', '&']).map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()).collect()).unwrap_or_default()
};
// deliverable briefs: a Deliver line naming a .brief beside the project's
let mut subs: Vec<(PathBuf, String)> = Vec::new();
if let Some(deliver) = brief_section(&brief, "deliver") {
for tok in deliver.split(['·', '\n']).map(str::trim) {
let tok = tok.split(['→', ' ']).next().unwrap_or("").trim();
if tok.ends_with(".brief") {
let p = dir.join(tok);
match std::fs::read_to_string(&p) {
Ok(t) => subs.push((p, t)),
Err(e) => subs.push((p, format!("(missing: {e})"))),
}
}
}
}
let mut modes = modes_of(&brief);
for (_, t) in &subs {
for m in modes_of(t) {
if !modes.contains(&m) {
modes.push(m);
}
}
}
let taste_dir = std::env::var_os("RAEA_TASTE").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".raea/taste"))); let taste_dir = std::env::var_os("RAEA_TASTE").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".raea/taste")));
// a cheap doctor (file reads and git config): CONTEXT_STALE when this project or the agent's skill is from another raea
let stale = raea_app_workspace::doctor::findings(&dir, &skill::agents(), &skill::version());
let stale = match stale.first() {
Some(f) => format!("CONTEXT_STALE raea doctor finds {} thing(s), first: {} (raea doctor --fix)\n\n", stale.len(), f.says),
None => String::new(),
};
let mut out = format!( let mut out = format!(
"# raea context: {title}\n\nRead all of this before any work on the project, in this order. The person's taste beats every guide's default; the brief\nbeats your own taste. Modes: {}.\n", "{stale}# raea context: {title}\n\nRead all of this before any work on the project, in this order. The person's taste beats every guide's default; the brief\nbeats your own taste. Modes: {}.\n",
if modes.is_empty() { "none yet (shape the brief first: who it's for, what they should believe, what kind of piece)".to_string() } else { modes.join(", ") } if modes.is_empty() { "none yet (shape the brief first: who it's for, what they should believe, what kind of piece)".to_string() } else { modes.join(", ") }
); );
context_body(&mut out, &dir, taste_dir, &modes, &brief_path, brief, subs, look);
Ok(out)
}
/// `raea next [DIR]`: the two or three useful next steps for the project (apps/workspace next.rs).
pub fn next(args: &[String]) -> R<String> {
let brief_path = brief_at(args.first().map(String::as_str).unwrap_or("."))?;
let l = spec::load_brief_ts(&brief_path)?;
let dir = brief_path.parent().unwrap_or(Path::new(".")).to_path_buf();
let stale = raea_app_workspace::doctor::findings(&dir, &skill::agents(), &skill::version()).len();
Ok(raea_app_workspace::next::text(&dir, &raea_app_workspace::next::Brief { needs: l.missing, modes: l.modes }, stale))
}
/// The brief.ts for a folder anywhere inside a project, or the file named.
fn brief_at(project: &str) -> R<PathBuf> {
let path = Path::new(project);
let brief_path = if path.is_dir() {
// from anywhere inside a project: the nearest folder up with a brief.ts or a .raea/project
let dir = path.canonicalize().ok().and_then(|d| d.ancestors().find(|a| a.join("brief.ts").is_file() || a.join(".raea/project").is_file()).map(Path::to_path_buf));
dir.unwrap_or_else(|| path.to_path_buf()).join("brief.ts")
} else {
path.to_path_buf()
};
if !brief_path.is_file() {
return Err(format!("no brief at {}: a project starts as brief.ts (`export default brief({{ title: ... }})` from \"raea/brief\")", brief_path.display()));
}
Ok(brief_path)
}
/// The sections of `raea context` after its head, in reading order.
#[allow(clippy::too_many_arguments)]
fn context_body(out: &mut String, dir: &Path, taste_dir: Option<PathBuf>, modes: &[String], brief_path: &Path, brief: String, subs: Vec<(PathBuf, String)>, look: Option<String>) {
let mut section = |name: String, body: String| out.push_str(&format!("\n\n===== {name} =====\n\n{}\n", body.trim_end())); let mut section = |name: String, body: String| out.push_str(&format!("\n\n===== {name} =====\n\n{}\n", body.trim_end()));
// the person's taste: always taste.brief, then each kind its modes need, once // the person's taste: always taste.ts, then each kind its modes need, once
match &taste_dir { match taste_dir.as_deref().and_then(|t| spec::taste_file(t, "taste").map(|f| (t, f))) {
Some(t) if t.join("taste.brief").is_file() => { Some((t, (p, text))) => {
section(format!("TASTE {}", t.join("taste.brief").display()), std::fs::read_to_string(t.join("taste.brief")).unwrap_or_default()); section(format!("TASTE {}", p.display()), text);
let mut kinds: Vec<&str> = Vec::new(); let mut kinds: Vec<&str> = Vec::new();
for m in &modes { for m in modes {
for k in taste_kinds(m) { for k in taste_kinds(m) {
if !kinds.contains(k) { if !kinds.contains(k) {
kinds.push(k); kinds.push(k);
@@ -140,20 +119,27 @@ pub fn context(project: Option<&str>) -> R<String> {
} }
} }
for k in kinds { for k in kinds {
let p = t.join(format!("{k}.brief")); if let Some((p, text)) = spec::taste_file(t, k) {
if let Ok(text) = std::fs::read_to_string(&p) {
section(format!("TASTE {}", p.display()), text); section(format!("TASTE {}", p.display()), text);
} }
} }
} }
_ => section("TASTE".into(), "(no taste yet: ~/.raea/taste/taste.brief holds the person's standing corrections)".into()), None => section("TASTE".into(), "(no taste yet: ~/.raea/taste/taste.ts holds the person's standing corrections)".into()),
}
// the workspace's house rules, which every project in it follows (docs/projects.feature)
if let Some((p, text)) = raea_app_workspace::up(&dir, ".raea/workspace").and_then(|ws| spec::taste_file(&ws, "taste")) {
section(format!("WORKSPACE TASTE {}", p.display()), text);
}
// the workspace's controllers, with this project's overrides: its settings and workflows, which the work follows
if let Some(text) = raea_app_workspace::summary(&dir, spec::spec_json) {
section("CONTROLLERS (raea controller ls; a project's own values marked)".into(), text);
} }
section(format!("BRIEF {}", brief_path.display()), brief.clone()); section(format!("BRIEF {}", brief_path.display()), brief.clone());
for (p, t) in &subs { for (p, t) in &subs {
section(format!("BRIEF {}", p.display()), t.clone()); section(format!("{} {}", if p.to_string_lossy().contains("script") { "SCRIPT" } else { "BRIEF" }, p.display()), t.clone());
} }
// the look: the brief's own section, and the brand's tokens when the project has them // the look: the brief's own section, and the brand's tokens when the project has them
let mut look = brief_section(&brief, "look").unwrap_or_else(|| "(the brief has no ## Look yet)".into()); let mut look = look.unwrap_or_else(|| "(the brief has no look yet)".into());
if let Ok(css) = std::fs::read_to_string(dir.join("brand/brand.css")) { if let Ok(css) = std::fs::read_to_string(dir.join("brand/brand.css")) {
look.push_str(&format!("\n\nbrand/brand.css:\n{css}")); look.push_str(&format!("\n\nbrand/brand.css:\n{css}"));
} }
@@ -163,12 +149,11 @@ pub fn context(project: Option<&str>) -> R<String> {
if let Ok(t) = std::fs::read_to_string(craft.join("floor.md")) { if let Ok(t) = std::fs::read_to_string(craft.join("floor.md")) {
section(format!("GUIDE craft floor ({})", craft.join("floor.md").display()), t); section(format!("GUIDE craft floor ({})", craft.join("floor.md").display()), t);
} }
for m in &modes { for m in modes {
let p = craft.join("modes").join(format!("{m}.md")); let p = craft.join("modes").join(format!("{m}.md"));
match std::fs::read_to_string(&p) { match std::fs::read_to_string(&p) {
Ok(t) => section(format!("GUIDE mode {m} ({})", p.display()), t), Ok(t) => section(format!("GUIDE mode {m} ({})", p.display()), t),
Err(_) => section(format!("GUIDE mode {m}"), format!("(raea has no guide for the mode {m:?} yet)")), Err(_) => section(format!("GUIDE mode {m}"), format!("(raea has no guide for the mode {m:?} yet)")),
} }
} }
Ok(out)
} }
+15 -2
View File
@@ -4,6 +4,7 @@
// (native.ts answers it), and every other verb is the engine's own command line (`engine`: the native `raea`), so there // (native.ts answers it), and every other verb is the engine's own command line (`engine`: the native `raea`), so there
// is one `raea`, and its help is the native one. Every command prints what a person would read; files hold the rest. // is one `raea`, and its help is the native one. Every command prints what a person would read; files hold the rest.
import { REGISTRY, TEMPLATE } from "./registry.gen"; import { REGISTRY, TEMPLATE } from "./registry.gen";
import { FEATURE_DIRS, featureLayout } from "./layout";
/** The host's answer to an op (src/native.ts answers shape, cut, frame and brand). Throws when there's no host. */ /** The host's answer to an op (src/native.ts answers shape, cut, frame and brand). Throws when there's no host. */
export type Host = (op: string, args: Record<string, unknown>) => any; export type Host = (op: string, args: Record<string, unknown>) => any;
@@ -20,6 +21,8 @@ type Fs = {
}; };
type Ctx = { cwd: string; fs: Fs }; type Ctx = { cwd: string; fs: Fs };
const out = (stdout: string, exitCode = 0, stderr = "") => ({ stdout, stderr, exitCode }); const out = (stdout: string, exitCode = 0, stderr = "") => ({ stdout, stderr, exitCode });
// `raea library` (library.ts), kept apart from the imports above
import { libraryVerb } from "./library";
function flag(args: string[], name: string): string | undefined { function flag(args: string[], name: string): string | undefined {
const i = args.indexOf(name); const i = args.indexOf(name);
@@ -88,8 +91,8 @@ eyes 38% down as the speaker moves; an objectPosition or transform turns it off)
<Img src>. Media files import as modules: import take from <Img src>. Media files import as modules: import take from
"./media/x.mov". Sound: music in Tone.js (import * as Tone from "raea/tone"): instruments in a Tone.Sampler "./media/x.mov". Sound: music in Tone.js (import * as Tone from "raea/tone"): instruments in a Tone.Sampler
playing a Part or Sequence, the instrument's notes from Tone.tokensynth("a warm upright bass", ["C2", "C3", "C4"]) or a playing a Part or Sequence, the instrument's notes from Tone.tokensynth("a warm upright bass", ["C2", "C3", "C4"]) or a
sample library (\`raea sounds\`); sao("prompt", {seconds}) for an effect, as an <Audio src>; fish("words") for sample library (\`raea sounds\`); sao("prompt", {seconds}) for an effect, as an <Audio src>; narration
narration. All local but fish. <Mix lufs ceiling> masters the sound. is <Speech text start> from raea/speech (Pocket TTS). All of it local. <Mix lufs ceiling> masters the sound.
Words: useWords() -> [{text, from, to}] (frames, the cuts' words), word("phrase") -> the frame it's said, Words: useWords() -> [{text, from, to}] (frames, the cuts' words), word("phrase") -> the frame it's said,
findPhrase(words, "phrase", {occurrence, edge: "start" | "end"}). findPhrase(words, "phrase", {occurrence, edge: "start" | "end"}).
Placement: <Region name="top" | "bottom" | "center" | "auto" | "full"> keeps a part in a band clear of the face and Placement: <Region name="top" | "bottom" | "center" | "auto" | "full"> keeps a part in a band clear of the face and
@@ -138,6 +141,14 @@ export function raeaHandler(host?: Host, engine?: Engine) {
made.push(name); made.push(name);
}; };
const shape = ask("shape", {}) as { width: number; height: number; fps: number }; const shape = ask("shape", {}) as { width: number; height: number; fps: number };
// by feature, as a Bevy project is (S5a): opt-in until it's the default
if (args.includes("--layout") && args[args.indexOf("--layout") + 1] !== "feature") return out("", 2, "raea init [--layout feature]\n");
if (args.includes("--layout")) {
for (const d of FEATURE_DIRS) await c.fs.mkdir(p(d), { recursive: true });
const name = c.cwd.replace(/\/$/, "").split("/").pop() || "project";
for (const [f, body] of Object.entries(featureLayout(name, shape))) await put(f, body);
return out(made.length ? `made ${made.join(", ")}; render it with raea render src/main.tsx\n` : "nothing to make: the project's files are here\n");
}
await c.fs.mkdir(p("components"), { recursive: true }); await c.fs.mkdir(p("components"), { recursive: true });
await put("edit.tsx", TEMPLATE["edit.tsx"]); await put("edit.tsx", TEMPLATE["edit.tsx"]);
await put("cuts.ts", cutsModule([], shape)); await put("cuts.ts", cutsModule([], shape));
@@ -221,6 +232,8 @@ export function raeaHandler(host?: Host, engine?: Engine) {
if (!q) return out("", 2, "raea brand DOMAIN|URL (stripe.com, or the site's URL: read on this machine)\n"); if (!q) return out("", 2, "raea brand DOMAIN|URL (stripe.com, or the site's URL: read on this machine)\n");
return out(text(ask("brand", { brand: q }))); return out(text(ask("brand", { brand: q })));
} }
case "library":
return out(libraryVerb(ask, args.slice(1), (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}));
default: default:
return await native(); return await native();
} }
+78
View File
@@ -0,0 +1,78 @@
// `raea init --layout feature`: an object's folder laid out as bevy_new_2d's template is, by feature (docs/sdk.feature
// S5a). A video is an App like a game: main.tsx registers its Composition, each feature (here its title) is one file
// with its components, shots are scenes in Sequences, and files sit in assets/, where staticFile reads them.
export interface Shape { width: number; height: number; fps: number }
/** The folders it makes, empty ones included: assets/ and src/'s screens/, shots/ and ui/. */
export const FEATURE_DIRS = ["assets", "src", "src/screens", "src/shots", "src/ui"];
/** Its files by path, for a project called `name`. */
export function featureLayout(name: string, shape: Shape): Record<string, string> {
const { width, height, fps } = shape;
return {
"space.json": JSON.stringify({ name, kind: "video" }, null, 2) + "\n",
"package.json": JSON.stringify({ name, private: true, raea: { plugins: [] } }, null, 2) + "\n",
"src/main.tsx": `// The App: its plugins and its root. A video registers its Composition here; its shots play in Sequences.
import { AbsoluteFill, Composition, Sequence, registerRoot } from "raea";
import { Opening } from "./shots/opening";
import { Title } from "./title";
const FPS = ${fps};
function Main() {
return (
<AbsoluteFill style={{ background: "#101418" }}>
<Sequence from={0} durationInFrames={FPS * 3}>
<Opening />
</Sequence>
<Title text="${name}" from={FPS / 2} />
</AbsoluteFill>
);
}
registerRoot(() => <Composition id="main" component={Main} width={${width}} height={${height}} fps={FPS} durationInFrames={FPS * 3} />);
`,
"src/title.tsx": `// A feature: its components together in one file. A feature with work in the App each frame (systems, resources)
// also exports its plugin, definePlugin({ name, build(app) }) from "raea/app"; this one draws only, so it has none.
import { interpolate, useCurrentFrame } from "raea";
export function Title({ text, from }: { text: string; from: number }) {
const f = useCurrentFrame();
const shown = interpolate(f, [from, from + 12], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });
return (
<div style={{ position: "absolute", left: 0, right: 0, bottom: "12%", textAlign: "center", fontFamily: "Inter", fontWeight: 800, fontSize: ${Math.round(Math.min(width, height) / 12)}, color: "#ffffff", opacity: shown }}>
{text}
</div>
);
}
`,
"src/shots/opening.tsx": `// A shot: a scene component, one time range of the cut (main.tsx places it in a Sequence).
import { AbsoluteFill, interpolate, useCurrentFrame } from "raea";
export function Opening() {
const f = useCurrentFrame();
const x = interpolate(f, [0, 60], [-20, 20], { extrapolateRight: "clamp" });
return (
<AbsoluteFill style={{ alignItems: "center", justifyContent: "center" }}>
<div style={{ width: "30%", aspectRatio: "1", borderRadius: "50%", background: "#ff7a1a", transform: \`translateX(\${x}%)\` }} />
</AbsoluteFill>
);
}
`,
"AGENTS.md": `# This project
A video, laid out by feature as a Bevy project is (raea init --layout feature):
- space.json: its name and kind. package.json: raea.plugins, the Bevy, Blitz and raea plugins it uses.
- assets/: its files. \`staticFile("x.png")\` reads assets/x.png (a media/ folder beside it is read first).
- src/main.tsx: the App, rendered with \`raea render src/main.tsx\`. It registers the Composition.
- src/<feature>.tsx: one feature each (title, captions, music), its components together; one with work in the App
each frame also exports its plugin (definePlugin from "raea/app").
- src/shots/: the shots, each a scene component placed in a Sequence. src/screens/: one file per top-level state.
src/ui/: page parts shared between features.
Never a components/ folder: a feature file holds a feature's components by name.
`,
};
}
+3
View File
@@ -8,10 +8,13 @@ use raea_runtime_react::scene::{self as motion, *};
use raea_runtime_export::{self as export, *}; use raea_runtime_export::{self as export, *};
use raea_app_tools as tools; use raea_app_tools as tools;
use serde_json::json; use serde_json::json;
use raea_neural as neural;
mod cli; mod cli;
mod guide; mod guide;
mod refused; mod refused;
mod skill;
mod spec;
mod tests; mod tests;
mod usage; mod usage;
mod verbs; mod verbs;
+106
View File
@@ -0,0 +1,106 @@
// `raea library`: an agent's way into the person's libraries (raea docs/libraries.feature), through the raea app's
// host (apps/app host/library/service.ts, asked as host op "library"). An agent can list libraries, make one, ask to
// add a folder or drive (the person allows it in the app; a folder they already granted is added at once), search by
// meaning, list files and tag them. Every command prints what a person would read.
type Ask = (op: string, args: Record<string, unknown>) => any;
type Lib = { id: string; name: string; files: number; indexed: number; sources: { kind: string; label: string; here?: boolean; online: boolean }[] };
export const LIBRARY_USAGE = `raea library (the workspace's libraries, their sources, and folders waiting for the person)
raea library new NAME
raea library add LIBRARY PATH (a folder or a drive: the person allows it in the app unless it's already granted)
raea library search "WORDS" [--library LIBRARY] [--kind video|image|audio] [--limit N] [--sound] (--sound: a described sound, ranked by sound alone)
raea library files LIBRARY
raea library tag SHA256 TAG[,TAG...]
raea library status | raea library scan
LIBRARY is a library's name or id.
`;
const flagOf = (args: string[], name: string) => {
const i = args.indexOf(name);
return i >= 0 ? args[i + 1] : undefined;
};
const t = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;
export function libraryVerb(ask: Ask, args: string[], env: Record<string, string | undefined>): string {
const workspace = env.RAEA_WORKSPACE ?? "w-default";
const by = env.RAEA_LIBRARY_BY ?? `agent:${env.RAEA_AGENT ?? "cli"}`;
const q = (op: string, a: Record<string, unknown> = {}) => ask("library", { op, ...a });
const all = (): Lib[] => q("list", { workspace }).libraries;
const find = (key?: string): Lib => {
if (!key) throw new Error(`which library?\n${LIBRARY_USAGE}`);
const ls = all();
const l = ls.find((x) => x.id === key) ?? ls.find((x) => x.name.toLowerCase() === key.toLowerCase());
if (!l) throw new Error(`no library "${key}"; there are: ${ls.map((x) => x.name).join(", ") || "none yet (raea library new NAME)"}`);
return l;
};
const [sub, ...rest] = args;
switch (sub) {
case undefined:
case "list": {
const ls = all();
const waiting: { library: string; path: string; by: string }[] = q("requests").requests;
if (!ls.length) return "No libraries yet. raea library new NAME makes one.\n";
return (
ls
.map((l) => {
const src = l.sources.map((s) => ` ${s.kind} ${s.label}${s.here ? "" : s.online ? " (another machine)" : " (offline)"}`);
const ask = waiting.filter((w) => w.library === l.id).map((w) => ` waiting for the person: ${w.path} (${w.by})`);
return [`${l.name} [${l.id}] ${l.files} files, ${l.indexed} indexed`, ...src, ...ask].join("\n");
})
.join("\n") + "\n"
);
}
case "new": {
// on this Mac unless --cloud (Pro: searchable from the web and other devices)
const name = rest.filter((w) => w !== "--cloud").join(" ").trim();
if (!name) throw new Error("raea library new NAME [--cloud]");
const l = q("create", { workspace, name, by, where: rest.includes("--cloud") ? "cloud" : "local" });
return `made ${l.name} [${l.id}]${l.id.startsWith("loc_") ? " on this Mac" : " in raea cloud"}. raea library add "${l.name}" PATH asks to add a folder or drive.\n`;
}
case "add": {
const [key, path] = rest;
if (!path) throw new Error("raea library add LIBRARY PATH");
const l = find(key);
const r = q("add", { library: l.id, path, by });
return r.state === "needs-approval"
? `asked: ${r.path} waits for the person to allow it in the raea app (Libraries > ${l.name}). Its files are indexed once they do.\n`
: `added ${r.label} to ${l.name}; its files are being scanned and indexed on this machine.\n`;
}
case "search": {
// --sound takes no value; the other flags take the word after them
const valued = (a?: string) => !!a?.startsWith("--") && a !== "--sound";
const words = rest.filter((a, i) => !a.startsWith("--") && !valued(rest[i - 1])).join(" ");
if (!words) throw new Error('raea library search "WORDS"');
const lib = flagOf(rest, "--library");
const r = q("search", { workspace, words, libraries: lib ? [find(lib).id] : undefined, kind: flagOf(rest, "--kind"), limit: Number(flagOf(rest, "--limit")) || 10, sound: rest.includes("--sound") });
if (!r.hits.length) return `nothing found for "${words}"\n`;
const lines = r.hits.map((h: any) => {
const span = h.t1 > 0 ? ` ${t(h.t0)}-${t(h.t1)}` : "";
const where = h.local ?? (h.file?.locations?.[0] ? `${h.file.locations[0].label}/${h.file.locations[0].path} (not on this machine)` : h.sha256);
return `${where}${span} (${h.matched.join(", ")})${h.text ? ` "${h.text.slice(0, 80)}"` : ""}`;
});
const note = r.by === "words" ? (r.rebuilding ? "(by words only: the cloud index is being rebuilt for a new model)\n" : "(by words only: the search model is still loading)\n") : r.by === "sound" ? "(by sound only)\n" : "";
return `${note}${lines.join("\n")}\n`;
}
case "files": {
const l = find(rest[0]);
const r = q("files", { library: l.id });
return r.files.map((f: any) => `${f.path} ${f.kind} ${f.sha256.slice(0, 12)}${f.labels.length ? ` labels: ${f.labels.join(", ")}` : ""}${f.tags.length ? ` tags: ${f.tags.join(", ")}` : ""}`).join("\n") + (r.next ? "\n(more: the app lists the rest)\n" : "\n");
}
case "tag": {
const [sha, tags] = rest;
if (!tags) throw new Error("raea library tag SHA256 TAG[,TAG...]");
const r = q("tag", { sha256: sha, tags: tags.split(",").map((x) => x.trim()).filter(Boolean) });
return `tagged ${sha.slice(0, 12)}: ${r.tags.join(", ")}\n`;
}
case "scan":
return `${q("scan").queued} new files to index\n`;
case "status": {
const s = q("status");
return `model ${s.model.phase}; ${s.indexing ? `indexing ${s.indexing.file} (${s.indexing.step}), ` : ""}${s.queue} waiting, ${s.done} done, ${s.failed} failed${s.errors[0] ? `\nlast error: ${s.errors[0].file}: ${s.errors[0].error}` : ""}\n`;
}
default:
throw new Error(LIBRARY_USAGE);
}
}
+2 -1
View File
@@ -13,7 +13,8 @@ fn main() {
let args: Vec<String> = std::env::args().skip(1).collect(); let args: Vec<String> = std::env::args().skip(1).collect();
let code = match args.first().map(String::as_str) { let code = match args.first().map(String::as_str) {
// `check VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3 // `check VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3
Some("check") => raea_app_check::cli(&args[1..]), // (with --taste or --quick, through the engine, which evaluates the taste.ts files or renders stills: raea_cli's `check`)
Some("check") if !args.iter().any(|a| a == "--taste" || a == "--quick") => raea_app_check::cli_with(&args[1..], Vec::new()),
// `ci …`: the gates' sound measurements and lightspeed's process measurements // `ci …`: the gates' sound measurements and lightspeed's process measurements
Some("ci") => raea_app_ci::cli(&args[1..]), Some("ci") => raea_app_ci::cli(&args[1..]),
_ => { _ => {
+29 -3
View File
@@ -1,6 +1,6 @@
// The agent shell's own verbs (init ...) on the native `raea`, which runs this file on its JavaScriptCore with Node's core // The agent shell's own verbs (init ...) on the native `raea`, which runs this file on its JavaScriptCore with Node's core
// (runtime/react/src/scene.rs shell(), raea_native::js::run_node), so each verb has one source: this package's handler. // (runtime/react/src/scene.rs shell(), raea_native::js::run_node), so each verb has one source: this package's handler.
// The host's ops it needs are answered here, one more with each verb ported (docs/agent-context.md); the rest refuse. // The host's ops it needs are answered here, one more with each verb ported (docs/agent-surfaces.md); the rest refuse.
// //
// native.ts RAEA VERB ARGS... RAEA: the native raea's path, for the engine's own verbs // native.ts RAEA VERB ARGS... RAEA: the native raea's path, for the engine's own verbs
import { spawnSync } from "node:child_process"; import { spawnSync } from "node:child_process";
@@ -81,14 +81,24 @@ function words(take: string, hear = false): Word[] {
.map((w) => ({ text: w.text.trim(), from: w.start_ms / 1000, to: w.end_ms / 1000 })); .map((w) => ({ text: w.text.trim(), from: w.start_ms / 1000, to: w.end_ms / 1000 }));
} }
/** A tool a clean Mac lacks, found or installed once by raea's tools/ensure.sh (docs/app.feature AP6), which sits in
* share/raea/tools beside a release's bin/raea, or in the tree a built raea is in; the bare name if there's none */
function ensure(name: string): string {
const real = realpathSync(raea);
const script = [`${dirname(real)}/../share/raea/tools/ensure.sh`, `${dirname(real)}/../../tools/ensure.sh`].find(existsSync);
if (!script) return name;
const r = spawnSync("bash", [script, name], { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] });
return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : name;
}
function hearTake(take: string, out: string) { function hearTake(take: string, out: string) {
const dir = mkdtempSync(`${tmpdir()}/raea-hear-`); const dir = mkdtempSync(`${tmpdir()}/raea-hear-`);
try { try {
const wav = `${dir}/take.wav`; const wav = `${dir}/take.wav`;
const a = spawnSync(raea, ["media", "audio", at(take), "--rate", "16000", "--mono", "-o", wav], { encoding: "utf8" }); const a = spawnSync(raea, ["media", "audio", at(take), "--rate", "16000", "--mono", "-o", wav], { encoding: "utf8" });
if (a.status !== 0) throw new Error(`no sound to transcribe in ${take}: ${(a.stdout + a.stderr).trim()}`); if (a.status !== 0) throw new Error(`no sound to transcribe in ${take}: ${(a.stdout + a.stderr).trim()}`);
const p = spawnSync("parakeet-mlx", [wav, "--output-format", "json", "--output-dir", dir], { encoding: "utf8" }); const p = spawnSync(ensure("parakeet-mlx"), [wav, "--output-format", "json", "--output-dir", dir], { encoding: "utf8" });
if (p.status !== 0) throw new Error(`transcribing ${take} needs parakeet-mlx (pip install parakeet-mlx), or cut it by time: --at A-B`); if (p.status !== 0) throw new Error(`transcribing ${take} needs parakeet-mlx (tools/ensure.sh installs it: ${(p.stderr ?? "").trim().split("\n").pop()}), or cut it by time: --at A-B`);
const heard = JSON.parse(readFileSync(`${dir}/take.json`, "utf8")) as { sentences: { tokens: { text: string; start: number; end: number }[] }[] }; const heard = JSON.parse(readFileSync(`${dir}/take.json`, "utf8")) as { sentences: { tokens: { text: string; start: number; end: number }[] }[] };
const ws = heard.sentences.flatMap((s) => wordsOf(s.tokens)).map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) })); const ws = heard.sentences.flatMap((s) => wordsOf(s.tokens)).map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) }));
writeFileSync(out, JSON.stringify(ws) + "\n"); writeFileSync(out, JSON.stringify(ws) + "\n");
@@ -353,6 +363,20 @@ function brand(a: { brand: string }): string {
return kit.said; return kit.said;
} }
/** An op of the feed host's libraries (apps/app host/library/service.ts): POST $RAEA_FEED_HOST/host/library. The feed
* sets RAEA_FEED_HOST for the agents it starts; elsewhere it's given by hand. */
function library(a: Record<string, unknown>): unknown {
const at = process.env.RAEA_FEED_HOST;
if (!at) throw new Error("libraries live in the raea app: run this from an agent the app started, or set RAEA_FEED_HOST to the app's address");
const r = spawnSync("curl", ["-sS", "--max-time", "120", "-w", "\n%{http_code}", "-H", "content-type: application/json", "--data-binary", "@-", `${at.replace(/\/$/, "")}/host/library`], { input: JSON.stringify(a), encoding: "utf8", maxBuffer: 64 << 20 });
const text = r.stdout ?? "";
const cut = text.lastIndexOf("\n");
const [body, code] = [text.slice(0, cut), Number(text.slice(cut + 1))];
if (r.status !== 0) throw new Error(`the raea app at ${at} didn't answer: ${(r.stderr ?? "").trim()}`);
if (!(code >= 200 && code < 300)) throw new Error(body.trim() || `the raea app said ${code}`);
return JSON.parse(body);
}
const host: Host = (op, a) => { const host: Host = (op, a) => {
switch (op) { switch (op) {
case "shape": case "shape":
@@ -363,6 +387,8 @@ const host: Host = (op, a) => {
return cut(a as Parameters<typeof cut>[0]); return cut(a as Parameters<typeof cut>[0]);
case "brand": case "brand":
return brand(a as Parameters<typeof brand>[0]); return brand(a as Parameters<typeof brand>[0]);
case "library":
return library(a);
default: default:
throw new Error(`raea: this step (${op}) isn't in the native raea yet`); throw new Error(`raea: this step (${op}) isn't in the native raea yet`);
} }
+179
View File
@@ -0,0 +1,179 @@
//! `raea skill` and `raea skills install` (docs/skills.feature SK6): the agent skills this raea ships, version-matched.
//! An agent can hold a skill from an older or newer install than its `raea`; the copy's front matter names the version it
//! came with (`version:`, stamped by tools/release.sh and by `skills install`), and when that differs from
//! `raea --version` the agent reads `raea skill` instead.
use super::*;
pub const USAGE: &str = "raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and for claude adds the quick-check hook unless --no-hooks)";
/// Where each agent reads a person's skills, one folder per skill holding SKILL.md. Checked by hand on 11-05:
/// claude: ~/.claude/skills (Claude Code's docs); codex: ~/.agents/skills (developers.openai.com/codex/skills, the user
/// scope; older builds read ~/.codex/skills); kimi: $KIMI_CODE_HOME/skills, else ~/.kimi-code/skills (kimi 2.3.3's own
/// binary; it also reads ~/.agents/skills and ~/.claude/skills); gemini: ~/.gemini/skills (geminicli.com/docs/cli/skills).
fn target(agent: &str) -> R<PathBuf> {
let home = tools::agent_mcp::user_home()?;
Ok(match agent {
"claude" => home.join(".claude/skills"),
"codex" => home.join(".agents/skills"),
"kimi" => std::env::var_os("KIMI_CODE_HOME").filter(|v| !v.is_empty()).map(PathBuf::from).unwrap_or_else(|| home.join(".kimi-code")).join("skills"),
"gemini" => home.join(".gemini/skills"),
a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
})
}
/// Each agent and the folder it reads skills from, for `raea doctor` (an agent with no folder is skipped).
pub fn agents() -> Vec<(&'static str, PathBuf)> {
["claude", "codex", "kimi", "gemini"].into_iter().filter_map(|a| target(a).ok().map(|t| (a, t))).collect()
}
/// `raea doctor [--fix] [DIR]` (SK10): what doesn't match this raea, an agent's skill reinstalled by --fix.
pub fn doctor(args: &[String]) -> R<String> {
let again = |agent: &str| install(&["install".into(), "--agent".into(), agent.into(), "--no-mcp".into()]);
raea_app_workspace::doctor::doctor(args, &agents(), &version(), &again)
}
/// This raea's version: the release's (share/raea/VERSION), or the crate's for a build from a checkout.
pub fn version() -> String {
std::fs::read_to_string(raea_io_home::home().join("VERSION"))
.ok()
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty())
.unwrap_or_else(|| format!("{}-checkout", env!("CARGO_PKG_VERSION")))
}
/// The skills raea ships: an install's share/raea/skills, or the checkout's sdk/skills.
fn shipped() -> R<PathBuf> {
let home = raea_io_home::home();
["skills", "sdk/skills"].iter().map(|d| home.join(d)).find(|d| d.join("raea/SKILL.md").is_file()).ok_or_else(|| format!("no skills under {}: reinstall raea (curl -fsSL https://raea.io/install | sh)", home.display()))
}
/// SKILL.md with `version: V` in its front matter (replacing one that's there), so a copy says which raea it came with.
pub fn stamp(text: &str, v: &str) -> String {
let Some(rest) = text.strip_prefix("---\n") else { return text.to_string() };
let Some(end) = rest.find("\n---\n") else { return text.to_string() };
let lines: Vec<&str> = rest[..end].lines().filter(|l| !l.starts_with("version:")).collect();
format!("---\n{}\nversion: {v}\n---\n{}", lines.join("\n"), &rest[end + 5..])
}
/// `raea skill [NAME] [--reference cli|feed|files|sdk]`: the shipped skill's text, or one of its references.
pub fn skill(args: &[String]) -> R<String> {
let name = args.first().filter(|a| !a.starts_with("--")).map(String::as_str).unwrap_or("raea");
let reference = args.iter().position(|a| a == "--reference").map(|i| args.get(i + 1).cloned().ok_or("--reference takes cli, feed, files or sdk"));
let ok = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-');
if !ok(name) {
return Err(format!("no skill {name:?}"));
}
let dir = shipped()?.join(name);
if !dir.join("SKILL.md").is_file() {
return Err(format!("no skill {name:?}: {}", installed_names()?.join(", ")));
}
match reference {
Some(r) => {
let r = r?;
let path = dir.join("reference").join(format!("{r}.md"));
if !ok(&r) || !path.is_file() {
return Err(format!("no reference {r:?} in {name}: cli, feed, files or sdk"));
}
std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))
}
None => Ok(stamp(&std::fs::read_to_string(dir.join("SKILL.md")).map_err(|e| e.to_string())?, &version())),
}
}
fn installed_names() -> R<Vec<String>> {
let mut v = Vec::new();
for e in std::fs::read_dir(shipped()?).map_err(|e| e.to_string())?.flatten() {
// raea-work is internal (work.raea.io's pages): a checkout has it, a release doesn't ship it
let name = e.file_name().to_string_lossy().into_owned();
if name != "raea-work" && e.path().join("SKILL.md").is_file() {
v.push(name);
}
}
v.sort();
Ok(v)
}
/// Copies a folder, following links (raea-bevy's topic files link to the craft guides in a checkout).
fn copy(from: &Path, to: &Path) -> R<()> {
std::fs::create_dir_all(to).map_err(|e| format!("{}: {e}", to.display()))?;
for e in std::fs::read_dir(from).map_err(|e| e.to_string())?.flatten() {
let (src, dst) = (e.path(), to.join(e.file_name()));
if src.is_dir() {
copy(&src, &dst)?;
} else if src.is_file() {
std::fs::copy(&src, &dst).map_err(|e| format!("{}: {e}", src.display()))?;
}
}
Ok(())
}
/// `raea skills install --agent claude|codex|kimi|gemini`: raea's skills, stamped with this version, where that agent
/// reads them; each replaces the copy that was there.
pub fn install(args: &[String]) -> R<String> {
if args.first().map(String::as_str) != Some("install") {
return Err(format!("usage: {USAGE}"));
}
let agent = args.iter().position(|a| a == "--agent").and_then(|i| args.get(i + 1)).ok_or("which agent: --agent claude|codex|kimi|gemini")?;
let to = target(agent)?;
let (from, v) = (shipped()?, version());
let mut out = String::new();
for name in installed_names()? {
let dst = to.join(&name);
if dst.exists() {
std::fs::remove_dir_all(&dst).map_err(|e| format!("{}: {e}", dst.display()))?;
}
copy(&from.join(&name), &dst)?;
let md = dst.join("SKILL.md");
let text = std::fs::read_to_string(&md).map_err(|e| e.to_string())?;
std::fs::write(&md, stamp(&text, &v)).map_err(|e| e.to_string())?;
out += &format!("{}: {name} {v}\n", dst.display());
}
// pinned moves (SK10): a skill per move, so an agent's /quieter loads the one guide
for (i, a) in args.iter().enumerate() {
if a == "--pin" {
let m = args.get(i + 1).ok_or("--pin takes a move: quieter, bolder, layout, adapt...")?;
out += &tools::agent_mcp::pin(&to, m, &v)?;
}
}
// Claude Code's hook: the quick check after a composition is saved (SK10); --no-hooks leaves its settings alone
if agent == "claude" && !args.iter().any(|a| a == "--no-hooks") {
let settings = target("claude")?.with_file_name("settings.json");
out += &format!("{}: hook `raea hook claude` {}\n", settings.display(), if tools::agent_mcp::claude_hook(&settings)? { "added" } else { "already there" });
}
// the MCP servers raea offers (SK11): blender, for a running Blender; --no-mcp leaves the agent's servers alone
if !args.iter().any(|a| a == "--no-mcp") {
out += &tools::agent_mcp::offer(agent)?;
out += "\n";
}
Ok(format!("{out}{agent} reads them in its next session"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stamp_puts_one_version_in_the_front_matter() {
let md = "---\nname: raea\nversion: 0.0.1\ndescription: d\n---\n\n# raea\n";
assert_eq!(stamp(md, "0.1.0-canary.3"), "---\nname: raea\ndescription: d\nversion: 0.1.0-canary.3\n---\n\n# raea\n");
assert_eq!(stamp("# no front matter\n", "1"), "# no front matter\n");
}
#[test]
fn the_skill_and_its_references_come_from_this_raea() {
let core = skill(&[]).unwrap();
assert!(core.starts_with("---\nname: raea\n") && core.contains(&format!("\nversion: {}\n---\n", version())), "{}", &core[..200.min(core.len())]);
assert!(skill(&["--reference".into(), "cli".into()]).unwrap().contains("raea render"));
assert!(skill(&["raea-bevy".into()]).is_ok());
assert!(skill(&["../x".into()]).is_err());
assert!(skill(&["--reference".into(), "../../x".into()]).is_err());
}
#[test]
fn install_targets_each_agents_folder() {
assert!(target("claude").unwrap().ends_with(".claude/skills"));
assert!(target("codex").unwrap().ends_with(".agents/skills"));
assert!(target("gemini").unwrap().ends_with(".gemini/skills"));
assert!(target("cursor").is_err());
}
}
+128
View File
@@ -0,0 +1,128 @@
//! Specs written in TypeScript (docs/handoff/authoring.md, docs/projects.feature PJ0): brief.ts, script.ts, taste.ts
//! and a workspace's controllers. A spec is a module whose default export is data; the engine evaluates it headless
//! (bundle_module with PRINT_DEFAULT, run_bundle) and Rust reads the JSON against the schema in core/brief, so tsc's errors come first and
//! these come second, naming the field.
use super::*;
use raea_core_brief as schema;
use serde::de::DeserializeOwned;
use std::sync::atomic::Ordering;
/// The default export of a spec module, as the JSON it evaluates to.
pub fn spec_json(ts: &Path) -> R<String> {
let ts = ts.canonicalize().map_err(|e| format!("{}: {e}", ts.display()))?;
let out = std::env::temp_dir().join(format!("raea-spec-{}.js", std::process::id()));
bundle_module(&ts, &out, PRINT_DEFAULT)?;
// the JSON is ours to read, not the person's to see: the run prints nothing to the terminal
let echo = raea_runtime_react::native::ECHO.swap(false, Ordering::Relaxed);
let ran = run_bundle(&out, 60.0);
raea_runtime_react::native::ECHO.store(echo, Ordering::Relaxed);
let _ = std::fs::remove_file(&out);
let (code, printed) = ran?;
let last = printed.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").to_string();
if code != 0 {
return Err(format!("{}: {}", ts.display(), last.strip_prefix("error: ").unwrap_or(&last)));
}
Ok(last)
}
/// A spec read against its schema; the error names the file and the field.
pub fn read_spec<T: DeserializeOwned>(ts: &Path) -> R<T> {
let name = ts.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
schema::read(&name, &spec_json(ts)?)
}
/// What `raea context` reads from a project's brief.ts.
pub struct Loaded {
pub path: PathBuf,
/// what the agent reads: the file as written, with what's missing from it after
pub text: String,
pub title: String,
pub modes: Vec<String>,
/// deliverables' own briefs and the project's script, each (path, text)
pub more: Vec<(PathBuf, String)>,
pub look: Option<String>,
/// what the brief still needs (schema::brief::doctor), empty when it's shaped
pub missing: Vec<String>,
}
/// A project's brief.ts: checked against the Brief schema, its modes, its deliverables' briefs and its script.
pub fn load_brief_ts(path: &Path) -> R<Loaded> {
let brief: schema::Brief = read_spec(path)?;
let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
let mut text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
let missing = schema::brief::doctor(&brief);
if !missing.is_empty() {
text.push_str(&format!("\n\nWhat the brief still needs:\n{}", missing.iter().map(|m| format!("- {m}")).collect::<Vec<_>>().join("\n")));
}
let mut modes: Vec<String> = brief.mode.iter().map(|m| m.trim().to_ascii_lowercase()).filter(|m| !m.is_empty()).collect();
let mut more = Vec::new();
let mut files: Vec<String> = brief.deliver.iter().flat_map(|d| [d.brief.clone(), d.script.clone()]).flatten().collect();
if dir.join("script.ts").is_file() && !files.iter().any(|f| f == "script.ts") {
files.push("script.ts".into());
}
for f in files {
let p = dir.join(&f);
let checked = if f.contains("script") { read_spec::<schema::Script>(&p).map(|_| ()) } else { read_spec::<schema::Brief>(&p).map(|b| modes.extend(b.mode)) };
let body = std::fs::read_to_string(&p).unwrap_or_else(|e| format!("(missing: {e})"));
more.push((p, match checked {
Ok(()) => body,
Err(e) => format!("{body}\n\n(raea can't read it: {e})"),
}));
}
modes.dedup();
Ok(Loaded { path: path.to_path_buf(), text, title: brief.title.clone(), modes, more, look: brief.look, missing })
}
/// A taste file by name (taste, motion, games...): NAME.ts, checked as Taste.
pub fn taste_file(dir: &Path, name: &str) -> Option<(PathBuf, String)> {
let ts = dir.join(format!("{name}.ts"));
let body = std::fs::read_to_string(&ts).ok()?;
Some(match read_spec::<schema::Taste>(&ts) {
Ok(_) => (ts, body),
Err(e) => (ts, format!("{body}\n\n(raea can't read it: {e})")),
})
}
/// The .ts files `--taste` names: the file, or every .ts in the folder.
fn taste_ts_files(args: &[String]) -> Vec<PathBuf> {
let Some(t) = args.iter().position(|a| a == "--taste").and_then(|i| args.get(i + 1)).map(PathBuf::from) else { return vec![] };
if t.extension().is_some_and(|x| x == "ts") {
return vec![t];
}
let mut v: Vec<PathBuf> = std::fs::read_dir(&t).into_iter().flatten().filter_map(|e| e.ok().map(|e| e.path())).filter(|f| f.extension().is_some_and(|x| x == "ts")).collect();
v.sort();
v
}
/// `--taste`'s .ts files, each checked as Taste.
pub fn tastes_ts(args: &[String]) -> R<Vec<schema::Taste>> {
taste_ts_files(args).iter().map(|f| read_spec(f)).collect()
}
/// `raea spec FILE.ts [--as KIND]`: the default export as JSON, checked as KIND (by default from the file's name:
/// brief, script, taste or plan in it, controller under controllers/; anything else is checked as Taste, the files in
/// ~/.raea/taste being named for their kind).
pub fn spec_cli(args: &[String]) -> R<String> {
const USAGE: &str = "usage: raea spec FILE.ts [--as brief|script|taste|plan|controller]";
let file = args.iter().enumerate().find(|(i, a)| !a.starts_with("--") && (*i == 0 || args[i - 1] != "--as")).map(|(_, a)| PathBuf::from(a)).ok_or(USAGE)?;
let named = file.to_string_lossy().to_lowercase();
let kind = args.iter().position(|a| a == "--as").and_then(|i| args.get(i + 1)).cloned().unwrap_or_else(|| {
let base = file.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
["brief", "script", "plan"].iter().find(|k| base.contains(*k)).map(|k| k.to_string()).unwrap_or(if named.contains("controllers/") { "controller".into() } else { "taste".into() })
});
let json = spec_json(&file)?;
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let value: serde_json::Value = match kind.as_str() {
"brief" => serde_json::to_value(schema::read::<schema::Brief>(&name, &json)?),
"script" => serde_json::to_value(schema::read::<schema::Script>(&name, &json)?),
"taste" => serde_json::to_value(schema::read::<schema::Taste>(&name, &json)?),
"plan" => serde_json::to_value(schema::read::<schema::Plan>(&name, &json)?),
"controller" => {
let raw: serde_json::Value = serde_json::from_str(&json).map_err(|e| format!("{name}: {e}"))?;
serde_json::to_value(schema::controller::normalize(&raw).map_err(|e| format!("{name}: {e}"))?)
}
k => return Err(format!("raea spec can't check a {k:?}: brief, script, taste, plan or controller\n{USAGE}")),
}
.map_err(|e| e.to_string())?;
Ok(value.to_string())
}
+15 -1
View File
@@ -37,6 +37,20 @@ fn help_lists_every_verb() {
} }
} }
#[test]
fn help_json_is_every_listed_verb() {
// `raea help --json` (tools/skills.sh gen's source): the verbs the help lists, not its prose, each with its flags
let help = run(&["help".to_string()]).unwrap();
let j: serde_json::Value = serde_json::from_str(&run(&["help".to_string(), "--json".to_string()]).unwrap()).unwrap();
let verbs: Vec<&str> = j["verbs"].as_array().unwrap().iter().map(|v| v["verb"].as_str().unwrap()).collect();
assert_eq!(verbs, verb_list(&help).iter().map(String::as_str).collect::<Vec<_>>());
assert!(!verbs.contains(&"compositions"), "the help's opening line isn't a verb: {verbs:?}");
let controller = j["verbs"].as_array().unwrap().iter().find(|v| v["verb"] == "controller").unwrap();
assert_eq!(controller["args"], 3);
assert!(controller["flags"].as_array().unwrap().iter().any(|f| f["flag"] == "--by" && f["values"] == 1));
assert!(j["verbs"].as_array().unwrap().iter().any(|v| v["verb"] == "gen" && v["own_parser"] == true));
}
#[test] #[test]
fn a_verb_refuses_what_it_doesnt_take() { fn a_verb_refuses_what_it_doesnt_take() {
let help = run(&["help".to_string()]).unwrap(); let help = run(&["help".to_string()]).unwrap();
@@ -90,7 +104,7 @@ fn every_flag_a_verb_reads_is_in_the_help() {
"--game", "--info", "--selftest", "--no-pointer", // an exported game's own player reads these (game.rs player_main) "--game", "--info", "--selftest", "--no-pointer", // an exported game's own player reads these (game.rs player_main)
"--o", // track and splat take "--o" for -o, a slip they forgive "--o", // track and splat take "--o" for -o, a slip they forgive
"--nope", "--loud", // test fixtures "--nope", "--loud", // test fixtures
"--help", "--help", "--version", // raea's own, before any verb
"--filter", "--bundle-only", "--define", "--alias", "--node-stub", // `raea test`, raea's own conformance runner, unlisted "--filter", "--bundle-only", "--define", "--alias", "--node-stub", // `raea test`, raea's own conformance runner, unlisted
]; ];
let lit = regex::Regex::new(r#""(--[a-z0-9][a-z0-9-]*)[="]"#).unwrap(); let lit = regex::Regex::new(r#""(--[a-z0-9][a-z0-9-]*)[="]"#).unwrap();
+52 -2
View File
@@ -139,8 +139,8 @@ pub fn usage_of(help: &str, verb: &str) -> Option<Usage> {
/// the ones it takes. None when it is, or when the help doesn't give the verb's usage. /// the ones it takes. None when it is, or when the help doesn't give the verb's usage.
pub fn stray(help: &str, args: &[String]) -> Option<String> { pub fn stray(help: &str, args: &[String]) -> Option<String> {
let verb = args.first()?; let verb = args.first()?;
// physics hands its subverb's arguments to the bake, the goo or the part, which check them // physics hands its subverb's arguments to the bake, the goo or the part, which check them; gen to raea-io-gen's own
if verb == "physics" { if verb == "physics" || verb == "gen" {
return None; return None;
} }
let u = usage_of(help, verb)?; let u = usage_of(help, verb)?;
@@ -163,3 +163,53 @@ pub fn stray(help: &str, args: &[String]) -> Option<String> {
} }
None None
} }
/// Every verb the help lists, in its order (each `raea VERB` it names).
pub fn verb_list(help: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for line in help.lines() {
// a usage line, not the help's prose ("raea: renders … raea compositions")
let line = line.trim().trim_start_matches("usage:").trim();
if !line.starts_with("raea ") {
continue;
}
let toks: Vec<&str> = line.split(" (").next().unwrap_or("").split_whitespace().collect();
for w in toks.windows(2).filter(|w| w[0] == "raea") {
let v = w[1].trim_end_matches(':');
if v.chars().all(|c| c.is_ascii_lowercase() || c == '-') && !v.is_empty() && !out.iter().any(|o| o == v) {
out.push(v.to_string());
}
}
}
out
}
/// Where a verb runs (docs/agent-surfaces.md section 4): HEADLESS unless it needs the feed's host.
fn access(verb: &str) -> &'static str {
match verb {
// the person's libraries live in the raea app's host; a folder an agent adds waits for the person's yes
"library" => "HOST, then PERSON to add a folder",
_ => "HEADLESS",
}
}
/// `raea help --json`: each verb with its usage lines, its flags (with how many values follow each), how many
/// arguments it takes (null: any number), its access tag, and `own_parser` when its own parser checks them (its flags
/// are then its own help's, not these). tools/skills.sh gen writes the CLI reference from it.
pub fn help_json(help: &str) -> serde_json::Value {
// a verb whose arguments its own parser checks: stray() lets even a flag no verb has through
let own = |v: &str| stray(help, &[v.to_string(), "--no-such-flag".to_string()]).is_none();
let rows: Vec<_> = verb_list(help)
.into_iter()
.map(|v| match usage_of(help, &v) {
Some(u) => {
let mut flags: Vec<_> = u.flags.into_iter().collect();
flags.sort();
json!({"verb": v, "usage": u.lines, "flags": flags.into_iter().map(|(f, n)| json!({"flag": f, "values": n})).collect::<Vec<_>>(), "args": u.slots, "access": access(&v), "own_parser": own(&v)})
}
// passes its arguments on (media's ffmpeg): its line, unparsed
None => json!({"verb": v, "usage": help.lines().map(str::trim).filter(|l| l.contains(&format!("raea {v} "))).collect::<Vec<_>>(), "flags": [], "args": null, "access": access(&v), "own_parser": true}),
})
.collect();
json!({"verbs": rows})
}
+2 -2
View File
@@ -95,8 +95,8 @@ pub fn mezz(args: &[String]) -> R<String> {
/// The agent shell's own verbs (engine/cli/src/index.ts) this binary runs; the rest come one by one (docs/agent-context.md) /// The agent shell's own verbs (engine/cli/src/index.ts) this binary runs; the rest come one by one (docs/agent-surfaces.md)
pub const SHELL: &[&str] = &["init", "cut", "frame", "part", "brand"]; pub const SHELL: &[&str] = &["init", "cut", "frame", "part", "brand", "library"];
/// One of SHELL's verbs: @raea/cli's handler, run by engine/cli/src/native.ts on raea's JavaScriptCore with Node's core, so the /// One of SHELL's verbs: @raea/cli's handler, run by engine/cli/src/native.ts on raea's JavaScriptCore with Node's core, so the
/// verb's one source is its TypeScript. native.ts answers the host's ops it needs, and runs this binary for the engine's verbs. /// verb's one source is its TypeScript. native.ts answers the host's ops it needs, and runs this binary for the engine's verbs.
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "raea-neural"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea neural: DLSS 5 neural rendering on a `render --aov` folder through the founder's own MLX-DLSS (docs/raytracing.feature RT2)"
[dependencies]
image = { version = "0.25", default-features = false, features = ["png"] }
# the CLI's flag reader and result type
raea-runtime-bundle = { path = "../../runtime/bundle" }
+223
View File
@@ -0,0 +1,223 @@
//! `raea neural mlxdlss DIR -o OUT` (docs/raytracing.feature RT2): DLSS 5's neural rendering on a render, on the Mac,
//! through MLX-DLSS (github.com/iamwavecut/MLX-DLSS, Apache-2.0), fed raea's own motion vectors and depth (`render
//! --aov`). An optional integration: the mlxdlss binary and the weights are the founder's (the weights are NVIDIA's,
//! extracted from their own DLSS install, and never ship with raea).
use std::path::{Path, PathBuf};
use raea_runtime_bundle::{R, flag};
pub const USAGE: &str = "raea neural mlxdlss DIR -o OUT [--model M.dlssmodel] [--intensity X] [--profile P] [--skin-structure X] [--local-structure X] [--steady A]";
fn tool_and_model(args: &[String]) -> R<(PathBuf, PathBuf)> {
let bin = std::env::var_os("RAEA_MLXDLSS").map(PathBuf::from).filter(|p| p.is_file()).ok_or(
"raea neural mlxdlss needs your own MLX-DLSS build: set RAEA_MLXDLSS to its mlxdlss binary (github.com/iamwavecut/MLX-DLSS, `swift build -c release`)",
)?;
let model = flag(args, "--model").or_else(|| std::env::var("RAEA_DLSS_MODEL").ok()).map(PathBuf::from).filter(|p| p.exists()).ok_or(
"raea neural mlxdlss needs weights you extracted yourself (MLX-DLSS's `mlxdlss-weights extract` from your NVIDIA DLSS install): --model or RAEA_DLSS_MODEL names the .dlssmodel; raea doesn't ship them",
)?;
Ok((bin, model))
}
/// The frames of a `render --aov` folder, in order: (picture, motion, depth).
fn frames(dir: &Path) -> R<Vec<(PathBuf, PathBuf, PathBuf)>> {
let mut pngs: Vec<PathBuf> = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "png") && p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("frame-"))).collect();
pngs.sort();
if pngs.is_empty() {
return Err(format!("{}: no frame-NNNNN.png (make it with raea render EDIT.tsx -o {} --aov)", dir.display(), dir.display()));
}
pngs.into_iter()
.map(|p| {
let stem = p.file_stem().unwrap().to_string_lossy().into_owned();
let (m, d) = (dir.join("motion").join(format!("{stem}.f32")), dir.join("depth").join(format!("{stem}.f32")));
if !m.is_file() || !d.is_file() {
return Err(format!("{}: no motion or depth beside it (render with --aov)", p.display()));
}
Ok((p, m, d))
})
.collect()
}
/// A 0..1 channel as an 8-bit one (rounded, clamped).
fn to_byte(x: f32) -> u8 {
(x.clamp(0.0, 1.0) * 255.0).round() as u8
}
fn f32s(p: &Path) -> R<Vec<f32>> {
let b = std::fs::read(p).map_err(|e| format!("{}: {e}", p.display()))?;
Ok(b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())
}
fn write_f32s(p: &Path, v: impl Iterator<Item = f32>) -> R<()> {
std::fs::write(p, v.flat_map(f32::to_le_bytes).collect::<Vec<u8>>()).map_err(|e| format!("{}: {e}", p.display()))
}
pub fn neural(args: &[String]) -> R<String> {
if args.first().map(String::as_str) != Some("mlxdlss") || args.len() < 2 {
return Err(format!("usage: {USAGE}"));
}
let dir = PathBuf::from(&args[1]);
let out = PathBuf::from(flag(args, "-o").ok_or(format!("usage: {USAGE}"))?);
let (bin, model) = tool_and_model(args)?;
let list = frames(&dir)?;
let (w, h) = image::image_dimensions(&list[0].0).map_err(|e| format!("{}: {e}", list[0].0.display()))?;
// the inputs as run-sequence reads them: float32 NHWC, rows top to bottom. Colour is the frame's sRGB values in
// 0..1 (as MLX-DLSS's own video path hands it frames); motion is negated, since run-sequence's normalized-uv adds
// it to a pixel to find where it was, and Bevy's is where it is minus where it was; depth is Bevy's reverse Z
let work = std::env::temp_dir().join(format!("raea-neural-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&work);
std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;
// one run-sequence a shot: the network keeps a history, and carried over a cut it painted the last shot's face
// onto the next one's
let starts = cuts(&list, w as usize, h as usize)?;
// each shot run, steadied and written before the next, and its float files deleted: a whole render's at once
// (colour, motion and the network's output, 70 MB a 1080p frame) filled the disk
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let a: f32 = flag(args, "--steady").map(|v| v.parse::<f32>().ok().filter(|a| *a > 0.0 && *a <= 1.0).ok_or("--steady takes 0..1 (1: off)")).transpose()?.unwrap_or(0.25);
let mut steady = Steady { w: w as usize, h: h as usize, a, hist: None };
for (k, &s0) in starts.iter().enumerate() {
let s1 = starts.get(k + 1).copied().unwrap_or(list.len());
let mut cmd = std::process::Command::new(&bin);
cmd.arg("run-sequence").arg(&model);
for (i, (png, m, d)) in list.iter().enumerate().take(s1).skip(s0) {
let rgb = image::open(png).map_err(|e| format!("{}: {e}", png.display()))?.to_rgb8();
if rgb.dimensions() != (w, h) {
return Err(format!("{}: {}x{}, the first frame is {w}x{h}", png.display(), rgb.width(), rgb.height()));
}
let (c, mo) = (work.join(format!("c{i:05}.f32")), work.join(format!("m{i:05}.f32")));
write_f32s(&c, rgb.as_raw().iter().map(|&b| b as f32 / 255.0))?;
// a shot's first frame has no last frame to have moved from
let mv = if i == s0 { vec![0.0; (w * h * 2) as usize] } else { f32s(m)? };
if mv.len() != (w * h * 2) as usize {
return Err(format!("{}: {} floats, a {w}x{h} frame's motion is {}", m.display(), mv.len(), w * h * 2));
}
write_f32s(&mo, mv.into_iter().map(|v| -v))?;
cmd.arg("--input").arg(&c).arg("--motion").arg(&mo).arg("--depth").arg(d);
}
let shot = work.join(format!("shot{k}"));
cmd.args(["--input-format", "rgb-temporal-reference", "--motion-format", "normalized-uv", "--depth-inverted", "true"]);
cmd.args(["--width", &w.to_string(), "--height", &h.to_string()]).arg("--output-dir").arg(&shot);
for key in ["--intensity", "--profile", "--skin-structure", "--local-structure"] {
if let Some(v) = flag(args, key) {
cmd.args([key, &v]);
}
}
let st = cmd.stdout(std::process::Stdio::null()).status().map_err(|e| format!("{}: {e}", bin.display()))?;
if !st.success() {
return Err(format!("mlxdlss run-sequence failed on frames {s0}..{s1} ({st})"));
}
for i in s0..s1 {
let _ = std::fs::remove_file(work.join(format!("c{i:05}.f32")));
let _ = std::fs::remove_file(work.join(format!("m{i:05}.f32")));
}
steady.hist = None;
for (i, (png, m, d)) in list.iter().enumerate().take(s1).skip(s0) {
let f = shot.join(format!("{:06}.f32", i - s0));
let v = f32s(&f)?;
if v.len() != (w * h * 3) as usize {
return Err(format!("mlxdlss frame {i}: {} floats, not {w}x{h}x3", v.len()));
}
let raw: Vec<f32> = image::open(png).map_err(|e| format!("{}: {e}", png.display()))?.to_rgb8().as_raw().iter().map(|&b| b as f32 / 255.0).collect();
let v = steady.frame(&raw, &v, &f32s(m)?, &f32s(d)?);
let px: Vec<u8> = v.iter().copied().map(to_byte).collect();
let dest = out.join(png.file_name().unwrap());
image::save_buffer(&dest, &px, w, h, image::ColorType::Rgb8).map_err(|e| format!("{}: {e}", dest.display()))?;
}
let _ = std::fs::remove_dir_all(&shot);
}
eprintln!("raea: {} shot(s), cut before frames {:?}", starts.len(), &starts[1..]);
let _ = std::fs::remove_dir_all(&work);
Ok(format!("APPLIED {} frames through DLSS 5 neural rendering (MLX-DLSS, raea's motion and depth) to {}", list.len(), out.display()))
}
/// `--steady A`: the network re-invents fine detail a little differently each frame (skin grain, a silhouette's edge),
/// which reads as shimmer where raea's own frames are still. Its change to each frame (its output minus raea's) is
/// carried along raea's motion vectors and blended in at A a frame (an exponential history, as TAA's), then added back
/// onto raea's frame: the look stays, the shimmer goes. A cut (`cuts`) and a pixel that came
/// out from behind something (its depth where it was isn't its depth now) start again from this frame's change.
/// 1 turns it off. On the faces reel's still shot: shimmer 0.21 -> about a quarter of it (RT2).
struct Steady {
w: usize,
h: usize,
a: f32,
/// the last frame: its carried change (3 a pixel), raea's frame and depth (None at a shot's start)
hist: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,
}
impl Steady {
fn frame(&mut self, raw: &[f32], net: &[f32], motion: &[f32], depth: &[f32]) -> Vec<f32> {
let (w, h, n) = (self.w, self.h, self.w * self.h);
let change: Vec<f32> = net.iter().zip(raw).map(|(o, r)| o - r).collect();
let carried = if self.hist.is_none() || self.a >= 1.0 {
change
} else {
let (hc, _, hd) = self.hist.as_ref().unwrap();
let mut c = vec![0f32; n * 3];
for y in 0..h {
for x in 0..w {
let i = y * w + x;
// where this pixel was: Bevy's motion is this frame's UV minus the last's
let (px, py) = (x as f32 - motion[i * 2] * w as f32, y as f32 - motion[i * 2 + 1] * h as f32);
let (fx, fy) = (px.floor(), py.floor());
let inside = fx >= 0.0 && fy >= 0.0 && fx < (w - 1) as f32 && fy < (h - 1) as f32;
let (x0, y0) = (fx as usize, fy as usize);
let was = if inside { hd[y0 * w + x0].max(hd[y0 * w + x0 + 1]).max(hd[(y0 + 1) * w + x0]).max(hd[(y0 + 1) * w + x0 + 1]) } else { -1.0 };
// reverse Z: close enough when within 2% (0 is the background, where any depth is the same)
let same = inside && ((was - depth[i]).abs() <= 0.02 * depth[i].max(was) || (was == 0.0 && depth[i] == 0.0));
for k in 0..3 {
let now = change[i * 3 + k];
c[i * 3 + k] = if same {
let (tx, ty) = (px - fx, py - fy);
let s = |xx: usize, yy: usize| hc[(yy * w + xx) * 3 + k];
let old = (s(x0, y0) * (1.0 - tx) + s(x0 + 1, y0) * tx) * (1.0 - ty) + (s(x0, y0 + 1) * (1.0 - tx) + s(x0 + 1, y0 + 1) * tx) * ty;
old + (now - old) * self.a
} else {
now
};
}
}
}
c
};
let out = raw.iter().zip(&carried).map(|(r, c)| r + c).collect();
self.hist = Some((carried, raw.to_vec(), depth.to_vec()));
out
}
}
/// Where the shots start (0 first): a frame is a cut when most of what it shows wasn't where its motion vectors say it
/// came from, by depth (reverse Z within 2%), or its foreground grew or shrank by half. raea's motion is the scene's,
/// so a cut between two people facing the same way (their silhouettes nearly the same) is still found.
fn cuts(list: &[(PathBuf, PathBuf, PathBuf)], w: usize, h: usize) -> R<Vec<usize>> {
let mut starts = vec![0];
let mut last = f32s(&list[0].2)?;
for (i, (_, m, d)) in list.iter().enumerate().skip(1) {
let (mv, depth) = (f32s(m)?, f32s(d)?);
if mv.len() != w * h * 2 || depth.len() != w * h {
return Err(format!("{}: not a {w}x{h} frame's motion and depth", m.display()));
}
let (mut fg, mut lost, mut was_fg) = (0usize, 0usize, 0usize);
for y in (0..h).step_by(2) {
for x in (0..w).step_by(2) {
let k = y * w + x;
was_fg += (last[k] > 0.0) as usize;
if depth[k] <= 0.0 {
continue;
}
fg += 1;
let (px, py) = ((x as f32 - mv[k * 2] * w as f32).round(), (y as f32 - mv[k * 2 + 1] * h as f32).round());
let ok = px >= 0.0 && py >= 0.0 && (px as usize) < w && (py as usize) < h && {
let was = last[py as usize * w + px as usize];
(was - depth[k]).abs() <= 0.02 * depth[k].max(was)
};
lost += (!ok) as usize;
}
}
let grew = fg.max(was_fg) as f32 / fg.min(was_fg).max(1) as f32;
if (fg > 0 && lost as f32 > 0.3 * fg as f32) || grew > 1.5 {
starts.push(i);
}
last = depth;
}
Ok(starts)
}
+1
View File
@@ -12,6 +12,7 @@ raea-sys-page = { path = "../../systems/page" }
raea-sys-fonts = { path = "../../systems/fonts" } raea-sys-fonts = { path = "../../systems/fonts" }
raea-runtime-twins = { path = "../../runtime/twins" } raea-runtime-twins = { path = "../../runtime/twins" }
raea-runtime-dom = { path = "../../runtime/dom" } raea-runtime-dom = { path = "../../runtime/dom" }
raea-runtime-edit = { path = "../../runtime/edit" }
raea-runtime-input = { path = "../../runtime/input" } raea-runtime-input = { path = "../../runtime/input" }
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "bevy_render", "bevy_asset", "bevy_image", "bevy_log", "bevy_window", "ui_bevy_render", "bevy_picking", "ui_picking", "bevy_input_focus"] } bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "bevy_render", "bevy_asset", "bevy_image", "bevy_log", "bevy_window", "ui_bevy_render", "bevy_picking", "ui_picking", "bevy_input_focus"] }
# the document: stylo's styles, Taffy's and Blitz's layout (floats on, as Chrome lays them out) # the document: stylo's styles, Taffy's and Blitz's layout (floats on, as Chrome lays them out)
+9 -13
View File
@@ -17,6 +17,8 @@ path = "src/main.rs"
[features] [features]
# the page on QuickJS (raea-runtime-js's portable engine) in place of JavaScriptCore # the page on QuickJS (raea-runtime-js's portable engine) in place of JavaScriptCore
portable = ["raea-runtime-js/portable"] portable = ["raea-runtime-js/portable"]
# raea's window on screen (--window: the desktop app, docs/app.feature AP5/AP6); the benches and tests stay headless
window = ["bevy/bevy_winit", "dep:raea-runtime-plugins", "raea-page-window/window"]
[dependencies] [dependencies]
# the window as an image the UI camera draws, picking's pointer input, the remote protocol, and every image format the # the window as an image the UI camera draws, picking's pointer input, the remote protocol, and every image format the
@@ -26,6 +28,8 @@ raea-runtime-js = { path = "../../../runtime/js" }
# the page's accessibility records # the page's accessibility records
raea-sys-a11y = { path = "../../../systems/a11y" } raea-sys-a11y = { path = "../../../systems/a11y" }
raea-page = { path = ".." } raea-page = { path = ".." }
# the desktop window: --chrome and the native calls (clipboard, links, notifications, the dock badge, raea:// links)
raea-page-window = { path = "../window" }
raea-sys-page = { path = "../../../systems/page" } raea-sys-page = { path = "../../../systems/page" }
raea-sys-fonts = { path = "../../../systems/fonts" } raea-sys-fonts = { path = "../../../systems/fonts" }
raea-runtime-dom = { path = "../../../runtime/dom" } raea-runtime-dom = { path = "../../../runtime/dom" }
@@ -38,22 +42,14 @@ blitz-dom = { version = "=0.3.0-beta.4", default-features = false }
stylo = "=0.22.0" stylo = "=0.22.0"
image = { version = "0.25", default-features = false, features = ["png"] } image = { version = "0.25", default-features = false, features = ["png"] }
serde_json = "1" serde_json = "1"
# the live stage (src/stage.rs): raea-runtime-live, with raea-runtime-react's features turned on here (the legacy app's), on # the live stage: <img data-raea-stage> (raea-page-stage)
# the shared device Bevy renders on here (raea-runtime-view's render_creation) raea-page-stage = { path = "../stage" }
raea-runtime-react = { path = "../../../runtime/react", default-features = false, features = ["h264", "av1", "scripts", "modules", "network"] } # the window build turns bevy_winit on for every Bevy app in the process; the stage's engine is told to leave it out (main.rs)
# and its sound's <Seedling> samples raea-runtime-plugins = { path = "../../../runtime/plugins", optional = true }
raea-runtime-sound = { path = "../../../runtime/sound", features = ["seedling"] }
raea-runtime-live = { path = "../../../runtime/live" }
# its stage's bakes find the bundle's functions (raea-runtime-bake's modules, as raea-runtime-react's were)
raea-runtime-bake = { path = "../../../runtime/bake", features = ["modules"] }
raea-gpu-device = { path = "../../../gpu/device" }
raea-runtime-view = { path = "../../../runtime/view" } raea-runtime-view = { path = "../../../runtime/view" }
wgpu = "=30.0.1"
# a picked element's prop written into the game's next version
raea-sys-tweak = { path = "../../../systems/tweak" }
tiny_http = "0.12" tiny_http = "0.12"
base64 = "0.22" base64 = "0.22"
# raea-io-media is here for its feature (the platform decoders raea-page and raea-runtime-js use), not called directly # raea-io-media is here for its feature (the platform decoders raea-page and raea-runtime-js use), not called directly
[package.metadata.cargo-shear] [package.metadata.cargo-shear]
ignored = ["raea-io-media", "raea-runtime-react", "raea-runtime-bake", "raea-runtime-sound"] ignored = ["raea-io-media"]
+17 -1
View File
@@ -5,10 +5,13 @@
//! adds [`HostPlugin`] and mounts its own (page::mount), its systems around the host's. //! adds [`HostPlugin`] and mounts its own (page::mount), its systems around the host's.
pub mod brp; pub mod brp;
/// the desktop window's chrome and native calls, in raea-page-window (kept under these names for main.rs and tests)
pub use raea_page_window::{chrome, native};
/// the live stage, in raea-page-stage
pub use raea_page_stage as stage;
pub mod inject; pub mod inject;
pub mod mcp; pub mod mcp;
pub mod page; pub mod page;
pub mod stage;
pub mod tree; pub mod tree;
use std::time::Duration; use std::time::Duration;
@@ -87,3 +90,16 @@ pub fn camera(mut commands: Commands, mut images: ResMut<Assets<Image>>, size: R
commands.insert_resource(inject::Target { image, norm, scale: 1.0, windowed: false }); commands.insert_resource(inject::Target { image, norm, scale: 1.0, windowed: false });
commands.insert_resource(UiCam(cam)); commands.insert_resource(UiCam(cam));
} }
/// On screen (raea's window, the `window` feature): the UI camera draws to the primary window at its own scale; the
/// window's pointer reaches picking through inject::window_pointer, its keys through bevy_winit as any app's.
pub fn camera_window(mut commands: Commands, mut images: ResMut<Assets<Image>>, primary: Query<Entity, With<bevy::window::PrimaryWindow>>) {
let win = primary.single().expect("raea's window has a primary window");
let target = RenderTarget::Window(bevy::window::WindowRef::Primary);
let norm = target.normalize(Some(win)).expect("the primary window normalizes");
let cam = commands.spawn((Camera2d, Camera { clear_color: ClearColorConfig::Custom(Color::BLACK), ..default() }, target)).id();
// the image is unused on screen (inject::Target), a pixel to fill the field
let image = images.add(Image::new_target_texture(1, 1, TextureFormat::Rgba8UnormSrgb, None));
commands.insert_resource(inject::Target { image, norm, scale: 1.0, windowed: true });
commands.insert_resource(UiCam(cam));
}
+45 -22
View File
@@ -1,12 +1,15 @@
//! raea-page-host: a bundle on a Blitz page in a headless Bevy app, for the benches. //! raea-page-host: a bundle on a Blitz page in a headless Bevy app, for the benches.
//! //!
//! raea-page-host BUNDLE [--css FILE[:FILE...]] [--root DIR[:DIR...]] [--size WxH] //! raea-page-host BUNDLE [--css FILE[:FILE...]] [--root DIR[:DIR...]] [--size WxH] [--window [--title T] [--chrome native|inset]]
//! //!
//! BUNDLE is built JS (an app's Blitz build). --css: the page's own CSS, laid out as Chrome lays out a page; without //! BUNDLE is built JS (an app's Blitz build). --css: the page's own CSS, laid out as Chrome lays out a page; without
//! it, bevy_ui's kinds. --root: where the page's own-origin fetches are read from (RAEA_PAGE_ROOT). --size: the //! it, bevy_ui's kinds. --root: where the page's own-origin fetches are read from (RAEA_PAGE_ROOT). --size: the
//! window, default 1440x900. RAEA_PAGE_BRP_PORT (default: a free one), RAEA_PAGE_MCP_PORT (default 7477; 0: none), //! window, default 1440x900. RAEA_PAGE_BRP_PORT (default: a free one), RAEA_PAGE_MCP_PORT (default 7477; 0: none),
//! RAEA_PAGE_PICK=0: the page's pointers and keys dispatched by the host (page::input) instead of through raea-page's //! RAEA_PAGE_PICK=0: the page's pointers and keys dispatched by the host (page::input) instead of through raea-page's
//! picking route, the default. The page's `<img data-raea-stage>` plays a composition live (src/stage.rs). //! picking route, the default. The page's `<img data-raea-stage>` plays a composition live (raea-page-stage).
//! --chrome inset: the page under a transparent title bar, its title area moving the window (raea-page-window).
//! --window (built with the `window` feature): on screen, a window of its own that closes the app (raea's desktop app;
//! RAEA_PAGE_HOST sends the page's /host/* to the feed's host: raea-page-net).
use std::time::Duration; use std::time::Duration;
@@ -14,18 +17,23 @@ use bevy::app::ScheduleRunnerPlugin;
use bevy::log::{Level, LogPlugin}; use bevy::log::{Level, LogPlugin};
use bevy::prelude::*; use bevy::prelude::*;
use bevy::render::pipelined_rendering::PipelinedRenderingPlugin; use bevy::render::pipelined_rendering::PipelinedRenderingPlugin;
use bevy::window::{ExitCondition, WindowResolution}; use bevy::window::ExitCondition;
use raea_page_host::chrome::{self, Chrome};
use raea_page_host::{HostPlugin, brp, camera, mcp, page, stage, tree}; use raea_page_host::{HostPlugin, brp, camera, mcp, page, stage, tree};
struct Args { struct Args {
bundle: String, bundle: String,
css: Option<Vec<String>>, css: Option<Vec<String>>,
size: UVec2, size: UVec2,
window: bool,
title: String,
chrome: Chrome,
} }
fn args() -> Result<Args, String> { fn args() -> Result<Args, String> {
let mut it = std::env::args().skip(1); let mut it = std::env::args().skip(1);
let (mut bundle, mut css, mut size) = (None, None, UVec2::new(1440, 900)); let (mut bundle, mut css, mut size, mut window, mut title) = (None, None, UVec2::new(1440, 900), false, "raea".to_string());
let mut chrome = Chrome::default();
while let Some(a) = it.next() { while let Some(a) = it.next() {
let mut val = || it.next().ok_or(format!("{a} needs a value")); let mut val = || it.next().ok_or(format!("{a} needs a value"));
match a.as_str() { match a.as_str() {
@@ -37,12 +45,16 @@ fn args() -> Result<Args, String> {
let (w, h) = v.split_once('x').ok_or(format!("--size {v}: WxH"))?; let (w, h) = v.split_once('x').ok_or(format!("--size {v}: WxH"))?;
size = UVec2::new(w.trim().parse().map_err(|_| format!("--size {v}"))?, h.trim().parse().map_err(|_| format!("--size {v}"))?); size = UVec2::new(w.trim().parse().map_err(|_| format!("--size {v}"))?, h.trim().parse().map_err(|_| format!("--size {v}"))?);
} }
"--window" if cfg!(feature = "window") => window = true,
"--window" => return Err("--window: this build has no window (build with --features window)".into()),
"--title" => title = val()?,
"--chrome" => chrome = Chrome::parse(&val()?)?,
s if s.starts_with("--") => return Err(format!("no option {s}")), s if s.starts_with("--") => return Err(format!("no option {s}")),
s => bundle = Some(s.to_string()), s => bundle = Some(s.to_string()),
} }
} }
let bundle = bundle.ok_or("usage: raea-page-host BUNDLE [--css FILE[:FILE]] [--root DIR[:DIR]] [--size WxH]")?; let bundle = bundle.ok_or("usage: raea-page-host BUNDLE [--css FILE[:FILE]] [--root DIR[:DIR]] [--size WxH]")?;
Ok(Args { bundle, css, size }) Ok(Args { bundle, css, size, window, title, chrome })
} }
fn main() { fn main() {
@@ -54,6 +66,10 @@ fn main() {
eprintln!("raea-page-host: {}: {e}", a.bundle); eprintln!("raea-page-host: {}: {e}", a.bundle);
std::process::exit(1); std::process::exit(1);
}); });
// with the window feature, bevy_winit is in every Bevy app this process makes: the stage's live engine (raea-render's
// Engine, on its own thread) would make a second event loop and panic, so it leaves WinitPlugin out
#[cfg(feature = "window")]
raea_runtime_plugins::register(raea_runtime_plugins::Registered { name: "raea-page-host window", install: |_| {}, group: Some(|b| b.disable::<bevy::winit::WinitPlugin>()), on_demand: false });
let picking = !std::env::var("RAEA_PAGE_PICK").is_ok_and(|v| v == "0"); let picking = !std::env::var("RAEA_PAGE_PICK").is_ok_and(|v| v == "0");
mcp::serve(mcp::port(), mcp::Server { name: "raea-page-host".into(), instructions: "A raea page. Drive it with input, read it with ui; brp reaches the whole ECS (Bevy Remote Protocol).".into(), prefix: "page".into() }); mcp::serve(mcp::port(), mcp::Server { name: "raea-page-host".into(), instructions: "A raea page. Drive it with input, read it with ui; brp reaches the whole ECS (Bevy Remote Protocol).".into(), prefix: "page".into() });
@@ -61,37 +77,44 @@ fn main() {
app.add_plugins( app.add_plugins(
DefaultPlugins DefaultPlugins
.set(WindowPlugin { .set(WindowPlugin {
primary_window: Some(Window { title: "raea".into(), resolution: WindowResolution::new(a.size.x, a.size.y), ..default() }), primary_window: Some(a.chrome.window(&a.title, a.size)),
exit_condition: ExitCondition::DontExit, // on screen, closing the window ends the app; headless, nothing closes it but the process
close_when_requested: false, exit_condition: if a.window { ExitCondition::OnPrimaryClosed } else { ExitCondition::DontExit },
close_when_requested: a.window,
..default() ..default()
}) })
.set(LogPlugin { level: Level::WARN, ..default() }) .set(LogPlugin { level: Level::WARN, ..default() })
// the shared device (raea_gpu_device), so a game on the stage (src/stage.rs), drawn there by the live engine, is a // the shared device (raea_gpu_device), so a game on the stage (raea-page-stage), drawn there by the live engine, is a
// texture this renderer copies with no trip across devices (RAEA_SHARED_DEVICE=0: Bevy's own, no stage) // texture this renderer copies with no trip across devices (RAEA_SHARED_DEVICE=0: Bevy's own, no stage)
.set(bevy::render::RenderPlugin { render_creation: raea_runtime_view::render_creation(), ..default() }) .set(bevy::render::RenderPlugin { render_creation: raea_runtime_view::render_creation(), ..default() })
// each update draws its own frame: the frame `ui` reports is the one rendered // each update draws its own frame: the frame `ui` reports is the one rendered
.disable::<PipelinedRenderingPlugin>(), .disable::<PipelinedRenderingPlugin>(),
); );
if !app.is_plugin_added::<ScheduleRunnerPlugin>() { // on screen, bevy_winit's event loop is the runner (a ScheduleRunner here replaced it: no window, 11-04)
if !a.window && !app.is_plugin_added::<ScheduleRunnerPlugin>() {
app.add_plugins(ScheduleRunnerPlugin::run_loop(Duration::from_secs_f64(1.0 / 60.0))); app.add_plugins(ScheduleRunnerPlugin::run_loop(Duration::from_secs_f64(1.0 / 60.0)));
} }
app.add_plugins(HostPlugin { size: a.size, double_click: Duration::from_millis(500), picking }) app.add_plugins(HostPlugin { size: a.size, double_click: Duration::from_millis(500), picking })
.add_plugins(brp::plugins(brp::port(), |r| r)) .add_plugins(brp::plugins(brp::port(), |r| r))
.add_plugins(stage::StagePlugin); .add_plugins(stage::StagePlugin)
// the clipboard, links, notifications, the dock badge, raea:// links and the chrome (raea-page-window)
.add_plugins(raea_page_window::DesktopPlugin { chrome: a.chrome, live: a.window });
raea_page_host::page_plugins(&mut app, picking); raea_page_host::page_plugins(&mut app, picking);
let (css, size) = (a.css, a.size); let (css, size) = (a.css, a.size);
app.add_systems( let preamble = vec![a.chrome.preamble()];
Startup, let mount = move |world: &mut World| {
(camera, move |world: &mut World| { chrome::install(world);
let m = page::Mount { code: code.clone(), preamble: vec![], css: css.clone(), styles: None, picking, size }; let m = page::Mount { code: code.clone(), preamble: preamble.clone(), css: css.clone(), styles: None, picking, size };
if let Err(e) = page::mount(world, m) { if let Err(e) = page::mount(world, m) {
eprintln!("raea-page-host: {e}"); eprintln!("raea-page-host: {e}");
std::process::exit(1); std::process::exit(1);
} }
}) };
.chain(), if a.window {
); app.add_systems(Startup, (raea_page_host::camera_window, mount).chain());
} else {
app.add_systems(Startup, (camera, mount).chain());
}
if picking { if picking {
app.add_systems(PreUpdate, (page::read_input, page::frame_input, page::size).chain().before(bevy::picking::PickingSystems::ProcessInput)) app.add_systems(PreUpdate, (page::read_input, page::frame_input, page::size).chain().before(bevy::picking::PickingSystems::ProcessInput))
.add_systems(Update, (page::step_dropping_asks, page::show).chain()); .add_systems(Update, (page::step_dropping_asks, page::show).chain());
+5
View File
@@ -68,6 +68,7 @@ pub fn mount(world: &mut World, m: Mount) -> Result<Entity, String> {
} }
} }
world.insert_resource(HostPage(page)); world.insert_resource(HostPage(page));
world.insert_resource(raea_page_stage::StagePage(page));
let shows = world.spawn((Shows, Node { position_type: PositionType::Absolute, width: percent(100), height: percent(100), ..default() }, UiTargetCamera(cam))).id(); let shows = world.spawn((Shows, Node { position_type: PositionType::Absolute, width: percent(100), height: percent(100), ..default() }, UiTargetCamera(cam))).id();
if m.picking { if m.picking {
// the node itself isn't a hit (bevy_ui's backend would report it above the page's twins, and nothing would // the node itself isn't a hit (bevy_ui's backend would report it above the page's twins, and nothing would
@@ -253,6 +254,10 @@ pub fn tree(page: Res<HostPage>, roots: NonSend<Roots>, docs: NonSend<Docs>, win
n["state"] = json!(state); n["state"] = json!(state);
if let Some(t) = s("data-text") { if let Some(t) = s("data-text") {
n["text"] = json!(t); n["text"] = json!(t);
} else if p.get("contentEditable").or(p.get("contenteditable")).is_some_and(|v| *v != json!(false) && *v != "false") {
// a contenteditable's text, as Chrome's textContent has it (an editor's document isn't in its props)
let node = roots.0.iter().find(|r| r.page == page.0).and_then(|r| r.nodes.by_id.get(&e.id)).and_then(|&n| docs.0.get(&page.0)?.get_node(n));
n["text"] = json!(node.map(|d| d.text_content()).unwrap_or_default());
} }
if let Some([top, max]) = e.scroll { if let Some([top, max]) = e.scroll {
n["scroll"] = json!({"top": r1(top), "max": r1(max)}); n["scroll"] = json!({"top": r1(top), "max": r1(max)});
+1
View File
@@ -20,6 +20,7 @@ pub struct PagePlugin;
impl Plugin for PagePlugin { impl Plugin for PagePlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
raea_runtime_dom::computed::register(); raea_runtime_dom::computed::register();
raea_runtime_edit::register();
app.add_plugins(( app.add_plugins((
raea_sys_page::PaintPlugin, raea_sys_page::PaintPlugin,
raea_runtime_twins::bridge::BridgePlugin::<raea_runtime_dom::host::Roots>::default(), raea_runtime_twins::bridge::BridgePlugin::<raea_runtime_dom::host::Roots>::default(),
+31
View File
@@ -0,0 +1,31 @@
[package]
name = "raea-page-stage"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "The live stage in a raea page: a game item's composition played live in the page's <img data-raea-stage> on raea-runtime-react's live engine, its frames copied on the GPU, driven by stage.* host calls"
[dependencies]
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "tonemapping_luts", "ktx2", "zstd_rust", "bevy_picking", "ui_picking", "bevy_ui_widgets", "bevy_input_focus", "jpeg", "bevy_remote", "tga", "qoi", "tiff", "pnm", "ff", "dds", "exr", "hdr", "webp", "gif", "bmp", "ico"] }
raea-runtime-js = { path = "../../../runtime/js" }
raea-runtime-dom = { path = "../../../runtime/dom" }
raea-sys-page = { path = "../../../systems/page" }
blitz-dom = { version = "=0.3.0-beta.4", default-features = false }
serde_json = "1"
# the live engine, with raea-runtime-react's features turned on here (the legacy app's), on the shared device Bevy renders
# on (raea-runtime-view's render_creation, set by the app)
raea-runtime-live = { path = "../../../runtime/live" }
raea-runtime-react = { path = "../../../runtime/react", default-features = false, features = ["h264", "av1", "scripts", "modules", "network"] }
# and its sound's <Seedling> samples
raea-runtime-sound = { path = "../../../runtime/sound", features = ["seedling"] }
# its bakes find the bundle's functions (raea-runtime-bake's modules, as raea-runtime-react's were)
raea-runtime-bake = { path = "../../../runtime/bake", features = ["modules"] }
raea-gpu-device = { path = "../../../gpu/device" }
wgpu = "=30.0.1"
# a picked element's prop written into the game's next version
raea-sys-tweak = { path = "../../../systems/tweak" }
# here for their features (the live engine's), not called directly
[package.metadata.cargo-shear]
ignored = ["raea-runtime-react", "raea-runtime-bake", "raea-runtime-sound"]
@@ -35,7 +35,10 @@ use raea_runtime_dom::host::Roots;
use raea_sys_page::view3d::ElementImages; use raea_sys_page::view3d::ElementImages;
use serde_json::{Value, json}; use serde_json::{Value, json};
use crate::page::HostPage; /// The page the stage is in: the app inserts it with the page it mounts (raea-page-host's page::mount).
#[derive(Resource)]
pub struct StagePage(pub Entity);
/// What the page asks of the stage's thread. /// What the page asks of the stage's thread.
enum Cmd { enum Cmd {
@@ -203,7 +206,7 @@ fn fit(stage: Res<Stage>, mut images: ResMut<Assets<Image>>) {
/// The page's `<img data-raea-stage>` shows the stage's image while the stage has a picture (ElementImages: Vello draws /// The page's `<img data-raea-stage>` shows the stage's image while the stage has a picture (ElementImages: Vello draws
/// it in the element's place). /// it in the element's place).
fn bind(stage: Res<Stage>, page: Option<Res<HostPage>>, roots: Option<NonSend<Roots>>, docs: Option<NonSend<Docs>>, mut shows: ResMut<ElementImages>, mut held: Local<Option<(Entity, blitz_dom::NodeId)>>) { fn bind(stage: Res<Stage>, page: Option<Res<StagePage>>, roots: Option<NonSend<Roots>>, docs: Option<NonSend<Docs>>, mut shows: ResMut<ElementImages>, mut held: Local<Option<(Entity, blitz_dom::NodeId)>>) {
let (Some(page), Some(roots), Some(_docs)) = (page, roots, docs) else { return }; let (Some(page), Some(roots), Some(_docs)) = (page, roots, docs) else { return };
let node = stage.size().and_then(|_| { let node = stage.size().and_then(|_| {
let r = roots.0.iter().find(|r| r.page == page.0)?; let r = roots.0.iter().find(|r| r.page == page.0)?;
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "raea-page-window"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea's desktop window around a page: its chrome (--chrome inset: the page under a transparent title bar, window.drag and window.zoom) and what a Mac app does that a page can't (the clipboard, links, notifications, the dock badge, raea:// links)"
[features]
# on screen (raea-page-host's --window): AppKit's calls are made; without it they are recorded and answered
window = ["bevy/bevy_winit", "dep:objc2", "dep:objc2-app-kit", "dep:objc2-foundation", "dep:raw-window-handle", "dep:block2"]
[dependencies]
bevy = { version = "=0.20.0", default-features = false, features = ["std", "bevy_window"] }
raea-runtime-js = { path = "../../../runtime/js" }
serde_json = "1"
# --chrome inset's unified toolbar (the traffic lights centred in a 52 pt title area) and native.rs's AppKit calls
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = { version = "0.6", optional = true }
objc2-app-kit = { version = "0.3", optional = true, default-features = false, features = ["std", "NSResponder", "NSView", "NSWindow", "NSToolbar"] }
objc2-foundation = { version = "0.3", optional = true, default-features = false, features = ["std", "NSString"] }
raw-window-handle = { version = "0.6", optional = true }
# completion handlers for notifications
block2 = { version = "0.6", optional = true }
+119
View File
@@ -0,0 +1,119 @@
//! The window's own chrome (--chrome inset, the desktop app): macOS's title bar made transparent with the page drawn
//! under it, its traffic lights kept, and what a title bar does left to the page. The page knows from
//! `globalThis.__raea_window` ({chrome, lights}: the lights' box in points, for the page to leave room for) and asks
//! through two host calls: `window.drag` (a press on the page's title area moves the window, as winit's drag_window
//! does from that press) and `window.zoom` (a double-click there zooms, as a native title bar's does).
use bevy::prelude::*;
use bevy::window::PrimaryWindow;
use raea_runtime_js::HostCalls;
use serde_json::json;
/// How the window's frame is drawn.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Chrome {
/// the system's title bar above the page
#[default]
Native,
/// the page fills the window, under a transparent title bar with only the traffic lights
Inset,
}
impl Chrome {
pub fn parse(s: &str) -> Result<Self, String> {
match s {
"native" => Ok(Self::Native),
"inset" => Ok(Self::Inset),
_ => Err(format!("--chrome {s}: native or inset")),
}
}
/// The primary window, titled and sized, with this chrome's title bar.
pub fn window(self, title: &str, size: UVec2) -> Window {
let inset = self == Self::Inset;
let resolution = bevy::window::WindowResolution::new(size.x, size.y);
Window { title: title.into(), resolution, titlebar_transparent: inset, titlebar_show_title: !inset, fullsize_content_view: inset, ..default() }
}
/// JS run before the page's bundle: what the page reads to draw its own title area.
pub fn preamble(self) -> String {
// the traffic lights under the empty unified toolbar (toolbar, below): three 14 pt buttons from x 20, 6 pt
// apart, centred in the 52 pt title area; elsewhere (no toolbar) AppKit's standard 28 pt bar's, from x 7
let lights = if cfg!(all(target_os = "macos", feature = "window")) {
json!({ "x": 20, "y": 19, "w": 54, "h": 14 })
} else {
json!({ "x": 7, "y": 6, "w": 54, "h": 14 })
};
let bar = if cfg!(all(target_os = "macos", feature = "window")) { 52 } else { 28 };
let v = match self {
Self::Native => json!({ "chrome": "native" }),
Self::Inset => json!({ "chrome": "inset", "lights": lights, "bar": bar }),
};
format!("globalThis.__raea_window = {v};")
}
}
/// The primary window, once winit has made it, given an empty unified toolbar (macOS): AppKit then draws a 52 pt title
/// area with the traffic lights centred in it, as in an app with a toolbar, under the page (inset chrome only).
#[cfg(all(target_os = "macos", feature = "window"))]
pub fn toolbar(_main: bevy::ecs::system::NonSendMarker, mut done: Local<bool>, chrome: Res<ChromeIs>) {
use objc2::MainThreadMarker;
use objc2_app_kit::{NSToolbar, NSView, NSWindowToolbarStyle};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
if *done || chrome.0 != Chrome::Inset {
return;
}
let Some(mtm) = MainThreadMarker::new() else { return };
bevy::winit::WINIT_WINDOWS.with_borrow(|ww| {
let Some(w) = ww.windows.values().next() else { return };
let Ok(handle) = w.window_handle() else { return };
let RawWindowHandle::AppKit(h) = handle.as_raw() else { return };
// SAFETY: winit's handle names its window's live content view, on this (the main) thread
let view: &NSView = unsafe { h.ns_view.cast().as_ref() };
let Some(win) = view.window() else { return };
let tb = NSToolbar::new(mtm);
win.setToolbar(Some(&tb));
win.setToolbarStyle(NSWindowToolbarStyle::Unified);
*done = true;
});
}
/// The chrome the window was opened with.
#[derive(Resource, Clone, Copy)]
pub struct ChromeIs(pub Chrome);
/// `window.drag` and `window.zoom`, on the primary window.
pub fn install(world: &mut World) {
world.init_resource::<HostCalls>();
world
.resource_mut::<HostCalls>()
.on("window.drag", |w, _args, answer| {
let mut q = w.query_filtered::<&mut Window, With<PrimaryWindow>>();
match q.single_mut(w) {
Ok(mut win) => {
win.start_drag_move();
answer.ok(json!(true))
}
Err(_) => answer.err("no window"),
}
})
.on("window.zoom", |w, _args, answer| {
let zoomed = {
let mut z = w.get_resource_or_insert_with(|| Zoomed(false));
z.0 = !z.0;
z.0
};
let mut q = w.query_filtered::<&mut Window, With<PrimaryWindow>>();
match q.single_mut(w) {
Ok(mut win) => {
win.set_maximized(zoomed);
answer.ok(json!(zoomed))
}
Err(_) => answer.err("no window"),
}
});
}
/// Whether `window.zoom` last zoomed the window (AppKit's zoom toggles; Bevy keeps no maximized state to read).
#[derive(Resource)]
struct Zoomed(bool);
+25
View File
@@ -0,0 +1,25 @@
//! raea's desktop window around a page (raea-page-host --window, the window raea.app runs): its chrome (chrome.rs) and
//! the native calls a page makes through host calls (native.rs).
pub mod chrome;
pub mod native;
use bevy::prelude::*;
/// The window's side of the app: the native calls (live only on screen, else recorded), the chrome it was opened with
/// and, on a Mac window with --chrome inset, its unified toolbar. `window.drag` and `window.zoom` are installed with
/// the page (chrome::install, at mount).
pub struct DesktopPlugin {
pub chrome: chrome::Chrome,
pub live: bool,
}
impl Plugin for DesktopPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(native::NativePlugin { live: self.live }).insert_resource(chrome::ChromeIs(self.chrome));
#[cfg(all(target_os = "macos", feature = "window"))]
if self.live {
app.add_systems(Update, chrome::toolbar);
}
}
}
+380
View File
@@ -0,0 +1,380 @@
//! What a Mac app does that a page can't (docs/onboarding.feature OB-N): the clipboard, links opened in the browser,
//! notifications, the dock badge, and raea:// links coming back to the app. The page asks through host calls:
//!
//! clipboard.write {text} clipboard.read -> text
//! app.open {url} an http(s) or mailto link, in the person's browser
//! notify {title, body} a macOS notification (asked for once, the first time: notify.permission)
//! notify.permission -> bool macOS's prompt, or its answer if already given
//! dock.badge {text} the dock icon's badge ("" clears it)
//! app.urls -> string[] raea:// links opened since the last ask, the app brought to the front for each
//! native.log -> {...} what was done, for tests
//!
//! Live only on screen (--window) and without RAEA_NO_OPEN=1: otherwise every call is recorded and answered as if done,
//! so headless runs never touch the person's clipboard, browser or notifications. Notifications and raea:// links need
//! the app's identity: the window running as raea.app's own process (tools/raea-app/launch.sh execs it from
//! Contents/MacOS); elsewhere notify answers an error that says so.
//! AppKit is called on the main thread: the calls queue here and `drain` (a NonSend system) runs them.
use std::sync::Mutex;
use bevy::ecs::system::NonSendMarker;
use bevy::prelude::*;
use raea_runtime_js::calls::{Answer, HostCalls};
use serde_json::{Value, json};
/// Whether calls reach macOS, or are only recorded.
#[derive(Resource, Clone, Copy)]
pub struct Live(pub bool);
/// What was done, live or recorded: read by native.log.
#[derive(Default)]
struct Log {
clipboard: String,
opened: Vec<String>,
notified: Vec<Value>,
badge: String,
urls: Vec<String>,
}
static LOG: Mutex<Option<Log>> = Mutex::new(None);
/// raea:// links that arrived and the page hasn't read yet (filled by the Apple event handler, on the main thread).
static URLS: Mutex<Vec<String>> = Mutex::new(Vec::new());
fn log<T>(f: impl FnOnce(&mut Log) -> T) -> T {
f(LOG.lock().unwrap().get_or_insert_with(Log::default))
}
/// A call waiting for the main thread.
struct Job(String, Value, Answer);
#[derive(Resource, Default)]
struct Queue(Mutex<Vec<Job>>);
/// The calls, live or recorded. Call once, after HostCalls exists.
pub struct NativePlugin {
pub live: bool,
}
impl Plugin for NativePlugin {
fn build(&self, app: &mut App) {
let live = self.live && std::env::var("RAEA_NO_OPEN").as_deref() != Ok("1");
app.insert_resource(Live(live)).init_resource::<Queue>().init_resource::<HostCalls>().add_systems(Startup, (calls, start)).add_systems(Update, drain);
}
}
fn calls(mut calls: ResMut<HostCalls>) {
for name in ["clipboard.write", "clipboard.read", "app.open", "notify", "notify.permission", "dock.badge", "app.urls", "native.log"] {
calls.on(name, move |w, args, answer| w.resource::<Queue>().0.lock().unwrap().push(Job(name.to_string(), args, answer)));
}
}
/// On screen: raea:// links are handed to the app from here on.
fn start(live: Res<Live>, _main: NonSendMarker) {
if live.0 {
mac::listen_for_urls();
}
}
fn drain(world: &mut World) {
let jobs = std::mem::take(&mut *world.resource::<Queue>().0.lock().unwrap());
if jobs.is_empty() {
return;
}
let live = world.resource::<Live>().0;
for Job(name, args, answer) in jobs {
run(live, &name, &args, answer);
}
}
// NonSend: AppKit wants its main thread. An exclusive system with this marker would be enough; drain takes &mut World,
// which Bevy's executors already run on the main thread.
fn text(a: &Value, k: &str) -> String {
a.get(k).and_then(Value::as_str).unwrap_or_default().to_string()
}
fn run(live: bool, name: &str, a: &Value, answer: Answer) {
match name {
"clipboard.write" => {
let t = text(a, "text");
if live {
mac::clipboard_write(&t);
}
log(|l| l.clipboard = t);
answer.ok(json!(true))
}
"clipboard.read" => answer.ok(json!(if live { mac::clipboard_read() } else { log(|l| l.clipboard.clone()) })),
"app.open" => {
let url = text(a, "url");
if !(url.starts_with("https://") || url.starts_with("http://") || url.starts_with("mailto:")) {
return answer.err(format!("app.open: {url:?} isn't an http(s) or mailto link"));
}
if live {
mac::open(&url);
}
log(|l| l.opened.push(url));
answer.ok(json!(true))
}
"notify" => {
let (title, body) = (text(a, "title"), text(a, "body"));
if live {
if let Err(e) = mac::notify(&title, &body) {
return answer.err(e);
}
}
log(|l| l.notified.push(json!({"title": title, "body": body})));
answer.ok(json!(true))
}
"notify.permission" => {
if live {
mac::ask_permission(answer)
} else {
answer.ok(json!(true))
}
}
"dock.badge" => {
let t = text(a, "text");
if live {
mac::badge(&t);
}
log(|l| l.badge = t);
answer.ok(json!(true))
}
"app.urls" => {
// a test hands the app a link with {push: url} when nothing is live (a raea:// link opened from outside)
if !live && let Some(u) = a.get("push").and_then(Value::as_str) {
URLS.lock().unwrap().push(u.to_string());
}
let urls = std::mem::take(&mut *URLS.lock().unwrap());
log(|l| l.urls.extend(urls.iter().cloned()));
answer.ok(json!(urls))
}
"native.log" => answer.ok(log(|l| json!({"live": live, "clipboard": l.clipboard, "opened": l.opened, "notified": l.notified, "badge": l.badge, "urls": l.urls}))),
_ => answer.err(format!("no native call {name}")),
}
}
#[cfg(all(target_os = "macos", feature = "window"))]
mod mac {
use super::{Answer, URLS};
use block2::RcBlock;
use objc2::rc::Retained;
use objc2::runtime::{AnyClass, AnyObject, Bool, NSObject};
use objc2::{ClassType, define_class, msg_send};
use objc2_foundation::NSString;
use serde_json::json;
use std::ffi::CString;
use std::sync::Mutex;
#[link(name = "UserNotifications", kind = "framework")]
unsafe extern "C" {}
#[link(name = "AppKit", kind = "framework")]
unsafe extern "C" {}
fn class(name: &str) -> Option<&'static AnyClass> {
AnyClass::get(&CString::new(name).ok()?)
}
fn rust(s: *mut AnyObject) -> String {
if s.is_null() {
return String::new();
}
let p: *const std::ffi::c_char = unsafe { msg_send![s, UTF8String] };
if p.is_null() { String::new() } else { unsafe { std::ffi::CStr::from_ptr(p) }.to_string_lossy().into_owned() }
}
fn app() -> *mut AnyObject {
unsafe { msg_send![class("NSApplication").unwrap(), sharedApplication] }
}
/// NSPasteboardTypeString's value
const PLAIN: &str = "public.utf8-plain-text";
/// The system clipboard, or (tests) a private pasteboard by name, which never touches the person's clipboard.
fn pasteboard(name: Option<&str>) -> *mut AnyObject {
let c = class("NSPasteboard").unwrap();
match name {
Some(n) => unsafe { msg_send![c, pasteboardWithName: &*NSString::from_str(n)] },
None => unsafe { msg_send![c, generalPasteboard] },
}
}
pub fn clipboard_write(t: &str) {
write_to(None, t)
}
pub fn clipboard_read() -> String {
read_from(None)
}
pub(super) fn write_to(name: Option<&str>, t: &str) {
unsafe {
let pb = pasteboard(name);
let _: isize = msg_send![pb, clearContents];
let _: Bool = msg_send![pb, setString: &*NSString::from_str(t), forType: &*NSString::from_str(PLAIN)];
}
}
pub(super) fn read_from(name: Option<&str>) -> String {
unsafe {
let pb = pasteboard(name);
rust(msg_send![pb, stringForType: &*NSString::from_str(PLAIN)])
}
}
pub fn open(url: &str) {
unsafe {
let u: *mut AnyObject = msg_send![class("NSURL").unwrap(), URLWithString: &*NSString::from_str(url)];
if u.is_null() {
return;
}
let ws: *mut AnyObject = msg_send![class("NSWorkspace").unwrap(), sharedWorkspace];
let _: Bool = msg_send![ws, openURL: u];
}
}
pub fn badge(t: &str) {
unsafe {
let tile: *mut AnyObject = msg_send![app(), dockTile];
let label: *const AnyObject = if t.is_empty() { std::ptr::null() } else { Retained::into_raw(NSString::from_str(t)).cast::<AnyObject>() };
let _: () = msg_send![tile, setBadgeLabel: label];
}
}
/// UNUserNotificationCenter refuses a process with no bundle identifier (it raises), so that is checked first.
fn center() -> Result<*mut AnyObject, String> {
unsafe {
let bundle: *mut AnyObject = msg_send![class("NSBundle").unwrap(), mainBundle];
let id: *mut AnyObject = msg_send![bundle, bundleIdentifier];
if id.is_null() {
return Err("notifications need raea.app (this window isn't running as the app)".into());
}
let c = class("UNUserNotificationCenter").ok_or("UserNotifications isn't loaded")?;
Ok(msg_send![c, currentNotificationCenter])
}
}
pub fn ask_permission(answer: Answer) {
let center = match center() {
Ok(c) => c,
Err(e) => return answer.err(e),
};
let slot = Mutex::new(Some(answer));
let done = RcBlock::new(move |granted: Bool, _err: *mut AnyObject| {
if let Some(a) = slot.lock().unwrap().take() {
a.ok(json!(granted.as_bool()))
}
});
// alert | sound | badge
let opts: usize = (1 << 2) | (1 << 1) | 1;
unsafe {
let _: () = msg_send![center, requestAuthorizationWithOptions: opts, completionHandler: &*done];
}
}
pub fn notify(title: &str, body: &str) -> Result<(), String> {
let center = center()?;
unsafe {
let content: Retained<AnyObject> = msg_send![class("UNMutableNotificationContent").ok_or("no UNMutableNotificationContent")?, new];
let _: () = msg_send![&*content, setTitle: &*NSString::from_str(title)];
let _: () = msg_send![&*content, setBody: &*NSString::from_str(body)];
let id = NSString::from_str(&format!("raea-{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()));
let none: *const AnyObject = std::ptr::null();
let req: *mut AnyObject = msg_send![class("UNNotificationRequest").unwrap(), requestWithIdentifier: &*id, content: &*content, trigger: none];
let _: () = msg_send![center, addNotificationRequest: req, withCompletionHandler: none];
}
Ok(())
}
define_class!(
// AppKit's Apple event handler for kAEGetURL: a raea:// link opened anywhere on the Mac
#[unsafe(super(NSObject))]
#[name = "RaeaUrlHandler"]
struct UrlHandler;
impl UrlHandler {
#[unsafe(method(handle:reply:))]
fn handle(&self, event: *mut AnyObject, _reply: *mut AnyObject) {
// keyDirectObject '----'
let desc: *mut AnyObject = unsafe { msg_send![event, paramDescriptorForKeyword: 0x2d2d2d2du32] };
let url = if desc.is_null() { String::new() } else { rust(unsafe { msg_send![desc, stringValue] }) };
if url.starts_with("raea://") {
URLS.lock().unwrap().push(url);
}
let _: () = unsafe { msg_send![app(), activateIgnoringOtherApps: Bool::YES] };
}
}
);
/// A kAEGetURL event carrying `url`, handed to the handler as AppKit would (tests).
#[cfg(test)]
pub(super) fn deliver(url: &str) {
unsafe {
let cls = class("NSAppleEventDescriptor").unwrap();
let none: *const AnyObject = std::ptr::null();
let gurl: u32 = 0x4755_524c;
let event: *mut AnyObject = msg_send![cls, appleEventWithEventClass: gurl, eventID: gurl, targetDescriptor: none, returnID: -1i16, transactionID: 0i32];
let s: *mut AnyObject = msg_send![cls, descriptorWithString: &*NSString::from_str(url)];
let _: () = msg_send![event, setParamDescriptor: s, forKeyword: 0x2d2d2d2du32];
let h: Retained<UrlHandler> = msg_send![UrlHandler::class(), new];
let _: () = msg_send![&*h, handle: event, reply: none];
}
}
pub fn listen_for_urls() {
unsafe {
// kept for the app's life: the event manager doesn't retain its handler
let handler: *mut AnyObject = Retained::<UrlHandler>::into_raw(msg_send![UrlHandler::class(), new]) as *mut AnyObject;
let mgr: *mut AnyObject = msg_send![class("NSAppleEventManager").unwrap(), sharedAppleEventManager];
// kInternetEventClass and kAEGetURL are both 'GURL'; the handler lives as long as the app
let gurl: u32 = 0x4755_524c;
let _: () = msg_send![mgr, setEventHandler: handler, andSelector: objc2::sel!(handle:reply:), forEventClass: gurl, andEventID: gurl];
}
}
}
/// Without a window (the benches, CI, other platforms): nothing reaches the system; Live is false, so these never run.
#[cfg(not(all(target_os = "macos", feature = "window")))]
mod mac {
use super::Answer;
pub fn clipboard_write(_: &str) {}
pub fn clipboard_read() -> String {
String::new()
}
pub fn open(_: &str) {}
pub fn badge(_: &str) {}
pub fn notify(_: &str, _: &str) -> Result<(), String> {
Err("notifications need raea's window on a Mac".into())
}
pub fn ask_permission(a: Answer) {
a.err("notifications need raea's window on a Mac")
}
pub fn listen_for_urls() {}
}
#[cfg(all(test, target_os = "macos", feature = "window"))]
mod tests {
use super::{URLS, mac};
#[test]
fn pasteboard_round_trip_on_a_private_board() {
let name = format!("io.raea.test.{}", std::process::id());
mac::write_to(Some(&name), "RAEA-CODE-42 ✓");
assert_eq!(mac::read_from(Some(&name)), "RAEA-CODE-42 ✓");
}
#[test]
fn a_raea_link_reaches_the_queue_and_others_dont() {
mac::deliver("raea://linked?code=ABC123");
mac::deliver("https://example.com/not-ours");
let urls = std::mem::take(&mut *URLS.lock().unwrap());
assert_eq!(urls, vec!["raea://linked?code=ABC123".to_string()]);
}
#[test]
fn notifications_outside_the_app_say_why() {
let e = mac::notify("t", "b").unwrap_err();
assert!(e.contains("raea.app"), "{e}");
}
}
+6
View File
@@ -55,6 +55,9 @@ bytemuck = "1"
# the media plane: clips decode through a MediaBackend (soft everywhere, apple on Apple) # the media plane: clips decode through a MediaBackend (soft everywhere, apple on Apple)
raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"], optional = true } raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"], optional = true }
# Bevy's Solari and MetalFX's denoiser on it (the raytracing feature)
raea-render-raytrace = { path = "raytrace", optional = true }
[features] [features]
# native: everything that only exists to render on the machine itself (clips' decoders, the GPU frame path and its # native: everything that only exists to render on the machine itself (clips' decoders, the GPU frame path and its
# traces, the direct views); without it raea-render is the program format and the 3D engine, which is what a browser build needs (docs/web-export.md, milestone 1) # traces, the direct views); without it raea-render is the program format and the 3D engine, which is what a browser build needs (docs/web-export.md, milestone 1)
@@ -64,6 +67,9 @@ web = ["bevy/webgpu"]
# AV1 (dav1d decode, rav1e encode) as a media backend: on by default; an exported game's player goes without it # AV1 (dav1d decode, rav1e encode) as a media backend: on by default; an exported game's player goes without it
# (lightspeed R7: about 1 MB of code no game uses) # (lightspeed R7: about 1 MB of code no game uses)
default = ["native", "h264", "av1", "scripts", "network"] default = ["native", "h264", "av1", "scripts", "network"]
# Bevy's Solari, ray-traced lighting and its reference path tracer (docs/raytracing.feature RT3), and MetalFX's
# denoiser on it on the Mac (RT4)
raytracing = ["native", "dep:raea-render-raytrace"]
# the soft backend's H.264 (openh264): mezzanines, raea-render export's GOPs, portable video decode; an exported game's # the soft backend's H.264 (openh264): mezzanines, raea-render export's GOPs, portable video decode; an exported game's
# player goes without it and decodes video on the platform (lightspeed R7) # player goes without it and decodes video on the platform (lightspeed R7)
h264 = ["native", "raea-io-media/h264"] h264 = ["native", "raea-io-media/h264"]
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "raea-render-raytrace"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea-render's ray tracing: Bevy's Solari for a scene whose camera asks for it (RT3), and MetalFX's temporal denoiser on it on the Mac (RT4)"
[dependencies]
bevy = { version = "=0.20.0", default-features = false, features = ["std", "3d_bevy_render", "bevy_solari"] }
# the same wgpu Bevy uses (the guide pass records on its device; MetalFX runs on its Metal objects)
wgpu = "=30.0.1"
# MetalFX's temporal denoiser (wgpu 30 is on objc2-metal 0.3)
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.6"
objc2-metal = { version = "0.3.2", default-features = false, features = ["std", "MTLTexture", "MTLCommandBuffer", "MTLCommandEncoder", "MTLBlitCommandEncoder", "MTLDevice", "MTLPixelFormat", "MTLResource"] }
objc2-metal-fx = "=0.3.2"
+25
View File
@@ -0,0 +1,25 @@
//! raea-render's ray tracing (docs/raytracing.feature): Bevy's Solari for a scene whose camera asks for it (RT3,
//! solari.rs), and MetalFX's temporal denoiser on its lighting on the Mac (RT4, metalfx.rs). raea-render brings this
//! crate in under its `raytracing` feature and adds it to an engine only when the program asks.
use bevy::prelude::*;
use std::collections::HashMap;
mod solari;
#[cfg(target_os = "macos")]
mod metalfx;
pub use solari::add;
/// The program asks for Solari: a camera's SolariLighting or Pathtracer component (`prog` is raea-render's Program).
pub fn wanted(prog: &impl std::fmt::Debug) -> bool {
format!("{prog:?}").contains("bevy_solari::")
}
/// After app.finish(): MetalFX's denoiser after Solari's lighting, on the Mac; nothing elsewhere.
pub fn add_denoiser(app: &mut App) {
#[cfg(target_os = "macos")]
metalfx::add(app);
#[cfg(not(target_os = "macos"))]
let _ = app;
}
+290
View File
@@ -0,0 +1,290 @@
//! RT4 (docs/raytracing.feature): MetalFX's temporal denoiser on Solari's lighting, on the Mac. No denoiser of Bevy's
//! runs on Metal (Solari's is DLSS Ray Reconstruction, NVIDIA's), so Solari draws its few rays a pixel as noise there;
//! MTLFXTemporalDenoisedScaler (macOS 26) takes that noisy colour and the frame's guide data and gives it back clean.
//!
//! Each frame, after Solari has lit the view and before the opaque pass draws the forward meshes, a compute pass writes the guide textures MetalFX reads from Bevy's G-buffer (diffuse and specular albedo,
//! world normal, roughness); then a command buffer of its own, recorded through wgpu's Metal backend, runs the
//! denoiser on the view's colour, depth and motion and copies its output back over the colour, before the forward
//! meshes and the tonemapping. The two command buffers go to wgpu's queue in that order, after Solari's.
//!
//! Where there's no MetalFX denoiser (not macOS 26, not Metal, a device it doesn't support) the lighting draws as it
//! is and raea says so once. RAEA_SOLARI_DENOISE=0 turns it off, to see the noise.
use super::*;
use bevy::core_pipeline::core_3d::main_opaque_pass_3d;
use bevy::ecs::schedule::Schedules;
use bevy::core_pipeline::prepass::ViewPrepassTextures;
use bevy::core_pipeline::schedule::{Core3d, Core3dSystems};
use bevy::render::render_resource::TextureFormat;
use bevy::render::renderer::{RenderContext, RenderDevice, ViewQuery};
use bevy::render::view::{ExtractedView, ViewTarget};
use bevy::solari::prelude::SolariLighting;
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2::Message;
use objc2_metal::{MTLBlitCommandEncoder, MTLCommandBuffer, MTLCommandEncoder, MTLPixelFormat, MTLTexture};
use objc2_metal_fx::{MTLFXTemporalDenoisedScaler, MTLFXTemporalDenoisedScalerBase, MTLFXTemporalDenoisedScalerDescriptor};
use wgpu::hal::api::Metal;
/// After app.finish(), when Solari's plugin has put its lighting system in Core3d: the denoiser right after that system
/// and before the opaque pass, as forward-drawn meshes (a <Character>'s skin, an extended material) come after it with
/// nothing in the G-buffer, and denoising them would smear them. Bevy doesn't export Solari's system, so it's found by
/// name and ordered against by its system type set.
pub(crate) fn add(app: &mut App) {
if std::env::var("RAEA_SOLARI_DENOISE").is_ok_and(|v| v == "0") {
return;
}
let Some(r) = app.get_sub_app_mut(bevy::render::RenderApp) else { return };
let mut schedules = r.world_mut().resource_mut::<Schedules>();
let Some(core) = schedules.get_mut(Core3d) else { return };
let mut solari = None;
for (_, s, _) in core.graph().systems.iter() {
if format!("{}", s.name()).ends_with("solari_lighting") {
solari = s.default_system_sets().into_iter().next();
break;
}
}
let Some(solari) = solari else {
eprintln!("raea: <SolariLighting>: Solari's lighting isn't in the render schedule; no MetalFX denoiser");
return;
};
core.add_systems(denoise.after(solari).before(main_opaque_pass_3d).in_set(Core3dSystems::MainPass));
}
// Bevy's G-buffer (bevy_pbr deferred/functions.wesl, types.wesl) to MetalFX's guides: r = base colour (sRGB-ish, pow
// 1/2.2) and perceptual roughness as unorm4x8; b = reflectance, metallic, occlusion, clearcoat as unorm4x8; a = a 24-bit
// octahedral normal (two 12-bit halves) and flags. Specular albedo is F0 (Bevy's 0.16 reflectance² for dielectrics,
// the base colour for metals)
const DECODE_WGSL: &str = r#"
@group(0) @binding(0) var gbuf: texture_2d<u32>;
@group(0) @binding(1) var diffuse: texture_storage_2d<rgba16float, write>;
@group(0) @binding(2) var specular: texture_storage_2d<rgba16float, write>;
@group(0) @binding(3) var normal: texture_storage_2d<rgba16float, write>;
@group(0) @binding(4) var rough: texture_storage_2d<r32float, write>;
fn unorm4x8(p: u32) -> vec4<f32> {
return vec4<f32>(f32(p & 255u), f32((p >> 8u) & 255u), f32((p >> 16u) & 255u), f32(p >> 24u)) / 255.0;
}
fn octahedral(v: vec2<f32>) -> vec3<f32> {
let f = v * 2.0 - 1.0;
var n = vec3<f32>(f, 1.0 - abs(f.x) - abs(f.y));
let t = saturate(-n.z);
let w = select(vec2<f32>(t), vec2<f32>(-t), n.xy >= vec2<f32>(0.0));
n = vec3<f32>(n.xy + w, n.z);
return normalize(n);
}
@compute @workgroup_size(8, 8, 1)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let size = textureDimensions(diffuse);
if (id.x >= size.x || id.y >= size.y) { return; }
let p = vec2<i32>(id.xy);
let g = textureLoad(gbuf, p, 0);
let a = unorm4x8(g.r);
let props = unorm4x8(g.b);
let base = pow(a.rgb, vec3<f32>(2.2));
let metallic = props.y;
let f0 = mix(vec3<f32>(0.16 * props.x * props.x), base, metallic);
let n = octahedral(vec2<f32>(f32(g.a & 0xFFFu), f32((g.a >> 12u) & 0xFFFu)) / 4095.0);
textureStore(diffuse, p, vec4<f32>(base * (1.0 - metallic), 1.0));
textureStore(specular, p, vec4<f32>(f0, 1.0));
textureStore(normal, p, vec4<f32>(n, 0.0));
textureStore(rough, p, vec4<f32>(a.w, 0.0, 0.0, 0.0));
}
"#;
/// A view's denoiser and its textures, made again when the view's size changes.
struct View {
size: UVec2,
scaler: Retained<ProtocolObject<dyn MTLFXTemporalDenoisedScaler>>,
diffuse: wgpu::Texture,
specular: wgpu::Texture,
normal: wgpu::Texture,
rough: wgpu::Texture,
out: wgpu::Texture,
fresh: bool,
}
#[derive(Default)]
struct Kit {
pipeline: Option<wgpu::ComputePipeline>,
views: HashMap<Entity, View>,
off: bool,
}
// the Metal objects are only touched on the render thread, in this system
unsafe impl Send for Kit {}
unsafe impl Sync for Kit {}
fn texture(dev: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat, usage: wgpu::TextureUsages, label: &str) -> wgpu::Texture {
dev.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: size.x, height: size.y, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
}
/// A texture's MTLTexture, retained.
fn mtl(t: &wgpu::Texture) -> Option<Retained<ProtocolObject<dyn MTLTexture>>> {
unsafe { t.as_hal::<Metal>() }.map(|t| t.raw_handle().retain())
}
impl View {
fn new(dev: &wgpu::Device, size: UVec2) -> Result<View, String> {
let hal = unsafe { dev.as_hal::<Metal>() }.ok_or("the GPU isn't on Metal")?;
let device = hal.raw_device();
unsafe {
if !MTLFXTemporalDenoisedScalerDescriptor::supportsDevice(device) {
return Err("MetalFX has no denoiser for this GPU (it needs macOS 26 and Apple silicon)".into());
}
let d = MTLFXTemporalDenoisedScalerDescriptor::new();
d.setColorTextureFormat(MTLPixelFormat::RGBA16Float);
d.setDepthTextureFormat(MTLPixelFormat::Depth32Float);
d.setMotionTextureFormat(MTLPixelFormat::RG16Float);
d.setDiffuseAlbedoTextureFormat(MTLPixelFormat::RGBA16Float);
d.setSpecularAlbedoTextureFormat(MTLPixelFormat::RGBA16Float);
d.setNormalTextureFormat(MTLPixelFormat::RGBA16Float);
d.setRoughnessTextureFormat(MTLPixelFormat::R32Float);
d.setOutputTextureFormat(MTLPixelFormat::RGBA16Float);
d.setInputWidth(size.x as _);
d.setInputHeight(size.y as _);
d.setOutputWidth(size.x as _);
d.setOutputHeight(size.y as _);
d.setRequiresSynchronousInitialization(true);
let scaler = d.newTemporalDenoisedScalerWithDevice(device).ok_or("MetalFX made no denoiser")?;
drop(hal);
use wgpu::TextureUsages as U;
let guide = U::STORAGE_BINDING | U::TEXTURE_BINDING;
Ok(View {
size,
scaler,
diffuse: texture(dev, size, wgpu::TextureFormat::Rgba16Float, guide, "metalfx diffuse albedo"),
specular: texture(dev, size, wgpu::TextureFormat::Rgba16Float, guide, "metalfx specular albedo"),
normal: texture(dev, size, wgpu::TextureFormat::Rgba16Float, guide, "metalfx normal"),
rough: texture(dev, size, wgpu::TextureFormat::R32Float, guide, "metalfx roughness"),
out: texture(dev, size, wgpu::TextureFormat::Rgba16Float, guide | U::RENDER_ATTACHMENT | U::COPY_SRC, "metalfx output"),
fresh: true,
})
}
}
/// The denoiser on `cb`, then its output copied over the colour.
fn encode(&mut self, cb: &ProtocolObject<dyn MTLCommandBuffer>, color: &wgpu::Texture, depth: &wgpu::Texture, motion: &wgpu::Texture, view: &ExtractedView, reset: bool) -> Result<(), &'static str> {
let get = |t: &wgpu::Texture| mtl(t).ok_or("a texture isn't a Metal one");
let (color, depth, motion) = (get(color)?, get(depth)?, get(motion)?);
let (diffuse, specular, normal, rough, out) = (get(&self.diffuse)?, get(&self.specular)?, get(&self.normal)?, get(&self.rough)?, get(&self.out)?);
let s = &*self.scaler;
unsafe {
s.setColorTexture(Some(&color));
s.setDepthTexture(Some(&depth));
s.setMotionTexture(Some(&motion));
s.setDiffuseAlbedoTexture(Some(&diffuse));
s.setSpecularAlbedoTexture(Some(&specular));
s.setNormalTexture(Some(&normal));
s.setRoughnessTexture(Some(&rough));
s.setOutputTexture(Some(&out));
// Bevy's motion is this frame's UV minus the last's; MetalFX's points from this pixel to where it was, in
// pixels
s.setMotionVectorScaleX(-(self.size.x as f32));
s.setMotionVectorScaleY(-(self.size.y as f32));
s.setJitterOffsetX(0.0);
s.setJitterOffsetY(0.0);
s.setDepthReversed(true);
s.setShouldResetHistory(reset || self.fresh);
matrices(s, view.world_from_view.to_matrix().inverse(), view.clip_from_view);
s.encodeToCommandBuffer(cb);
let blit = cb.blitCommandEncoder().ok_or("no blit encoder")?;
blit.copyFromTexture_toTexture(&out, &color);
blit.endEncoding();
}
self.fresh = false;
Ok(())
}
}
/// worldToViewMatrix and viewToClipMatrix, simd_float4x4 properties objc2-metal-fx leaves out (no simd types in
/// objc2): sent by hand, as four float32x4 columns (an aggregate of four vectors, passed as simd_float4x4 is). Only on
/// Apple silicon, and only where the scaler has them; objc2 checks a message's types in a debug build and doesn't know
/// simd's, so a debug build leaves them out.
#[allow(unused_variables)]
fn matrices(s: &ProtocolObject<dyn MTLFXTemporalDenoisedScaler>, world_to_view: Mat4, view_to_clip: Mat4) {
#[cfg(all(target_arch = "aarch64", not(debug_assertions)))]
unsafe {
use objc2::{msg_send, sel};
use std::arch::aarch64::float32x4_t;
#[repr(C)]
#[derive(Clone, Copy)]
struct Float4x4([float32x4_t; 4]);
unsafe impl objc2::Encode for Float4x4 {
const ENCODING: objc2::Encoding = objc2::Encoding::Struct("?", &[]);
}
let m = |m: Mat4| Float4x4(m.to_cols_array_2d().map(|c| std::mem::transmute::<[f32; 4], float32x4_t>(c)));
let has: bool = msg_send![s, respondsToSelector: sel!(setWorldToViewMatrix:)];
if has {
let _: () = msg_send![s, setWorldToViewMatrix: m(world_to_view)];
let _: () = msg_send![s, setViewToClipMatrix: m(view_to_clip)];
}
}
}
fn denoise(view: ViewQuery<(&ViewTarget, &ViewPrepassTextures, &ExtractedView, &SolariLighting)>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {
if kit.off {
return;
}
let entity = view.entity();
let (target, pre, ext, solari) = view.into_inner();
let (Some(depth), Some(motion), Some(gbuf)) = (pre.depth.as_ref(), pre.motion_vectors.as_ref(), pre.deferred.as_ref()) else { return };
if target.main_texture_format() != TextureFormat::Rgba16Float {
return;
}
let color: &wgpu::Texture = target.main_texture();
let size = UVec2::new(color.width(), color.height());
let dev = device.wgpu_device().clone();
if kit.views.get(&entity).map(|v| v.size) != Some(size) {
match View::new(&dev, size) {
Ok(v) => {
kit.views.insert(entity, v);
}
Err(e) => {
kit.off = true;
eprintln!("raea: <SolariLighting>: no MetalFX denoiser ({e}); the lighting draws un-denoised (docs/raytracing.feature RT4)");
return;
}
}
}
let pipeline = kit
.pipeline
.get_or_insert_with(|| {
let module = dev.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("metalfx guides"), source: wgpu::ShaderSource::Wgsl(DECODE_WGSL.into()) });
dev.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("metalfx guides"), layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: None })
})
.clone();
let v = kit.views.get_mut(&entity).unwrap();
let views = [&v.diffuse, &v.specular, &v.normal, &v.rough].map(|t| t.create_view(&Default::default()));
let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&*gbuf.texture.default_view) }];
for (i, tv) in views.iter().enumerate() {
entries.push(wgpu::BindGroupEntry { binding: i as u32 + 1, resource: wgpu::BindingResource::TextureView(tv) });
}
let bind = dev.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("metalfx guides"), layout: &pipeline.get_bind_group_layout(0), entries: &entries });
{
let mut pass = ctx.command_encoder().begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("metalfx guides"), timestamp_writes: None });
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &bind, &[]);
pass.dispatch_workgroups(size.x.div_ceil(8), size.y.div_ceil(8), 1);
}
// a command buffer of its own (wgpu won't mix its own commands and raw ones on one encoder), after the guides'
let mut raw = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("metalfx denoise") });
let done = unsafe {
raw.as_hal_mut::<Metal, _, _>(|e| match e.and_then(|e| e.raw_command_buffer()) {
Some(cb) => v.encode(cb, color, &depth.texture.texture, &motion.texture.texture, ext, solari.reset),
None => Err("wgpu gave no Metal command buffer"),
})
};
ctx.add_command_buffer(raw.finish());
if let Err(e) = done {
kit.off = true;
eprintln!("raea: <SolariLighting>: the MetalFX denoiser stopped ({e}); the lighting draws un-denoised");
}
}
+111
View File
@@ -0,0 +1,111 @@
//! RT3 (docs/raytracing.feature): Bevy's Solari, ray-traced lighting, for a scene whose camera asks for it
//! (<SolariLighting> or <Pathtracer> in raea/3d: SolariLighting or Pathtracer under <Camera3d>). Its plugins come in
//! only then: SolariLightingPlugin makes every opaque material deferred, which would change every other scene.
//! The shared GPU device asks for every feature its adapter has (raea-gpu-device), so ray queries are on where the GPU
//! has them; where it doesn't, Solari's plugins say so and the scene draws with raster lighting.
//!
//! Solari traces a mesh only in one layout (positions, normals, UV 0, tangents, nothing else, u32 indices), so each
//! mesh gets a copy in that layout for its RaytracingMesh3d, made once per mesh. Skinned and morphed meshes (a
//! <Character>) are left raster-lit, as Solari 0.20 can't trace them (RT5).
use super::*;
use bevy::camera::CameraMainTextureUsages;
use bevy::mesh::{Indices, PrimitiveTopology, VertexAttributeValues};
use bevy::solari::pathtracer::{Pathtracer, PathtracingPlugin};
use bevy::solari::prelude::{RaytracingMesh3d, SolariLighting, SolariPlugins};
pub fn add(app: &mut App) {
app.add_plugins((SolariPlugins, PathtracingPlugin)).add_systems(PostUpdate, (cameras, meshes).before(bevy::camera::CameraUpdateSystems));
}
/// A camera or mesh already set up (or left out).
#[derive(Component)]
struct Done;
// Solari's camera needs: no MSAA and a main texture it can write to (SolariLighting's docs); Hdr, the prepasses and
// deferred come with its required components
fn cameras(mut cmd: Commands, q: Query<(Entity, Option<&CameraMainTextureUsages>), (Or<(With<SolariLighting>, With<Pathtracer>)>, Without<Done>)>) {
for (e, u) in &q {
let usages = u.map_or_else(|| CameraMainTextureUsages::default().0, |u| u.0) | bevy::render::render_resource::TextureUsages::STORAGE_BINDING;
cmd.entity(e).insert((Msaa::Off, CameraMainTextureUsages(usages), Done));
}
}
type Pending = (With<MeshMaterial3d<StandardMaterial>>, Without<RaytracingMesh3d>, Without<Done>);
fn meshes(
mut cmd: Commands,
on: Query<(), Or<(With<SolariLighting>, With<Pathtracer>)>>,
q: Query<(Entity, &Mesh3d, Has<bevy::mesh::skinning::SkinnedMesh>, Has<bevy::mesh::morph::MeshMorphWeights>), Pending>,
mut assets: ResMut<Assets<Mesh>>,
mut copies: Local<HashMap<AssetId<Mesh>, Option<Handle<Mesh>>>>,
mut said: Local<bool>,
) {
if on.is_empty() {
return;
}
for (e, m, skinned, morphed) in &q {
if skinned || morphed {
if !*said {
*said = true;
eprintln!("raea: <SolariLighting>: a skinned or morphed mesh (a <Character>) draws raster-lit; Bevy 0.20's Solari can't trace it (docs/raytracing.feature RT5)");
}
cmd.entity(e).insert(Done);
continue;
}
// each mesh's traceable form, made once: itself when it's in Solari's layout, else a copy; None when it can't
// be traced (not triangles, no normals, or its data only on the GPU)
let h = match copies.get(&m.0.id()) {
Some(h) => h.clone(),
None => {
let Some(t) = assets.get(&m.0).map(traceable) else { continue };
let h = match t {
Some(Traceable::Same) => Some(m.0.clone()),
Some(Traceable::Copy(mesh)) => Some(assets.add(mesh)),
None => None,
};
copies.insert(m.0.id(), h.clone());
h
}
};
match h {
Some(h) => cmd.entity(e).insert((RaytracingMesh3d(h), Done)),
None => cmd.entity(e).insert(Done),
};
}
}
enum Traceable {
Same,
Copy(Mesh),
}
fn traceable(src: &Mesh) -> Option<Traceable> {
if src.primitive_topology() != PrimitiveTopology::TriangleList {
return None;
}
let ids: Vec<_> = src.attributes().map(|(a, _)| a.id).collect();
let layout = [Mesh::ATTRIBUTE_POSITION.id, Mesh::ATTRIBUTE_NORMAL.id, Mesh::ATTRIBUTE_UV_0.id, Mesh::ATTRIBUTE_TANGENT.id];
if ids == layout && matches!(src.indices(), Some(Indices::U32(_))) {
return Some(Traceable::Same);
}
let pos = src.attribute(Mesh::ATTRIBUTE_POSITION)?.clone();
let n = pos.len();
let normal = src.attribute(Mesh::ATTRIBUTE_NORMAL)?.clone();
let uv = src.attribute(Mesh::ATTRIBUTE_UV_0).cloned().unwrap_or(VertexAttributeValues::Float32x2(vec![[0.0, 0.0]; n]));
let mut out = Mesh::new(PrimitiveTopology::TriangleList, bevy::asset::RenderAssetUsages::default());
out.insert_attribute(Mesh::ATTRIBUTE_POSITION, pos);
out.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normal);
out.insert_attribute(Mesh::ATTRIBUTE_UV_0, uv);
let idx: Vec<u32> = match src.indices() {
Some(Indices::U32(v)) => v.clone(),
Some(Indices::U16(v)) => v.iter().map(|&i| i as u32).collect(),
None => (0..n as u32).collect(),
};
out.insert_indices(Indices::U32(idx));
match src.attribute(Mesh::ATTRIBUTE_TANGENT) {
Some(t) => out.insert_attribute(Mesh::ATTRIBUTE_TANGENT, t.clone()),
None => out.generate_tangents().ok()?,
}
Some(Traceable::Copy(out))
}
+4
View File
@@ -40,6 +40,9 @@ pub(crate) use target::*;
mod open; mod open;
mod load; mod load;
mod output; mod output;
// RT1: each frame's motion vectors and depth, for a neural or denoising pass after the render
mod aov;
pub use aov::Aov;
// a frame's rows, the edit, the clock and the row helpers every pass reads (raea-sys-frame) // a frame's rows, the edit, the clock and the row helpers every pass reads (raea-sys-frame)
use raea_sys_frame::*; use raea_sys_frame::*;
@@ -215,6 +218,7 @@ impl Engine {
self.pre_step(); self.pre_step();
plugins::arm(self.app.world_mut()); plugins::arm(self.app.world_mut());
self.app.update(); self.app.update();
self.capture_aov(f);
} }
/// With MotionBlur, the frame before the clock's drawn first (its readback ignored): Bevy takes each mesh's, /// With MotionBlur, the frame before the clock's drawn first (its readback ignored): Bevy takes each mesh's,
+143
View File
@@ -0,0 +1,143 @@
//! RT1 (docs/raytracing.feature): each frame's motion vectors and depth, the guide data a neural or denoising pass
//! after the render needs (MLX-DLSS's run-sequence, MetalFX). Asked for with `want_aov`, before the first draw: the 3D
//! cameras then draw Bevy's depth and motion-vector prepasses (MSAA off: a multisampled prepass can't be read), and
//! each frame's first draw reads both back (`take_aov`). A redraw of the same frame keeps the first draw's: drawn
//! again, every mesh's last pose is its pose now, and its motion would read zero.
use super::*;
use bevy::core_pipeline::prepass::{DepthPrepass, MotionVectorPrepass, ViewPrepassTextures};
/// One frame's guide data at the prepass's size (the frame's, times RAEA_SS).
pub struct Aov {
pub w: u32,
pub h: u32,
/// w x h x 2, Bevy's motion vectors: this frame's UV minus the last frame's (x right, y down)
pub motion: Vec<f32>,
/// w x h, reverse Z (1 at the near plane, 0 at infinity)
pub depth: Vec<f32>,
}
/// The guide data is wanted; `frame` is the frame last read, `last` what it read.
#[derive(Resource, Default)]
pub(crate) struct AovWanted {
frame: Option<i64>,
last: Option<Aov>,
}
fn aov_prepasses(mut cmd: Commands, q: Query<Entity, (With<Camera3d>, Without<MotionVectorPrepass>)>) {
for e in &q {
cmd.entity(e).insert((DepthPrepass, MotionVectorPrepass, Msaa::Off));
}
}
// the motion texture is made without COPY_SRC (bevy_core_pipeline's prepare_core_3d_depth_textures), so it's read in
// a shader, not copied: both textures into one buffer, three floats a pixel
const AOV_WGSL: &str = r#"
@group(0) @binding(0) var depth_t: texture_depth_2d;
@group(0) @binding(1) var motion_t: texture_2d<f32>;
@group(0) @binding(2) var<storage, read_write> out: array<f32>;
@group(0) @binding(3) var<uniform> dims: vec4<u32>;
@compute @workgroup_size(8, 8, 1)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if (id.x >= dims.x || id.y >= dims.y) { return; }
let p = vec2<i32>(id.xy);
let m = textureLoad(motion_t, p, 0).xy;
let i = (id.y * dims.x + id.x) * 3u;
out[i] = m.x;
out[i + 1u] = m.y;
out[i + 2u] = textureLoad(depth_t, p, 0);
}
"#;
impl Engine {
/// Draw the guide data from now on (before the first draw: a camera's prepass is set up as it's extracted).
pub fn want_aov(&mut self) {
if self.app.world().contains_resource::<AovWanted>() {
return;
}
self.app.init_resource::<AovWanted>();
self.app.add_systems(Update, aov_prepasses);
}
/// Frame f's guide data, read after its first draw (Engine::draw calls this).
pub(crate) fn capture_aov(&mut self, f: i64) {
let Some(w) = self.app.world().get_resource::<AovWanted>() else { return };
if w.frame == Some(f) {
return;
}
let got = self.read_aov();
let mut w = self.app.world_mut().resource_mut::<AovWanted>();
w.frame = Some(f);
match got {
Ok(a) => w.last = Some(a),
Err(e) => {
w.last = None;
eprintln!("raea: frame {f}: no motion vectors or depth: {e}");
}
}
}
/// The guide data the last frame drawn read, taken (None when it wasn't asked for or couldn't be read).
pub fn take_aov(&mut self) -> Option<Aov> {
self.app.world_mut().get_resource_mut::<AovWanted>()?.last.take()
}
fn read_aov(&mut self) -> Result<Aov, String> {
let rw = self.app.get_sub_app_mut(bevy::render::RenderApp).ok_or("no render app")?.world_mut();
// the biggest view with both (the frame's camera; a screen's or a mirror's is smaller)
let mut q = rw.query::<&ViewPrepassTextures>();
let pick = q
.iter(rw)
.filter(|t| t.depth.is_some() && t.motion_vectors.is_some())
.max_by_key(|t| t.size.width * t.size.height)
.ok_or("no 3D camera drew a depth and motion-vector prepass")?;
// the target is a row taller than the frame (the frame tag's row, open.rs), at the frame's scale (RAEA_SS)
let (w, h) = (pick.size.width, pick.size.height.min(self.h * (pick.size.width / self.w.max(1)).max(1)));
let depth = pick.depth_only_view().ok_or("the prepass has no depth view")?.clone();
let motion = pick.motion_vectors.as_ref().unwrap().texture.default_view.clone();
let device = rw.resource::<bevy::render::renderer::RenderDevice>().wgpu_device().clone();
let queue = rw.resource::<bevy::render::renderer::RenderQueue>().clone();
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("aov"), source: wgpu::ShaderSource::Wgsl(AOV_WGSL.into()) });
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("aov"), layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: None });
let size = w as u64 * h as u64 * 12;
let out = device.create_buffer(&wgpu::BufferDescriptor { label: Some("aov"), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
let back = device.create_buffer(&wgpu::BufferDescriptor { label: Some("aov readback"), size, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
let dims = wgpu::util::DeviceExt::create_buffer_init(&device, &wgpu::util::BufferInitDescriptor { label: Some("aov dims"), contents: bytemuck::cast_slice(&[w, h, 0u32, 0u32]), usage: wgpu::BufferUsages::UNIFORM });
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("aov"),
layout: &pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&*depth) },
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&*motion) },
wgpu::BindGroupEntry { binding: 2, resource: out.as_entire_binding() },
wgpu::BindGroupEntry { binding: 3, resource: dims.as_entire_binding() },
],
});
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("aov") });
{
let mut pass = enc.begin_compute_pass(&Default::default());
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &bind, &[]);
pass.dispatch_workgroups(w.div_ceil(8), h.div_ceil(8), 1);
}
enc.copy_buffer_to_buffer(&out, 0, &back, 0, size);
queue.submit([enc.finish()]);
let (tx, rx) = std::sync::mpsc::channel();
back.slice(..).map_async(wgpu::MapMode::Read, move |r| {
let _ = tx.send(r);
});
device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(std::time::Duration::from_secs(60)) }).map_err(|e| format!("the guide data's readback: {e}"))?;
rx.recv().map_err(|e| e.to_string())?.map_err(|e| format!("the guide data's readback: {e}"))?;
let data = back.slice(..).get_mapped_range().map_err(|e| format!("the guide data's readback: {e:?}"))?;
let px: &[f32] = bytemuck::cast_slice(&data);
let n = (w * h) as usize;
let (mut motion, mut depth) = (Vec::with_capacity(n * 2), Vec::with_capacity(n));
for p in px.chunks_exact(3) {
motion.extend_from_slice(&p[..2]);
depth.push(p[2]);
}
drop(data);
back.unmap();
Ok(Aov { w, h, motion, depth })
}
}
+11 -1
View File
@@ -27,7 +27,12 @@ impl Engine {
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
let group = group.disable::<bevy::render::pipelined_rendering::PipelinedRenderingPlugin>(); let group = group.disable::<bevy::render::pipelined_rendering::PipelinedRenderingPlugin>();
// a registered Bevy plugin may change the group (plugins.rs: one that brings bevy_winit turns WinitPlugin off) // a registered Bevy plugin may change the group (plugins.rs: one that brings bevy_winit turns WinitPlugin off)
app.add_plugins(plugins::group(group)) app.add_plugins(plugins::group(group));
#[cfg(feature = "raytracing")]
if raea_render_raytrace::wanted(prog) {
raea_render_raytrace::add(&mut app);
}
app
.init_resource::<Clock>() .init_resource::<Clock>()
.init_resource::<Out>() .init_resource::<Out>()
.init_resource::<Error>() .init_resource::<Error>()
@@ -152,6 +157,11 @@ impl Engine {
mem_mark("engine: plugins built (DefaultPlugins, the render device)"); mem_mark("engine: plugins built (DefaultPlugins, the render device)");
app.finish(); app.finish();
mem_mark("engine: plugins finished"); mem_mark("engine: plugins finished");
// RT4: MetalFX's denoiser goes in after Solari's lighting, which Solari's plugin adds as it finishes
#[cfg(feature = "raytracing")]
if raea_render_raytrace::wanted(prog) {
raea_render_raytrace::add_denoiser(&mut app);
}
// lights clustered on the CPU, not by Bevy 0.19's GPU clustering: on a fresh engine's first frames the GPU's // lights clustered on the CPU, not by Bevy 0.19's GPU clustering: on a fresh engine's first frames the GPU's
// cluster lists left a spot light out (its fog shaft drawn, its light on no surface), for as many updates as its // cluster lists left a spot light out (its fog shaft drawn, its light on no surface), for as many updates as its
// readback took, so a render (a fresh engine a frame) missed it where play, warm, had it: volumetric-grid's // readback took, so a render (a fresh engine a frame) missed it where play, warm, had it: volumetric-grid's
+5 -1
View File
@@ -176,7 +176,11 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
match t.kind.as_str() { match t.kind.as_str() {
// directional (as before), point or spot: scene3d // directional (as before), point or spot: scene3d
"light" => scene3d::light(world, e, vals), "light" => scene3d::light(world, e, vals),
"model" => scene3d::model(world, e, t, inserted, dir)?, // and its cloth, when it has one (meshseq/cloth.rs)
"model" => {
scene3d::model(world, e, t, inserted, dir)?;
meshseq::cloth::spawn(world, e, t, inserted, dir)?
}
// a picture pressed onto a surface (<Decal>): decal.rs // a picture pressed onto a surface (<Decal>): decal.rs
"decal" => decal::spawn(world, e, t, inserted, dir)?, "decal" => decal::spawn(world, e, t, inserted, dir)?,
// a box of air a <VolumetricFog> draws: scene3d // a box of air a <VolumetricFog> draws: scene3d
+1 -3
View File
@@ -4,9 +4,7 @@ version = "0.1.0"
edition = "2024" edition = "2024"
license = "FSL-1.1-ALv2" license = "FSL-1.1-ALv2"
publish = false publish = false
description = "Made assets: a composition's make(model, prompt, seed, params) kept once under its content hash, from the local models (SAO, TokenSynth, splats, matchmove) or raea's API" description = "Made assets: a composition's make(model, prompt, seed, params) kept once under its content hash, from the local models (SAO, TokenSynth, splats, matchmove)"
[features]
[dependencies] [dependencies]
raea-io-home = { path = "../home" } raea-io-home = { path = "../home" }
-71
View File
@@ -1,71 +0,0 @@
//! make()s through raea's API (fish narration, the `service` feature), with the paid-request cap and its ledger.
use super::*;
/// Where a run's paid requests are counted: the file the host names in $RAEA_GEN_LEDGER (void: one per eval scenario,
/// one per agent turn), whole; else the edit's own assets/paid.jsonl over the last 24 hours. Every render is its
/// own process, so the count has to outlive one.
pub(crate) fn ledger(dir: &Path) -> (PathBuf, Option<u64>) {
match std::env::var_os("RAEA_GEN_LEDGER").filter(|v| !v.is_empty()) {
Some(p) => (PathBuf::from(p), None),
None => (dir.join("paid.jsonl"), Some(24 * 3600)),
}
}
pub(crate) fn now_s() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// Whether a paid request may go now. On by default and capped (the founder's decision, 2026-10-15): $RAEA_GEN_PAID=0
/// turns paid models off, and $RAEA_GEN_BUDGET=N sets the cap per run (default PAID_PER_RUN). A cached make() sends
/// nothing and counts nothing.
pub(crate) fn paid_allowed(model: &str, dir: &Path) -> Result<(), String> {
if std::env::var("RAEA_GEN_PAID").as_deref() == Ok("0") {
return Err(format!("{model} is paid generation, and the host turned it off (RAEA_GEN_PAID=0)"));
}
let n = std::env::var("RAEA_GEN_BUDGET").ok().and_then(|n| n.trim().parse::<usize>().ok()).unwrap_or(PAID_PER_RUN);
let (file, window) = ledger(dir);
let since = window.map(|w| now_s().saturating_sub(w)).unwrap_or(0);
let spent = std::fs::read_to_string(&file).unwrap_or_default().lines()
.filter_map(|l| serde_json::from_str::<J>(l).ok())
.filter(|l| l["t"].as_u64().unwrap_or(0) >= since)
.count();
if spent >= n {
return Err(format!("{model}: this run has used its {n} paid generations (RAEA_GEN_BUDGET); use tokensynth or sao (local), a cached take, or no sound"));
}
Ok(())
}
/// One paid request, counted when it's sent: a request that fails may still be billed.
pub(crate) fn count_paid(model: &str, dir: &Path) {
let (file, _) = ledger(dir);
if let Some(d) = file.parent() {
let _ = std::fs::create_dir_all(d);
}
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&file) {
use std::io::Write;
let _ = writeln!(f, "{}", json!({"t": now_s(), "model": model}));
}
}
/// A setting: the process environment first, then raea's settings file ($RAEA_ENV_FILE, else ~/.raea/env).
pub(crate) fn setting(name: &str) -> Option<String> {
if let Some(v) = std::env::var(name).ok().filter(|v| !v.trim().is_empty()) {
return Some(v.trim().to_string());
}
let file = std::env::var_os("RAEA_ENV_FILE").map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".raea/env"));
std::fs::read_to_string(file).ok()?.lines().find_map(|l| {
let (k, v) = l.trim().split_once('=')?;
(k.trim() == name && !l.trim_start().starts_with('#')).then(|| v.trim().trim_matches('"').to_string())
}).filter(|v| !v.is_empty())
}
/// A build without raea's API (the public engine) makes only with the local models.
#[cfg(not(feature = "service"))]
pub(crate) fn api(model: &str, _prompt: &str, _params: &J, _part: &Path) -> Result<(Vec<u8>, String), String> {
Err(format!("{model} isn't in this build of raea (the local models are tokensynth for music and sao for foley)"))
}
+7 -13
View File
@@ -4,15 +4,12 @@
//! //!
//! `make` is a registry keyed by model name: `stand-in` (a deterministic gradient and shapes drawn from the prompt and //! `make` is a registry keyed by model name: `stand-in` (a deterministic gradient and shapes drawn from the prompt and
//! seed, what tests use), the two local audio models, `tokensynth` (an instrument's notes, for music) and `sao` (Stable //! seed, what tests use), the two local audio models, `tokensynth` (an instrument's notes, for music) and `sao` (Stable
//! Audio Open on Core ML, foley), and raea's API: `fish` (narration). `lyria` (music) is retired: //! Audio Open on Core ML, foley). Every model runs on this computer. `lyria` (music) and `fish` (narration, through
//! a take made before plays from the index, and a new one is refused. The local models install themselves on first use (tools/sao/setup.sh, //! raea's API) are retired: a take made before plays from the index, and a new one is refused. Narration is Pocket TTS
//! (raea/speech), and Fish Audio is a `raea gen` backend like fal or Replicate (`fish:<model>`, the founder's own key). The local models install themselves on first use (tools/sao/setup.sh,
//! tools/tokensynth/setup.sh). Each made asset gets a line in `assets/made.jsonl` under its cache key, a hash of //! tools/tokensynth/setup.sh). Each made asset gets a line in `assets/made.jsonl` under its cache key, a hash of
//! (model, prompt, seed, params); `made` reads only that index, so a render or a check that resolves a make() never //! (model, prompt, seed, params); `made` reads only that index, so a render or a check that resolves a make() never
//! generates. //! generates.
//!
//! raea's API (`fish`, signed in with a device token) is the `service` feature; the public engine builds without it, and
//! its paid-request bookkeeping below goes unused there.
#![cfg_attr(not(feature = "service"), allow(dead_code))]
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -27,18 +24,13 @@ pub use splat::{ensure_splat, splat_dir, splat_params};
mod local; mod local;
use local::*; use local::*;
mod api;
use api::*;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
/// The models `make` knows, by the name an edit writes: local ones first, then the paid API's. `matchmove` (a camera /// The models `make` knows, by the name an edit writes: the local ones, then the retired ones whose takes still play. `matchmove` (a camera
/// solve) is made from a clip, by `Store::matchmove`, and indexed the same way. /// solve) is made from a clip, by `Store::matchmove`, and indexed the same way.
pub const MODELS: [&str; 6] = ["stand-in", "tokensynth", "sao", "fish", "lyria", "matchmove"]; pub const MODELS: [&str; 6] = ["stand-in", "tokensynth", "sao", "fish", "lyria", "matchmove"];
/// Paid requests a run may send when the host doesn't say ($RAEA_GEN_BUDGET): the founder's choice, on and capped small.
pub const PAID_PER_RUN: usize = 3;
/// TokenSynth's runtimes (tools/tokensynth/run.py --precision), and the one a note gets when its params don't say. /// TokenSynth's runtimes (tools/tokensynth/run.py --precision), and the one a note gets when its params don't say.
pub const TOKENSYNTH_PRECISIONS: [&str; 5] = ["fp32", "fp16", "bf16", "int8", "coreml"]; pub const TOKENSYNTH_PRECISIONS: [&str; 5] = ["fp32", "fp16", "bf16", "int8", "coreml"];
pub const TOKENSYNTH_PRECISION: &str = "fp16"; pub const TOKENSYNTH_PRECISION: &str = "fp16";
@@ -109,7 +101,8 @@ impl Store {
"tokensynth" => tokensynth(prompt, seed, params, &part).map(|wav| (wav, "wav".to_string())), "tokensynth" => tokensynth(prompt, seed, params, &part).map(|wav| (wav, "wav".to_string())),
"matchmove" => Err("matchmove is made from a clip: Store::matchmove(clip, params)".to_string()), "matchmove" => Err("matchmove is made from a clip: Store::matchmove(clip, params)".to_string()),
"lyria" => Err("lyria is retired (raea's generation policy, 2026-10-20): make music with tokensynth; a lyria take made before still plays from assets/made.jsonl".to_string()), "lyria" => Err("lyria is retired (raea's generation policy, 2026-10-20): make music with tokensynth; a lyria take made before still plays from assets/made.jsonl".to_string()),
_ => api(model, prompt, params, &part), "fish" => Err("fish is no longer part of raea (2026-11-05): narrate with <Speech> from raea/speech (Pocket TTS, on this computer), or make a line with a `raea gen` step on fish:<model> and your FISH_API_KEY; a fish take made before still plays from assets/made.jsonl".to_string()),
_ => Err(format!("unknown model `{model}`")),
}; };
let _ = std::fs::remove_file(&part); let _ = std::fs::remove_file(&part);
let (bytes, ext) = made?; let (bytes, ext) = made?;
@@ -229,6 +222,7 @@ pub fn ensure_installed(model: &str) -> Result<PathBuf, String> {
if std::env::var("RAEA_AUDIO_AUTOSETUP").as_deref() == Ok("0") { if std::env::var("RAEA_AUDIO_AUTOSETUP").as_deref() == Ok("0") {
return Err(format!("{model} isn't installed: run {how}")); return Err(format!("{model} isn't installed: run {how}"));
} }
raea_io_home::offline(&format!("installing {model} ({size} downloaded)"))?;
if !script.exists() { if !script.exists() {
return Err(format!("{model} isn't installed in {}, and its setup script isn't at {}", dir.display(), script.display())); return Err(format!("{model} isn't installed in {}, and its setup script isn't at {}", dir.display(), script.display()));
} }
+7 -1
View File
@@ -1,5 +1,12 @@
use super::*; use super::*;
#[test]
fn a_new_fish_take_is_refused() {
let s = Store { dir: std::env::temp_dir().join(format!("render-fish-{}", std::process::id())) };
let e = s.make("fish", "Three drops.", 1, &json!({})).unwrap_err();
assert!(e.contains("no longer part of raea") && e.contains("<Speech>"), "{e}");
let _ = std::fs::remove_dir_all(&s.dir);
}
#[test] #[test]
fn a_new_lyria_take_is_refused() { fn a_new_lyria_take_is_refused() {
@@ -8,7 +15,6 @@ fn a_new_lyria_take_is_refused() {
let _ = std::fs::remove_dir_all(&s.dir); let _ = std::fs::remove_dir_all(&s.dir);
} }
#[test] #[test]
fn the_key_ignores_param_order_but_not_seed_or_params() { fn the_key_ignores_param_order_but_not_seed_or_params() {
let k = make_key("sao", "rain", 3, &json!({"seconds": 6, "a": 1})); let k = make_key("sao", "rain", 3, &json!({"seconds": 6, "a": 1}));
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "raea-io-gen-comfy"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "ComfyUI both ways for generation flows: any workflow read and lifted to a flow, a flow written as a workflow, and a ComfyUI server as a place steps run"
[dependencies]
raea-io-gen-core = { path = "../gen-core" }
serde_json = "1"
+178
View File
@@ -0,0 +1,178 @@
//! ComfyUI's partner API nodes (comfy.org bills them in its own credits) as made steps: the same vendor's model on
//! made.app, at the provider's price. A node's class names the vendor and what it does; its `model` setting, when it
//! has one, picks the version. 3D nodes (Tripo, Meshy, Rodin, Hunyuan) go to the same vendor on fal, since made makes
//! no meshes. The chat nodes
//! (Claude, OpenAI, Gemini) become text.generate on OpenRouter. Luma, Pixverse, Vidu and Runway stay ComfyUI.
use serde_json::{Map, Value as J, json};
use raea_io_gen_core::flow::Step;
/// Class prefix, what it does (`image`: generate, or edit when it's given an image; `video`: likewise with a video;
/// `upscale`, `vupscale`, `speech`, `lipsync`, …), and its made model unless VERSIONS picks another.
const TABLE: &[(&str, &str, &str)] = &[
("GeminiImage", "image", "nano_banana_2"),
("GeminiNanoBanana2", "image", "nano_banana_2"),
("OpenAIGPTImage", "image", "gpt_image_2"),
("OpenAIDalle", "image", "gpt_image_2"),
("ByteDanceSeedream", "image", "seedream_5_pro"),
("ByteDanceImageEdit", "image", "seedream_5_pro_edit"),
("GrokImage", "image", "grok_imagine_image_2"),
("Flux2Image", "image", "flux_2_pro"),
("Flux3Image", "image", "flux_2_pro"),
("FluxKontextMax", "image", "flux_kontext_max"),
("FluxKontext", "image", "flux_kontext_pro"),
("FluxProUltra", "image", "flux_1_1_pro"),
("FluxPro", "image", "flux_1_1_pro"),
("RecraftV4TextToImage", "image", "recraft_4_1"),
("RecraftTextToImage", "image", "recraft_4_1"),
("Krea", "image", "krea_2"),
("MetaMuseImage", "image", "muse_image"),
("QwenImage", "image", "qwen_image_3"),
("IdeogramV4", "image", "ideogram_v4_5_edit"),
("ReveImage", "image", "reve_create"),
("BriaRemoveBackground", "rembg", "bria_background_removal"),
("WavespeedImageUpscale", "upscale", "topaz_upscale_image"),
("MagnificImageUpscaler", "upscale", "topaz_upscale_image"),
("TopazImage", "upscale", "topaz_upscale_image"),
("WavespeedFlashVSR", "vupscale", "seedvr_video_upscale"),
("TopazVideo", "vupscale", "seedvr_video_upscale"),
("KlingOmniProEditVideo", "video", "kling_o3_edit_pro"),
("KlingOmniPro", "video", "kling_o3_pro"),
("Kling4", "video", "kling_4"),
("KlingLipSync", "lipsync", "kling_lipsync"),
("KlingAvatar", "lipsync", "kling_avatar_v2_pro"),
("KlingMotionControl", "video", "kling_3_motion_control_pro"),
("Kling", "video", "kling_3_pro"),
("Veo3", "video", "veo_3_1"),
("Veo", "video", "veo_3_1"),
("ByteDance2Reference", "video", "seedance_2_5_reference"),
("ByteDance2", "video", "seedance_2"),
("ByteDanceImageToVideo", "video", "seedance_1_5_pro"),
("ByteDanceTextToVideo", "video", "seedance_1_5_pro"),
("ByteDanceFirstLastFrame", "video", "seedance_1_5_pro"),
("MinimaxHailuo03Reference", "video", "minimax_h3_max_reference"),
("MinimaxHailuo03", "video", "minimax_h3_max"),
("MinimaxHailuo", "video", "hailuo_02"),
("Minimax", "video", "hailuo_02"),
("Wan3Reference", "video", "wan_3_0_prime_reference"),
("Wan3", "video", "wan_3"),
("Wan2VideoEdit", "video", "wan_3_reference_edit"),
("Wan2", "video", "wan_2_7"),
("WanImageToVideoApi", "video", "wan_2_5_i2v"),
("WanTextToVideoApi", "video", "wan_2_7"),
("WanReferenceVideoApi", "video", "wan_3_0_prime_reference"),
("HappyHorse", "video", "happy_horse_1_1"),
("LtxApi", "video", "ltx_2_5_fast"),
("GrokVideoExtend", "video", "grok_imagine_video_extend"),
("GrokVideo", "video", "grok_imagine_video_1_5"),
("FluxVideoEdit", "video", "flux_3"),
("SyncLipSync", "lipsync", "sync_lipsync_v3"),
("SyncTalkingImage", "lipsync", "omnihuman_1_5"),
("VeedFabric", "lipsync", "veed_fabric"),
("ElevenLabsTextToSpeech", "speech", "elevenlabs_turbo_v2_5"),
("HeyGenTextToSpeech", "speech", "elevenlabs_turbo_v2_5"),
("HeyGenVoiceTextToSpeech", "speech", "elevenlabs_turbo_v2_5"),
("ElevenLabsSoundEffects", "sfx", "elevenlabs_sound_effects_v2"),
("ElevenLabsMusic", "music", "elevenlabs_music_v2_5"),
// the chat nodes write prompts: OpenRouter has each vendor's models
("ClaudeNode", "text", "anthropic/claude-sonnet-4.5"),
("OpenAIChatNode", "text", "openai/gpt-5"),
("OpenRouterLLMNode", "text", "moonshotai/kimi-k3.1-pro"),
("GeminiNode", "text", "google/gemini-2.5-flash"),
// 3D: no made model makes meshes, so these go to fal directly (an endpoint id has a slash)
("TripoTextToModel", "mesh", "tripo3d/h3.1/text-to-3d"),
("TripoImageToModel", "mesh", "tripo3d/h3.1/image-to-3d"),
("TripoMultiviewToModel", "mesh", "tripo3d/h3.1/multiview-to-3d"),
("TripoP1ImageToModel", "mesh", "tripo3d/p1/image-to-3d"),
("TripoPSeriesImageToModel", "mesh", "tripo3d/p2/image-to-3d"),
("MeshyTextToModel", "mesh", "meshy/v7.1/text-to-3d"),
("MeshyImageToModel", "mesh", "meshy/v7.1/image-to-3d"),
("MeshyMultiImageToModel", "mesh", "meshy/v7.1/multi-image-to-3d"),
("Rodin3D", "mesh", "fal-ai/hyper3d/rodin/v2.5"),
("TencentImageToModel", "mesh", "fal-ai/hunyuan-3d/v3.1/pro/image-to-3d"),
("TencentTextToModel", "mesh", "fal-ai/hunyuan-3d/v3.1/pro/text-to-3d"),
];
/// A TABLE row's other models: the first whose text is in the node's `model` setting (lowercased) wins.
const VERSIONS: &[(&str, &str, &str)] = &[
("GeminiImage", "3-pro", "nano_banana_pro"), ("GeminiImage", "pro-image", "nano_banana_pro"), ("GeminiImage", "2.5", "nano_banana"),
("OpenAIGPTImage", "2.5", "gpt_image_2_5_flare"),
("ByteDanceSeedream", "4.5", "seedream_5_pro"), ("ByteDanceSeedream", "4", "seedream_4"),
("GrokImage", "quality", "grok_imagine_image_quality"),
("Kling", "2-6", "kling_2_6"), ("Kling", "2.6", "kling_2_6"), ("Kling", "2-5", "kling_2_5_turbo_pro"), ("Kling", "2.5", "kling_2_5_turbo_pro"),
("Veo3", "fast", "veo_3_fast"), ("Veo", "fast", "veo_3_fast"),
];
/// ComfyUI input names and the flow input each becomes.
const NAMES: &[(&str, &str)] = &[
("prompt", "prompt"), ("text", "prompt"), ("negative_prompt", "negative"), ("seed", "seed"), ("aspect_ratio", "aspect_ratio"),
("duration", "seconds"), ("resolution", "resolution"), ("generate_audio", "audio"),
("first_frame", "start_image"), ("start_frame", "start_image"), ("start_image", "start_image"),
("end_frame", "end_image"), ("last_frame", "end_image"), ("end_image", "end_image"),
("image", "image"), ("images", "image"), ("input_image", "image"), ("reference_images", "refs"), ("reference_image", "refs"),
("video", "video"), ("audio", "x_audio"),
];
/// A partner node as a step (its links still `[id, slot]`, for the lifter to point at steps), or None.
pub fn api_step(class: &str, inputs: &Map<String, J>) -> Option<Step> {
let (row, does, model) = TABLE.iter().find(|(prefix, _, _)| class.starts_with(prefix))?;
let setting = inputs.get("model").and_then(|m| m.as_str()).unwrap_or("").to_ascii_lowercase();
let made = VERSIONS.iter().find(|(r, text, _)| r == row && setting.contains(text)).map_or(*model, |v| v.2);
let mut i = Map::new();
for (k, v) in inputs {
// a dynamic combo's settings (`model.resolution`) are the chosen version's own
let base = k.rsplit('.').next().unwrap_or(k);
if let Some((_, to)) = NAMES.iter().find(|(from, _)| *from == base) {
i.entry(to.to_string()).or_insert(v.clone());
}
}
let (has_image, has_video) = (i.contains_key("image") || i.contains_key("refs"), i.contains_key("video"));
let op = match *does {
"image" if has_image => "image.edit",
"image" => "image.generate",
"video" if has_video => "video.edit",
"video" => {
if let Some(img) = i.remove("image") {
i.entry("start_image".to_string()).or_insert(img);
}
"video.generate"
}
"upscale" => "image.upscale",
"rembg" => "image.remove_background",
"vupscale" => "video.upscale",
"speech" => {
if let Some(p) = i.remove("prompt") {
i.insert("text".into(), p);
}
"audio.speech"
}
"sfx" => "audio.sfx",
"music" => "audio.music",
"mesh" => "mesh.generate",
"text" => "text.generate",
// lip sync: a video (or a still) and the audio it's synced to
_ => {
let media = i.remove("video").or_else(|| i.remove("image")).or_else(|| i.remove("start_image"));
i.insert("video".into(), media.unwrap_or(J::Null));
i.entry("prompt".to_string()).or_insert(json!(""));
"video.edit"
}
};
if op == "image.edit" && !i.contains_key("image") {
if let Some(r) = i.remove("refs") {
i.insert("image".into(), r);
}
}
if op == "image.edit" || op == "video.edit" || op == "video.generate" {
i.entry("prompt".to_string()).or_insert(json!(""));
}
// inputs an op doesn't take are carried as the model's own (x_…)
let known = raea_io_gen_core::flow::op(op).map(|o| [o.2, o.3].concat()).unwrap_or_default();
let i: Map<String, J> = i.into_iter().map(|(k, v)| if known.contains(&k.as_str()) || k.starts_with("x_") { (k, v) } else { (format!("x_{k}"), v) }).collect();
let mut s = Step::new(op, J::Object(i));
s.model = Some(match (*does, made.contains('/')) { ("text", _) => format!("openrouter:{made}"), (_, true) => format!("fal:{made}"), _ => format!("made:{made}") });
s.from = Some(format!("comfy {class} ({})", if setting.is_empty() { "-" } else { &setting }));
Some(s)
}
+29
View File
@@ -0,0 +1,29 @@
//! ComfyUI both ways: a workflow (UI or API format) read into named nodes and lifted to a flow; a flow written back as
//! an API-format workflow; and a ComfyUI server (local, or hosted on Modal or any machine) as a place a step runs.
pub mod api_nodes;
pub mod lift;
pub mod needs;
pub mod read;
pub mod schema;
pub mod server;
pub mod view;
pub mod write;
use serde_json::Value as J;
use raea_io_gen_core::flow::Flow;
pub(crate) use raea_io_gen_core::flow::index as flow_index;
/// A workflow's JSON as a flow, with the schema this machine has.
pub fn import(v: &J) -> Result<lift::Lifted, String> {
let schema = schema::load();
let g = read::read(v, &schema)?;
Ok(lift::lift(&g, &schema))
}
/// A flow as API-format JSON for ComfyUI's /prompt.
pub fn export(f: &Flow) -> Result<J, String> {
write::write(f)
}
+370
View File
@@ -0,0 +1,370 @@
//! A ComfyUI graph lifted to a flow: each output's chain named by what it makes. A sampler chain (KSampler or
//! SamplerCustomAdvanced, its loaders, prompts and latent) becomes image.generate, image.edit or video.generate with
//! its weights, LoRAs and settings kept as inputs; a partner API node (Gemini, Kling, Veo, Seedance, …) becomes the
//! same op on the made model that runs that vendor's model; loaders become media.load. What has no name stays ComfyUI
//! nodes in a `comfy` step, with the steps it reads bound in, so it runs exactly on a ComfyUI server.
use std::collections::BTreeMap;
use serde_json::{Map, Value as J, json};
use crate::api_nodes::api_step;
use crate::read::{Graph, link, upstream};
use raea_io_gen_core::flow::{Flow, Step};
const SAMPLERS: [&str; 4] = ["KSampler", "KSamplerAdvanced", "SamplerCustomAdvanced", "SamplerCustom"];
const LOADS: [(&str, &str); 5] = [("LoadImage", "image"), ("LoadImageMask", "image"), ("LoadVideo", "file"), ("VHS_LoadVideo", "video"), ("LoadAudio", "audio")];
/// latent or conditioning nodes that make a sampler's output a video, and the image inputs they carry
const VIDEO_LATENTS: [&str; 12] = ["EmptyHunyuanLatentVideo", "EmptyLTXVLatentVideo", "EmptyMochiLatentVideo", "EmptyCosmosLatentVideo", "WanImageToVideo", "WanFirstLastFrameToVideo", "Wan22ImageToVideoLatent", "LTXVImgToVideo", "HunyuanImageToVideo", "CosmosImageToVideoLatent", "WanVaceToVideo", "EmptyWanLatentVideo"];
/// What a lift found: the flow, and each sink's step (by sink node id) for a reader.
pub struct Lifted {
pub flow: Flow,
pub sinks: BTreeMap<String, String>,
}
fn is_sink(class: &str, schema_out: bool) -> bool {
schema_out || class.starts_with("Save") || class.starts_with("Preview") || class == "VHS_VideoCombine"
}
struct Cx<'a> {
g: &'a Graph,
flow: Flow,
/// comfy node id → step id, once lifted
done: BTreeMap<String, String>,
}
impl Cx<'_> {
fn input(&self, id: &str, name: &str) -> Option<&J> {
self.g.get(id)?.inputs.get(name)
}
/// An input followed to a literal: through primitive and string nodes (a node's own value, text or string), a
/// switch's chosen branch (the other when that one leads nowhere: an LLM enhancer), string edits to their source.
fn lit(&self, id: &str, name: &str) -> Option<J> {
self.lit_at(self.input(id, name)?, 0)
}
fn lit_at(&self, v: &J, depth: usize) -> Option<J> {
let Some((src, _)) = link(v) else { return Some(v.clone()) };
if depth > 12 {
return None;
}
let n = self.g.get(src)?;
let follow = |k: &str| n.inputs.get(k).and_then(|x| self.lit_at(x, depth + 1));
if n.class.contains("Switch") {
let on = follow("switch").and_then(|b| b.as_bool()).unwrap_or(false);
let (a, b) = if on { ("on_true", "on_false") } else { ("on_false", "on_true") };
return follow(a).filter(|x| x.as_str().is_none_or(|s| !s.trim().is_empty())).or_else(|| follow(b));
}
["value", "text", "string", "prompt", "string_a", "text_a"].iter().find_map(|k| follow(k))
}
/// The first node upstream of `id` (itself not counted) whose class passes `f`.
fn find(&self, id: &str, f: impl Fn(&str) -> bool) -> Option<String> {
upstream(self.g, id).into_iter().skip(1).find(|n| self.g.get(n).is_some_and(|x| f(&x.class)))
}
/// The text a conditioning input leads to: the nearest text-encode node's words.
fn text(&self, id: &str, input: &str) -> Option<String> {
let (src, _) = link(self.input(id, input)?)?;
let enc = std::iter::once(src.to_string()).chain(upstream(self.g, src)).find(|n| self.g.get(n).is_some_and(|x| x.class.contains("TextEncode")))?;
["text", "prompt", "t5xxl", "clip_l"].iter().find_map(|k| self.lit(&enc, k)).and_then(|v| v.as_str().map(str::to_string))
}
fn step(&mut self, comfy_id: &str, mut step: Step) -> String {
let id = format!("n{}", comfy_id.replace(':', "_"));
if step.from.is_none() {
step.from = Some(format!("comfy {} {comfy_id}", self.g[comfy_id].class));
}
self.flow.steps.insert(id.clone(), step);
self.done.insert(comfy_id.to_string(), id.clone());
id
}
/// The step that makes what `id`'s output is: lifted when it can be named, else kept as ComfyUI nodes.
fn lift(&mut self, id: &str) -> String {
if let Some(s) = self.done.get(id) {
return s.clone();
}
let class = self.g[id].class.clone();
if let Some((_, key)) = LOADS.iter().find(|(c, _)| *c == class) {
let path = self.lit(id, key).unwrap_or(J::Null);
return self.step(id, Step::new("media.load", json!({"path": path})));
}
if class == "VAEDecode" || class == "VAEDecodeTiled" {
let why = match self.find(id, |c| SAMPLERS.contains(&c)) {
Some(s) => match self.sampler(&s) {
Ok(step) => return self.step(id, step),
Err(why) => why,
},
None => "no sampler upstream".to_string(),
};
let kept = self.keep(id);
self.flow.steps.get_mut(&kept).unwrap().from = Some(format!("comfy VAEDecode {id}, kept: {why}"));
return kept;
}
if class == "ImageUpscaleWithModel" {
if let Some((img, _)) = self.input(id, "image").and_then(link).map(|(a, b)| (a.to_string(), b)) {
let model = self.input(id, "upscale_model").and_then(link).and_then(|(m, _)| self.lit(m, "model_name"));
let factor = model.as_ref().and_then(|m| m.as_str()).and_then(|m| m.chars().next().and_then(|c| c.to_digit(10))).unwrap_or(4);
let image = self.lift(&img);
return self.step(id, Step::new("image.upscale", json!({"image": format!("@{image}"), "factor": factor, "weights": model})));
}
}
if let Some(step) = self.utility(id, &class) {
return self.step(id, step);
}
let named: Map<String, J> = self.g[id].inputs.clone();
if let Some(mut step) = api_step(&class, &named) {
// its media inputs are other nodes' outputs: lift them and point at their steps
for v in step.inputs.values_mut() {
self.point(v);
}
return self.step(id, step);
}
self.keep(id)
}
/// Links inside a lifted step's inputs (`[id, slot]`, or arrays of them) replaced by `@step`.
fn point(&mut self, v: &mut J) {
if let Some((src, _)) = link(v).map(|(a, b)| (a.to_string(), b)) {
*v = json!(format!("@{}", self.lift(&src)));
} else if let Some(a) = v.as_array_mut() {
for x in a {
self.point(x);
}
}
}
/// A node with no name kept as ComfyUI: it and what it reads, up to media that other steps make (a load, a
/// lifted generation), which are bound in as `bind: {"<node>.<input>": "@step"}`.
fn keep(&mut self, id: &str) -> String {
let mut nodes = Map::new();
let mut bind = Map::new();
let mut queue = vec![id.to_string()];
while let Some(n) = queue.pop() {
if nodes.contains_key(&n) {
continue;
}
let node = self.g[&n].clone();
for (name, v) in &node.inputs {
let Some((src, _)) = link(v) else { continue };
let sc = &self.g[src].class;
let media = LOADS.iter().any(|(c, _)| c == sc) || ((sc == "VAEDecode" || sc == "VAEDecodeTiled") && src != id);
if media && src != id {
let step = self.lift(src);
bind.insert(format!("{n}.{name}"), json!(format!("@{step}")));
} else {
queue.push(src.to_string());
}
}
nodes.insert(n.clone(), json!({"class_type": node.class, "inputs": node.inputs}));
}
let mut inputs = json!({"nodes": nodes, "output": id});
if !bind.is_empty() {
inputs["bind"] = J::Object(bind);
}
self.step(id, Step::new("comfy", inputs))
}
/// A sampler's chain as one step.
fn sampler(&mut self, s: &str) -> Result<Step, String> {
let class = self.g[s].class.clone();
let mut i = Map::new();
// the guider holds the prompts on SamplerCustomAdvanced; the sampler itself does elsewhere
let cond = if class == "SamplerCustomAdvanced" { self.input(s, "guider").and_then(link).map(|(g, _)| g.to_string()).ok_or("its guider isn't linked")? } else { s.to_string() };
let prompt = ["positive", "conditioning", "cond1"].iter().find_map(|k| self.text(&cond, k)).ok_or_else(|| format!("no prompt found up {}'s conditioning", self.g[&cond].class))?;
i.insert("prompt".into(), json!(prompt));
if let Some(neg) = self.text(&cond, "negative").or_else(|| self.text(&cond, "cond2")).filter(|t| !t.trim().is_empty()) {
i.insert("negative".into(), json!(neg));
}
let pick = |cx: &Cx, from: Option<String>, keys: &[(&str, &str)], i: &mut Map<String, J>| {
if let Some(n) = from {
for (k, to) in keys {
if let Some(v) = cx.lit(&n, k).filter(|v| !v.is_null()) {
i.insert(to.to_string(), v);
}
}
}
};
pick(self, Some(s.into()), &[("seed", "seed"), ("noise_seed", "seed"), ("steps", "steps"), ("cfg", "cfg"), ("sampler_name", "sampler"), ("scheduler", "scheduler")], &mut i);
if class == "SamplerCustomAdvanced" {
let up = |name: &str| self.input(s, name).and_then(link).map(|(n, _)| n.to_string());
pick(self, up("noise"), &[("noise_seed", "seed")], &mut i);
pick(self, up("sigmas"), &[("steps", "steps"), ("scheduler", "scheduler"), ("denoise", "x_denoise")], &mut i);
pick(self, up("sampler"), &[("sampler_name", "sampler")], &mut i);
pick(self, Some(cond.clone()), &[("cfg", "cfg")], &mut i);
}
if let Some(g) = self.find(&cond, |c| c == "FluxGuidance") {
pick(self, Some(g), &[("guidance", "cfg")], &mut i);
}
// weights and LoRAs: every loader up the model input
let model_root = self.input(s, "model").or_else(|| self.input(&cond, "model")).and_then(link).map(|(m, _)| m.to_string());
if let Some(m) = model_root {
let chain = upstream(self.g, &m);
let mut weights = Vec::new();
let mut loras = Vec::new();
for n in &chain {
for k in ["ckpt_name", "unet_name"] {
if let Some(w) = self.lit(n, k) {
weights.push(w);
}
}
if let Some(l) = self.lit(n, "lora_name") {
loras.push(json!({"name": l, "strength": self.lit(n, "strength_model").unwrap_or(json!(1.0))}));
}
}
if !weights.is_empty() {
i.insert("weights".into(), if weights.len() == 1 { weights.remove(0) } else { J::Array(weights) });
}
if !loras.is_empty() {
i.insert("loras".into(), J::Array(loras));
}
}
// the latent says what kind of step this is
let latent = self.input(s, "latent_image").and_then(link).map(|(l, _)| l.to_string());
let video = self.find(s, |c| VIDEO_LATENTS.contains(&c) || c.ends_with("ToVideo") || c.contains("ToVideoLatent"));
if let Some(v) = video {
for (k, to) in [("width", "width"), ("height", "height"), ("length", "x_frames")] {
if let Some(x) = self.lit(&v, k) {
i.insert(to.into(), x);
}
}
for (k, to) in [("start_image", "start_image"), ("image", "start_image"), ("end_image", "end_image")] {
if let Some((src, _)) = self.input(&v, k).and_then(link).map(|(a, b)| (a.to_string(), b)) {
let st = self.lift(&src);
i.insert(to.into(), json!(format!("@{st}")));
}
}
return Ok(Step::new("video.generate", J::Object(i)));
}
let mut latent = latent.ok_or("its latent isn't linked")?;
// a second pass (a refiner, a high- then low-noise sampler) or an upscaled latent: back to the first latent
for _ in 0..8 {
let n = &self.g[&latent];
let next = if SAMPLERS.contains(&n.class.as_str()) { n.inputs.get("latent_image") } else if n.class.starts_with("LatentUpscale") { n.inputs.get("samples") } else { None };
match next.and_then(link) {
Some((l, _)) => latent = l.to_string(),
None => break,
}
}
let lclass = self.g[&latent].class.clone();
if lclass.starts_with("Empty") {
pick(self, Some(latent), &[("width", "width"), ("height", "height")], &mut i);
return Ok(Step::new("image.generate", J::Object(i)));
}
// an encoded image: img2img (or inpainting, with a mask on the way)
let enc = std::iter::once(latent.clone()).chain(upstream(self.g, &latent)).find(|n| self.g.get(n).is_some_and(|x| x.class.starts_with("VAEEncode") || x.class == "InpaintModelConditioning")).ok_or_else(|| format!("its latent comes from {}, neither empty nor an encoded image", lclass))?;
let (px, _) = self.input(&enc, "pixels").and_then(link).map(|(a, b)| (a.to_string(), b)).ok_or("the encoded image isn't linked")?;
let image = self.lift(&px);
i.insert("image".into(), json!(format!("@{image}")));
if let Some((m, _)) = self.input(&enc, "mask").or_else(|| self.input(&latent, "mask")).and_then(link).map(|(a, b)| (a.to_string(), b)) {
let mask = self.lift(&m);
i.insert("mask".into(), json!(format!("@{mask}")));
}
if let Some(d) = self.lit(s, "denoise") {
i.insert("strength".into(), d);
}
Ok(Step::new("image.edit", J::Object(i)))
}
}
impl Cx<'_> {
/// The image utilities raea runs itself (image.crop, image.scale, image.stitch), from ComfyUI's core nodes; None
/// for any other node, or one whose image or numbers aren't plain.
fn utility(&mut self, id: &str, class: &str) -> Option<Step> {
let num = |cx: &Self, k: &str| cx.lit(id, k).filter(|v| v.is_number());
let image = |cx: &mut Self, k: &str| -> Option<J> {
let (src, _) = cx.input(id, k).and_then(link).map(|(a, b)| (a.to_string(), b))?;
Some(json!(format!("@{}", cx.lift(&src))))
};
let mut i = Map::new();
match class {
"ImageCrop" => {
for k in ["width", "height", "x", "y"] {
i.insert(k.into(), num(self, k)?);
}
i.insert("image".into(), image(self, "image")?);
Some(Step::new("image.crop", J::Object(i)))
}
"ImageScale" | "ImageScaleBy" | "ImageScaleToTotalPixels" => {
match class {
// 0 keeps the picture's proportions on that side
"ImageScale" => {
for k in ["width", "height"] {
if let Some(v) = num(self, k).filter(|v| v.as_f64() != Some(0.0)) {
i.insert(k.into(), v);
}
}
let cover = self.lit(id, "crop").is_some_and(|c| c == "center");
i.insert("fit".into(), json!(if cover { "cover" } else { "stretch" }));
}
"ImageScaleBy" => { i.insert("factor".into(), num(self, "scale_by")?); }
_ => { i.insert("megapixels".into(), num(self, "megapixels")?); }
}
i.insert("image".into(), image(self, "image")?);
Some(Step::new("image.scale", J::Object(i)))
}
"ImageStitch" => {
let mut images = vec![image(self, "image1")?];
images.extend(image(self, "image2"));
i.insert("images".into(), J::Array(images));
if let Some(d) = self.lit(id, "direction") {
i.insert("direction".into(), d);
}
Some(Step::new("image.stitch", J::Object(i)))
}
_ => None,
}
}
}
/// Every output of a graph lifted. A video sink (CreateVideo, VHS_VideoCombine) gives its step seconds from frames
/// and fps.
pub fn lift(g: &Graph, schema: &crate::schema::Schema) -> Lifted {
let mut cx = Cx { g, flow: Flow::default(), done: BTreeMap::new() };
let mut sinks = BTreeMap::new();
for (id, n) in g {
if !is_sink(&n.class, schema.get(&n.class).is_some_and(|c| c.output_node)) || n.class == "PreviewAny" {
continue;
}
// what the sink saves: its first linked input, through CreateVideo-style wrappers that only add fps
let Some((mut src, slot)) = n.inputs.values().find_map(link).map(|(a, b)| (a.to_string(), b)) else { continue };
let mut fps = n.inputs.get("frame_rate").or(n.inputs.get("fps")).cloned();
if g[&src].class == "CreateVideo" {
fps = cx.lit(&src, "fps").or(fps);
if let Some((img, _)) = g[&src].inputs.get("images").and_then(link) {
src = img.to_string();
}
}
let step = cx.lift(&src);
if let (Some(fps), Some(s)) = (fps.and_then(|f| f.as_f64()), cx.flow.steps.get_mut(&step)) {
if s.op == "video.generate" || s.inputs.contains_key("x_frames") {
s.op = "video.generate".into();
if let Some(frames) = s.inputs.remove("x_frames").and_then(|f| f.as_f64()) {
s.inputs.insert("seconds".into(), json!(((frames / fps) * 100.0).round() / 100.0));
}
s.inputs.insert("fps".into(), json!(fps));
}
}
// a kept node saved from several of its outputs (a stem separator's four): the step gives each slot, in order
if let Some(st) = cx.flow.steps.get_mut(&step).filter(|st| st.op == "comfy" && st.inputs.get("output").and_then(|o| o.as_str()) == Some(src.as_str())) {
let slots = st.inputs.entry("slots").or_insert(json!([]));
if let Some(a) = slots.as_array_mut().filter(|a| !a.contains(&json!(slot))) {
a.push(json!(slot));
}
}
if !cx.flow.out.contains(&step) {
cx.flow.out.push(step.clone());
}
sinks.insert(id.clone(), step);
}
// one slot, the first: the plain case, no list
for st in cx.flow.steps.values_mut() {
if st.inputs.get("slots") == Some(&json!([0])) {
st.inputs.remove("slots");
}
}
Lifted { flow: cx.flow, sinks }
}
+101
View File
@@ -0,0 +1,101 @@
//! What a workflow needs from a ComfyUI server beyond what it has: the node packs its classes come from and the model
//! files its loaders read. A UI-format workflow says both itself (each node's `properties.cnr_id`, the ComfyUI
//! registry's id for its pack, or `aux_id`, a GitHub repo; `properties.models`, each file with its download URL and
//! models/ folder). Classes it doesn't attribute, and API-format graphs, are looked up in ComfyUI-Manager's
//! extension-node-map (which repo provides which class), kept in ~/.cache/raea-gen, then the registry's node search. tools/comfy/setup.sh nodes|models
//! installs them on this machine's server, tools/comfy/modal_comfy.py on the hosted one.
use std::collections::{BTreeMap, BTreeSet};
use serde_json::{Value as J, json};
use crate::schema::Schema;
/// Classes neither the map nor the registry search knows, found by hand (10-29): (class, repo).
const KNOWN: &[(&str, &str)] = &[
("ImageConstant", "https://github.com/spacepxl/ComfyUI-Image-Filters"),
// utility-audioseparation's own note names this pack; its __init__.py registers the class
("AudioStemSeparate", "https://github.com/lum3on/ComfyUI_AudioTools"),
];
/// The ComfyUI registry's pack for a class, by its node search (api.comfy.org); None when it finds none or several.
fn registry_pack(class: &str) -> Option<String> {
let q: String = class.bytes().map(|b| if b.is_ascii_alphanumeric() { (b as char).to_string() } else { format!("%{b:02X}") }).collect();
let r = raea_io_gen_core::http::call("GET", &format!("https://api.comfy.org/nodes/search?comfy_node_search={q}&limit=2"), &[], raea_io_gen_core::http::Body::None, None, 30).ok()?;
let v = r.json().ok()?;
match v["nodes"].as_array()?.as_slice() {
[one] => one["id"].as_str().map(str::to_string),
_ => None,
}
}
const NODE_MAP: &str = "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/extension-node-map.json";
/// ComfyUI-Manager's class → repo map (the first repo listing a class; several packs reuse some names).
fn node_map() -> BTreeMap<String, String> {
let f = raea_io_gen_core::made::cached("comfy-extension-node-map.json");
if !f.is_file() {
let _ = std::fs::create_dir_all(f.parent().unwrap_or(&f));
let _ = raea_io_gen_core::http::call("GET", NODE_MAP, &[], raea_io_gen_core::http::Body::None, Some(&f), 120);
}
let v: J = std::fs::read(&f).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or(J::Null);
let mut m = BTreeMap::new();
for (repo, entry) in v.as_object().into_iter().flatten() {
for class in entry[0].as_array().into_iter().flatten().filter_map(|c| c.as_str()) {
m.entry(class.to_string()).or_insert_with(|| repo.clone());
}
}
m
}
/// Every node of a UI-format workflow, its subgraphs' too.
fn ui_nodes(v: &J) -> Vec<&J> {
let mut out: Vec<&J> = v["nodes"].as_array().into_iter().flatten().collect();
for s in v["definitions"]["subgraphs"].as_array().into_iter().flatten() {
out.extend(s["nodes"].as_array().into_iter().flatten());
}
out
}
/// What `workflow` needs that a server with `schema` lacks: {"packs": registry ids, "repos": git URLs, "models":
/// [{name, url, directory}], "unknown": classes nobody is known to provide}.
pub fn needs(workflow: &J, schema: &Schema) -> J {
let (mut packs, mut repos, mut unknown) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new());
let mut models: BTreeMap<String, J> = BTreeMap::new();
let mut loose = BTreeSet::new();
let ui = workflow["nodes"].is_array();
let classes: Vec<(String, Option<&J>)> = if ui {
ui_nodes(workflow).into_iter().map(|n| (n["type"].as_str().unwrap_or("").to_string(), Some(&n["properties"]))).collect()
} else {
workflow.as_object().into_iter().flatten().map(|(_, n)| (n["class_type"].as_str().unwrap_or("").to_string(), None)).collect()
};
for (class, props) in classes {
for m in props.and_then(|p| p["models"].as_array()).into_iter().flatten() {
if let Some(name) = m["name"].as_str() {
models.insert(name.to_string(), json!({"name": name, "url": m["url"], "directory": m["directory"]}));
}
}
// a subgraph's own node (its type is the subgraph's id), a note, or a class the server has
if class.is_empty() || schema.contains_key(&class) || class.len() == 36 && class.matches('-').count() == 4 || matches!(class.as_str(), "Note" | "MarkdownNote" | "Reroute" | "PrimitiveNode") {
continue;
}
match props.map(|p| (p["cnr_id"].as_str(), p["aux_id"].as_str())) {
Some((Some(id), _)) if id != "comfy-core" => { packs.insert(id.to_string()); }
Some((_, Some(aux))) => { repos.insert(format!("https://github.com/{aux}")); }
_ => { loose.insert(class); }
}
}
if !loose.is_empty() {
let map = node_map();
for class in loose {
if let Some(repo) = map.get(&class).cloned().or_else(|| KNOWN.iter().find(|k| k.0 == class).map(|k| k.1.to_string())) {
repos.insert(repo);
} else if let Some(id) = registry_pack(&class) {
packs.insert(id);
} else {
unknown.insert(class);
}
}
}
json!({"packs": packs, "repos": repos, "models": models.into_values().collect::<Vec<_>>(), "unknown": unknown})
}
+229
View File
@@ -0,0 +1,229 @@
//! A ComfyUI workflow as nodes with named inputs: API format (what /prompt takes: `{id: {class_type, inputs}}`,
//! links as `[id, slot]`) as it is, and UI format (what the editor saves: positional widgets, a link table, subgraphs,
//! reroutes, primitives, muted and bypassed nodes) brought to the same shape. Subgraphs are inlined with their ids
//! prefixed by the instance's (`105:23`); notes and muted nodes go; a bypassed node passes its input of the same type.
use std::collections::BTreeMap;
use serde_json::{Map, Value as J, json};
use crate::schema::{Schema, name_widgets};
#[derive(Clone, Debug, PartialEq)]
pub struct Node {
pub class: String,
/// a setting's value, or `[node id, output slot]` for a link
pub inputs: Map<String, J>,
pub title: Option<String>,
}
pub type Graph = BTreeMap<String, Node>;
/// `[id, slot]`: the node and output an input is linked to.
pub fn link(v: &J) -> Option<(&str, usize)> {
let a = v.as_array().filter(|a| a.len() == 2)?;
Some((a[0].as_str()?, a[1].as_u64()? as usize))
}
/// Either format, told apart by its shape. A PNG's or a wrapper's `{"prompt": {...}}` is opened too.
pub fn read(v: &J, schema: &Schema) -> Result<Graph, String> {
if v["nodes"].is_array() {
return from_ui(v, schema);
}
let api = if v["prompt"].is_object() { &v["prompt"] } else { v };
let o = api.as_object().ok_or("not a ComfyUI workflow: neither UI format (nodes, links) nor API format ({id: {class_type, inputs}})")?;
let mut g = Graph::new();
for (id, n) in o {
let Some(class) = n["class_type"].as_str() else { continue };
let mut inputs = n["inputs"].as_object().cloned().unwrap_or_default();
// API format writes link ids as strings or numbers depending on who saved it
for v in inputs.values_mut() {
if let Some(a) = v.as_array_mut().filter(|a| a.len() == 2 && a[1].is_u64()) {
if let Some(n) = a[0].as_u64() {
a[0] = json!(n.to_string());
}
}
}
g.insert(id.clone(), Node { class: class.into(), inputs, title: n["_meta"]["title"].as_str().map(str::to_string) });
}
if g.is_empty() {
return Err("no nodes with a class_type".into());
}
Ok(g)
}
/// Where an input's value comes from while a UI workflow is being flattened.
#[derive(Clone, Debug)]
enum Src {
Link(String, usize),
Lit(J),
}
struct Flat {
nodes: Vec<(String, String, i64, J, Vec<(String, Option<Src>, String)>, Option<String>)>,
/// (node, slot) that stand for something else: a subgraph's outputs, reroutes, primitives, bypassed nodes
alias: BTreeMap<(String, usize), Option<Src>>,
}
pub(crate) fn ui_links(v: &J) -> BTreeMap<i64, (i64, usize)> {
v.as_array().into_iter().flatten().filter_map(|l| match l {
J::Array(a) => Some((a[0].as_i64()?, (a[1].as_i64()?, a[2].as_u64()? as usize))),
J::Object(_) => Some((l["id"].as_i64()?, (l["origin_id"].as_i64()?, l["origin_slot"].as_u64()? as usize))),
_ => None,
}).collect()
}
fn flatten(nodes: &J, links: &J, prefix: &str, defs: &BTreeMap<String, J>, parent: &[Option<Src>], flat: &mut Flat, depth: usize) -> Result<Vec<Option<Src>>, String> {
if depth > 16 {
return Err("subgraphs nested more than 16 deep (a subgraph that contains itself?)".into());
}
let table = ui_links(links);
let src_of = |link: &J| -> Option<Src> {
let (origin, slot) = *table.get(&link.as_i64()?)?;
if origin == -10 { parent.get(slot).cloned().flatten() } else { Some(Src::Link(format!("{prefix}{origin}"), slot)) }
};
for n in nodes.as_array().into_iter().flatten() {
let id = format!("{prefix}{}", id_of(n));
let class = n["type"].as_str().unwrap_or_default().to_string();
let mode = n["mode"].as_i64().unwrap_or(0);
let ins: Vec<(String, Option<Src>, String)> = n["inputs"].as_array().into_iter().flatten().map(|i| {
(i["name"].as_str().unwrap_or_default().to_string(), src_of(&i["link"]), i["type"].as_str().unwrap_or("*").to_string())
}).collect();
if let Some(sub) = defs.get(&class) {
// the instance's own widget values fill the subgraph's inputs that aren't linked, in widget order
let wv = n["widgets_values"].as_array().cloned().unwrap_or_default();
let mut wi = 0;
let by_name: BTreeMap<String, Option<Src>> = n["inputs"].as_array().into_iter().flatten().map(|i| {
let name = i["name"].as_str().unwrap_or_default().to_string();
let mut s = src_of(&i["link"]);
if i["widget"].is_object() {
if s.is_none() {
s = wv.get(wi).cloned().map(Src::Lit);
}
wi += 1;
}
(name, s)
}).collect();
let feed: Vec<Option<Src>> = sub["inputs"].as_array().into_iter().flatten().map(|si| by_name.get(si["name"].as_str().unwrap_or_default()).cloned().flatten()).collect();
let outs = if mode == 2 { vec![] } else { flatten(&sub["nodes"], &sub["links"], &format!("{id}:"), defs, &feed, flat, depth + 1)? };
for (k, o) in outs.into_iter().enumerate() {
flat.alias.insert((id.clone(), k), o);
}
continue;
}
let first = || ins.first().and_then(|(_, v, _)| v.clone());
match class.as_str() {
"Note" | "MarkdownNote" | "Label (rgthree)" => continue,
"Reroute" => { flat.alias.insert((id, 0), first()); continue; }
"PrimitiveNode" => { flat.alias.insert((id, 0), n["widgets_values"].get(0).cloned().map(Src::Lit)); continue; }
_ => {}
}
if mode == 2 {
for k in 0..8 { flat.alias.insert((id.clone(), k), None); }
continue;
}
if mode == 4 {
// bypassed: each output passes the first linked input of its type
for (k, o) in n["outputs"].as_array().into_iter().flatten().enumerate() {
let ty = o["type"].as_str().unwrap_or("*");
let pass = ins.iter().find(|i| i.1.is_some() && (i.2 == ty || ty == "*")).and_then(|i| i.1.clone());
flat.alias.insert((id.clone(), k), pass);
}
continue;
}
flat.nodes.push((id, class, mode, n["widgets_values"].clone(), ins, n["title"].as_str().map(str::to_string)));
}
// what this level hands out: links into its output node (-20)
let mut outs: Vec<Option<Src>> = Vec::new();
for l in links.as_array().into_iter().flatten() {
let (target, tslot, link_id) = match l {
J::Array(a) => (a[3].as_i64(), a[4].as_u64(), a[0].clone()),
_ => (l["target_id"].as_i64(), l["target_slot"].as_u64(), l["id"].clone()),
};
if target == Some(-20) {
let k = tslot.unwrap_or(0) as usize;
if outs.len() <= k {
outs.resize(k + 1, None);
}
outs[k] = src_of(&link_id);
}
}
Ok(outs)
}
fn from_ui(v: &J, schema: &Schema) -> Result<Graph, String> {
let defs: BTreeMap<String, J> = v["definitions"]["subgraphs"].as_array().into_iter().flatten().filter_map(|s| Some((s["id"].as_str()?.to_string(), s.clone()))).collect();
let mut flat = Flat { nodes: Vec::new(), alias: BTreeMap::new() };
flatten(&v["nodes"], &v["links"], "", &defs, &[], &mut flat, 0)?;
// follow aliases to a real node's output (or a literal)
let resolve = |s: &Src| -> Option<Src> {
let mut s = s.clone();
for _ in 0..64 {
match &s {
Src::Link(id, slot) => match flat.alias.get(&(id.clone(), *slot)) {
Some(next) => s = next.clone()?,
None => return Some(s),
},
Src::Lit(_) => return Some(s),
}
}
None
};
let mut g = Graph::new();
for (id, class, _, wv, ins, title) in &flat.nodes {
let c = schema.get(class);
let mut inputs: Map<String, J> = name_widgets(c, wv).into_iter().filter(|(k, _)| c.is_none() || !k.starts_with("widget_")).collect();
for (name, src, _) in ins {
match src.as_ref().and_then(resolve) {
Some(Src::Link(n, slot)) => { inputs.insert(name.clone(), json!([n, slot])); }
Some(Src::Lit(l)) => { inputs.insert(name.clone(), l); }
None => {}
}
}
g.insert(id.clone(), Node { class: class.clone(), inputs, title: title.clone() });
}
// a link to a node that went (muted, a note) is dropped rather than left dangling
let ids: std::collections::BTreeSet<String> = g.keys().cloned().collect();
for n in g.values_mut() {
n.inputs.retain(|_, v| link(v).is_none_or(|(id, _)| ids.contains(id)));
}
if g.is_empty() {
return Err("the workflow has no nodes that run".into());
}
Ok(g)
}
/// API format, as /prompt takes it.
pub fn to_api(g: &Graph) -> J {
J::Object(g.iter().map(|(id, n)| {
let mut o = json!({"class_type": n.class, "inputs": n.inputs});
if let Some(t) = &n.title {
o["_meta"] = json!({"title": t});
}
(id.clone(), o)
}).collect())
}
/// The nodes `id` reads from, nearest first, itself included.
pub fn upstream(g: &Graph, id: &str) -> Vec<String> {
let (mut seen, mut queue) = (Vec::new(), vec![id.to_string()]);
while let Some(n) = queue.pop() {
if seen.contains(&n) {
continue;
}
if let Some(node) = g.get(&n) {
queue.extend(node.inputs.values().filter_map(link).map(|(s, _)| s.to_string()));
}
seen.push(n);
}
seen
}
/// A UI node's id as text (a number in most workflows, a string in some).
pub(crate) fn id_of(n: &J) -> String {
match &n["id"] {
J::Number(i) => i.to_string(),
J::String(s) => s.clone(),
_ => String::new(),
}
}
+190
View File
@@ -0,0 +1,190 @@
//! What each ComfyUI node class takes, in order: a UI workflow keeps a node's settings as `widgets_values`, a list by
//! position, and only the class's schema names them. The schema comes from a ComfyUI server's /object_info, kept as
//! ~/.cache/raea-gen/comfy-object-info.json by `raea gen comfy schema [URL]`; without it, CORE names the settings of
//! the classes most workflows are built from.
use std::collections::BTreeMap;
use serde_json::Value as J;
/// One setting a node shows as a widget: its name, its type, whether a seed-style "control after generate" value
/// follows it in widgets_values, and (a dynamic combo) the settings each choice adds after it.
#[derive(Clone, Debug)]
pub struct Widget {
pub name: String,
pub ty: String,
pub control: bool,
pub choices: BTreeMap<String, Vec<Widget>>,
}
#[derive(Clone, Debug, Default)]
pub struct Class {
pub widgets: Vec<Widget>,
/// link-only inputs (MODEL, IMAGE, …) by name
pub links: Vec<(String, String)>,
pub outputs: Vec<String>,
/// a partner API node (comfy.org's paid nodes: Kling, Veo, Gemini, …)
pub api: bool,
pub output_node: bool,
}
pub type Schema = BTreeMap<String, Class>;
/// The settings, in widget order, of the classes most workflows use. `+` marks a seed followed by its control value.
const CORE: &[(&str, &str)] = &[
("CheckpointLoaderSimple", "ckpt_name"),
("CLIPTextEncode", "text"),
("KSampler", "seed+ steps cfg sampler_name scheduler denoise"),
("KSamplerAdvanced", "add_noise noise_seed+ steps cfg sampler_name scheduler start_at_step end_at_step return_with_leftover_noise"),
("EmptyLatentImage", "width height batch_size"),
("EmptySD3LatentImage", "width height batch_size"),
("SaveImage", "filename_prefix"),
("LoadImage", "image upload"),
("LoraLoader", "lora_name strength_model strength_clip"),
("LoraLoaderModelOnly", "lora_name strength_model"),
("UNETLoader", "unet_name weight_dtype"),
("CLIPLoader", "clip_name type device"),
("DualCLIPLoader", "clip_name1 clip_name2 type device"),
("VAELoader", "vae_name"),
("KSamplerSelect", "sampler_name"),
("BasicScheduler", "scheduler steps denoise"),
("RandomNoise", "noise_seed+"),
("FluxGuidance", "guidance"),
("CFGGuider", "cfg"),
("ModelSamplingSD3", "shift"),
("ModelSamplingAuraFlow", "shift"),
("SaveVideo", "filename_prefix format codec"),
("CreateVideo", "fps"),
("LoadVideo", "file upload"),
("ImageScaleBy", "upscale_method scale_by"),
("UpscaleModelLoader", "model_name"),
("SaveAudio", "filename_prefix"),
("PrimitiveStringMultiline", "value"),
("PrimitiveString", "value"),
("PrimitiveInt", "value+"),
("PrimitiveFloat", "value"),
("PrimitiveBoolean", "value"),
("WanImageToVideo", "width height length batch_size"),
("EmptyHunyuanLatentVideo", "width height length batch_size"),
];
fn core() -> Schema {
CORE.iter().map(|(class, ws)| {
let widgets = ws.split_whitespace().map(|w| Widget { name: w.trim_end_matches('+').into(), ty: String::new(), control: w.ends_with('+'), choices: BTreeMap::new() }).collect();
(class.to_string(), Class { widgets, ..Default::default() })
}).collect()
}
const WIDGET_TYPES: [&str; 6] = ["INT", "FLOAT", "STRING", "BOOLEAN", "COMBO", "COMFY_DYNAMICCOMBO_V3"];
fn widget(name: &str, spec: &J) -> Option<Widget> {
let ty = match &spec[0] {
J::Array(_) => "COMBO".to_string(),
J::String(s) => s.clone(),
_ => return None,
};
let opts = &spec[1];
if !WIDGET_TYPES.contains(&ty.as_str()) || opts["forceInput"] == true {
return None;
}
let control = !matches!(opts.get("control_after_generate"), None | Some(J::Bool(false)));
let mut choices = BTreeMap::new();
if ty == "COMFY_DYNAMICCOMBO_V3" {
for o in opts["options"].as_array().into_iter().flatten() {
let key = o["key"].as_str().unwrap_or_default().to_string();
choices.insert(key, ordered(&o["inputs"], None).0);
}
}
Some(Widget { name: name.into(), ty, control, choices })
}
/// Widgets and links of an `input` block, in the order the class declares (input_order, else the block's own).
fn ordered(input: &J, order: Option<&J>) -> (Vec<Widget>, Vec<(String, String)>) {
let (mut ws, mut ls) = (Vec::new(), Vec::new());
for part in ["required", "optional"] {
let block = &input[part];
let names: Vec<String> = match order.and_then(|o| o[part].as_array()) {
Some(a) => a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(),
None => block.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(),
};
for n in names {
let spec = &block[&n];
match widget(&n, spec) {
Some(w) => ws.push(w),
None => ls.push((n, spec[0].as_str().unwrap_or("*").to_string())),
}
}
}
(ws, ls)
}
/// A schema from /object_info's JSON.
pub fn from_object_info(v: &J) -> Schema {
v.as_object().map(|o| o.iter().map(|(class, c)| {
let (widgets, links) = ordered(&c["input"], c.get("input_order"));
let outputs = c["output"].as_array().map(|a| a.iter().map(|t| String::from(t.as_str().unwrap_or("*"))).collect()).unwrap_or_default();
(class.clone(), Class { widgets, links, outputs, api: c["api_node"] == true, output_node: c["output_node"] == true })
}).collect()).unwrap_or_default()
}
/// The server's node classes, kept in raea gen's cache under this name (made::cached).
pub const CACHE_NAME: &str = "comfy-object-info.json";
/// The schema this machine has: the cached /object_info over CORE.
pub fn load() -> Schema {
let mut s = core();
if let Some(v) = std::fs::read(raea_io_gen_core::made::cached(CACHE_NAME)).ok().and_then(|b| serde_json::from_slice::<J>(&b).ok()) {
s.extend(from_object_info(&v));
}
s
}
/// The value kept at a widget slot: an index into widgets_values, or a dynamic combo's setting by name.
pub fn slot_value(values: &J, at: &J) -> J {
match at {
J::String(k) => values[k.as_str()].clone(),
_ => values[at.as_u64().unwrap_or(0) as usize].clone(),
}
}
/// A UI node's widgets_values named: (name, value) for each, the control values after seeds skipped, a dynamic
/// combo's added settings as `combo.setting`. Values beyond what the schema names keep their place as `widget_N`.
pub fn name_widgets(class: Option<&Class>, values: &J) -> Vec<(String, J)> {
widget_slots(class, values).into_iter().map(|(name, at)| {
let v = slot_value(values, &at);
(name, v)
}).collect()
}
/// Where each named setting is in a UI node's widgets_values: its index, or its key when a node pack saves its
/// widgets by name (an edit writes back there; apps/app's whiteboards change a flow's settings this way).
pub fn widget_slots(class: Option<&Class>, values: &J) -> Vec<(String, J)> {
// some node packs (VideoHelperSuite) save their widgets by name already
if let Some(o) = values.as_object() {
return o.keys().filter(|k| k.as_str() != "videopreview").map(|k| (k.clone(), J::String(k.clone()))).collect();
}
let vals = values.as_array().cloned().unwrap_or_default();
let mut out = Vec::new();
let mut i = 0;
fn walk(ws: &[Widget], prefix: &str, vals: &[J], i: &mut usize, out: &mut Vec<(String, J)>) {
for w in ws {
let Some(v) = vals.get(*i) else { return };
out.push((format!("{prefix}{}", w.name), J::from(*i)));
*i += 1;
// a control value ("randomize", "fixed", …) rides after a seed; an older save may leave it out
if w.control && vals.get(*i).and_then(|c| c.as_str()).is_some_and(|c| ["fixed", "increment", "decrement", "randomize"].contains(&c)) {
*i += 1;
}
if let Some(sub) = v.as_str().and_then(|k| w.choices.get(k)) {
walk(sub, &format!("{}.", w.name), vals, i, out);
}
}
}
if let Some(c) = class {
walk(&c.widgets, "", &vals, &mut i, &mut out);
}
for k in i..vals.len() {
out.push((format!("widget_{k}"), J::from(k)));
}
out
}
+142
View File
@@ -0,0 +1,142 @@
//! A ComfyUI server as a place steps run: this machine's (`raea gen comfy setup` installs one) or one hosted
//! anywhere that speaks ComfyUI's own HTTP API (a Modal app, a rented GPU). RAEA_COMFY_URL says where (default
//! http://127.0.0.1:8188); RAEA_COMFY_TOKEN, when set, goes as a bearer token (a hosted server behind auth).
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use serde_json::{Value as J, json};
use raea_io_gen_core::http::{Body, call};
use raea_io_gen_core::setting;
pub struct Comfy {
pub url: String,
token: Option<String>,
}
impl Comfy {
pub fn from_settings() -> Comfy {
Comfy { url: setting("RAEA_COMFY_URL").unwrap_or_else(|| "http://127.0.0.1:8188".into()).trim_end_matches('/').to_string(), token: setting("RAEA_COMFY_TOKEN") }
}
fn headers(&self) -> Vec<String> {
self.token.iter().map(|t| format!("Authorization: Bearer {t}")).collect()
}
fn get(&self, path: &str, secs: u32) -> Result<J, String> {
let r = call("GET", &format!("{}{path}", self.url), &self.headers(), Body::None, None, secs)?;
if !r.ok() {
return Err(format!("ComfyUI {path} answered {}: {}", r.code, r.text(300)));
}
r.json()
}
/// Whether a server answers at all.
pub fn up(&self) -> bool {
self.get("/system_stats", 5).is_ok()
}
/// Whether it answers, giving a hosted one (a Modal app scaled to zero) up to `limit` to start; this machine's
/// is asked once.
pub fn wake(&self, limit: Duration) -> bool {
if self.url.contains("127.0.0.1") || self.url.contains("localhost") {
return self.up();
}
let t = Instant::now();
while t.elapsed() < limit {
if self.get("/system_stats", 60).is_ok() {
return true;
}
std::thread::sleep(Duration::from_secs(3));
}
false
}
/// The server's node schema, kept for the importer (schema::CACHE_NAME, in made::cached).
pub fn save_schema(&self) -> Result<usize, String> {
let v = self.get("/object_info", 120)?;
let n = v.as_object().map(|o| o.len()).unwrap_or(0);
let f = raea_io_gen_core::made::cached(crate::schema::CACHE_NAME);
let _ = std::fs::create_dir_all(f.parent().unwrap_or(Path::new(".")));
std::fs::write(&f, v.to_string()).map_err(|e| format!("{}: {e}", f.display()))?;
Ok(n)
}
/// A file into the server's input folder; the name a Load node uses for it.
pub fn upload(&self, file: &Path) -> Result<String, String> {
let fields = vec![("image".to_string(), format!("@{}", file.display())), ("overwrite".to_string(), "true".to_string())];
let r = call("POST", &format!("{}/upload/image", self.url), &self.headers(), Body::Form(&fields), None, 600)?;
if !r.ok() {
return Err(format!("ComfyUI upload of {} answered {}: {}", file.display(), r.code, r.text(300)));
}
let v = r.json()?;
let name = v["name"].as_str().ok_or("ComfyUI upload: no name")?;
Ok(match v["subfolder"].as_str().filter(|s| !s.is_empty()) { Some(sub) => format!("{sub}/{name}"), None => name.to_string() })
}
/// An API-format graph queued; its prompt id. A graph the server refuses says which nodes and why.
pub fn queue(&self, graph: &J) -> Result<String, String> {
let body = json!({"prompt": graph, "client_id": "raea-gen"});
let r = call("POST", &format!("{}/prompt", self.url), &self.headers(), Body::Json(&body), None, 120)?;
let v = r.json().unwrap_or(J::Null);
if !r.ok() {
let mut why = v["error"]["message"].as_str().unwrap_or("refused").to_string();
for (node, e) in v["node_errors"].as_object().into_iter().flatten() {
let errs: Vec<String> = e["errors"].as_array().into_iter().flatten().map(|x| format!("{} ({})", x["message"].as_str().unwrap_or(""), x["details"].as_str().unwrap_or(""))).collect();
why += &format!("; node {node} {}: {}", e["class_type"].as_str().unwrap_or(""), errs.join(", "));
}
return Err(format!("ComfyUI refused the graph: {why}"));
}
v["prompt_id"].as_str().map(str::to_string).ok_or_else(|| format!("ComfyUI /prompt: no prompt_id in {v}"))
}
/// The prompt's history once it ends; an error when it failed. Given up after `limit` with no result.
pub fn wait(&self, id: &str, limit: Duration) -> Result<J, String> {
let t = Instant::now();
let mut nap = 1;
loop {
let h = self.get(&format!("/history/{id}"), 30)?;
if let Some(entry) = h.get(id) {
if entry["status"]["status_str"] == "error" {
let msg = entry["status"]["messages"].as_array().into_iter().flatten().filter(|m| m[0] == "execution_error").map(|m| format!("{} {}: {}", m[1]["node_type"].as_str().unwrap_or(""), m[1]["node_id"].as_str().unwrap_or(""), m[1]["exception_message"].as_str().unwrap_or("").trim())).collect::<Vec<_>>().join("; ");
return Err(format!("ComfyUI run failed: {msg}"));
}
if entry["status"]["completed"] == true || entry["outputs"].as_object().is_some_and(|o| !o.is_empty()) {
return Ok(entry.clone());
}
}
if t.elapsed() > limit {
return Err(format!("ComfyUI prompt {id} gave nothing back in {}s", limit.as_secs()));
}
std::thread::sleep(Duration::from_secs(nap));
nap = (nap + 1).min(5);
}
}
/// One node's files from a finished run, downloaded into `dir`.
pub fn fetch(&self, entry: &J, node: &str, dir: &Path) -> Result<Vec<PathBuf>, String> {
let out = &entry["outputs"][node];
let mut files = Vec::new();
for key in ["images", "gifs", "videos", "video", "audio", "3d"] {
for f in out[key].as_array().into_iter().flatten() {
let (name, sub, ty) = (f["filename"].as_str().unwrap_or(""), f["subfolder"].as_str().unwrap_or(""), f["type"].as_str().unwrap_or("output"));
if name.is_empty() {
continue;
}
let dest = dir.join(name.rsplit('/').next().unwrap_or(name));
let q = |s: &str| s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect::<String>();
let url = format!("{}/view?filename={}&subfolder={}&type={}", self.url, q(name), q(sub), q(ty));
let r = call("GET", &url, &self.headers(), Body::None, Some(&dest), 600)?;
if !r.ok() {
return Err(format!("ComfyUI /view {name} answered {}", r.code));
}
files.push(dest);
}
}
if files.is_empty() {
return Err(format!("ComfyUI node {node} saved no files (outputs: {})", out));
}
Ok(files)
}
}
+225
View File
@@ -0,0 +1,225 @@
//! A workflow as a whiteboard shows it (docs/whiteboards.feature CF1, apps/app src/whiteboard/flow.ts): each node
//! with its class, title, mode, place and settings by name; the links between them; its groups. And a board's edits
//! written back (CF2): settings, bypass and notes. The workflow stays the source of truth; the board is a view of it.
use serde_json::{Map, Value as J, json};
use crate::read::{id_of, link, ui_links};
use crate::schema::{Schema, slot_value, widget_slots};
const NOTES: [&str; 2] = ["Note", "MarkdownNote"];
fn mode_name(m: i64) -> &'static str {
match m {
2 => "mute",
4 => "bypass",
_ => "on",
}
}
/// A node's settings by name, with where each is kept (`at`: an index into widgets_values, or an input's name).
fn ui_widgets(n: &J, schema: &Schema) -> Vec<J> {
let class = n["type"].as_str().unwrap_or_default();
let wv = &n["widgets_values"];
if NOTES.contains(&class) {
return vec![json!({"name": "text", "value": wv[0].clone(), "at": 0})];
}
widget_slots(schema.get(class), wv).into_iter().map(|(name, at)| {
let value = slot_value(wv, &at);
json!({"name": name, "value": value, "at": at})
}).collect()
}
/// The workflow (UI or API format) as nodes, links and groups. A UI workflow's own layout comes along (pos, size);
/// an API one has none, and the board lays it out by its links. Subgraphs show as the node that holds them.
pub fn view(v: &J, schema: &Schema) -> Result<J, String> {
if v["nodes"].is_array() {
let table = ui_links(&v["links"]);
let mut nodes = Vec::new();
let mut links = Vec::new();
for n in v["nodes"].as_array().into_iter().flatten() {
let id = id_of(n);
let mut inputs = Vec::new();
for i in n["inputs"].as_array().into_iter().flatten() {
let name = i["name"].as_str().unwrap_or_default();
if let Some((from, slot)) = i["link"].as_i64().and_then(|l| table.get(&l)) {
links.push(json!({"from": from.to_string(), "slot": slot, "to": id, "input": name, "type": i["type"]}));
}
inputs.push(json!({"name": name, "type": i["type"], "linked": i["link"].is_i64()}));
}
let outputs: Vec<J> = n["outputs"].as_array().into_iter().flatten().map(|o| json!({"name": o["name"], "type": o["type"]})).collect();
nodes.push(json!({
"id": id, "class": n["type"], "title": n["title"], "mode": mode_name(n["mode"].as_i64().unwrap_or(0)),
"pos": n["pos"], "size": n["size"], "widgets": ui_widgets(n, schema), "inputs": inputs, "outputs": outputs,
"note": NOTES.contains(&n["type"].as_str().unwrap_or_default()),
}));
}
let groups: Vec<J> = v["groups"].as_array().into_iter().flatten().map(|g| json!({"title": g["title"], "box": g["bounding"], "color": g["color"]})).collect();
return Ok(json!({"format": "ui", "nodes": nodes, "links": links, "groups": groups}));
}
let api = if v["prompt"].is_object() { &v["prompt"] } else { v };
let o = api.as_object().ok_or("not a ComfyUI workflow: neither UI format (nodes, links) nor API format ({id: {class_type, inputs}})")?;
let mut ids: Vec<&String> = o.keys().filter(|k| o[k.as_str()]["class_type"].is_string()).collect();
ids.sort_by_key(|k| (k.parse::<i64>().unwrap_or(i64::MAX), k.to_string()));
let mut nodes = Vec::new();
let mut links = Vec::new();
for id in ids {
let n = &o[id.as_str()];
let mut widgets = Vec::new();
let mut inputs = Vec::new();
for (name, val) in n["inputs"].as_object().into_iter().flatten() {
match link(val) {
Some((from, slot)) => {
links.push(json!({"from": from, "slot": slot, "to": id, "input": name}));
inputs.push(json!({"name": name, "linked": true}));
}
None => widgets.push(json!({"name": name, "value": val, "at": name})),
}
}
nodes.push(json!({"id": id, "class": n["class_type"], "title": n["_meta"]["title"], "mode": "on", "widgets": widgets, "inputs": inputs, "outputs": [], "note": false}));
}
if nodes.is_empty() {
return Err("no nodes with a class_type".into());
}
Ok(json!({"format": "api", "nodes": nodes, "links": links, "groups": []}))
}
/// A board's value for a setting in the setting's own type: "30" for a number is 30, "true" for a flag is true.
fn coerce(old: &J, new: &J) -> Result<J, String> {
let Some(s) = new.as_str() else { return Ok(new.clone()) };
Ok(match old {
J::Number(n) if n.is_i64() || n.is_u64() => J::from(s.trim().parse::<i64>().map_err(|_| format!("{s:?} isn't a whole number"))?),
J::Number(_) => json!(s.trim().parse::<f64>().map_err(|_| format!("{s:?} isn't a number"))?),
J::Bool(_) => J::Bool(match s.trim() { "true" | "on" | "yes" => true, "false" | "off" | "no" => false, _ => return Err(format!("{s:?} isn't true or false")) }),
_ => new.clone(),
})
}
/// A board's edits written into the workflow: `{widgets: [{node, name, value}], modes: [{node, mode: on|bypass|mute}],
/// notes: [{node?, text}]}` (a note with no node is a new Note node). Returns how many changes it made.
pub fn set(v: &mut J, changes: &J, schema: &Schema) -> Result<usize, String> {
let mut n_changed = 0;
if v["nodes"].is_array() {
let find = |v: &mut J, id: &str| -> Result<usize, String> {
v["nodes"].as_array().unwrap().iter().position(|n| id_of(n) == id).ok_or(format!("the workflow has no node {id}"))
};
for c in changes["widgets"].as_array().into_iter().flatten() {
let (id, name) = (c["node"].as_str().unwrap_or_default(), c["name"].as_str().unwrap_or_default());
let k = find(v, id)?;
let n = &mut v["nodes"][k];
let at = ui_widgets(n, schema).into_iter().find(|w| w["name"] == name).map(|w| w["at"].clone()).ok_or(format!("node {id} has no setting {name}"))?;
let slot = match &at { J::String(key) => &mut n["widgets_values"][key.as_str()], _ => &mut n["widgets_values"][at.as_u64().unwrap_or(0) as usize] };
let new = coerce(slot, &c["value"])?;
if *slot != new {
*slot = new;
n_changed += 1;
}
}
for c in changes["modes"].as_array().into_iter().flatten() {
let id = c["node"].as_str().unwrap_or_default();
let m = match c["mode"].as_str() { Some("on") => 0, Some("mute") => 2, Some("bypass") => 4, other => return Err(format!("mode {other:?}: on, bypass or mute")) };
let k = find(v, id)?;
if v["nodes"][k]["mode"].as_i64().unwrap_or(0) != m {
v["nodes"][k]["mode"] = J::from(m);
n_changed += 1;
}
}
for c in changes["notes"].as_array().into_iter().flatten() {
let text = c["text"].as_str().ok_or("a note needs its text")?;
if let Some(id) = c["node"].as_str() {
let k = find(v, id)?;
if v["nodes"][k]["widgets_values"][0] != text {
v["nodes"][k]["widgets_values"] = json!([text]);
n_changed += 1;
}
continue;
}
// a new note goes right of everything, so it covers nothing
let nodes = v["nodes"].as_array().unwrap();
let right = nodes.iter().map(|n| n["pos"][0].as_f64().unwrap_or(0.0) + n["size"][0].as_f64().unwrap_or(0.0)).fold(0.0, f64::max);
let top = nodes.iter().filter_map(|n| n["pos"][1].as_f64()).fold(f64::MAX, f64::min);
let id = v["last_node_id"].as_i64().unwrap_or(0).max(nodes.iter().filter_map(|n| n["id"].as_i64()).max().unwrap_or(0)) + 1;
let mut note = Map::new();
for (k, val) in [("id", json!(id)), ("type", json!("Note")), ("pos", json!([right + 60.0, if top == f64::MAX { 0.0 } else { top }])), ("size", json!([320, 120])), ("flags", json!({})), ("order", json!(nodes.len())), ("mode", json!(0)), ("inputs", json!([])), ("outputs", json!([])), ("properties", json!({})), ("widgets_values", json!([text]))] {
note.insert(k.into(), val);
}
v["nodes"].as_array_mut().unwrap().push(J::Object(note));
v["last_node_id"] = json!(id);
n_changed += 1;
}
return Ok(n_changed);
}
if changes["modes"].as_array().is_some_and(|a| !a.is_empty()) || changes["notes"].as_array().is_some_and(|a| !a.is_empty()) {
return Err("an API-format workflow keeps no bypass or notes: save the workflow from ComfyUI's editor (UI format) to have them".into());
}
let api = if v["prompt"].is_object() { &mut v["prompt"] } else { v };
for c in changes["widgets"].as_array().into_iter().flatten() {
let (id, name) = (c["node"].as_str().unwrap_or_default(), c["name"].as_str().unwrap_or_default());
let slot = api.get_mut(id).and_then(|n| n["inputs"].get_mut(name)).ok_or(format!("node {id} has no setting {name}"))?;
if link(slot).is_some() {
return Err(format!("node {id}'s {name} is a link, not a setting"));
}
let new = coerce(slot, &c["value"])?;
if *slot != new {
*slot = new;
n_changed += 1;
}
}
Ok(n_changed)
}
#[cfg(test)]
mod tests {
use super::*;
fn ui() -> J {
json!({
"last_node_id": 3,
"nodes": [
{"id": 1, "type": "KSampler", "mode": 0, "pos": [0, 0], "size": [300, 260], "inputs": [{"name": "model", "type": "MODEL", "link": 7}], "outputs": [{"name": "LATENT", "type": "LATENT"}], "widgets_values": [42, "randomize", 20, 7.5, "euler", "normal", 1.0]},
{"id": 2, "type": "CheckpointLoaderSimple", "mode": 4, "pos": [-400, 0], "size": [300, 100], "outputs": [{"name": "MODEL", "type": "MODEL"}], "widgets_values": ["sd.safetensors"]},
{"id": 3, "type": "Note", "mode": 0, "pos": [0, 300], "size": [300, 100], "widgets_values": ["try 30 steps"]}
],
"links": [[7, 2, 0, 1, 0, "MODEL"]],
"groups": [{"title": "Sample", "bounding": [-20, -40, 360, 320]}]
})
}
#[test]
fn a_ui_workflow_viewed_names_settings_past_the_seed_control() {
let s = crate::schema::load();
let g = view(&ui(), &s).unwrap();
let k = &g["nodes"][0];
assert_eq!(k["widgets"][1], json!({"name": "steps", "value": 20, "at": 2}));
assert_eq!(g["nodes"][1]["mode"], "bypass");
assert_eq!(g["links"][0], json!({"from": "2", "slot": 0, "to": "1", "input": "model", "type": "MODEL"}));
assert_eq!(g["groups"][0]["title"], "Sample");
assert_eq!(g["nodes"][2]["note"], true);
}
#[test]
fn edits_go_back_into_the_workflow_in_their_own_types() {
let s = crate::schema::load();
let mut w = ui();
let n = set(&mut w, &json!({"widgets": [{"node": "1", "name": "steps", "value": "30"}, {"node": "1", "name": "cfg", "value": "6.5"}], "modes": [{"node": "2", "mode": "on"}], "notes": [{"node": "3", "text": "30 is better"}, {"text": "new idea"}]}), &s).unwrap();
assert_eq!(n, 5);
assert_eq!(w["nodes"][0]["widgets_values"], json!([42, "randomize", 30, 6.5, "euler", "normal", 1.0]));
assert_eq!(w["nodes"][1]["mode"], 0);
assert_eq!(w["nodes"][2]["widgets_values"], json!(["30 is better"]));
assert_eq!(w["nodes"][3]["type"], "Note");
assert_eq!(w["last_node_id"], 4);
assert!(set(&mut w, &json!({"widgets": [{"node": "1", "name": "steps", "value": "lots"}]}), &s).is_err());
}
#[test]
fn an_api_workflow_takes_settings_but_not_bypass() {
let s = crate::schema::load();
let mut w = json!({"1": {"class_type": "ImageScale", "inputs": {"image": ["2", 0], "width": 48}}, "2": {"class_type": "LoadImage", "inputs": {"image": "in.png"}}});
let g = view(&w, &s).unwrap();
assert_eq!(g["links"][0], json!({"from": "2", "slot": 0, "to": "1", "input": "image"}));
assert_eq!(set(&mut w, &json!({"widgets": [{"node": "1", "name": "width", "value": "64"}]}), &s).unwrap(), 1);
assert_eq!(w["1"]["inputs"]["width"], 64);
assert!(set(&mut w, &json!({"widgets": [{"node": "1", "name": "image", "value": "x"}]}), &s).is_err());
assert!(set(&mut w, &json!({"modes": [{"node": "1", "mode": "bypass"}]}), &s).is_err());
}
}
+258
View File
@@ -0,0 +1,258 @@
//! A flow written as a ComfyUI workflow (API format). A step with ComfyUI weights and no made model becomes the
//! classic chain (checkpoint, LoRAs, prompts, latent, KSampler, decode); a `comfy` step goes back as its own nodes;
//! a load becomes LoadImage, LoadVideo or LoadAudio; every other step becomes a RaeaMade node, which tools/comfy/raea_made
//! (a custom node pack) runs on made.app from inside ComfyUI (text.generate on OpenRouter, its words on a STRING output). Each output gets a Save node of its kind.
use std::collections::BTreeMap;
use serde_json::{Map, Value as J, json};
use raea_io_gen_core::flow::{Flow, Kind, Step, op, reference};
/// A step's output in the written graph: the node, the slot, what kind of thing it is.
type Out = (String, usize, Kind);
struct W {
nodes: Map<String, J>,
outs: BTreeMap<String, Out>,
/// a comfy step's outputs when it gives several slots (`slots`), in its order: `@step.N` is the Nth
slots: BTreeMap<String, Vec<Out>>,
}
impl W {
fn add(&mut self, id: String, class: &str, inputs: J) -> String {
self.nodes.insert(id.clone(), json!({"class_type": class, "inputs": inputs}));
id
}
fn link(&self, v: &J) -> Option<J> {
let r = reference(v)?;
let (n, s, _) = match crate::flow_index(v).and_then(|i| self.slots.get(r)?.get(i)) {
Some(o) => o,
None => self.outs.get(r)?,
};
Some(json!([n, s]))
}
}
fn kind_of(step: &Step, w: &W) -> Kind {
match op(&step.op).map(|o| o.1) {
Some(Kind::Any) | None => {
if step.op == "media.load" {
let p = step.inputs.get("path").or(step.inputs.get("url")).and_then(|p| p.as_str()).unwrap_or("").to_ascii_lowercase();
return if [".mp4", ".mov", ".webm", ".mkv"].iter().any(|e| p.ends_with(e)) { Kind::Video } else if [".wav", ".mp3", ".flac", ".m4a", ".ogg"].iter().any(|e| p.ends_with(e)) { Kind::Audio } else { Kind::Image };
}
let _ = w;
Kind::Image
}
Some(k) => k,
}
}
fn get<'a>(s: &'a Step, k: &str) -> Option<&'a J> {
s.inputs.get(k)
}
/// Whether a step is written as the classic sampler chain: it names ComfyUI weights and isn't sent to made.
fn local_chain(s: &Step) -> bool {
matches!(s.op.as_str(), "image.generate" | "image.edit") && get(s, "weights").is_some_and(|w| w.is_string()) && !s.model.as_deref().is_some_and(|m| m.starts_with("made:"))
}
pub fn write(flow: &Flow) -> Result<J, String> {
let mut w = W { nodes: Map::new(), outs: BTreeMap::new(), slots: BTreeMap::new() };
for id in flow.order()? {
let s = &flow.steps[&id];
let kind = kind_of(s, &w);
let out: Out = if s.op == "media.load" {
let p = get(s, "path").or(get(s, "url")).and_then(|p| p.as_str()).unwrap_or("input.png");
let name = std::path::Path::new(p).file_name().and_then(|n| n.to_str()).unwrap_or(p).to_string();
let (class, key) = match kind { Kind::Video => ("LoadVideo", "file"), Kind::Audio => ("LoadAudio", "audio"), _ => ("LoadImage", "image") };
(w.add(id.clone(), class, json!({key: name})), 0, kind)
} else if s.op == "comfy" {
comfy(&mut w, &id, s)?
} else if let Some(o) = native(&mut w, &id, s) {
o
} else if local_chain(s) {
chain(&mut w, &id, s)
} else {
made(&mut w, &id, s, kind)
};
w.outs.insert(id, out);
}
for (k, o) in flow.out.iter().enumerate() {
// one Save per output; a step giving several slots gets one per slot: save<k>, save<k>.1, save<k>.2, …
let outs = w.slots.get(o).cloned().unwrap_or_else(|| vec![w.outs[o].clone()]);
for (j, (n, slot, kind)) in outs.into_iter().enumerate() {
let (class, key) = match kind { Kind::Video => ("SaveVideo", "video"), Kind::Audio => ("SaveAudio", "audio"), Kind::Text => ("PreviewAny", "source"), _ => ("SaveImage", "images") };
let mut inputs = json!({key: [n, slot], "filename_prefix": format!("raea/{o}")});
if class == "PreviewAny" {
inputs = json!({key: [n, slot]});
}
if class == "SaveVideo" {
inputs["format"] = json!("auto");
inputs["codec"] = json!("auto");
}
w.add(if j == 0 { format!("save{k}") } else { format!("save{k}.{j}") }, class, inputs);
}
}
Ok(J::Object(w.nodes))
}
/// A `comfy` step's nodes, ids prefixed by the step's, links rewritten, bound inputs pointed at the steps they name.
fn comfy(w: &mut W, id: &str, s: &Step) -> Result<Out, String> {
let nodes = get(s, "nodes").and_then(|n| n.as_object()).ok_or(format!("step `{id}`: comfy nodes aren't an object"))?;
let bind = get(s, "bind").and_then(|b| b.as_object()).cloned().unwrap_or_default();
let pre = |n: &str| format!("{id}.{n}");
for (nid, n) in nodes {
let mut inputs = n["inputs"].as_object().cloned().unwrap_or_default();
for (name, v) in inputs.iter_mut() {
if let Some(target) = bind.get(&format!("{nid}.{name}")) {
*v = w.link(target).ok_or(format!("step `{id}` binds {nid}.{name} to {target}, which isn't written yet"))?;
} else if let Some(a) = v.as_array_mut().filter(|a| a.len() == 2 && a[1].is_u64() && a[0].is_string()) {
a[0] = json!(pre(a[0].as_str().unwrap_or_default()));
}
}
w.add(pre(nid), n["class_type"].as_str().unwrap_or_default(), J::Object(inputs));
}
let output = get(s, "output").and_then(|o| o.as_str()).ok_or(format!("step `{id}`: no output node"))?;
let class = nodes.get(output).and_then(|n| n["class_type"].as_str()).unwrap_or("");
let schema = crate::schema::load();
let slots: Vec<usize> = get(s, "slots").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_u64()).map(|x| x as usize).collect()).filter(|v: &Vec<usize>| !v.is_empty()).unwrap_or(vec![0]);
let mut outs = Vec::new();
for slot in slots {
// what the node puts out there, from the server's schema where it's known, else read from its name
let ty = schema.get(class).and_then(|c| c.outputs.get(slot)).cloned().unwrap_or_default();
outs.push(if ty == "MASK" {
// a mask is saved as the picture of it
let m = w.add(pre(&format!("{output}.picture{slot}")), "MaskToImage", json!({"mask": [pre(output), slot]}));
(m, 0, Kind::Image)
} else {
let kind = match ty.as_str() {
"VIDEO" => Kind::Video,
"AUDIO" => Kind::Audio,
"IMAGE" => Kind::Image,
_ if class.contains("Video") => Kind::Video,
_ if class.contains("Audio") => Kind::Audio,
_ => Kind::Image,
};
(pre(output), slot, kind)
});
}
let first = outs[0].clone();
if outs.len() > 1 {
w.slots.insert(id.to_string(), outs);
}
Ok(first)
}
/// raea's own image utilities as ComfyUI's core nodes: ImageCrop, ImageScale (or ScaleBy, ScaleToTotalPixels), and
/// ImageStitch chained for more than two pictures.
/// A step's setting `k`, else `d`.
fn num(s: &Step, k: &str, d: J) -> J {
get(s, k).cloned().unwrap_or(d)
}
fn native(w: &mut W, id: &str, s: &Step) -> Option<Out> {
let img = |w: &W, k: &str| get(s, k).and_then(|v| w.link(v));
let node = match s.op.as_str() {
"image.crop" => w.add(id.into(), "ImageCrop", json!({"image": img(w, "image")?, "width": num(s, "width", json!(512)), "height": num(s, "height", json!(512)), "x": num(s, "x", json!(0)), "y": num(s, "y", json!(0))})),
"image.scale" => {
let image = img(w, "image")?;
if let Some(f) = get(s, "factor") {
w.add(id.into(), "ImageScaleBy", json!({"image": image, "upscale_method": "lanczos", "scale_by": f}))
} else if let Some(mp) = get(s, "megapixels") {
w.add(id.into(), "ImageScaleToTotalPixels", json!({"image": image, "upscale_method": "lanczos", "megapixels": mp, "resolution_steps": 1}))
} else {
// contain has no core node: it scales as stretch would, to the box
let crop = if get(s, "fit").is_some_and(|f| f == "cover") { "center" } else { "disabled" };
w.add(id.into(), "ImageScale", json!({"image": image, "upscale_method": "lanczos", "width": num(s, "width", json!(0)), "height": num(s, "height", json!(0)), "crop": crop}))
}
}
"image.stitch" => {
let links: Vec<J> = get(s, "images")?.as_array()?.iter().filter_map(|v| w.link(v)).collect();
let dir = num(s, "direction", json!("right"));
let mut acc = links.first()?.clone();
let mut last = String::new();
for (k, next) in links.iter().enumerate().skip(1) {
let nid = if k + 1 == links.len() { id.to_string() } else { format!("{id}.{k}") };
last = w.add(nid, "ImageStitch", json!({"image1": acc, "image2": next, "direction": dir, "match_image_size": true, "spacing_width": 0, "spacing_color": "white"}));
acc = json!([last, 0]);
}
if last.is_empty() {
// one picture: nothing to stitch
return Some((acc[0].as_str()?.to_string(), acc[1].as_u64()? as usize, Kind::Image));
}
last
}
_ => return None,
};
Some((node, 0, Kind::Image))
}
/// The classic chain for a step with weights: checkpoint, each LoRA, the prompts, a latent (empty, or the image
/// encoded), KSampler, decode.
fn chain(w: &mut W, id: &str, s: &Step) -> Out {
let n = |k: &str| format!("{id}.{k}");
w.add(n("ckpt"), "CheckpointLoaderSimple", json!({"ckpt_name": get(s, "weights")}));
let (mut model, mut clip) = (json!([n("ckpt"), 0]), json!([n("ckpt"), 1]));
for (k, l) in get(s, "loras").and_then(|l| l.as_array()).cloned().unwrap_or_default().iter().enumerate() {
let lid = w.add(n(&format!("lora{k}")), "LoraLoader", json!({"model": model, "clip": clip, "lora_name": l["name"], "strength_model": l["strength"].as_f64().unwrap_or(1.0), "strength_clip": l["strength"].as_f64().unwrap_or(1.0)}));
(model, clip) = (json!([lid, 0]), json!([lid, 1]));
}
w.add(n("pos"), "CLIPTextEncode", json!({"clip": clip, "text": num(s, "prompt", json!(""))}));
w.add(n("neg"), "CLIPTextEncode", json!({"clip": clip, "text": num(s, "negative", json!(""))}));
let (latent, denoise) = match get(s, "image").and_then(|v| w.link(v)) {
Some(img) => {
w.add(n("enc"), "VAEEncode", json!({"pixels": img, "vae": [n("ckpt"), 2]}));
(json!([n("enc"), 0]), num(s, "strength", json!(0.75)))
}
None => {
w.add(n("latent"), "EmptyLatentImage", json!({"width": num(s, "width", json!(1024)), "height": num(s, "height", json!(1024)), "batch_size": 1}));
(json!([n("latent"), 0]), json!(1.0))
}
};
w.add(n("sample"), "KSampler", json!({
"model": model, "positive": [n("pos"), 0], "negative": [n("neg"), 0], "latent_image": latent,
"seed": num(s, "seed", json!(0)), "steps": num(s, "steps", json!(25)), "cfg": num(s, "cfg", json!(7.0)),
"sampler_name": num(s, "sampler", json!("euler")), "scheduler": num(s, "scheduler", json!("normal")), "denoise": denoise,
}));
w.add(n("decode"), "VAEDecode", json!({"samples": [n("sample"), 0], "vae": [n("ckpt"), 2]}));
(n("decode"), 0, Kind::Image)
}
/// A RaeaMade node: the op, the made model, the text inputs as settings, the rest as JSON; media as links.
fn made(w: &mut W, id: &str, s: &Step, kind: Kind) -> Out {
let mut inputs = Map::new();
let mut params = Map::new();
let mut refs = 0;
for (k, v) in &s.inputs {
let links: Vec<J> = match v {
J::Array(a) => a.iter().filter_map(|x| w.link(x)).collect(),
_ => w.link(v).into_iter().collect(),
};
if !links.is_empty() {
for l in links {
// ComfyUI inputs are one link each: a list of references becomes ref_1, ref_2, …
let name = if matches!(v, J::Array(_)) || k == "refs" { refs += 1; format!("ref_{refs}") } else { k.clone() };
inputs.insert(name, l);
}
} else if k == "prompt" || k == "text" {
inputs.insert("prompt".into(), v.clone());
} else {
params.insert(k.clone(), v.clone());
}
}
inputs.insert("op".into(), json!(s.op));
inputs.insert("model".into(), json!(s.model.as_deref().and_then(|m| m.strip_prefix("made:")).unwrap_or("auto")));
inputs.insert("params".into(), json!(J::Object(params).to_string()));
inputs.entry("prompt").or_insert(json!(""));
// RaeaMade's outputs: IMAGE, VIDEO, AUDIO, MASK, STRING
let slot = match kind { Kind::Video => 1, Kind::Audio => 2, Kind::Text => 4, _ => 0 };
let node = w.add(id.to_string(), "RaeaMade", J::Object(inputs));
if s.op == "image.remove_background" {
// the cut-out's transparency rides as the mask: joined back so it's saved
let join = w.add(format!("{id}.alpha"), "JoinImageWithAlpha", json!({"image": [node, 0], "alpha": [node, 3]}));
return (join, 0, kind);
}
(node, slot, kind)
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "raea-io-gen-core"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "Generation flows' ground: the flow format and its op table, settings, and the hosted backends a step runs on (made.app at provider cost, fal, Replicate, OpenRouter, Modal)"
[dependencies]
raea-io-home = { path = "../home" }
serde_json = "1"
sha2 = "0.10"
+90
View File
@@ -0,0 +1,90 @@
//! A made request sent to fal itself, at fal's price. made says `markupPercent: 0`, but since 2026-10-29 it rounds each
//! job up to a whole credit (10¢): a 1¢ FLUX Klein image is billed 10¢ (its /v1/cost answers providerCostCents 1,
//! customerCostCents 10). For a model made runs on fal, its catalog row says exactly how made calls fal: the endpoint
//! (`workflowId`, or `editWorkflowId` when given media), each media role's fal field (`mediaRoles`), and how settings
//! are renamed, scaled, stringified or dropped (`inputMap`, `providerParams`). So when made would charge more than the
//! provider does, the same request goes to fal directly (FAL_KEY), unless RAEA_GEN_VIA=made. A model made runs
//! elsewhere goes the same way when fal serves the same model (TWINS).
use serde_json::{Map, Value as J, json};
/// made models it runs elsewhere that fal also serves, the same model at the same setting: (made id, fal endpoint,
/// fal endpoint given pictures, fal settings that make it that model). gpt_image_2_5_fast is made_batch's
/// gpt-image-2.5-flare-low: fal's page prices low quality at 0.4-0.6¢ an image (10-29), made bills 10¢.
const TWINS: &[(&str, &str, &str, &str)] = &[
("gpt_image_2_5_fast", "openai/gpt-image-2.5/flare/text-to-image", "openai/gpt-image-2.5/flare/edit", r#"{"quality":"low"}"#),
];
fn twin(model: &J) -> Option<&'static (&'static str, &'static str, &'static str, &'static str)> {
TWINS.iter().find(|t| model["id"] == t.0)
}
/// Whether this model can go straight to fal: made runs it there (or fal serves its twin), and none of its settings
/// need made's own handling.
pub fn possible(model: &J) -> bool {
twin(model).is_some() || model["provider"] == "fal" && model["workflowId"].is_string() && !model["inputMap"].as_object().is_some_and(|m| m.values().any(|v| v["dimensions"] == true))
}
/// A made body for a twin: the prompt, pictures as image_urls, the aspect as fal's image_size, the twin's settings.
fn twin_body(t: &(&str, &str, &str, &str), made: &J) -> (String, J) {
let medias = made["medias"].as_array().cloned().unwrap_or_default();
let mut out: Map<String, J> = serde_json::from_str(t.3).unwrap_or_default();
out.insert("prompt".into(), made["prompt"].clone());
if let Some(size) = made["aspect_ratio"].as_str().and_then(|a| match a {
"1:1" => Some("square_hd"), "4:3" => Some("landscape_4_3"), "3:4" => Some("portrait_4_3"),
"16:9" => Some("landscape_16_9"), "9:16" => Some("portrait_16_9"), _ => None,
}) {
out.insert("image_size".into(), json!(size));
}
if medias.is_empty() {
return (t.1.to_string(), J::Object(out));
}
out.insert("image_urls".into(), J::Array(medias.iter().map(|m| m["value"].clone()).collect()));
(t.2.to_string(), J::Object(out))
}
/// A made body (model, prompt, medias with values as URLs, settings) as (fal endpoint, fal input).
pub fn body(model: &J, made: &J) -> Result<(String, J), String> {
if let Some(t) = twin(model) {
return Ok(twin_body(t, made));
}
let medias = made["medias"].as_array().cloned().unwrap_or_default();
let endpoint = match (medias.is_empty(), model["editWorkflowId"].as_str()) {
(false, Some(e)) => e,
_ => model["workflowId"].as_str().ok_or("no workflowId")?,
}.to_string();
let map = model["inputMap"].as_object().cloned().unwrap_or_default();
let mut out = Map::new();
for (k, v) in made.as_object().into_iter().flatten() {
if matches!(k.as_str(), "model" | "medias" | "request_id" | "max_cost_cents" | "count") {
continue;
}
let rule = map.get(k).cloned().unwrap_or(J::Null);
if rule["drop"] == true {
continue;
}
let mut v = v.clone();
if let Some(scale) = rule["scale"].as_f64() {
v = json!(v.as_f64().unwrap_or(0.0) * scale);
}
if let Some(to) = rule["values"].get(v.to_string().trim_matches('"')).or_else(|| rule["values"].get(v.as_str().unwrap_or(""))) {
v = to.clone();
} else if rule["stringify"] == true {
v = json!(v.to_string().trim_matches('"'));
}
out.insert(rule["field"].as_str().unwrap_or(k).to_string(), v);
}
let roles = model["mediaRoles"].as_object().cloned().unwrap_or_default();
for m in &medias {
let role = m["role"].as_str().unwrap_or("");
let field = roles.get(role).and_then(|f| f.as_str()).ok_or(format!("{} has no fal field for role {role}", model["id"]))?;
match field.strip_suffix("[]") {
Some(list) => out.entry(list).or_insert(json!([])).as_array_mut().ok_or("media field clash")?.push(m["value"].clone()),
None => { out.insert(field.to_string(), m["value"].clone()); }
}
}
for (k, v) in model["providerParams"].as_object().into_iter().flatten() {
out.entry(k.clone()).or_insert(v.clone());
}
Ok((endpoint, J::Object(out)))
}
+151
View File
@@ -0,0 +1,151 @@
//! fal directly, for what made doesn't carry (3D: Tripo, Meshy, Rodin, Hunyuan 3D; any niche endpoint): a step
//! whose model is `fal:<endpoint id>`. A request goes on fal's queue (queue.fal.run), is polled at the status URL it
//! hands back and read from the response URL; the files are every `url` in the response. Media go inline as data
//! URIs. The key is FAL_KEY; prices come from fal's pricing API (a unit price per image, second or request).
use std::path::Path;
use std::time::{Duration, Instant};
use serde_json::{Value as J, json};
use crate::http::{Body, call, key_header};
pub struct Fal {
headers: Vec<String>,
}
impl Fal {
pub fn from_settings() -> Result<Fal, String> {
Ok(Fal { headers: vec![key_header("FAL_KEY", "Key", "fal needs FAL_KEY in ~/.raea/env (fal.ai/dashboard/keys)")?] })
}
fn json(&self, method: &str, url: &str, body: Option<&J>) -> Result<J, String> {
let r = call(method, url, &self.headers, body.map(Body::Json).unwrap_or(Body::None), None, 120)?;
let v = r.json().map_err(|e| format!("fal {}: {e}", crate::http::redact(url)))?;
if !r.ok() {
return Err(format!("fal {} answered {}: {}", crate::http::redact(url), r.code, crate::http::clip(&v["detail"].as_str().map(str::to_string).unwrap_or(v.to_string()))));
}
Ok(v)
}
/// The endpoint's unit price in cents and what the unit is (`image`, `second`, `request`…), when fal publishes one.
pub fn price(&self, endpoint: &str) -> Result<(f64, String), String> {
let v = self.json("GET", &format!("https://api.fal.ai/v1/models/pricing?endpoint_id={endpoint}"), None)?;
let p = v["prices"].as_array().and_then(|a| a.first()).ok_or(format!("fal has no price for {endpoint}"))?;
Ok((p["unit_price"].as_f64().unwrap_or(0.0) * 100.0, p["unit"].as_str().unwrap_or("request").to_string()))
}
/// The endpoint's input fields (from its OpenAPI page), kept in ~/.cache/raea-gen/fal/: (name, is a list).
pub fn inputs(&self, endpoint: &str) -> Vec<(String, bool)> {
let cache = crate::made::cache_dir().join("fal").join(format!("{}.json", endpoint.replace('/', "__")));
let spec = std::fs::read(&cache).ok().and_then(|b| serde_json::from_slice::<J>(&b).ok()).or_else(|| {
let r = call("GET", &format!("https://fal.ai/api/openapi/queue/openapi.json?endpoint_id={endpoint}"), &[], Body::None, None, 30).ok()?;
let v = r.json().ok().filter(|_| r.ok())?;
let _ = std::fs::create_dir_all(cache.parent()?);
let _ = std::fs::write(&cache, v.to_string());
Some(v)
});
let Some(spec) = spec else { return vec![] };
spec["components"]["schemas"].as_object().into_iter().flatten().filter(|(k, _)| k.ends_with("Input")).flat_map(|(_, v)| {
v["properties"].as_object().into_iter().flatten().map(|(n, p)| (n.clone(), p["type"] == "array")).collect::<Vec<_>>()
}).collect()
}
/// A request run to the end: fal's response JSON.
/// A local file into fal's storage; its https URL, so a request carries a link rather than megabytes of data URI.
pub fn upload(&self, file: &std::path::Path) -> Result<String, String> {
let mime = crate::made::mime_of(file);
let name = file.file_name().and_then(|n| n.to_str()).unwrap_or("file");
let v = self.json("POST", "https://rest.alpha.fal.ai/storage/upload/initiate?storage_type=fal-cdn-v3", Some(&json!({"content_type": mime, "file_name": name})))?;
let (put, url) = (v["upload_url"].as_str().ok_or("fal storage: no upload_url")?, v["file_url"].as_str().ok_or("fal storage: no file_url")?);
let r = call("PUT", put, &[format!("Content-Type: {mime}")], Body::File(file), None, 600)?;
if !r.ok() {
return Err(format!("fal storage upload of {} answered {}", file.display(), r.code));
}
Ok(url.to_string())
}
pub fn run(&self, endpoint: &str, input: &J, stall: Duration) -> Result<J, String> {
let q = self.json("POST", &format!("https://queue.fal.run/{endpoint}"), Some(input))?;
let status = q["status_url"].as_str().ok_or_else(|| format!("fal queue: no status_url in {q}"))?.to_string();
let response = q["response_url"].as_str().ok_or("fal queue: no response_url")?.to_string();
let (mut seen, mut since, mut nap) = (String::new(), Instant::now(), 1);
loop {
let s = self.json("GET", &status, None)?;
let now = format!("{}:{}", s["status"], s["queue_position"]);
match s["status"].as_str() {
Some("COMPLETED") => break,
Some("FAILED" | "ERROR") => return Err(format!("fal {endpoint} failed: {s}")),
_ => {}
}
if now != seen {
(seen, since) = (now, Instant::now());
} else if since.elapsed() > stall {
let _ = self.json("PUT", &format!("{}/cancel", status.trim_end_matches("/status")), None);
return Err(format!("fal {endpoint} sat at {seen} for {}s, canceled", stall.as_secs()));
}
std::thread::sleep(Duration::from_secs(nap));
nap = (nap + 1).min(6);
}
self.json("GET", &response, None)
}
}
/// Every file URL in a response, in the order they appear (images[0].url, video.url, model_mesh.url, …).
pub fn urls(v: &J, out: &mut Vec<String>) {
match v {
J::Object(o) => {
if let Some(u) = o.get("url").and_then(|u| u.as_str()).filter(|u| u.starts_with("http")) {
out.push(u.to_string());
}
o.iter().filter(|(k, _)| k.as_str() != "url").for_each(|(_, x)| urls(x, out));
}
J::Array(a) => a.iter().for_each(|x| urls(x, out)),
_ => {}
}
}
/// A local file as a data URI, which fal's endpoints take wherever they take a URL.
pub fn data_uri(file: &Path) -> Result<String, String> {
let bytes = std::fs::read(file).map_err(|e| format!("{}: {e}", file.display()))?;
Ok(format!("data:{};base64,{}", crate::made::mime_of(file), base64(&bytes)))
}
fn base64(b: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut s = String::with_capacity(b.len().div_ceil(3) * 4);
for c in b.chunks(3) {
let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
for i in 0..4 {
s.push(if i <= c.len() { T[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
}
}
s
}
/// A step's inputs as the endpoint's fields: prompt, seed, negative_prompt; x_<name> as <name>; media into the
/// endpoint's image field (from its schema: `image_url`, `input_image_url`, `image_urls`, …).
pub fn body(inputs: &serde_json::Map<String, J>, media: &[(String, String)], fields: &[(String, bool)]) -> J {
let mut b = json!({});
for (k, v) in inputs {
match k.as_str() {
"prompt" | "seed" | "negative" => { b[if k == "negative" { "negative_prompt" } else { k.as_str() }] = v.clone(); }
k if k.starts_with("x_") => { b[&k[2..]] = v.clone(); }
_ => {}
}
}
let images: Vec<&String> = media.iter().map(|(_, u)| u).collect();
if images.is_empty() {
return b;
}
let field = |list: bool| fields.iter().find(|(n, l)| *l == list && n.contains("image_url")).map(|(n, _)| n.clone());
match (images.len(), field(false), field(true)) {
(1, Some(one), _) => b[one.as_str()] = json!(images[0]),
(_, _, Some(many)) => b[many.as_str()] = json!(images),
(_, Some(one), None) => b[one.as_str()] = json!(images[0]),
// no schema to read: fal's most common names
(1, None, None) => b["image_url"] = json!(images[0]),
_ => b["image_urls"] = json!(images),
}
b
}
+87
View File
@@ -0,0 +1,87 @@
//! Fish Audio: an audio.speech step on Fish's text-to-speech (`fish:<model>`, else `fish:s2.1-pro`), with the founder's own
//! key in FISH_API_KEY. raea sends the step's words (`text`), its `voice` as Fish's reference_id (a voice model's id
//! from fish.audio) and its `speed` as Fish's prosody speed, and keeps the MP3 that comes back. Fish bills UTF-8 bytes
//! of text ($15 a million on its price list, 11-05), so a plan quotes the words before anything is sent.
//! RAEA_FISH_API points the requests somewhere else (a test's stand-in).
use std::path::{Path, PathBuf};
use serde_json::{Map, Value as J, json};
use crate::http::{Body, call};
use crate::setting;
/// The model a bare `fish:` names.
pub const DEFAULT_MODEL: &str = "s2.1-pro";
/// Fish's price for a million UTF-8 bytes of text, in cents.
const CENTS_PER_MILLION_BYTES: f64 = 1500.0;
fn model(name: &str) -> &str {
if name.is_empty() { DEFAULT_MODEL } else { name }
}
/// What a step's words would cost, in cents (whole cents, rounded up; a short line is 1¢).
pub fn quote(text: &str) -> u64 {
((text.len() as f64) * CENTS_PER_MILLION_BYTES / 1_000_000.0).ceil().max(1.0) as u64
}
/// The JSON body Fish's /v1/tts reads, from an audio.speech step's inputs.
pub fn body(inputs: &Map<String, J>) -> Result<J, String> {
let text = inputs.get("text").and_then(J::as_str).filter(|t| !t.trim().is_empty()).ok_or("an audio.speech step on fish needs text")?;
let mut b = json!({"text": text, "format": "mp3"});
if let Some(v) = inputs.get("voice").and_then(J::as_str).filter(|v| !v.is_empty()) {
b["reference_id"] = json!(v);
}
if let Some(s) = inputs.get("speed").and_then(J::as_f64) {
if !(0.5..=2.0).contains(&s) {
return Err(format!("fish: speed is 0.5 to 2, got {s}"));
}
b["prosody"] = json!({"speed": s});
}
Ok(b)
}
/// One audio.speech step on Fish: the MP3 written beside `stem`, and what the words cost.
pub fn run(name: &str, op: &str, inputs: &Map<String, J>, stem: &Path) -> Result<(PathBuf, u64), String> {
if op != "audio.speech" {
return Err(format!("fish:{name} makes speech (audio.speech), not {op}"));
}
let key = setting("FISH_API_KEY").ok_or("fish needs your Fish Audio API key: put FISH_API_KEY=… in ~/.raea/env (fish.audio, API keys)")?;
let body = body(inputs)?;
let api = setting("RAEA_FISH_API").unwrap_or_else(|| "https://api.fish.audio".into());
let out = stem.with_extension("mp3");
let h = [format!("Authorization: Bearer {key}"), format!("model: {}", model(name))];
let r = call("POST", &format!("{}/v1/tts", api.trim_end_matches('/')), &h, Body::Json(&body), Some(&out), 600)?;
if !r.ok() {
let said = std::fs::read_to_string(&out).unwrap_or_default().chars().take(300).collect::<String>();
let _ = std::fs::remove_file(&out);
return Err(format!("fish:{} answered {}: {said}", model(name), r.code));
}
if !r.mime.starts_with("audio/") {
let _ = std::fs::remove_file(&out);
return Err(format!("fish:{} answered {} rather than audio", model(name), r.mime));
}
Ok((out, quote(body["text"].as_str().unwrap_or(""))))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_step_becomes_fishs_body() {
let i = json!({"text": "Three drops.", "voice": "abc", "speed": 0.85});
assert_eq!(body(i.as_object().unwrap()).unwrap(), json!({"text": "Three drops.", "format": "mp3", "reference_id": "abc", "prosody": {"speed": 0.85}}));
assert!(body(json!({"text": " "}).as_object().unwrap()).is_err());
assert!(body(json!({"text": "a", "speed": 3}).as_object().unwrap()).is_err());
}
#[test]
fn words_are_quoted_by_their_bytes() {
assert_eq!(quote("short"), 1);
assert_eq!(quote(&"a".repeat(10_000)), 15);
// a non-ASCII character is several bytes
assert_eq!(quote(&"語".repeat(10_000)), 45);
}
}
+225
View File
@@ -0,0 +1,225 @@
//! A flow: generation steps by what they make, not by who runs them. Each step is an op from OPS (image.generate,
//! video.generate, audio.sfx, …) with its inputs, literal or `@step` (another step's output); a step may name a model
//! (`made:kling_3_pro_i2v`, `fal:<endpoint>`, `replicate:owner/name`, `openrouter:<model>`, `modal:<endpoint>`, `comfy`,
//! `local:sao`) or leave it to the router. A step the importer couldn't name keeps its
//! ComfyUI nodes whole (`comfy`), so nothing is lost and it runs where ComfyUI runs.
//!
//! On disk it's JSON (`{"flow": 1, "steps": {...}, "out": [...]}`); agents write it in TypeScript with raea/gen's
//! flow(), which prints the same JSON.
use std::collections::BTreeMap;
use serde_json::{Map, Value as J, json};
use sha2::{Digest, Sha256};
/// What a step makes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Image,
Video,
Audio,
/// a 3D model (glb)
Mesh,
/// words (a prompt an LLM wrote): a step reading one gets its text in place of the reference
Text,
Any,
}
/// The ops a step may be: its name, what it makes, the inputs it reads (the first ones it can't go without).
pub const OPS: &[(&str, Kind, &[&str], &[&str])] = &[
("image.generate", Kind::Image, &["prompt"], &["negative", "width", "height", "aspect_ratio", "seed", "steps", "cfg", "sampler", "scheduler", "weights", "loras", "refs", "resolution"]),
("image.edit", Kind::Image, &["image", "prompt"], &["mask", "strength", "negative", "seed", "steps", "cfg", "sampler", "scheduler", "weights", "loras", "refs", "aspect_ratio", "resolution"]),
("image.upscale", Kind::Image, &["image"], &["factor", "weights"]),
("image.remove_background", Kind::Image, &["image"], &[]),
("image.expand", Kind::Image, &["image", "aspect_ratio"], &["prompt"]),
// run by raea itself (io/gen native.rs), no model: ComfyUI's ImageCrop, ImageScale* and ImageStitch
("image.crop", Kind::Image, &["image", "width", "height"], &["x", "y"]),
("image.scale", Kind::Image, &["image"], &["width", "height", "factor", "megapixels", "fit"]),
("image.stitch", Kind::Image, &["images"], &["direction"]),
("video.generate", Kind::Video, &[], &["prompt", "negative", "sampler", "scheduler", "seconds", "fps", "width", "height", "aspect_ratio", "start_image", "end_image", "refs", "audio", "seed", "steps", "cfg", "weights", "loras", "resolution"]),
("video.edit", Kind::Video, &["video", "prompt"], &["refs", "seconds", "aspect_ratio", "resolution"]),
("video.reframe", Kind::Video, &["video", "aspect_ratio"], &[]),
("video.upscale", Kind::Video, &["video"], &["factor"]),
("audio.music", Kind::Audio, &["prompt"], &["seconds", "seed", "weights"]),
("audio.sfx", Kind::Audio, &["prompt"], &["seconds", "video", "seed", "weights"]),
("audio.speech", Kind::Audio, &["text"], &["voice", "speed"]),
("mesh.generate", Kind::Mesh, &[], &["prompt", "image", "refs", "seed", "texture"]),
("text.generate", Kind::Text, &["prompt"], &["system", "image", "refs"]),
("media.load", Kind::Any, &[], &["path", "url"]),
("comfy", Kind::Any, &["nodes", "output"], &["bind", "slots"]),
];
pub fn op(name: &str) -> Option<&'static (&'static str, Kind, &'static [&'static str], &'static [&'static str])> {
OPS.iter().find(|o| o.0 == name)
}
#[derive(Clone, Debug, PartialEq)]
pub struct Step {
pub op: String,
pub inputs: Map<String, J>,
/// `made:<id>`, `comfy`, `replicate`, `local:<name>`, or None for the router's choice
pub model: Option<String>,
/// how the step came to be (`comfy: KSampler 3 ← CheckpointLoaderSimple 4, …`), for a reader
pub from: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Flow {
pub steps: BTreeMap<String, Step>,
pub out: Vec<String>,
}
/// `@id` (or `@id.N`, an output by index): the step it points at.
pub fn reference(v: &J) -> Option<&str> {
v.as_str()?.strip_prefix('@').map(|r| r.split_once('.').map_or(r, |(step, _)| step))
}
/// Which of a step's files a reference names: `@step.N` the Nth (a batch's pictures); None for `@step`.
pub fn index(v: &J) -> Option<usize> {
v.as_str()?.strip_prefix('@')?.split_once('.')?.1.parse().ok()
}
/// Every step a value points at, nested in arrays and objects too (`refs: ["@a", "@b"]`).
pub fn references(v: &J, out: &mut Vec<String>) {
match v {
J::String(_) => out.extend(reference(v).map(str::to_string)),
J::Array(a) => a.iter().for_each(|x| references(x, out)),
J::Object(o) => o.values().for_each(|x| references(x, out)),
_ => {}
}
}
impl Step {
pub fn new(op: &str, inputs: J) -> Step {
Step { op: op.into(), inputs: inputs.as_object().cloned().unwrap_or_default(), model: None, from: None }
}
pub fn needs(&self) -> Vec<String> {
let mut out = Vec::new();
// a comfy step's own nodes link by [id, slot], never by @; only its bindings point at other steps
let inputs: Vec<&J> = if self.op == "comfy" { self.inputs.get("bind").into_iter().collect() } else { self.inputs.values().collect() };
inputs.into_iter().for_each(|v| references(v, &mut out));
out.sort();
out.dedup();
out
}
}
impl Flow {
pub fn parse(v: &J) -> Result<Flow, String> {
if v["flow"].as_u64() != Some(1) {
return Err("not a flow: it says {\"flow\": 1, \"steps\": {...}} at the top".into());
}
let mut f = Flow::default();
for (id, s) in v["steps"].as_object().ok_or("a flow's steps are an object by id")? {
let op = s["op"].as_str().ok_or(format!("step `{id}` has no op"))?;
let mut step = Step::new(op, s["in"].clone());
step.model = s["model"].as_str().map(str::to_string);
step.from = s["from"].as_str().map(str::to_string);
f.steps.insert(id.clone(), step);
}
f.out = v["out"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();
f.check()?;
Ok(f)
}
pub fn to_json(&self) -> J {
let steps: Map<String, J> = self.steps.iter().map(|(id, s)| {
let mut o = json!({"op": s.op, "in": s.inputs});
if let Some(m) = &s.model {
o["model"] = json!(m);
}
if let Some(f) = &s.from {
o["from"] = json!(f);
}
(id.clone(), o)
}).collect();
json!({"flow": 1, "steps": steps, "out": self.out})
}
/// Ops known, required inputs given, references to steps that exist, no cycles, outputs that exist.
pub fn check(&self) -> Result<(), String> {
for (id, s) in &self.steps {
let (_, _, required, optional) = op(&s.op).ok_or_else(|| format!("step `{id}`: unknown op `{}` (ops: {})", s.op, OPS.iter().map(|o| o.0).collect::<Vec<_>>().join(", ")))?;
for r in required.iter() {
if !s.inputs.contains_key(*r) {
return Err(format!("step `{id}` ({}) needs `{r}`", s.op));
}
}
if s.op != "comfy" {
if let Some(k) = s.inputs.keys().find(|k| !required.contains(&k.as_str()) && !optional.contains(&k.as_str()) && !k.starts_with("x_")) {
return Err(format!("step `{id}` ({}) doesn't take `{k}` (it takes {}; a model's own setting goes in as x_<name>)", s.op, required.iter().chain(optional.iter()).copied().collect::<Vec<_>>().join(", ")));
}
}
for n in s.needs() {
if !self.steps.contains_key(&n) {
return Err(format!("step `{id}` points at `@{n}`, which isn't a step"));
}
}
}
for o in &self.out {
if !self.steps.contains_key(o) {
return Err(format!("out names `{o}`, which isn't a step"));
}
}
self.order().map(|_| ())
}
/// Steps in an order that runs each after what it reads.
pub fn order(&self) -> Result<Vec<String>, String> {
let (mut done, mut out) = (std::collections::BTreeSet::new(), Vec::new());
while out.len() < self.steps.len() {
let ready: Vec<String> = self.steps.iter().filter(|(id, s)| !done.contains(*id) && s.needs().iter().all(|n| done.contains(n))).map(|(id, _)| id.clone()).collect();
if ready.is_empty() {
let left: Vec<&String> = self.steps.keys().filter(|k| !done.contains(*k)).collect();
return Err(format!("these steps read each other in a circle: {left:?}"));
}
for r in ready {
done.insert(r.clone());
out.push(r);
}
}
Ok(out)
}
/// Each step's key: a hash of its op, model and inputs, with each reference replaced by that step's key, so a
/// step's key changes when anything it's made from does. Cached outputs are found by it.
pub fn keys(&self) -> Result<BTreeMap<String, String>, String> {
let mut keys = BTreeMap::new();
for id in self.order()? {
let s = &self.steps[&id];
let inputs = J::Object(s.inputs.clone());
let resolved = substitute(&inputs, &|r| keys.get(r).map(|k: &String| format!("key:{k}")));
let text = format!("{}\u{0}{}\u{0}{}", s.op, s.model.as_deref().unwrap_or(""), canonical(&resolved));
keys.insert(id, format!("{:x}", Sha256::digest(text.as_bytes()))[..24].to_string());
}
Ok(keys)
}
}
/// A value with every `@ref` string replaced by what `f` gives for it (or kept).
pub fn substitute(v: &J, f: &dyn Fn(&str) -> Option<String>) -> J {
match v {
J::String(_) => reference(v).and_then(f).map(J::String).unwrap_or_else(|| v.clone()),
J::Array(a) => J::Array(a.iter().map(|x| substitute(x, f)).collect()),
J::Object(o) => J::Object(o.iter().map(|(k, x)| (k.clone(), substitute(x, f))).collect()),
_ => v.clone(),
}
}
/// JSON with object keys sorted and whole floats written as integers, so the same inputs always hash the same.
pub fn canonical(v: &J) -> String {
match v {
J::Object(o) => {
let mut ks: Vec<&String> = o.keys().collect();
ks.sort();
format!("{{{}}}", ks.iter().map(|k| format!("{}:{}", J::String((*k).clone()), canonical(&o[*k]))).collect::<Vec<_>>().join(","))
}
J::Array(a) => format!("[{}]", a.iter().map(canonical).collect::<Vec<_>>().join(",")),
J::Number(n) => match n.as_f64() {
Some(f) if f.fract() == 0.0 && f.abs() < 1e15 => format!("{}", f as i64),
_ => n.to_string(),
},
_ => v.to_string(),
}
}
+122
View File
@@ -0,0 +1,122 @@
//! HTTP through curl (raea's io crates link no HTTP client). The URL, headers and body go to curl's stdin as its
//! config, so a key never shows in the process list.
use std::io::Write;
use std::path::Path;
use serde_json::Value as J;
/// What came back: the status, the content type and the body (empty when it went to a file).
pub struct Reply {
pub code: u16,
pub mime: String,
pub body: Vec<u8>,
}
impl Reply {
pub fn ok(&self) -> bool {
(200..300).contains(&self.code)
}
pub fn json(&self) -> Result<J, String> {
serde_json::from_slice(&self.body).map_err(|e| format!("not JSON ({e}): {}", self.text(200)))
}
pub fn text(&self, n: usize) -> String {
String::from_utf8_lossy(&self.body).chars().take(n).collect()
}
}
/// What to send: a JSON body, a file's bytes (PUT uploads), or nothing.
pub enum Body<'a> {
None,
Json(&'a J),
File(&'a Path),
/// form fields and files, as curl's -F takes them (ComfyUI's /upload/image)
Form(&'a [(String, String)]),
}
fn q(s: &str) -> String {
format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
}
/// One request. `out` takes the body when given (downloads); otherwise it comes back in the reply.
pub fn call(method: &str, url: &str, headers: &[String], body: Body, out: Option<&Path>, secs: u32) -> Result<Reply, String> {
raea_io_home::offline(&format!("raea gen's request to {}", redact(url)))?;
let mut config = format!("url = {}\nrequest = {}\nheader = \"User-Agent: raea-gen\"\nmax-time = {secs}\nlocation\n", q(url), q(method));
for h in headers {
config += &format!("header = {}\n", q(h));
}
match body {
Body::None => {}
Body::Json(j) => config += &format!("header = \"Content-Type: application/json\"\ndata-binary = {}\n", q(&j.to_string())),
Body::File(p) => config += &format!("upload-file = {}\n", q(&p.display().to_string())),
Body::Form(fields) => {
for (k, v) in fields {
config += &format!("form = {}\n", q(&format!("{k}={v}")));
}
}
}
let tmp;
let dest = match out {
Some(p) => p,
None => {
// one name per call: two requests at once in one process never share a file
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
tmp = std::env::temp_dir().join(format!("raea-gen-{}-{n}", std::process::id()));
&tmp
}
};
let mut child = std::process::Command::new("curl")
.args(["-sS", "-K", "-", "-o"])
.arg(dest)
.args(["-w", "%{http_code} %{content_type}"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| format!("curl: {e}"))?;
child.stdin.take().ok_or("curl: no stdin")?.write_all(config.as_bytes()).map_err(|e| format!("curl: {e}"))?;
let o = child.wait_with_output().map_err(|e| format!("curl: {e}"))?;
if !o.status.success() {
let _ = out.is_none().then(|| std::fs::remove_file(dest));
return Err(format!("{method} {}: {}", redact(url), String::from_utf8_lossy(&o.stderr).trim()));
}
let w = String::from_utf8_lossy(&o.stdout).to_string();
let (code, mime) = w.split_once(' ').unwrap_or((&w, ""));
let body = if out.is_none() {
let b = std::fs::read(dest).unwrap_or_default();
let _ = std::fs::remove_file(dest);
b
} else {
Vec::new()
};
Ok(Reply { code: code.parse().unwrap_or(0), mime: mime.to_string(), body })
}
/// A URL as an error may show it: no query (signed links carry their signature there).
/// The Authorization header for a hosted service's key, read with crate::setting: `Authorization: SCHEME KEY`,
/// or `missing` (where to get one) when it isn't set.
pub fn key_header(name: &str, scheme: &str, missing: &str) -> Result<String, String> {
Ok(format!("Authorization: {scheme} {}", crate::setting(name).ok_or(missing)?))
}
pub fn redact(url: &str) -> &str {
url.split('?').next().unwrap_or(url)
}
/// Text for an error: data URIs cut to their head, the whole kept under 600 characters.
pub fn clip(s: &str) -> String {
let mut out = String::new();
let mut rest = s;
while let Some(i) = rest.find("data:") {
out += &rest[..i];
let tail = &rest[i..];
let end = tail.find(|c: char| c == '"' || c == ' ' || c == '\'').unwrap_or(tail.len());
out += &format!("{}…", &tail[..end.min(40)]);
rest = &tail[end..];
}
out += rest;
out.chars().take(600).collect()
}
+19
View File
@@ -0,0 +1,19 @@
//! 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
//! are raea-io-gen.
pub mod direct;
pub mod fal;
pub mod fish;
pub mod flow;
pub mod http;
pub mod made;
pub mod modal;
pub mod openrouter;
pub mod replicate;
pub mod types;
/// A setting: the environment, then raea's settings file (raea_io_home::setting).
pub use raea_io_home::setting;
Loaded 100 of 384 files, more files were not shown because too many files have changed in this diff. Show more