mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 21:03:47 -10:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea61f3c66c | ||
|
|
d0f09511fe |
No files matched your search
+22
-1
@@ -58,7 +58,23 @@ pub struct Track {
|
||||
|
||||
/// A file's first video track's display rotation (clockwise degrees; 0 when it has none or isn't an MP4/MOV).
|
||||
pub fn rotation_of(path: &Path) -> i32 {
|
||||
std::fs::read(path).map(|b| mp4_rotation(&b)).unwrap_or(0)
|
||||
// the moov box alone, as a file of that one box (the whole file was read for it: gigabytes, for a matrix)
|
||||
let Some(moov) = raea_io_codec::mp4box::moov_of(path) else { return 0 };
|
||||
let mut b = ((moov.len() + 8) as u32).to_be_bytes().to_vec();
|
||||
b.extend_from_slice(b"moov");
|
||||
b.extend_from_slice(&moov);
|
||||
mp4_rotation(&b)
|
||||
}
|
||||
|
||||
/// The first video track's sample entry (avc1, hvc1, av01, ...), from the moov box alone.
|
||||
fn video_fourcc(path: &Path) -> Option<[u8; 4]> {
|
||||
use raea_io_codec::mp4box::{boxes, child, moov_of};
|
||||
let moov = moov_of(path)?;
|
||||
boxes(&moov).into_iter().filter(|(k, _)| k == b"trak").find_map(|(_, trak)| {
|
||||
let mdia = child(trak, b"mdia")?;
|
||||
(child(mdia, b"hdlr")?.get(8..12)? == b"vide").then_some(())?;
|
||||
child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?.get(12..16)?.try_into().ok()
|
||||
})
|
||||
}
|
||||
|
||||
/// The first video track's display rotation, from its tkhd matrix (QuickTime's 16.16 a, b, c, d).
|
||||
@@ -107,6 +123,11 @@ fn mp4_rotation(b: &[u8]) -> i32 {
|
||||
}
|
||||
|
||||
pub fn demux(path: &Path, want: &str) -> R<Track> {
|
||||
// another codec's file is refused before it is read: every open of a 4K HEVC interview on Linux read its whole
|
||||
// gigabyte here to learn it wasn't H.264, then went to the backend that reads it (two minutes on a cloud disk)
|
||||
if let Some(is) = video_fourcc(path).filter(|f| want.len() >= 3 && f[..3] != want.as_bytes()[..3]) {
|
||||
return Err(format!("{}: {}, not {want} (this backend reads {want} mezzanines)", path.display(), String::from_utf8_lossy(&is)));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let mp4 = re_mp4::Mp4::read_bytes(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let (_, t) = mp4
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//! A file of another codec is refused from its moov box alone, and a rotation is read from it, without the file's
|
||||
//! pictures being read (a 1 GB HEVC interview was read whole on every open to learn it wasn't H.264).
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
fn made(dir: &Path, name: &str, args: &[&str]) -> Option<PathBuf> {
|
||||
let p = dir.join(name);
|
||||
Command::new("ffmpeg").args(["-v", "error", "-y"]).args(args).arg(&p).status().is_ok_and(|s| s.success()).then_some(p)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_codec_is_refused_by_its_tables_and_a_rotation_read_from_them() {
|
||||
let dir = std::env::temp_dir().join(format!("raea-soft-refuse-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let src = ["-f", "lavfi", "-i", "testsrc2=s=128x72:r=30:d=1", "-pix_fmt", "yuv420p"];
|
||||
let Some(other) = made(&dir, "other.mp4", &[&src[..], &["-c:v", "mpeg4"]].concat()) else { return eprintln!("skipped: no ffmpeg here") };
|
||||
let e = raea_io_soft::demux(&other, "avc1").err().expect("an MPEG-4 file isn't H.264");
|
||||
assert!(e.contains("mp4v, not avc1"), "{e}");
|
||||
// cut short after its moov, the refusal is the same: nothing past the tables was needed
|
||||
if let Some(front) = made(&dir, "front.mp4", &[&src[..], &["-c:v", "mpeg4", "-movflags", "+faststart"]].concat()) {
|
||||
let bytes = std::fs::read(&front).unwrap();
|
||||
let mdat = bytes.windows(4).position(|w| w == b"mdat").unwrap();
|
||||
std::fs::write(&front, &bytes[..mdat + 4]).unwrap();
|
||||
assert!(raea_io_soft::demux(&front, "avc1").err().unwrap().contains("mp4v, not avc1"));
|
||||
assert_eq!(raea_io_soft::rotation_of(&front), 0);
|
||||
}
|
||||
// an H.264 file is read as before, and one turned on its side says so
|
||||
if let Some(h264) = made(&dir, "h264.mp4", &[&src[..], &["-c:v", "libx264"]].concat()) {
|
||||
assert!(raea_io_soft::demux(&h264, "avc1").is_ok());
|
||||
assert_eq!(raea_io_soft::rotation_of(&h264), 0);
|
||||
let h = h264.to_string_lossy().to_string();
|
||||
if let Some(turned) = made(&dir, "turned.mp4", &["-display_rotation:v:0", "90", "-i", &h, "-c", "copy"]) {
|
||||
assert_eq!(raea_io_soft::rotation_of(&turned).rem_euclid(180), 90);
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -34,6 +34,7 @@
|
||||
// Every route but /healthz needs RAEA_CLOUD_TOKEN: `Authorization: Bearer TOKEN`, or ?token= (a browser's WebSocket
|
||||
// can't set headers). The agent and raea get the container's environment without the token or the state keys.
|
||||
|
||||
import { jobsOf, watchTurnEnd } from "./turn-end.ts"
|
||||
import { execFileSync, spawn } from "node:child_process"
|
||||
import { timingSafeEqual } from "node:crypto"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
@@ -412,7 +413,20 @@ server.on("upgrade", (req, socket, head) => {
|
||||
buf += c
|
||||
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) if (i > 0) ws.send(buf.slice(0, i))
|
||||
})
|
||||
ws.on("message", (m) => ((heard = Date.now()), child.stdin.write(m.toString() + "\n")))
|
||||
let heardFromCaller = Date.now()
|
||||
ws.on("message", (m) => ((heard = heardFromCaller = Date.now()), child.stdin.write(m.toString() + "\n")))
|
||||
// the turn's end from the agent's own transcript, said along the socket (turn-end.ts): raea cloud closes the turn
|
||||
// on it without waiting for an answer to session/prompt that may not come
|
||||
if (agent.id === "antigravity-acp" && env.GEMINI_HOME) {
|
||||
const stopWatch = watchTurnEnd(
|
||||
env.GEMINI_HOME,
|
||||
() => heardFromCaller,
|
||||
(by) => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/turn_end", params: { by } })),
|
||||
() => !!child.pid && jobsOf(child.pid, path.dirname(agent.command), WORK).length > 0,
|
||||
)
|
||||
ws.on("close", stopWatch)
|
||||
child.on("exit", stopWatch)
|
||||
}
|
||||
ws.on("close", stopAll)
|
||||
child.on("error", (e) => ws.close(1011, `couldn't start ${agent.id}: ${e.message}`.slice(0, 120)))
|
||||
child.on("exit", (code) => (ws.close(1011, `${agent.id} exited ${code}`), stopAll()))
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
// A turn's end, read off the agent's own records and said along its socket as a `_raea/turn_end` notification, so raea
|
||||
// cloud closes the turn in seconds whether or not the agent answers its session/prompt (12-01: Gemini wrote its delivery
|
||||
// message and never answered; the run stayed open 45 minutes, until the idle agent was ended here, and was then read
|
||||
// as cut off and started again. Shane: "should not be more than a couple seconds to detect a stall").
|
||||
//
|
||||
// Antigravity keeps a transcript of each session, a JSON line a step. A model step that finished and called no tool is
|
||||
// the end of its turn only when nothing it started still runs: it ends a step the same way to wait on a render it left
|
||||
// in the background (123 of 131 such steps in one StreetTalk run), and is woken when that finishes. So both are read:
|
||||
// the transcript's last line, and the processes that are the agent's own.
|
||||
import { closeSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, statSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
|
||||
/** the step a transcript line ends a turn at, and when it was made (ms); null for any other line */
|
||||
export function turnEndOf(line: string): { step: number; at: number } | null {
|
||||
let m: any
|
||||
try {
|
||||
m = JSON.parse(line)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!m || m.type !== "PLANNER_RESPONSE" || m.status !== "DONE" || m.source !== "MODEL") return null
|
||||
if (Array.isArray(m.tool_calls) && m.tool_calls.length) return null
|
||||
const at = Date.parse(m.created_at ?? "")
|
||||
return typeof m.step_index === "number" && Number.isFinite(at) ? { step: m.step_index, at } : null
|
||||
}
|
||||
|
||||
/** a file's last whole line */
|
||||
export function lastLine(file: string, most = 1 << 20): string {
|
||||
const size = statSync(file).size
|
||||
const n = Math.min(size, most)
|
||||
const b = Buffer.alloc(n)
|
||||
const fd = openSync(file, "r")
|
||||
try {
|
||||
readSync(fd, b, 0, n, size - n)
|
||||
} finally {
|
||||
closeSync(fd)
|
||||
}
|
||||
const lines = b.toString("utf8").split("\n").filter(Boolean)
|
||||
return lines.at(-1) ?? ""
|
||||
}
|
||||
|
||||
/** the transcript written to last under an Antigravity home (GEMINI_HOME), or null */
|
||||
export function newestTranscript(geminiHome: string): { file: string; mtime: number } | null {
|
||||
const brain = path.join(geminiHome, "antigravity-acp", "brain")
|
||||
let best: { file: string; mtime: number } | null = null
|
||||
let names: string[] = []
|
||||
try {
|
||||
names = readdirSync(brain)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
for (const n of names) {
|
||||
const f = path.join(brain, n, ".system_generated", "logs", "transcript.jsonl")
|
||||
try {
|
||||
const m = statSync(f).mtimeMs
|
||||
if (!best || m > best.mtime) best = { file: f, mtime: m }
|
||||
} catch {}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/** What an agent has running that isn't the agent itself: every process in its session (it's started detached, so
|
||||
* the session is its own), descended from it, or working under `work` (a job started with a session of its own),
|
||||
* but for the agent's own programs (under `agentDir`) and raea cloud's (their command names .raea-cloud). Linux /proc. */
|
||||
export function jobsOf(pid: number, agentDir: string, work: string, proc = "/proc"): number[] {
|
||||
const all: { pid: number; ppid: number; sid: number }[] = []
|
||||
let names: string[] = []
|
||||
try {
|
||||
names = readdirSync(proc)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
for (const n of names) {
|
||||
if (!/^\d+$/.test(n)) continue
|
||||
try {
|
||||
// "pid (comm) state ppid pgrp session ...": comm may hold spaces and brackets, so read from its last ")"
|
||||
const st = readFileSync(path.join(proc, n, "stat"), "utf8")
|
||||
const f = st.slice(st.lastIndexOf(")") + 2).split(" ")
|
||||
all.push({ pid: Number(n), ppid: Number(f[1]), sid: Number(f[3]) })
|
||||
} catch {}
|
||||
}
|
||||
const kids = new Set<number>([pid])
|
||||
for (let grew = true; grew; ) {
|
||||
grew = false
|
||||
for (const p of all) if (!kids.has(p.pid) && kids.has(p.ppid)) (kids.add(p.pid), (grew = true))
|
||||
}
|
||||
const link = (n: number, what: string) => {
|
||||
try {
|
||||
return readlinkSync(path.join(proc, String(n), what))
|
||||
} catch {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
const cmd = (n: number) => {
|
||||
try {
|
||||
return readFileSync(path.join(proc, String(n), "cmdline"), "utf8").replace(/\0/g, " ")
|
||||
} catch {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return all
|
||||
.filter((p) => p.pid !== pid && p.pid !== process.pid)
|
||||
.filter((p) => p.sid === pid || kids.has(p.pid) || (link(p.pid, "cwd") + "/").startsWith(work.replace(/\/?$/, "/")))
|
||||
.filter((p) => !link(p.pid, "exe").startsWith(agentDir) && !cmd(p.pid).includes(".raea-cloud"))
|
||||
.map((p) => p.pid)
|
||||
}
|
||||
|
||||
/** Watches an Antigravity agent's transcript and calls `said` once for each turn that ends after `told()` (when the
|
||||
* agent was last sent anything: a turn that ended before its newest prompt isn't this one's), once `busy()` has been
|
||||
* false two looks running. Returns its stop. */
|
||||
export function watchTurnEnd(geminiHome: string, told: () => number, said: (by: string) => void, busy: () => boolean = () => false, everyMs = 1000): () => void {
|
||||
let seen = -1
|
||||
let idle = 0
|
||||
const t = setInterval(() => {
|
||||
try {
|
||||
const tr = newestTranscript(geminiHome)
|
||||
const end = tr ? turnEndOf(lastLine(tr.file)) : null
|
||||
// a second's slack: the transcript's times are whole seconds
|
||||
if (!end || end.step === seen || end.at < told() - 1000 || busy()) return void (idle = 0)
|
||||
if (++idle < 2) return
|
||||
seen = end.step
|
||||
said("its transcript, and nothing of its own running")
|
||||
} catch {}
|
||||
}, everyMs)
|
||||
t.unref?.()
|
||||
return () => clearInterval(t)
|
||||
}
|
||||
+54
-1
@@ -3,12 +3,13 @@
|
||||
// paths read on the worker)
|
||||
|
||||
import assert from "node:assert/strict"
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { parseSummary, pick } from "../server/gpu.ts"
|
||||
import { plan, projectRoot } from "../server/offload.ts"
|
||||
import { shellEnv } from "../server/shell-os.ts"
|
||||
import { jobsOf, lastLine, newestTranscript, turnEndOf, watchTurnEnd } from "../server/turn-end.ts"
|
||||
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
|
||||
|
||||
const L4 = `Devices:
|
||||
@@ -107,3 +108,55 @@ console.log("units: ok")
|
||||
console.log("ok google-token")
|
||||
}
|
||||
|
||||
|
||||
{
|
||||
// a turn's end in Antigravity's transcript: a finished model step that called no tool (turn-end.ts)
|
||||
const done = { step_index: 1716, source: "MODEL", type: "PLANNER_RESPONSE", status: "DONE", created_at: "2026-12-02T03:34:18Z", content: "All six cuts are delivered." }
|
||||
assert.deepEqual(turnEndOf(JSON.stringify(done)), { step: 1716, at: Date.parse("2026-12-02T03:34:18Z") })
|
||||
assert.equal(turnEndOf(JSON.stringify({ ...done, tool_calls: [{ name: "run_command" }] })), null)
|
||||
assert.equal(turnEndOf(JSON.stringify({ ...done, status: "RUNNING" })), null)
|
||||
assert.equal(turnEndOf(JSON.stringify({ ...done, type: "RUN_COMMAND" })), null)
|
||||
assert.equal(turnEndOf("not json"), null)
|
||||
const home = mkdtempSync(path.join(os.tmpdir(), "raea-turn-end-"))
|
||||
const logs = path.join(home, "antigravity-acp", "brain", "s1", ".system_generated", "logs")
|
||||
mkdirSync(logs, { recursive: true })
|
||||
const file = path.join(logs, "transcript.jsonl")
|
||||
const now = Date.now()
|
||||
const line = (o: object) => JSON.stringify(o) + "\n"
|
||||
writeFileSync(file, line({ ...done, step_index: 1, created_at: new Date(now - 60_000).toISOString() }))
|
||||
assert.equal(newestTranscript(home)?.file, file)
|
||||
assert.equal(JSON.parse(lastLine(file)).step_index, 1)
|
||||
// an end from before the agent was last told anything isn't this turn's; one after it is said once
|
||||
const said: string[] = []
|
||||
let busy = true
|
||||
const stop = watchTurnEnd(home, () => now, (by) => said.push(by), () => busy, 10)
|
||||
await new Promise((ok) => setTimeout(ok, 60))
|
||||
assert.deepEqual(said, [])
|
||||
writeFileSync(file, line({ ...done, step_index: 2, tool_calls: [{ name: "x" }], created_at: new Date(now + 1000).toISOString() }) + line({ ...done, step_index: 3, created_at: new Date(now + 2000).toISOString() }))
|
||||
// the step ended, but a job the agent started still runs: it's waiting, not done
|
||||
await new Promise((ok) => setTimeout(ok, 80))
|
||||
assert.deepEqual(said, [])
|
||||
busy = false
|
||||
await new Promise((ok) => setTimeout(ok, 80))
|
||||
stop()
|
||||
assert.deepEqual(said, ["its transcript, and nothing of its own running"])
|
||||
// an agent's own jobs, from a made-up /proc: its session's and its children's, not its own programs or raea cloud's
|
||||
const proc = path.join(home, "proc")
|
||||
const put = (pid: number, ppid: number, sid: number, exe: string, cmd: string, cwd = "/") => {
|
||||
mkdirSync(path.join(proc, String(pid)), { recursive: true })
|
||||
writeFileSync(path.join(proc, String(pid), "stat"), `${pid} (a (odd) name) S ${ppid} ${sid} ${sid} 0 -1`)
|
||||
writeFileSync(path.join(proc, String(pid), "cmdline"), cmd.replace(/ /g, "\0"))
|
||||
symlinkSync(exe, path.join(proc, String(pid), "exe"))
|
||||
symlinkSync(cwd, path.join(proc, String(pid), "cwd"))
|
||||
}
|
||||
put(100, 1, 100, "/opt/raea-cloud/agents/antigravity-acp/agy", "agy")
|
||||
put(101, 100, 100, "/opt/raea-cloud/agents/antigravity-acp/localharness_external", "localharness_external")
|
||||
put(50, 1, 50, "/usr/bin/node", "node /opt/raea-cloud/server/main.ts")
|
||||
put(60, 50, 50, "/usr/bin/node", "node .raea-cloud/live/live.cjs", "/srv/work/threads/r1")
|
||||
assert.deepEqual(jobsOf(100, "/opt/raea-cloud/agents/antigravity-acp", "/srv/work", proc), [])
|
||||
put(200, 101, 100, "/opt/raea/bin/raea", "raea render edit.tsx")
|
||||
put(300, 1, 300, "/usr/bin/ffmpeg", "ffmpeg -i a.mp4", "/srv/work/threads/r1/out")
|
||||
assert.deepEqual(jobsOf(100, "/opt/raea-cloud/agents/antigravity-acp", "/srv/work", proc).sort(), [200, 300])
|
||||
rmSync(home, { recursive: true, force: true })
|
||||
console.log("ok turn-end")
|
||||
}
|
||||
Reference in new issue
Block a user