mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fbde2d3343 |
No files matched your search
Generated
-1
@@ -13820,7 +13820,6 @@ dependencies = [
|
|||||||
"fastrand",
|
"fastrand",
|
||||||
"raea-app-check",
|
"raea-app-check",
|
||||||
"raea-app-double",
|
"raea-app-double",
|
||||||
"raea-io-clef",
|
|
||||||
"raea-io-home",
|
"raea-io-home",
|
||||||
"raea-sys-columns",
|
"raea-sys-columns",
|
||||||
"raea-sys-fingerprint",
|
"raea-sys-fingerprint",
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ fn labels_from_three_projects_calibrate_a_question_and_new_words_are_measured_on
|
|||||||
let sent = &groups[0].questions[0];
|
let sent = &groups[0].questions[0];
|
||||||
assert!(sent.calibrated() && sent.calibration.as_ref().is_some_and(|c| c.by == "you"), "{sent:?}");
|
assert!(sent.calibrated() && sent.calibration.as_ref().is_some_and(|c| c.by == "you"), "{sent:?}");
|
||||||
// new words for the flat question, asked of its labelled clips
|
// new words for the flat question, asked of its labelled clips
|
||||||
let (sum, both) = calibrate::try_words("cal.flat", "Does anything look broken?", &Opts { jobs: 4, dry: false, ask: sees_bad, by_ref: None }, &mut |_| {}).unwrap();
|
let (sum, both) = calibrate::try_words("cal.flat", "Does anything look broken?", &Opts { jobs: 4, dry: false, ask: sees_bad }, &mut |_| {}).unwrap();
|
||||||
let (old, new) = both.unwrap();
|
let (old, new) = both.unwrap();
|
||||||
assert_eq!(sum.calls, 36);
|
assert_eq!(sum.calls, 36);
|
||||||
assert_eq!((old.auc, new.auc, new.problems + new.clean), (Some(0.5), Some(1.0), 36), "{new:?}");
|
assert_eq!((old.auc, new.auc, new.problems + new.clean), (Some(0.5), Some(1.0), 36), "{new:?}");
|
||||||
|
|||||||
+27
-119
@@ -5,12 +5,6 @@
|
|||||||
//! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing. A group can
|
//! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing. A group can
|
||||||
//! carry clips kept from an earlier call instead of a file to cut (`raea ask try`), and every question goes out with the
|
//! carry clips kept from an earlier call instead of a file to cut (`raea ask try`), and every question goes out with the
|
||||||
//! person's own calibration when it has earned one (calibrate.rs).
|
//! person's own calibration when it has earned one (calibrate.rs).
|
||||||
//!
|
|
||||||
//! Through an agent key (a pipeline, CI, a raea cloud box), a call about the picture with its sound, at most a minute,
|
|
||||||
//! names the video kept on raea-api and its window instead of cutting clips here (raea_io_clef::by_reference, 12-04): the
|
|
||||||
//! video goes up once, raea-api cuts the window, and this machine decodes nothing, so every call goes at once. Where
|
|
||||||
//! that isn't offered, each file's video windows are cut in one pass over the stretch they cover (`media::videos`),
|
|
||||||
//! not one decode per window.
|
|
||||||
|
|
||||||
use std::collections::{BTreeSet, HashMap};
|
use std::collections::{BTreeSet, HashMap};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
@@ -18,7 +12,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|||||||
use std::sync::{Arc, Mutex, mpsc};
|
use std::sync::{Arc, Mutex, mpsc};
|
||||||
|
|
||||||
use raea_core_ask::{Kind, Picks, Question, Sees, Window, limits};
|
use raea_core_ask::{Kind, Picks, Question, Sees, Window, limits};
|
||||||
use raea_io_clef::{Answered, ByReference, Call, Fail, Media, Source, media};
|
use raea_io_clef::{Answered, Call, Fail, Media, media};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
@@ -108,20 +102,11 @@ pub struct Opts {
|
|||||||
pub dry: bool,
|
pub dry: bool,
|
||||||
/// how a call is made: `raea_io_clef::ask` (a test gives its own)
|
/// how a call is made: `raea_io_clef::ask` (a test gives its own)
|
||||||
pub ask: fn(&Call) -> Result<Answered, Fail>,
|
pub ask: fn(&Call) -> Result<Answered, Fail>,
|
||||||
/// how a call by reference is made, when one can be (an agent key is the first route): `raea_io_clef::ask_by_reference`;
|
|
||||||
/// its `Fail::Next` means the clips are cut here and `ask` is used
|
|
||||||
pub by_ref: Option<fn(&ByReference) -> Result<Answered, Fail>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Opts {
|
impl Opts {
|
||||||
pub fn new(jobs: usize, dry: bool) -> Opts {
|
pub fn new(jobs: usize, dry: bool) -> Opts {
|
||||||
let by_ref = !raea_io_clef::by_reference::off(&raea_io_clef::route::open());
|
Opts { jobs, dry, ask: raea_io_clef::ask }
|
||||||
Opts { jobs, dry, ask: raea_io_clef::ask, by_ref: by_ref.then_some(raea_io_clef::ask_by_reference as fn(&ByReference) -> Result<Answered, Fail>) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether this machine cuts the picture: nothing goes by reference, or raea-api has said it can't take it.
|
|
||||||
fn cuts_here(&self) -> bool {
|
|
||||||
self.by_ref.is_none() || raea_io_clef::by_reference::off(&raea_io_clef::route::open())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,50 +166,6 @@ pub fn plan(entries: &[Entry]) -> (Vec<Group>, Vec<Answer>) {
|
|||||||
/// Clips cut once a run, by what they are.
|
/// Clips cut once a run, by what they are.
|
||||||
type Cuts = Mutex<HashMap<String, Result<Arc<Vec<u8>>, String>>>;
|
type Cuts = Mutex<HashMap<String, Result<Arc<Vec<u8>>, String>>>;
|
||||||
|
|
||||||
/// A clip's name among the cuts: what it is, of which file, over which window.
|
|
||||||
fn cut_key(what: &str, f: &Path, from: f64, to: Option<f64>) -> String {
|
|
||||||
format!("{what}:{}:{from}:{to:?}", f.display())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Each file's video windows the run's calls look at, cut in one pass the first time any of them is needed here.
|
|
||||||
struct Batches {
|
|
||||||
windows: HashMap<PathBuf, Vec<(f64, Option<f64>)>>,
|
|
||||||
done: Mutex<HashMap<PathBuf, Arc<Mutex<bool>>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Batches {
|
|
||||||
fn plan(groups: &[Group]) -> Batches {
|
|
||||||
let mut windows: HashMap<PathBuf, Vec<(f64, Option<f64>)>> = HashMap::new();
|
|
||||||
for g in groups.iter().filter(|g| g.kept.is_none() && g.sees == Sees::Video && g.piece.probe.video) {
|
|
||||||
let w = windows.entry(g.piece.file.clone()).or_default();
|
|
||||||
if !w.contains(&(g.from, g.to)) {
|
|
||||||
w.push((g.from, g.to));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Batches { windows, done: Mutex::default() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every window of `f` not cut yet, cut in one pass (once a run); a window it fails leaves is cut on its own later.
|
|
||||||
fn cut(&self, cuts: &Cuts, f: &Path) {
|
|
||||||
let Some(all) = self.windows.get(f).filter(|w| w.len() > 1) else { return };
|
|
||||||
let lock = self.done.lock().unwrap().entry(f.to_path_buf()).or_default().clone();
|
|
||||||
let mut done = lock.lock().unwrap();
|
|
||||||
if std::mem::replace(&mut *done, true) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let left: Vec<(f64, Option<f64>)> = all.iter().filter(|(from, to)| !cuts.lock().unwrap().contains_key(&cut_key("video", f, *from, *to))).copied().collect();
|
|
||||||
if left.len() < 2 {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if let Ok(clips) = media::videos(f, &left) {
|
|
||||||
let mut c = cuts.lock().unwrap();
|
|
||||||
for ((from, to), clip) in left.iter().zip(clips) {
|
|
||||||
c.insert(cut_key("video", f, *from, *to), Ok(Arc::new(clip)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn cut(cuts: &Cuts, key: String, make: impl FnOnce() -> Result<Vec<u8>, String>) -> Result<Arc<Vec<u8>>, String> {
|
fn cut(cuts: &Cuts, key: String, make: impl FnOnce() -> Result<Vec<u8>, String>) -> Result<Arc<Vec<u8>>, String> {
|
||||||
if let Some(r) = cuts.lock().unwrap().get(&key) {
|
if let Some(r) = cuts.lock().unwrap().get(&key) {
|
||||||
return r.clone();
|
return r.clone();
|
||||||
@@ -235,7 +176,7 @@ fn cut(cuts: &Cuts, key: String, make: impl FnOnce() -> Result<Vec<u8>, String>)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A group's media, and its seconds of video and of sound (for the estimate).
|
/// A group's media, and its seconds of video and of sound (for the estimate).
|
||||||
fn media_of(g: &Group, cuts: &Cuts, batches: Option<&Batches>) -> Result<(Media, f64, f64), String> {
|
fn media_of(g: &Group, cuts: &Cuts) -> Result<(Media, f64, f64), String> {
|
||||||
if let Some(k) = &g.kept {
|
if let Some(k) = &g.kept {
|
||||||
return Ok((k.media.clone(), k.video_seconds, k.sound_seconds));
|
return Ok((k.media.clone(), k.video_seconds, k.sound_seconds));
|
||||||
}
|
}
|
||||||
@@ -246,12 +187,9 @@ fn media_of(g: &Group, cuts: &Cuts, batches: Option<&Batches>) -> Result<(Media,
|
|||||||
let (mut vs, mut ss) = (0.0, 0.0);
|
let (mut vs, mut ss) = (0.0, 0.0);
|
||||||
for f in &files {
|
for f in &files {
|
||||||
let p = if *f == g.piece.file.as_path() { g.piece.probe } else { media::probe(f)? };
|
let p = if *f == g.piece.file.as_path() { g.piece.probe } else { media::probe(f)? };
|
||||||
let k = |what: &str| cut_key(what, f, from, to);
|
let k = |what: &str| format!("{what}:{}:{from}:{to:?}", f.display());
|
||||||
match g.sees {
|
match g.sees {
|
||||||
Sees::Video if p.video => {
|
Sees::Video if p.video => {
|
||||||
if let Some(b) = batches {
|
|
||||||
b.cut(cuts, f);
|
|
||||||
}
|
|
||||||
m.videos.push(cut(cuts, k("video"), || media::video(f, from, to))?.to_vec());
|
m.videos.push(cut(cuts, k("video"), || media::video(f, from, to))?.to_vec());
|
||||||
vs += span(&p).min(limits::VIDEO_SECONDS);
|
vs += span(&p).min(limits::VIDEO_SECONDS);
|
||||||
}
|
}
|
||||||
@@ -297,34 +235,40 @@ pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut
|
|||||||
out(Event::Answer(a));
|
out(Event::Answer(a));
|
||||||
}
|
}
|
||||||
let cuts: Cuts = Mutex::default();
|
let cuts: Cuts = Mutex::default();
|
||||||
let batches = Batches::plan(&groups);
|
|
||||||
let (next, spent) = (AtomicUsize::new(0), AtomicBool::new(false));
|
let (next, spent) = (AtomicUsize::new(0), AtomicBool::new(false));
|
||||||
let spent_why = Mutex::new(String::new());
|
let spent_why = Mutex::new(String::new());
|
||||||
let (tx, rx) = mpsc::channel::<(usize, Done)>();
|
let (tx, rx) = mpsc::channel::<(usize, Done)>();
|
||||||
std::thread::scope(|s| {
|
std::thread::scope(|s| {
|
||||||
for _ in 0..o.jobs.clamp(1, JOBS_MOST).min(groups.len().max(1)) {
|
for _ in 0..o.jobs.clamp(1, 16).min(groups.len().max(1)) {
|
||||||
let (tx, groups, cuts, batches, next, spent, spent_why) = (tx.clone(), &groups, &cuts, &batches, &next, &spent, &spent_why);
|
let (tx, groups, cuts, next, spent, spent_why) = (tx.clone(), &groups, &cuts, &next, &spent, &spent_why);
|
||||||
s.spawn(move || {
|
s.spawn(move || {
|
||||||
loop {
|
loop {
|
||||||
let i = next.fetch_add(1, Ordering::Relaxed);
|
let i = next.fetch_add(1, Ordering::Relaxed);
|
||||||
let Some(g) = groups.get(i) else { break };
|
let Some(g) = groups.get(i) else { break };
|
||||||
let spend = |why: String| {
|
|
||||||
spent.store(true, Ordering::Relaxed);
|
|
||||||
*spent_why.lock().unwrap() = why.clone();
|
|
||||||
Done::Waits(why)
|
|
||||||
};
|
|
||||||
let done = if spent.load(Ordering::Relaxed) {
|
let done = if spent.load(Ordering::Relaxed) {
|
||||||
Done::Waits(spent_why.lock().unwrap().clone())
|
Done::Waits(spent_why.lock().unwrap().clone())
|
||||||
} else if let Some(r) = by_reference(g, o) {
|
|
||||||
// asked by reference; when it can't be, the clips are cut here below
|
|
||||||
match r {
|
|
||||||
Ok(a) => Done::Asked(a, vec![], g.piece.state()),
|
|
||||||
Err(Fail::Spent(why)) => spend(why),
|
|
||||||
Err(Fail::Stop(why)) => Done::Failed(why),
|
|
||||||
Err(Fail::Next(_)) => here(g, o, cuts, batches, &spend),
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
here(g, o, cuts, batches, &spend)
|
match media_of(g, cuts) {
|
||||||
|
Err(e) => Done::Failed(e),
|
||||||
|
Ok((m, vs, ss)) => {
|
||||||
|
let state = g.kept.as_ref().map_or_else(|| g.piece.state(), |k| k.state.clone());
|
||||||
|
let call = Call { state, questions: g.questions.clone(), media: m };
|
||||||
|
let estimate = limits::estimate(vs, ss, call.media.stills.len(), call.state.len(), call.questions.len());
|
||||||
|
if o.dry {
|
||||||
|
Done::Would(would(g, &call, estimate))
|
||||||
|
} else {
|
||||||
|
match (o.ask)(&call) {
|
||||||
|
Ok(a) => Done::Asked(a, kept(&call.media), call.state),
|
||||||
|
Err(Fail::Spent(why)) => {
|
||||||
|
spent.store(true, Ordering::Relaxed);
|
||||||
|
*spent_why.lock().unwrap() = why.clone();
|
||||||
|
Done::Waits(why)
|
||||||
|
}
|
||||||
|
Err(f) => Done::Failed(f.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
if tx.send((i, done)).is_err() {
|
if tx.send((i, done)).is_err() {
|
||||||
break;
|
break;
|
||||||
@@ -341,42 +285,6 @@ pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut
|
|||||||
sum
|
sum
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Calls at once: by reference each is a request and no work here, so more than a machine has cores.
|
|
||||||
const JOBS_MOST: usize = 32;
|
|
||||||
|
|
||||||
/// A call by reference, when this group can go that way: the picture with its sound (or none), of one file, a minute at
|
|
||||||
/// most, not clips kept from an earlier call, not a dry run. None: it can't, and its clips are cut here.
|
|
||||||
fn by_reference(g: &Group, o: &Opts) -> Option<Result<Answered, Fail>> {
|
|
||||||
let ask = o.by_ref?;
|
|
||||||
let p = g.piece.probe;
|
|
||||||
let end = g.to.unwrap_or(p.seconds).min(p.seconds);
|
|
||||||
if o.dry || g.kept.is_some() || !g.with.is_empty() || g.sees != Sees::Video || !p.video || end <= g.from || end - g.from > limits::VIDEO_SECONDS {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let source = Source { file: g.piece.file.clone(), from: g.from, to: g.to, sound: g.hears && p.sound };
|
|
||||||
Some(ask(&ByReference { state: g.piece.state(), questions: g.questions.clone(), source }))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A call with its clips cut here (or kept from an earlier call): asked, or (dry) what would be sent.
|
|
||||||
fn here(g: &Group, o: &Opts, cuts: &Cuts, batches: &Batches, spend: &dyn Fn(String) -> Done) -> Done {
|
|
||||||
match media_of(g, cuts, o.cuts_here().then_some(batches)) {
|
|
||||||
Err(e) => Done::Failed(e),
|
|
||||||
Ok((m, vs, ss)) => {
|
|
||||||
let state = g.kept.as_ref().map_or_else(|| g.piece.state(), |k| k.state.clone());
|
|
||||||
let call = Call { state, questions: g.questions.clone(), media: m };
|
|
||||||
let estimate = limits::estimate(vs, ss, call.media.stills.len(), call.state.len(), call.questions.len());
|
|
||||||
if o.dry {
|
|
||||||
return Done::Would(would(g, &call, estimate));
|
|
||||||
}
|
|
||||||
match (o.ask)(&call) {
|
|
||||||
Ok(a) => Done::Asked(a, kept(&call.media), call.state),
|
|
||||||
Err(Fail::Spent(why)) => spend(why),
|
|
||||||
Err(f) => Done::Failed(f.to_string()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The clips a call sent, kept by hash for `raea ask try`.
|
/// The clips a call sent, kept by hash for `raea ask try`.
|
||||||
fn kept(m: &Media) -> Vec<String> {
|
fn kept(m: &Media) -> Vec<String> {
|
||||||
let each = |v: &[Vec<u8>], ext: &str| v.iter().map(|b| record::keep_media(b, ext)).collect::<Vec<_>>();
|
let each = |v: &[Vec<u8>], ext: &str| v.iter().map(|b| record::keep_media(b, ext)).collect::<Vec<_>>();
|
||||||
|
|||||||
@@ -124,7 +124,7 @@ fn clip(name: &str) -> PathBuf {
|
|||||||
fn run(entries: Vec<Entry>, jobs: usize, ask: fn(&Call) -> Result<Answered, Fail>) -> (runner::Summary, Vec<Answer>) {
|
fn run(entries: Vec<Entry>, jobs: usize, ask: fn(&Call) -> Result<Answered, Fail>) -> (runner::Summary, Vec<Answer>) {
|
||||||
setup();
|
setup();
|
||||||
let mut got = Vec::new();
|
let mut got = Vec::new();
|
||||||
let sum = runner::run(entries, &Opts { jobs, dry: false, ask, by_ref: None }, &mut |e| {
|
let sum = runner::run(entries, &Opts { jobs, dry: false, ask }, &mut |e| {
|
||||||
if let Event::Answer(a) = e {
|
if let Event::Answer(a) = e {
|
||||||
got.push(a.clone());
|
got.push(a.clone());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ raea-sys-fingerprint = { path = "../../systems/fingerprint" }
|
|||||||
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
|
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
|
||||||
# score --ask: each flag asked again of the decision model (docs/ask.feature AK8)
|
# score --ask: each flag asked again of the decision model (docs/ask.feature AK8)
|
||||||
raea-app-double = { path = "../double" }
|
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" }
|
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
|
||||||
# the encoders and the columns they make
|
# the encoders and the columns they make
|
||||||
raea-sys-columns = { path = "../../systems/columns" }
|
raea-sys-columns = { path = "../../systems/columns" }
|
||||||
|
|||||||
@@ -21,13 +21,13 @@ use std::path::Path;
|
|||||||
|
|
||||||
pub use serve::serve;
|
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)
|
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
|
||||||
pub type Eval = fn(&Path) -> Result<String, String>;
|
pub type Eval = fn(&Path) -> Result<String, String>;
|
||||||
|
|
||||||
/// The flags each verb takes, and whether each takes a value
|
/// 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),
|
("--fp", true),
|
||||||
("--was", true),
|
("--was", true),
|
||||||
("--to", true),
|
("--to", true),
|
||||||
@@ -51,6 +51,7 @@ pub(crate) const FLAGS: [(&str, bool); 30] = [
|
|||||||
("--as", true),
|
("--as", true),
|
||||||
("--against", true),
|
("--against", true),
|
||||||
("--profile", true),
|
("--profile", true),
|
||||||
|
("--by", true),
|
||||||
("--ask", true),
|
("--ask", true),
|
||||||
("--tally", false),
|
("--tally", false),
|
||||||
("--bad", false),
|
("--bad", false),
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT` has a fresh session of
|
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT [--by kimi|claude]`
|
||||||
//! 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
|
//! 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
|
//! 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
|
//! 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
|
//! --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
|
/// One fresh session's words: kimi's or claude's stream, the assistant's text joined
|
||||||
fn ask(cwd: &Path, p: &str) -> Result<String, String> {
|
fn ask(by: &str, p: &str) -> Result<String, String> {
|
||||||
raea_io_clef::critic::ask(cwd, p)
|
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> {
|
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>())
|
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 {
|
pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
|
||||||
let run = || -> Result<String, String> {
|
let run = || -> Result<String, String> {
|
||||||
let w = words(args)?;
|
let w = words(args)?;
|
||||||
let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p));
|
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 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 fp = dir.read(None).map_err(|e| e.to_string())?;
|
||||||
let mut notes = pinned(&project);
|
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()));
|
return Ok(format!("no new pinned notes in {}", project.display()));
|
||||||
}
|
}
|
||||||
for chunk in notes.chunks_mut(40) {
|
for chunk in notes.chunks_mut(40) {
|
||||||
let text = ask(&project, &prompt(&fp, chunk))?;
|
let text = ask(by, &prompt(&fp, chunk))?;
|
||||||
let ans = answer(&text).ok_or_else(|| "the critic answered no readings JSON".to_string())?;
|
let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?;
|
||||||
fold(chunk, &fp, &ans, by);
|
fold(chunk, &fp, &ans, by);
|
||||||
eprintln!("read {} notes", chunk.len());
|
eprintln!("read {} notes", chunk.len());
|
||||||
}
|
}
|
||||||
let read = notes.iter().filter(|n| !n.kind.is_empty()).count();
|
let read = notes.iter().filter(|n| !n.kind.is_empty()).count();
|
||||||
kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));
|
kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));
|
||||||
write_readings(&dir, &kept).map_err(|e| e.to_string())?;
|
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() {
|
match run() {
|
||||||
Ok(o) => {
|
Ok(o) => {
|
||||||
@@ -264,7 +285,7 @@ mod tests {
|
|||||||
let fp = raea_sys_fingerprint::taxonomy::base("me");
|
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 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();
|
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[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[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");
|
assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading");
|
||||||
|
|||||||
+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
|
//! A judge that is an agent CLI rather than clef-omni: `raea judge DIR --by kimi|claude` (Shane, 11-06: "use claude or
|
||||||
//! picks or the agent names): a fresh session of the agent this project runs on, which the host that started it (raea
|
//! 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;
|
||||||
//! 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
|
//! claude with Read alone), given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and
|
||||||
//! look at, given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and never the code or
|
//! never the code or the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
|
||||||
//! 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
|
||||||
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --read` records
|
|
||||||
//! its reading as the eye clef is calibrated against.
|
//! its reading as the eye clef is calibrated against.
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
@@ -12,10 +11,7 @@ use serde_json::{Map, Value, json};
|
|||||||
|
|
||||||
use crate::rubric::{BAR, scores};
|
use crate::rubric::{BAR, scores};
|
||||||
|
|
||||||
/// Whether this session has a critic to ask: where it has, the agent judges; else clef.
|
pub const BY: [&str; 2] = ["kimi", "claude"];
|
||||||
pub fn critic() -> bool {
|
|
||||||
raea_io_clef::critic::here()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The judge prompt: the sheets by name, the brief's words, and the JSON to answer. A `raea make` job's kind asks its
|
/// 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.
|
/// 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)
|
(out, defects, photo)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One fresh judging session of this project's own agent over DIR's sheets, through the host (RAEA_JUDGE_URL): its
|
/// One fresh judging session by `by` over DIR's sheets: its verdict JSON. Its steps stream (kimi's stream-json), each
|
||||||
/// verdict JSON.
|
/// 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>, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
|
pub fn ask(kind: Option<&str>, by: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
|
||||||
let dir = dunce::canonicalize(dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
|
use std::io::BufRead as _;
|
||||||
eprintln!("judge: a fresh session of this project's agent is reading the sheets");
|
let dir = dunce::canonicalize(&dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
|
||||||
let text = raea_io_clef::critic::ask(&dir, &prompt(kind, &dir, brief, target)).map_err(|e| format!("judge: {e}"))?;
|
let p = prompt(kind, &dir, brief, target);
|
||||||
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>()))
|
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
|
//! ~/.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
|
//! (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
|
//! 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.
|
//! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is.
|
||||||
|
|
||||||
use std::path::PathBuf;
|
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 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 kind = kind_in(&verdict);
|
||||||
let cats = scores(kind);
|
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
|
// an agent's reading as the eye (`--by kimi`): a fresh session's scores, and its pass by the same rule in code
|
||||||
if args.iter().any(|a| a == "--read") {
|
if let Some(by) = args.iter().position(|a| a == "--by").and_then(|i| args.get(i + 1)) {
|
||||||
let by = "agent";
|
let v = crate::agent::ask(kind, by, &dir, &json!({}), None)?;
|
||||||
let v = crate::agent::ask(kind, &dir, &json!({}), None)?;
|
|
||||||
let (eye, defects, _) = crate::agent::read(kind, &v);
|
let (eye, defects, _) = crate::agent::read(kind, &v);
|
||||||
if eye.len() < cats.len() {
|
if eye.len() < cats.len() {
|
||||||
return Err(format!("judge eye: {by} scored only {} of {} categories", 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
|
//! 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.
|
//! 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 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 --read: the session's agent's reading as the eye)
|
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --by kimi: an 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 calibrate [--kind scene|kit|shot] [--json]
|
//! 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,
|
//! `--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 mod rubric;
|
||||||
|
|
||||||
|
pub use agent::BY;
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
@@ -31,7 +30,7 @@ use raea_core_facts::{Finding, Level, finding};
|
|||||||
use raea_runtime_bundle::flag;
|
use raea_runtime_bundle::flag;
|
||||||
use serde_json::{Value, json};
|
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).
|
/// `--kind`, checked: one of the rubric's kinds, or none (the default rubric).
|
||||||
pub fn kind_of(args: &[String]) -> Result<Option<String>, String> {
|
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 brief = brief_of(flag(args, "--brief").as_deref())?;
|
||||||
let target = flag(args, "--target").map(PathBuf::from);
|
let target = flag(args, "--target").map(PathBuf::from);
|
||||||
let dry = args.iter().any(|a| a == "--dry");
|
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 by != "clef" {
|
||||||
if dry {
|
if dry {
|
||||||
return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));
|
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);
|
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"]}));
|
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 (pass, why) = rubric::pass_for(kind, &scores, &defects);
|
||||||
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
|
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 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 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,
|
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)});
|
"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!(!pass && why[0].starts_with("blocking"));
|
||||||
assert!(crate::agent::last_verdict("no json here").is_none());
|
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
|
// 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];
|
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 (agent)"));
|
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!(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]
|
#[test]
|
||||||
|
|||||||
@@ -136,34 +136,6 @@ Feature: Ask: questions about a piece's picture and sound, answered by the decis
|
|||||||
pool spent on the third call keeps two calls' answers and sends nothing more. `raea check`, the critique and
|
pool spent on the third call keeps two calls' answers and sends nothing more. `raea check`, the critique and
|
||||||
the fingerprint move onto the runner in AK5, AK4 and AK8. docs/manual/reference/sdk/ask.md is `raea/ask`'s.
|
the fingerprint move onto the runner in AK5, AK4 and AK8. docs/manual/reference/sdk/ask.md is `raea/ask`'s.
|
||||||
|
|
||||||
@needs:AK3
|
|
||||||
Scenario: AK3b. A window asked by reference: the video kept once on raea-api, cut there
|
|
||||||
Given a raea cloud box judging a project's beats (12-04): about 18 questions a stop, each about its own window of
|
|
||||||
one of about six cuts (94 MB each, 1080x1920), every `raea ask` decoding its cut, cutting its window and
|
|
||||||
encoding it (6.4 s and 18 s of CPU an ask on the box's 8 cores, so six at a time was the ceiling)
|
|
||||||
And raea-api's `POST /v1/clef/media {sha256, size}` (kept, or a URL to PUT it to once) and `POST /v1/clef/ask
|
|
||||||
{state, questions, source: {sha256, from, to, sound}}`, which cuts the window with Cloudflare's Media
|
|
||||||
Transformations (480 px wide H.264, the sound in the clip), keeps the clip, and asks clef as any ask
|
|
||||||
(raea-platform apps/site/api/src/clef.ts)
|
|
||||||
When a call is asked through an agent key (`RAEA_AGENT_KEY` is the first route) about the picture with its
|
|
||||||
sound, one file, at most 60 s
|
|
||||||
Then each video goes up once a run by its SHA-256, or not at all when the account's storage has it already
|
|
||||||
(Git LFS, an upload), every call names it and its window, and the machine decodes nothing, so `--jobs` can be
|
|
||||||
as many as the calls (32 at most)
|
|
||||||
And a raea-api that doesn't offer it (an older one: 404 or 403 for the route, bad_media for the source; one
|
|
||||||
without Media Transformations: 501) turns it off for the run, and a window it can't cut (too large, not kept,
|
|
||||||
a failed cut) is cut here for that call alone; the app's route, stills, a sound alone, files set beside it
|
|
||||||
(`--with`) and windows over 60 s are cut here as before; `RAEA_ASK_BY_REFERENCE=0` turns it off
|
|
||||||
And where windows are cut here, each file's video windows are cut in one pass over the stretch they cover (one
|
|
||||||
decode, one scale, a split to each window's encode), and windows more than 2 s apart are separate passes
|
|
||||||
And `raea goal check` asks all of a stop's windows in one `raea ask --batch` (sdk/goal goal.ts askClefMany), so the
|
|
||||||
brief and each file are read once and each video goes up once
|
|
||||||
Status: in review 12-04 (raea PR on goal-spawn-fallback, raea-platform PR clef-by-reference). io/clef tests (a
|
|
||||||
video goes up once and each window is asked by its hash, a kept one isn't sent, an older raea-api turns it off,
|
|
||||||
a window too large is cut here alone, a spent pool stops), media.rs's stretches test and raea-platform's
|
|
||||||
test/clef-source.sh (a fake cutter in place of Media Transformations) are written; the Rust is unbuilt (the
|
|
||||||
machine had 7 GB free), and Media Transformations on a real cut is unmeasured.
|
|
||||||
|
|
||||||
Rule: AK4. On the person's plan
|
Rule: AK4. On the person's plan
|
||||||
|
|
||||||
@needs:AK3
|
@needs:AK3
|
||||||
|
|||||||
@@ -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 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
|
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
|
Rule: it is proven end to end
|
||||||
Scenario: CL12. A stand-in agent, then a real one
|
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
|
Then test/smoke.sh builds the image, starts it, and checks CL4-CL7, CL14 and CL15 with test/echo-agent.mjs (a
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ raea fingerprint things shot.mp4 --json > things.json
|
|||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```sh
|
```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.
|
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 |
|
| `--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) |
|
| `--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 |
|
| `--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 |
|
| `--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 |
|
| `--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 |
|
| `--from` | `LIST` | A file listing the renders to learn from, one path a line, relative to the file; lines starting with # are skipped |
|
||||||
|
|||||||
@@ -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
|
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
|
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
|
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
|
work, judged by a fresh critic that may only read: `raea goal judge` asks one (`--by claude`, `kimi` or `clef`) and
|
||||||
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
|
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. Who judges is raea's to settle, never the agent's: a rule with a piece to watch or hear (the files it
|
newest file. `clef` is clef-omni, as `raea ask` reaches it: it watches and hears the files a rule names (in the rule's
|
||||||
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`
|
"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
|
||||||
reaches it; any other goes to a fresh session of the agent this project runs on, which the raea app or raea cloud
|
can't see stays open. It is the critic where `RAEA_AGENT_KEY` is set, as on raea cloud; elsewhere the critic is `claude`.
|
||||||
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.
|
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import { brief, rules } from "raea/brief"
|
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 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 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 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 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)
|
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 |
|
| `--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...]`). |
|
| `--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) |
|
| `--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. |
|
| `--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. |
|
| `--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. |
|
||||||
|
|||||||
@@ -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
|
`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,
|
judged without the code or the conversation that made them: by clef-omni on a frozen rubric (the default), or by a
|
||||||
on the judge prompt, where the raea app or raea cloud started that agent; else by clef-omni on a frozen rubric. Who
|
fresh Kimi or Claude session on the judge prompt. The scores come back as data, and whether the scene passes is
|
||||||
judges is raea's to settle: there's no flag for it. 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.
|
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,
|
`--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
|
```sh
|
||||||
raea render scene.tsx --review review/
|
raea render scene.tsx --review review/
|
||||||
raea judge review/ --brief brief.ts
|
raea judge review/ --brief brief.ts
|
||||||
raea judge review/ --target reference.png --json
|
raea judge review/ --by claude --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/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 eye review/ composition=4 light=3 --pass yes # record your own scores, for calibration
|
||||||
raea judge calibrate
|
raea judge calibrate
|
||||||
```
|
```
|
||||||
@@ -33,7 +32,7 @@ raea judge calibrate
|
|||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```sh
|
```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.
|
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 |
|
| Flag | Takes | What it does |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `--brief` | `brief.ts` | The project's brief, so the judge knows what the scene is for. |
|
| `--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. |
|
| `--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. |
|
| `--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. |
|
| `--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. |
|
| `--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. |
|
| `--target` | `T.png` | A reference image the colour sheet is judged against. |
|
||||||
|
|
||||||
<!-- generated:end -->
|
<!-- generated:end -->
|
||||||
@@ -44,7 +44,6 @@ libraries (pianos, General MIDI instruments, orchestral and percussion samples,
|
|||||||
| `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN` | The decision model (clef-omni on Workers AI) on your own Cloudflare account, for `raea ask`, `raea judge` and the checks that ask. Signed in to raea on Pro or Studio, the app pays from your plan's monthly pool first (docs/ask.feature) |
|
| `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN` | The decision model (clef-omni on Workers AI) on your own Cloudflare account, for `raea ask`, `raea judge` and the checks that ask. Signed in to raea on Pro or Studio, the app pays from your plan's monthly pool first (docs/ask.feature) |
|
||||||
| `RAEA_AGENT_KEY`, `RAEA_API` | An agent key with the `ask` scope, and the API address it came with: asks from your plan's pool with no app running (a pipeline, CI, a server) |
|
| `RAEA_AGENT_KEY`, `RAEA_API` | An agent key with the `ask` scope, and the API address it came with: asks from your plan's pool with no app running (a pipeline, CI, a server) |
|
||||||
| `RAEA_ASK_ROUTE` | `app`, `agent` or `own`: ask only that way, rather than the first that answers |
|
| `RAEA_ASK_ROUTE` | `app`, `agent` or `own`: ask only that way, rather than the first that answers |
|
||||||
| `RAEA_ASK_BY_REFERENCE` | `0`: never ask about a window by naming the video kept on raea-api; cut its clips here (docs/ask.feature AK3b) |
|
|
||||||
| `RAEA_ASK_DIR` | Where `raea ask` keeps its answers, the clips it cut and its cache (`~/.raea/ask`) |
|
| `RAEA_ASK_DIR` | Where `raea ask` keeps its answers, the clips it cut and its cache (`~/.raea/ask`) |
|
||||||
| `RAEA_CLEF_REPLAY` | A JSON file of answers by question id, given back for every call: for tests, which then never spend |
|
| `RAEA_CLEF_REPLAY` | A JSON file of answers by question id, given back for every call: for tests, which then never spend |
|
||||||
| `RAEA_GUIDES` | A folder of craft references for the agent's `guide` tool (`captions.md`, `motion-rules.md`, ...) |
|
| `RAEA_GUIDES` | A folder of craft references for the agent's `guide` tool (`captions.md`, `motion-rules.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)
|
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 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 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 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
|
/// One of GOAL_TS's verbs (or `make place`): printed as it says, and the process exits with its code (1 on an
|
||||||
|
|||||||
@@ -1,170 +0,0 @@
|
|||||||
//! A call that names a video kept on raea-api and a window of it, in place of its clips (docs/ask.feature AK3b; raea-api
|
|
||||||
//! clef.ts, "Asking by reference"). A raea cloud box judging a project's beats decoded the same cut for every window it
|
|
||||||
//! asked about (12-04: 6.4 s and 18 s of CPU an ask, so six at a time was its ceiling). Now each video goes up once a
|
|
||||||
//! run, by its SHA-256 (`POST /v1/clef/media`, then one PUT; nothing at all when it's there already, in the account's
|
|
||||||
//! storage or Git LFS), and each call names it and a window, which raea-api cuts with Cloudflare's Media
|
|
||||||
//! Transformations: nothing is decoded here, so every window can be asked at once. Only through an agent key (the route
|
|
||||||
//! a pipeline, CI or a raea cloud box asks by), and only for the picture with its sound, at most 60 s (runner.rs says
|
|
||||||
//! which calls); anything else, and every call once raea-api has shown it doesn't offer this, cuts its clips here as
|
|
||||||
//! before. `RAEA_ASK_BY_REFERENCE=0` turns it off.
|
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
use std::io::Read as _;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::sync::{Arc, Mutex, OnceLock};
|
|
||||||
|
|
||||||
use raea_core_ask::Question;
|
|
||||||
use raea_io_home::setting;
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
|
|
||||||
use crate::cache;
|
|
||||||
use crate::client::{Answered, Call, Fail, Transport, api_answer, said};
|
|
||||||
use crate::route::Route;
|
|
||||||
|
|
||||||
/// The largest video raea-api cuts (Media Transformations' input limit).
|
|
||||||
pub const MAX_BYTES: u64 = 100 * 1024 * 1024;
|
|
||||||
|
|
||||||
const ROUTE: &str = "your raea plan, with an agent key (cut on raea-api)";
|
|
||||||
|
|
||||||
/// A window of a video, to be cut on raea-api: `sound` puts its sound in the clip (clef hears a video's soundtrack with
|
|
||||||
/// its frames).
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct Source {
|
|
||||||
pub file: PathBuf,
|
|
||||||
pub from: f64,
|
|
||||||
pub to: Option<f64>,
|
|
||||||
pub sound: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One call by reference: what the piece is, its questions, and the window they're about.
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct ByReference {
|
|
||||||
pub state: String,
|
|
||||||
pub questions: Vec<Question>,
|
|
||||||
pub source: Source,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The raea-apis that have shown they don't offer it this run (an older one, or one that can't cut): every call to them
|
|
||||||
/// cuts its own clips.
|
|
||||||
fn refused() -> &'static Mutex<HashSet<String>> {
|
|
||||||
static OFF: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
|
|
||||||
OFF.get_or_init(Mutex::default)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn turn_off(api: &str) {
|
|
||||||
refused().lock().unwrap().insert(api.to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether asking by reference is off for the rest of this run (or wasn't open: no agent key first, or turned off).
|
|
||||||
pub fn off(routes: &[Route]) -> bool {
|
|
||||||
api(routes).is_none()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The agent key's raea-api and key, when a call can go by reference: an agent key is the first route, and neither
|
|
||||||
/// `RAEA_ASK_BY_REFERENCE=0` nor that raea-api has turned it off.
|
|
||||||
pub fn api(routes: &[Route]) -> Option<(&str, &str)> {
|
|
||||||
if setting("RAEA_ASK_BY_REFERENCE").as_deref() == Some("0") {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
match routes.first() {
|
|
||||||
Some(Route::Agent { api, key }) if !refused().lock().unwrap().contains(api.as_str()) => Some((api.as_str(), key.as_str())),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Kept = Arc<OnceLock<Result<String, Fail>>>;
|
|
||||||
|
|
||||||
/// Each file hashed and kept once a run, by its path, length and time written: every call about it waits for that once.
|
|
||||||
fn memo(file: &Path) -> Kept {
|
|
||||||
static FILES: OnceLock<Mutex<HashMap<String, Kept>>> = OnceLock::new();
|
|
||||||
let m = std::fs::metadata(file).ok();
|
|
||||||
let id = format!("{}\u{1f}{:?}\u{1f}{:?}", file.display(), m.as_ref().map(|m| m.len()), m.and_then(|m| m.modified().ok()));
|
|
||||||
FILES.get_or_init(Mutex::default).lock().unwrap().entry(id).or_default().clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A file's SHA-256 and length, read once in 1 MiB pieces.
|
|
||||||
pub fn hashed(file: &Path) -> Result<(String, u64), String> {
|
|
||||||
let mut f = std::fs::File::open(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
|
||||||
let (mut h, mut buf, mut n) = (Sha256::new(), vec![0u8; 1 << 20], 0u64);
|
|
||||||
loop {
|
|
||||||
let got = f.read(&mut buf).map_err(|e| format!("{}: {e}", file.display()))?;
|
|
||||||
if got == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
h.update(&buf[..got]);
|
|
||||||
n += got as u64;
|
|
||||||
}
|
|
||||||
Ok((h.finalize().iter().map(|b| format!("{b:02x}")).collect(), n))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The video on raea-api, by its SHA-256: there already, or sent once. A raea-api that doesn't know the route turns
|
|
||||||
/// asking by reference off for the run.
|
|
||||||
fn keep(t: &dyn Transport, api: &str, key: &str, file: &Path) -> Result<String, Fail> {
|
|
||||||
let (sha, size) = hashed(file).map_err(Fail::Next)?;
|
|
||||||
if size > MAX_BYTES {
|
|
||||||
return Err(Fail::Next(format!("{} is over {} MB, more than raea-api cuts", file.display(), MAX_BYTES >> 20)));
|
|
||||||
}
|
|
||||||
let (code, j) = t.post(&format!("{api}/v1/clef/media"), Some(key), &json!({"sha256": sha, "size": size})).map_err(|e| Fail::Next(format!("keeping {} for asking: {e}", file.display())))?;
|
|
||||||
match code {
|
|
||||||
200 if j["kept"] == true => Ok(sha),
|
|
||||||
200 => {
|
|
||||||
let url = j["url"].as_str().ok_or_else(|| Fail::Next("raea-api gave no URL to keep the video at".into()))?;
|
|
||||||
match t.put_file(url, file) {
|
|
||||||
Ok(200..=299) => Ok(sha),
|
|
||||||
Ok(c) => Err(Fail::Next(format!("keeping {} for asking: HTTP {c}", file.display()))),
|
|
||||||
Err(e) => Err(Fail::Next(e)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// no plan, a spent pool, a file too large to cut there: this call's clips are cut here, and its ask says why
|
|
||||||
402 | 413 => Err(Fail::Next(said(&j, code))),
|
|
||||||
// an older raea-api (404, or 403 for an agent key's route it doesn't know): cut here for the rest of the run
|
|
||||||
_ => {
|
|
||||||
turn_off(api);
|
|
||||||
Err(Fail::Next(format!("raea-api doesn't keep videos for asking: {}", said(&j, code))))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The body raea-api takes: the state, the questions, and the video by its hash with the window.
|
|
||||||
fn body(call: &ByReference, sha: &str) -> Value {
|
|
||||||
let c = Call { state: call.state.clone(), questions: call.questions.clone(), ..Default::default() };
|
|
||||||
let s = &call.source;
|
|
||||||
let mut source = json!({"sha256": sha, "from": s.from, "sound": s.sound});
|
|
||||||
if let Some(to) = s.to {
|
|
||||||
source["to"] = json!(to);
|
|
||||||
}
|
|
||||||
json!({"state": c.state(), "questions": c.questions(), "source": source})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One call by reference through the agent key's raea-api. `Fail::Next` means cut the clips here and ask as before.
|
|
||||||
pub fn ask(t: &dyn Transport, call: &ByReference, routes: &[Route]) -> Result<Answered, Fail> {
|
|
||||||
let Some((api, key)) = api(routes) else { return Err(Fail::Next("asked by reference only with an agent key".into())) };
|
|
||||||
let questions = Call { questions: call.questions.clone(), ..Default::default() };
|
|
||||||
if let Some(p) = questions.question_problem() {
|
|
||||||
return Err(Fail::Stop(p));
|
|
||||||
}
|
|
||||||
let file = &call.source.file;
|
|
||||||
let sha = memo(file).get_or_init(|| keep(t, api, key, file)).clone()?;
|
|
||||||
let body = body(call, &sha);
|
|
||||||
let ckey = cache::key_of(&body);
|
|
||||||
if let Some(answers) = cache::get(&ckey) {
|
|
||||||
return Ok(Answered { answers, cost: 0.0, cached: true, route: "asked before (cache)".into(), pool_left: None });
|
|
||||||
}
|
|
||||||
let own = routes.iter().any(|r| matches!(r, Route::Own { .. }));
|
|
||||||
let (code, j) = t.post(&format!("{api}/v1/clef/ask"), Some(key), &body).map_err(|e| Fail::Next(format!("{ROUTE} didn't answer: {e}")))?;
|
|
||||||
match (code, j["error"].as_str()) {
|
|
||||||
// an older raea-api (it reads no source), or one that can't cut: cut here for the rest of the run
|
|
||||||
(400, Some("bad_media")) | (501, _) => {
|
|
||||||
turn_off(api);
|
|
||||||
Err(Fail::Next(format!("{ROUTE}: {}", said(&j, code))))
|
|
||||||
}
|
|
||||||
// not kept any more, too large to cut there, the cut failed: this call's clips are cut here
|
|
||||||
(404 | 413 | 502, _) | (400, Some("bad_source")) => Err(Fail::Next(format!("{ROUTE}: {}", said(&j, code)))),
|
|
||||||
_ => {
|
|
||||||
let a = api_answer(code, &j, ROUTE, own)?;
|
|
||||||
cache::put(&ckey, &a.answers);
|
|
||||||
Ok(a)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -16,13 +16,8 @@ pub fn dir() -> PathBuf {
|
|||||||
|
|
||||||
/// The request's hash.
|
/// The request's hash.
|
||||||
pub fn key(call: &Call) -> String {
|
pub fn key(call: &Call) -> String {
|
||||||
key_of(&call.clef_body())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The hash of a request's body as sent (an ask by reference names its video by hash and window: by_reference.rs).
|
|
||||||
pub fn key_of(body: &Value) -> String {
|
|
||||||
let mut h = Sha256::new();
|
let mut h = Sha256::new();
|
||||||
h.update(body.to_string().as_bytes());
|
h.update(call.clef_body().to_string().as_bytes());
|
||||||
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
|
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+10
-38
@@ -3,8 +3,6 @@
|
|||||||
//! The answers come back by question id with the call's cost. A transport is handed in, so tests replay recorded
|
//! The answers come back by question id with the call's cost. A transport is handed in, so tests replay recorded
|
||||||
//! answers and never spend.
|
//! answers and never spend.
|
||||||
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use base64::Engine as _;
|
use base64::Engine as _;
|
||||||
use base64::engine::general_purpose::STANDARD as B64;
|
use base64::engine::general_purpose::STANDARD as B64;
|
||||||
use raea_core_ask::{Question, limits};
|
use raea_core_ask::{Question, limits};
|
||||||
@@ -57,10 +55,6 @@ impl std::fmt::Display for Fail {
|
|||||||
/// An HTTP POST of JSON: its status and body. `Http` is the real one; a test hands in its own.
|
/// An HTTP POST of JSON: its status and body. `Http` is the real one; a test hands in its own.
|
||||||
pub trait Transport {
|
pub trait Transport {
|
||||||
fn post(&self, url: &str, bearer: Option<&str>, body: &Value) -> Result<(u16, Value), String>;
|
fn post(&self, url: &str, bearer: Option<&str>, body: &Value) -> Result<(u16, Value), String>;
|
||||||
/// A file's bytes PUT to a presigned URL (a video kept on raea-api to be asked about by reference): its status.
|
|
||||||
fn put_file(&self, url: &str, file: &Path) -> Result<u16, String> {
|
|
||||||
Err(format!("this transport doesn't send files ({url}, {})", file.display()))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Http;
|
pub struct Http;
|
||||||
@@ -77,25 +71,16 @@ impl Transport for Http {
|
|||||||
Err(e) => Err(format!("{url}: {e}")),
|
Err(e) => Err(format!("{url}: {e}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn put_file(&self, url: &str, file: &Path) -> Result<u16, String> {
|
|
||||||
let f = std::fs::File::open(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
|
||||||
let len = f.metadata().map_err(|e| format!("{}: {e}", file.display()))?.len();
|
|
||||||
// a Content-Length of its own, so the body isn't chunked: R2 and raea-api's own URLs take only a known length
|
|
||||||
let r = ureq::put(url).timeout(std::time::Duration::from_secs(600)).set("content-length", &len.to_string());
|
|
||||||
match r.send(f) {
|
|
||||||
Ok(res) => Ok(res.status()),
|
|
||||||
Err(ureq::Error::Status(code, _)) => Ok(code),
|
|
||||||
Err(e) => Err(format!("sending {}: {e}", file.display())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Call {
|
impl Call {
|
||||||
/// Why it can't be sent as it stands, or None: clef's counts and sizes, every question's own limits.
|
/// Why it can't be sent as it stands, or None: clef's counts and sizes, every question's own limits.
|
||||||
pub fn problem(&self) -> Option<String> {
|
pub fn problem(&self) -> Option<String> {
|
||||||
let m = &self.media;
|
let m = &self.media;
|
||||||
if let Some(p) = self.question_problem() {
|
if self.questions.is_empty() || self.questions.len() > limits::QUESTIONS {
|
||||||
|
return Some(format!("a call asks 1 to {} questions, not {}", limits::QUESTIONS, self.questions.len()));
|
||||||
|
}
|
||||||
|
if let Some(p) = self.questions.iter().find_map(limits::check) {
|
||||||
return Some(p);
|
return Some(p);
|
||||||
}
|
}
|
||||||
if m.stills.is_empty() && m.videos.is_empty() && m.sounds.is_empty() {
|
if m.stills.is_empty() && m.videos.is_empty() && m.sounds.is_empty() {
|
||||||
@@ -111,19 +96,11 @@ impl Call {
|
|||||||
(m.videos.iter().chain(&m.sounds).map(Vec::len).sum::<usize>() > limits::AV_BYTES).then(|| "the videos and sounds together are over 16 MiB".into())
|
(m.videos.iter().chain(&m.sounds).map(Vec::len).sum::<usize>() > limits::AV_BYTES).then(|| "the videos and sounds together are over 16 MiB".into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Why its questions can't be sent, or None: how many, and each one's own limits.
|
fn questions(&self) -> Value {
|
||||||
pub(crate) fn question_problem(&self) -> Option<String> {
|
|
||||||
if self.questions.is_empty() || self.questions.len() > limits::QUESTIONS {
|
|
||||||
return Some(format!("a call asks 1 to {} questions, not {}", limits::QUESTIONS, self.questions.len()));
|
|
||||||
}
|
|
||||||
self.questions.iter().find_map(limits::check)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn questions(&self) -> Value {
|
|
||||||
Value::Object(self.questions.iter().map(|q| (q.id.clone(), q.wire())).collect())
|
Value::Object(self.questions.iter().map(|q| (q.id.clone(), q.wire())).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn state(&self) -> String {
|
fn state(&self) -> String {
|
||||||
self.state.chars().take(limits::STATE_CHARS).collect()
|
self.state.chars().take(limits::STATE_CHARS).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,7 +128,7 @@ impl Call {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn said(body: &Value, code: u16) -> String {
|
fn said(body: &Value, code: u16) -> String {
|
||||||
body["message"].as_str().or(body["error"].as_str()).map(str::to_string).unwrap_or_else(|| format!("HTTP {code}"))
|
body["message"].as_str().or(body["error"].as_str()).map(str::to_string).unwrap_or_else(|| format!("HTTP {code}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,11 +151,6 @@ pub fn workers_ai(t: &dyn Transport, call: &Call, account: &str, token: &str) ->
|
|||||||
/// to the account's pool. `own_keys` says whether a spent pool may fall through to the person's own account.
|
/// to the account's pool. `own_keys` says whether a spent pool may fall through to the person's own account.
|
||||||
pub fn raea_api(t: &dyn Transport, call: &Call, url: &str, bearer: Option<&str>, route: &str, own_keys: bool) -> Result<Answered, Fail> {
|
pub fn raea_api(t: &dyn Transport, call: &Call, url: &str, bearer: Option<&str>, route: &str, own_keys: bool) -> Result<Answered, Fail> {
|
||||||
let (code, j) = t.post(url, bearer, &call.api_body()).map_err(|e| Fail::Next(format!("{route} didn't answer: {e}")))?;
|
let (code, j) = t.post(url, bearer, &call.api_body()).map_err(|e| Fail::Next(format!("{route} didn't answer: {e}")))?;
|
||||||
api_answer(code, &j, route, own_keys)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// raea-api's answer read: the answers, or why not (a spent pool stops a batch unless the person's own keys can go on).
|
|
||||||
pub(crate) fn api_answer(code: u16, j: &Value, route: &str, own_keys: bool) -> Result<Answered, Fail> {
|
|
||||||
match (code, j["error"].as_str()) {
|
match (code, j["error"].as_str()) {
|
||||||
(200..=299, _) => Ok(Answered {
|
(200..=299, _) => Ok(Answered {
|
||||||
answers: j["answers"].as_object().cloned().unwrap_or_default(),
|
answers: j["answers"].as_object().cloned().unwrap_or_default(),
|
||||||
@@ -187,8 +159,8 @@ pub(crate) fn api_answer(code: u16, j: &Value, route: &str, own_keys: bool) -> R
|
|||||||
route: route.into(),
|
route: route.into(),
|
||||||
pool_left: j["pool_left_usd"].as_f64(),
|
pool_left: j["pool_left_usd"].as_f64(),
|
||||||
}),
|
}),
|
||||||
(402, Some("pool_spent")) if !own_keys => Err(Fail::Spent(said(j, code))),
|
(402, Some("pool_spent")) if !own_keys => Err(Fail::Spent(said(&j, code))),
|
||||||
(400 | 413, _) => Err(Fail::Stop(said(j, code))),
|
(400 | 413, _) => Err(Fail::Stop(said(&j, code))),
|
||||||
_ => Err(Fail::Next(format!("{route}: {}", said(j, code)))),
|
_ => Err(Fail::Next(format!("{route}: {}", said(&j, code)))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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())
|
|
||||||
}
|
|
||||||
+1
-11
@@ -1,16 +1,12 @@
|
|||||||
//! The decision model, called one way for every caller (docs/ask.feature AK1b): a call's body and its answers
|
//! The decision model, called one way for every caller (docs/ask.feature AK1b): a call's body and its answers
|
||||||
//! (`client`), the media cut to what it reads (`media`), the route it takes, the person's plan first (`route`), and the
|
//! (`client`), the media cut to what it reads (`media`), the route it takes, the person's plan first (`route`), and the
|
||||||
//! answers kept by request (`cache`). `raea ask` (apps/ask) and `raea judge` call it. Through an agent key, a call about
|
//! answers kept by request (`cache`). `raea ask` (apps/ask) and `raea judge` call it.
|
||||||
//! a window of a video can name the video kept on raea-api instead of sending its clips (`by_reference`).
|
|
||||||
|
|
||||||
pub mod by_reference;
|
|
||||||
pub mod cache;
|
pub mod cache;
|
||||||
pub mod client;
|
pub mod client;
|
||||||
pub mod critic;
|
|
||||||
pub mod media;
|
pub mod media;
|
||||||
pub mod route;
|
pub mod route;
|
||||||
|
|
||||||
pub use by_reference::{ByReference, Source};
|
|
||||||
pub use client::{Answered, Call, Fail, Http, Media, Transport};
|
pub use client::{Answered, Call, Fail, Http, Media, Transport};
|
||||||
pub use route::Route;
|
pub use route::Route;
|
||||||
|
|
||||||
@@ -19,11 +15,5 @@ pub fn ask(call: &Call) -> Result<Answered, Fail> {
|
|||||||
route::ask(&Http, call, &route::open())
|
route::ask(&Http, call, &route::open())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One call by reference (a window of a video kept on raea-api), by the routes open on this computer. `Fail::Next`
|
|
||||||
/// means it can't go that way: cut the clips here and `ask`.
|
|
||||||
pub fn ask_by_reference(call: &ByReference) -> Result<Answered, Fail> {
|
|
||||||
by_reference::ask(&Http, call, &route::open())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
@@ -99,68 +99,6 @@ pub fn video(file: &Path, from: f64, to: Option<f64>) -> Result<Vec<u8>, String>
|
|||||||
out.read()
|
out.read()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Windows a pass reads together: those that overlap or sit within this many seconds of each other. Further apart, each
|
|
||||||
/// stretch is its own pass, so two short windows a minute apart don't decode the minute between them.
|
|
||||||
const STRETCH_GAP: f64 = 2.0;
|
|
||||||
|
|
||||||
/// Each window as seconds from and to, held to 60 s as `video` holds it.
|
|
||||||
fn spans(windows: &[(f64, Option<f64>)]) -> Vec<(f64, f64)> {
|
|
||||||
windows.iter().map(|&(from, to)| (from, from + to.map(|t| (t - from).max(0.1)).unwrap_or(limits::VIDEO_SECONDS).min(limits::VIDEO_SECONDS))).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The windows (by index) gathered into stretches read in one pass each.
|
|
||||||
fn stretches(spans: &[(f64, f64)]) -> Vec<Vec<usize>> {
|
|
||||||
let mut order: Vec<usize> = (0..spans.len()).collect();
|
|
||||||
order.sort_by(|a, b| spans[*a].0.total_cmp(&spans[*b].0));
|
|
||||||
let mut out: Vec<Vec<usize>> = Vec::new();
|
|
||||||
let mut end = f64::NEG_INFINITY;
|
|
||||||
for i in order {
|
|
||||||
match out.last_mut() {
|
|
||||||
Some(s) if spans[i].0 <= end + STRETCH_GAP => s.push(i),
|
|
||||||
_ => out.push(vec![i]),
|
|
||||||
}
|
|
||||||
end = if out.last().is_some_and(|s| s.len() > 1) { end.max(spans[i].1) } else { spans[i].1 };
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Several windows of one file's picture, as `video` cuts each (480 px wide, 10 frames a second, no sound), in the
|
|
||||||
/// windows' order: each stretch of nearby windows decoded once, scaled once and split to each window's own encode,
|
|
||||||
/// rather than decoded again for every window (12-04: a raea cloud box asked 18 windows of six cuts, each decoded on its
|
|
||||||
/// own).
|
|
||||||
pub fn videos(file: &Path, windows: &[(f64, Option<f64>)]) -> Result<Vec<Vec<u8>>, String> {
|
|
||||||
let spans = spans(windows);
|
|
||||||
let mut out: Vec<Option<Vec<u8>>> = vec![None; windows.len()];
|
|
||||||
for s in stretches(&spans) {
|
|
||||||
if let &[i] = s.as_slice() {
|
|
||||||
out[i] = Some(video(file, windows[i].0, windows[i].1)?);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let start = s.iter().map(|&i| spans[i].0).fold(f64::INFINITY, f64::min);
|
|
||||||
let end = s.iter().map(|&i| spans[i].1).fold(f64::NEG_INFINITY, f64::max);
|
|
||||||
let outs: Vec<Temp> = s.iter().map(|_| Temp::new("mp4")).collect();
|
|
||||||
let mut graph = format!("[0:v]scale=480:-2,fps=10,split={}", s.len());
|
|
||||||
for n in 0..s.len() {
|
|
||||||
graph += &format!("[s{n}]");
|
|
||||||
}
|
|
||||||
for (n, &i) in s.iter().enumerate() {
|
|
||||||
graph += &format!(";[s{n}]trim=start={:.3}:end={:.3},setpts=PTS-STARTPTS[v{n}]", spans[i].0 - start, spans[i].1 - start);
|
|
||||||
}
|
|
||||||
let mut c = tool("ffmpeg", file)?;
|
|
||||||
c.args(["-nostdin", "-v", "error", "-y", "-ss", &format!("{start:.3}"), "-t", &format!("{:.3}", end - start)]).arg("-i").arg(file);
|
|
||||||
c.args(["-filter_complex", &graph]);
|
|
||||||
let enc = small_h264()?;
|
|
||||||
for (n, t) in outs.iter().enumerate() {
|
|
||||||
c.args(["-map", &format!("[v{n}]"), "-an"]).args(&enc).args(["-movflags", "+faststart"]).arg(&t.0);
|
|
||||||
}
|
|
||||||
run(c, "cutting the pictures")?;
|
|
||||||
for (&i, t) in s.iter().zip(&outs) {
|
|
||||||
out[i] = Some(t.read()?);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(out.into_iter().map(Option::unwrap_or_default).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The sound from `from` to `to` (at most 300 s), mono 16 kHz MP3.
|
/// The sound from `from` to `to` (at most 300 s), mono 16 kHz MP3.
|
||||||
pub fn sound(file: &Path, from: f64, to: Option<f64>) -> Result<Vec<u8>, String> {
|
pub fn sound(file: &Path, from: f64, to: Option<f64>) -> Result<Vec<u8>, String> {
|
||||||
let out = Temp::new("mp3");
|
let out = Temp::new("mp3");
|
||||||
@@ -194,14 +132,4 @@ mod tests {
|
|||||||
assert_eq!(window(0.0, None, 60.0), ["-ss", "0.000", "-t", "60.000"]);
|
assert_eq!(window(0.0, None, 60.0), ["-ss", "0.000", "-t", "60.000"]);
|
||||||
assert_eq!(window(0.0, Some(400.0), 300.0)[3], "300.000");
|
assert_eq!(window(0.0, Some(400.0), 300.0)[3], "300.000");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nearby_windows_are_read_in_one_pass_and_far_ones_apart() {
|
|
||||||
// a cut's beats, one after another, and a window to its end; one more a minute later
|
|
||||||
let w = [(0.0, Some(3.5)), (3.5, Some(7.2)), (7.2, Some(12.0)), (5.0, None), (90.0, Some(94.0))];
|
|
||||||
let s = spans(&w);
|
|
||||||
assert_eq!(s[3], (5.0, 65.0), "a window to the end is held to 60 s");
|
|
||||||
assert_eq!(stretches(&s), [vec![0, 1, 3, 2], vec![4]]);
|
|
||||||
assert_eq!(stretches(&spans(&[(0.0, Some(1.0)), (2.5, Some(3.0)), (6.0, Some(7.0))])), [vec![0, 1], vec![2]]);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -106,111 +106,3 @@ fn workers_ai_gets_data_urls_and_raea_api_bare_base64() {
|
|||||||
assert_eq!(c.api_body()["audio"][0], "AQ==");
|
assert_eq!(c.api_body()["audio"][0], "AQ==");
|
||||||
assert_eq!(clef["questions"]["q"]["type"], "noul");
|
assert_eq!(clef["questions"]["q"]["type"], "noul");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- asking by reference (by_reference.rs): a video kept on raea-api once, each window asked by its hash
|
|
||||||
|
|
||||||
use crate::by_reference::{self, ByReference, Source};
|
|
||||||
|
|
||||||
/// Canned replies by URL ending, every URL asked (a file sent as "PUT url") and every body sent.
|
|
||||||
struct Api {
|
|
||||||
replies: Vec<(&'static str, u16, Value)>,
|
|
||||||
seen: RefCell<Vec<String>>,
|
|
||||||
bodies: RefCell<Vec<Value>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Api {
|
|
||||||
fn new(replies: Vec<(&'static str, u16, Value)>) -> Api {
|
|
||||||
Api { replies, seen: RefCell::default(), bodies: RefCell::default() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Transport for Api {
|
|
||||||
fn post(&self, url: &str, _bearer: Option<&str>, body: &Value) -> Result<(u16, Value), String> {
|
|
||||||
self.seen.borrow_mut().push(url.to_string());
|
|
||||||
self.bodies.borrow_mut().push(body.clone());
|
|
||||||
self.replies.iter().find(|(end, ..)| url.ends_with(end)).map(|(_, c, j)| (*c, j.clone())).ok_or_else(|| format!("{url}: connection refused"))
|
|
||||||
}
|
|
||||||
fn put_file(&self, url: &str, file: &std::path::Path) -> Result<u16, String> {
|
|
||||||
self.seen.borrow_mut().push(format!("PUT {url}"));
|
|
||||||
std::fs::metadata(file).map(|_| 200).map_err(|e| e.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A "video" unique to its test (the files kept are remembered by path), and an agent key's route to its own raea-api
|
|
||||||
/// (a raea-api that turns asking by reference off does so for itself alone).
|
|
||||||
fn video(test: &str) -> (std::path::PathBuf, Vec<Route>) {
|
|
||||||
setup();
|
|
||||||
let f = std::env::temp_dir().join(format!("raea-clef-ref-{}-{test}.mp4", std::process::id()));
|
|
||||||
std::fs::write(&f, format!("not really a video: {test}")).unwrap();
|
|
||||||
(f, vec![Route::Agent { api: format!("https://{test}.api.test"), key: "k".into() }])
|
|
||||||
}
|
|
||||||
|
|
||||||
fn by_ref(file: &std::path::Path, from: f64, to: Option<f64>) -> ByReference {
|
|
||||||
let source = Source { file: file.to_path_buf(), from, to, sound: true };
|
|
||||||
ByReference { state: format!("a test piece: {}", file.display()), questions: vec![Question::plain("q", "Is the product on screen?")], source }
|
|
||||||
}
|
|
||||||
|
|
||||||
const BY_REF: &str = r#"{"answers": {"q": {"noul": 0.4}}, "cost_usd": 0.001, "cached": false, "pool_left_usd": 1.5}"#;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_video_goes_up_once_and_each_window_is_asked_by_its_hash() {
|
|
||||||
let (file, routes) = video("once");
|
|
||||||
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": false, "url": "https://r2.test/put"})), ("/v1/clef/ask", 200, serde_json::from_str(BY_REF).unwrap())]);
|
|
||||||
let a = by_reference::ask(&api, &by_ref(&file, 1.0, Some(3.5)), &routes).unwrap();
|
|
||||||
assert_eq!((a.answers["q"]["noul"].as_f64(), a.route.as_str()), (Some(0.4), "your raea plan, with an agent key (cut on raea-api)"));
|
|
||||||
by_reference::ask(&api, &by_ref(&file, 3.5, None), &routes).unwrap();
|
|
||||||
let seen = api.seen.borrow();
|
|
||||||
assert_eq!(seen.iter().map(|u| u.rsplit('/').next().unwrap()).collect::<Vec<_>>(), ["media", "put", "ask", "ask"], "{seen:?}");
|
|
||||||
let (sha, size) = by_reference::hashed(&file).unwrap();
|
|
||||||
let bodies = api.bodies.borrow();
|
|
||||||
assert_eq!(bodies[0], json!({"sha256": sha, "size": size}));
|
|
||||||
assert_eq!(bodies[1]["source"], json!({"sha256": sha, "from": 1.0, "to": 3.5, "sound": true}));
|
|
||||||
assert_eq!(bodies[2]["source"], json!({"sha256": sha, "from": 3.5, "sound": true}), "a window to the end names no end");
|
|
||||||
assert!(bodies[1].get("videos").is_none() && bodies[1]["questions"]["q"]["type"] == "noul");
|
|
||||||
// the same call again comes from the cache
|
|
||||||
let again = by_reference::ask(&api, &by_ref(&file, 1.0, Some(3.5)), &routes).unwrap();
|
|
||||||
assert!(again.cached && api.seen.borrow().len() == 4);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_video_already_there_isnt_sent() {
|
|
||||||
let (file, routes) = video("there");
|
|
||||||
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", 200, serde_json::from_str(BY_REF).unwrap())]);
|
|
||||||
by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes).unwrap();
|
|
||||||
assert!(!api.seen.borrow().iter().any(|u| u.starts_with("PUT")), "{:?}", api.seen.borrow());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_older_raea_api_turns_it_off_and_the_clips_are_cut_here() {
|
|
||||||
let (file, routes) = video("older");
|
|
||||||
let api = Api::new(vec![("/v1/clef/media", 403, json!({"error": "agent_scope", "message": "an agent key reaches ..."}))]);
|
|
||||||
assert!(by_reference::api(&routes).is_some());
|
|
||||||
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes), Err(crate::Fail::Next(_))));
|
|
||||||
assert!(by_reference::off(&routes), "the rest of the run cuts its own clips");
|
|
||||||
// one that keeps videos but reads no source (bad_media) or can't cut (501) does the same
|
|
||||||
for (test, code, error) in [("no-source", 400, "bad_media"), ("no-cutter", 501, "cut_unavailable")] {
|
|
||||||
let (file, routes) = video(test);
|
|
||||||
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", code, json!({"error": error, "message": "no"}))]);
|
|
||||||
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes), Err(crate::Fail::Next(_))), "{test}");
|
|
||||||
assert!(by_reference::off(&routes), "{test}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_window_raea_api_cant_cut_is_cut_here_and_the_rest_still_go_by_reference() {
|
|
||||||
let (file, routes) = video("too-large");
|
|
||||||
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", 413, json!({"error": "media_too_large", "message": "over 16 MB"}))]);
|
|
||||||
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(60.0)), &routes), Err(crate::Fail::Next(m)) if m.contains("16 MB")));
|
|
||||||
assert!(!by_reference::off(&routes));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_spent_pool_stops_and_only_an_agent_key_asks_by_reference() {
|
|
||||||
let (file, routes) = video("spent");
|
|
||||||
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", 402, json!({"error": "pool_spent", "message": "used up"}))]);
|
|
||||||
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes), Err(crate::Fail::Spent(_))));
|
|
||||||
let app_first = [Route::App("http://127.0.0.1:9".into()), routes[0].clone()];
|
|
||||||
let none = Api::new(vec![]);
|
|
||||||
assert!(matches!(by_reference::ask(&none, &by_ref(&file, 0.0, Some(2.0)), &app_first), Err(crate::Fail::Next(_))));
|
|
||||||
assert!(none.seen.borrow().is_empty(), "the app's route cuts its own clips");
|
|
||||||
}
|
|
||||||
@@ -2,6 +2,3 @@ node_modules
|
|||||||
deploy
|
deploy
|
||||||
test
|
test
|
||||||
README.md
|
README.md
|
||||||
# a box image (deploy/fly/Dockerfile) takes these two from deploy/
|
|
||||||
!deploy/git
|
|
||||||
!deploy/fly/start.sh
|
|
||||||
@@ -1,76 +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
|
|
||||||
# raea's SDK files fixed after the release the image installs (image/sdk-overlay, by their path under share/raea/sdk),
|
|
||||||
# each only while the installed file still has the fault, so a release with the fix keeps its own. 12-03: 0.1.17-rc4's
|
|
||||||
# goal.ts named-imports spawn, which raea's runtime hasn't got, and every raea goal check on a box died (raea #329)
|
|
||||||
RUN f=/opt/raea/share/raea/sdk/goal/src/packs/goal.ts; \
|
|
||||||
if grep -q 'import { spawn } from "node:child_process"' "$f"; then cp image/sdk-overlay/goal/src/packs/goal.ts "$f" && echo "overlay: goal.ts"; fi
|
|
||||||
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
|
SCALEDOWN = 2
|
||||||
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
|
# 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
|
# 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
|
# 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
|
||||||
# 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
|
CPU_SCALEDOWN = 60
|
||||||
# those started cold at 60 (Shane: "no workflow should take more than 20 minutes")
|
|
||||||
CPU_SCALEDOWN = 180
|
|
||||||
|
|
||||||
|
|
||||||
def on(gpus, job):
|
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
|
# 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)
|
# (raea, the composition, each clip read on from its last keyframe) for 10 s of frames (11-30)
|
||||||
CPU_PARTS = 2
|
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
|
# 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
|
# 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
|
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
|
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):
|
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,
|
"""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
|
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"))
|
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)
|
flat = bool(video and cpu_render and not opts.get("gpu") and (p.get("manifest") or {}).get("has3d") is False)
|
||||||
r0 = None
|
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))
|
first = list(range(at0, at0 + n0))
|
||||||
if flat and n0:
|
if flat and n0:
|
||||||
r0 = bill.add(waited(cpu_render, log, id, rest, first, at0, video=video))
|
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"]:
|
if r0 and r0["code"]:
|
||||||
log(r0["out"], err=True)
|
log(r0["out"], err=True)
|
||||||
return r0["code"]
|
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
|
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)
|
# 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)
|
cold_s = start_s if flat else max(start_s, p["s"] - frame_s)
|
||||||
if quick:
|
k = gpus_for(left, frame_s, cold_s, most)
|
||||||
k, m = (max(1, min(most, -(-left // FLAT_PART))) if left else 0), 1
|
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
|
||||||
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)
|
|
||||||
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)
|
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 ""
|
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)"
|
on = f"{k} {kind}s" if not flat else f"{k} containers with no GPU (no 3D in it)"
|
||||||
if r0:
|
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")
|
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:
|
else:
|
||||||
log("raea farm: nothing to draw: every frame is in a run kept from an earlier render")
|
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"]:
|
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 []
|
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 []
|
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
|
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:
|
if again:
|
||||||
# what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it 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)")
|
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)
|
code = spread(gpu_render, gpu_kind, again, log, "frames", bill, opts["gpus"], got)
|
||||||
if code:
|
if code:
|
||||||
return 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
|
# 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")
|
# containers' frames (11-25: "the volume wouldn't reload ... cwd of raea render")
|
||||||
if video:
|
if video:
|
||||||
t0 = time.time()
|
|
||||||
t.join()
|
t.join()
|
||||||
took("the sound", t0)
|
|
||||||
t0 = time.time()
|
|
||||||
reload() # the other containers' frames
|
reload() # the other containers' frames
|
||||||
took("reloading the volume", t0)
|
|
||||||
frames = f"{os.path.dirname(work)}/frames"
|
frames = f"{os.path.dirname(work)}/frames"
|
||||||
dest = os.path.join(work, out)
|
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)
|
# (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):
|
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)
|
farm_keys.put(store, keyed["keys"], got, frames)
|
||||||
took("keeping the runs drawn", t0)
|
|
||||||
t0 = time.time()
|
|
||||||
got += farm_keys.take(hits, frames)
|
got += farm_keys.take(hits, frames)
|
||||||
took(f"bringing {len(hits)} kept runs", t0)
|
|
||||||
if manifest and p.get("manifest"):
|
if manifest and p.get("manifest"):
|
||||||
path = os.path.join(work, manifest)
|
path = os.path.join(work, manifest)
|
||||||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||||
|
|||||||
@@ -1,312 +0,0 @@
|
|||||||
// The rule packs (MK29, MK38; Rust's goal gates until 11-29, now here alone): any goal held to its rules,
|
|
||||||
// from what's on disk and what a fresh critic said, never from the agent that did the work (11-26, Shane: "it can't
|
|
||||||
// stop unless all the goals pass").
|
|
||||||
// run the command exits 0 in the brief's folder, within its timeout (300 s by default), run again each time
|
|
||||||
// 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}}}.
|
|
||||||
// a namespace import: raea's own runtime (engine/native/src/node.js) has spawnSync and no spawn, and a named import of
|
|
||||||
// spawn failed the whole module there, so every `raea goal check` on a box died before it read a file (12-03, raea
|
|
||||||
// 0.1.17-rc4: no StreetTalk cut could publish)
|
|
||||||
import * as cp from "node:child_process"
|
|
||||||
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
|
||||||
import path from "node:path"
|
|
||||||
import { check, found } from "raea/check"
|
|
||||||
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
|
|
||||||
import type { Job } from "../facts.ts"
|
|
||||||
import { RAEA } from "../media.ts"
|
|
||||||
|
|
||||||
/** where a goal's critic verdict is kept, relative to the brief */
|
|
||||||
export const verdictPath = (g: Contract) => `review/judge/${nameOf(g)}.json`
|
|
||||||
export const TIMEOUT = 300
|
|
||||||
/** folders that aren't the work: what the job writes about itself, and what tools keep */
|
|
||||||
const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"])
|
|
||||||
|
|
||||||
/** what a check keeps beside a file it read (its report, its words, its scene): a reading of the work, not a change
|
|
||||||
* to it. A done check that heard a cut's words wrote them beside it, and the critic's verdict of a minute before read
|
|
||||||
* as older than the work (12-01) */
|
|
||||||
const READING = /\.(check|words|scene|floor|montage)\.json$/
|
|
||||||
|
|
||||||
/** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */
|
|
||||||
export function newest(dir: string): number | null {
|
|
||||||
let best: number | null = null
|
|
||||||
const stack = [dir]
|
|
||||||
let seen = 0
|
|
||||||
while (stack.length) {
|
|
||||||
const d = stack.pop()!
|
|
||||||
let names: string[] = []
|
|
||||||
try {
|
|
||||||
names = readdirSync(d)
|
|
||||||
} catch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for (const name of names) {
|
|
||||||
if (++seen > 20_000) return best
|
|
||||||
const p = path.join(d, name)
|
|
||||||
let st
|
|
||||||
try {
|
|
||||||
st = statSync(p)
|
|
||||||
} catch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (st.isDirectory()) {
|
|
||||||
if (!(d === dir && NOT_WORK.has(name)) && name !== "node_modules" && name !== ".git") stack.push(p)
|
|
||||||
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return best
|
|
||||||
}
|
|
||||||
|
|
||||||
type Verdict = { at: number; by: string; goal?: string; rules: Record<string, { pass: boolean; why: string } | undefined> }
|
|
||||||
export function verdict(dir: string, g: Contract): Verdict | null {
|
|
||||||
try {
|
|
||||||
return JSON.parse(readFileSync(path.join(dir, verdictPath(g)), "utf8")) as Verdict
|
|
||||||
} catch {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const goalOf = (j: Job): Contract | null => j.contract
|
|
||||||
|
|
||||||
export const runPack = check<Job>({ id: "run", text: "each command rule exits 0", over: "job", at: ["done"] }, async (j) => {
|
|
||||||
for (const r of goalOf(j)?.rules ?? []) {
|
|
||||||
if (!r.run) continue
|
|
||||||
const { ok, said } = await j.run(r.run, r.timeout ?? TIMEOUT)
|
|
||||||
if (!ok) found({ says: `${r.id}: \`${r.run}\` ${said}`, about: [r.id] })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
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!)
|
|
||||||
// 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)
|
|
||||||
for (const r of says) {
|
|
||||||
const one = v?.rules?.[r.id]
|
|
||||||
const fix = NO_CRITIC
|
|
||||||
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 })
|
|
||||||
else if (!one.pass) found({ says: `${r.id}: a fresh critic found it not true yet: ${one.why}`, about: [r.id] })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
/** 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}`)
|
|
||||||
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": "..."}}}`
|
|
||||||
}
|
|
||||||
|
|
||||||
/** the verdict: the object around the text's last "rules" key (a critic may think aloud, or quote the shape, first) */
|
|
||||||
export function lastVerdict(text: string): Verdict | null {
|
|
||||||
const key = text.lastIndexOf('"rules"')
|
|
||||||
if (key < 0) return null
|
|
||||||
for (let open = text.lastIndexOf("{", key); open >= 0; open = text.lastIndexOf("{", open - 1)) {
|
|
||||||
let depth = 0
|
|
||||||
let inStr = false
|
|
||||||
for (let i = open; i < text.length; i++) {
|
|
||||||
const ch = text[i]
|
|
||||||
if (inStr) {
|
|
||||||
if (ch === "\\") i++
|
|
||||||
else if (ch === '"') inStr = false
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (ch === '"') inStr = true
|
|
||||||
else if (ch === "{") depth++
|
|
||||||
else if (ch === "}" && --depth === 0) {
|
|
||||||
try {
|
|
||||||
const v = JSON.parse(text.slice(open, i + 1))
|
|
||||||
if (v && typeof v.rules === "object") return v
|
|
||||||
} catch {}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
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 */
|
|
||||||
function made(dir: string): string[] {
|
|
||||||
const out: { f: string; at: number }[] = []
|
|
||||||
const walk = (d: string) => {
|
|
||||||
for (const e of existsSync(d) ? readdirSync(d, { withFileTypes: true }) : []) {
|
|
||||||
const f = path.join(d, e.name)
|
|
||||||
if (e.isDirectory()) walk(f)
|
|
||||||
else if (VIDEO.test(e.name)) out.push({ f, at: statSync(f).mtimeMs })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
walk(path.join(dir, "out"))
|
|
||||||
return out.sort((x, y) => y.at - x.at).map((x) => path.relative(dir, x.f))
|
|
||||||
}
|
|
||||||
/** clef-omni as the critic (`raea ask`, paid as ask is): it watches and hears a piece, and reads no folder. A rule is
|
|
||||||
* 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"]> {
|
|
||||||
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)
|
|
||||||
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) {
|
|
||||||
const key = [file, w?.[1], w?.[2]].join("\u001f")
|
|
||||||
const at = groups.get(key) ?? { file, from: w?.[1], to: w?.[2], rules: [] }
|
|
||||||
at.rules.push(r)
|
|
||||||
groups.set(key, at)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const got = new Map<string, { pass: boolean; why: string }[]>()
|
|
||||||
const list = [...groups.values()]
|
|
||||||
const heard = ask === askClef && !asyncSpawn()
|
|
||||||
? askClefMany(dir, list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to })))
|
|
||||||
: 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]
|
|
||||||
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) {
|
|
||||||
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: !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[]>
|
|
||||||
const askArgs = (file: string, says: string[], from?: string, to?: string) => ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])]
|
|
||||||
const rowsOf = (out: string) => out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
|
||||||
/** whether this runtime has an async spawn (raea's own has only spawnSync) */
|
|
||||||
const asyncSpawn = () => typeof (cp as { spawn?: unknown }).spawn === "function"
|
|
||||||
/** every ask at once where there's no async spawn (raea's runtime): one shell runs them CLEF_AT_ONCE at a time, each
|
|
||||||
* into its own file under review/ (12-04, StreetTalk round 18: asked one after another, a stop's 18 beats took 7.7 of
|
|
||||||
* its 10.5 minutes) */
|
|
||||||
export function askClefMany(dir: string, jobs: { file: string; says: string[]; from?: string; to?: string }[]): Answer[][] {
|
|
||||||
if (!jobs.length) return []
|
|
||||||
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
|
|
||||||
mkdirSync(tmp, { recursive: true })
|
|
||||||
const sq = (t: string) => `'${t.replace(/'/g, `'\\''`)}'`
|
|
||||||
const lines = jobs.map((k, i) => `${[RAEA, ...askArgs(k.file, k.says, k.from, k.to)].map(sq).join(" ")} > ${sq(`${tmp}/${i}.out`)} 2> ${sq(`${tmp}/${i}.err`)} &${(i + 1) % CLEF_AT_ONCE === 0 ? "\nwait" : ""}`)
|
|
||||||
try {
|
|
||||||
const r = cp.spawnSync("sh", ["-c", [...lines, "wait"].join("\n")], { cwd: dir, encoding: "utf8" }) as { error?: Error }
|
|
||||||
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
|
|
||||||
const read = (f: string) => (existsSync(f) ? String(readFileSync(f, "utf8")) : "")
|
|
||||||
return jobs.map((k, i) => {
|
|
||||||
const rows = rowsOf(read(`${tmp}/${i}.out`))
|
|
||||||
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${read(`${tmp}/${i}.err`).trim().slice(-300) || read(`${tmp}/${i}.out`).trim().slice(-300)}`)
|
|
||||||
return rows
|
|
||||||
})
|
|
||||||
} finally {
|
|
||||||
rmSync(tmp, { recursive: true, force: true })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/** `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[]> {
|
|
||||||
const args = askArgs(file, says, from, to)
|
|
||||||
// where there's no async spawn (raea's runtime), one at a time (clefVerdict asks them all at once: askClefMany)
|
|
||||||
if (!asyncSpawn()) {
|
|
||||||
const r = cp.spawnSync(RAEA, args, { cwd: dir, encoding: "utf8" }) as { stdout?: string; stderr?: string; error?: Error }
|
|
||||||
if (r.error) return Promise.reject(new Error(`couldn't run raea ask: ${r.error.message}`))
|
|
||||||
const rows = rowsOf(String(r.stdout ?? ""))
|
|
||||||
if (rows.length !== says.length) return Promise.reject(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 Promise.resolve(rows)
|
|
||||||
}
|
|
||||||
return new Promise((ok, no) => {
|
|
||||||
const c = cp.spawn(RAEA, args, { 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 = rowsOf(out)
|
|
||||||
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)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 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`)
|
|
||||||
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
|
|
||||||
}
|
|
||||||
function keep(g: Contract, dir: string, out: Verdict): Verdict {
|
|
||||||
const file = path.join(dir, verdictPath(g))
|
|
||||||
mkdirSync(path.dirname(file), { recursive: true })
|
|
||||||
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
export const hasVerdict = (dir: string, g: Contract) => existsSync(path.join(dir, verdictPath(g)))
|
|
||||||
@@ -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}
|
// 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)
|
// 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 /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,
|
// 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
|
// 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
|
// 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 { claudeStopHook, jobsOf, markedEnd, sessionIn, watchEnd, watchTurnEnd } from "./turn-end.ts"
|
||||||
import { execFile, spawn } from "node:child_process"
|
import { execFile, spawn } from "node:child_process"
|
||||||
import { timingSafeEqual } from "node:crypto"
|
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 { createServer, type IncomingMessage, type ServerResponse } from "node:http"
|
||||||
import path from "node:path"
|
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 { WebSocketServer } from "ws"
|
||||||
import { installed, spawnFor } from "./agents.ts"
|
import { installed, spawnFor } from "./agents.ts"
|
||||||
import { guard } from "./memguard.ts"
|
import { guard } from "./memguard.ts"
|
||||||
@@ -56,7 +50,6 @@ import { checkGoogle, finishGoogleSignIn, screenPort, startGoogleSignIn, unpackC
|
|||||||
import { connect as tcp } from "node:net"
|
import { connect as tcp } from "node:net"
|
||||||
import { login, loginState } from "./login.ts"
|
import { login, loginState } from "./login.ts"
|
||||||
import { Outside, resolve, WORK } from "./workspace.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 ?? ""
|
const TOKEN = process.env.RAEA_CLOUD_TOKEN ?? ""
|
||||||
if (TOKEN.length < 16) {
|
if (TOKEN.length < 16) {
|
||||||
@@ -177,6 +170,24 @@ async function body(req: IncomingMessage): Promise<Buffer> {
|
|||||||
return Buffer.concat(parts)
|
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
|
/** 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
|
* 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
|
* 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 server = createServer(async (req, res) => {
|
||||||
const url = new URL(req.url ?? "/", "http://raea-cloud")
|
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")
|
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)
|
if (!authorized(req, url)) return json(res, { error: "unauthorized" }, 401)
|
||||||
try {
|
try {
|
||||||
if (url.pathname === "/v1/health" && req.method === "GET") {
|
if (url.pathname === "/v1/health" && req.method === "GET") {
|
||||||
@@ -283,7 +278,7 @@ const server = createServer(async (req, res) => {
|
|||||||
running: running.size,
|
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/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/shell" && req.method === "POST") return await shell(req, res)
|
||||||
if (url.pathname === "/v1/jobs" && req.method === "POST") {
|
if (url.pathname === "/v1/jobs" && req.method === "POST") {
|
||||||
@@ -375,10 +370,7 @@ server.on("upgrade", (req, socket, head) => {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`)
|
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 }
|
const env = 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 }
|
|
||||||
wss.handleUpgrade(req, socket, head, (ws) => {
|
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
|
// 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)
|
// 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)
|
running.add(child)
|
||||||
agentSockets.add(ws)
|
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
|
// 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
|
// 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
|
// 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()
|
ws.terminate()
|
||||||
stopAll()
|
stopAll()
|
||||||
}, Math.min(60_000, IDLE_AGENT_MS / 2))
|
}, 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)))
|
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
|
// 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)
|
// 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")
|
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" } }))
|
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 () => {
|
server.listen(PORT, async () => {
|
||||||
await versionKnown
|
await versionKnown
|
||||||
const d = device(childEnv())
|
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`)
|
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 {
|
export class RaeaCloud {
|
||||||
readonly url: string
|
readonly url: string
|
||||||
private token: string
|
private token: string
|
||||||
@@ -112,8 +103,7 @@ export class RaeaCloud {
|
|||||||
constructor(o: { url: string; token: string; spriteToken?: string }) {
|
constructor(o: { url: string; token: string; spriteToken?: string }) {
|
||||||
this.url = o.url.replace(/\/+$/, "")
|
this.url = o.url.replace(/\/+$/, "")
|
||||||
this.token = o.token
|
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 = o.spriteToken
|
||||||
this.spriteToken = onSprite(this.url) ? o.spriteToken : undefined
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A request to the box, its response as it comes, for a caller that reads the body itself (a stream of a file
|
/** 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):
|
def starmap(self, calls, order_outputs=False, return_exceptions=True):
|
||||||
return [self.remote(*c) for c in calls]
|
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 = []
|
lines = []
|
||||||
log = lambda t, err=False: lines.append(t)
|
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")
|
ok("a GPU run that timed out fails the job instead of being waited on forever")
|
||||||
|
|
||||||
shutil.rmtree(root)
|
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 assert from "node:assert/strict"
|
||||||
import { execSync } from "node:child_process"
|
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 os from "node:os"
|
||||||
import path from "node:path"
|
import path from "node:path"
|
||||||
import { parseSummary, pick } from "../server/gpu.ts"
|
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 { 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 { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
|
||||||
import { localSources } from "../server/media.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:
|
const L4 = `Devices:
|
||||||
========
|
========
|
||||||
@@ -215,51 +213,3 @@ console.log("units: ok")
|
|||||||
assert.equal(localSources({}, [], "/x"), 0)
|
assert.equal(localSources({}, [], "/x"), 0)
|
||||||
console.log("ok localSources")
|
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")
|
|
||||||
}
|
|
||||||
+45
-191
@@ -5,11 +5,8 @@
|
|||||||
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
|
// 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)
|
// (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}}}.
|
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
|
||||||
// a namespace import: raea's own runtime (engine/native/src/node.js) has spawnSync and no spawn, and a named import of
|
import { spawnSync } from "node:child_process"
|
||||||
// spawn failed the whole module there, so every `raea goal check` on a box died before it read a file (12-03, raea
|
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||||
// 0.1.17-rc4: no StreetTalk cut could publish)
|
|
||||||
import * as cp from "node:child_process"
|
|
||||||
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
|
||||||
import path from "node:path"
|
import path from "node:path"
|
||||||
import { check, found } from "raea/check"
|
import { check, found } from "raea/check"
|
||||||
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
|
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
|
||||||
@@ -79,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) => {
|
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)
|
const says = saysOf(goalOf(j) ?? null)
|
||||||
if (!says.length) return
|
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
|
// 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))
|
const fresh = !!v && (changed === null || v.at >= Math.floor(changed / 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)
|
|
||||||
for (const r of says) {
|
for (const r of says) {
|
||||||
const one = v?.rules?.[r.id]
|
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 })
|
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 (!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 })
|
else if (!fresh) found({ says: `${r.id}: the work changed after the critic judged it`, about: [r.id], fix })
|
||||||
@@ -104,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 */
|
/** 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 {
|
export function prompt(g: Contract, dir: string): string {
|
||||||
const rules = only.map((r) => `- ${r.id}: ${r.says}`)
|
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": "..."}}}`
|
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": "..."}}}`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,15 +124,11 @@ export function lastVerdict(text: string): Verdict | null {
|
|||||||
return 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
|
export const BY = ["claude", "kimi", "clef"] as const
|
||||||
* (a file it names, or the videos under out/) by Clef-Omni; any other by a fresh session of the agent this project
|
/** the critic when none is named: clef where an agent key is set (a raea cloud box, whose shell has no Claude
|
||||||
* runs on, which the host that started the agent offers as RAEA_JUDGE_URL (raea cloud's box, critic.ts; the raea app) */
|
* sign-in: 12-01, every judging there answered "Not logged in"), else Claude Code */
|
||||||
const criticUrl = () => process.env.RAEA_JUDGE_URL || null
|
export const critic = () => (process.env.RAEA_AGENT_KEY && process.env.RAEA_API ? "clef" : "claude")
|
||||||
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)
|
|
||||||
}
|
|
||||||
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
|
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
|
||||||
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
|
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
|
||||||
/** the videos under out/, newest first */
|
/** the videos under out/, newest first */
|
||||||
@@ -165,34 +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
|
* 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 */
|
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
|
||||||
const CLEF_PIECES = 12
|
const CLEF_PIECES = 12
|
||||||
/** the pieces a rule is about: the files it names that are on disk, else the newest videos under out/ */
|
export function clefVerdict(g: Contract, dir: string, ask = askClef): Verdict["rules"] {
|
||||||
function piecesOf(r: Said, dir: string): string[] {
|
const all = made(dir)
|
||||||
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 calls `raea ask` makes at once: 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); six `raea ask`s at once was a raea cloud box's ceiling,
|
|
||||||
* each decoding its cut (12-04). Now one `raea ask --batch` asks them all: through an agent key each window is asked by
|
|
||||||
* reference (the cut sent once, raea-api cuts the window: docs/ask.feature AK3b) and costs the box nothing, so all at
|
|
||||||
* once; cut on the machine, each cut's windows are cut in one pass */
|
|
||||||
export const CLEF_AT_ONCE = 24
|
|
||||||
|
|
||||||
/** `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"]> {
|
|
||||||
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
|
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
|
||||||
const pieces = new Map<string, string[]>()
|
const pieces = new Map<string, string[]>()
|
||||||
for (const r of only) {
|
for (const r of saysOf(g)) {
|
||||||
const files = piecesOf(r, dir)
|
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)
|
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
|
||||||
pieces.set(r.id, files)
|
pieces.set(r.id, files)
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
@@ -203,155 +165,47 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const got = new Map<string, { pass: boolean; why: string }[]>()
|
const got = new Map<string, { pass: boolean; why: string }[]>()
|
||||||
const list = [...groups.values()]
|
for (const k of groups.values()) {
|
||||||
const jobs = list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to }))
|
const answers = ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to)
|
||||||
// raea's own: one `raea ask --batch` for every window; a caller's own `ask` (a test) one job at a time
|
|
||||||
const heard = ask !== askClef
|
|
||||||
? await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
|
|
||||||
: asyncSpawn() ? await askClefManyAsync(dir, jobs) : askClefMany(dir, jobs)
|
|
||||||
for (const [j, k] of list.entries()) {
|
|
||||||
const answers = heard[j]
|
|
||||||
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"}` }]))
|
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"] = {}
|
const rules: Verdict["rules"] = {}
|
||||||
for (const r of only) {
|
for (const r of saysOf(g)) {
|
||||||
const a = got.get(r.id) ?? []
|
const a = got.get(r.id) ?? []
|
||||||
const open = a.filter((x) => !x.pass)
|
const open = a.filter((x) => !x.pass)
|
||||||
rules[r.id] = !pieces.get(r.id)?.length
|
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("; ") }
|
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
|
||||||
}
|
}
|
||||||
return rules
|
return rules
|
||||||
}
|
}
|
||||||
type Answer = { choice?: string; says?: string; problem?: string | null }
|
type Answer = { choice?: string; says?: string; problem?: string | null }
|
||||||
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
|
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Answer[] {
|
||||||
type AskJob = { file: string; says: string[]; from?: string; to?: string }
|
const r = spawnSync(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
|
||||||
const askArgs = (file: string, says: string[], from?: string, to?: string) => ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])]
|
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
|
||||||
const rowsOf = (out: string) => out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
const rows = String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||||
/** whether this runtime has an async spawn (raea's own has only spawnSync) */
|
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)}`)
|
||||||
const asyncSpawn = () => typeof (cp as { spawn?: unknown }).spawn === "function"
|
return rows
|
||||||
|
|
||||||
/** a question's id from its words, as `raea ask` makes it (apps/ask verbs.rs own_id), so a batch's ids are the command
|
|
||||||
* line's and its cached answers still count */
|
|
||||||
export const ownId = (words: string) => `own-${words.split(/[^A-Za-z0-9]+/).filter(Boolean).slice(0, 6).map((w) => w.toLowerCase()).join("-")}`.slice(0, 64)
|
|
||||||
/** one job a batch line (apps/ask verbs.rs from_batch): its file, its window, its rules as true-or-false questions */
|
|
||||||
const batchLine = (k: AskJob) => JSON.stringify({
|
|
||||||
file: k.file,
|
|
||||||
...(k.from || k.to ? { window: { ...(k.from ? { from: Number(k.from) } : {}), ...(k.to ? { to: Number(k.to) } : {}) } } : {}),
|
|
||||||
questions: k.says.map((s) => ({ id: ownId(s), ask: s, type: "choose", options: ["true", "false"] })),
|
|
||||||
})
|
|
||||||
/** the batch's answers back to their jobs, by file, window and question id: each job's in its rules' order */
|
|
||||||
function answersOf(jobs: AskJob[], out: string, err: string): Answer[][] {
|
|
||||||
const at = (file: string, from: number, to: number | null) => [file, from, to].join("\u001f")
|
|
||||||
const want = new Map(jobs.map((k, i) => [at(k.file, Number(k.from ?? 0), k.to ? Number(k.to) : null), i]))
|
|
||||||
const got: (Answer | undefined)[][] = jobs.map((k) => k.says.map(() => undefined))
|
|
||||||
const why = new Map<number, string>()
|
|
||||||
for (const l of out.split("\n")) {
|
|
||||||
let o: { answer?: string; file?: string; id?: string; from?: number; to?: number | null; not_asked?: string; waits?: string } & Answer
|
|
||||||
try { o = JSON.parse(l) } catch { continue }
|
|
||||||
const j = want.get(at(String(o.file), Number(o.from ?? 0), o.to ?? null))
|
|
||||||
if (j === undefined) continue
|
|
||||||
if (!o.answer) { if (o.not_asked || o.waits) why.set(j, String(o.not_asked ?? o.waits)); continue }
|
|
||||||
const i = jobs[j].says.findIndex((s, n) => ownId(s) === o.id && !got[j][n])
|
|
||||||
if (i >= 0) got[j][i] = o
|
|
||||||
}
|
|
||||||
return jobs.map((k, j) => {
|
|
||||||
const rows = got[j].filter((a): a is Answer => !!a)
|
|
||||||
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${why.get(j) ?? (err.trim().slice(-300) || out.trim().slice(-300))}`)
|
|
||||||
return rows
|
|
||||||
})
|
|
||||||
}
|
|
||||||
/** the batch written for `raea ask --batch`, in review/ (gone after) */
|
|
||||||
function batchFile(dir: string, jobs: AskJob[]): { file: string; args: string[]; done: () => void } {
|
|
||||||
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
|
|
||||||
mkdirSync(tmp, { recursive: true })
|
|
||||||
const file = path.join(tmp, "batch.jsonl")
|
|
||||||
writeFileSync(file, jobs.map(batchLine).join("\n") + "\n")
|
|
||||||
return { file, args: ["ask", "--batch", file, "--json", "--jobs", String(Math.min(CLEF_AT_ONCE, jobs.length))], done: () => rmSync(tmp, { recursive: true, force: true }) }
|
|
||||||
}
|
|
||||||
/** every job in one `raea ask --batch` (12-04): the brief and each cut read once, each cut sent to raea-api once when the
|
|
||||||
* windows are asked by reference, else each cut's windows cut in one pass, CLEF_AT_ONCE calls at once. Where there's
|
|
||||||
* no async spawn (raea's runtime) it waits here; askClefManyAsync is the same with node's spawn */
|
|
||||||
export function askClefMany(dir: string, jobs: AskJob[]): Answer[][] {
|
|
||||||
if (!jobs.length) return []
|
|
||||||
const b = batchFile(dir, jobs)
|
|
||||||
try {
|
|
||||||
const r = cp.spawnSync(RAEA, b.args, { cwd: dir, encoding: "utf8", maxBuffer: 64 << 20 }) as { stdout?: string; stderr?: string; error?: Error }
|
|
||||||
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
|
|
||||||
return answersOf(jobs, String(r.stdout ?? ""), String(r.stderr ?? ""))
|
|
||||||
} finally {
|
|
||||||
b.done()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export function askClefManyAsync(dir: string, jobs: AskJob[]): Promise<Answer[][]> {
|
|
||||||
if (!jobs.length) return Promise.resolve([])
|
|
||||||
const b = batchFile(dir, jobs)
|
|
||||||
return new Promise<Answer[][]>((ok, no) => {
|
|
||||||
const c = cp.spawn(RAEA, b.args, { 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", () => {
|
|
||||||
try { ok(answersOf(jobs, out, err)) } catch (e) { no(e) }
|
|
||||||
})
|
|
||||||
}).finally(b.done)
|
|
||||||
}
|
|
||||||
/** `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[]> {
|
|
||||||
const args = askArgs(file, says, from, to)
|
|
||||||
// where there's no async spawn (raea's runtime), one at a time (clefVerdict asks them all at once: askClefMany)
|
|
||||||
if (!asyncSpawn()) {
|
|
||||||
const r = cp.spawnSync(RAEA, args, { cwd: dir, encoding: "utf8" }) as { stdout?: string; stderr?: string; error?: Error }
|
|
||||||
if (r.error) return Promise.reject(new Error(`couldn't run raea ask: ${r.error.message}`))
|
|
||||||
const rows = rowsOf(String(r.stdout ?? ""))
|
|
||||||
if (rows.length !== says.length) return Promise.reject(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 Promise.resolve(rows)
|
|
||||||
}
|
|
||||||
return new Promise((ok, no) => {
|
|
||||||
const c = cp.spawn(RAEA, args, { 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 = rowsOf(out)
|
|
||||||
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)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
|
/** one fresh critic over a goal's `says` rules (`raea goal judge`): its verdict kept at review/judge/NAME.json,
|
||||||
* (criticUrl above), its verdict kept at review/judge/NAME.json, stamped with when it was asked (so work changed while
|
* stamped with when it was asked (so work changed while it judged counts as changed after) */
|
||||||
* it judged counts as changed after) */
|
export function judge(g: Contract, dir: string, by: string): Verdict {
|
||||||
export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef; agent?: (cwd: string, prompt: string) => Promise<string> } = {}): Promise<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`)
|
||||||
const all = saysOf(g)
|
if (!(BY as readonly string[]).includes(by)) throw new Error(`--by ${by}: the critics are ${BY.join(", ")}`)
|
||||||
if (!all.length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
|
|
||||||
const asked = Math.floor(Date.now() / 1000)
|
const asked = Math.floor(Date.now() / 1000)
|
||||||
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
|
if (by === "clef") return keep(g, dir, { at: asked, by, goal: g.aim ?? nameOf(g), rules: clefVerdict(g, dir) })
|
||||||
const read = all.filter((r) => !watched.includes(r))
|
const p = prompt(g, dir)
|
||||||
// what's watched and heard, and what's read, at once: neither waits on the other
|
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 })
|
||||||
const [heard, said] = await Promise.all([
|
if (r.error) throw new Error(`couldn't run ${by}: ${r.error.message} (is its CLI installed and signed in?)`)
|
||||||
watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : Promise.resolve({} as Verdict["rules"]),
|
let words = String(r.stdout ?? "")
|
||||||
read.length ? (o.agent ?? askAgent)(dir, prompt(g, dir, read)) : Promise.resolve(null),
|
try {
|
||||||
])
|
const o = JSON.parse(words)
|
||||||
const rules: Verdict["rules"] = { ...heard }
|
if (typeof o.result === "string") words = o.result
|
||||||
if (said !== null) {
|
} catch {}
|
||||||
const v = lastVerdict(said)
|
const v = lastVerdict(words)
|
||||||
if (!v) throw new Error(`the critic gave no verdict: ${said.slice(-300).trim()}`)
|
if (!v) throw new Error(`${by} answered no verdict: ${words.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, { ...v, at: asked, by, goal: g.aim ?? nameOf(g) })
|
||||||
}
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
function keep(g: Contract, dir: string, out: Verdict): Verdict {
|
function keep(g: Contract, dir: string, out: Verdict): Verdict {
|
||||||
const file = path.join(dir, verdictPath(g))
|
const file = path.join(dir, verdictPath(g))
|
||||||
|
|||||||
+6
-6
@@ -13,7 +13,7 @@
|
|||||||
// says what for; it holds nothing.
|
// 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 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 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 { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||||
import path from "node:path"
|
import path from "node:path"
|
||||||
import { pathToFileURL } from "node:url"
|
import { pathToFileURL } from "node:url"
|
||||||
@@ -24,7 +24,7 @@ import * as media from "./media.ts"
|
|||||||
import { registeredPack } from "./packs/job.ts"
|
import { registeredPack } from "./packs/job.ts"
|
||||||
import { tastePack } from "./packs/taste.ts"
|
import { tastePack } from "./packs/taste.ts"
|
||||||
import { loadProject, type Project } from "./project.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 { PACK_CHECKS } from "./packs/index.ts"
|
||||||
import { second } from "./packs/look.ts"
|
import { second } from "./packs/look.ts"
|
||||||
import { deliverablesOf } from "./packs/job.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 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 (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 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]`
|
raea make place FILE [--at S[,S...]] [--box WxH]`
|
||||||
|
|
||||||
export async function main(argv: string[]): Promise<number> {
|
export async function main(argv: string[]): Promise<number> {
|
||||||
@@ -260,8 +260,8 @@ export async function main(argv: string[]): Promise<number> {
|
|||||||
if (!said?.trim()) {
|
if (!said?.trim()) {
|
||||||
const sheet = media.sheet(path.resolve(file))
|
const sheet = media.sheet(path.resolve(file))
|
||||||
const full = kindOf(path.resolve(file)) === "video" ? media.looks(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
|
// 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 && process.env.RAEA_AGENT_KEY && process.env.RAEA_API ? second(path.resolve(file)) : null
|
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}`)
|
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"' : ""}`)
|
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
|
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`}`)
|
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
|
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 ?? ""}`)
|
for (const [id, r] of Object.entries(v.rules)) console.log(`${r?.pass ? "ok " : "open"} ${id}: ${r?.why ?? ""}`)
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
import { expect, test } from "bun:test"
|
|
||||||
import { spawnSync } from "node:child_process"
|
|
||||||
import { mkdtempSync, readdirSync, readFileSync } from "node:fs"
|
|
||||||
import { tmpdir } from "node:os"
|
|
||||||
import path from "node:path"
|
|
||||||
|
|
||||||
// a stop's windows in one `raea ask --batch` (12-04): one after another its 18 beats took 7.7 minutes, and six `raea
|
|
||||||
// ask`s at once was a raea cloud box's ceiling, each decoding its cut. One batch reads the brief and each cut once and
|
|
||||||
// asks every window by reference (docs/ask.feature AK3b). A child with a stand-in raea (a second a run), since RAEA is
|
|
||||||
// read once, as goal.ts is loaded; on raea's runtime (no async spawn) and under node's spawn alike
|
|
||||||
for (const how of ["askClefMany", "askClefManyAsync"]) {
|
|
||||||
test(`${how} asks every job in one raea ask --batch and gives each job its answers in its rules' order`, () => {
|
|
||||||
const dir = mkdtempSync(path.join(tmpdir(), "raea-ask-many-"))
|
|
||||||
const log = path.join(dir, "runs.log")
|
|
||||||
const script = `
|
|
||||||
import { ${how} as ask } from ${JSON.stringify(path.join(import.meta.dir, "../src/packs/goal.ts"))}
|
|
||||||
const jobs = Array.from({ length: 6 }, (_, i) => ({ file: "out/cut " + i + "'s.mp4", says: i % 2 ? ["The product is on screen from 1 s to 2 s", "Someone speaks"] : ["one"], ...(i < 5 ? { from: String(i), to: String(i + 1.5) } : {}) }))
|
|
||||||
const t0 = Date.now()
|
|
||||||
const got = await ask(${JSON.stringify(dir)}, jobs)
|
|
||||||
console.log(JSON.stringify({ ms: Date.now() - t0, n: got.map((r) => r.length), file: got[1][0].file, ids: got[1].map((a) => a.id), to: got[4][0].to, end: got[5][0].to }))
|
|
||||||
`
|
|
||||||
const r = spawnSync("bun", ["-e", script], { encoding: "utf8", env: { ...process.env, RAEA_REAL: path.join(import.meta.dir, "fixtures/fake-ask/raea"), FAKE_ASK_LOG: log } })
|
|
||||||
expect(r.stderr.trim().split("\n").filter((l) => /error/i.test(l))).toEqual([])
|
|
||||||
const o = JSON.parse(r.stdout.trim().split("\n").at(-1)!)
|
|
||||||
expect(o.ms).toBeLessThan(3_000)
|
|
||||||
expect(o.n).toEqual([1, 2, 1, 2, 1, 2])
|
|
||||||
expect(o.file).toBe("out/cut 1's.mp4")
|
|
||||||
expect(o.ids).toEqual(["own-the-product-is-on-screen-from", "own-someone-speaks"])
|
|
||||||
expect([o.to, o.end]).toEqual([5.5, null])
|
|
||||||
const runs = readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l))
|
|
||||||
expect(runs.length).toBe(1)
|
|
||||||
expect(runs[0].slice(0, 1).concat(runs[0].slice(3))).toEqual(["ask", "--json", "--jobs", "6"])
|
|
||||||
expect(readdirSync(path.join(dir, "review"))).toEqual([])
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
test("a job the batch doesn't answer says why", () => {
|
|
||||||
const dir = mkdtempSync(path.join(tmpdir(), "raea-ask-short-"))
|
|
||||||
const script = `
|
|
||||||
import { askClefMany } from ${JSON.stringify(path.join(import.meta.dir, "../src/packs/goal.ts"))}
|
|
||||||
try { askClefMany(${JSON.stringify(dir)}, [{ file: "out/a.mp4", says: ["one"] }]) ; console.log("no error") } catch (e) { console.log(String(e.message)) }
|
|
||||||
`
|
|
||||||
// a raea that answers nothing (it only says its arguments back)
|
|
||||||
const r = spawnSync("bun", ["-e", script], { encoding: "utf8", env: { ...process.env, RAEA_REAL: "/bin/echo" } })
|
|
||||||
expect(r.stdout).toContain("raea ask answered 0 of 1 about out/a.mp4: ask --batch")
|
|
||||||
})
|
|
||||||
Vendored
-14
@@ -1,14 +0,0 @@
|
|||||||
#!/usr/bin/env bun
|
|
||||||
// a stand-in `raea ask --batch FILE --json --jobs N`: after a second, one answer a line for each question of each line,
|
|
||||||
// as `raea ask --json` prints them; every run noted in $FAKE_ASK_LOG (one line a run, its arguments)
|
|
||||||
import { appendFileSync, readFileSync } from "node:fs"
|
|
||||||
const args = process.argv.slice(2)
|
|
||||||
if (process.env.FAKE_ASK_LOG) appendFileSync(process.env.FAKE_ASK_LOG, JSON.stringify(args) + "\n")
|
|
||||||
const at = args.indexOf("--batch")
|
|
||||||
if (args[0] !== "ask" || at < 0) { console.error(`the fake only answers a batch: ${args.join(" ")}`); process.exit(1) }
|
|
||||||
await Bun.sleep(1000)
|
|
||||||
for (const l of readFileSync(args[at + 1], "utf8").split("\n").filter(Boolean)) {
|
|
||||||
const e = JSON.parse(l)
|
|
||||||
for (const q of e.questions) console.log(JSON.stringify({ answer: "a", file: e.file, id: q.id, from: e.window?.from ?? 0, to: e.window?.to ?? null, choice: "true", says: "true (0.9)", problem: null }))
|
|
||||||
}
|
|
||||||
console.log(JSON.stringify({ summary: {} }))
|
|
||||||
@@ -4,7 +4,7 @@ import { expect, test } from "bun:test"
|
|||||||
import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"
|
import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"
|
||||||
import { tmpdir } from "node:os"
|
import { tmpdir } from "node:os"
|
||||||
import path from "node:path"
|
import path from "node:path"
|
||||||
import { CLEF_AT_ONCE, 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 { goalCheck } from "../src/run.ts"
|
||||||
import { project, put } from "./project.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" }]))
|
const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
|
||||||
put(d, "work.txt", "the work")
|
put(d, "work.txt", "the work")
|
||||||
const says = async () => (await goalCheck({ cwd: d })).findings.filter((x) => x.check === "says")
|
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("raea goal judge")
|
||||||
expect((await says())[0].fix).toBe(NO_CRITIC)
|
|
||||||
const later = Math.floor(Date.now() / 1000) + 5
|
const later = Math.floor(Date.now() / 1000) + 5
|
||||||
mkdirSync(path.join(d, "review/judge"), { recursive: true })
|
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" } } }))
|
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")
|
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 () => {
|
test("file rules are deliverables", async () => {
|
||||||
const d = project(goal([{ id: "export", file: "out/final.txt" }]))
|
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"]])
|
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")
|
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-"))
|
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
|
||||||
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
|
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")
|
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 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 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}`)
|
asked.push(`${file} ${from ?? ""}-${to ?? ""} ${says.length}`)
|
||||||
return says.map((q) => ({ choice: q.includes("caption") && file.includes("b_") ? "false" : "true", says: "said" }))
|
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?.pass).toBe(false)
|
||||||
expect(rules.all?.why).toBe("out/cuts/b_9x16.mp4: said")
|
expect(rules.all?.why).toBe("out/cuts/b_9x16.mp4: said")
|
||||||
const empty = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
|
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", () => {
|
test("a reading kept beside a file isn't the work changing", () => {
|
||||||
@@ -150,21 +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"), "{}")
|
writeFileSync(path.join(d, "out/cuts/a_b_c_v1_9x16.render.json"), "{}")
|
||||||
expect(newest(d)!).toBeGreaterThan(1_000_000)
|
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" }))
|
|
||||||
})
|
|
||||||
// a caller's own ask is held to CLEF_AT_ONCE (24): all eight at once
|
|
||||||
expect(most).toBe(Math.min(CLEF_AT_ONCE, names.length))
|
|
||||||
expect(rules.seen?.pass).toBe(true)
|
|
||||||
})
|
|
||||||
@@ -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),
|
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`.
|
`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
|
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
|
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.
|
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.
|
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.
|
`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
|
Who plays which role:
|
||||||
for you (the agent this project runs on where the raea app or raea cloud started it, else clef-omni for the numbers).
|
- **In Claude Code:** the session is the builder. The judge is a new subagent every round, plus `raea judge` (clef-omni)
|
||||||
You never pick it.
|
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.
|
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.
|
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.
|
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
|
- 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.
|
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
|
- Run `raea judge review/r<n> --by kimi` (or `--by claude`; plain `raea judge` is clef-omni, cheap but advice only
|
||||||
photos, this round's sheets, and last round's sheets and verdict: never your code, your log or your list. Who reads
|
until calibrated). Each is a new session that sees only the sheets. In Claude Code you can also hand the sheets to a
|
||||||
them is raea's to settle, not yours.
|
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
|
- 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.
|
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.
|
- 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
|
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
|
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.
|
`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
|
3. **A fresh critic for the fixes.** `raea judge review/rN --kind scene --by claude --brief brief.ts --target
|
||||||
media/ref/target.png --json` scores the kind's rubric (scene: layout, props, signage, materials,
|
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
|
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
|
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.
|
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`,
|
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
|
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
|
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
|
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.
|
(`--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,
|
6. **Grade.** `<Grade {...gradeLook("cinematic")} />` from `raea/post_process`: clean, cinematic, gritty or vintage,
|
||||||
|
|||||||
@@ -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
|
- 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
|
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`).
|
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
|
- 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
|
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.
|
drawn, and writes their words as an .srt beside them; unmarked, they're part of the graphics.
|
||||||
|
|||||||
+1
-1
Submodule skills updated: 6c71231e97...fb72c5e256.
@@ -22,8 +22,7 @@ generic=(
|
|||||||
)
|
)
|
||||||
# allowed: example home folders, the credits for what raea ports (NOTICE, ported headers), and licence boilerplate. Written
|
# 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.
|
# 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)/|PERFORMANCE OF'
|
||||||
allow='/Users/(a|you|me|name|user|USER|runner)/|/home/(you|user|runner|USER|sprite|raea)/|PERFORMANCE OF'
|
|
||||||
allow+='|Portions ported from Hyper''Frames \(Apache-2\.0|ports? from Hyper''Frames|github\.com/heygen-com/hyper''frames'
|
allow+='|Portions ported from Hyper''Frames \(Apache-2\.0|ports? from Hyper''Frames|github\.com/heygen-com/hyper''frames'
|
||||||
|
|
||||||
names_file() {
|
names_file() {
|
||||||
|
|||||||
Reference in new issue
Block a user