mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
917d41b12a |
No files matched your search
Generated
+10
-1
@@ -13801,6 +13801,7 @@ name = "raea-app-engines"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-app-forma",
|
||||
"raea-app-interchange",
|
||||
"raea-app-tools",
|
||||
"raea-io-home",
|
||||
@@ -13820,7 +13821,6 @@ dependencies = [
|
||||
"fastrand",
|
||||
"raea-app-check",
|
||||
"raea-app-double",
|
||||
"raea-io-clef",
|
||||
"raea-io-home",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint",
|
||||
@@ -13830,6 +13830,14 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-forma"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-io-home",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-game"
|
||||
version = "0.1.0"
|
||||
@@ -14065,6 +14073,7 @@ name = "raea-app-tools"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-app-forma",
|
||||
"raea-app-motion",
|
||||
"raea-io-assets",
|
||||
"raea-io-gen",
|
||||
|
||||
@@ -237,6 +237,7 @@ members = [
|
||||
"apps/tools",
|
||||
"apps/motion",
|
||||
"apps/engines",
|
||||
"apps/forma",
|
||||
"apps/interchange",
|
||||
"apps/judge",
|
||||
"apps/make",
|
||||
|
||||
@@ -9,6 +9,8 @@ description = "The `raea` verbs that script other engines from TypeScript: Blend
|
||||
[dependencies]
|
||||
# Blender found or downloaded, its scripts in Python, and the helpers Godot's setup shares (apps/tools/src/blender.rs)
|
||||
raea-app-tools = { path = "../tools" }
|
||||
# forma, a headless modeller (GPL-3.0-or-later), downloaded and run as its own program, its .glb fixed after (apps/forma)
|
||||
raea-app-forma = { path = "../forma" }
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# a TypeScript script bundled and run on raea's engine, posting raea/blender's batches to the bridge (blender.post)
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
|
||||
+10
-2
@@ -1,6 +1,8 @@
|
||||
//! The verbs that script other engines from TypeScript: Blender (`raea setup blender`, `raea blender run SCRIPT.py|.ts`;
|
||||
//! finding and setting Blender up is apps/tools/src/blender.rs) and Godot with GodotJS (`raea setup godot`,
|
||||
//! `raea godot run|types|open`; sdk/blender and sdk/godot are their TypeScript sides).
|
||||
//! `raea godot run|types|open`; sdk/blender and sdk/godot are their TypeScript sides). forma, a headless modeller for
|
||||
//! hard-surface parts, runs the same way: downloaded, run as its own program, never linked (`raea setup forma`,
|
||||
//! `raea forma`; apps/forma).
|
||||
|
||||
/// the Blender a TypeScript script drives (`raea blender run SCRIPT.ts`, sdk/blender)
|
||||
pub mod blender_bridge;
|
||||
@@ -16,11 +18,16 @@ pub mod shot;
|
||||
pub mod round;
|
||||
|
||||
use raea_app_tools::blender;
|
||||
/// `raea setup forma` and `raea forma`: forma (GPL-3.0-or-later) downloaded and run as its own program (apps/forma)
|
||||
pub use raea_app_forma as forma;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// The CLI's verbs here, or None for any other: `setup blender|godot`, `blender ...` and `godot ...`.
|
||||
/// The CLI's verbs here, or None for any other: `setup blender|godot|forma`, `blender ...`, `godot ...` and `forma ...`.
|
||||
pub fn cli(args: &[String]) -> Option<R<String>> {
|
||||
if let Some(done) = forma::cli(args) {
|
||||
return Some(done);
|
||||
}
|
||||
let second = args.get(1).map(String::as_str);
|
||||
Some(match (args.first()?.as_str(), second) {
|
||||
("setup", Some("blender")) => blender::setup(&args[2..]),
|
||||
@@ -54,5 +61,6 @@ mod tests {
|
||||
assert!(cli(&args("render edit.tsx")).is_none());
|
||||
assert!(cli(&[]).is_none());
|
||||
assert!(cli(&args("godot")).unwrap().unwrap_err().contains(godot::USAGE));
|
||||
assert!(cli(&args("forma")).is_some());
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,6 @@ raea-sys-fingerprint = { path = "../../systems/fingerprint" }
|
||||
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
|
||||
# score --ask: each flag asked again of the decision model (docs/ask.feature AK8)
|
||||
raea-app-double = { path = "../double" }
|
||||
# the critic a note is read by: a fresh session of the project's own agent (critic.rs)
|
||||
raea-io-clef = { path = "../../io/clef" }
|
||||
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
|
||||
# the encoders and the columns they make
|
||||
raea-sys-columns = { path = "../../systems/columns" }
|
||||
|
||||
@@ -21,13 +21,13 @@ use std::path::Path;
|
||||
|
||||
pub use serve::serve;
|
||||
|
||||
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
|
||||
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
|
||||
|
||||
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
|
||||
pub type Eval = fn(&Path) -> Result<String, String>;
|
||||
|
||||
/// The flags each verb takes, and whether each takes a value
|
||||
pub(crate) const FLAGS: [(&str, bool); 30] = [
|
||||
pub(crate) const FLAGS: [(&str, bool); 31] = [
|
||||
("--fp", true),
|
||||
("--was", true),
|
||||
("--to", true),
|
||||
@@ -51,6 +51,7 @@ pub(crate) const FLAGS: [(&str, bool); 30] = [
|
||||
("--as", true),
|
||||
("--against", true),
|
||||
("--profile", true),
|
||||
("--by", true),
|
||||
("--ask", true),
|
||||
("--tally", false),
|
||||
("--bad", false),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT` has a fresh session of
|
||||
//! the project's own agent (its host's critic, raea_io_clef::critic; never one raea or the agent picks) read each pinned note on the project's videos into a kind (defect, direction, praise or
|
||||
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT [--by kimi|claude]`
|
||||
//! has a fresh agent session read each pinned note on the project's videos into a kind (defect, direction, praise or
|
||||
//! both) and an axis from the fingerprint's own axes, kept in the fingerprint's readings.jsonl. Nothing trains on them
|
||||
//! yet: `raea fingerprint readings --ask N` puts N readings to the person as questions in the app (`raea show
|
||||
//! --question`, answers to the "fingerprint" inbox), `readings --tally` counts how often the person agreed, and only
|
||||
@@ -99,9 +99,30 @@ pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// One fresh session of the project's own agent, through its host (raea_io_clef::critic): its words
|
||||
fn ask(cwd: &Path, p: &str) -> Result<String, String> {
|
||||
raea_io_clef::critic::ask(cwd, p)
|
||||
/// One fresh session's words: kimi's or claude's stream, the assistant's text joined
|
||||
fn ask(by: &str, p: &str) -> Result<String, String> {
|
||||
let mut c = std::process::Command::new(by);
|
||||
match by {
|
||||
"kimi" => c.args(["-p", p, "--output-format", "stream-json"]),
|
||||
"claude" => c.args(["-p", p, "--output-format", "stream-json", "--verbose", "--allowedTools", ""]),
|
||||
o => return Err(format!("--by {o}: kimi or claude")),
|
||||
};
|
||||
let out = c.output().map_err(|e| format!("couldn't run {by}: {e}"))?;
|
||||
let mut text = String::new();
|
||||
for line in String::from_utf8_lossy(&out.stdout).lines() {
|
||||
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
|
||||
let content = if v["role"] == "assistant" { &v["content"] } else if v["type"] == "assistant" { &v["message"]["content"] } else if v["type"] == "result" { &v["result"] } else { continue };
|
||||
match content {
|
||||
Value::String(s) => text += s,
|
||||
Value::Array(a) => a.iter().filter_map(|p| p["text"].as_str()).for_each(|s| text += s),
|
||||
_ => {}
|
||||
}
|
||||
text.push('\n');
|
||||
}
|
||||
if text.trim().is_empty() {
|
||||
return Err(format!("{by} said nothing: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
pub fn readings_of(dir: &Folder) -> Vec<Reading> {
|
||||
@@ -112,12 +133,12 @@ pub fn write_readings(dir: &Folder, r: &[Reading]) -> std::io::Result<()> {
|
||||
std::fs::write(dir.dir.join("readings.jsonl"), r.iter().filter_map(|x| serde_json::to_string(x).ok()).map(|l| l + "\n").collect::<String>())
|
||||
}
|
||||
|
||||
/// `raea fingerprint read PROJECT`
|
||||
/// `raea fingerprint read PROJECT [--by kimi|claude]`
|
||||
pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let run = || -> Result<String, String> {
|
||||
let w = words(args)?;
|
||||
let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p));
|
||||
let by = "agent";
|
||||
let by = flag(args, "--by").unwrap_or("kimi");
|
||||
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
|
||||
let fp = dir.read(None).map_err(|e| e.to_string())?;
|
||||
let mut notes = pinned(&project);
|
||||
@@ -127,15 +148,15 @@ pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
|
||||
return Ok(format!("no new pinned notes in {}", project.display()));
|
||||
}
|
||||
for chunk in notes.chunks_mut(40) {
|
||||
let text = ask(&project, &prompt(&fp, chunk))?;
|
||||
let ans = answer(&text).ok_or_else(|| "the critic answered no readings JSON".to_string())?;
|
||||
let text = ask(by, &prompt(&fp, chunk))?;
|
||||
let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?;
|
||||
fold(chunk, &fp, &ans, by);
|
||||
eprintln!("read {} notes", chunk.len());
|
||||
}
|
||||
let read = notes.iter().filter(|n| !n.kind.is_empty()).count();
|
||||
kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));
|
||||
write_readings(&dir, &kept).map_err(|e| e.to_string())?;
|
||||
Ok(format!("{read} notes read into labels by a fresh session of the project's agent, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
|
||||
Ok(format!("{read} notes read into labels by {by}, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
|
||||
};
|
||||
match run() {
|
||||
Ok(o) => {
|
||||
@@ -264,7 +285,7 @@ mod tests {
|
||||
let fp = raea_sys_fingerprint::taxonomy::base("me");
|
||||
let mut n = vec![Reading { note: "n1".into(), ..Default::default() }, Reading { note: "n2".into(), ..Default::default() }, Reading { note: "n3".into(), ..Default::default() }];
|
||||
let ans = answer("I read them.\n[{\"id\": \"n1\", \"kind\": \"defect\", \"axis\": \"glitch\"}, {\"id\": \"n2\", \"kind\": \"direction\", \"axis\": \"made up\"}, {\"id\": \"n3\", \"kind\": \"rant\", \"axis\": null}]").unwrap();
|
||||
fold(&mut n, &fp, &ans, "agent");
|
||||
fold(&mut n, &fp, &ans, "kimi");
|
||||
assert_eq!((n[0].kind.as_str(), n[0].axis.as_deref()), ("defect", Some("glitch")));
|
||||
assert_eq!((n[1].kind.as_str(), n[1].axis.as_deref()), ("direction", None), "an axis the fingerprint hasn't is dropped");
|
||||
assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading");
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "raea-app-forma"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea setup forma` and `raea forma`: forma (GPL-3.0-or-later) downloaded and run as its own program, its .glb fixed after"
|
||||
|
||||
[dependencies]
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# the .glb forma writes, read and written back with its colours linear and its normals smoothed (glb.rs)
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,340 @@
|
||||
//! The .glb forma writes, fixed for a renderer that reads glTF as the spec says (docs/forma.feature FM3, FM4). forma
|
||||
//! 0.4.4 writes a material's colour as it was typed (sRGB, as a person picks one) into baseColorFactor, which glTF reads
|
||||
//! as linear, so every colour comes out pale; and it writes one normal per face, so a cylinder shows its facets. The fix
|
||||
//! converts the colours, and gives each corner the mean of the faces around it that meet its own at under `smooth`
|
||||
//! degrees, so a box keeps its edges and a cylinder's side turns round. Only the JSON's colours and the normals' bytes
|
||||
//! change: positions, indices, UVs and the file's layout stay as forma wrote them. A fixed file is marked in
|
||||
//! asset.extras and left alone after, so fixing twice never darkens it twice.
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// The mark a fixed file carries in asset.extras.
|
||||
pub const MARK: &str = "raea_forma";
|
||||
|
||||
const JSON: u32 = 0x4E4F_534A;
|
||||
const BIN: u32 = 0x004E_4942;
|
||||
const FLOAT: u64 = 5126;
|
||||
|
||||
/// What a fix changed.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct Fixed {
|
||||
/// materials whose colour was made linear
|
||||
pub colours: usize,
|
||||
/// mesh primitives whose normals were smoothed
|
||||
pub primitives: usize,
|
||||
/// the file was fixed before and is unchanged
|
||||
pub already: bool,
|
||||
}
|
||||
|
||||
/// Fixes a .glb in place (written beside it, then renamed over it).
|
||||
pub fn fix_file(path: &Path, smooth: Option<f32>) -> R<Fixed> {
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let (out, fixed) = fix(&bytes, smooth).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
if !fixed.already {
|
||||
let tmp = path.with_extension("raea-tmp");
|
||||
std::fs::write(&tmp, out).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
||||
std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
}
|
||||
Ok(fixed)
|
||||
}
|
||||
|
||||
/// The fixed file's bytes. `smooth`: the largest angle in degrees between two faces whose shared corners are smoothed;
|
||||
/// None keeps forma's normals.
|
||||
pub fn fix(glb: &[u8], smooth: Option<f32>) -> R<(Vec<u8>, Fixed)> {
|
||||
let (mut doc, mut bin) = read(glb)?;
|
||||
if doc["asset"]["extras"][MARK].is_object() {
|
||||
return Ok((glb.to_vec(), Fixed { colours: 0, primitives: 0, already: true }));
|
||||
}
|
||||
let colours = linear_colours(&mut doc);
|
||||
let primitives = match smooth {
|
||||
Some(deg) => smooth_normals(&doc, &mut bin, deg)?,
|
||||
None => 0,
|
||||
};
|
||||
let asset = doc.as_object_mut().ok_or("the glTF JSON isn't an object")?.entry("asset").or_insert_with(|| json!({"version": "2.0"}));
|
||||
let extras = asset.as_object_mut().ok_or("asset isn't an object")?.entry("extras").or_insert_with(|| json!({}));
|
||||
if let Some(e) = extras.as_object_mut() {
|
||||
e.insert(MARK.into(), json!({"colours": "linear", "smooth": smooth}));
|
||||
}
|
||||
Ok((write(&doc, &bin), Fixed { colours, primitives, already: false }))
|
||||
}
|
||||
|
||||
/// The JSON chunk and the BIN chunk (empty when there is none).
|
||||
pub fn read(glb: &[u8]) -> R<(Value, Vec<u8>)> {
|
||||
let u32_at = |at: usize| glb.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
if glb.get(..4) != Some(b"glTF") || u32_at(4) != Some(2) {
|
||||
return Err("not a glTF 2.0 binary (.glb)".into());
|
||||
}
|
||||
let (len, kind) = (u32_at(12).ok_or("no JSON chunk")? as usize, u32_at(16).ok_or("no JSON chunk")?);
|
||||
let text = glb.get(20..20 + len).filter(|_| kind == JSON).ok_or("the first chunk isn't JSON")?;
|
||||
let doc: Value = serde_json::from_slice(text).map_err(|e| format!("the glTF JSON: {e}"))?;
|
||||
let at = 20 + len;
|
||||
let bin = match (u32_at(at), u32_at(at + 4)) {
|
||||
(Some(n), Some(BIN)) => glb.get(at + 8..at + 8 + n as usize).ok_or("the BIN chunk runs past the file")?.to_vec(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
Ok((doc, bin))
|
||||
}
|
||||
|
||||
/// A .glb of a JSON document and a BIN chunk, each padded to four bytes as glTF asks (the JSON with spaces).
|
||||
pub fn write(doc: &Value, bin: &[u8]) -> Vec<u8> {
|
||||
let mut text = serde_json::to_vec(doc).unwrap_or_default();
|
||||
while !text.len().is_multiple_of(4) {
|
||||
text.push(b' ');
|
||||
}
|
||||
let mut data = bin.to_vec();
|
||||
while !data.len().is_multiple_of(4) {
|
||||
data.push(0);
|
||||
}
|
||||
let total = 12 + 8 + text.len() + if data.is_empty() { 0 } else { 8 + data.len() };
|
||||
let mut out = Vec::with_capacity(total);
|
||||
out.extend_from_slice(b"glTF");
|
||||
out.extend_from_slice(&2u32.to_le_bytes());
|
||||
out.extend_from_slice(&(total as u32).to_le_bytes());
|
||||
out.extend_from_slice(&(text.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&JSON.to_le_bytes());
|
||||
out.extend_from_slice(&text);
|
||||
if !data.is_empty() {
|
||||
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&BIN.to_le_bytes());
|
||||
out.extend_from_slice(&data);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// sRGB's transfer undone: the linear value glTF's baseColorFactor holds.
|
||||
pub fn srgb_to_linear(c: f64) -> f64 {
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
|
||||
/// Every material's baseColorFactor made linear (alpha kept); how many there were.
|
||||
fn linear_colours(doc: &mut Value) -> usize {
|
||||
let Some(mats) = doc.get_mut("materials").and_then(Value::as_array_mut) else { return 0 };
|
||||
let mut n = 0;
|
||||
for m in mats {
|
||||
if let Some(c) = m.pointer_mut("/pbrMetallicRoughness/baseColorFactor").and_then(Value::as_array_mut) {
|
||||
for v in c.iter_mut().take(3) {
|
||||
if let Some(x) = v.as_f64() {
|
||||
*v = json!(srgb_to_linear(x));
|
||||
}
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Where an accessor's elements are in the BIN chunk: the first's byte, the step between them, how many, the component
|
||||
/// type, the components in each. None for one this fix doesn't read (sparse, another buffer, or past the chunk).
|
||||
fn layout(doc: &Value, acc: u64, bin: &[u8]) -> Option<(usize, usize, usize, u64, usize)> {
|
||||
let a = doc["accessors"].get(acc as usize)?;
|
||||
if a.get("sparse").is_some() {
|
||||
return None;
|
||||
}
|
||||
let v = doc["bufferViews"].get(a["bufferView"].as_u64()? as usize)?;
|
||||
if v["buffer"].as_u64().unwrap_or(0) != 0 {
|
||||
return None;
|
||||
}
|
||||
let comp = a["componentType"].as_u64()?;
|
||||
let size = match comp {
|
||||
5120 | 5121 => 1,
|
||||
5122 | 5123 => 2,
|
||||
5125 | 5126 => 4,
|
||||
_ => return None,
|
||||
};
|
||||
let n = match a["type"].as_str()? {
|
||||
"SCALAR" => 1,
|
||||
"VEC2" => 2,
|
||||
"VEC3" => 3,
|
||||
"VEC4" => 4,
|
||||
_ => return None,
|
||||
};
|
||||
let start = v["byteOffset"].as_u64().unwrap_or(0) as usize + a["byteOffset"].as_u64().unwrap_or(0) as usize;
|
||||
let stride = v["byteStride"].as_u64().map_or(size * n, |s| s as usize);
|
||||
let count = a["count"].as_u64()? as usize;
|
||||
(count == 0 || start + stride * (count - 1) + size * n <= bin.len()).then_some((start, stride, count, comp, n))
|
||||
}
|
||||
|
||||
fn f32_at(bin: &[u8], at: usize) -> f32 {
|
||||
f32::from_le_bytes([bin[at], bin[at + 1], bin[at + 2], bin[at + 3]])
|
||||
}
|
||||
|
||||
fn vec3s(doc: &Value, acc: u64, bin: &[u8]) -> Option<Vec<[f32; 3]>> {
|
||||
let (start, stride, count, comp, n) = layout(doc, acc, bin)?;
|
||||
(comp == FLOAT && n == 3).then(|| (0..count).map(|i| std::array::from_fn(|k| f32_at(bin, start + i * stride + 4 * k))).collect())
|
||||
}
|
||||
|
||||
fn indices(doc: &Value, prim: &Value, bin: &[u8], verts: usize) -> Option<Vec<usize>> {
|
||||
let Some(acc) = prim.get("indices").and_then(Value::as_u64) else { return Some((0..verts).collect()) };
|
||||
let (start, stride, count, comp, n) = layout(doc, acc, bin)?;
|
||||
if n != 1 {
|
||||
return None;
|
||||
}
|
||||
let at = |i: usize| start + i * stride;
|
||||
let idx: Vec<usize> = match comp {
|
||||
5121 => (0..count).map(|i| bin[at(i)] as usize).collect(),
|
||||
5123 => (0..count).map(|i| u16::from_le_bytes([bin[at(i)], bin[at(i) + 1]]) as usize).collect(),
|
||||
5125 => (0..count).map(|i| u32::from_le_bytes([bin[at(i)], bin[at(i) + 1], bin[at(i) + 2], bin[at(i) + 3]]) as usize).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
idx.iter().all(|&i| i < verts).then_some(idx)
|
||||
}
|
||||
|
||||
fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
|
||||
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
|
||||
}
|
||||
fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
|
||||
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
||||
}
|
||||
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
|
||||
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
||||
}
|
||||
fn unit(a: [f32; 3]) -> Option<[f32; 3]> {
|
||||
let l = dot(a, a).sqrt();
|
||||
(l > 1e-20).then(|| [a[0] / l, a[1] / l, a[2] / l])
|
||||
}
|
||||
|
||||
/// New normals for one primitive: each corner takes the area-weighted mean of the triangles at its position (corners
|
||||
/// forma split per face are joined by position) whose facing is within `deg` of the corner's own normal.
|
||||
pub fn smoothed(pos: &[[f32; 3]], normals: &[[f32; 3]], idx: &[usize], deg: f32) -> Vec<[f32; 3]> {
|
||||
let lo = pos.iter().fold([f32::MAX; 3], |m, p| std::array::from_fn(|k| m[k].min(p[k])));
|
||||
let hi = pos.iter().fold([f32::MIN; 3], |m, p| std::array::from_fn(|k| m[k].max(p[k])));
|
||||
let eps = (dot(sub(hi, lo), sub(hi, lo)).sqrt() * 1e-6).max(1e-9);
|
||||
let key = |p: [f32; 3]| p.map(|c| (c / eps).round() as i64);
|
||||
let mut group: HashMap<[i64; 3], usize> = HashMap::new();
|
||||
let gid: Vec<usize> = pos.iter().map(|&p| { let n = group.len(); *group.entry(key(p)).or_insert(n) }).collect();
|
||||
let mut around: Vec<Vec<[f32; 3]>> = vec![Vec::new(); group.len()];
|
||||
for t in idx.as_chunks::<3>().0 {
|
||||
let f = cross(sub(pos[t[1]], pos[t[0]]), sub(pos[t[2]], pos[t[0]]));
|
||||
if unit(f).is_none() {
|
||||
continue;
|
||||
}
|
||||
let mut seen = [usize::MAX; 3];
|
||||
for (k, &v) in t.iter().enumerate() {
|
||||
if !seen.contains(&gid[v]) {
|
||||
around[gid[v]].push(f);
|
||||
seen[k] = gid[v];
|
||||
}
|
||||
}
|
||||
}
|
||||
let cos = deg.to_radians().cos();
|
||||
(0..pos.len())
|
||||
.map(|v| {
|
||||
let Some(own) = unit(normals[v]) else { return normals[v] };
|
||||
let sum = around[gid[v]].iter().filter(|f| unit(**f).is_some_and(|u| dot(u, own) >= cos)).fold([0.0; 3], |s, f| [s[0] + f[0], s[1] + f[1], s[2] + f[2]]);
|
||||
unit(sum).unwrap_or(own)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every triangle primitive's normals smoothed in the BIN chunk; how many primitives changed. A primitive with tangents
|
||||
/// is left alone (smoothing would leave them stale), as is one whose data this fix doesn't read.
|
||||
fn smooth_normals(doc: &Value, bin: &mut [u8], deg: f32) -> R<usize> {
|
||||
let mut done: HashSet<u64> = HashSet::new();
|
||||
let mut n = 0;
|
||||
for mesh in doc["meshes"].as_array().into_iter().flatten() {
|
||||
for prim in mesh["primitives"].as_array().into_iter().flatten() {
|
||||
let attrs = &prim["attributes"];
|
||||
let (Some(p), Some(nm)) = (attrs["POSITION"].as_u64(), attrs["NORMAL"].as_u64()) else { continue };
|
||||
if prim["mode"].as_u64().unwrap_or(4) != 4 || attrs.get("TANGENT").is_some() || !done.insert(nm) {
|
||||
continue;
|
||||
}
|
||||
let (Some(pos), Some(normals)) = (vec3s(doc, p, bin), vec3s(doc, nm, bin)) else { continue };
|
||||
let Some(idx) = indices(doc, prim, bin, pos.len()).filter(|_| pos.len() == normals.len()) else { continue };
|
||||
let new = smoothed(&pos, &normals, &idx, deg);
|
||||
let (start, stride, ..) = layout(doc, nm, bin).ok_or("the normals moved")?;
|
||||
for (i, v) in new.iter().enumerate() {
|
||||
for (k, c) in v.iter().enumerate() {
|
||||
let at = start + i * stride + 4 * k;
|
||||
bin[at..at + 4].copy_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Two triangles forma-style (corners split per face, flat normals) meeting along x at `fold` degrees, with
|
||||
/// a red material typed as sRGB.
|
||||
fn hinge(fold: f32) -> Vec<u8> {
|
||||
let (s, c) = fold.to_radians().sin_cos();
|
||||
let pos: [[f32; 3]; 6] = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, -c, s], [1.0, 0.0, 0.0]];
|
||||
let b = unit(cross(sub(pos[4], pos[3]), sub(pos[5], pos[3]))).unwrap();
|
||||
let nrm: [[f32; 3]; 6] = [[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], b, b, b];
|
||||
let mut bin = Vec::new();
|
||||
for v in pos.iter().chain(nrm.iter()) {
|
||||
for c in v {
|
||||
bin.extend_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
}
|
||||
for i in 0u16..6 {
|
||||
bin.extend_from_slice(&i.to_le_bytes());
|
||||
}
|
||||
let doc = json!({
|
||||
"asset": {"version": "2.0", "generator": "forma"},
|
||||
"materials": [{"pbrMetallicRoughness": {"baseColorFactor": [0.72, 0.36, 0.0, 0.5]}}],
|
||||
"meshes": [{"primitives": [{"attributes": {"POSITION": 0, "NORMAL": 1}, "indices": 2, "material": 0}]}],
|
||||
"accessors": [
|
||||
{"bufferView": 0, "componentType": 5126, "count": 6, "type": "VEC3"},
|
||||
{"bufferView": 0, "byteOffset": 72, "componentType": 5126, "count": 6, "type": "VEC3"},
|
||||
{"bufferView": 1, "componentType": 5123, "count": 6, "type": "SCALAR"}
|
||||
],
|
||||
"bufferViews": [{"buffer": 0, "byteLength": 144}, {"buffer": 0, "byteOffset": 144, "byteLength": 12}],
|
||||
"buffers": [{"byteLength": 156}]
|
||||
});
|
||||
write(&doc, &bin)
|
||||
}
|
||||
|
||||
fn normals_of(glb: &[u8]) -> Vec<[f32; 3]> {
|
||||
let (doc, bin) = read(glb).unwrap();
|
||||
vec3s(&doc, 1, &bin).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours_become_linear_once() {
|
||||
let (out, f) = fix(&hinge(10.0), None).unwrap();
|
||||
assert_eq!(f, Fixed { colours: 1, primitives: 0, already: false });
|
||||
let (doc, _) = read(&out).unwrap();
|
||||
let c: Vec<f64> = doc["materials"][0]["pbrMetallicRoughness"]["baseColorFactor"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
assert!((c[0] - 0.4770).abs() < 1e-3 && (c[1] - 0.1065).abs() < 1e-3 && c[2] == 0.0 && c[3] == 0.5, "{c:?}");
|
||||
assert_eq!(doc["asset"]["generator"], "forma");
|
||||
let (again, f2) = fix(&out, Some(40.0)).unwrap();
|
||||
assert!(f2.already && again == out);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shallow_fold_turns_round_and_a_sharp_one_stays() {
|
||||
let (out, f) = fix(&hinge(10.0), Some(40.0)).unwrap();
|
||||
assert_eq!(f.primitives, 1);
|
||||
let n = normals_of(&out);
|
||||
// the corners on the shared edge lean halfway; the corners on one face alone keep its facing
|
||||
let tilt = |v: [f32; 3]| dot(v, [0.0, 0.0, 1.0]).acos().to_degrees();
|
||||
assert!((tilt(n[0]) - 5.0).abs() < 0.01 && (tilt(n[1]) - 5.0).abs() < 0.01 && (tilt(n[3]) - 5.0).abs() < 0.01, "{n:?}");
|
||||
assert!(tilt(n[2]) < 1e-3 && (tilt(n[4]) - 10.0).abs() < 0.01, "{n:?}");
|
||||
for v in &n {
|
||||
assert!((dot(*v, *v) - 1.0).abs() < 1e-5);
|
||||
}
|
||||
let (sharp, _) = fix(&hinge(60.0), Some(40.0)).unwrap();
|
||||
assert_eq!(normals_of(&sharp), normals_of(&hinge(60.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_keeps_its_layout() {
|
||||
let src = hinge(10.0);
|
||||
let (out, _) = fix(&src, Some(40.0)).unwrap();
|
||||
assert_eq!(out.len() % 4, 0);
|
||||
assert_eq!(u32::from_le_bytes([out[8], out[9], out[10], out[11]]) as usize, out.len());
|
||||
let ((_, a), (_, b)) = (read(&src).unwrap(), read(&out).unwrap());
|
||||
assert_eq!(a.len(), b.len());
|
||||
assert_eq!(a[..72], b[..72], "positions untouched");
|
||||
assert_eq!(a[144..], b[144..], "indices untouched");
|
||||
assert!(fix(b"not a glb", None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
//! `raea setup forma` and `raea forma` (docs/forma.feature). forma (github.com/wrong-nebula/forma) is a headless
|
||||
//! modeller for hard-surface parts: a few lines of its pipe language make a watertight mesh with exact sizes in
|
||||
//! milliseconds (gears, brackets, threads, enclosures, a lathed vase, a table). forma is GPL-3.0-or-later and raea is
|
||||
//! FSL, so raea never links forma or ships it: setup downloads forma's own release into ~/.raea/tools/forma, as
|
||||
//! `raea setup blender` does Blender, and `raea forma` runs it as a program of its own, then fixes the .glb it wrote
|
||||
//! (glb.rs). What forma makes belongs to whoever made it; the GPL covers forma alone.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// the .glb forma writes, its colours made linear and its normals smoothed
|
||||
pub mod glb;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// The forma raea downloads and is tested with.
|
||||
pub const VERSION: &str = "0.4.4";
|
||||
/// Linux: forma's static musl binary from its GitHub release, which needs no Node; each archive's sha256, pinned.
|
||||
const LINUX: [(&str, &str); 2] = [
|
||||
("x86_64", "52ffc3d60787a9aab9989064624729115e6b1b8d29e53540fde0188443af9470"),
|
||||
("aarch64", "c4788352ce97c432a818d4c8e6f16d60e74e193909ac56ea5b1a066cf967bb5d"),
|
||||
];
|
||||
/// Elsewhere: the npm package forma-3d (forma built for WebAssembly, with its CLI and MCP server), run by Node 18+ or
|
||||
/// Bun; the tarball's sha512, pinned (npm's own integrity for it, in hex).
|
||||
const NPM_SHA512: &str = "676e7990b32dbc3a035079509c5ac9baa86bd24423a53e57e9b586f4b7ff45b07bda75842f58e795c7a128b8a35bc94bc1eafc8e2f94126bcc5f1c3200626a95";
|
||||
/// The angle under which `raea forma` smooths a .glb's normals unless --smooth says.
|
||||
pub const SMOOTH: f32 = 40.0;
|
||||
|
||||
pub const USAGE: &str = "raea setup forma [--check] [--download] (find forma or download it into ~/.raea/tools/forma: forma 0.4.4, a headless modeller for hard-surface parts (GPL-3.0-or-later, so raea runs it as its own program and never ships it), its static binary on Linux, else its npm package run by Node 18+ or Bun, each checked against its pinned hash)\n raea forma SCRIPT.forma -o OUT.glb|.stl|.obj|.3mf|.step [--unit m|cm|mm|um|in|ft] [--render PREVIEW.png] [--draw BLUEPRINT.svg] [--size PX] [--smooth DEG] [--flat] [--no-strict] (a forma script made into OUT, each named part its own node; a mesh that isn't watertight is refused with forma's reason unless --no-strict; a .glb's colours are made linear, as glTF reads them, and its normals smoothed where faces meet under DEG degrees (40 unless given; --flat keeps forma's faceted ones); --render's preview draws the last part, raea render draws them all)\n raea forma fix FILE.glb... [--smooth DEG] [--flat] (the same fix on a .glb forma wrote by itself (its MCP server's export, its own CLI): colours linear, normals smoothed; a file fixed before is left alone)\n raea forma spec [--topic deform|curves|uv|remesh|scene] [--gbnf] (forma's language reference, about 500 tokens: its primitives, operations and selectors)";
|
||||
|
||||
/// How forma is run: its own binary, or its npm package's CLI by a JavaScript runtime.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Forma {
|
||||
Native(PathBuf),
|
||||
Js { runtime: PathBuf, cli: PathBuf },
|
||||
}
|
||||
|
||||
impl Forma {
|
||||
pub fn command(&self) -> Command {
|
||||
match self {
|
||||
Forma::Native(bin) => Command::new(bin),
|
||||
Forma::Js { runtime, cli } => {
|
||||
let mut c = Command::new(runtime);
|
||||
c.arg(cli);
|
||||
c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
match self {
|
||||
Forma::Native(p) | Forma::Js { cli: p, .. } => p,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where raea keeps its download of forma.
|
||||
pub fn own_dir() -> R<PathBuf> {
|
||||
Ok(raea_io_home::user_home().ok_or("no home folder (HOME)")?.join(".raea/tools/forma"))
|
||||
}
|
||||
|
||||
fn on_path(name: &str) -> Option<PathBuf> {
|
||||
let exe = if cfg!(windows) { format!("{name}.exe") } else { name.to_string() };
|
||||
std::env::split_paths(&std::env::var_os("PATH")?).map(|d| d.join(&exe)).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Node, else Bun: what runs forma's npm package.
|
||||
fn js_runtime() -> R<PathBuf> {
|
||||
on_path("node").or_else(|| on_path("bun")).ok_or_else(|| "forma runs here on Node.js 18 or later, or Bun, and neither is on PATH: install one (https://nodejs.org), then raea setup forma again".into())
|
||||
}
|
||||
|
||||
/// A forma at a path: a .mjs or .js is forma's npm CLI, anything else its binary.
|
||||
fn at(p: PathBuf) -> R<Forma> {
|
||||
Ok(if p.extension().is_some_and(|x| x == "mjs" || x == "js") { Forma::Js { runtime: js_runtime()?, cli: p } } else { Forma::Native(p) })
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
/// The forma to use and where it came from: `git config --global raea.forma` (a binary or forma's bin/forma.mjs),
|
||||
/// raea's download, then a `forma` on PATH that says it is forma.
|
||||
pub fn find() -> R<Option<(Forma, &'static str)>> {
|
||||
let configured = run(Command::new("git").args(["config", "--global", "raea.forma"]), "git config").ok().map(|o| PathBuf::from(o.trim()));
|
||||
if let Some(p) = configured.filter(|p| p.is_file()) {
|
||||
return Ok(Some((at(p)?, "raea.forma in git config")));
|
||||
}
|
||||
let dir = own_dir()?;
|
||||
for p in [dir.join(if cfg!(windows) { "forma.exe" } else { "forma" }), dir.join("package/bin/forma.mjs")] {
|
||||
if p.is_file() {
|
||||
return Ok(Some((at(p)?, "raea's download")));
|
||||
}
|
||||
}
|
||||
Ok(on_path("forma").map(Forma::Native).filter(|f| version(f).is_ok()).map(|f| (f, "PATH")))
|
||||
}
|
||||
|
||||
/// `forma --version`'s first line ("forma 0.4.4 (WASM)"); an error when the program isn't forma.
|
||||
pub fn version(f: &Forma) -> R<String> {
|
||||
let out = run(f.command().arg("--version"), "forma --version")?;
|
||||
out.lines().map(str::trim).find(|l| l.starts_with("forma")).map(str::to_string).ok_or_else(|| format!("{} --version didn't say forma", f.path().display()))
|
||||
}
|
||||
|
||||
/// A file's sha256 or sha512 in hex, by the platform's own tool (as blender.rs and godot.rs check their downloads).
|
||||
pub fn digest(file: &Path, bits: u32) -> R<String> {
|
||||
let out = if cfg!(windows) {
|
||||
run(Command::new("certutil").arg("-hashfile").arg(file).arg(format!("SHA{bits}")), "certutil")?.lines().nth(1).unwrap_or_default().replace(' ', "")
|
||||
} else if on_path("shasum").is_some() {
|
||||
run(Command::new("shasum").args(["-a", &bits.to_string()]).arg(file), "shasum")?.split_whitespace().next().unwrap_or_default().to_string()
|
||||
} else {
|
||||
run(Command::new(format!("sha{bits}sum")).arg(file), "sha sum")?.split_whitespace().next().unwrap_or_default().to_string()
|
||||
};
|
||||
Ok(out.to_lowercase())
|
||||
}
|
||||
|
||||
/// Downloads forma into ~/.raea/tools/forma, checked against its pinned hash: Linux's binary, else the npm package.
|
||||
fn download() -> R<(Forma, String)> {
|
||||
let linux = LINUX.iter().find(|(arch, _)| cfg!(target_os = "linux") && *arch == std::env::consts::ARCH);
|
||||
let (url, bits, want, file) = match linux {
|
||||
Some((arch, sum)) => (format!("https://github.com/wrong-nebula/forma/releases/download/v{VERSION}/forma-linux-{arch}-musl.tar.gz"), 256, *sum, "forma.tar.gz"),
|
||||
None => {
|
||||
js_runtime()?; // before downloading what nothing here could run
|
||||
(format!("https://registry.npmjs.org/forma-3d/-/forma-3d-{VERSION}.tgz"), 512, NPM_SHA512, "forma-3d.tgz")
|
||||
}
|
||||
};
|
||||
let dir = own_dir()?;
|
||||
let tmp = dir.with_file_name("forma.download");
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
let unpacked = tmp.join("unpacked");
|
||||
std::fs::create_dir_all(&unpacked).map_err(|e| format!("{}: {e}", unpacked.display()))?;
|
||||
let got = tmp.join(file);
|
||||
run(Command::new("curl").args(["-fL", "--retry", "3", "-o"]).arg(&got).arg(&url), "downloading forma")?;
|
||||
if digest(&got, bits)? != want {
|
||||
return Err(format!("{url} doesn't match its pinned sha{bits}; nothing installed (it's in {})", tmp.display()));
|
||||
}
|
||||
run(Command::new("tar").arg("-xzf").arg(&got).arg("-C").arg(&unpacked), "unpacking forma")?;
|
||||
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);
|
||||
let what = if linux.is_some() { "its Linux binary from github.com/wrong-nebula/forma" } else { "its npm package forma-3d" };
|
||||
let f = find()?.filter(|(_, from)| *from == "raea's download").ok_or_else(|| format!("{url} held no forma"))?.0;
|
||||
Ok((f, format!("downloaded forma {VERSION}, {what}")))
|
||||
}
|
||||
|
||||
/// `raea setup forma [--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 (f, from) = match find()?.filter(|_| !fresh) {
|
||||
Some((f, from)) => (f, from.to_string()),
|
||||
None if check => return Ok(format!("CHECKED no forma found (raea.forma, {}, PATH): raea setup forma downloads forma {VERSION}", own_dir()?.display())),
|
||||
None => download()?,
|
||||
};
|
||||
let v = version(&f)?;
|
||||
let pinned = if v.contains(VERSION) { String::new() } else { format!(" (raea is tested with {VERSION}: raea setup forma --download fetches it)") };
|
||||
let head = if check { "CHECKED " } else { "APPLIED " };
|
||||
Ok(format!("{head} {v} ({from}){pinned}\n {}\n make: raea forma SCRIPT.forma -o OUT.glb; its language: raea forma spec; agents: the `forma` MCP server (raea skills install adds it)\n forma is GPL-3.0-or-later and runs as its own program; what it makes is yours", f.path().display()))
|
||||
}
|
||||
|
||||
/// `raea forma`'s arguments, read.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct Make {
|
||||
pub script: String,
|
||||
pub out: String,
|
||||
pub unit: Option<String>,
|
||||
pub render: Option<String>,
|
||||
pub draw: Option<String>,
|
||||
pub size: Option<String>,
|
||||
pub smooth: Option<f32>,
|
||||
pub strict: bool,
|
||||
}
|
||||
|
||||
/// Reads `raea forma SCRIPT -o OUT ...` (args without the verb).
|
||||
pub fn parse(args: &[String]) -> R<Make> {
|
||||
let mut m = Make { smooth: Some(SMOOTH), strict: true, ..Default::default() };
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
let mut val = |flag: &str| it.next().cloned().ok_or_else(|| format!("{flag} takes a value: {USAGE}"));
|
||||
match a.as_str() {
|
||||
"-o" | "--out" => m.out = val(a)?,
|
||||
"--unit" => m.unit = Some(val(a)?),
|
||||
"--render" => m.render = Some(val(a)?),
|
||||
"--draw" => m.draw = Some(val(a)?),
|
||||
"--size" => m.size = Some(val(a)?),
|
||||
"--smooth" => m.smooth = Some(val(a)?.parse().map_err(|_| "--smooth takes degrees, 40 say".to_string())?),
|
||||
"--flat" => m.smooth = None,
|
||||
"--no-strict" => m.strict = false,
|
||||
f if f.starts_with('-') && f != "-" => return Err(format!("raea forma has no {f}: {USAGE}")),
|
||||
s if m.script.is_empty() => m.script = s.to_string(),
|
||||
s => return Err(format!("one script at a time ({} and {s})", m.script)),
|
||||
}
|
||||
}
|
||||
if m.script.is_empty() || m.out.is_empty() {
|
||||
return Err(format!("usage: {USAGE}"));
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// forma's own arguments for a make: always one node per named part in a .glb.
|
||||
pub fn forma_args(m: &Make) -> Vec<String> {
|
||||
let mut a: Vec<String> = vec!["eval".into(), if m.strict { "--strict" } else { "--no-strict" }.into()];
|
||||
if m.out.to_lowercase().ends_with(".glb") {
|
||||
a.push("--scene".into());
|
||||
}
|
||||
a.extend(["--out".into(), m.out.clone()]);
|
||||
for (flag, v) in [("--unit", &m.unit), ("--render", &m.render), ("--size", &m.size), ("--draw", &m.draw)] {
|
||||
if let Some(v) = v {
|
||||
a.extend([flag.to_string(), v.clone()]);
|
||||
}
|
||||
}
|
||||
a.push(m.script.clone());
|
||||
a
|
||||
}
|
||||
|
||||
/// `raea forma fix FILE.glb... [--smooth DEG] [--flat]` (args after `fix`): needs no forma, only its files.
|
||||
pub fn fix(args: &[String]) -> R<String> {
|
||||
let mut smooth = Some(SMOOTH);
|
||||
let mut files = Vec::new();
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--smooth" => smooth = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--smooth takes degrees, 40 say")?),
|
||||
"--flat" => smooth = None,
|
||||
f if f.starts_with('-') => return Err(format!("raea forma fix has no {f}: {USAGE}")),
|
||||
f if f.to_lowercase().ends_with(".glb") => files.push(f),
|
||||
f => return Err(format!("{f} isn't a .glb: forma's .stl, .obj, .3mf and .step carry no colours to fix")),
|
||||
}
|
||||
}
|
||||
if files.is_empty() {
|
||||
return Err(format!("which .glb: {USAGE}"));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for f in files {
|
||||
let fixed = glb::fix_file(Path::new(f), smooth)?;
|
||||
out.push(if fixed.already { format!("CHECKED {f}: fixed before, left alone") } else { format!("APPLIED {f}: {} colours made linear, {} meshes' normals smoothed", fixed.colours, fixed.primitives) });
|
||||
}
|
||||
Ok(out.join("\n"))
|
||||
}
|
||||
|
||||
/// `raea forma ...` (args with the verb): `spec` passes through to forma; a make runs forma, then fixes the .glb.
|
||||
pub fn forma(args: &[String]) -> R<String> {
|
||||
if args.get(1).map(String::as_str) == Some("fix") {
|
||||
return fix(&args[2..]);
|
||||
}
|
||||
let (f, _) = find()?.ok_or("no forma: raea setup forma finds or downloads it")?;
|
||||
if args.get(1).map(String::as_str) == Some("spec") {
|
||||
return run(f.command().arg("spec").args(&args[2..]), "forma spec");
|
||||
}
|
||||
let m = parse(&args[1..])?;
|
||||
if m.script != "-" && !Path::new(&m.script).is_file() {
|
||||
return Err(format!("no script {}", m.script));
|
||||
}
|
||||
let o = f.command().args(forma_args(&m)).stdin(Stdio::inherit()).output().map_err(|e| format!("{}: {e}", f.path().display()))?;
|
||||
let (out, err) = (String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
|
||||
if !o.status.success() {
|
||||
let why = if o.status.code() == Some(3) { " (not watertight: --no-strict writes it anyway)" } else { "" };
|
||||
return Err(format!("forma refused {}{why}: {}{}", m.script, err.trim(), if out.trim().is_empty() { String::new() } else { format!("\n{}", out.trim()) }));
|
||||
}
|
||||
let mut report = out.trim_end().to_string();
|
||||
if m.out.to_lowercase().ends_with(".glb") {
|
||||
let fixed = glb::fix_file(Path::new(&m.out), m.smooth)?;
|
||||
let normals = match m.smooth {
|
||||
Some(d) => format!("{} meshes' normals smoothed under {d}°", fixed.primitives),
|
||||
None => "normals flat as forma wrote them".into(),
|
||||
};
|
||||
report += &format!("\nAPPLIED {}: {} colours made linear, {normals}", m.out, fixed.colours);
|
||||
} else {
|
||||
report += &format!("\nAPPLIED {}", m.out);
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// The verbs here, or None for any other: `setup forma` and `forma ...`.
|
||||
pub fn cli(args: &[String]) -> Option<R<String>> {
|
||||
match (args.first()?.as_str(), args.get(1).map(String::as_str)) {
|
||||
("setup", Some("forma")) => Some(setup(&args[2..])),
|
||||
("forma", _) => Some(forma(args)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(s: &str) -> Vec<String> {
|
||||
s.split_whitespace().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_make_reads_its_flags_and_passes_forma_its_own() {
|
||||
let m = parse(&args("bolt.forma -o bolt.glb --unit mm --render b.png --smooth 30")).unwrap();
|
||||
assert_eq!((m.smooth, m.strict, m.unit.as_deref()), (Some(30.0), true, Some("mm")));
|
||||
assert_eq!(forma_args(&m).join(" "), "eval --strict --scene --out bolt.glb --unit mm --render b.png bolt.forma");
|
||||
let flat = parse(&args("p.forma -o p.stl --flat --no-strict")).unwrap();
|
||||
assert_eq!((flat.smooth, flat.strict), (None, false));
|
||||
assert_eq!(forma_args(&flat).join(" "), "eval --no-strict --out p.stl p.forma");
|
||||
assert_eq!(parse(&args("p.forma -o p.glb")).unwrap().smooth, Some(SMOOTH));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_make_refuses_what_it_cant_read() {
|
||||
assert!(parse(&args("p.forma")).unwrap_err().starts_with("usage:"));
|
||||
assert!(parse(&args("p.forma -o p.glb --bogus")).unwrap_err().contains("no --bogus"));
|
||||
assert!(parse(&args("a.forma b.forma -o p.glb")).unwrap_err().contains("one script"));
|
||||
assert!(parse(&args("p.forma -o p.glb --smooth soft")).is_err());
|
||||
assert!(parse(&args("p.forma -o")).unwrap_err().contains("takes a value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_flag_is_in_the_usage() {
|
||||
for f in ["--check", "--download", "--unit", "--render", "--draw", "--size", "--smooth", "--flat", "--no-strict", "--topic", "--gbnf"] {
|
||||
assert!(USAGE.contains(&format!("[{f}")), "{f}");
|
||||
}
|
||||
assert!(cli(&args("setup blender")).is_none() && cli(&args("render x.tsx")).is_none() && cli(&[]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digests_of_a_known_file() {
|
||||
let f = std::env::temp_dir().join(format!("raea-forma-digest-{}", std::process::id()));
|
||||
std::fs::write(&f, b"abc").unwrap();
|
||||
let (a, b) = (digest(&f, 256), digest(&f, 512));
|
||||
let _ = std::fs::remove_file(&f);
|
||||
assert_eq!(a.unwrap(), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
|
||||
assert!(b.unwrap().starts_with("ddaf35a193617aba"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fix_takes_only_glb_files() {
|
||||
assert!(fix(&args("part.stl")).unwrap_err().contains("isn't a .glb"));
|
||||
assert!(fix(&args("--flat")).unwrap_err().starts_with("which .glb"));
|
||||
assert!(fix(&args("a.glb --soft")).unwrap_err().contains("no --soft"));
|
||||
let d = std::env::temp_dir().join(format!("raea-forma-fix-{}.glb", std::process::id()));
|
||||
std::fs::write(&d, glb::write(&serde_json::json!({"asset": {"version": "2.0"}, "materials": [{"pbrMetallicRoughness": {"baseColorFactor": [0.5, 0.5, 0.5, 1.0]}}]}), &[])).unwrap();
|
||||
let p = d.to_string_lossy().to_string();
|
||||
let (first, again) = (fix(std::slice::from_ref(&p)), fix(&[p]));
|
||||
let _ = std::fs::remove_file(&d);
|
||||
assert!(first.unwrap().contains("1 colours made linear") && again.unwrap().contains("fixed before"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_names_its_kind() {
|
||||
assert_eq!(at(PathBuf::from("/x/forma")).unwrap(), Forma::Native(PathBuf::from("/x/forma")));
|
||||
}
|
||||
}
|
||||
+72
-17
@@ -1,9 +1,8 @@
|
||||
//! A judge that is an agent rather than clef-omni (Shane, 11-06: an agent as the judge; 12-03: never a harness raea
|
||||
//! picks or the agent names): a fresh session of the agent this project runs on, which the host that started it (raea
|
||||
//! cloud's box, the raea app) offers as RAEA_JUDGE_URL. Each call is a new session, run in DIR with only the sheets to
|
||||
//! look at, given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and never the code or
|
||||
//! the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
|
||||
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --read` records
|
||||
//! A judge that is an agent CLI rather than clef-omni: `raea judge DIR --by kimi|claude` (Shane, 11-06: "use claude or
|
||||
//! kimi cli as the judge"). Each call is a new session, run in DIR with only the sheets to look at (kimi's media tool;
|
||||
//! claude with Read alone), given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and
|
||||
//! never the code or the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
|
||||
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --by kimi` records
|
||||
//! its reading as the eye clef is calibrated against.
|
||||
|
||||
use std::path::Path;
|
||||
@@ -12,10 +11,7 @@ use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::rubric::{BAR, scores};
|
||||
|
||||
/// Whether this session has a critic to ask: where it has, the agent judges; else clef.
|
||||
pub fn critic() -> bool {
|
||||
raea_io_clef::critic::here()
|
||||
}
|
||||
pub const BY: [&str; 2] = ["kimi", "claude"];
|
||||
|
||||
/// The judge prompt: the sheets by name, the brief's words, and the JSON to answer. A `raea make` job's kind asks its
|
||||
/// own categories and the bar (docs/goal.feature MK5); none asks the rubric raea judge has always asked.
|
||||
@@ -129,11 +125,70 @@ pub fn read(kind: Option<&str>, v: &Value) -> (Map<String, Value>, Vec<Value>, V
|
||||
(out, defects, photo)
|
||||
}
|
||||
|
||||
/// One fresh judging session of this project's own agent over DIR's sheets, through the host (RAEA_JUDGE_URL): its
|
||||
/// verdict JSON.
|
||||
pub fn ask(kind: Option<&str>, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
|
||||
let dir = dunce::canonicalize(dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
|
||||
eprintln!("judge: a fresh session of this project's agent is reading the sheets");
|
||||
let text = raea_io_clef::critic::ask(&dir, &prompt(kind, &dir, brief, target)).map_err(|e| format!("judge: {e}"))?;
|
||||
last_verdict(&text).ok_or_else(|| format!("judge: the critic gave no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
|
||||
/// One fresh judging session by `by` over DIR's sheets: its verdict JSON. Its steps stream (kimi's stream-json), each
|
||||
/// said on stderr as it comes, so a watcher sees it working through a judgement that can take minutes.
|
||||
pub fn ask(kind: Option<&str>, by: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
|
||||
use std::io::BufRead as _;
|
||||
let dir = dunce::canonicalize(&dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
|
||||
let p = prompt(kind, &dir, brief, target);
|
||||
let mut cmd = match by {
|
||||
"kimi" => {
|
||||
let mut c = std::process::Command::new("kimi");
|
||||
c.args(["-p", &p, "--output-format", "stream-json"]);
|
||||
c
|
||||
}
|
||||
"claude" => {
|
||||
let mut c = std::process::Command::new("claude");
|
||||
c.args(["-p", &p, "--allowedTools", "Read", "--output-format", "stream-json", "--verbose"]);
|
||||
c
|
||||
}
|
||||
o => return Err(format!("judge: --by {o}: the judges are clef (the default), {}", BY.join(", "))),
|
||||
};
|
||||
let mut child = cmd.current_dir(&dir).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn()
|
||||
.map_err(|e| format!("judge: couldn't run {by}: {e} (is the {by} CLI installed and signed in?)"))?;
|
||||
let mut said = Vec::new();
|
||||
let mut last = String::new();
|
||||
for line in std::io::BufReader::new(child.stdout.take().ok_or("judge: no output pipe")?).lines().map_while(Result::ok) {
|
||||
let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
|
||||
said.extend(texts(&v));
|
||||
let step = match (v["role"].as_str(), v["type"].as_str()) {
|
||||
(Some("tool") | Some("user"), _) => "looked at a picture".to_string(),
|
||||
(Some("assistant"), _) | (_, Some("assistant")) => texts(&v).last().map_or_else(|| "thinking".into(), |t| t[..t.floor_char_boundary(100)].to_string()),
|
||||
_ => continue,
|
||||
};
|
||||
if step != last {
|
||||
eprintln!("judge ({by}): {}", step.replace('\n', " "));
|
||||
last = step;
|
||||
}
|
||||
}
|
||||
let out = child.wait_with_output().map_err(|e| format!("judge: {by}: {e}"))?;
|
||||
let text = said.join("\n");
|
||||
if !out.status.success() && last_verdict(&text).is_none() {
|
||||
return Err(format!("judge: {by} failed: {}", String::from_utf8_lossy(&out.stderr).lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output")));
|
||||
}
|
||||
last_verdict(&text).ok_or_else(|| format!("judge: {by} answered no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
|
||||
}
|
||||
|
||||
/// The words in one streamed line: kimi's {role: assistant, content: "..."}; claude's {type: assistant, message:
|
||||
/// {content: [{type: text, text}]}} and its final {type: result, result}.
|
||||
fn texts(v: &Value) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if v["role"] == "assistant"
|
||||
&& let Some(s) = v["content"].as_str()
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
for c in v["message"]["content"].as_array().into_iter().flatten() {
|
||||
if c["type"] == "text"
|
||||
&& let Some(s) = c["text"].as_str()
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
}
|
||||
if v["type"] == "result"
|
||||
&& let Some(s) = v["result"].as_str()
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
//! ~/.raea/judge/eye.jsonl. `raea judge calibrate` fits, per category, a line from the judge's score to his
|
||||
//! (least squares), and says how often the mapped judge's pass agrees with his. The judge gates only once it has 10
|
||||
//! rounds or more, some passed by the eye and some not, and agrees on 8 in 10 or better; until then `gating` is false and its verdict is advice
|
||||
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --read` records a
|
||||
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --by kimi|claude` records a
|
||||
//! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is.
|
||||
|
||||
use std::path::PathBuf;
|
||||
@@ -46,10 +46,9 @@ pub fn record(args: &[String]) -> Result<String, String> {
|
||||
let verdict: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("judge.json")).map_err(|_| format!("judge eye: no {}: judge the round first (raea judge {})", dir.join("judge.json").display(), dir.display()))?).map_err(|e| e.to_string())?;
|
||||
let kind = kind_in(&verdict);
|
||||
let cats = scores(kind);
|
||||
// the session's agent's reading as the eye (`--read`): a fresh session's scores, and its pass by the same rule in code
|
||||
if args.iter().any(|a| a == "--read") {
|
||||
let by = "agent";
|
||||
let v = crate::agent::ask(kind, &dir, &json!({}), None)?;
|
||||
// an agent's reading as the eye (`--by kimi`): a fresh session's scores, and its pass by the same rule in code
|
||||
if let Some(by) = args.iter().position(|a| a == "--by").and_then(|i| args.get(i + 1)) {
|
||||
let v = crate::agent::ask(kind, by, &dir, &json!({}), None)?;
|
||||
let (eye, defects, _) = crate::agent::read(kind, &v);
|
||||
if eye.len() < cats.len() {
|
||||
return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), cats.len()));
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
//! fresh every round and blind to the code, with the pass decided here in code. Until it is calibrated against Shane's
|
||||
//! eye (`raea judge eye`, `raea judge calibrate`, eye.rs) its verdict is advice: `gating` says which.
|
||||
//!
|
||||
//! raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry]
|
||||
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --read: the session's agent's reading as the eye)
|
||||
//! Who judges is never asked: a fresh session of the project's own agent where its host offers one (agent.rs), else
|
||||
//! clef-omni.
|
||||
//! raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry]
|
||||
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --by kimi: an agent's reading as the eye)
|
||||
//! raea judge calibrate [--kind scene|kit|shot] [--json]
|
||||
//!
|
||||
//! `--kind` asks a `raea make` job's own rubric (docs/goal.feature MK5): a scene's, a kit's or a shot list's categories,
|
||||
@@ -24,6 +22,7 @@ pub fn kind_gates(kind: &str) -> bool {
|
||||
}
|
||||
pub mod rubric;
|
||||
|
||||
pub use agent::BY;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -31,7 +30,7 @@ use raea_core_facts::{Finding, Level, finding};
|
||||
use raea_runtime_bundle::flag;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR [--read] [CATEGORY=SCORE ...] [--pass yes|no] | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: a fresh session of the project's own agent on the judge prompt where its host offers one, else clef-omni on the frozen rubric; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)";
|
||||
pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)";
|
||||
|
||||
/// `--kind`, checked: one of the rubric's kinds, or none (the default rubric).
|
||||
pub fn kind_of(args: &[String]) -> Result<Option<String>, String> {
|
||||
@@ -108,12 +107,12 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
let brief = brief_of(flag(args, "--brief").as_deref())?;
|
||||
let target = flag(args, "--target").map(PathBuf::from);
|
||||
let dry = args.iter().any(|a| a == "--dry");
|
||||
let by = if agent::critic() { "agent".to_string() } else { "clef".into() };
|
||||
let by = flag(args, "--by").unwrap_or_else(|| "clef".into());
|
||||
if by != "clef" {
|
||||
if dry {
|
||||
return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));
|
||||
}
|
||||
let v = agent::ask(kind, &dir, &brief, target.as_deref())?;
|
||||
let v = agent::ask(kind, &by, &dir, &brief, target.as_deref())?;
|
||||
let (scores, defects, photo) = agent::read(kind, &v);
|
||||
return finish(args, kind, &dir, scores.clone(), scores, defects, photo, 0.0, &by, false, json!({"blind": v["blind"], "show_as_is": v["show_as_is"]}));
|
||||
}
|
||||
@@ -191,7 +190,7 @@ fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::M
|
||||
let (pass, why) = rubric::pass_for(kind, &scores, &defects);
|
||||
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
|
||||
let mean = if vals.is_empty() { 0.0 } else { (vals.iter().sum::<f64>() / vals.len() as f64 * 100.0).round() / 100.0 };
|
||||
let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { "the project's agent".to_string() };
|
||||
let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { format!("{by} cli") };
|
||||
let found = findings(&defects, by, advice);
|
||||
let mut verdict = json!({"dir": dir.display().to_string(), "kind": kind, "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo,
|
||||
"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model, "findings": found, "count": finding::count(&found)});
|
||||
|
||||
@@ -70,10 +70,10 @@ fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
|
||||
assert!(!pass && why[0].starts_with("blocking"));
|
||||
assert!(crate::agent::last_verdict("no json here").is_none());
|
||||
// what it saw, as Findings (DR3): a gating judge's blocking defect is an error, an advising one's a warn
|
||||
let f = &crate::findings(&defects, "agent", false)[0];
|
||||
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (agent)"));
|
||||
let f = &crate::findings(&defects, "kimi", false)[0];
|
||||
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (kimi)"));
|
||||
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
|
||||
assert_eq!(crate::findings(&defects, "agent", true)[0].level, raea_core_facts::Level::Warn);
|
||||
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -12,6 +12,8 @@ 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" }
|
||||
# the forma version the `forma` MCP server is pinned to (agent_mcp.rs; forma itself is fetched by npx, never linked)
|
||||
raea-app-forma = { path = "../forma" }
|
||||
raea-io-media = { path = "../../io/media", default-features = false }
|
||||
serde_json = "1"
|
||||
# the verbs' flags read as a render reads its own
|
||||
|
||||
+56
-29
@@ -1,14 +1,26 @@
|
||||
//! 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.
|
||||
//! The MCP servers `raea skills install` offers an agent (docs/skills.feature SK11): `blender`, which drives a running
|
||||
//! Blender through the MCP for Blender add-on (`raea setup blender` installs it), and `forma`, forma's own server for
|
||||
//! modelling hard-surface parts in a few lines (docs/forma.feature FM6). 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"];
|
||||
/// An MCP server raea offers: its name, the program, its arguments.
|
||||
pub struct Server {
|
||||
pub name: &'static str,
|
||||
pub cmd: &'static str,
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
/// The servers raea offers. Each is fetched by its runner when an agent first starts it, so nothing is installed here:
|
||||
/// blender by uv's uvx, forma (GPL-3.0-or-later, its own program) by npm's npx at the version raea is tested with.
|
||||
/// Windows starts npx through cmd, as npx there is a .cmd script.
|
||||
pub fn servers() -> Vec<Server> {
|
||||
let forma = ["-y".to_string(), "-p".into(), format!("forma-3d@{}", raea_app_forma::VERSION), "forma-3d-mcp".into()];
|
||||
let (cmd, args) = if cfg!(windows) { ("cmd", ["/c".to_string(), "npx".into()].into_iter().chain(forma).collect()) } else { ("npx", forma.to_vec()) };
|
||||
vec![Server { name: "blender", cmd: "uvx", args: vec!["mcp-for-blender".into()] }, Server { name: "forma", cmd, args }]
|
||||
}
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
@@ -28,18 +40,18 @@ fn json_file(agent: &str) -> R<Option<PathBuf>> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Adds `blender` to a JSON config's `mcpServers` unless one is there; true when it added.
|
||||
pub fn add_json(path: &Path) -> R<bool> {
|
||||
/// Adds a server to a JSON config's `mcpServers` unless one of its name is there; true when it added.
|
||||
pub fn add_json(path: &Path, sv: &Server) -> 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) {
|
||||
if servers.contains_key(sv.name) {
|
||||
return Ok(false);
|
||||
}
|
||||
servers.insert(NAME.into(), json!({"command": CMD, "args": ARGS}));
|
||||
servers.insert(sv.name.into(), json!({"command": sv.cmd, "args": sv.args}));
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
@@ -49,45 +61,52 @@ pub fn add_json(path: &Path) -> R<bool> {
|
||||
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> {
|
||||
/// Adds a `[mcp_servers.NAME]` table to Codex's config.toml unless one is there; true when it added.
|
||||
pub fn add_toml(path: &Path, sv: &Server) -> R<bool> {
|
||||
let text = std::fs::read_to_string(path).unwrap_or_default();
|
||||
if text.lines().any(|l| l.trim() == format!("[mcp_servers.{NAME}]")) {
|
||||
let (name, cmd) = (sv.name, sv.cmd);
|
||||
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 args = sv.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()))?;
|
||||
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.
|
||||
/// Registers every server raea offers for an agent, a line each saying what happened.
|
||||
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()) };
|
||||
servers().iter().map(|sv| offer_one(agent, sv)).collect::<R<Vec<_>>>().map(|l| l.join("\n"))
|
||||
}
|
||||
|
||||
/// Registers one 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.
|
||||
fn offer_one(agent: &str, sv: &Server) -> R<String> {
|
||||
let name = sv.name;
|
||||
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));
|
||||
return Ok(line(add_toml(&p, sv)?, &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();
|
||||
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())?;
|
||||
let o = Command::new("claude").args(["mcp", "add", "--scope", "user", name, "--", sv.cmd]).args(&sv.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 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))
|
||||
Ok(line(add_json(&p, sv)?, &p))
|
||||
}
|
||||
|
||||
/// A move's guide as a skill of its own, named for the move: its description from the guide's first paragraph.
|
||||
@@ -115,18 +134,26 @@ mod tests {
|
||||
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());
|
||||
let all = servers();
|
||||
let (blender, forma) = (&all[0], &all[1]);
|
||||
assert!(add_json(&j, blender).unwrap());
|
||||
assert!(!add_json(&j, blender).unwrap());
|
||||
std::fs::write(&j, r#"{"theme":"dark","mcpServers":{"blender":{"command":"mine"}}}"#).unwrap();
|
||||
assert!(!add_json(&j).unwrap());
|
||||
assert!(!add_json(&j, blender).unwrap());
|
||||
assert!(add_json(&j, forma).unwrap());
|
||||
let kept: Value = serde_json::from_str(&std::fs::read_to_string(&j).unwrap()).unwrap();
|
||||
assert_eq!(kept["mcpServers"]["blender"]["command"], "mine");
|
||||
assert_eq!(kept["theme"], "dark");
|
||||
let pinned = format!("forma-3d@{}", raea_app_forma::VERSION);
|
||||
assert!(kept["mcpServers"]["forma"]["args"].as_array().unwrap().iter().any(|a| a == pinned.as_str()), "{kept}");
|
||||
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!(add_toml(&t, blender).unwrap());
|
||||
assert!(!add_toml(&t, blender).unwrap());
|
||||
assert_eq!(std::fs::read_to_string(&t).unwrap(), "model = \"x\"\n\n[mcp_servers.blender]\ncommand = \"uvx\"\nargs = [\"mcp-for-blender\"]\n");
|
||||
assert!(add_toml(&t, forma).unwrap());
|
||||
assert!(std::fs::read_to_string(&t).unwrap().contains(&format!("[mcp_servers.forma]\ncommand = {:?}\n", forma.cmd)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ pub mod song;
|
||||
pub mod sound;
|
||||
pub mod splat;
|
||||
|
||||
/// the MCP servers `raea skills install` offers an agent (blender, for a running Blender)
|
||||
/// the MCP servers `raea skills install` offers an agent (blender, for a running Blender; forma, for hard-surface parts)
|
||||
pub mod agent_mcp;
|
||||
pub mod agent_hooks;
|
||||
/// Grok Bot as a `raea skills install` target: its copy staged on this Mac, and the links that finish it in Grok Bot
|
||||
|
||||
@@ -83,7 +83,7 @@ pub struct CutPlan {
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields)]
|
||||
#[ts(rename = "CutBeat")]
|
||||
#[ts(rename = "Beat")]
|
||||
pub struct Beat {
|
||||
/// where it starts, in seconds from the cut's start (0 for the first)
|
||||
pub at: f64,
|
||||
|
||||
@@ -54,11 +54,11 @@ pub fn declarations() -> String {
|
||||
/// The goal's declarations (what the work is held to: goal.rs, cut.rs, playable.rs, rules.rs): sdk/raea/src/brief-goal.gen.ts
|
||||
pub fn goal_declarations() -> String {
|
||||
let cfg = Config::new();
|
||||
// a cut's beats are its own (cut.rs Beat, CutBeat in TypeScript: feel, story, asl, tempo), not a script's
|
||||
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.".to_string()];
|
||||
// a cut's beats are a script's (script.rs Beat)
|
||||
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.\nimport type { Beat } from \"./brief.gen\";".to_string()];
|
||||
out.extend(decls!(cfg;
|
||||
goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals,
|
||||
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Beat, cut::Phrase, cut::Cta, cut::Open,
|
||||
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
|
||||
playable::Playable, playable::Orientation,
|
||||
rules::Rule,
|
||||
));
|
||||
|
||||
@@ -103,20 +103,6 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
|
||||
And a worker that can't be reached fails the render unless RAEA_CLOUD_GPU_FALLBACK=cpu
|
||||
And every other raea command runs on the box
|
||||
|
||||
Scenario: CL16. raea cloud's boxes are Fly Machines
|
||||
Given the boxes were Sprites (deploy/sprites/), which ran at most 10 at once, read their disk in about 26 ms a
|
||||
read and stopped at 8 cores and 16 GB (12-03)
|
||||
Then each box is a Fly app of its own (raea-box-N for the box raea-N) with one Machine of deploy/fly/Dockerfile,
|
||||
8 dedicated cores and 16 GB, and a volume for its home folder: the agents' sign-ins, ~/.raea-cloud.env, ~/work
|
||||
And its work folder is /home/sprite/work as on a Sprite (the image links /home/sprite to /home/raea), so a moved
|
||||
project's folders and paths are the same
|
||||
And the server exits when the box has been idle RAEA_CLOUD_IDLE_STOP_MIN minutes (no request, connection,
|
||||
process working in ~/work, or hold file touched lately: server/idle.ts), the Machine stays stopped, and Fly's
|
||||
proxy starts it again at the next request
|
||||
And deploy/fly/box.sh makes a box (up), moves a Sprite's (move: its token kept, its home sent from the Sprite
|
||||
straight to the new box's file API), and puts every box on a release (latest)
|
||||
And a file PUT to a box streams to disk and lands whole, never held in memory
|
||||
|
||||
Rule: it is proven end to end
|
||||
Scenario: CL12. A stand-in agent, then a real one
|
||||
Then test/smoke.sh builds the image, starts it, and checks CL4-CL7, CL14 and CL15 with test/echo-agent.mjs (a
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
@spec
|
||||
Feature: forma, a headless modeller for hard-surface parts, run as its own program
|
||||
Shane, 2026-12-03, on github.com/wrong-nebula/forma: "can we make this an external package and integration we can
|
||||
use or allow agents to download... its a gpl license so idk what that means for us". forma is a ~1 MB pure-Rust
|
||||
modeller built for agents: a few lines of its pipe language (`box(4, 2, 0.4) | bevel(vertical, 0.25) | cut(cyl(0.5,
|
||||
1))`) make a watertight mesh with exact sizes in milliseconds, with semantic edge and face selectors instead of vertex
|
||||
indices. On 12-03 ten parts (gears, a flange, a threaded bolt, a mug, an enclosure, a lathed pawn, a lofted bottle,
|
||||
a table, a desk lamp, a lettered plate) each built in about 0.2 s through its npm CLI, and loaded straight into raea
|
||||
with <Model>. Two faults showed under raea's light: every colour pale (forma writes the sRGB value it was given into
|
||||
baseColorFactor, which glTF reads as linear) and every curve faceted (one normal per face). Its text is a blocky
|
||||
capitals-only face, and it can't make anything organic.
|
||||
|
||||
The licence: forma is GPL-3.0-or-later, raea is FSL-1.1, and the two can't be combined into one program. So raea
|
||||
never links forma's crates or bundles its WebAssembly into the SDK, the CLI or the apps. raea downloads forma's own
|
||||
release and runs it as a separate program, as it already does Blender (apps/tools/src/blender.rs), and works only
|
||||
on the files forma writes. The GPL covers forma, not what it makes, and running it on raea cloud isn't distributing
|
||||
it (GPLv3, not the AGPL).
|
||||
|
||||
Where it sits beside raea's own modelling (docs/blender.feature's framing): TSX is the scene; solids, sdf and grow
|
||||
make what numbers or rules define inside raea; forma is a faster way to make a hard-surface part an agent can check
|
||||
by its numbers (watertight, volume, box) before anyone looks; Blender stays the workshop for assets that are already
|
||||
good; raea gen and CC0 libraries make what looks define.
|
||||
|
||||
Background:
|
||||
Given raea pins one forma version (apps/forma VERSION, 0.4.4) with a hash for each download it makes
|
||||
And forma lives in ~/.raea/tools/forma, or wherever `git config --global raea.forma` points
|
||||
|
||||
Rule: Getting forma
|
||||
|
||||
@done
|
||||
Scenario: FM1. raea setup forma finds forma or downloads the pinned version
|
||||
Given `raea setup forma [--check] [--download]`
|
||||
When no forma is found (raea.forma, raea's download, a `forma` on PATH that says it is forma)
|
||||
Then on Linux (x86_64, aarch64) forma's static musl binary is downloaded from its GitHub release and checked
|
||||
against its pinned sha256: it needs no Node
|
||||
And elsewhere forma's npm package (forma-3d) is downloaded from the npm registry and checked against its pinned
|
||||
sha512, to be run by Node 18+ or Bun; with neither on PATH it says so before downloading anything
|
||||
And a download that doesn't match its hash installs nothing and says where it left the file
|
||||
And --check only says what would be used; --download replaces what is there
|
||||
And the report names forma's version, where it came from, and that forma is GPL and runs as its own program
|
||||
|
||||
Rule: Making parts
|
||||
|
||||
@done
|
||||
Scenario: FM2. raea forma makes a script's parts, strict by default
|
||||
Given `raea forma SCRIPT.forma -o OUT.glb|.stl|.obj|.3mf|.step [--unit U] [--render P.png] [--draw B.svg]`
|
||||
Then forma evaluates the script with --strict, and a .glb gets one node per named part (--scene)
|
||||
And forma's report (each part's vertices, watertight, volume, box) is printed as it wrote it
|
||||
And a part that isn't watertight is refused with forma's reason and nothing is written, unless --no-strict
|
||||
And a flag raea forma doesn't know is refused with the usage
|
||||
And `raea forma spec [--topic T] [--gbnf]` prints forma's own language reference
|
||||
|
||||
@done
|
||||
Scenario: FM3. A .glb's colours are made linear, as glTF reads them
|
||||
Given a .glb forma wrote, its baseColorFactor typed as sRGB
|
||||
Then each material's colour is converted sRGB to linear (alpha kept), so terracotta reads terracotta under raea's
|
||||
light and not pink
|
||||
And the file is marked in asset.extras.raea_forma, and a marked file is never converted twice
|
||||
And `raea forma fix FILE.glb... [--smooth DEG] [--flat]` does FM3 and FM4 to a .glb forma wrote by itself (its
|
||||
MCP server's export), with no forma needed
|
||||
|
||||
@done
|
||||
Scenario: FM4. A .glb's normals are smoothed where faces meet at under 40 degrees
|
||||
Given forma's one normal per face
|
||||
Then each corner takes the area-weighted mean of the faces at its position whose facing is within DEG of its own
|
||||
(--smooth DEG, 40 unless given), so a box keeps its edges and a cylinder's side turns round
|
||||
And positions, indices, UVs and the file's layout are kept byte for byte; only the normals' bytes change
|
||||
And --flat keeps forma's normals; a primitive with tangents, or one in a layout the fix doesn't read, is left alone
|
||||
|
||||
Scenario: FM5. The fixed parts under raea's light match what the script asked for
|
||||
Given the 12-03 table (scratchpad forma-try): ten parts made by `raea forma`, loaded with <Model>, one still
|
||||
Then each part's lit colour is within a JND of its typed colour lit the same way in a raea <Cuboid>
|
||||
And no curved part shows facets in a 4x crop
|
||||
|
||||
Rule: Agents
|
||||
|
||||
@done
|
||||
Scenario: FM6. raea skills install adds forma's MCP server
|
||||
Given `raea skills install --agent claude|codex|kimi|gemini`
|
||||
Then beside `blender`, a `forma` MCP server is registered: `npx -y -p forma-3d@VERSION forma-3d-mcp` (through
|
||||
`cmd /c` on Windows), fetched by npx when the agent first starts it
|
||||
And a server the person already registered under the name is left as they set it; --no-mcp adds neither
|
||||
|
||||
Scenario: FM7. The raea skill says when forma is the tool and when it isn't
|
||||
Given the raea skill (raea-skills, skills/raea/3d.md)
|
||||
Then it names forma for hard-surface parts numbers define (mechanical parts, props with exact sizes, a blockout's
|
||||
furniture) and `raea forma` over forma's own CLI, so the .glb comes out fixed
|
||||
And it names what forma is wrong for: anything organic (people, animals, cloth, plants), textures, lettering
|
||||
that has to look good, and the scene itself, which stays TSX
|
||||
And it says the MCP server's exports aren't fixed: a part meant for a render goes through `raea forma`, or
|
||||
`raea forma fix FILE.glb` after the server exported it
|
||||
@@ -37,7 +37,7 @@ raea fingerprint things shot.mp4 --json > things.json
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)
|
||||
raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
@@ -54,6 +54,7 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
|
||||
| `--axis` | `A` | The axis a label is for, by name, such as blur or clip |
|
||||
| `--bad` | – | The moment has the problem the axis names (the default) |
|
||||
| `--box` | `x0,y0,x1,y1` | Where in the frame the label is, as fractions of the width and height |
|
||||
| `--by` | `kimi\|claude` | With read: which fresh session reads your notes, kimi (the default) or claude |
|
||||
| `--extends` | `FP` | Another of your fingerprints to start from: the new one takes its axes and adds its own |
|
||||
| `--fp` | `CHILD` | Which fingerprint to use, by name; without it, the default |
|
||||
| `--from` | `LIST` | A file listing the renders to learn from, one path a line, relative to the file; lines starting with # are skipped |
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
---
|
||||
title: "raea forma"
|
||||
summary: "Make hard-surface parts from a few lines of forma's language: watertight meshes with exact sizes, written as a .glb raea renders."
|
||||
order: 117
|
||||
sources: ["apps/forma/src/lib.rs", "apps/forma/src/glb.rs", "apps/tools/src/agent_mcp.rs"]
|
||||
---
|
||||
|
||||
`raea forma` runs [forma](https://github.com/wrong-nebula/forma), a headless modeller for hard-surface parts, on a
|
||||
script in its pipe language, and writes the parts it makes: gears, brackets, threaded bolts, enclosures, a lathed vase,
|
||||
a table and its legs. Each named part is its own node in the .glb, every mesh is checked watertight, and a script
|
||||
evaluates in milliseconds, so an agent can write a part, read forma's report (sizes, volume, whether it is watertight)
|
||||
and change it in the same turn. Load the .glb with `<Model>` and light it in raea.
|
||||
|
||||
forma writes a material's colour as it was typed into the .glb, where glTF reads linear colour, so every part would
|
||||
render pale; and it writes one normal per face, so a curved side shows its facets. `raea forma` fixes both in the file
|
||||
after forma writes it: colours made linear, and corners smoothed where faces meet at under 40 degrees (a box keeps its
|
||||
edges, a cylinder's side turns round). The file is marked as fixed and never fixed twice. `raea forma fix` does the
|
||||
same to a .glb forma wrote by itself, through its MCP server or its own CLI.
|
||||
|
||||
forma is GPL-3.0-or-later, so raea never links it or ships it. [`raea setup forma`](setup.md) downloads forma's own
|
||||
release into `~/.raea/tools/forma` and `raea forma` runs it as a program of its own. What forma makes is yours.
|
||||
|
||||
```sh
|
||||
raea setup forma
|
||||
raea forma spec # the language, about 500 tokens
|
||||
raea forma bracket.forma -o assets/bracket.glb # strict: refused with forma's reason unless watertight
|
||||
raea forma gears.forma --unit mm -o assets/gears.glb --draw gears.svg
|
||||
raea forma fix assets/vase.glb # one the MCP server exported
|
||||
```
|
||||
|
||||
Use it for parts that numbers define: mechanical parts, props with exact sizes, a blockout's furniture. It is the wrong
|
||||
tool for anything organic (people, animals, cloth, plants), for textures, and for the scene itself, which stays TSX.
|
||||
`raea skills install` adds forma's own MCP server to an agent as `forma`, for modelling a part over several turns.
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea forma SCRIPT.forma -o OUT.glb|.stl|.obj|.3mf|.step [--unit m|cm|mm|um|in|ft] [--render PREVIEW.png] [--draw BLUEPRINT.svg] [--size PX] [--smooth DEG] [--flat] [--no-strict] (a forma script made into OUT, each named part its own node; a mesh that isn't watertight is refused with forma's reason unless --no-strict; a .glb's colours are made linear, as glTF reads them, and its normals smoothed where faces meet under DEG degrees (40 unless given; --flat keeps forma's faceted ones); --render's preview draws the last part, raea render draws them all)
|
||||
raea forma fix FILE.glb... [--smooth DEG] [--flat] (the same fix on a .glb forma wrote by itself (its MCP server's export, its own CLI): colours linear, normals smoothed; a file fixed before is left alone)
|
||||
raea forma spec [--topic deform|curves|uv|remesh|scene] [--gbnf] (forma's language reference, about 500 tokens: its primitives, operations and selectors)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--draw` | `BLUEPRINT.svg` | Also write a dimensioned SVG drawing of the parts. |
|
||||
| `--flat` | – | Keep forma's normals, one per face, faceted. |
|
||||
| `--gbnf` | – | With `spec`: print forma's GBNF grammar, for constrained decoding. |
|
||||
| `--no-strict` | – | Write the mesh even when it isn't watertight. |
|
||||
| `--render` | `PREVIEW.png` | Also write forma's own PNG preview (four views of the last part). |
|
||||
| `--size` | `PX` | The preview's size in pixels (512 unless given). |
|
||||
| `--smooth` | `DEG` | Smooth normals where faces meet at under DEG degrees (40 unless given). |
|
||||
| `--topic` | `deform\|curves\|uv\|remesh\|scene` | With `spec`: one topic's reference. |
|
||||
| `--unit` | `m\|cm\|mm\|um\|in\|ft` | The unit the script is written in (metres unless given); a .glb is always in metres. |
|
||||
| `-o` | `OUT.glb\|.stl\|.obj\|.3mf\|.step` | Where to write the parts; a .glb gets its colours and normals fixed. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -54,13 +54,11 @@ findings are then warnings.
|
||||
A rules goal (`rules({...})`, what raea.app's `/goal` writes) is any other work: the aim in your words and the rules
|
||||
that must hold before the agent stops. A `run` rule is a command that must exit 0 in the brief's folder (300 seconds
|
||||
unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is words that must be true of the
|
||||
work, judged by a fresh critic that may only read. `raea goal check` asks for the verdict itself when it's missing or
|
||||
older than the work (`raea goal judge` asks now), and keeps it in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's
|
||||
newest file. Who judges is raea's to settle, never the agent's: a rule with a piece to watch or hear (the files it
|
||||
names, in its "from A s to B s" window if it has one, else every video under out/) goes to clef-omni, as `raea ask`
|
||||
reaches it; any other goes to a fresh session of the agent this project runs on, which the raea app or raea cloud
|
||||
started (it offers the session's critic as `RAEA_JUDGE_URL`). Outside such a session a rule with nothing to watch
|
||||
stays open and says why.
|
||||
work, judged by a fresh critic that may only read: `raea goal judge` asks one (`--by claude`, `kimi` or `clef`) and
|
||||
keeps its verdict in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's
|
||||
newest file. `clef` is clef-omni, as `raea ask` reaches it: it watches and hears the files a rule names (in the rule's
|
||||
"from A s to B s" window if it has one), else every video under out/, and reads no folder, so a rule about text it
|
||||
can't see stays open. It is the critic where `RAEA_AGENT_KEY` is set, as on raea cloud; elsewhere the critic is `claude`.
|
||||
|
||||
```ts
|
||||
import { brief, rules } from "raea/brief"
|
||||
@@ -100,7 +98,7 @@ goal's rules are never copied into the plan: the plan is the work, the goal is w
|
||||
raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
|
||||
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
|
||||
raea goal seen FILE ["what you see and would change" --look "its design at full size, beside a reference"] [--surprise "SECONDS s: what it is"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size)
|
||||
raea goal judge [--goal NAME] (a goal's `says` rules judged now, as `raea goal check` judges them itself: a rule with a piece to watch or hear (a file it names, else the videos under out/) by clef-omni, any other by a fresh session of the agent this project runs on, which only reads; review/judge/NAME.json. Who judges is raea's to settle, never yours)
|
||||
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude)
|
||||
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)
|
||||
raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them)
|
||||
```
|
||||
@@ -113,6 +111,7 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
|
||||
| --- | --- | --- |
|
||||
| `--apply` | `EDITS.json\|-` | plan edits (JSON, `-` for stdin), each written where its task is written |
|
||||
| `--at` | `edit\|render\|publish\|done` | The moment `check` runs the rules of (default `done`); for `place`, the seconds to read (`S[,S...]`). |
|
||||
| `--by` | `claude\|kimi\|clef` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
|
||||
| `--goal` | `NAME` | only this goal of the brief's (by its name) |
|
||||
| `--json` | – | `check`: print the report (review/goal.json's shape). `gates`: the record and critic gates as JSON. |
|
||||
| `--look` | `"its design` | `seen`: a video's design judged on its frames at full size (FILE.looks/): its type, captions, cards and end beside a reference, and what was changed. |
|
||||
|
||||
@@ -101,7 +101,7 @@ Music read, voices, and the audio setup.
|
||||
|
||||
## raea make: the asset tools
|
||||
|
||||
What a project is made from, each a `raea make TOOL`: components, solids, clothes and motion for SOMA's body, splats, physics, light and weathering bakes, foley and instruments; and generated media, Blender and Godot.
|
||||
What a project is made from, each a `raea make TOOL`: components, solids, clothes and motion for SOMA's body, splats, physics, light and weathering bakes, foley and instruments; and generated media, Blender, Godot and forma.
|
||||
|
||||
| Verb | What it does |
|
||||
| --- | --- |
|
||||
@@ -120,6 +120,7 @@ What a project is made from, each a `raea make TOOL`: components, solids, clothe
|
||||
| [`raea gen`](gen.md) | Generate images, video, music, sound, speech, 3D models and text through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI. |
|
||||
| [`raea blender`](blender.md) | Run a Blender Python script headless, with raea's library of mesh scripts: convert, decimate, repair, split, bake, rig, cloth. |
|
||||
| [`raea godot`](godot.md) | Run a TypeScript script against Godot's whole API in a headless Godot with GodotJS, record what it draws as frames, or open the editor on the project. |
|
||||
| [`raea forma`](forma.md) | Make hard-surface parts from a few lines of forma's language: watertight meshes with exact sizes, written as a .glb raea renders. |
|
||||
|
||||
## Agents and setup
|
||||
|
||||
@@ -133,8 +134,8 @@ What an agent reads and shows the person, and the tools raea installs.
|
||||
| [`raea notes`](notes.md) | A person's notes as files the work is held to: each taken word for word, then restated as asks before anything changes. |
|
||||
| [`raea show`](show.md) | Show the person something in the raea app, as an item they can use and answer: stills, a video, a sound, a script, an interactive .tsx or a question. |
|
||||
| [`raea skill`](skill.md) | Print the agent skill this raea ships, matched to its version, or one of its references. |
|
||||
| [`raea skills`](skills.md) | Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP server and hook. |
|
||||
| [`raea setup`](setup.md) | Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on. |
|
||||
| [`raea skills`](skills.md) | Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP servers and hook. |
|
||||
| [`raea setup`](setup.md) | Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on; or download forma, Godot and the motion models. |
|
||||
| [`raea bug`](bug.md) | Report a bug in raea itself to raea's server: a line saying what's wrong and what happened, with raea's version and the OS added, no account needed. |
|
||||
| [`raea ask`](ask.md) | Ask about a piece's picture and sound: clef-omni answers in words and a probability, paid from your raea plan, and every answer is kept so a question can be calibrated. |
|
||||
|
||||
|
||||
@@ -6,9 +6,8 @@ sources: ["apps/judge/src/lib.rs", "apps/judge/src/rubric.rs", "apps/judge/src/a
|
||||
---
|
||||
|
||||
`raea judge` reads the sheets [`raea render --review`](render.md) makes (`colour.png`, `clay.png`) and has them
|
||||
judged without the code or the conversation that made them: by a fresh session of the agent this project runs on,
|
||||
on the judge prompt, where the raea app or raea cloud started that agent; else by clef-omni on a frozen rubric. Who
|
||||
judges is raea's to settle: there's no flag for it. The scores come back as data, and whether the scene passes is
|
||||
judged without the code or the conversation that made them: by clef-omni on a frozen rubric (the default), or by a
|
||||
fresh Kimi or Claude session on the judge prompt. The scores come back as data, and whether the scene passes is
|
||||
decided in code from them. clef only advises until it has been calibrated against a person's or an agent's eye.
|
||||
|
||||
`--kind scene|kit|shot` judges on that kind's own rubric, for a scene, kit or shot goal ([`raea goal`](goal.md)): a scene on layout,
|
||||
@@ -22,8 +21,8 @@ own.
|
||||
```sh
|
||||
raea render scene.tsx --review review/
|
||||
raea judge review/ --brief brief.ts
|
||||
raea judge review/ --target reference.png --json
|
||||
raea judge review/r3 --kind kit --brief brief.ts # a kit job's round, on the kit rubric
|
||||
raea judge review/ --by claude --target reference.png --json
|
||||
raea judge review/r3 --kind kit --by claude --brief brief.ts # a kit job's round, on the kit rubric
|
||||
raea judge eye review/ composition=4 light=3 --pass yes # record your own scores, for calibration
|
||||
raea judge calibrate
|
||||
```
|
||||
@@ -33,7 +32,7 @@ raea judge calibrate
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR [--read] [CATEGORY=SCORE ...] [--pass yes|no] | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: a fresh session of the project's own agent on the judge prompt where its host offers one, else clef-omni on the frozen rubric; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)
|
||||
raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
@@ -43,11 +42,11 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--brief` | `brief.ts` | The project's brief, so the judge knows what the scene is for. |
|
||||
| `--by` | `clef\|kimi\|claude` | Who judges: clef-omni on the rubric (default), or a fresh Kimi or Claude session. With `judge eye`, the agent whose eye is recorded. |
|
||||
| `--dry` | – | Print what the judge would be asked, with its images, without asking. |
|
||||
| `--json` | – | Print the verdict as JSON: each score, the defects found and the pass. |
|
||||
| `--kind` | `scene\|kit\|shot` | The rubric: `scene`, `kit` or `shot` (the make loop's categories), instead of the film rubric. |
|
||||
| `--pass` | `yes\|no` | With `judge eye`: whether you'd pass it, recorded with your scores. |
|
||||
| `--read` | – | With `judge eye`: a fresh session of the project's agent reads the round, recorded as its eye. |
|
||||
| `--target` | `T.png` | A reference image the colour sheet is judged against. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -1,16 +1,22 @@
|
||||
---
|
||||
title: "raea setup"
|
||||
summary: "Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on."
|
||||
summary: "Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on; or download forma, Godot and the motion models."
|
||||
order: 129
|
||||
sources: ["apps/tools/src/blender.rs"]
|
||||
sources: ["apps/tools/src/blender.rs", "apps/forma/src/lib.rs"]
|
||||
---
|
||||
|
||||
`raea setup blender` finds the Blender on this machine (from `git config raea.blender`, raea's own copy, /Applications or the `PATH`), or downloads the current LTS from blender.org into `~/.raea/tools/blender`. It then installs the add-on that
|
||||
lets an agent drive Blender over MCP. [`raea blender run`](blender.md) uses the Blender it found.
|
||||
|
||||
`raea setup forma` finds forma (from `git config raea.forma`, raea's own copy or the `PATH`), or downloads forma
|
||||
itself into `~/.raea/tools/forma`: its static binary on Linux, else its npm package, run by Node 18+ or Bun. Each is
|
||||
checked against the hash raea pins. forma is GPL-3.0-or-later, so it is fetched from forma's own release and never
|
||||
shipped with raea; [`raea forma`](forma.md) runs it as a program of its own.
|
||||
|
||||
```sh
|
||||
raea setup blender --check
|
||||
raea setup blender
|
||||
raea setup forma
|
||||
```
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
@@ -19,6 +25,7 @@ raea setup blender
|
||||
|
||||
```sh
|
||||
raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install raea's add-on and the MCP add-on)
|
||||
raea setup forma [--check] [--download] (find forma or download it into ~/.raea/tools/forma: forma 0.4.4, a headless modeller for hard-surface parts (GPL-3.0-or-later, so raea runs it as its own program and never ships it), its static binary on Linux, else its npm package run by Node 18+ or Bun, each checked against its pinned hash)
|
||||
raea setup motion [--check] (what raea make motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU)
|
||||
raea setup godot [--check] (download Godot 4.6.1 with GodotJS, its TypeScript bindings (MIT), into ~/.raea/tools/godot: JavaScriptCore on the Mac, QuickJS on Windows and Linux; raea's own build (the Mac's notarized), else GodotJS's, each checked against its pinned sha256)
|
||||
```
|
||||
@@ -29,7 +36,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--check` | – | Say which Blender would be used, without downloading or installing anything. |
|
||||
| `--download` | – | Download the LTS even when a Blender is already on this machine. |
|
||||
| `--check` | – | Say which Blender (or forma) would be used, without downloading or installing anything. |
|
||||
| `--download` | – | Download the LTS (or forma's pinned version) even when one is already on this machine. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
title: "raea skills"
|
||||
summary: "Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP server and hook."
|
||||
summary: "Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP servers and hook."
|
||||
order: 128
|
||||
sources: ["engine/cli/src/skill.rs"]
|
||||
---
|
||||
|
||||
`raea skills install` copies the skill this raea ships into the folder an agent reads skills from, stamped with this
|
||||
version: `~/.claude/skills` for Claude Code, `~/.agents/skills` for Codex, Kimi Code's skills folder, and
|
||||
`~/.gemini/skills` for Gemini. It also adds the Blender MCP server to the agent, and raea's hooks to every agent
|
||||
`~/.gemini/skills` for Gemini. It also adds the Blender and forma MCP servers to the agent, and raea's hooks to every agent
|
||||
([`raea hook`](hook.md)): media opened in the Mac's viewer goes to `raea show`, and the quick check runs after each
|
||||
saved composition. A skill folder that's a link (a checkout of raea-skills) is left as it is.
|
||||
|
||||
@@ -26,7 +26,7 @@ raea skills install --agent claude --pin quieter --pin bolder # /quieter and
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--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 adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)
|
||||
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--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 and forma MCP servers unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
@@ -37,7 +37,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
|
||||
| --- | --- | --- |
|
||||
| `--agent` | `claude\|codex\|kimi\|gemini\|grokbot` | Which agent to install for. |
|
||||
| `--no-hooks` | – | Leave Claude Code's settings alone: don't add the quick-check hook. |
|
||||
| `--no-mcp` | – | Don't add the Blender MCP server to the agent. |
|
||||
| `--no-mcp` | – | Don't add the Blender and forma MCP servers to the agent. |
|
||||
| `--pin` | `MOVE` | Install a note's guide as a skill of its own, so `/MOVE` loads just it (`quieter`, `bolder`, `layout`, `adapt` and the rest). Repeatable. |
|
||||
| `--reference` | `cli\|feed\|files\|sdk` | Used by `raea skill`; see [`raea skill`](skill.md). |
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ pub const GOAL_TS: &[&str] = &["check", "tasks", "seen", "judge"];
|
||||
pub const GOAL_USAGE: &str = "raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
|
||||
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
|
||||
raea goal seen FILE [\"what you see and would change\" --look \"its design at full size, beside a reference\"] [--surprise \"SECONDS s: what it is\"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size)
|
||||
raea goal judge [--goal NAME] (a goal's `says` rules judged now, as `raea goal check` judges them itself: a rule with a piece to watch or hear (a file it names, else the videos under out/) by clef-omni, any other by a fresh session of the agent this project runs on, which only reads; review/judge/NAME.json. Who judges is raea's to settle, never yours)
|
||||
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude)
|
||||
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)";
|
||||
|
||||
/// One of GOAL_TS's verbs (or `make place`): printed as it says, and the process exits with its code (1 on an
|
||||
|
||||
@@ -146,7 +146,7 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
let usage = format!("{usage}\n raea bug TITLE... --text TEXT [--command CMD] [--error TEXT] [--agent NAME] [--dry-run] (a bug in raea itself, not in your own composition, sent to raea's server with raea's version and the OS, no account needed: words only, paths, emails and keys taken out before it goes; five a day from a machine, the same bug again counted on the first report; --dry-run prints what would go and sends nothing)");
|
||||
let usage = format!("{usage}\n {} ({})\n {} ({})", raea_sys_fixes::USAGE, raea_sys_fixes::ABOUT, raea_app_voice::USAGE, raea_app_voice::ABOUT); // a problem looked up before it's guessed at (systems/fixes); speech to speech (apps/voice)
|
||||
// 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|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\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|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\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 raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
|
||||
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\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|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\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 raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::forma::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
|
||||
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
|
||||
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, format!("{GOAL_USAGE}\n {}", raea_app_make::USAGE), raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
|
||||
return Ok(usage::under_make(&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 words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\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 make component list [WORDS] [--json] | raea make component show NAME [--json] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use and by how people ask: text/reveal, \"count up\", \"chat input\", template; show tells one in full: what it draws, when to use it and when not, its props)\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 --pick X,Y --view YAW,PITCH,DISTANCE --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 {} ({})\n {capcut}\n {layers}\n {xml}\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 {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\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 {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\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)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
|
||||
@@ -196,7 +196,8 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
if args[0] == "setup" && args.get(1).map(String::as_str) == Some("motion") {
|
||||
return tools::motion::setup(&args[2..]);
|
||||
}
|
||||
// `setup blender|godot`, `blender ...` and `godot ...`: Blender and Godot scripted (SK11, apps/engines)
|
||||
// `setup blender|godot|forma`, `blender ...`, `godot ...` and `forma ...`: Blender and Godot scripted, forma run (SK11,
|
||||
// apps/engines, apps/forma)
|
||||
if let Some(done) = raea_app_engines::cli(args) {
|
||||
return done;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! `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|grokbot [--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 adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)";
|
||||
pub const USAGE: &str = "raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--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 and forma MCP servers unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)";
|
||||
|
||||
/// `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> {
|
||||
@@ -117,7 +117,7 @@ pub fn install(args: &[String]) -> R<String> {
|
||||
if agent == "grokbot" { return tools::agent_grokbot::stage(&to, out); }
|
||||
// every agent's hooks (A5d, SK10), in its own config: --no-hooks leaves it alone
|
||||
if !args.iter().any(|a| a == "--no-hooks") { out += &tools::agent_hooks::install(agent)?; }
|
||||
// the MCP servers raea offers (SK11): blender, for a running Blender; --no-mcp leaves the agent's servers alone
|
||||
// the MCP servers raea offers (SK11): blender, for a running Blender, and forma (FM6); --no-mcp leaves the agent's servers alone
|
||||
if !args.iter().any(|a| a == "--no-mcp") {
|
||||
out += &tools::agent_mcp::offer(agent)?;
|
||||
out += "\n";
|
||||
|
||||
@@ -32,7 +32,7 @@ fn help_lists_every_verb() {
|
||||
let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));
|
||||
let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();
|
||||
assert!(missing.is_empty(), "not in raea help: {missing:?}");
|
||||
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_playable::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
|
||||
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_playable::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_engines::forma::USAGE, raea_app_lightbake::USAGE] {
|
||||
assert!(help.contains(usage), "{usage}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
//! The critic a project's rules are judged by when the judgement needs reading rather than watching (Shane, 12-03:
|
||||
//! never a harness raea picks or the agent names): a fresh session of the agent this project runs on, which the host
|
||||
//! that started the agent (raea cloud's box, sdk/cloud/server/critic.ts; the raea app) offers as RAEA_JUDGE_URL, with
|
||||
//! the session's RAEA_JUDGE_TOKEN. `raea judge`, `raea fingerprint read` and `raea goal judge` (sdk/goal) ask it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// What a person reads when there's no critic here: no tool, agent or model named, because none is theirs to pick.
|
||||
pub const NONE_HERE: &str = "an agent's reading is a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has";
|
||||
|
||||
/// Whether this session has a critic to ask.
|
||||
pub fn here() -> bool {
|
||||
std::env::var("RAEA_JUDGE_URL").is_ok_and(|u| !u.is_empty())
|
||||
}
|
||||
|
||||
/// One question to a fresh session of this project's agent, in `cwd`: what it says back.
|
||||
pub fn ask(cwd: &std::path::Path, prompt: &str) -> Result<String, String> {
|
||||
let url = std::env::var("RAEA_JUDGE_URL").ok().filter(|u| !u.is_empty()).ok_or(NONE_HERE)?;
|
||||
let token = std::env::var("RAEA_JUDGE_TOKEN").unwrap_or_default();
|
||||
let r = ureq::post(&url).set("authorization", &format!("Bearer {token}")).timeout(std::time::Duration::from_secs(15 * 60))
|
||||
.send_json(json!({"cwd": cwd.display().to_string(), "prompt": prompt}));
|
||||
let body: Value = match r {
|
||||
Ok(r) => r.into_json().map_err(|e| format!("the critic's answer: {e}"))?,
|
||||
Err(ureq::Error::Status(_, r)) => return Err(format!("the critic couldn't: {}", r.into_json::<Value>().ok().and_then(|v| v["error"].as_str().map(String::from)).unwrap_or_default())),
|
||||
Err(e) => return Err(format!("the critic: {e}")),
|
||||
};
|
||||
body["text"].as_str().map(String::from).ok_or_else(|| "the critic gave no text".into())
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
pub mod cache;
|
||||
pub mod client;
|
||||
pub mod critic;
|
||||
pub mod media;
|
||||
pub mod route;
|
||||
|
||||
|
||||
@@ -2,6 +2,3 @@ node_modules
|
||||
deploy
|
||||
test
|
||||
README.md
|
||||
# a box image (deploy/fly/Dockerfile) takes these two from deploy/
|
||||
!deploy/git
|
||||
!deploy/fly/start.sh
|
||||
@@ -1,71 +0,0 @@
|
||||
# A raea cloud box as a Fly Machine (12-03: the boxes moved off Sprites, which ran at most 10 at once, read their disk
|
||||
# in about 26 ms a read, and stopped at 8 cores and 16 GB). What deploy/sprites/setup.sh put on a Sprite is built in
|
||||
# here once: Ubuntu as the Sprites ran it, raea's Linux release, Node, Chrome for the Google sign-in, ffmpeg, the PDF
|
||||
# tools and brand faces, the ACP agents and sdk/cloud's server. The home folder (/home/raea: the agents' sign-ins,
|
||||
# ~/.raea-cloud.env, ~/work) is the Machine's volume, so a new image changes the programs and keeps everything else.
|
||||
# deploy/fly/box.sh builds it from sdk/cloud:
|
||||
#
|
||||
# fly deploy --build-only --push -c deploy/fly/image.toml --build-arg RAEA_VERSION=0.1.17-rc3 ...
|
||||
FROM ubuntu:26.04
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# what setup.sh installed: raea's runtime libraries and Mesa's lavapipe (the box draws previews on its CPU; its renders
|
||||
# go to the farm), ffmpeg and the PDF tools (12-02: every agent installed them itself at each project's start), Python
|
||||
# (the footage prep's transcript file), the sign-in browser's display, and sudo for an agent that needs a package
|
||||
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \
|
||||
ca-certificates curl git git-lfs zstd xz-utils bzip2 unzip procps less ripgrep openssl sudo python3 \
|
||||
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools ffmpeg poppler-utils \
|
||||
xvfb x11vnc xdotool fonts-noto-color-emoji > /dev/null \
|
||||
&& for f in fonts-inter fonts-roboto fonts-open-sans fonts-lato fonts-montserrat fonts-noto-core fonts-ibm-plex \
|
||||
fonts-bebas-neue fonts-urw-base35 fonts-liberation2; do apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || echo "no $f"; done \
|
||||
&& curl -fsSLo /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb \
|
||||
&& apt-get install -y -qq /tmp/chrome.deb > /dev/null && rm -f /tmp/chrome.deb \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ARG NODE=24.22.0
|
||||
RUN curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | tar -xJ -C /opt \
|
||||
&& ln -sf /opt/node-v$NODE-linux-x64/bin/node /opt/node-v$NODE-linux-x64/bin/npm /opt/node-v$NODE-linux-x64/bin/npx /usr/local/bin/
|
||||
|
||||
# the box's user, uid 1000 as the image's entrypoint expects; /home/sprite is the same folder, so the paths a project
|
||||
# moved from a Sprite wrote down (its agents' transcripts, its settings) still open
|
||||
RUN (userdel -r ubuntu 2> /dev/null || true) && useradd -m -u 1000 -s /bin/bash raea \
|
||||
&& echo 'raea ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/raea && chmod 440 /etc/sudoers.d/raea \
|
||||
&& ln -s /home/raea /home/sprite
|
||||
|
||||
# raea, checked against its release's .sha256
|
||||
ARG RAEA_VERSION
|
||||
ARG RAEA_REPO=shinyobjectz/raea
|
||||
RUN set -e; : "${RAEA_VERSION:?--build-arg RAEA_VERSION}"; f=raea-$RAEA_VERSION-linux-x86_64.tar.gz; \
|
||||
u=https://github.com/$RAEA_REPO/releases/download/v$RAEA_VERSION; \
|
||||
cd /tmp && curl -fsSL -o $f "$u/$f" && curl -fsSL -o $f.sha256 "$u/$f.sha256" && sha256sum -c --quiet $f.sha256 \
|
||||
&& mkdir -p /opt/raea && tar -xzf $f -C /opt/raea --strip-components=1 && rm -f $f $f.sha256 \
|
||||
&& /opt/raea/bin/raea --version
|
||||
|
||||
WORKDIR /opt/raea-cloud
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev --no-fund --no-audit --loglevel=error
|
||||
# the agents, by ACP registry id, with the server they're started by (agents.ts reads its neighbours)
|
||||
COPY server server
|
||||
ARG AGENTS="antigravity-acp claude-acp kimi-code"
|
||||
RUN node server/agents.ts install $AGENTS
|
||||
COPY src src
|
||||
COPY image image
|
||||
COPY deploy/git deploy/git
|
||||
COPY deploy/fly/start.sh image/fly-start.sh
|
||||
# readable by raea whatever modes the files had where the image was built (12-03: a checkout made with umask 077 gave
|
||||
# the entrypoint 711, and it re-runs itself as raea)
|
||||
RUN chmod -R a+rX /opt/raea-cloud && chmod +x image/*.sh deploy/git/* \
|
||||
&& ln -sf /opt/raea-cloud/image/raea.sh /usr/local/bin/raea \
|
||||
&& ln -sf /opt/raea-cloud/deploy/git/repo.sh /usr/local/bin/raea-repo \
|
||||
&& git lfs install --system --skip-repo > /dev/null
|
||||
|
||||
# the build, shown on GET /v1/health and raea cloud's /v1/admin/boxes, so which code a box runs is never a guess
|
||||
ARG COMMIT=unknown
|
||||
ARG DIRTY=false
|
||||
RUN printf '{"commit":"%s","build":"%.12s","dirty":%s,"raea":"%s","image":"fly","built_at":"%s"}\n' \
|
||||
"$COMMIT" "$COMMIT" "$DIRTY" "$RAEA_VERSION" "$(date -u +%Y-%m-%dT%H:%M:%S+00:00)" > /opt/raea-cloud/BUILD.json
|
||||
|
||||
# RAEA_CLOUD_IDLE_STOP_MIN: the server exits when the box has been idle this long, and the Machine stops (idle.ts)
|
||||
ENV HOME=/home/raea NODE_ENV=production PORT=8080 WGPU_BACKEND=vulkan RAEA_CLOUD_DEVICE=cpu RAEA_CLOUD_IDLE_STOP_MIN=10
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/opt/raea-cloud/image/fly-start.sh"]
|
||||
@@ -1,234 +0,0 @@
|
||||
#!/bin/bash
|
||||
# raea cloud's agent boxes as Fly Machines (12-03; they were Sprites, deploy/sprites/, which ran at most 10 at once and
|
||||
# read their disk in about 26 ms a read). Each box is a Fly app of its own (raea-box-2 is the box raea-2) with one
|
||||
# Machine of the box image (Dockerfile here) and one volume for its home folder: the agents' sign-ins, the box's
|
||||
# settings (~/.raea-cloud.env) and ~/work. The Machine stops itself when the box is idle (server/idle.ts) and Fly's
|
||||
# proxy starts it at the next request, so it bills while it works. From sdk/cloud:
|
||||
#
|
||||
# deploy/fly/box.sh image [VERSION] the box image built and pushed: raea VERSION's Linux release (the newest when
|
||||
# none is named) and sdk/cloud's server from this tree (RAEA_CLOUD_REF: from
|
||||
# raea's repo at that commit). Prints the image, kept in ~/.config/raea-cloud/fly-image
|
||||
# deploy/fly/box.sh up NAME the box made or brought onto the last image built: its app, addresses, volume,
|
||||
# settings and Machine, then its health
|
||||
# deploy/fly/box.sh move NAME a Sprite box onto Fly: its settings (its token too, so raea cloud's list only
|
||||
# changes address) and its home folder copied, then listed in raea cloud
|
||||
# deploy/fly/box.sh register NAME the box into raea cloud's list at its Fly address (POST /v1/admin/boxes)
|
||||
# deploy/fly/box.sh status NAME its address, Machine and health
|
||||
# deploy/fly/box.sh token NAME its RAEA_CLOUD_TOKEN
|
||||
# deploy/fly/box.sh list raea cloud's boxes in order, each one's health and build
|
||||
# deploy/fly/box.sh latest [VERSION] the image built for a release and every Fly box in raea cloud's list put on it
|
||||
# deploy/fly/box.sh key NAME a raea agent key (raea_ak_...) from stdin, or the clipboard, onto the box
|
||||
# deploy/fly/box.sh sh NAME [CMD] a shell on the box (as root), or CMD there
|
||||
#
|
||||
# The org is raea's, written once in ~/.config/raea-cloud/fly.env (RAEA_FLY_ORG=raea), never another business's. Each
|
||||
# box's settings are kept on this Mac too, in ~/.config/raea-cloud/boxes/NAME.env (mode 600), and go to the box as Fly
|
||||
# secrets; the farm's come from ~/.config/raea-cloud/farm.env.
|
||||
set -euo pipefail
|
||||
REPO=shinyobjectz/raea
|
||||
HERE=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
CONF=$HOME/.config/raea-cloud
|
||||
FLY_CONF=${RAEA_FLY_ENV:-$CONF/fly.env}
|
||||
ORG=$([ -f "$FLY_CONF" ] && sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1 || true)
|
||||
[ -n "$ORG" ] || { echo "fly box: write RAEA_FLY_ORG=<the Fly org raea owns> in $FLY_CONF (fly orgs list)"; exit 2; }
|
||||
# Content Jet's org and any other business's: never (private/cloud/sprites-denied.txt lists them for Sprites too)
|
||||
DENIED=$(git -C "$HERE" rev-parse --show-toplevel 2> /dev/null)/private/cloud/sprites-denied.txt
|
||||
if { [ -f "$DENIED" ] && grep -qxF "$ORG" "$DENIED"; } || [ "$ORG" = kamal-hafid ]; then
|
||||
echo "fly box: $ORG belongs to another business; raea's boxes go in an org raea owns"; exit 2
|
||||
fi
|
||||
REGION=${RAEA_FLY_REGION:-iad}
|
||||
SIZE=${RAEA_BOX_SIZE:-performance-8x}
|
||||
VOLUME_GB=${RAEA_BOX_DISK_GB:-100}
|
||||
IMAGE_APP=raea-box-image
|
||||
FARM=${RAEA_FARM_ENV:-$CONF/farm.env}
|
||||
newest() { gh release view -R "$REPO" --json tagName -q .tagName 2> /dev/null | sed 's/^v//'; }
|
||||
NAME=${2:-}
|
||||
app() { echo "raea-box-${1#raea-}"; }
|
||||
url() { echo "https://$(app "$1").fly.dev"; }
|
||||
envfile() { echo "$CONF/boxes/$1.env"; }
|
||||
need_name() { [ -n "$NAME" ] || { echo "fly box: name the box (raea-2)"; exit 2; }; }
|
||||
# whether the org has an app by this name (fly apps list --json: its table draws borders round each name)
|
||||
has_app() { fly apps list --org "$ORG" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(a.get("Name") == sys.argv[1] for a in json.load(sys.stdin)) else 1)' "$1"; }
|
||||
machine() { fly machines list -a "$(app "$1")" --json 2> /dev/null | python3 -c 'import json,sys
|
||||
m=[x for x in json.load(sys.stdin) if x.get("state")!="destroyed"]
|
||||
print(m[0]["id"] if m else "")'; }
|
||||
healthy() {
|
||||
local u t
|
||||
u=$(url "$1") t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$1")")
|
||||
for _ in $(seq 1 60); do
|
||||
curl -fsS -m 20 -H "authorization: Bearer $t" "$u/v1/health" 2> /dev/null && return 0
|
||||
sleep 5
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
image)
|
||||
version=${2:-${RAEA_VERSION:-$(newest)}}
|
||||
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
|
||||
src=$HERE
|
||||
if [ -n "${RAEA_CLOUD_REF:-}" ]; then
|
||||
# sdk/cloud at that commit of raea's repo, as a release's boxes take it
|
||||
src=$(mktemp -d)
|
||||
git -C "$src" init -q && git -C "$src" sparse-checkout set sdk/cloud
|
||||
git -C "$src" fetch -q --depth 1 --filter=blob:none "https://github.com/$REPO" "$RAEA_CLOUD_REF" && git -C "$src" checkout -q FETCH_HEAD
|
||||
src=$src/sdk/cloud
|
||||
commit=$RAEA_CLOUD_REF dirty=false
|
||||
else
|
||||
commit=$(git -C "$HERE" rev-parse HEAD)
|
||||
dirty=$([ -n "$(git -C "$HERE" status --porcelain -- .)" ] && echo true || echo false)
|
||||
fi
|
||||
has_app "$IMAGE_APP" || fly apps create "$IMAGE_APP" --org "$ORG" > /dev/null
|
||||
# (|| true: on a clean tree the test fails, and set -e ended the script there with nothing said)
|
||||
label=v$version-${commit:0:10}$([ "$dirty" = true ] && echo "-dirty-$(date +%s)" || true)
|
||||
(cd "$src" && fly deploy --build-only --push -a "$IMAGE_APP" -c deploy/fly/image.toml --dockerfile deploy/fly/Dockerfile \
|
||||
--image-label "$label" --build-arg RAEA_VERSION="$version" --build-arg COMMIT="$commit" --build-arg DIRTY="$dirty" .) >&2
|
||||
echo "registry.fly.io/$IMAGE_APP:$label" | tee "$CONF/fly-image"
|
||||
;;
|
||||
up)
|
||||
need_name
|
||||
image=${RAEA_BOX_IMAGE:-$(cat "$CONF/fly-image" 2> /dev/null || true)}
|
||||
[ -n "$image" ] || { echo "fly box: no image built yet (deploy/fly/box.sh image)"; exit 2; }
|
||||
a=$(app "$NAME") f=$(envfile "$NAME")
|
||||
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
|
||||
if [ ! -s "$f" ]; then
|
||||
# a new box: its own token, and the farm's settings
|
||||
[ -f "$FARM" ] || { echo "fly box: $FARM names no farm (RAEA_CLOUD_GPU_URL, RAEA_CLOUD_GPU_TOKEN)"; exit 2; }
|
||||
(umask 077; { echo "RAEA_CLOUD_TOKEN=$(openssl rand -hex 32)"; grep '^RAEA_CLOUD_GPU_' "$FARM"; echo "RAEA_API=https://api.raea.cloud"; } > "$f")
|
||||
echo "fly box: $NAME is new: settings in $f (its agent key: deploy/fly/box.sh key $NAME)"
|
||||
fi
|
||||
has_app "$a" || fly apps create "$a" --org "$ORG" > /dev/null
|
||||
fly ips list -a "$a" 2> /dev/null | grep -q 'v6' || {
|
||||
fly ips allocate-v4 --shared -a "$a" > /dev/null
|
||||
fly ips allocate-v6 -a "$a" > /dev/null
|
||||
}
|
||||
# the box's settings as Fly secrets, from the file (never on a command line)
|
||||
fly secrets import --stage -a "$a" < "$f" > /dev/null
|
||||
fly volumes list -a "$a" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(v.get("name") == "home" and v.get("state") != "destroyed" for v in json.load(sys.stdin)) else 1)' || fly volumes create home --size "$VOLUME_GB" --region "$REGION" -a "$a" -y > /dev/null
|
||||
id=$(machine "$NAME")
|
||||
if [ -z "$id" ]; then
|
||||
fly machine run "$image" -a "$a" -r "$REGION" --vm-size "$SIZE" -v home:/home/raea -n box \
|
||||
-p 443:8080/tcp:tls:http -p 80:8080/tcp:http --autostart --autostop=off --restart on-failure --detach > /dev/null
|
||||
# a Machine made by run takes the app's secrets as it's made; from then on the box reads its settings from
|
||||
# ~/.raea-cloud.env on its volume (start.sh)
|
||||
fly secrets deploy -a "$a" > /dev/null 2>&1 || true
|
||||
elif [ "$(fly machines list -a "$a" --json 2> /dev/null | python3 -c 'import json, sys; print(json.load(sys.stdin)[0]["config"]["image"].split("@")[0])')" != "${image%@*}" ]; then
|
||||
# a new image: the Machine made again from it (it restarts; its volume stays). Only then: a restart cut off a
|
||||
# home's upload that had started after the health check passed on the instance before it (12-03, raea-3, 5, 11)
|
||||
fly machine update "$id" -a "$a" --image "$image" --vm-size "$SIZE" --autostart --autostop=off --restart on-failure -y > /dev/null
|
||||
fly machine wait "$id" -a "$a" --state started --wait-timeout 120 > /dev/null 2>&1 || true
|
||||
fi
|
||||
healthy "$NAME" > /dev/null || { echo "fly box: $NAME didn't answer at $(url "$NAME")"; exit 1; }
|
||||
"$0" status "$NAME"
|
||||
;;
|
||||
move)
|
||||
need_name
|
||||
# the Sprite's settings, its token among them, so raea cloud only changes the box's address
|
||||
. "$(dirname "$0")/../sprites/org.sh"
|
||||
f=$(envfile "$NAME")
|
||||
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
|
||||
(umask 077; sprite exec -o "$ORG" -s "$NAME" -- cat /home/sprite/.raea-cloud.env > "$f")
|
||||
grep -q '^RAEA_CLOUD_TOKEN=' "$f" || { echo "fly box: couldn't read $NAME's settings from its Sprite"; exit 1; }
|
||||
ORG=$(sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1) "$0" up "$NAME"
|
||||
# its home folder, but for caches anything can make again: agents' sign-ins, their sessions, ~/work. Sent by the
|
||||
# Sprite itself straight to the new box's file API (it streams to disk), never through this Mac (12-03: through
|
||||
# sprite exec it came at about 4 MB/s), then unpacked there
|
||||
a=$(app "$NAME")
|
||||
# a home that arrived whole in a try before this one is unpacked, not sent again (a .part is only part of one)
|
||||
healthy "$NAME" > /dev/null || true
|
||||
if fly ssh console -a "$a" -q -C "test -s /home/raea/work/.move/home.tar.zst" > /dev/null 2>&1; then
|
||||
echo "fly box: $NAME's home arrived in a try before this one: unpacking it"
|
||||
else
|
||||
fly ssh console -a "$a" -q -C "rm -rf /home/raea/work/.move" > /dev/null 2>&1 || true
|
||||
echo "fly box: sending $NAME's home from its Sprite to $(url "$NAME")"
|
||||
# --no-stdin: a dropped link to the Sprite reconnects to the same session (12-03: all four copies lost theirs at
|
||||
# once, 6 minutes in, and with stdin attached sprite exec refuses to reconnect)
|
||||
sprite exec --no-stdin -o "$ORG" -s "$NAME" -- bash -c ". ~/.raea-cloud.env && tar -C /home/sprite --exclude=./.cache --exclude=./.npm --exclude=./.raea-cloud.env --exclude=./work/.move -cf - . | zstd -q -T0 -3 | curl -fsS --retry 0 -T - -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" '$(url "$NAME")/v1/files?path=.move/home.tar.zst' && echo SENT-WHOLE" > "$CONF/boxes/$NAME.move.log" 2>&1 &
|
||||
sending=$!
|
||||
# what has arrived, every 15 s; nothing more in MOVE_STILL_S (2 minutes) and the copy is stopped there, never waited
|
||||
# out (12-03, Shane: fail fast at every step)
|
||||
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$f" | tail -1)
|
||||
got=-1 since=$SECONDS
|
||||
while kill -0 "$sending" 2> /dev/null; do
|
||||
n=$(curl -s -m 20 -H "authorization: Bearer $tok" "$(url "$NAME")/v1/files?path=.move" | python3 -c 'import json, sys
|
||||
try: print(sum(d.get("bytes") or 0 for d in json.load(sys.stdin)))
|
||||
except Exception: print(-1)')
|
||||
if [ "${n:--1}" -gt "$got" ]; then
|
||||
echo "fly box: $NAME: $((n / 1048576)) MB arrived"
|
||||
got=$n since=$SECONDS
|
||||
elif [ $((SECONDS - since)) -ge "${MOVE_STILL_S:-120}" ]; then
|
||||
kill "$sending" 2> /dev/null
|
||||
echo "fly box: $NAME's upload stopped growing at $((got / 1048576)) MB for $((SECONDS - since)) s: stopped; run move again"
|
||||
exit 1
|
||||
fi
|
||||
sleep 15
|
||||
done
|
||||
wait "$sending"
|
||||
grep -v 'bind: warning' "$CONF/boxes/$NAME.move.log"
|
||||
grep -q SENT-WHOLE "$CONF/boxes/$NAME.move.log" || { echo "fly box: $NAME's home didn't arrive whole (above); nothing unpacked, run move again"; exit 1; }
|
||||
fi
|
||||
# unpacked there, saying so every 500 MB (a silent unpack of 26 GB looked stalled: 12-03, raea-4 and raea-6)
|
||||
# run from inside the work folder, which the box's idle stop sees as work going on (server/idle.ts); the box woken
|
||||
# first, as fly ssh doesn't start a stopped Machine
|
||||
healthy "$NAME" > /dev/null || true
|
||||
# and the box held while it unpacks (~/.raea-hold, which its idle stop reads): its image may be older than idle.ts's
|
||||
# real-path match
|
||||
fly ssh console -a "$a" -q -C "sh -c '(while kill -0 \$\$ 2> /dev/null; do touch /home/raea/.raea-hold; sleep 60; done) & cd /home/raea/work/.move && zstd -dqc home.tar.zst | tar -C /home/raea -xf - --checkpoint=50000 --checkpoint-action=echo=\"fly box: $NAME: %{}T unpacked\" && cd /home/raea && rm -rf work/.move && chown -R raea:raea /home/raea && du -sh /home/raea'"
|
||||
# its own settings on its disk too, as a Sprite kept them
|
||||
fly ssh console -a "$a" -q -C "sh -c 'umask 077; cat > /home/raea/.raea-cloud.env && chown raea:raea /home/raea/.raea-cloud.env'" < "$f"
|
||||
# RAEA_BOX_REGISTER=0: copied, but raea cloud still sends work to the Sprite until deploy/fly/box.sh register NAME
|
||||
if [ "${RAEA_BOX_REGISTER:-1}" = 0 ]; then echo "fly box: $NAME copied; not registered yet"; else "$0" register "$NAME"; fi
|
||||
;;
|
||||
register)
|
||||
need_name
|
||||
api=${RAEA_CLOUD_API:-https://api.raea.cloud}
|
||||
key=${RAEA_CLOUD_ADMIN_KEY:-$(security find-generic-password -s raea-cloud-prod-staff-key -w 2> /dev/null || true)}
|
||||
[ -n "$key" ] || { echo "fly box: no staff key (RAEA_CLOUD_ADMIN_KEY, or raea-cloud-prod-staff-key in the keychain)"; exit 2; }
|
||||
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
|
||||
body=$(python3 -c 'import json,sys; print(json.dumps({"name": sys.argv[1], "url": sys.argv[2], "token": sys.argv[3], "first": sys.argv[4] == "1"}))' "$NAME" "$(url "$NAME")" "$tok" "${RAEA_BOX_FIRST:-0}")
|
||||
curl -fsS -X POST -H "authorization: Bearer $key" -H 'content-type: application/json' --data-binary @- "$api/v1/admin/boxes" <<< "$body" > /dev/null || { echo "fly box: raea cloud refused $NAME"; exit 1; }
|
||||
echo "fly box: $NAME is listed in raea cloud at $(url "$NAME")"
|
||||
;;
|
||||
status)
|
||||
need_name
|
||||
echo "$(url "$NAME") machine $(machine "$NAME")"
|
||||
t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
|
||||
curl -fsS -m 60 -H "authorization: Bearer $t" "$(url "$NAME")/v1/health" | head -c 600
|
||||
echo
|
||||
;;
|
||||
token) need_name; sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")" ;;
|
||||
list) exec "$(dirname "$0")/../sprites/box.sh" list ;;
|
||||
latest)
|
||||
version=${2:-$(newest)}
|
||||
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
|
||||
linux=raea-$version-linux-x86_64.tar.gz
|
||||
gh release view "v$version" -R "$REPO" --json assets -q '.assets[].name' 2> /dev/null | grep -qx "$linux" || { echo "fly box: v$version has no $linux yet: no box changed"; exit 1; }
|
||||
ref=$(gh api "repos/$REPO/commits/v$version" -q .sha) || { echo "fly box: couldn't read v$version's commit"; exit 1; }
|
||||
RAEA_CLOUD_REF=$ref "$0" image "$version" > /dev/null
|
||||
names=$("$0" list | sed 's/^[* ] *//' | awk '{print $1}' | grep '^raea-' || true)
|
||||
failed=""
|
||||
for b in $names; do
|
||||
[ -s "$(envfile "$b")" ] || { echo "fly box: $b isn't a Fly box here (no $(envfile "$b")): passed over"; continue; }
|
||||
echo "fly box: $b onto raea $version (${ref:0:10})"
|
||||
"$0" up "$b" > /dev/null || failed+=" $b"
|
||||
done
|
||||
[ -z "$failed" ] || { echo "fly box: not on $version:$failed"; exit 1; }
|
||||
echo "fly box: every Fly box is on raea $version"
|
||||
;;
|
||||
key)
|
||||
need_name
|
||||
if [ -t 0 ]; then k=$(pbpaste); else k=$(cat); fi
|
||||
k=$(printf %s "$k" | tr -d '[:space:]')
|
||||
case "$k" in raea_ak_*) ;; *) echo "fly box: that isn't a raea agent key (raea_ak_...)"; exit 2 ;; esac
|
||||
f=$(envfile "$NAME")
|
||||
(umask 077; { grep -v '^RAEA_AGENT_KEY=' "$f" || true; echo "RAEA_AGENT_KEY=$k"; } > "$f.new" && mv "$f.new" "$f")
|
||||
printf 'RAEA_AGENT_KEY=%s\n' "$k" | fly secrets import -a "$(app "$NAME")" > /dev/null && echo "fly box: agent key on $NAME, its Machine restarted"
|
||||
;;
|
||||
sh)
|
||||
need_name
|
||||
if [ -n "${3:-}" ]; then fly ssh console -a "$(app "$NAME")" -q -C "$3"; else fly ssh console -a "$(app "$NAME")"; fi
|
||||
;;
|
||||
*)
|
||||
sed -n '2,25p' "$0"
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -1,7 +0,0 @@
|
||||
# The app whose registry holds the box image (deploy/fly/box.sh image): it runs no machines of its own. Each box is an
|
||||
# app of its own (raea-box-2, ...) whose one Machine runs this image with its volume.
|
||||
app = "raea-box-image"
|
||||
primary_region = "iad"
|
||||
|
||||
[build]
|
||||
dockerfile = "Dockerfile"
|
||||
@@ -1,43 +0,0 @@
|
||||
#!/bin/bash
|
||||
# A Fly box's start, as root: the volume made the box's home, the box's own settings read from it, then the image's
|
||||
# entrypoint (image/entrypoint.sh), which goes on as raea and runs the server. The server exits 0 when the box has been
|
||||
# idle RAEA_CLOUD_IDLE_STOP_MIN minutes (server/idle.ts), and with the Machine's restart policy on-failure it then stays
|
||||
# stopped until Fly's proxy starts it for the next request.
|
||||
set -uo pipefail
|
||||
H=/home/raea
|
||||
# the box's name: RAEA_BOX, else the app's (raea-box-2 is the box raea-2)
|
||||
BOX=${RAEA_BOX:-${FLY_APP_NAME:-box}}
|
||||
BOX=${BOX/raea-box-/raea-}
|
||||
mkdir -p "$H/work"
|
||||
[ "$(stat -c %u "$H")" = 1000 ] || chown -R raea:raea "$H"
|
||||
[ "$(stat -c %u "$H/work")" = 1000 ] || chown raea:raea "$H/work"
|
||||
# footage is read 16 MB ahead (setup.sh's 12-01 measure on a Sprite; a volume gains the same on long reads)
|
||||
for b in /sys/block/*/queue/read_ahead_kb; do echo 16384 > "$b" 2> /dev/null || true; done
|
||||
# the box's own token, the farm's address and key, the agent key and raea cloud's address: kept on the volume, as a
|
||||
# Sprite kept them (box.sh writes it; a box moved from a Sprite brings its own). Fly secrets, when set, come first.
|
||||
if [ -s "$H/.raea-cloud.env" ]; then
|
||||
while IFS='=' read -r k v; do
|
||||
[[ "$k" =~ ^[A-Z_][A-Z0-9_]*$ ]] || continue
|
||||
[ -n "${!k:-}" ] || export "$k=$v"
|
||||
done < "$H/.raea-cloud.env"
|
||||
fi
|
||||
: "${RAEA_CLOUD_TOKEN:?the box has no RAEA_CLOUD_TOKEN: a Fly secret, or a line of ~/.raea-cloud.env}"
|
||||
# what the box runs with, written back to its disk: raea cloud's fleet makes a new box from a healthy one by reading it
|
||||
(umask 077; for k in RAEA_CLOUD_TOKEN RAEA_AGENT_KEY RAEA_API RAEA_CLOUD_GPU_URL RAEA_CLOUD_GPU_TOKEN; do
|
||||
[ -n "${!k:-}" ] && echo "$k=${!k}"
|
||||
done > "$H/.raea-cloud.env.new" && mv "$H/.raea-cloud.env.new" "$H/.raea-cloud.env" && chown 1000:1000 "$H/.raea-cloud.env")
|
||||
# the work folder by the path raea cloud names it on every box (/home/sprite is /home/raea: the image links it), so
|
||||
# the folders and paths of projects made on a Sprite are the same here
|
||||
export RAEA_CLOUD_WORK=/home/sprite/work
|
||||
# the box's commits say which box made them
|
||||
[ -s "$H/.gitconfig" ] || {
|
||||
sudo -u raea HOME=$H git config --global user.name "raea cloud $BOX"
|
||||
sudo -u raea HOME=$H git config --global user.email "$BOX@box.raea.io"
|
||||
sudo -u raea HOME=$H git config --global init.defaultBranch main
|
||||
}
|
||||
python3 - "$BOX" << 'PY'
|
||||
import json, sys
|
||||
p = "/opt/raea-cloud/BUILD.json"
|
||||
b = json.load(open(p)); b["box"] = sys.argv[1]; json.dump(b, open(p, "w"))
|
||||
PY
|
||||
exec /opt/raea-cloud/image/entrypoint.sh
|
||||
@@ -247,10 +247,8 @@ class Log:
|
||||
SCALEDOWN = 2
|
||||
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
|
||||
# edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones
|
||||
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it. 180 since
|
||||
# 12-03: an agent renders all its cuts at once, then each one its fix touched a minute or two later, and every one of
|
||||
# those started cold at 60 (Shane: "no workflow should take more than 20 minutes")
|
||||
CPU_SCALEDOWN = 180
|
||||
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it
|
||||
CPU_SCALEDOWN = 60
|
||||
|
||||
|
||||
def on(gpus, job):
|
||||
|
||||
@@ -94,19 +94,6 @@ PARTS = 4
|
||||
# another: 2 parts each. At 4 an 894-frame ad went out as 32 parts of 28 frames, each paying about 5 s to start
|
||||
# (raea, the composition, each clip read on from its last keyframe) for 10 s of frames (11-30)
|
||||
CPU_PARTS = 2
|
||||
# A video with no 3D (its keys say so) is planned for the time it takes, not the containers' seconds (12-03, Shane: "no
|
||||
# workflow should take more than 20 minutes"): its runs go out at once, with no timed first run before them (that run
|
||||
# and its wait were 15-25 s of every render), each run at least FLAT_PART frames, on as many containers as the job may
|
||||
# have. A 1080x1920 ad cut drew 0.46-0.69 s a frame on a container with no GPU (11-30, 12-03), which FLAT_FRAME_S plans
|
||||
# the bill by.
|
||||
FLAT_PART = 24
|
||||
FLAT_FRAME_S = 0.6
|
||||
# a run still out once this share of a job's runs are in, and after HEDGE_AFTER times the slowest finished one (or
|
||||
# HEDGE_MIN_S more than it), is sent again to another container, and the first answer is kept (12-03: one of 21 runs took
|
||||
# 81 s where the others took 11-15, and the whole render waited on it)
|
||||
HEDGE_SHARE = 0.7
|
||||
HEDGE_AFTER = 1.5
|
||||
HEDGE_MIN_S = 8.0
|
||||
# a video part's start is never planned at less than this (s): the timed run's own start is measured on a warm
|
||||
# container with the clips' first frames, and came out at 2.8-3.6 s where the parts after it paid about 5
|
||||
PART_START = 5.0
|
||||
@@ -267,81 +254,6 @@ def spread(fn, kind, calls, log, what, bill=None, most=None, got=None, again=Non
|
||||
return code
|
||||
|
||||
|
||||
def _ready(h):
|
||||
"""a spawned run's answer, the exception it raised, or None while it's still running"""
|
||||
try:
|
||||
return h.get(timeout=0)
|
||||
except Exception as e:
|
||||
# Modal's "not yet" is a TimeoutError; its FunctionTimeoutError (the run ran out of time) is the run's answer
|
||||
if isinstance(e, TimeoutError) and type(e).__name__ != "FunctionTimeoutError":
|
||||
return None
|
||||
return e
|
||||
|
||||
|
||||
def hedged(fn, kind, calls, log, what, bill=None, most=None, got=None, again=None, clock=time.time, pause=None, wait_s=0.5):
|
||||
"""`calls` on `fn` as spread() runs them, each spawned at once (at most `most` containers), and a run still out
|
||||
once HEDGE_SHARE of them are in and it has taken HEDGE_AFTER times the slowest finished one (HEDGE_MIN_S more at
|
||||
least) sent once more: the first answer of the two is kept and the other cancelled. A run draws the same frames
|
||||
to the same files wherever it runs, so either answer is the run's."""
|
||||
if not calls:
|
||||
return 0
|
||||
pause = pause or time.sleep
|
||||
if most and len(calls) > most:
|
||||
fn = fn.with_options(max_containers=most)
|
||||
code = 0
|
||||
t0 = clock()
|
||||
out = {c[3]: {"call": c, "h": [fn.spawn(*c)], "at": t0, "again": False} for c in calls}
|
||||
took = []
|
||||
while out:
|
||||
for first in list(out):
|
||||
o = out[first]
|
||||
r = None
|
||||
for h in o["h"]:
|
||||
r = _ready(h)
|
||||
if r is not None:
|
||||
break
|
||||
if r is None:
|
||||
continue
|
||||
for h in o["h"]:
|
||||
try:
|
||||
h.cancel()
|
||||
except Exception:
|
||||
pass
|
||||
del out[first]
|
||||
took.append(clock() - o["at"])
|
||||
if isinstance(r, Exception):
|
||||
log(f"raea farm: a run failed{' without a GPU' if again is not None else ''}: {r!r}"[:600], err=again is None)
|
||||
if again is not None:
|
||||
again.append(o["call"])
|
||||
else:
|
||||
code = code or 1
|
||||
continue
|
||||
if bill:
|
||||
bill.add(r)
|
||||
if again is not None and (r["code"] or (r.get("manifest") or {}).get("has3d")):
|
||||
why = "it drew 3D" if not r["code"] else f"exit {r['code']}: " + " | ".join((r.get("out") or "").strip().splitlines()[-3:])
|
||||
log(f"raea farm: frames from {r.get('first')} didn't draw without a GPU ({why})"[:600])
|
||||
again.append(o["call"])
|
||||
continue
|
||||
if got is not None:
|
||||
got.append(r)
|
||||
log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s")
|
||||
if r["code"]:
|
||||
log(r["out"], err=True)
|
||||
code = code or r["code"]
|
||||
if not out:
|
||||
break
|
||||
if took and len(calls) - len(out) >= HEDGE_SHARE * len(calls):
|
||||
slow = max(took)
|
||||
for first, o in out.items():
|
||||
if not o["again"] and clock() - o["at"] > max(slow * HEDGE_AFTER, slow + HEDGE_MIN_S):
|
||||
o["again"] = True
|
||||
o["h"].append(fn.spawn(*o["call"]))
|
||||
log(f"raea farm: frames from {first} still out after {clock() - o['at']:.0f} s (the others took {slow:.0f} s at most): sent again, the first answer kept")
|
||||
pause(wait_s)
|
||||
return code
|
||||
|
||||
|
||||
def timed(r, n):
|
||||
"""A timed run's (seconds a frame, seconds to start): the frame from raea's own clocks over the whole frame (React,
|
||||
the page, the clips read, the draw, the encode: farm.py's work_ms) when the run says them, else from its "N ms a
|
||||
@@ -412,10 +324,6 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
nv = bool((p.get("manifest") or {}).get("has3d"))
|
||||
flat = bool(video and cpu_render and not opts.get("gpu") and (p.get("manifest") or {}).get("has3d") is False)
|
||||
r0 = None
|
||||
# a flat video whose keys said so goes out at once: no timed first run (FLAT_PART)
|
||||
quick = bool(flat and p.get("keys"))
|
||||
if quick:
|
||||
n0 = 0
|
||||
first = list(range(at0, at0 + n0))
|
||||
if flat and n0:
|
||||
r0 = bill.add(waited(cpu_render, log, id, rest, first, at0, video=video))
|
||||
@@ -436,22 +344,17 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
if r0 and r0["code"]:
|
||||
log(r0["out"], err=True)
|
||||
return r0["code"]
|
||||
frame_s, start_s = timed(r0, n0) if r0 else ((FLAT_FRAME_S, PART_START) if quick else (0.0, 0.0))
|
||||
frame_s, start_s = timed(r0, n0) if r0 else (0.0, 0.0)
|
||||
left = todo - n0
|
||||
# a container beyond the first starts cold: frame 0's whole time, less its one frame (the first is warm by now)
|
||||
cold_s = start_s if flat else max(start_s, p["s"] - frame_s)
|
||||
if quick:
|
||||
k, m = (max(1, min(most, -(-left // FLAT_PART))) if left else 0), 1
|
||||
else:
|
||||
k = gpus_for(left, frame_s, cold_s, most)
|
||||
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
|
||||
k = gpus_for(left, frame_s, cold_s, most)
|
||||
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
|
||||
cost = price(gpu_kind, p["s"]) + price(kind, (r0["s"] if r0 else 0) + k * m * start_s + (k - 1) * (cold_s - start_s) + left * frame_s, busy=(r0 or {}).get("cores") or 0)
|
||||
parts = f" in {k * m} parts" if m > 1 else ""
|
||||
on = f"{k} {kind}s" if not flat else f"{k} containers with no GPU (no 3D in it)"
|
||||
if r0:
|
||||
log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {on}{parts}, about ${cost:.3f} in all")
|
||||
elif quick and left:
|
||||
log(f"raea farm: {left} frames on {on}, all at once, about ${cost:.3f} in all")
|
||||
else:
|
||||
log("raea farm: nothing to draw: every frame is in a run kept from an earlier render")
|
||||
if opts.get("max_usd") is not None and cost > opts["max_usd"]:
|
||||
@@ -462,38 +365,24 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
got = [r0] if r0 else []
|
||||
calls = [(id, rest, f, at, False, video, *([True] if nv and not flat else [])) for a, b, share in farm_keys.spans(gaps, n0, k * m) for f, at in runs(a, b, share, warm)] if left else []
|
||||
again = [] if flat else None
|
||||
code = (hedged if quick else spread)(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
|
||||
code = spread(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
|
||||
if again:
|
||||
# what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it again
|
||||
log(f"raea farm: {len(again)} of {len(calls)} runs go to a GPU (they failed without one, or have 3D in them)")
|
||||
code = spread(gpu_render, gpu_kind, again, log, "frames", bill, opts["gpus"], got)
|
||||
if code:
|
||||
return code
|
||||
# each step from here says how long it took when it took a second or more (12-03: a render whose every frame was
|
||||
# kept still took 64 s between "nothing to draw" and "joined", and nothing said where; Shane: fail fast at every step)
|
||||
def took(what, t0):
|
||||
if time.time() - t0 >= 1:
|
||||
log(f"raea farm: {what} took {time.time() - t0:.1f} s")
|
||||
|
||||
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
|
||||
# containers' frames (11-25: "the volume wouldn't reload ... cwd of raea render")
|
||||
if video:
|
||||
t0 = time.time()
|
||||
t.join()
|
||||
took("the sound", t0)
|
||||
t0 = time.time()
|
||||
reload() # the other containers' frames
|
||||
took("reloading the volume", t0)
|
||||
frames = f"{os.path.dirname(work)}/frames"
|
||||
dest = os.path.join(work, out)
|
||||
# (a run that drew 3D after all isn't kept: its frames can hang on the frames before them)
|
||||
if store and not any((r.get("manifest") or {}).get("has3d") for r in got):
|
||||
t0 = time.time()
|
||||
farm_keys.put(store, keyed["keys"], got, frames)
|
||||
took("keeping the runs drawn", t0)
|
||||
t0 = time.time()
|
||||
got += farm_keys.take(hits, frames)
|
||||
took(f"bringing {len(hits)} kept runs", t0)
|
||||
if manifest and p.get("manifest"):
|
||||
path = os.path.join(work, manifest)
|
||||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
// An agent socket kept alive, and ended when its caller is gone (the /v1/acp socket, main.ts).
|
||||
// A message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two minutes
|
||||
// without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven "socket
|
||||
// closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent never sees it.
|
||||
// And a ping with it: a caller that answers none for CALLER_GONE_MS is gone though its half of the socket stayed open
|
||||
// (an API restart), and the socket is ended, which stops its agent (12-03: a stopped project's Gemini, busy, so never
|
||||
// idle, went on an hour running goal checks on raea-5).
|
||||
import type { WebSocket } from "ws"
|
||||
|
||||
export const CALLER_GONE_MS = 3 * 60_000
|
||||
const EVERY_MS = 20_000
|
||||
|
||||
/** the keepalive's timer: clear it when the socket closes */
|
||||
export function keepAlive(ws: WebSocket, who: string, goneMs = CALLER_GONE_MS, everyMs = EVERY_MS): ReturnType<typeof setInterval> {
|
||||
let pong = Date.now()
|
||||
ws.on("pong", () => (pong = Date.now()))
|
||||
return setInterval(() => {
|
||||
if (ws.readyState !== ws.OPEN) return
|
||||
if (Date.now() - pong > goneMs) {
|
||||
process.stderr.write(`raea-cloud: ${who}'s caller answered no ping in ${Math.round(goneMs / 1000)} s: ended\n`)
|
||||
ws.terminate()
|
||||
return
|
||||
}
|
||||
ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}')
|
||||
ws.ping()
|
||||
}, everyMs)
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
// The critic a project's rules are judged by on this box (Shane, 12-03: "nothing should judge or check with another
|
||||
// harness ... the context should never tell the agent to even have to decide what harness or model or provider"):
|
||||
// a fresh session of the same agent the project runs on, with the same sign-in, asked one question and given nothing
|
||||
// it could change. Each agent session started here (WS /v1/acp) gets RAEA_JUDGE_URL and RAEA_JUDGE_TOKEN in its
|
||||
// environment; `raea goal judge` and `raea judge` in that agent's shell POST to it, and the critic runs as that agent.
|
||||
//
|
||||
// POST /host/judge {cwd, prompt} authorization: Bearer RAEA_JUDGE_TOKEN -> {text}
|
||||
//
|
||||
// The token is the session's: it names the agent and environment to start, and is forgotten when the session ends.
|
||||
import { spawn } from "node:child_process"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import path from "node:path"
|
||||
|
||||
interface Critic {
|
||||
command: string
|
||||
args: string[]
|
||||
env: NodeJS.ProcessEnv
|
||||
root: string
|
||||
}
|
||||
|
||||
const critics = new Map<string, Critic>()
|
||||
|
||||
/** the environment an agent session adds so its shell can ask for a critic: the URL and the session's token */
|
||||
export function register(c: Critic, port: number): { env: Record<string, string>; forget: () => void } {
|
||||
const token = randomBytes(24).toString("hex")
|
||||
critics.set(token, c)
|
||||
return { env: { RAEA_JUDGE_URL: `http://127.0.0.1:${port}/host/judge`, RAEA_JUDGE_TOKEN: token }, forget: () => critics.delete(token) }
|
||||
}
|
||||
|
||||
/** the critic a token names, or null */
|
||||
export const criticFor = (token: string | null | undefined): Critic | null => (token ? (critics.get(token) ?? null) : null)
|
||||
|
||||
/** a permission the critic asks for: what only reads is allowed once, anything else refused (it judges, it changes nothing) */
|
||||
type Option = { optionId: string; kind: string }
|
||||
export function answerPermission(p: { options: Option[]; toolCall?: { kind?: string } }): string {
|
||||
const reads = ["read", "search", "fetch", "think"].includes(String(p.toolCall?.kind ?? ""))
|
||||
const want = reads ? ["allow_once", "allow_always"] : ["reject_once", "reject_always"]
|
||||
return (p.options.find((o) => want.includes(o.kind)) ?? p.options.find((o) => (reads ? o.kind.startsWith("allow") : o.kind.startsWith("reject"))) ?? p.options[0]).optionId
|
||||
}
|
||||
|
||||
/** one question to a fresh session of the critic's agent in `cwd`: what it says back */
|
||||
export function ask(c: Critic, cwd: string, prompt: string, timeoutMs = 10 * 60_000): Promise<string> {
|
||||
const dir = path.resolve(c.root, cwd)
|
||||
if (dir !== c.root && !dir.startsWith(c.root + path.sep)) return Promise.reject(new Error(`${cwd} isn't in the workspace`))
|
||||
return new Promise((done, fail) => {
|
||||
const child = spawn(c.command, c.args, { cwd: dir, env: c.env, stdio: ["pipe", "pipe", "pipe"], detached: true })
|
||||
let said = ""
|
||||
let err = ""
|
||||
let n = 0
|
||||
let finished = false
|
||||
const waiting = new Map<number, (m: { result?: unknown; error?: { message?: string } }) => void>()
|
||||
const stop = () => {
|
||||
try {
|
||||
if (child.pid) process.kill(-child.pid, "SIGTERM")
|
||||
} catch {}
|
||||
}
|
||||
const end = (e: Error | null) => {
|
||||
if (finished) return
|
||||
finished = true
|
||||
clearTimeout(timer)
|
||||
stop()
|
||||
e ? fail(e) : done(said)
|
||||
}
|
||||
const timer = setTimeout(() => end(new Error(`the critic said nothing final in ${Math.round(timeoutMs / 60_000)} min`)), timeoutMs)
|
||||
const send = (m: object) => child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...m })}\n`)
|
||||
const call = (method: string, params: object) =>
|
||||
new Promise<any>((ok, no) => {
|
||||
const id = ++n
|
||||
waiting.set(id, (m) => (m.error ? no(new Error(m.error.message ?? JSON.stringify(m.error))) : ok(m.result)))
|
||||
send({ id, method, params })
|
||||
})
|
||||
let buf = ""
|
||||
child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
|
||||
buf += chunk
|
||||
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) {
|
||||
let m: any
|
||||
try {
|
||||
m = JSON.parse(buf.slice(0, i))
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (m.id != null && !m.method && waiting.has(m.id)) {
|
||||
const w = waiting.get(m.id)!
|
||||
waiting.delete(m.id)
|
||||
w(m)
|
||||
} else if (m.method === "session/update") {
|
||||
const u = m.params?.update
|
||||
if (u?.sessionUpdate === "agent_message_chunk" && u.content?.type === "text") said += u.content.text ?? ""
|
||||
} else if (m.method === "session/request_permission") {
|
||||
send({ id: m.id, result: { outcome: { outcome: "selected", optionId: answerPermission(m.params) } } })
|
||||
} else if (m.id != null && m.method) {
|
||||
// a client method this critic doesn't offer (it reads with its own tools)
|
||||
send({ id: m.id, error: { code: -32601, message: `${m.method} isn't offered here` } })
|
||||
}
|
||||
}
|
||||
})
|
||||
child.stderr.setEncoding("utf8").on("data", (c: string) => (err = (err + c).slice(-4000)))
|
||||
child.on("error", (e) => end(new Error(`the critic didn't start: ${e.message}`)))
|
||||
child.on("exit", (code) => end(finished ? null : new Error(`the critic ended (${code}) before it answered: ${err.trim().slice(-300)}`)))
|
||||
;(async () => {
|
||||
await call("initialize", { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false } })
|
||||
const s = await call("session/new", { cwd: dir, mcpServers: [] })
|
||||
await call("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: prompt }] })
|
||||
end(null)
|
||||
})().catch((e) => end(e as Error))
|
||||
})
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// GET and PUT /v1/files: a file of the work folder read or written, or a folder listed. Both ways stream: a body is
|
||||
// never held in memory (12-03: a box's home folder, gigabytes, moved from a Sprite to a Fly Machine in one request).
|
||||
import { createReadStream, createWriteStream, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs"
|
||||
import type { IncomingMessage, ServerResponse } from "node:http"
|
||||
import path from "node:path"
|
||||
import { pipeline } from "node:stream/promises"
|
||||
|
||||
type Json = (res: ServerResponse, v: unknown, status?: number) => unknown
|
||||
|
||||
export function files(req: IncomingMessage, res: ServerResponse, url: URL, o: { resolve: (p: string) => string; work: string; json: Json }) {
|
||||
const { json } = o
|
||||
const p = o.resolve(url.searchParams.get("path") ?? ".")
|
||||
if (req.method === "PUT") {
|
||||
// to disk as it comes, beside the file, then put in its place whole
|
||||
mkdirSync(path.dirname(p), { recursive: true })
|
||||
const part = `${p}.part-${process.pid}-${Date.now()}`
|
||||
return pipeline(req, createWriteStream(part)).then(
|
||||
() => {
|
||||
renameSync(part, p)
|
||||
json(res, { path: path.relative(o.work, p), bytes: statSync(p).size })
|
||||
},
|
||||
(e) => {
|
||||
rmSync(part, { force: true })
|
||||
if (!res.headersSent) json(res, { error: `the file didn't arrive whole: ${(e as Error).message}` }, 500)
|
||||
},
|
||||
)
|
||||
}
|
||||
let st
|
||||
try {
|
||||
st = statSync(p)
|
||||
} catch {
|
||||
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
|
||||
}
|
||||
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size })
|
||||
return pipeline(createReadStream(p), res).catch(() => res.destroy())
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
// A box on a Fly Machine stops itself when nothing is going on (12-03: the boxes moved off Sprites, which paused on
|
||||
// their own; a Machine runs, and bills, until something stops it). Fly's proxy starts a stopped Machine again on the
|
||||
// next request, so a box only has to know when it's idle: then the server exits 0, the entrypoint saves and exits, and
|
||||
// the Machine (restart policy on-failure) stays stopped.
|
||||
//
|
||||
// Idle is all of: no request for `quietMs`, no connection open (an agent's ACP socket, a shell's stream), nothing the
|
||||
// server runs, no process anywhere working in the box's work folder (a render, the footage prep, an agent's
|
||||
// background job: each runs in a project's folder), and no hold. A hold is the file HOLD_FILE touched within
|
||||
// `holdMs`: raea cloud touches it while a project is unfinished (its awake alarm), as it held a Sprite's task before.
|
||||
//
|
||||
// Off unless RAEA_CLOUD_IDLE_STOP_MIN is set (the Fly image sets it), so a box elsewhere never stops itself.
|
||||
import { readdirSync, readFileSync, readlinkSync, realpathSync, statSync } from "node:fs"
|
||||
import type { Server } from "node:http"
|
||||
import path from "node:path"
|
||||
|
||||
export const HOLD_FILE = ".raea-hold"
|
||||
|
||||
/** a process other than this one (and its parents) whose working folder is under `work` */
|
||||
export function workingIn(work: string, self = process.pid): number[] {
|
||||
const mine = new Set<number>()
|
||||
for (let p = self; p > 1; ) {
|
||||
mine.add(p)
|
||||
try {
|
||||
// /proc/PID/stat: "PID (name) STATE PPID ...", the name in brackets may hold spaces
|
||||
const stat = readFileSync(`/proc/${p}/stat`, "utf8")
|
||||
p = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1])
|
||||
} catch {
|
||||
break
|
||||
}
|
||||
}
|
||||
const out: number[] = []
|
||||
let pids: string[] = []
|
||||
try {
|
||||
pids = readdirSync("/proc").filter((d) => /^\d+$/.test(d))
|
||||
} catch {
|
||||
return out
|
||||
}
|
||||
// the folder by the name it's given and by its real one: /proc says where a process is with no symlink in the way, and
|
||||
// a Fly box's work folder is /home/sprite/work, a link to /home/raea/work (12-03: a 64 GB unpack in it was taken for
|
||||
// idle and the box stopped under it)
|
||||
const roots = [path.resolve(work) + "/"]
|
||||
try {
|
||||
roots.push(realpathSync(work) + "/")
|
||||
} catch {}
|
||||
for (const d of pids) {
|
||||
const pid = Number(d)
|
||||
if (mine.has(pid)) continue
|
||||
try {
|
||||
const cwd = readlinkSync(`/proc/${d}/cwd`) + "/"
|
||||
if (roots.some((r) => cwd.startsWith(r))) out.push(pid)
|
||||
} catch {}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export interface IdleOptions {
|
||||
server: Server
|
||||
work: string
|
||||
home: string
|
||||
/** whether the server itself has something running (an agent, a shell, a job) */
|
||||
busy: () => boolean
|
||||
quietMs: number
|
||||
holdMs?: number
|
||||
everyMs?: number
|
||||
log?: (line: string) => void
|
||||
exit?: () => void
|
||||
}
|
||||
|
||||
/** watches for the box going idle and exits when it has been idle a whole `quietMs`; returns what marks a request */
|
||||
export function stopWhenIdle(o: IdleOptions): { touch: () => void; stop: () => void } {
|
||||
let last = Date.now()
|
||||
const holdMs = o.holdMs ?? 10 * 60_000
|
||||
const log = o.log ?? ((l) => process.stderr.write(l + "\n"))
|
||||
const exit = o.exit ?? (() => process.exit(0))
|
||||
const why = (): string | null => {
|
||||
if (Date.now() - last < o.quietMs) return "a request came lately"
|
||||
if (o.busy()) return "the server runs something"
|
||||
try {
|
||||
const held = statSync(path.join(o.home, HOLD_FILE)).mtimeMs
|
||||
if (Date.now() - held < holdMs) return "a project holds it"
|
||||
} catch {}
|
||||
const w = workingIn(o.work)
|
||||
if (w.length) return `${w.length} processes work in ${o.work}`
|
||||
return null
|
||||
}
|
||||
const timer = setInterval(() => {
|
||||
o.server.getConnections((e, n) => {
|
||||
if (!e && n > 0) return
|
||||
if (why()) return
|
||||
log(`raea-cloud: idle for ${Math.round(o.quietMs / 60_000)} min (no request, connection, process or hold): stopping, so the machine stops`)
|
||||
clearInterval(timer)
|
||||
o.server.close()
|
||||
exit()
|
||||
})
|
||||
}, o.everyMs ?? 30_000)
|
||||
timer.unref()
|
||||
return { touch: () => void (last = Date.now()), stop: () => clearInterval(timer) }
|
||||
}
|
||||
+27
-41
@@ -19,8 +19,6 @@
|
||||
// browser): {credential, email?}, handed back once, or {pending: true}
|
||||
// WS /v1/google-token/ID/screen the box's own browser for that sign-in, over VNC (google-screen.ts)
|
||||
// POST /v1/google-token/check {credential} one short Antigravity turn on it (or a Gemini API key): {ok, said, models}
|
||||
// POST /host/judge {cwd, prompt} a fresh session of the asking agent session's own agent, as the critic its rules are
|
||||
// judged by: {text}. Its token is the session's RAEA_JUDGE_TOKEN (critic.ts)
|
||||
// WS /v1/acp?agent=ID one agent process per socket: a text frame is one ACP message to its stdin,
|
||||
// each line it prints is one frame back. A caller signing the agent in as one of
|
||||
// its own clients (raea cloud, per workspace) sends x-raea-agent-env: JSON of the
|
||||
@@ -39,13 +37,9 @@
|
||||
import { claudeStopHook, jobsOf, markedEnd, sessionIn, watchEnd, watchTurnEnd } from "./turn-end.ts"
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { timingSafeEqual } from "node:crypto"
|
||||
import { existsSync, mkdirSync, readFileSync, symlinkSync } from "node:fs"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
|
||||
import path from "node:path"
|
||||
import { homedir } from "node:os"
|
||||
import { keepAlive } from "./alive.ts"
|
||||
import { files } from "./files.ts"
|
||||
import { stopWhenIdle } from "./idle.ts"
|
||||
import { WebSocketServer } from "ws"
|
||||
import { installed, spawnFor } from "./agents.ts"
|
||||
import { guard } from "./memguard.ts"
|
||||
@@ -56,7 +50,6 @@ import { checkGoogle, finishGoogleSignIn, screenPort, startGoogleSignIn, unpackC
|
||||
import { connect as tcp } from "node:net"
|
||||
import { login, loginState } from "./login.ts"
|
||||
import { Outside, resolve, WORK } from "./workspace.ts"
|
||||
import { ask as askCritic, criticFor, register as registerCritic } from "./critic.ts"
|
||||
|
||||
const TOKEN = process.env.RAEA_CLOUD_TOKEN ?? ""
|
||||
if (TOKEN.length < 16) {
|
||||
@@ -177,6 +170,24 @@ async function body(req: IncomingMessage): Promise<Buffer> {
|
||||
return Buffer.concat(parts)
|
||||
}
|
||||
|
||||
function files(req: IncomingMessage, res: ServerResponse, url: URL) {
|
||||
const p = resolve(url.searchParams.get("path") ?? ".")
|
||||
if (req.method === "PUT")
|
||||
return body(req).then((b) => {
|
||||
mkdirSync(path.dirname(p), { recursive: true })
|
||||
writeFileSync(p, b)
|
||||
json(res, { path: path.relative(WORK, p), bytes: b.length })
|
||||
})
|
||||
let st
|
||||
try {
|
||||
st = statSync(p)
|
||||
} catch {
|
||||
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
|
||||
}
|
||||
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size }).end(readFileSync(p))
|
||||
}
|
||||
|
||||
/** An NDJSON answer's headers sent at once, and an empty line ({}) every KEEPALIVE_MS until it ends: the box sits
|
||||
* behind Cloudflare, which answers 524 when nothing comes back for 100 s, and `raea goal check --json` over seven
|
||||
* cuts prints nothing until it's done (11-30, Dutch's stop at Client sign-off was sent back on it). Readers skip a
|
||||
@@ -239,23 +250,7 @@ async function shell(req: IncomingMessage, res: ServerResponse) {
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://raea-cloud")
|
||||
// a request (other than a platform's health check) keeps an idle box up (idle.ts)
|
||||
// a request is the box at work from when it starts until it ends: a 19-minute upload counted only its start, and the
|
||||
// box stopped as idle the moment it ended (12-03)
|
||||
if (url.pathname !== "/healthz") (idle?.touch(), res.on("close", () => idle?.touch()))
|
||||
if (url.pathname === "/healthz") return res.writeHead(200, { "content-type": "text/plain" }).end("ok")
|
||||
// the critic an agent's shell asks (critic.ts): its own session's token, not the box's
|
||||
if (url.pathname === "/host/judge" && req.method === "POST") {
|
||||
const c = criticFor(/^Bearer (.+)$/.exec(String(req.headers.authorization ?? ""))?.[1])
|
||||
if (!c) return json(res, { error: "no agent session with that token here" }, 401)
|
||||
try {
|
||||
const b = JSON.parse(String(await body(req)))
|
||||
if (typeof b.prompt !== "string" || !b.prompt) return json(res, { error: "prompt is the question" }, 400)
|
||||
return json(res, { text: await askCritic(c, typeof b.cwd === "string" ? b.cwd : ".", b.prompt) })
|
||||
} catch (e) {
|
||||
return json(res, { error: (e as Error).message }, 502)
|
||||
}
|
||||
}
|
||||
if (!authorized(req, url)) return json(res, { error: "unauthorized" }, 401)
|
||||
try {
|
||||
if (url.pathname === "/v1/health" && req.method === "GET") {
|
||||
@@ -283,7 +278,7 @@ const server = createServer(async (req, res) => {
|
||||
running: running.size,
|
||||
})
|
||||
}
|
||||
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url, { resolve, work: WORK, json })
|
||||
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url)
|
||||
if (url.pathname === "/v1/run" && req.method === "POST") return await run(req, res)
|
||||
if (url.pathname === "/v1/shell" && req.method === "POST") return await shell(req, res)
|
||||
if (url.pathname === "/v1/jobs" && req.method === "POST") {
|
||||
@@ -375,10 +370,7 @@ server.on("upgrade", (req, socket, head) => {
|
||||
} catch (e) {
|
||||
return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`)
|
||||
}
|
||||
const base = own ? { ...withoutKeys(childEnv()), ...agent.env, ...RUN_DEFAULTS, ...own } : { ...childEnv(), ...agent.env }
|
||||
// this session's critic (critic.ts): the same agent, sign-in and environment, which `raea goal judge` in its shell asks
|
||||
const critic = registerCritic({ command: agent.command, args: agent.args, env: base, root: WORK }, PORT)
|
||||
const env = { ...base, ...critic.env }
|
||||
const env = own ? { ...withoutKeys(childEnv()), ...agent.env, ...RUN_DEFAULTS, ...own } : { ...childEnv(), ...agent.env }
|
||||
wss.handleUpgrade(req, socket, head, (ws) => {
|
||||
// its own process group, so what it started (a render left running in the background) stops with it: a killed
|
||||
// agent's renders went on as orphans, 4 GB of them on raea-2 (11-25)
|
||||
@@ -396,7 +388,11 @@ server.on("upgrade", (req, socket, head) => {
|
||||
}
|
||||
running.add(child)
|
||||
agentSockets.add(ws)
|
||||
const beat = keepAlive(ws, agent.id)
|
||||
// a message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two
|
||||
// minutes without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven
|
||||
// "socket closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent
|
||||
// never sees it
|
||||
const beat = setInterval(() => ws.readyState === ws.OPEN && ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}'), 20_000)
|
||||
// an agent that has said nothing and been sent nothing for IDLE_AGENT_MS is ended: raea cloud ends a turn whose
|
||||
// agent is quiet 30 min (acp-run.ts QUIET_TOOL_MS), and a socket whose caller went away without closing it (an API
|
||||
// restart; the Sprite's proxy kept the box's half open) otherwise kept its agent forever (11-30: two Gemini agents
|
||||
@@ -408,7 +404,7 @@ server.on("upgrade", (req, socket, head) => {
|
||||
ws.terminate()
|
||||
stopAll()
|
||||
}, Math.min(60_000, IDLE_AGENT_MS / 2))
|
||||
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat), clearInterval(idle), critic.forget()))
|
||||
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat), clearInterval(idle)))
|
||||
child.on("exit", () => (running.delete(child), clearInterval(idle)))
|
||||
// its stderr to the box's log as before, and along the socket as _raea/stderr notifications, so raea cloud keeps
|
||||
// it with the run's trace (runtrace.ts) instead of only on this box's disk (11-25: raea-1's logs died with it)
|
||||
@@ -475,16 +471,6 @@ if (existsSync("/proc/meminfo") && process.env.RAEA_CLOUD_MEMGUARD !== "0")
|
||||
process.stderr.write(line + "\n")
|
||||
for (const ws of agentSockets) if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: line + "\n" } }))
|
||||
})
|
||||
// a box on a Fly Machine stops itself when nothing is going on, and Fly's proxy starts it at the next request (idle.ts)
|
||||
const idleMin = Number(process.env.RAEA_CLOUD_IDLE_STOP_MIN ?? 0)
|
||||
const idle =
|
||||
idleMin > 0
|
||||
? stopWhenIdle({ server, work: WORK, home: homedir(), busy: () => running.size > 0 || agentSockets.size > 0, quietMs: idleMin * 60_000 })
|
||||
: null
|
||||
// a request may take as long as its body takes to come: Node's 5 minutes cut a home folder's upload off at 408
|
||||
// (12-03, a Sprite's home moved to a Fly box). A client still has 60 s to send its headers.
|
||||
server.requestTimeout = 0
|
||||
server.headersTimeout = 60_000
|
||||
server.listen(PORT, async () => {
|
||||
await versionKnown
|
||||
const d = device(childEnv())
|
||||
|
||||
+1
-11
@@ -91,15 +91,6 @@ async function follow(res: Response, onOutput: ((text: string, stream: "out" | "
|
||||
throw new Error(`${what} ended without an exit code`)
|
||||
}
|
||||
|
||||
/** whether a box's address is a Sprite's (behind the Sprite's own auth) */
|
||||
export const onSprite = (url: string): boolean => {
|
||||
try {
|
||||
return new URL(url).hostname.endsWith(".sprites.app")
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export class RaeaCloud {
|
||||
readonly url: string
|
||||
private token: string
|
||||
@@ -112,8 +103,7 @@ export class RaeaCloud {
|
||||
constructor(o: { url: string; token: string; spriteToken?: string }) {
|
||||
this.url = o.url.replace(/\/+$/, "")
|
||||
this.token = o.token
|
||||
// only a box on a Sprite is behind the Sprite's auth; a box elsewhere (a Fly Machine's own app) takes its token
|
||||
this.spriteToken = onSprite(this.url) ? o.spriteToken : undefined
|
||||
this.spriteToken = o.spriteToken
|
||||
}
|
||||
|
||||
/** A request to the box, its response as it comes, for a caller that reads the body itself (a stream of a file
|
||||
|
||||
@@ -69,11 +69,6 @@ class FakeGpu:
|
||||
def starmap(self, calls, order_outputs=False, return_exceptions=True):
|
||||
return [self.remote(*c) for c in calls]
|
||||
|
||||
def spawn(self, *a, **kw):
|
||||
# a run spawned on its own (farm_plan.hedged, waited): answered at once
|
||||
r = self.remote(*a, **kw)
|
||||
return type("Done", (), {"get": lambda self, timeout=None: r, "cancel": lambda self: None})()
|
||||
|
||||
|
||||
lines = []
|
||||
log = lambda t, err=False: lines.append(t)
|
||||
@@ -349,50 +344,3 @@ assert not any("waiting" in l for l in lines), lines
|
||||
ok("a GPU run that timed out fails the job instead of being waited on forever")
|
||||
|
||||
shutil.rmtree(root)
|
||||
|
||||
|
||||
# a flat video's runs go out at once, and a run that hangs back is sent again (farm_plan.hedged, 12-03)
|
||||
class Call:
|
||||
def __init__(self, answer_at, r, clock):
|
||||
self.answer_at, self.r, self.clock, self.cancelled = answer_at, r, clock, False
|
||||
|
||||
def get(self, timeout=None):
|
||||
if self.clock() >= self.answer_at:
|
||||
return self.r
|
||||
raise TimeoutError()
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled = True
|
||||
|
||||
|
||||
class Straggly:
|
||||
"""runs that answer after 10 s, but the first try of the run from frame 40 answers only after 500 s"""
|
||||
|
||||
def __init__(self, clock):
|
||||
self.clock, self.spawned = clock, []
|
||||
|
||||
def with_options(self, **kw):
|
||||
return self
|
||||
|
||||
def spawn(self, id, args, frames, first, *rest):
|
||||
late = first == 40 and not any(f == 40 for f, _ in self.spawned)
|
||||
c = Call(self.clock() + (500 if late else 10), {"code": 0, "s": 10.0, "frames": len(frames), "first": first}, self.clock)
|
||||
self.spawned.append((first, c))
|
||||
return c
|
||||
|
||||
|
||||
now = [0.0]
|
||||
clock = lambda: now[0]
|
||||
def tick(_s):
|
||||
now[0] += 1
|
||||
st = Straggly(clock)
|
||||
lines.clear()
|
||||
calls = [("jh", ["render"], list(range(a, a + 10)), a, False, True) for a in range(0, 60, 10)]
|
||||
got = []
|
||||
assert fp.hedged(st, "CPU", calls, log, "frames", got=got, again=[], clock=clock, pause=tick) == 0, lines
|
||||
assert sorted(r["first"] for r in got) == [0, 10, 20, 30, 40, 50], got
|
||||
assert [f for f, _ in st.spawned].count(40) == 2, st.spawned
|
||||
assert now[0] < 100, now
|
||||
assert any("sent again" in l for l in lines), lines
|
||||
assert [c.cancelled for f, c in st.spawned if f == 40] == [True, True]
|
||||
ok("a run that hangs back while the rest are in is sent again, and the first answer kept: the render doesn't wait on it")
|
||||
+1
-51
@@ -4,7 +4,7 @@
|
||||
|
||||
import assert from "node:assert/strict"
|
||||
import { execSync } from "node:child_process"
|
||||
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { parseSummary, pick } from "../server/gpu.ts"
|
||||
@@ -13,8 +13,6 @@ import { shellEnv } from "../server/shell-os.ts"
|
||||
import { claudeStopHook, jobsOf, lastLine, markedEnd, sessionIn, transcriptOf, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts"
|
||||
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
|
||||
import { localSources } from "../server/media.ts"
|
||||
import { keepAlive } from "../server/alive.ts"
|
||||
import { answerPermission, ask as askCritic, criticFor, register as registerCritic } from "../server/critic.ts"
|
||||
|
||||
const L4 = `Devices:
|
||||
========
|
||||
@@ -215,51 +213,3 @@ console.log("units: ok")
|
||||
assert.equal(localSources({}, [], "/x"), 0)
|
||||
console.log("ok localSources")
|
||||
}
|
||||
|
||||
{
|
||||
// the critic (critic.ts): a session's token names its agent; a fresh session of it answers; reads only
|
||||
const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), "critic-")))
|
||||
mkdirSync(path.join(root, "proj"))
|
||||
const agent = { command: process.execPath, args: [path.join(import.meta.dirname, "echo-agent.mjs")], env: { ...process.env }, root }
|
||||
const r = registerCritic(agent, 8080)
|
||||
assert.equal(r.env.RAEA_JUDGE_URL, "http://127.0.0.1:8080/host/judge")
|
||||
assert.equal(criticFor(r.env.RAEA_JUDGE_TOKEN), agent)
|
||||
assert.equal(criticFor("nope"), null)
|
||||
const said = await askCritic(agent, "proj", "is the plan complete?")
|
||||
assert.match(said, /echo: is the plan complete\?/)
|
||||
assert.match(said, new RegExp(`cwd: ${path.join(root, "proj").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`))
|
||||
// the echo agent's permission names no kind of tool: refused, as anything but a read is
|
||||
assert.match(said, /permission: no/)
|
||||
await assert.rejects(askCritic(agent, "../elsewhere", "x"), /isn't in the workspace/)
|
||||
assert.equal(answerPermission({ toolCall: { kind: "read" }, options: [{ optionId: "a", kind: "allow_once" }, { optionId: "r", kind: "reject_once" }] }), "a")
|
||||
assert.equal(answerPermission({ toolCall: { kind: "edit" }, options: [{ optionId: "a", kind: "allow_once" }, { optionId: "r", kind: "reject_once" }] }), "r")
|
||||
r.forget()
|
||||
assert.equal(criticFor(r.env.RAEA_JUDGE_TOKEN), null)
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
console.log("ok critic")
|
||||
}
|
||||
|
||||
{
|
||||
// a caller that answers pings keeps its socket; one that answers none is ended, which stops its agent (alive.ts)
|
||||
const { WebSocketServer, WebSocket } = await import("ws")
|
||||
const wss = new WebSocketServer({ port: 0 })
|
||||
const port = (wss.address() as { port: number }).port
|
||||
const ended: boolean[] = []
|
||||
wss.on("connection", (ws) => {
|
||||
const beat = keepAlive(ws, "test", 120, 20)
|
||||
ws.on("close", () => (clearInterval(beat), ended.push(true)))
|
||||
})
|
||||
const live = new WebSocket(`ws://127.0.0.1:${port}`)
|
||||
await new Promise((ok) => live.on("open", ok))
|
||||
await new Promise((ok) => setTimeout(ok, 400))
|
||||
assert.equal(live.readyState, WebSocket.OPEN, "a caller that answers pings was ended")
|
||||
live.close()
|
||||
await new Promise((ok) => setTimeout(ok, 50))
|
||||
// autoPong off: this caller answers nothing, as one whose half stayed open after it went away
|
||||
const gone = new WebSocket(`ws://127.0.0.1:${port}`, { autoPong: false } as never)
|
||||
await new Promise((ok) => gone.on("open", ok))
|
||||
const closed = await new Promise<boolean>((ok) => (gone.on("close", () => ok(true)), setTimeout(() => ok(false), 1000)))
|
||||
assert.ok(closed, "a caller that answered no ping wasn't ended")
|
||||
wss.close()
|
||||
console.log("ok an agent socket's caller gone is ended")
|
||||
}
|
||||
+44
-99
@@ -5,7 +5,7 @@
|
||||
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
|
||||
// (file rules are deliverables: the deliverables pack holds them)
|
||||
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
|
||||
import { spawn } from "node:child_process"
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
@@ -76,23 +76,13 @@ export const runPack = check<Job>({ id: "run", text: "each command rule exits 0"
|
||||
export const saysPack = check<Job>({ id: "says", text: "each `says` rule found true by a fresh critic after the work's last change", over: "job", at: ["done"] }, async (j) => {
|
||||
const says = saysOf(goalOf(j) ?? null)
|
||||
if (!says.length) return
|
||||
let v = verdict(j.root, j.contract!)
|
||||
const v = verdict(j.root, j.contract!)
|
||||
const changed = newest(j.root)
|
||||
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
|
||||
const freshOf = (x: Verdict | null) => !!x && (newest(j.root) === null || x.at >= Math.floor(newest(j.root)! / 1000))
|
||||
// a verdict missing, stale or short of a rule is asked for here (the check is the one command; the agent never
|
||||
// judges by hand), where this session has a critic to ask
|
||||
if (!(freshOf(v) && says.every((r) => v!.rules?.[r.id])) && hasCritic(j.root, says)) {
|
||||
try {
|
||||
v = await judge(j.contract!, j.root)
|
||||
} catch (e) {
|
||||
found({ says: `the critic couldn't judge: ${(e as Error).message}` })
|
||||
return
|
||||
}
|
||||
}
|
||||
const fresh = freshOf(v)
|
||||
const fresh = !!v && (changed === null || v.at >= Math.floor(changed / 1000))
|
||||
for (const r of says) {
|
||||
const one = v?.rules?.[r.id]
|
||||
const fix = NO_CRITIC
|
||||
const fix = `raea goal judge${j.contract?.name ? ` --goal ${j.contract.name}` : ""}`
|
||||
if (!v) found({ says: `${r.id}: not judged yet`, about: [r.id], fix })
|
||||
else if (!one) found({ says: `${r.id}: the last judging didn't cover it`, about: [r.id], fix })
|
||||
else if (!fresh) found({ says: `${r.id}: the work changed after the critic judged it`, about: [r.id], fix })
|
||||
@@ -101,8 +91,8 @@ export const saysPack = check<Job>({ id: "says", text: "each `says` rule found t
|
||||
})
|
||||
|
||||
/** what the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing */
|
||||
export function prompt(g: Contract, dir: string, only: Said[] = saysOf(g)): string {
|
||||
const rules = only.map((r) => `- ${r.id}: ${r.says}`)
|
||||
export function prompt(g: Contract, dir: string): string {
|
||||
const rules = saysOf(g).map((r) => `- ${r.id}: ${r.says}`)
|
||||
return `You are a fresh critic. You did none of this work and owe it nothing. The work is in ${dir}: read whatever you need there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: ${g.aim ?? nameOf(g)}\n\nFor each rule below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n${rules.join("\n")}\n\nAnswer last with one JSON object and nothing after it: {"rules": {"ID": {"pass": true, "why": "..."}}}`
|
||||
}
|
||||
|
||||
@@ -134,15 +124,11 @@ export function lastVerdict(text: string): Verdict | null {
|
||||
return null
|
||||
}
|
||||
|
||||
/** where a rule is judged, chosen here and never by the agent (Shane, 12-03): a rule with a piece to watch or hear
|
||||
* (a file it names, or the videos under out/) by Clef-Omni; any other by a fresh session of the agent this project
|
||||
* runs on, which the host that started the agent offers as RAEA_JUDGE_URL (raea cloud's box, critic.ts; the raea app) */
|
||||
const criticUrl = () => process.env.RAEA_JUDGE_URL || null
|
||||
export const NO_CRITIC = "it's judged by a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has: it's judged when that session checks the goal"
|
||||
/** whether every rule here can be judged in this session */
|
||||
export function hasCritic(dir: string, rules: Said[]): boolean {
|
||||
return !!criticUrl() || rules.every((r) => piecesOf(r, dir).length > 0)
|
||||
}
|
||||
export const BY = ["claude", "kimi", "clef"] as const
|
||||
/** the critic when none is named: clef where an agent key is set (a raea cloud box, whose shell has no Claude
|
||||
* sign-in: 12-01, every judging there answered "Not logged in"), else Claude Code */
|
||||
export const critic = () => (process.env.RAEA_AGENT_KEY && process.env.RAEA_API ? "clef" : "claude")
|
||||
|
||||
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
|
||||
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
|
||||
/** the videos under out/, newest first */
|
||||
@@ -162,31 +148,13 @@ function made(dir: string): string[] {
|
||||
* asked of the files it names, in its "from A s to B s" window if it has one, else of every video under out/ (the
|
||||
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
|
||||
const CLEF_PIECES = 12
|
||||
/** the pieces a rule is about: the files it names that are on disk, else the newest videos under out/ */
|
||||
function piecesOf(r: Said, dir: string): string[] {
|
||||
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
|
||||
return named.length ? named : made(dir).slice(0, CLEF_PIECES)
|
||||
}
|
||||
/** how many `raea ask`s run at once: each is one cut (or one stretch of it) heard and watched; one after another, a
|
||||
* project's beats took 6-17 minutes of every goal check (12-03, StreetTalk: 18 of them, a cut's beats each a stretch) */
|
||||
export const CLEF_AT_ONCE = 6
|
||||
|
||||
/** `f` on each item, at most `n` at once, the answers in the items' order */
|
||||
async function pool<T, R>(items: T[], n: number, f: (t: T) => Promise<R>): Promise<R[]> {
|
||||
const out: R[] = new Array(items.length)
|
||||
let next = 0
|
||||
const worker = async () => {
|
||||
for (let i = next++; i < items.length; i = next++) out[i] = await f(items[i])
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker))
|
||||
return out
|
||||
}
|
||||
|
||||
export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef, only: Said[] = saysOf(g)): Promise<Verdict["rules"]> {
|
||||
export function clefVerdict(g: Contract, dir: string, ask = askClef): Verdict["rules"] {
|
||||
const all = made(dir)
|
||||
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
|
||||
const pieces = new Map<string, string[]>()
|
||||
for (const r of only) {
|
||||
const files = piecesOf(r, dir)
|
||||
for (const r of saysOf(g)) {
|
||||
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
|
||||
const files = named.length ? named : all.slice(0, CLEF_PIECES)
|
||||
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
|
||||
pieces.set(r.id, files)
|
||||
for (const file of files) {
|
||||
@@ -197,70 +165,47 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
|
||||
}
|
||||
}
|
||||
const got = new Map<string, { pass: boolean; why: string }[]>()
|
||||
const list = [...groups.values()]
|
||||
const heard = await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
|
||||
for (const [j, k] of list.entries()) {
|
||||
const answers = heard[j]
|
||||
for (const k of groups.values()) {
|
||||
const answers = ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to)
|
||||
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
|
||||
}
|
||||
const rules: Verdict["rules"] = {}
|
||||
for (const r of only) {
|
||||
for (const r of saysOf(g)) {
|
||||
const a = got.get(r.id) ?? []
|
||||
const open = a.filter((x) => !x.pass)
|
||||
rules[r.id] = !pieces.get(r.id)?.length
|
||||
? { pass: false, why: "it names no file on disk and out/ holds no video yet, so there's nothing to watch or hear" }
|
||||
? { pass: false, why: "clef watches and hears a piece, and this rule names no file on disk while out/ holds no video: name the file in the rule, or judge it --by claude where Claude Code is signed in" }
|
||||
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
|
||||
}
|
||||
return rules
|
||||
}
|
||||
type Answer = { choice?: string; says?: string; problem?: string | null }
|
||||
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
|
||||
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
|
||||
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
|
||||
return new Promise((ok, no) => {
|
||||
const c = spawn(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
|
||||
let out = "", err = ""
|
||||
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
|
||||
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
|
||||
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
|
||||
c.on("close", () => {
|
||||
const rows = out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
|
||||
ok(rows)
|
||||
})
|
||||
})
|
||||
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Answer[] {
|
||||
const r = spawnSync(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
|
||||
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
|
||||
const rows = String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
if (rows.length !== says.length) throw new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`)
|
||||
return rows
|
||||
}
|
||||
|
||||
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
|
||||
* (criticUrl above), its verdict kept at review/judge/NAME.json, stamped with when it was asked (so work changed while
|
||||
* it judged counts as changed after) */
|
||||
export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef; agent?: (cwd: string, prompt: string) => Promise<string> } = {}): Promise<Verdict> {
|
||||
const all = saysOf(g)
|
||||
if (!all.length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
|
||||
/** one fresh critic over a goal's `says` rules (`raea goal judge`): its verdict kept at review/judge/NAME.json,
|
||||
* stamped with when it was asked (so work changed while it judged counts as changed after) */
|
||||
export function judge(g: Contract, dir: string, by: string): Verdict {
|
||||
if (!saysOf(g).length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
|
||||
if (!(BY as readonly string[]).includes(by)) throw new Error(`--by ${by}: the critics are ${BY.join(", ")}`)
|
||||
const asked = Math.floor(Date.now() / 1000)
|
||||
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
|
||||
const read = all.filter((r) => !watched.includes(r))
|
||||
// what's watched and heard, and what's read, at once: neither waits on the other
|
||||
const [heard, said] = await Promise.all([
|
||||
watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : Promise.resolve({} as Verdict["rules"]),
|
||||
read.length ? (o.agent ?? askAgent)(dir, prompt(g, dir, read)) : Promise.resolve(null),
|
||||
])
|
||||
const rules: Verdict["rules"] = { ...heard }
|
||||
if (said !== null) {
|
||||
const v = lastVerdict(said)
|
||||
if (!v) throw new Error(`the critic gave no verdict: ${said.slice(-300).trim()}`)
|
||||
for (const r of read) rules[r.id] = v.rules?.[r.id] ?? { pass: false, why: "the critic didn't answer this rule" }
|
||||
}
|
||||
return keep(g, dir, { at: asked, by: [watched.length ? "clef" : "", read.length ? "agent" : ""].filter(Boolean).join("+"), goal: g.aim ?? nameOf(g), rules })
|
||||
}
|
||||
/** a fresh session of this project's own agent, through the host that started it (RAEA_JUDGE_URL): what it says */
|
||||
async function askAgent(cwd: string, p: string): Promise<string> {
|
||||
const url = criticUrl()
|
||||
if (!url) throw new Error(NO_CRITIC)
|
||||
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${process.env.RAEA_JUDGE_TOKEN ?? ""}` }, body: JSON.stringify({ cwd, prompt: p }), signal: AbortSignal.timeout(15 * 60_000) })
|
||||
const j = (await r.json().catch(() => ({}))) as { text?: string; error?: string }
|
||||
if (!r.ok || typeof j.text !== "string") throw new Error(j.error ?? `the critic answered ${r.status}`)
|
||||
return j.text
|
||||
if (by === "clef") return keep(g, dir, { at: asked, by, goal: g.aim ?? nameOf(g), rules: clefVerdict(g, dir) })
|
||||
const p = prompt(g, dir)
|
||||
const r = by === "claude" ? spawnSync("claude", ["-p", p, "--allowedTools", "Read Grep Glob", "--output-format", "json"], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 }) : spawnSync("kimi", ["-p", p], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
|
||||
if (r.error) throw new Error(`couldn't run ${by}: ${r.error.message} (is its CLI installed and signed in?)`)
|
||||
let words = String(r.stdout ?? "")
|
||||
try {
|
||||
const o = JSON.parse(words)
|
||||
if (typeof o.result === "string") words = o.result
|
||||
} catch {}
|
||||
const v = lastVerdict(words)
|
||||
if (!v) throw new Error(`${by} answered no verdict: ${words.slice(-300).trim()}`)
|
||||
return keep(g, dir, { ...v, at: asked, by, goal: g.aim ?? nameOf(g) })
|
||||
}
|
||||
function keep(g: Contract, dir: string, out: Verdict): Verdict {
|
||||
const file = path.join(dir, verdictPath(g))
|
||||
|
||||
@@ -17,7 +17,7 @@ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { CutBeat as Beat } from "raea/brief.gen"
|
||||
import type { Beat } from "raea/brief.gen"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { type Faces, Unmet } from "../media.ts"
|
||||
import { cutOf } from "./cut.ts"
|
||||
|
||||
+6
-6
@@ -13,7 +13,7 @@
|
||||
// says what for; it holds nothing.
|
||||
// raea goal tasks [DIR] [--json] | --apply EDITS.json|- the brief's plan as tasks, and edits written back (tasks.ts)
|
||||
// raea goal seen FILE "WHAT" [--surprise "S s: WHAT"] what was seen of FILE as it is now, and its surprise
|
||||
// raea goal judge [--goal NAME] a goal's `says` rules judged now (review/judge/); raea goal check asks it itself
|
||||
// raea goal judge [--goal NAME] [--by claude|kimi|clef] a fresh critic over a goal's `says` rules (review/judge/)
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
@@ -24,7 +24,7 @@ import * as media from "./media.ts"
|
||||
import { registeredPack } from "./packs/job.ts"
|
||||
import { tastePack } from "./packs/taste.ts"
|
||||
import { loadProject, type Project } from "./project.ts"
|
||||
import { judge } from "./packs/goal.ts"
|
||||
import { critic, judge } from "./packs/goal.ts"
|
||||
import { PACK_CHECKS } from "./packs/index.ts"
|
||||
import { second } from "./packs/look.ts"
|
||||
import { deliverablesOf } from "./packs/job.ts"
|
||||
@@ -230,7 +230,7 @@ const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal
|
||||
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|-
|
||||
raea goal seen FILE (its contact sheet and its frames at full size, to look at)
|
||||
raea goal seen FILE "what you see and would change" --look "its design at full size, beside a reference" [--surprise "SECONDS s: what it is"]
|
||||
raea goal judge [--goal NAME]
|
||||
raea goal judge [--goal NAME] [--by claude|kimi|clef]
|
||||
raea make place FILE [--at S[,S...]] [--box WxH]`
|
||||
|
||||
export async function main(argv: string[]): Promise<number> {
|
||||
@@ -260,8 +260,8 @@ export async function main(argv: string[]): Promise<number> {
|
||||
if (!said?.trim()) {
|
||||
const sheet = media.sheet(path.resolve(file))
|
||||
const full = kindOf(path.resolve(file)) === "video" ? media.looks(path.resolve(file)) : []
|
||||
// on raea cloud (where Clef-Omni is paid for), a second opinion on the whole cut with its sound: never the look itself
|
||||
const op = full.length && process.env.RAEA_AGENT_KEY && process.env.RAEA_API ? second(path.resolve(file)) : null
|
||||
// on raea cloud (where the critic is clef), a second opinion on the whole cut with its sound: never the look itself
|
||||
const op = full.length && critic() === "clef" ? second(path.resolve(file)) : null
|
||||
if (op) console.log(`a second opinion (clef watched and heard all of it and answered a list of checks; a FOUND is a fix or a reason it's wrong; how it looks is still yours to judge, on the frames):\n${op}`)
|
||||
console.log(`${sheet}\n${full.join("\n")}\nlook at every frame of the sheet for what happens, and open each full-size frame for how it looks (type, captions, cards, the end: beside a reference ad's frame, not from the sheet), then: raea goal seen ${file} "what you see and would change"${full.length ? ' --look "its design at full size, beside a reference, and what you changed"' : ""}`)
|
||||
return 0
|
||||
@@ -312,7 +312,7 @@ export async function main(argv: string[]): Promise<number> {
|
||||
console.error(`raea goal judge: ${!root ? "no brief.ts here or above" : !said.length ? `no goal${name ? ` named ${name}` : ""} here has \`says\` rules` : `several goals have \`says\` rules (${said.map(nameOf).join(", ")}): name one with --goal`}`)
|
||||
return 2
|
||||
}
|
||||
const v = await judge(said[0], root)
|
||||
const v = judge(said[0], root, flag(a, "--by") ?? critic())
|
||||
for (const [id, r] of Object.entries(v.rules)) console.log(`${r?.pass ? "ok " : "open"} ${id}: ${r?.why ?? ""}`)
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { expect, test } from "bun:test"
|
||||
import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { clefVerdict, judge, lastVerdict, NO_CRITIC, newest } from "../src/packs/goal.ts"
|
||||
import { clefVerdict, lastVerdict, newest } from "../src/packs/goal.ts"
|
||||
import { goalCheck } from "../src/run.ts"
|
||||
import { project, put } from "./project.ts"
|
||||
|
||||
@@ -30,8 +30,7 @@ test("words need a fresh critic", async () => {
|
||||
const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
|
||||
put(d, "work.txt", "the work")
|
||||
const says = async () => (await goalCheck({ cwd: d })).findings.filter((x) => x.check === "says")
|
||||
// no critic in this session: it says so, and names no tool or agent to run
|
||||
expect((await says())[0].fix).toBe(NO_CRITIC)
|
||||
expect((await says())[0].fix).toBe("raea goal judge")
|
||||
const later = Math.floor(Date.now() / 1000) + 5
|
||||
mkdirSync(path.join(d, "review/judge"), { recursive: true })
|
||||
writeFileSync(path.join(d, VERDICT), JSON.stringify({ at: later, by: "claude", rules: { friendly: { pass: true, why: "it says hello warmly" } } }))
|
||||
@@ -44,63 +43,6 @@ test("words need a fresh critic", async () => {
|
||||
expect((await says())[0].says).toContain("it is curt")
|
||||
})
|
||||
|
||||
test("the check asks this session's critic itself", async () => {
|
||||
const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
|
||||
put(d, "work.txt", "the work")
|
||||
const heard: { auth: string | null; cwd: string; prompt: string }[] = []
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
async fetch(req) {
|
||||
const b = (await req.json()) as { cwd: string; prompt: string }
|
||||
heard.push({ auth: req.headers.get("authorization"), ...b })
|
||||
return Response.json({ text: 'thinking... {"rules": {"friendly": {"pass": true, "why": "it says hello warmly"}}}' })
|
||||
},
|
||||
})
|
||||
process.env.RAEA_JUDGE_URL = `http://127.0.0.1:${server.port}/host/judge`
|
||||
process.env.RAEA_JUDGE_TOKEN = "t0k"
|
||||
try {
|
||||
const r = await goalCheck({ cwd: d })
|
||||
expect(r.findings.filter((x) => x.check === "says")).toEqual([])
|
||||
expect(heard).toHaveLength(1)
|
||||
expect(heard[0].auth).toBe("Bearer t0k")
|
||||
expect(heard[0].prompt).toContain("friendly: the reply is friendly")
|
||||
// judged once: a second check reads the kept verdict
|
||||
await goalCheck({ cwd: d })
|
||||
expect(heard).toHaveLength(1)
|
||||
} finally {
|
||||
delete process.env.RAEA_JUDGE_URL
|
||||
delete process.env.RAEA_JUDGE_TOKEN
|
||||
server.stop(true)
|
||||
}
|
||||
})
|
||||
|
||||
test("a rule with a piece to watch goes to clef, any other to the agent", async () => {
|
||||
const g = goal([
|
||||
{ id: "plan", says: "plan.md names every cut" },
|
||||
{ id: "cut", says: "out/a.mp4 opens on the hook" },
|
||||
])
|
||||
const d = project(g)
|
||||
put(d, "out/a.mp4", "video")
|
||||
const clefAsked: string[] = []
|
||||
const agentAsked: string[] = []
|
||||
const v = await judge(g as never, d, {
|
||||
ask: (_dir, file, says) => (clefAsked.push(file), says.map(() => ({ choice: "true" }))),
|
||||
agent: async (_cwd, p) => (agentAsked.push(p), '{"rules": {"plan": {"pass": false, "why": "cut 3 is missing"}}}'),
|
||||
})
|
||||
// out/ holds a video, so both are about a piece: clef judges both, and nothing asks the agent
|
||||
expect(agentAsked).toEqual([])
|
||||
expect(Object.keys(v.rules).sort()).toEqual(["cut", "plan"])
|
||||
const bare = project(g)
|
||||
const v2 = await judge(g as never, bare, {
|
||||
ask: (_dir, file, says) => (clefAsked.push(file), says.map(() => ({ choice: "true" }))),
|
||||
agent: async (_cwd, p) => (agentAsked.push(p), '{"rules": {"plan": {"pass": false, "why": "cut 3 is missing"}, "cut": {"pass": false, "why": "no cut yet"}}}'),
|
||||
})
|
||||
expect(agentAsked).toHaveLength(1)
|
||||
expect(agentAsked[0]).toContain("plan: plan.md names every cut")
|
||||
expect(v2.rules.plan?.why).toBe("cut 3 is missing")
|
||||
expect(v2.by).toBe("agent")
|
||||
})
|
||||
|
||||
test("file rules are deliverables", async () => {
|
||||
const d = project(goal([{ id: "export", file: "out/final.txt" }]))
|
||||
expect((await goalCheck({ cwd: d })).findings.map((x) => [x.check, x.says])).toEqual([["deliverables", "missing: out/final.txt"]])
|
||||
@@ -121,13 +63,13 @@ test("a check runs only at its moments", async () => {
|
||||
expect((await goalCheck({ cwd: d, at: "done" })).checks).toContain("run")
|
||||
})
|
||||
|
||||
test("clef judges a rule on the file it names, else on every video made, and says when there's nothing to watch", async () => {
|
||||
test("clef judges a rule on the file it names, else on every video made, and says when there's nothing to watch", () => {
|
||||
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
|
||||
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
|
||||
for (const f of ["out/cuts/a_9x16.mp4", "out/cuts/b_9x16.mp4"]) writeFileSync(path.join(d, f), "x")
|
||||
const g = { name: "rules", rules: [{ id: "named", says: "In out/cuts/a_9x16.mp4, from 0 s to 3 s, the host is speaking" }, { id: "all", says: "No caption covers a face" }] } as never
|
||||
const asked: string[] = []
|
||||
const rules = await clefVerdict(g, d, (_dir, file, says, from, to) => {
|
||||
const rules = clefVerdict(g, d, (_dir, file, says, from, to) => {
|
||||
asked.push(`${file} ${from ?? ""}-${to ?? ""} ${says.length}`)
|
||||
return says.map((q) => ({ choice: q.includes("caption") && file.includes("b_") ? "false" : "true", says: "said" }))
|
||||
})
|
||||
@@ -136,7 +78,7 @@ test("clef judges a rule on the file it names, else on every video made, and say
|
||||
expect(rules.all?.pass).toBe(false)
|
||||
expect(rules.all?.why).toBe("out/cuts/b_9x16.mp4: said")
|
||||
const empty = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
|
||||
expect((await clefVerdict(g, empty, () => [])).all?.why).toContain("names no file on disk")
|
||||
expect(clefVerdict(g, empty, () => []).all?.why).toContain("names no file on disk")
|
||||
})
|
||||
|
||||
test("a reading kept beside a file isn't the work changing", () => {
|
||||
@@ -150,20 +92,3 @@ test("a reading kept beside a file isn't the work changing", () => {
|
||||
writeFileSync(path.join(d, "out/cuts/a_b_c_v1_9x16.render.json"), "{}")
|
||||
expect(newest(d)!).toBeGreaterThan(1_000_000)
|
||||
})
|
||||
|
||||
test("clef hears several cuts at once, and the critic reads while it does", async () => {
|
||||
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-at-once-"))
|
||||
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
|
||||
const names = ["a", "b", "c", "d", "e", "f", "g", "h"]
|
||||
for (const n of names) writeFileSync(path.join(d, `out/cuts/${n}_9x16.mp4`), "x")
|
||||
const g = { name: "rules", rules: [{ id: "seen", says: "No caption covers a face" }] } as never
|
||||
let now = 0, most = 0
|
||||
const rules = await clefVerdict(g, d, async (_dir, _file, says) => {
|
||||
most = Math.max(most, ++now)
|
||||
await new Promise((ok) => setTimeout(ok, 20))
|
||||
now--
|
||||
return says.map(() => ({ choice: "true", says: "fine" }))
|
||||
})
|
||||
expect(most).toBe(6)
|
||||
expect(rules.seen?.pass).toBe(true)
|
||||
})
|
||||
@@ -20,8 +20,7 @@ Run `raea context PROJECT` before anything else and read all of it. It prints, i
|
||||
every project. A line there beats any guide.
|
||||
2. **The brief** (`brief.ts`): who it's for (`audience`), the one thing they should think afterwards (`believe`),
|
||||
what kind of piece it is (`mode`), the narrator and tone (`voice`), what it delivers, the tasks and the agents.
|
||||
Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction. To write one,
|
||||
`raea guide brief` has its types, a cut goal's contract and an example.
|
||||
Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction.
|
||||
3. **The look** (the brief's `look`, and `brand/brand.css` when there is one): the project's committed world.
|
||||
4. **The floor**: what breaks a piece, read again right before every edit.
|
||||
5. **One guide per mode**: what that kind of piece has to do.
|
||||
|
||||
@@ -32,7 +32,7 @@ and the Stop hook won't let you end before it says done.
|
||||
beside it, `lod` for when it's small on screen), `lineup.tsx` (every piece at its real size beside a 1 m bar),
|
||||
`cover.png`, `thumbs/` and `kit.json`. Import it as `@shared/components/KIT/RotaryPhone`.
|
||||
7. **Review and judge.** `raea render shared/components/KIT/lineup.tsx --review review/rN`, then
|
||||
`raea judge review/rN --kind kit --brief brief.ts --json`. The kit rubric: cohesion, reference
|
||||
`raea judge review/rN --kind kit --by claude --brief brief.ts --json`. The kit rubric: cohesion, reference
|
||||
fidelity, the brief, mesh (clay), texture, assembly (clay), scale (clay), labels. Fix its blocking defects or
|
||||
answer them in NOTES.md, and keep going until `raea goal check` passes.
|
||||
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
There are three texts to copy and fill: a brief template, a builder prompt and a judge prompt for a fresh context.
|
||||
`bevy/scenes` says why each step exists. This page gives the words.
|
||||
|
||||
Who plays which role: you are the builder; `raea judge` is the judge, a fresh session every round that raea starts
|
||||
for you (the agent this project runs on where the raea app or raea cloud started it, else clef-omni for the numbers).
|
||||
You never pick it.
|
||||
Who plays which role:
|
||||
- **In Claude Code:** the session is the builder. The judge is a new subagent every round, plus `raea judge` (clef-omni)
|
||||
for the numbers.
|
||||
- **In the raea app's feed:** Kimi is the builder and `raea judge` is the judge.
|
||||
|
||||
The judge sees only pictures and the brief's words, never the code or the builder's notes. Code decides
|
||||
Either way, the judge sees only pictures and the brief's words, never the code or the builder's notes. Code decides
|
||||
the pass, and the builder never sees the pass line. A figure the builder can read becomes a target to game.
|
||||
|
||||
Where these texts come from: the published Blender + Claude workflows.
|
||||
@@ -143,9 +144,11 @@ STEP R: REVIEW (after every stage, and after every fix)
|
||||
the same cameras every round.
|
||||
- Open both sheets and look at every tile yourself. Write your own list. "Looks good" is not a review. Name each
|
||||
problem precisely ("the dryer doors are flat grey discs", not "the dryers look off"), with its tile and its fix.
|
||||
- Run `raea judge review/r<n>`. It's a new session that sees only the sheets, the brief's words, the target, the real
|
||||
photos, this round's sheets, and last round's sheets and verdict: never your code, your log or your list. Who reads
|
||||
them is raea's to settle, not yours.
|
||||
- Run `raea judge review/r<n> --by kimi` (or `--by claude`; plain `raea judge` is clef-omni, cheap but advice only
|
||||
until calibrated). Each is a new session that sees only the sheets. In Claude Code you can also hand the sheets to a
|
||||
NEW subagent with the judge prompt. Give it only the
|
||||
brief's words, the target, the real photos, this round's sheets, and last round's sheets and verdict. Never give it
|
||||
your code, your log or your list.
|
||||
- Fix every blocking defect named, or write in review/log.md why it is wrong and what you checked. A judge can be
|
||||
wrong: a shadow read as a hole. Change one material per round. Every fix is code in the scene.
|
||||
- Re-run the stage's checks after every fix. A fix that breaks a check is not done.
|
||||
|
||||
@@ -159,8 +159,8 @@ Three tiers, each gating once it has earned it (`raea goal check` lists them):
|
||||
objects, a brand; on a framing sheet, a camera through a wall or a subject lost. Every answer lands in the ask
|
||||
ledger, matched to the sheet's bytes, so a re-rendered sheet needs asking again. A question gates once
|
||||
`raea ask calibrate` passes it (16 problem and 16 clean labels, held-out AUC 0.8); until then it's advice.
|
||||
3. **A fresh critic for the fixes.** `raea judge review/rN --kind scene --brief brief.ts --target
|
||||
media/ref/target.png --json` scores the kind's rubric (scene: layout, props, signage, materials,
|
||||
3. **A fresh critic for the fixes.** `raea judge review/rN --kind scene --by claude --brief brief.ts --target
|
||||
media/ref/target.png --json` (or clef, kimi) scores the kind's rubric (scene: layout, props, signage, materials,
|
||||
light, atmosphere, plausibility, composition; layout and props judged on clay), on a production bar: don't
|
||||
nitpick, at most five fixes. It sees the sheets and the brief's words only, never the code or your log. Code
|
||||
decides the pass; the thresholds aren't in the prompt. A round judged on another kind's rubric doesn't count.
|
||||
|
||||
@@ -44,7 +44,7 @@ before it says done.
|
||||
4. **Block it.** `raea make framing` renders every shot's first, middle and last frame onto `review/framing.png`,
|
||||
stamped with the name and time. Look at every row: the subject in frame at the start and the end, nothing through
|
||||
a wall. Ask it (`raea ask review/framing.png --std make.framing.through_wall --std make.framing.subject_lost`) and
|
||||
judge it (`raea judge review --kind shot`: framing, move, focus, clearance, continuity, grade).
|
||||
judge it (`raea judge review --kind shot --by claude`: framing, move, focus, clearance, continuity, grade).
|
||||
5. **Clearance.** `raea scene stage SHOT.tsx --clearance 0.45` holds the camera 0.45 m (a carried camera) off every solid part on every frame
|
||||
(`--clearance 0.15` for a camera on a rig). Glass, decals, volumes and parts under 5 cm are passed over.
|
||||
6. **Grade.** `<Grade {...gradeLook("cinematic")} />` from `raea/post_process`: clean, cinematic, gritty or vintage,
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
# brief.ts: the brief as code
|
||||
|
||||
A project's brief.ts is a module whose default export is `brief({...})` from `raea/brief`. raea runs it, `raea goal
|
||||
check` holds the work to its `goal`, and tsc checks it against the same types raea reads. Everything you need to write
|
||||
one is on this page, so you don't need to open the SDK.
|
||||
|
||||
## The shape
|
||||
|
||||
```ts
|
||||
import { brief, cut, rules } from "raea/brief"
|
||||
|
||||
export default brief({
|
||||
title: string, // the project as people name it
|
||||
for?: string, // the client or person it's for
|
||||
audience?: string, // who watches, and where
|
||||
believe?: string, // the one thing they should think afterwards
|
||||
voice?: string, look?: string, sound?: string,
|
||||
notDoing?: string[], // the anti-goals
|
||||
assumed?: string[], // facts you wrote that the person hasn't confirmed, by key ("audience")
|
||||
sections?: { heading: string, text: string }[],
|
||||
goal?: Goal | Goal[], // what the work is held to: cut(), rules(), scene(), kit(), shot(), playable()
|
||||
plan?: PlanFile, // tasks (raea/task plan()), inline or imported
|
||||
})
|
||||
```
|
||||
|
||||
A goal made with `cut({...})` or `rules({...})` takes these fields:
|
||||
|
||||
| Field | What it is |
|
||||
| --- | --- |
|
||||
| `aim` | what the goal is, in the person's words |
|
||||
| `rules` | `{ id, run? , timeout?, file?, says? }[]`: what must hold before you stop (below) |
|
||||
| `cut` | a cut job's contract, the brief as rules (below) |
|
||||
| `deliverables` | files that must exist when it's done, relative to brief.ts (a cut goal lists its own) |
|
||||
| `previews` | what it shows but never delivers (`review/` and `previews/` when left out) |
|
||||
| `checks` | the project's own `check()`s from raea/check, imported into brief.ts |
|
||||
| `name`, `after`, `step` | for several goals in order: a goal's name, the goals before it, its workflow step |
|
||||
|
||||
## A cut job's contract (`cut: {...}`)
|
||||
|
||||
Every `from` is the brief's own words, copied from its text file as they are, so a person can find the line the
|
||||
rule came from. raea refuses a `from` it can't find.
|
||||
|
||||
| Field | Type | What it holds |
|
||||
| --- | --- | --- |
|
||||
| `brief` | `string` | the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf brief_docs/brief.txt`) |
|
||||
| `count` | `{ value: number, from }` | how many cuts the brief asks for. Fewer planned stays open until a person answers an `open` item about `"count"` |
|
||||
| `seconds` | `[least, most]` | a cut's length when the cut doesn't give its own |
|
||||
| `formats` | `string[]` | `"9:16"`, `"16:9"`, `"1:1"`, `"4:5"`: every cut's formats when the cut doesn't give its own |
|
||||
| `cuts` | `CutPlan[]` | one per cut: `{ id, angle?, kind?, hook?, text?, formats?, seconds?, beats? }` |
|
||||
| `say` | `{ text, from, every? }[]` | what is said or shown in every cut (`every: false`: one cut is enough) |
|
||||
| `never` | `{ text, from }[]` | what no cut says or shows: a banned claim, a word, a name |
|
||||
| `cta` | `{ text, from, also?, within? }` | the line every cut ends on, heard or shown in its last `within` seconds (8 by default); `also` lists other lines the brief rotates |
|
||||
| `open` | `{ question, from, about?, answer?, by? }[]` | the brief's open items (TBD, to confirm). Each holds the job open until a person's answer is written in, with who gave it |
|
||||
| `frames` | `boolean` | every face whole and every text big enough, in every frame (true by default) |
|
||||
|
||||
A cut's `id` is `[a-z0-9_]` and unique. Each format lands as `out/cuts/<id>_<format with x>.mp4`, for example
|
||||
`out/cuts/a1_s1_9x16.mp4`. `text` is `"captions"`, `"hook"` or `"none"`. `kind` is `"solo"` or `"mashup"`. `hook` is
|
||||
one of the brief's hook types, as the brief names it.
|
||||
|
||||
A cut's `beats` are decided before it's cut, in order: `{ at, feel, story?, asl?, tempo? }[]`. `at` is where the beat
|
||||
starts, in seconds from the cut's start (0 for the first). `feel` is what the viewer feels there, in the person's
|
||||
words, and `story` is what they understand by its end. A fresh critic watches each beat for both. `asl` is the beat's
|
||||
average shot length in seconds, and `tempo` is how its shot lengths move: `"build"` (shorter as it goes), `"release"`
|
||||
(longer) or `"hold"` (even). The montage check holds the cut to them.
|
||||
|
||||
## Rules
|
||||
|
||||
| Kind | Example | How it's checked |
|
||||
| --- | --- | --- |
|
||||
| `run` | `{ id: "tests", run: "bun test" }` | the command must exit 0 in brief.ts's folder (300 s unless `timeout` says otherwise) |
|
||||
| `file` | `{ id: "sheet", file: "review/sheet.png" }` | the file must exist (`a\|b`: either one; `dir/`: three or more pictures in it) |
|
||||
| `says` | `{ id: "logo_end", says: "The wordmark is on screen in each cut's last 3 seconds" }` | words that must be true of the work, judged by a fresh critic, never by you |
|
||||
|
||||
You don't run the critic yourself or choose it: `raea goal check` asks for a verdict when one is missing or older than
|
||||
the work. A `says` rule about a video ("in each cut's last 3 seconds") is watched and heard. One about files or text
|
||||
is read.
|
||||
|
||||
## An example
|
||||
|
||||
```ts
|
||||
// brief.ts
|
||||
import { brief, cut } from "raea/brief"
|
||||
|
||||
export default brief({
|
||||
title: "Juniper Tea · street interviews, round 1",
|
||||
for: "Juniper Tea",
|
||||
audience: "TikTok and Reels, 25-40, already buying loose-leaf",
|
||||
believe: "Juniper tastes like the tea shop, at home",
|
||||
goal: cut({
|
||||
aim: "Ten 9:16 cuts from the street interviews, each ending on the free-trial line",
|
||||
cut: {
|
||||
brief: "brief_docs/brief.txt",
|
||||
count: { value: 10, from: "10 unique cuts total" },
|
||||
seconds: [20, 40],
|
||||
formats: ["9:16"],
|
||||
cuts: [
|
||||
{
|
||||
id: "a1_s1", angle: "Angle 1", kind: "solo", hook: "Direct Problem", text: "captions",
|
||||
beats: [
|
||||
{ at: 0, feel: "caught off guard, curious", story: "she's a real tea drinker, not an actor", asl: 1.5, tempo: "build" },
|
||||
{ at: 4, feel: "the small sadness of bad tea at home", story: "bagged tea tastes like paper to her", asl: 3, tempo: "hold" },
|
||||
{ at: 14, feel: "the surprise of a good first sip", story: "Juniper is the shop's taste at home", asl: 2, tempo: "release" },
|
||||
],
|
||||
},
|
||||
{ id: "a1_s2", angle: "Angle 1", kind: "mashup", hook: "Reaction", text: "captions" },
|
||||
],
|
||||
say: [{ text: "free shipping over $35", from: "Mention: free shipping over $35", every: false }],
|
||||
never: [{ text: "cures", from: "Never claim the tea cures or treats anything" }],
|
||||
cta: { text: "Try Juniper free for 30 days", from: "CTA: \"Try Juniper free for 30 days\"" },
|
||||
open: [
|
||||
{
|
||||
question: "The footage holds 4 usable interviews, not 10: deliver 4 this round?",
|
||||
from: "10 unique cuts total", about: "count",
|
||||
// left out until the person answers; then their words and who gave them
|
||||
answer: "Yes, 4 now and the rest after the reshoot", by: "the client's producer",
|
||||
},
|
||||
],
|
||||
},
|
||||
rules: [
|
||||
{ id: "wordmark_end", says: "The Juniper wordmark is on screen in each cut's last 3 seconds" },
|
||||
],
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
Write it, then run `raea goal check`. It names each rule that doesn't hold and the line of the brief it came from.
|
||||
@@ -16,11 +16,6 @@
|
||||
- Size captions at 60 px or more at 1080 wide (scale with the width), with at least 3:1 contrast against the pixels
|
||||
behind them. Keep them in one place unless a move means something, and keep them off cards, logos, burned-in text
|
||||
and the face (`motion/placement`).
|
||||
- To put a caption or hook in a box that hugs each line, as TikTok draws its text, use `HugText` from
|
||||
`raea/hug-text`: `<HugText lines={[...]} fill="#E8423F" color="#fff" className="..." />`. Each line gets a fill as
|
||||
wide as its words, with one rounded shape around them all. You give the lines, so you decide where each breaks
|
||||
(a caption's come from its word groups). Its emoji draw in colour on any machine, as `EmojiText` from the same
|
||||
module also does. The box is allowed, never required.
|
||||
- Mark each caption: `data-raea-role="caption"` on the element holding its words. A layered export (`raea export
|
||||
capcut`, `raea export xml`; `motion/delivery`) then puts the captions on a track of their own, styled as they're
|
||||
drawn, and writes their words as an .srt beside them; unmarked, they're part of the graphics.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.
|
||||
import type { Beat } from "./brief.gen";
|
||||
|
||||
export type Goal = { kind: GoalKind,
|
||||
/**
|
||||
@@ -232,29 +233,7 @@ text?: string, formats?: Array<string>, seconds?: [number, number],
|
||||
* the cut's beats in order (docs/goal.feature MK48): what each must make the viewer feel and understand, decided
|
||||
* before the cut (Murch: emotion and story weigh most), and its pace
|
||||
*/
|
||||
beats?: Array<CutBeat>, };
|
||||
|
||||
export type CutBeat = {
|
||||
/**
|
||||
* where it starts, in seconds from the cut's start (0 for the first)
|
||||
*/
|
||||
at: number,
|
||||
/**
|
||||
* what the viewer feels here, in the person's words ("the itch of a chore left undone")
|
||||
*/
|
||||
feel: string,
|
||||
/**
|
||||
* what the viewer understands by its end ("the app does the reminding")
|
||||
*/
|
||||
story?: string,
|
||||
/**
|
||||
* its average shot length in seconds: the shots inside it average within a third of this
|
||||
*/
|
||||
asl?: number,
|
||||
/**
|
||||
* how its shot lengths move: "build" (shorter as it goes), "release" (longer) or "hold" (even)
|
||||
*/
|
||||
tempo?: string, };
|
||||
beats?: Array<Beat>, };
|
||||
|
||||
export type Phrase = {
|
||||
/**
|
||||
|
||||
+1
-1
Submodule skills updated: 6c71231e97...fb72c5e256.
@@ -30,7 +30,7 @@ const GROUPS: [string, string, string[]][] = [
|
||||
["Goal and checks", "What the work is held to (brief.ts's `goal`, checked by `raea goal`), and what's wrong before anyone watches it.", ["goal", "check", "judge", "fingerprint", "findings", "scene", "light", "bench", "world", "doctor", "hook", "traces"]],
|
||||
["Footage", "Takes, cuts and the camera, from your own media.", ["media", "words", "cut", "frame", "track", "mezz", "neural"]],
|
||||
["Sound", "Music read, voices, and the audio setup.", ["song", "setup-audio", "voice"]],
|
||||
["raea make: the asset tools", "What a project is made from, each a `raea make TOOL`: components, solids, clothes and motion for SOMA's body, splats, physics, light and weathering bakes, foley and instruments; and generated media, Blender and Godot.", ["make", "component", "solid", "clothes", "motion", "splat", "physics", "bake", "wear", "sao", "tokensynth", "sounds", "gen", "blender", "godot"]],
|
||||
["raea make: the asset tools", "What a project is made from, each a `raea make TOOL`: components, solids, clothes and motion for SOMA's body, splats, physics, light and weathering bakes, foley and instruments; and generated media, Blender, Godot and forma.", ["make", "component", "solid", "clothes", "motion", "splat", "physics", "bake", "wear", "sao", "tokensynth", "sounds", "gen", "blender", "godot", "forma"]],
|
||||
["Agents and setup", "What an agent reads and shows the person, and the tools raea installs.", ["guide", "fix", "context", "notes", "show", "skill", "skills", "setup", "bug", "ask"]],
|
||||
]
|
||||
/** a verb as it is typed: an asset tool is under make (`make solid`), every other verb is itself */
|
||||
|
||||
@@ -22,8 +22,7 @@ generic=(
|
||||
)
|
||||
# allowed: example home folders, the credits for what raea ports (NOTICE, ported headers), and licence boilerplate. Written
|
||||
# split ('Hyper''Frames') so this line doesn't match the names list itself.
|
||||
# (/home/sprite and /home/raea are raea cloud's box users, a Sprite's and a Fly Machine's: no person's folder)
|
||||
allow='/Users/(a|you|me|name|user|USER|runner)/|/home/(you|user|runner|USER|sprite|raea)/|PERFORMANCE OF'
|
||||
allow='/Users/(a|you|me|name|user|USER|runner)/|/home/(you|user|runner|USER)/|PERFORMANCE OF'
|
||||
allow+='|Portions ported from Hyper''Frames \(Apache-2\.0|ports? from Hyper''Frames|github\.com/heygen-com/hyper''frames'
|
||||
|
||||
names_file() {
|
||||
|
||||
Reference in new issue
Block a user