mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
An edit holding several cuts has one words.json, so Captions had no words for each cut and agents wrote their own captions at a typed top, in the app's UI zones.
338 lines
21 KiB
TypeScript
338 lines
21 KiB
TypeScript
// @raea/cli: the agent shell's own verbs of `raea` (init, cut, frame, part, brand), the project's files for editing video
|
|
// as a React + TypeScript project. The native raea runs this handler for the verbs in its SHELL list (motion.rs shell(),
|
|
// through src/native.ts on its JavaScriptCore); what needs perception, ffmpeg or raea's API is asked of `host`
|
|
// (native.ts answers it), and every other verb is the engine's own command line (`engine`: the native `raea`), so there
|
|
// is one `raea`, and its help is the native one. Every command prints what a person would read; files hold the rest.
|
|
import { REGISTRY, TEMPLATE } from "./registry.gen";
|
|
import { FEATURE_DIRS, featureLayout } from "./layout";
|
|
|
|
/** The host's answer to an op (src/native.ts answers shape, cut, frame and brand). Throws when there's no host. */
|
|
export type Host = (op: string, args: Record<string, unknown>) => any;
|
|
|
|
/** The engine's own command line (the native `raea`: render FILE.tsx, play, guide, song, add PKG ...), run in the shell's
|
|
* folder. The shell gives it; without one, those verbs say so. */
|
|
export type Engine = (args: string[], ctx: unknown) => Promise<{ stdout: string; stderr: string; exitCode: number }>;
|
|
|
|
type Fs = {
|
|
exists(p: string): Promise<boolean>;
|
|
readFile(p: string, enc?: string): Promise<string>;
|
|
writeFile(p: string, data: string): Promise<void>;
|
|
mkdir(p: string, o?: { recursive?: boolean }): Promise<void>;
|
|
};
|
|
type Ctx = { cwd: string; fs: Fs };
|
|
const out = (stdout: string, exitCode = 0, stderr = "") => ({ stdout, stderr, exitCode });
|
|
// `raea library` (library.ts), kept apart from the imports above
|
|
import { libraryVerb } from "./library";
|
|
// `raea show` (show.ts): what a session shows the person, in the raea app
|
|
import { absolute, fromCwd, labelsIn, showVerb } from "./show";
|
|
// `raea make clothes` (clothes.ts): garments for SOMA's body from words
|
|
import { clothesVerb } from "./clothes";
|
|
// the component library (catalog.ts): open components sorted by use, listed and copied by `raea make component`
|
|
import { added, found, listed, searched, shown as inFull, terms, type Got, type Item } from "./catalog";
|
|
// `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server
|
|
import { bugVerb } from "./bug";
|
|
|
|
function flag(args: string[], name: string): string | undefined {
|
|
const i = args.indexOf(name);
|
|
return i >= 0 ? args[i + 1] : undefined;
|
|
}
|
|
|
|
const clean = (args: string[], ...withValue: string[]) =>
|
|
args.filter((a, i) => !a.startsWith("--") && !withValue.includes(args[i - 1] ?? ""));
|
|
|
|
/** A clip of a take: seconds in the take's own time, and the line it carries. */
|
|
export interface Cut {
|
|
take: string;
|
|
file: string;
|
|
from: number;
|
|
to: number;
|
|
line: string;
|
|
/** a sound-only take's clip plays as <Audio> (#89); absent means video */
|
|
kind?: "video" | "audio";
|
|
}
|
|
|
|
/** cuts.ts from the clips: data the edit imports (each take's file as a module, so the bundler finds the media). */
|
|
export function cutsModule(clips: Cut[], edit: { width: number; height: number; fps: number }): string {
|
|
const files = [...new Set(clips.map((c) => c.file))];
|
|
const id = (f: string) => "m_" + f.replace(/\W/g, "_");
|
|
const rows = clips.map((c) => ` { take: ${JSON.stringify(c.take)}, src: ${id(c.file)}, from: ${c.from.toFixed(3)}, to: ${c.to.toFixed(3)}, line: ${JSON.stringify(c.line)}, kind: ${JSON.stringify(c.kind ?? "video")} },`);
|
|
return `// written by \`raea cut\`: the clips, in order, in each take's own seconds. Re-run raea cut to change them, or edit
|
|
// by hand (the edit reads only this file). cuts.json beside it is the same list for raea's checks.
|
|
${files.map((f) => `import ${id(f)} from ${JSON.stringify("./" + f)};`).join("\n")}
|
|
|
|
export const edit = ${JSON.stringify(edit)};
|
|
export type Cut = { take: string; src: string; from: number; to: number; line: string; kind: "video" | "audio" };
|
|
export const cuts: Cut[] = [
|
|
${rows.join("\n")}
|
|
];
|
|
/** a clip's length in the edit's frames */
|
|
export const frames = (c: Cut) => Math.max(1, Math.round((c.to - c.from) * edit.fps));
|
|
/** the cuts end to end, in frames */
|
|
export const total = cuts.reduce((n, c) => n + frames(c), 0);
|
|
`;
|
|
}
|
|
|
|
const NOTES = `# This project
|
|
|
|
A video edit as a React + TypeScript project, rendered by raea.
|
|
|
|
- edit.tsx: the composition. Change anything: layout, timing, which component plays when.
|
|
- cuts.ts: the clips (\`raea cut\` writes it, with cuts.json and words.json beside it; re-run it rather than editing
|
|
by hand, or captions and checks lose their timing). components/: components you added (\`raea make component add\`), yours to change.
|
|
- brand/brand.css: the brand's tokens (\`raea brand DOMAIN\` reads them from its site), loaded with the project's
|
|
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen". Its colours and faces are the palette, as classes
|
|
(text-brand-accent, bg-brand-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3, font-brand,
|
|
font-brand-body) or --brand-* variables; never a colour from outside it. Size, weight, layout and motion are yours,
|
|
chosen against the brand's own best work.
|
|
- \`raea render edit.tsx -o final.mp4 --manifest render.json\` renders, then checks the export once as it ends
|
|
(\`raea check\`: real faults only, each ERROR with its fix, kept as final.check.json; nothing runs it again). Fix the
|
|
ERRORs; a warning is a note for the person. \`raea render edit.tsx --at 105 -o review/stills/\` gives frame 105 to
|
|
look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX); \`raea help\` lists the rest.
|
|
|
|
## raea (everything there is; import from "raea")
|
|
|
|
Time: useCurrentFrame() (frames, from 0 inside the nearest Sequence), useVideoConfig() {width, height, fps,
|
|
durationInFrames}, interpolate(frame, [in...], [out...], {extrapolateLeft, extrapolateRight: "clamp", easing}),
|
|
spring({frame, fps, config}), Easing.bezier(a, b, c, d) / Easing.inOut(...).
|
|
Layout: <AbsoluteFill>, <Sequence from durationInFrames>, <Series><Series.Sequence durationInFrames>, <Loop>, <Freeze>.
|
|
Media: <Video src startFrom endAt volume playbackRate muted punchIn style>; a take cropped to another shape goes
|
|
through components/Framed.tsx when the project has it (<Framed src startFrom endAt at? punchIn?>: the crop on the
|
|
person's face, from footage/faces.json; at picks a face by where it is across the take), else an objectPosition you
|
|
measured on the take, never a guess. <Audio src startFrom endAt volume={n | (f) => n} gainDb fadeIn fadeOut>,
|
|
<Img src>. Media files import as modules: import take from
|
|
"./media/x.mov". Sound: decide what each scene is heard as first (silence, its own sound, effects, music), and make
|
|
it as \`raea guide sound\` says; narration is <Speech text start> from raea/speech. <Mix lufs ceiling> masters the sound.
|
|
Words: useWords() -> [{text, from, to}] (frames, the cuts' words), word("phrase") -> the frame it's said,
|
|
findPhrase(words, "phrase", {occurrence, edge: "start" | "end"}).
|
|
Placement: <Captions said?> (said: a cut's own words, when the edit holds several cuts) captions in the brand's style;
|
|
titles go in <Region name="top" | "bottom" | "center" | "auto" | "full">. Both keep clear of the face and the app's
|
|
buttons; never type a text's top or left.
|
|
Composition: registerRoot(() => <Composition id component width height fps durationInFrames />).
|
|
Not there: React hooks come from "react" (useMemo, useState), not from raea.
|
|
`;
|
|
|
|
/** The workspace a folder is in: the nearest folder at or above it holding .raea/workspace, through the shell's fs. */
|
|
async function workspaceAbove(c: Ctx, from: string): Promise<string | undefined> {
|
|
// up to the root, / or on Windows C:
|
|
for (let d = from.replace(/[\\/]+$/, ""); d; ) {
|
|
if (await c.fs.exists(`${d}/.raea/workspace`)) return d;
|
|
const up = Math.max(d.lastIndexOf("/"), d.lastIndexOf("\\"));
|
|
if (up < 0) break;
|
|
d = d.slice(0, up);
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/** The `raea` command's handler (the shell wraps it with just-bash's defineCommand, so this package needs no dependency). */
|
|
export function raeaHandler(host?: Host, engine?: Engine) {
|
|
return async (args: string[], ctx: unknown) => {
|
|
const c = ctx as unknown as Ctx;
|
|
const p = (rel: string) => fromCwd(c.cwd, rel);
|
|
const ask = (op: string, a: Record<string, unknown> = {}) => {
|
|
if (!host) throw new Error(`raea ${op} needs a host (the native raea's src/native.ts); this shell has none`);
|
|
return host(op, a);
|
|
};
|
|
const text = (v: unknown) => (typeof v === "string" ? v : JSON.stringify(v, null, 2)) + "\n";
|
|
const native = (a: string[] = args) => {
|
|
if (!engine) throw new Error(`raea ${a[0]} is the engine's (the native raea), and this shell has none`);
|
|
return engine(a, ctx);
|
|
};
|
|
// a set is a folder of examples/components (`raea make component add reel` copies it whole); a component is one file of a
|
|
// set that says `// raea make component add NAME: ...` at its top (`raea make component add`, before 11-12), and copies alone
|
|
const said = (src: string) => (/^\/\/ raea (?:make )?component add [\w-]+: (.*)$/m.exec(src)?.[1] ?? "").split(". ")[0];
|
|
const single = (n: string) => Object.values(REGISTRY).map((set) => set[`${n}.tsx`]).find((src) => src && new RegExp(`^// raea (?:make )?component add ${n}:`, "m").test(src));
|
|
const parts = () =>
|
|
Object.entries(REGISTRY)
|
|
.flatMap(([set, files]) => [
|
|
`${set.padEnd(14)} the whole set, ${Object.keys(files).length} files, into components/${set}/`,
|
|
...Object.entries(files).filter(([f, src]) => single(f.replace(/\.tsx$/, "")) === src).map(([f, src]) => `${f.replace(/\.tsx$/, "").padEnd(14)} ${said(src)}`),
|
|
])
|
|
.join("\n") + "\n";
|
|
try {
|
|
switch (args[0]) {
|
|
// the native raea's help lists the shell's verbs with its own: one list
|
|
case undefined:
|
|
case "help":
|
|
case "--help":
|
|
return await native(["help"]);
|
|
case "init": {
|
|
const made: string[] = [];
|
|
const put = async (name: string, body: string) => {
|
|
if (await c.fs.exists(p(name))) return;
|
|
await c.fs.writeFile(p(name), body);
|
|
made.push(name);
|
|
};
|
|
const shape = ask("shape", {}) as { width: number; height: number; fps: number };
|
|
// by feature, as a Bevy project is (S5a): opt-in until it's the default
|
|
if (args.includes("--layout") && args[args.indexOf("--layout") + 1] !== "feature") return out("", 2, "raea init [--layout feature]\n");
|
|
if (args.includes("--layout")) {
|
|
for (const d of FEATURE_DIRS) await c.fs.mkdir(p(d), { recursive: true });
|
|
const name = c.cwd.replace(/[\\/]$/, "").split(/[\\/]/).pop() || "project";
|
|
for (const [f, body] of Object.entries(featureLayout(name, shape))) await put(f, body);
|
|
return out(made.length ? `made ${made.join(", ")}; render it with raea render src/main.tsx\n` : "nothing to make: the project's files are here\n");
|
|
}
|
|
await c.fs.mkdir(p("components"), { recursive: true });
|
|
await put("edit.tsx", TEMPLATE["edit.tsx"]);
|
|
await put("cuts.ts", cutsModule([], shape));
|
|
await put("styles.gen.ts", `export const css = "";\n`);
|
|
// AGENTS.md is raea's own notes: an older generated copy (it opens with this header) is brought up to date, a
|
|
// person's own file is left alone
|
|
const notes = p("AGENTS.md");
|
|
if (await c.fs.exists(notes)) {
|
|
const was = await c.fs.readFile(notes, "utf8");
|
|
if (was !== NOTES && was.startsWith("# This project\n\nA video edit as a React + TypeScript project")) {
|
|
await c.fs.writeFile(notes, NOTES);
|
|
made.push("AGENTS.md (updated)");
|
|
}
|
|
} else await put("AGENTS.md", NOTES);
|
|
return out(made.length ? `made ${made.join(", ")}\n` : "nothing to make: the project's files are here\n");
|
|
}
|
|
// `raea make component` copies raea's sets and components into the project's components/ (docs/layout.feature
|
|
// LY4), or with --shared into the workspace's shared/components/, which every project imports as @shared/components/
|
|
case "component": {
|
|
const was = "";
|
|
// the library beside this raea (none in a shell with no host: raea's own sets are all it lists)
|
|
const shelf = (): Item[] => (host ? (host("components", { op: "list" }) as Item[]) : []);
|
|
if (args[1] === undefined) return out(parts() + listed(shelf(), []), 0, was);
|
|
const ws = clean(args.slice(2));
|
|
// --json: the items found (each with its props, when to use it and when not) for an agent to pick from
|
|
if (args[1] === "list" && args.includes("--json")) return out(`${JSON.stringify(ws.length ? searched(shelf(), terms(ws)) : shelf(), null, 1)}\n`, 0, was);
|
|
if (args[1] === "list") return out(ws.length ? listed(shelf(), ws) : parts() + listed(shelf(), []), 0, was);
|
|
// show: one item in full, so it can be picked without opening its file
|
|
if (args[1] === "show") {
|
|
const item = ws[0] ? found(shelf(), ws[0]) : undefined;
|
|
if (!item) return out("", 1, `${was}raea make component show: no "${ws[0] ?? ""}" in the library (raea make component list WORDS finds one)\n`);
|
|
const at = (await c.fs.exists(p("compositions"))) ? "../components" : "./components";
|
|
return out(args.includes("--json") ? `${JSON.stringify(item, null, 1)}\n` : inFull(item, at), 0, was);
|
|
}
|
|
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] [--json] | show NAME [--json] | add NAME ... [--shared] [--force]\n`);
|
|
const names = clean(args.slice(2));
|
|
if (!names.length) return out("", 2, `${was}raea make component add NAME ... (raea make component list shows them)\n`);
|
|
const force = args.includes("--force");
|
|
let home = "components";
|
|
// what imports it: a composition in compositions/ reaches ../components/, one at the root ./components/
|
|
let from = (await c.fs.exists(p("compositions"))) ? "../components" : "./components";
|
|
if (args.includes("--shared")) {
|
|
const ws = await workspaceAbove(c, c.cwd);
|
|
if (!ws) return out("", 1, `${was}raea make component add --shared: no workspace above ${c.cwd} (no .raea/workspace): add it to the project instead\n`);
|
|
home = `${ws}/shared/components`;
|
|
from = "@shared/components";
|
|
}
|
|
await c.fs.mkdir(p(home), { recursive: true });
|
|
const done: string[] = [];
|
|
const shown = (rel: string) => (absolute(home) ? `shared/components/${rel.slice(home.length + 1)}` : rel);
|
|
for (const n of names) {
|
|
const set = REGISTRY[n];
|
|
if (set) {
|
|
// a set is the project's own once copied: never overwritten unasked, and said so loudly
|
|
const dir = `${home}/${n}`;
|
|
if (!force && (await c.fs.exists(p(dir)))) return out(done.join(""), 1, `raea make component add: ${shown(dir)}/ is already here (yours now; --force replaces its files)\n`);
|
|
await c.fs.mkdir(p(dir), { recursive: true });
|
|
for (const [f, src] of Object.entries(set)) await c.fs.writeFile(p(`${dir}/${f}`), src);
|
|
done.push(`${shown(dir)}/ ${Object.keys(set).length} files; import from "${from}/${n}"\n`);
|
|
continue;
|
|
}
|
|
const src = single(n);
|
|
// a library component: its folder under components/CATEGORY/NAME/, with the shared files it needs
|
|
const got = src || !host ? null : (host("components", { op: "get", name: n }) as Got | null);
|
|
if (got) {
|
|
let wrote = 0;
|
|
let kept = 0;
|
|
for (const [f, text] of Object.entries(got.files)) {
|
|
const dest = p(`${home}/${f}`);
|
|
if (!force && (await c.fs.exists(dest))) kept++;
|
|
else {
|
|
await c.fs.mkdir(dest.slice(0, dest.lastIndexOf("/")), { recursive: true });
|
|
await c.fs.writeFile(dest, text);
|
|
wrote++;
|
|
}
|
|
}
|
|
// its npm packages (culori and the like), installed by the engine's package manager when there is one
|
|
let installed = "";
|
|
if (got.item.packages?.length && engine) {
|
|
const r = await native(["add", ...got.item.packages]);
|
|
installed = r.exitCode ? `raea add failed: ${(r.stderr || r.stdout).trim().split("\n")[0]}` : "installed";
|
|
}
|
|
done.push(added(got, absolute(home) ? "shared/components" : home, from, wrote, kept, installed));
|
|
continue;
|
|
}
|
|
if (!src) return out(done.join(""), 1, `raea make component add: no component or set "${n}" (raea make component list shows them, list WORDS searches the library)\n`);
|
|
const dest = p(`${home}/${n}.tsx`);
|
|
if (!force && (await c.fs.exists(dest))) {
|
|
done.push(`${shown(`${home}/${n}.tsx`)} is already here (yours now; --force replaces it)\n`);
|
|
continue;
|
|
}
|
|
await c.fs.writeFile(dest, src);
|
|
done.push(`${shown(`${home}/${n}.tsx`)} import it: import ${n.replace(/(^|-)(\w)/g, (_, __, ch) => ch.toUpperCase())} from "${from}/${n}";\n`);
|
|
}
|
|
return out(done.join(""), 0, was);
|
|
}
|
|
// `add` is npm packages (the engine's package manager); a registry component's name is pointed at `raea make component add`
|
|
case "add": {
|
|
const r = await native();
|
|
const part = clean(args.slice(1)).find((n) => REGISTRY[n] || single(n));
|
|
return r.exitCode && part ? { ...r, stderr: r.stderr + `(a raea component? raea make component add ${part})\n` } : r;
|
|
}
|
|
case "cut": {
|
|
const spans: number[][] = [];
|
|
args.forEach((a, i) => {
|
|
if (a === "--at" && args[i + 1]) {
|
|
const m = /^(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)$/.exec(args[i + 1]);
|
|
if (m) spans.push([Number(m[1]), Number(m[2])]);
|
|
}
|
|
});
|
|
const [take, ...lines] = clean(args.slice(1), "--at");
|
|
if (!take || (!lines.length && !spans.length)) return out("", 2, `raea cut TAKE "line" ["line" ...] | --at A-B [--at C-D ...] [--append]\n`);
|
|
const prev: Cut[] = args.includes("--append") && (await c.fs.exists(p("cuts.json"))) ? JSON.parse(await c.fs.readFile(p("cuts.json"), "utf8")).cuts : [];
|
|
const r = ask("cut", { take, lines, spans, keep: prev }) as { edit: { width: number; height: number; fps: number }; cuts: Cut[]; words: unknown[]; perception?: unknown; said: string };
|
|
await c.fs.writeFile(p("cuts.ts"), cutsModule(r.cuts, r.edit));
|
|
await c.fs.writeFile(p("cuts.json"), JSON.stringify({ edit: r.edit, cuts: r.cuts }, null, 2) + "\n");
|
|
await c.fs.writeFile(p("words.json"), JSON.stringify(r.words) + "\n");
|
|
// where the face and the safe band are in the edit, for <Region> and the checks (a host may not see faces)
|
|
if (r.perception) await c.fs.writeFile(p("perception.json"), JSON.stringify(r.perception) + "\n");
|
|
return out(r.said.endsWith("\n") ? r.said : r.said + "\n");
|
|
}
|
|
// what a file says, word by word (raea goal check's words, say, never and CTA packs hear through it)
|
|
case "words": {
|
|
const file = clean(args.slice(1), "-o").find((a) => a !== "-o");
|
|
if (!file) return out("", 2, "raea words FILE [-o OUT.words.json]\n");
|
|
return out(text(ask("words", { file, out: flag(args, "-o") })));
|
|
}
|
|
case "frame": {
|
|
const take = clean(args.slice(1), "--at")[0];
|
|
if (!take) return out("", 2, "raea frame TAKE [--at SECONDS]\n");
|
|
const at = flag(args, "--at");
|
|
return out(text(ask("frame", { take, at: at === undefined ? undefined : Number(at) })));
|
|
}
|
|
case "brand": {
|
|
const q = clean(args.slice(1)).join(" ");
|
|
if (!q) return out("", 2, "raea brand DOMAIN|URL (stripe.com, or the site's URL: read on this machine)\n");
|
|
return out(text(ask("brand", { brand: q })));
|
|
}
|
|
case "library":
|
|
return out(libraryVerb(ask, args.slice(1), (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}));
|
|
case "show": {
|
|
// --labels FILE.json: read here, where the shell's files are (show.ts labelsIn)
|
|
const at = args.lastIndexOf("--labels");
|
|
const file = at > 0 ? args[at + 1] : undefined;
|
|
let listed: unknown[] | undefined;
|
|
try {
|
|
listed = file === undefined ? undefined : labelsIn(await c.fs.readFile(p(file), "utf8"), file);
|
|
} catch (e) {
|
|
return out("", 2, `raea show: ${(e as Error).message.startsWith("--labels") ? (e as Error).message : `--labels ${file}: ${(e as Error).message}`}\n`);
|
|
}
|
|
return out(showVerb(ask, args.slice(1), c.cwd, (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}, listed));
|
|
}
|
|
case "clothes":
|
|
return out(clothesVerb(ask, args.slice(1)));
|
|
case "bug":
|
|
return out(bugVerb(ask, args.slice(1), (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}));
|
|
default:
|
|
return await native();
|
|
}
|
|
} catch (e) {
|
|
return out("", 1, `raea ${args[0] ?? ""}: ${String((e as Error)?.message ?? e)}\n`);
|
|
}
|
|
};
|
|
}
|